Files
dbx-main/app/modules/performance/tests/test_auto_sync.py
T
king 07861dfe8c feat(performance): 자동 업데이트 일정 설정 — 매출·광고비 따로 간격·요일·시작/끝
- 실적 설정 "자동 업데이트" 카드(관리자): 매출 실적·광고비 각각 사용·요일([매일]·[평일])·
  시작/끝 시각(5분 단위)·간격(5~720분, 5분 단위, 기본 30분), PUT /api/auto-sync-schedule
- 마이그레이션 011 perf_settings(key auto_sync, JSONB). 미적용·값 없음 = 기본 일정(매일 9~19시 30분)
- auto_sync: 종류별 일정·Scheduler(1분마다 다시 읽어 바뀐 종류만 다시 계산, 종류마다 따로 스레드)
- 매출·광고비 탭 카운트다운이 각자 일정대로 다음 회차 계산(nextScheduleSlot)
- 테스트: 일정 계산·검증·Scheduler·저장 API·브라우저(설정 카드·카운트다운)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 18:01:00 +09:00

248 lines
13 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))
D = au.default_schedule() # 매일 09:00 ~ 19:00, 30분마다 (env 없을 때)
def _t(h, m, d=13): # 2026-10-13 = 화요일
return datetime(2026, 10, d, h, m, tzinfo=KST)
def _s(**kw):
return {**D, **kw}
def test_default_schedule_every_half_hour_9_to_19(monkeypatch):
monkeypatch.delenv("PERFORMANCE_AUTO_SYNC_HOURS", raising=False)
assert au.default_schedule() == {"enabled": True, "interval": 30, "days": [0, 1, 2, 3, 4, 5, 6],
"start": "09:00", "end": "19:00"}
slots = [t for t in (_t(0, 0) + timedelta(minutes=5 * i) for i in range(288)) if au.is_slot(t, D)]
assert slots[0] == _t(9, 0) and slots[-1] == _t(19, 0) and len(slots) == 21
assert not au.is_slot(_t(19, 30), D) and not au.is_slot(_t(8, 30), D) and not au.is_slot(_t(10, 15), D)
monkeypatch.setenv("PERFORMANCE_AUTO_SYNC_HOURS", "8-20") # 일정 저장 전 기본 시간대 = env
assert au.default_schedule()["start"] == "08:00" and au.default_schedule()["end"] == "20:00"
def test_next_slot():
assert au.next_slot(_t(8, 10), D) == _t(9, 0)
assert au.next_slot(_t(9, 0), D) == _t(9, 30) # 지금 회차는 이미 지남 → 다음
assert au.next_slot(datetime(2026, 10, 13, 9, 29, 59, tzinfo=KST), D) == _t(9, 30)
assert au.next_slot(_t(18, 45), D) == _t(19, 0)
assert au.next_slot(_t(19, 0), D) == _t(9, 0, d=14) # 저녁 이후 → 다음 날 9시
assert au.next_slot(_t(23, 59), D) == _t(9, 0, d=14)
def test_next_slot_custom_interval_window_weekdays():
s = _s(interval=25, start="08:35", end="10:00")
assert au.next_slot(_t(8, 0), s) == _t(8, 35)
assert au.next_slot(_t(8, 35), s) == _t(9, 0)
assert au.next_slot(_t(9, 40), s) == _t(9, 50) # 08:35 · 09:00 · 09:25 · 09:50 (10:15 는 끝 뒤)
assert au.next_slot(_t(9, 50), s) == _t(8, 35, d=14)
assert au.is_slot(_t(9, 25), s) and not au.is_slot(_t(10, 0), s)
assert au.is_slot(_t(10, 0), _s(interval=5, start="08:35", end="10:00")) # 끝 시각과 딱 맞으면 끝도 회차
weekdays = _s(days=[0, 1, 2, 3, 4])
assert au.next_slot(datetime(2026, 10, 16, 19, 0, tzinfo=KST), weekdays) == _t(9, 0, d=19) # 금 저녁 → 월 9시
assert not au.is_slot(datetime(2026, 10, 17, 10, 0, tzinfo=KST), weekdays) # 토요일
once = _s(start="07:05", end="07:05", days=[2]) # 수요일 07:05 한 번
assert au.next_slot(_t(7, 5), once) == datetime(2026, 10, 14, 7, 5, tzinfo=KST)
assert au.next_slot(datetime(2026, 10, 14, 7, 5, tzinfo=KST), once) == datetime(2026, 10, 21, 7, 5, tzinfo=KST)
assert au.next_slot(_t(9, 0), _s(enabled=False)) is None and au.next_slot(_t(9, 0), _s(days=[])) is None
assert au.next_slot(_t(9, 0), _s(interval=720, start="00:00", end="23:55")) == _t(12, 0)
def test_validate_schedule():
ok = au.validate_schedule({"enabled": True, "interval": "45", "days": [4, 0, 0], "start": "7:05", "end": "21:30"})
assert ok == {"enabled": True, "interval": 45, "days": [0, 4], "start": "07:05", "end": "21:30"}
assert au.validate_schedule({**D, "enabled": False, "days": []})["days"] == [] # 끈 일정은 요일 없어도 됨
import pytest
for bad, word in [({**D, "interval": 7}, "5분 단위"), ({**D, "interval": 0}, "간격"), ({**D, "interval": 725}, "간격"),
({**D, "interval": "x"}, "숫자"), ({**D, "days": []}, "요일을 하나"), ({**D, "days": [7]}, "요일"),
({**D, "days": [True]}, "요일"), ({**D, "start": "09:03"}, "5분 단위"), ({**D, "end": "24:00"}, "HH:MM"),
({**D, "start": "19:00", "end": "09:00"}, "끝 시각"), (None, "형식")]:
with pytest.raises(ValueError, match=word):
au.validate_schedule(bad)
def test_normalize_and_load_schedules():
from app.modules.performance.db import SettingsMigrationNeeded
saved = {"sales": _s(interval=10), "ads": {"interval": 3}} # 광고비 값이 깨짐 → 그 종류만 기본
n = au.normalize(saved)
assert n["sales"]["interval"] == 10 and n["ads"] == D
assert au.normalize(None) == {"sales": D, "ads": D}
class Store:
def __init__(self, value=None, missing=False):
self.value, self.missing = value, missing
def get_setting(self, key):
assert key == "auto_sync"
if self.missing:
raise SettingsMigrationNeeded()
return self.value
assert au.load_schedules(Store(saved)) == (n, True)
assert au.load_schedules(Store(missing=True)) == ({"sales": D, "ads": D}, False)
assert au.load_schedules(object()) == ({"sales": D, "ads": D}, True) # get_setting 없는 저장소
def test_describe():
assert au.describe(D) == "매일 09:00~19:00 · 30분마다"
assert au.describe(_s(days=[0, 1, 2, 3, 4], interval=90)) == "평일 09:00~19:00 · 1시간 30분마다"
assert au.describe(_s(days=[5, 6], interval=120)) == "주말 09:00~19:00 · 2시간마다"
assert au.describe(_s(days=[0, 2, 4], start="10:00", end="10:00")) == "월·수·금 10:00"
assert au.describe(_s(enabled=False)) == "꺼짐"
def test_scheduler_runs_each_kind_on_its_own_schedule():
fired = []
sch = au.Scheduler(lambda kind, due: fired.append((kind, due)))
schedules = {"sales": D, "ads": _s(interval=60, days=[0, 1, 2, 3, 4])}
sch.update(schedules, _t(9, 10)) # 시작 시각 회차는 안 돌림 — 다음부터
assert sch.due == {"sales": _t(9, 30), "ads": _t(10, 0)}
assert sch.wait_seconds(_t(9, 10)) == 60.0 and sch.wait_seconds(datetime(2026, 10, 13, 9, 29, 30, tzinfo=KST)) == 30.0
sch.tick(_t(9, 29))
assert fired == []
sch.tick(_t(9, 30))
assert fired == [("sales", _t(9, 30))] and sch.due["sales"] == _t(10, 0)
sch.tick(datetime(2026, 10, 13, 10, 0, 20, tzinfo=KST)) # 둘 다 10:00 → 둘 다(따로)
assert fired[1:] == [("sales", _t(10, 0)), ("ads", _t(10, 0))]
sch.tick(_t(11, 40)) # 밀린 회차(10:30·11:00·11:30)는 한 번만, 다음은 지금 뒤
assert fired[3:] == [("sales", _t(10, 30)), ("ads", _t(11, 0))]
assert sch.due == {"sales": _t(12, 0), "ads": _t(12, 0)}
sch.update(schedules, _t(11, 41)) # 일정 그대로 → due 그대로
assert sch.due["sales"] == _t(12, 0)
sch.update({**schedules, "sales": _s(interval=5)}, _t(11, 41)) # 매출 일정만 바뀜 → 매출만 지금부터 다시
assert sch.due == {"sales": _t(11, 45), "ads": _t(12, 0)}
sch.update({"sales": _s(interval=5), "ads": _s(enabled=False)}, _t(11, 41))
assert sch.due["ads"] is None and sch.due["sales"] == _t(11, 45)
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_only_given_kinds(monkeypatch):
"""종류마다 따로 회차(2026-10-26) — kinds=("ads",) 면 매출은 건드리지 않는다."""
from app.modules.performance import ad_sync, jobs
from app.modules.performance.sync import SyncService
sales = []
monkeypatch.setattr(SyncService, "sync_all", lambda self, **kw: sales.append(1) or [])
monkeypatch.setattr(ad_sync.AdSyncService, "sync_all", lambda self, start, end, *, user="", job=None: [])
monkeypatch.setattr(ad_sync, "ad_credentials", lambda store, ring: None)
monkeypatch.setattr(jobs, "running_job", lambda kind="sales": None)
class Store:
def last_update_at(self):
return None
def ad_source_statuses(self):
return {}
res = au.run_once(Store(), None, today=date(2026, 10, 13), days=3, kinds=("ads",))
assert sales == [] and res["sales_skipped"] and not res["ads_skipped"] and res["from"] == "2026-10-11"
res = au.run_once(Store(), None, today=date(2026, 10, 13), days=3, kinds=("sales",))
assert sales == [1] and res["ads_skipped"] and not res["sales_skipped"]
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 # 예외가 새지 않음