Files
dbx-main/app/modules/performance/tests/test_auto_sync.py
T
king 232695c004 feat(performance): 광고비 탭 [광고비 업데이트] 진행 창·자동 업데이트·업데이트 시각
- 채널별 [구글/메타 광고 불러오기] 버튼을 없애고 매출 탭과 같은 모양으로
  마지막 업데이트 · 다음 업데이트까지(카운트다운) · [광고비 업데이트]
- 진행 창 작업에 종류(sales/ads) 추가 — 광고 채널별 진행 막대(수집 → 저장
  → 완료), 채널별 중지·전체 취소는 저장 직전까지, 진행 중이면 합류
- POST /api/ad-sync, GET /api/ad-sync/current
- 자동 업데이트 회차에서 매출과 광고비를 동시에 각각 진행 창 작업으로
- 마지막 광고비 업데이트 = 광고 API 마지막 성공 가져오기 시각

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 13:44:45 +09:00

128 lines
5.6 KiB
Python

"""매출 자동 업데이트 — 회차 시각 계산·건너뛰기."""
from __future__ import annotations
from datetime import date, datetime, timedelta, timezone
from app.modules.performance import auto_sync as au
KST = timezone(timedelta(hours=9))
H = (9, 19)
def _t(h, m, d=13):
return datetime(2026, 10, d, h, m, tzinfo=KST)
def test_slots_every_half_hour_9_to_19():
slots = [t for t in (_t(0, 0) + timedelta(minutes=30 * i) for i in range(48)) if au.is_slot(t, H)]
assert slots[0] == _t(9, 0) and slots[-1] == _t(19, 0) and len(slots) == 21
assert not au.is_slot(_t(19, 30), H) and not au.is_slot(_t(8, 30), H) and not au.is_slot(_t(10, 15), H)
def test_next_slot():
assert au.next_slot(_t(8, 10), H) == _t(9, 0)
assert au.next_slot(_t(9, 0), H) == _t(9, 30) # 지금 회차는 이미 지남 → 다음
assert au.next_slot(datetime(2026, 10, 13, 9, 29, 59, tzinfo=KST), H) == _t(9, 30)
assert au.next_slot(_t(18, 45), H) == _t(19, 0)
assert au.next_slot(_t(19, 0), H) == _t(9, 0, d=14) # 저녁 이후 → 다음 날 9시
assert au.next_slot(_t(23, 59), H) == _t(9, 0, d=14)
def test_env_parsing(monkeypatch):
monkeypatch.delenv("PERFORMANCE_AUTO_SYNC", raising=False)
monkeypatch.delenv("PERFORMANCE_AUTO_SYNC_DAYS", raising=False)
monkeypatch.delenv("PERFORMANCE_AUTO_SYNC_HOURS", raising=False)
assert au.enabled() and au.sync_days() == 10 and au.hour_window() == (9, 19)
monkeypatch.setenv("PERFORMANCE_AUTO_SYNC", "false")
monkeypatch.setenv("PERFORMANCE_AUTO_SYNC_DAYS", "200")
monkeypatch.setenv("PERFORMANCE_AUTO_SYNC_HOURS", "20-8") # 잘못된 값 → 기본
assert not au.enabled() and au.sync_days() == 90 and au.hour_window() == (9, 19)
monkeypatch.setenv("PERFORMANCE_AUTO_SYNC_HOURS", "8-20")
assert au.hour_window() == (8, 20)
def test_run_once_uses_job_and_skips_when_busy(monkeypatch):
from app.modules.performance import jobs
from app.modules.performance.sync import SyncService
calls = []
def fake_sync_all(self, *, start, end, codes=None, trigger="manual", user="", job=None):
calls.append((start, end, trigger, user, job is not None))
return [{"code": "naver", "ok": True}, {"code": "toss", "ok": False, "skipped": False}]
class Store:
def last_update_at(self):
return "2026-10-13T09:00:05+09:00"
monkeypatch.setattr(SyncService, "sync_all", fake_sync_all)
monkeypatch.setattr(jobs, "running_job", lambda kind="sales": None)
res = au.run_once(Store(), None, today=date(2026, 10, 13), days=10)
assert calls == [(date(2026, 10, 4), date(2026, 10, 13), "schedule", au.AUTO_USER, True)]
# 광고 API 저장소 메서드가 없는 가짜 저장소 — 광고 가져오기는 조용히 빠지고 매출 결과는 그대로
assert res == {"skipped": False, "sales_skipped": False, "ads_skipped": False, "from": "2026-10-04",
"to": "2026-10-13", "ok": 1, "failed": ["toss"], "error": "", "ads": []}
monkeypatch.setattr(jobs, "running_job", lambda kind="sales": object())
assert au.run_once(Store(), None, today=date(2026, 10, 13), days=10)["skipped"]
assert len(calls) == 1
# 광고비 업데이트만 돌고 있으면 매출은 그 회차에 그대로 돈다(종류별로 따로)
monkeypatch.setattr(jobs, "running_job", lambda kind="sales": object() if kind == "ads" else None)
res = au.run_once(Store(), None, today=date(2026, 10, 13), days=10)
assert res["ads_skipped"] and not res["sales_skipped"] and len(calls) == 2
def test_run_once_runs_ads_as_progress_job(monkeypatch):
"""자동 회차의 광고비 = 광고비 진행 창 작업(kind=ads) — 채널별 진행·마지막 업데이트 시각."""
from app.modules.performance import ad_sync, jobs
from app.modules.performance.sync import SyncService
monkeypatch.setattr(SyncService, "sync_all", lambda self, **kw: [])
seen = {}
def fake_all(self, start, end, *, user="", job=None):
seen["job"] = job
return [{"code": "google", "ok": True, "days": 10, "total": 1000}]
monkeypatch.setattr(ad_sync.AdSyncService, "sync_all", fake_all)
class Store:
def last_update_at(self):
return None
def ad_source_statuses(self):
return {"google": {"last_success_sync_at": "2026-10-13T09:00:07+09:00"},
"meta": {"last_success_sync_at": "2026-10-13T08:30:02+09:00"}}
monkeypatch.setattr(ad_sync, "ad_credentials", lambda store, ring: None)
res = au.run_once(Store(), None, today=date(2026, 10, 13), days=10)
job = seen["job"]
assert job.kind == "ads" and job.finished and job.last_update_at == "2026-10-13T09:00:07+09:00"
assert res["ads"] == [{"code": "google", "ok": True}] and jobs.running_job("ads") is None
def test_startup_clears_orphan_running_runs(monkeypatch):
"""서버 시작 때 지난 프로세스가 남긴 '진행 중' 기록을 정리(2026-10-19) — 자동 업데이트를 꺼 둬도, DB 오류여도 앱은 뜬다."""
from types import SimpleNamespace
from app.modules.performance import auto_sync as a
calls = []
class Store:
def abandon_running_runs(self):
calls.append(1)
return 2
monkeypatch.setattr(a, "_started", False)
monkeypatch.setenv("PERFORMANCE_AUTO_SYNC", "false")
assert a.start_auto_sync_thread(SimpleNamespace(performance_store=Store())) is False
assert calls == [1]
class Broken:
def abandon_running_runs(self):
raise RuntimeError("db down")
assert a.start_auto_sync_thread(SimpleNamespace(performance_store=Broken())) is False # 예외가 새지 않음