"""구글 광고 API 연동(2026-10-15) — 입력 검사·토큰·조회·변환·오류 안내·저장 서비스·라우터. 구글 서버는 가짜(httpx MockTransport).""" from __future__ import annotations import json from datetime import date from decimal import Decimal from urllib.parse import parse_qs import httpx import pytest from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import rsa from app.modules.performance import ad_sync from app.modules.performance.ad_sources import google_ads as ga from app.modules.performance.adapters.base import AdapterContext, ApiError, AuthFailed, NotConfigured from app.modules.performance.credentials import CredentialService, aad_for from app.modules.performance.security import crypto KEY1 = "11" * 32 def _sa_json() -> str: key = rsa.generate_private_key(public_exponent=65537, key_size=2048) pem = key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption()).decode() return json.dumps({"type": "service_account", "client_email": "erp@proj.iam.gserviceaccount.com", "private_key_id": "kid1", "private_key": pem, "token_uri": "https://oauth2.googleapis.com/token"}) SA = _sa_json() class Creds: def __init__(self, values): self.values = values def get(self, key): return self.values.get(key, "") def has(self, key): return bool(self.values.get(key)) def set(self, key, value): self.values[key] = value def known_secrets(self): return [v for v in self.values.values() if v] def _ctx(**over): values = {"customer_id": "123-456-7890", "service_account_json": SA} values.update(over) return AdapterContext(code="google", credentials=Creds(values)) def _install(monkeypatch, handler): """구글(토큰·광고 API) 가짜 서버 — handler(request) 가 searchStream 응답을 만든다. 보낸 요청을 돌려준다.""" ga._token_cache.clear() seen = [] def route(request: httpx.Request) -> httpx.Response: seen.append(request) if request.url.host == "oauth2.googleapis.com": form = parse_qs(request.content.decode()) assert form["grant_type"] == ["urn:ietf:params:oauth:grant-type:jwt-bearer"] and form["assertion"][0].count(".") == 2 return httpx.Response(200, json={"access_token": "ya29.TOKEN", "expires_in": 3600}) return handler(request) monkeypatch.setattr(ga, "_http", lambda ctx: httpx.Client(transport=httpx.MockTransport(route))) return seen ROWS = [{"results": [ {"customer": {"currencyCode": "KRW"}, "segments": {"date": "2026-10-01"}, "metrics": {"costMicros": "123456500000", "impressions": "20000", "clicks": "400", "conversions": 12.5, "conversionsValue": 617282.5}}, {"customer": {"currencyCode": "KRW"}, "segments": {"date": "2026-10-02"}, "metrics": {"impressions": "50"}}, # 비용 0(값이 빠진 칸) ]}, {"results": [ {"customer": {"currencyCode": "KRW"}, "segments": {"date": "2026-10-03"}, "metrics": {"costMicros": "1000000", "clicks": "1", "impressions": "10", "conversionsValue": 3000}}, ]}] def test_validate_credentials(): src = ga.GoogleAdsSource() ok = {"customer_id": "123-456-7890", "service_account_json": SA} assert src.validate_credentials(ok) == [] assert src.validate_credentials({**ok, "service_account_json": "__stored__"}) == [] assert "developer_token" not in {f.key for f in src.visible_fields()} # 개발자 토큰 폐지(2026-09-09) — 입력칸 없음 errs = src.validate_credentials({**ok, "customer_id": "12345", "login_customer_id": "abc", "api_version": "26", "service_account_json": '{"type": "authorized_user"}'}) assert len(errs) == 4 and not any("BEGIN" in e for e in errs) # 키 내용은 문구에 없음 assert "입력하세요" in " ".join(src.validate_credentials({})) assert "JSON" in " ".join(src.validate_credentials({**ok, "service_account_json": "not json"})) def test_fetch_days_converts_and_sends_headers(monkeypatch): seen = _install(monkeypatch, lambda req: httpx.Response(200, json=ROWS)) days = ga.GoogleAdsSource().fetch_days(_ctx(login_customer_id="999-888-7777", api_version="v27"), date(2026, 10, 1), date(2026, 10, 3)) api = seen[-1] assert str(api.url) == "https://googleads.googleapis.com/v27/customers/1234567890/googleAds:searchStream" assert api.headers["Authorization"] == "Bearer ya29.TOKEN" and "developer-token" not in api.headers # 폐지된 머리글은 보내지 않음 assert api.headers["login-customer-id"] == "9998887777" q = json.loads(api.content)["query"] assert "segments.date BETWEEN '2026-10-01' AND '2026-10-03'" in q and "metrics.conversions_value" in q d1, d2, d3 = days # 광고비 = 부가세 포함(2026-10-15): 123,456.5원 × 1.1 = 135,802.15 → 135,802. ROAS 는 구글 값 그대로(617,282.5 ÷ 123,456.5) assert (d1.day, d1.amount, d1.roas) == (date(2026, 10, 1), 135802, Decimal("500.00")) assert d1.metrics == {"광고비(부가세 포함)": 135802, "비용(부가세 별도)": 123457, "노출수": 20000, "클릭수": 400, "클릭률(%)": 2.0, "전환수": 12.5, "전환 가치": 617283, "ROAS(%)": 500.0} assert list(d1.metrics)[:2] == ["광고비(부가세 포함)", "비용(부가세 별도)"] # 일자별 표 열 순서 assert (d2.amount, d2.roas, d2.metrics["클릭률(%)"]) == (0, None, 0.0) # 비용 0 → ROAS 없음 assert (d3.amount, d3.roas) == (1, Decimal("300000.00")) # 토큰은 한 번만 받아 두고 다시 쓴다 ga.GoogleAdsSource().fetch_days(_ctx(), date(2026, 10, 1), date(2026, 10, 1)) assert sum(1 for r in seen if r.url.host == "oauth2.googleapis.com") == 1 assert "login-customer-id" not in seen[-1].headers and "/v26/" in str(seen[-1].url) # 비우면 MCC 없음·기본 버전 def test_errors_are_explained(monkeypatch): src = ga.GoogleAdsSource() denied = [{"error": {"code": 403, "message": "The caller does not have permission", "status": "PERMISSION_DENIED", "details": [{"errors": [{"errorCode": {"authorizationError": "USER_PERMISSION_DENIED"}, "message": "User doesn't have permission to access customer."}]}]}}] _install(monkeypatch, lambda req: httpx.Response(403, json=denied)) with pytest.raises(AuthFailed) as e: src.fetch_days(_ctx(), date(2026, 10, 1), date(2026, 10, 1)) assert "USER_PERMISSION_DENIED" in e.value.message and "액세스 및 보안" in e.value.message # 사용자 화면 오류(2026-10-15): 로그인 고객 ID(MCC) 칸에 권한 없는 번호 → 칸을 비우라는 안내 bad_login = [{"error": {"code": 403, "message": "PERMISSION_DENIED", "details": [{"errors": [ {"errorCode": {"authorizationError": "INVALID_LOGIN_CUSTOMER_ID"}, "message": "The login customer id header 'Optional[9998887777]' could not be validated."}]}]}}] _install(monkeypatch, lambda req: httpx.Response(403, json=bad_login)) with pytest.raises(AuthFailed) as e: src.fetch_days(_ctx(login_customer_id="999-888-7777"), date(2026, 10, 1), date(2026, 10, 1)) assert "INVALID_LOGIN_CUSTOMER_ID" in e.value.message and "칸을 지우고" in e.value.message _install(monkeypatch, lambda req: httpx.Response(404, text="Not Found")) with pytest.raises(ApiError) as e: src.fetch_days(_ctx(api_version="v19"), date(2026, 10, 1), date(2026, 10, 1)) assert "v19" in e.value.message and "API 버전" in e.value.message usd = [{"results": [{"customer": {"currencyCode": "USD"}, "segments": {"date": "2026-10-01"}, "metrics": {}}]}] _install(monkeypatch, lambda req: httpx.Response(200, json=usd)) with pytest.raises(ApiError, match="USD"): src.fetch_days(_ctx(), date(2026, 10, 1), date(2026, 10, 1)) with pytest.raises(NotConfigured): src.fetch_days(_ctx(customer_id=""), date(2026, 10, 1), date(2026, 10, 1)) ga._token_cache.clear() def bad_token(request): return httpx.Response(400, json={"error": "invalid_grant", "error_description": "Invalid JWT Signature."}) monkeypatch.setattr(ga, "_http", lambda ctx: httpx.Client(transport=httpx.MockTransport(bad_token))) with pytest.raises(AuthFailed, match="invalid_grant"): src.fetch_days(_ctx(), date(2026, 10, 1), date(2026, 10, 1)) def test_connection_message(monkeypatch): body = [{"results": [{"customer": {"id": "1234567890", "descriptiveName": "미라네주방", "currencyCode": "KRW", "timeZone": "Asia/Seoul"}}]}] _install(monkeypatch, lambda req: httpx.Response(200, json=body)) assert ga.GoogleAdsSource().test_connection(_ctx()) == "연결됨 — 미라네주방 · 통화 KRW · 시간대 Asia/Seoul" def test_ad_credentials_use_own_namespace(): """광고 인증정보 암호문은 "perf:ad:{채널}:{항목}" 에 묶인다 — 쇼핑몰 암호문과 바꿔 넣으면 복호화되지 않는다.""" ring = crypto.KeyRing.from_env({"APP_ENCRYPTION_KEY": KEY1}) class Table: def __init__(self): self.rows = {} def credential_rows(self, code): return {k: {"encrypted_value": v, "key_version": 1} for (c, k), v in self.rows.items() if c == code} def upsert_credential(self, code, key, *, encrypted_value, key_version, user=""): self.rows[(code, key)] = encrypted_value t = Table() svc = CredentialService(t, lambda: ring, aad_ns=ad_sync.AD_NS) svc.save(ga.GoogleAdsSource(), {"service_account_json": SA, "customer_id": "1234567890"}, user="king") assert svc.accessor("google").get("service_account_json") == SA assert aad_for("google", "service_account_json", "ad:") == "perf:ad:google:service_account_json" with pytest.raises(Exception): crypto.decrypt(t.rows[("google", "service_account_json")], aad=aad_for("google", "service_account_json"), ring=ring) # 저장된 일반 항목을 화면에서 비우고 [연결 테스트] → 그 항목은 빈 값으로(저장값 무시), 새 입력값이 있으면 그 값 svc.save(ga.GoogleAdsSource(), {"login_customer_id": "999-888-7777"}, user="king") acc = svc.accessor("google", cleared={"login_customer_id"}) assert acc.get("login_customer_id") == "" and not acc.has("login_customer_id") and acc.get("customer_id") == "1234567890" assert svc.accessor("google").get("login_customer_id") == "999-888-7777" acc = svc.accessor("google", overrides={"login_customer_id": "111-222-3333"}, cleared={"login_customer_id"}) assert acc.get("login_customer_id") == "111-222-3333" # [저장] 때 clear 로 보내면 지워진다(빈 칸 = 유지가 아니라 지움) t.delete_credential = lambda code, key: t.rows.pop((code, key)) svc.save(ga.GoogleAdsSource(), {}, clear=["login_customer_id"], user="king") assert ("google", "login_customer_id") not in t.rows class FakeStore: def __init__(self): self.replaced, self.status = [], [] def ad_credential_keys_by_code(self): return {"google": {"customer_id", "service_account_json"}} def ad_credential_rows(self, code): return {} def replace_ad_api_range(self, code, start, end, days, *, user=""): self.replaced.append((code, start, end, days, user)) return len(days) def record_ad_status(self, code, *, status, ok, error="", kind="test"): self.status.append((code, status, ok, error, kind)) def _service(store, source): svc = ad_sync.AdSyncService(store, CredentialService(None, lambda: None)) svc.configured = lambda: {"google": True} svc._ctx = lambda code, values=None, user="": _ctx() return svc def test_sync_service_saves_and_records(monkeypatch): store = FakeStore() from app.modules.performance.ad_sources.base import AdDay src = ga.GoogleAdsSource() monkeypatch.setattr(src, "fetch_days", lambda ctx, s, e: [AdDay(date(2026, 10, 1), 1000, Decimal("250.00"), {"비용": 1000})]) monkeypatch.setattr(ad_sync, "get_source", lambda code: src) svc = _service(store, src) res = svc.sync("google", date(2026, 10, 1), date(2026, 10, 3), user="king@x") assert res["ok"] and res["days"] == 1 and res["total"] == 1000 assert store.replaced == [("google", date(2026, 10, 1), date(2026, 10, 3), [(date(2026, 10, 1), 1000, Decimal("250.00"), {"비용": 1000})], "king@x")] assert store.status[-1] == ("google", "ok", True, "", "sync") # 실패: 저장 안 하고 상태에 오류(저장된 비밀값은 가림) def boom(ctx, s, e): raise AuthFailed("거부된 값 123-456-7890") monkeypatch.setattr(src, "fetch_days", boom) res = svc.sync("google", date(2026, 10, 1), date(2026, 10, 1)) assert not res["ok"] and res["status"] == "auth_failed" and "123-456-7890" not in res["message"] # 꺼낸 인증정보 값은 가림 assert len(store.replaced) == 1 and store.status[-1][1:3] == ("auth_failed", False) # 같은 채널 동시 실행 막기 lock = ad_sync._lock("google") lock.acquire() try: with pytest.raises(ad_sync.AdSyncBusy): svc.sync("google", date(2026, 10, 1), date(2026, 10, 1)) assert svc.sync_all(date(2026, 10, 1), date(2026, 10, 1))[0]["skipped"] finally: lock.release() def test_sync_endpoint(monkeypatch): import importlib from fastapi import FastAPI from fastapi.testclient import TestClient from app.modules.performance import common perf_router = importlib.import_module("app.modules.performance.router") calls, admin = [], {"v": False} class Svc: def __init__(self): self.result = {"ok": True, "code": "google", "name": "구글 광고", "days": 3, "total": 9000} self.conf = {"google": True} def configured(self): return self.conf def sync(self, code, start, end, *, user=""): calls.append((code, start, end, user)) return {**self.result, "from": start.isoformat(), "to": end.isoformat()} svc = Svc() monkeypatch.setattr(common, "require_store", lambda request, admin=False: (object(), {"email": "king@x"})) monkeypatch.setattr(perf_router, "today_kst", lambda: date(2026, 10, 15)) monkeypatch.setattr(perf_router, "_ad_services", lambda store: (None, svc)) import app.store as app_store monkeypatch.setattr(app_store, "is_admin", lambda user: admin["v"]) app = FastAPI() app.include_router(perf_router.router) client = TestClient(app) r = client.post("/performance/api/ad-sources/google/sync", json={"from": "2026-10-01", "to": "2026-10-31"}) assert r.status_code == 200 and r.json()["to"] == "2026-10-15" # 오늘 뒤는 잘라냄 assert calls[-1] == ("google", date(2026, 10, 1), date(2026, 10, 15), "king@x") r = client.post("/performance/api/ad-sources/google/sync", json={}) assert r.status_code == 200 and calls[-1][1] == date(2026, 10, 6) # 기본 = 최근 10일 r = client.post("/performance/api/ad-sources/google/sync", json={"from": "2026-01-01", "to": "2026-10-15"}) assert r.status_code == 403 # 92일 넘으면 관리자만 admin["v"] = True assert client.post("/performance/api/ad-sources/google/sync", json={"from": "2026-01-01", "to": "2026-10-15"}).status_code == 200 assert client.post("/performance/api/ad-sources/kakao/sync", json={}).status_code == 404 # 광고 API 연동이 없는 채널 r = client.post("/performance/api/ad-sources/meta/sync", json={}) # 메타(2026-10-16) — 연동은 있으나 미설정 assert r.status_code == 400 and "설정되지 않았습니다" in r.json()["detail"] svc.result = {"ok": False, "code": "google", "name": "구글 광고", "status": "auth_failed", "message": "권한 없음"} r = client.post("/performance/api/ad-sources/google/sync", json={}) assert r.status_code == 502 and "권한 없음" in r.json()["detail"] svc.conf = {"google": False} r = client.post("/performance/api/ad-sources/google/sync", json={}) assert r.status_code == 400 and "설정" in r.json()["detail"] def test_sync_all_with_job_reports_channel_progress(monkeypatch): """[광고비 업데이트](2026-10-20) — 채널별 진행 막대: 완료(일·광고비)·실패·중지(저장 안 함).""" from app.modules.performance import jobs from app.modules.performance.ad_sources.base import AdDay store = FakeStore() src = ga.GoogleAdsSource() monkeypatch.setattr(src, "fetch_days", lambda ctx, s, e: [AdDay(date(2026, 10, 1), 1000, None, {}), AdDay(date(2026, 10, 2), 2000, None, {})]) monkeypatch.setattr(ad_sync, "get_source", lambda code: src) svc = _service(store, src) job = jobs.create_job(user="king@x", start=None, end=None, kind="ads") res = svc.sync_all(date(2026, 10, 1), date(2026, 10, 2), user="king@x", job=job) assert res[0]["ok"] and job.kind == "ads" shop = job.snapshot()["shops"][0] assert shop["state"] == "done" and shop["upserted"] == 2 and shop["message"] == "광고비 ₩3,000" and shop["fraction"] == 1.0 # 수집 뒤 저장 직전에 [중지] → 저장하지 않음 job2 = jobs.create_job(user="king@x", start=None, end=None, kind="ads") def fetch_then_stop(ctx, s, e): job2.stop_shop("google") return [AdDay(date(2026, 10, 1), 1000, None, {})] monkeypatch.setattr(src, "fetch_days", fetch_then_stop) before = len(store.replaced) res = svc.sync_all(date(2026, 10, 1), date(2026, 10, 1), job=job2) assert res[0].get("cancelled") and len(store.replaced) == before assert job2.snapshot()["shops"][0]["state"] == "cancelled" # 실패 → 막대에 오류(상태·문구) def boom(ctx, s, e): raise AuthFailed("거부") monkeypatch.setattr(src, "fetch_days", boom) job3 = jobs.create_job(user="king@x", start=None, end=None, kind="ads") svc.sync_all(date(2026, 10, 1), date(2026, 10, 1), job=job3) s3 = job3.snapshot()["shops"][0] assert s3["state"] == "error" and s3["status"] == "auth_failed" for j in (job, job2, job3): j.finish() def test_ad_sync_job_endpoint(monkeypatch): import importlib from fastapi import FastAPI from fastapi.testclient import TestClient from app.modules.performance import common, jobs perf_router = importlib.import_module("app.modules.performance.router") ran = [] class Svc: conf = {"google": True, "meta": False} def configured(self): return self.conf monkeypatch.setattr(common, "require_store", lambda request, admin=False: (object(), {"email": "king@x"})) monkeypatch.setattr(perf_router, "today_kst", lambda: date(2026, 10, 15)) monkeypatch.setattr(perf_router, "_ad_services", lambda store: (None, Svc())) monkeypatch.setattr(ad_sync, "run_ad_job", lambda store, ring, job, s, e, user="": ran.append((job.id, s, e, user))) app = FastAPI() app.include_router(perf_router.router) client = TestClient(app) assert client.get("/performance/api/ad-sync/current").json() == {"job": None} r = client.post("/performance/api/ad-sync", json={"from": "2026-10-01", "to": "2026-10-31"}) body = r.json() assert r.status_code == 200 and not body["joined"] and body["job"]["kind"] == "ads" assert body["job"]["to"] == "2026-10-15" # 오늘 뒤는 잘라냄 import time for _ in range(50): if ran: break time.sleep(0.02) assert ran and ran[0][1:] == (date(2026, 10, 1), date(2026, 10, 15), "king@x") # 진행 중이면 새로 시작하지 않고 합류(매출 업데이트와 별개) r = client.post("/performance/api/ad-sync", json={}) assert r.json()["joined"] and r.json()["job"]["id"] == body["job"]["id"] assert client.get("/performance/api/ad-sync/current").json()["job"]["id"] == body["job"]["id"] assert jobs.running_job("sales") is None or jobs.running_job("sales").kind == "sales" jobs.get_job(body["job"]["id"]).finish() Svc.conf = {"google": False} r = client.post("/performance/api/ad-sync", json={}) assert r.status_code == 400 and "광고 API" in r.json()["detail"]