"""자동 업데이트 일정 설정(2026-10-26, 마이그레이션 011) — 저장 API(관리자·검증·011 미적용 503), 화면 카운트다운 값(종류별 일정).""" from __future__ import annotations import importlib from datetime import datetime, timedelta, timezone import pytest from fastapi import FastAPI from fastapi.testclient import TestClient from app.modules.performance import auto_sync, common from app.modules.performance.db import SettingsMigrationNeeded perf_router = importlib.import_module("app.modules.performance.router") KST = timezone(timedelta(hours=9)) D = auto_sync.default_schedule() class Store: def __init__(self, value=None, missing=False): self.value, self.missing, self.saved = value, missing, [] def get_setting(self, key): if self.missing: raise SettingsMigrationNeeded() return self.value def set_setting(self, key, value, *, user=""): if self.missing: raise SettingsMigrationNeeded() self.saved.append((key, value, user)) self.value = value @pytest.fixture def client_store(monkeypatch): st, calls = Store(), [] def fake_require(request, admin=False): calls.append(admin) return st, {"email": "admin@x"} monkeypatch.setattr(common, "require_store", fake_require) monkeypatch.delenv("PERFORMANCE_AUTO_SYNC", raising=False) monkeypatch.setattr("app.timezone.now_kst", lambda: datetime(2026, 10, 16, 18, 50, tzinfo=KST)) # 금요일 app = FastAPI() app.include_router(perf_router.router) return TestClient(app), st, calls def test_save_schedule(client_store): c, st, calls = client_store body = {"sales": {"enabled": True, "interval": 15, "days": [0, 1, 2, 3, 4], "start": "08:30", "end": "20:00"}, "ads": {"enabled": False, "interval": 60, "days": [], "start": "09:00", "end": "18:00"}} r = c.put("/performance/api/auto-sync-schedule", json=body) assert r.status_code == 200 and calls == [True] # 관리자만 j = r.json() assert st.saved == [("auto_sync", body, "admin@x")] assert j["sales"]["next_at"] == "2026-10-16T19:00:00+09:00" and j["sales"]["label"] == "평일 08:30~20:00 · 15분마다" assert j["ads"]["next_at"] == "" and j["ads"]["label"] == "꺼짐" and j["env_on"] def test_save_schedule_rejects_bad_values(client_store): c, st, _ = client_store bad = {"sales": {**D, "interval": 12}, "ads": D} r = c.put("/performance/api/auto-sync-schedule", json=bad) assert r.status_code == 400 and r.json()["detail"].startswith("매출 실적:") and "5분 단위" in r.json()["detail"] r = c.put("/performance/api/auto-sync-schedule", json={"sales": D, "ads": {**D, "start": "20:00", "end": "08:00"}}) assert r.status_code == 400 and r.json()["detail"].startswith("광고비:") assert c.put("/performance/api/auto-sync-schedule", json={"sales": D}).status_code == 400 # 광고비 일정 없음 assert st.saved == [] st.missing = True r = c.put("/performance/api/auto-sync-schedule", json={"sales": D, "ads": D}) assert r.status_code == 503 and "011" in r.json()["detail"] def test_countdown_ctx_per_kind(monkeypatch): monkeypatch.delenv("PERFORMANCE_AUTO_SYNC", raising=False) monkeypatch.delenv("PERFORMANCE_AUTO_SYNC_HOURS", raising=False) monkeypatch.setattr("app.timezone.now_kst", lambda: datetime(2026, 10, 16, 18, 50, tzinfo=KST)) st = Store({"sales": {**D, "interval": 5}, "ads": {**D, "days": [0, 1, 2, 3, 4], "start": "10:00"}}) sales = perf_router._auto_sync_ctx(st, "sales") assert sales["next_at"] == "2026-10-16T18:55:00+09:00" and sales["schedule"]["interval"] == 5 assert sales["label"] == "매일 09:00~19:00 · 5분마다" and sales["now"].startswith("2026-10-16T18:50:00") assert perf_router._auto_sync_ctx(st, "ads")["next_at"] == "2026-10-16T19:00:00+09:00" st.value = {"sales": D, "ads": {**D, "days": [0, 1, 2, 3, 4], "start": "10:00", "end": "10:00"}} assert perf_router._auto_sync_ctx(st, "ads")["next_at"] == "2026-10-19T10:00:00+09:00" # 금 저녁 → 월 10시 st.value = {"sales": {**D, "enabled": False}, "ads": D} assert perf_router._auto_sync_ctx(st, "sales") is None # 끈 종류는 카운트다운 숨김 st.missing = True assert perf_router._auto_sync_ctx(st, "sales")["next_at"] == "2026-10-16T19:00:00+09:00" # 011 전 = 기본 일정 monkeypatch.setenv("PERFORMANCE_AUTO_SYNC", "false") assert perf_router._auto_sync_ctx(st, "sales") is None def test_settings_card_ctx(monkeypatch): monkeypatch.delenv("PERFORMANCE_AUTO_SYNC", raising=False) ctx = perf_router._auto_sync_settings_ctx(Store(missing=True)) assert not ctx["ready"] and ctx["env_on"] and [k["kind"] for k in ctx["kinds"]] == ["sales", "ads"] assert ctx["kinds"][0]["schedule"] == D and ctx["step"] == 5 class Broken: def get_setting(self, key): raise RuntimeError("db down") ctx = perf_router._auto_sync_settings_ctx(Broken()) assert ctx["ready"] and "RuntimeError" in ctx["error"] and ctx["kinds"][1]["schedule"] == D