Files
dbx-main/app/modules/performance/tests/test_auto_sync.py
T
king e7b1e17579 feat(performance): 광고비 탭 구글 광고비·ROAS 를 Google Ads API 로 가져오기 + 설정에서 키 입력
- 실적 설정 "광고 API 연동" 카드: 개발자 토큰·고객 ID·로그인 고객 ID(MCC)·서비스 계정 JSON·API 버전(기본 v26)
  → 쇼핑몰과 같은 마스터 키로 암호화(perf_ad_credentials, AAD perf:ad:…), 연결 테스트·상태(perf_ad_source_status)
- ad_sources/(채널 하나 = 파일 하나) + google_ads.py: 서비스 계정 JWT 토큰(httpx) → REST searchStream GAQL,
  비용(cost_micros 원 반올림, 부가세 별도)·ROAS(전환 가치÷비용)·노출·클릭·전환 항목, KRW 계정만, 오류 코드별 안내
- ad_sync.py: 기간 한 트랜잭션 저장(source='api', 안 준 날은 예전 API 값만 지움), 같은 채널 동시 실행 차단, 비밀값 가림
- 광고비 탭 [구글 광고 불러오기](보는 기간, 92일 넘으면 관리자) + 매출 자동 업데이트 회차에 함께, API 값 초록 숫자,
  구글 머리글 = 일자별 항목 표
- 마이그레이션 007, 테스트 test_google_ads.py(가짜 구글 서버) — performance 테스트 83개 통과

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

70 lines
3.1 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: 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, "from": "2026-10-04", "to": "2026-10-13", "ok": 1, "failed": ["toss"], "error": "",
"ads": []}
monkeypatch.setattr(jobs, "running_job", lambda: object())
assert au.run_once(Store(), None, today=date(2026, 10, 13), days=10)["skipped"]
assert len(calls) == 1