"""구글 광고 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 = {"developer_token": "DEVTOKEN", "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 = {"developer_token": "x", "customer_id": "123-456-7890", "service_account_json": SA} assert src.validate_credentials(ok) == [] assert src.validate_credentials({**ok, "service_account_json": "__stored__", "developer_token": "__stored__"}) == [] 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 api.headers["developer-token"] == "DEVTOKEN" 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 assert (d1.day, d1.amount, d1.roas) == (date(2026, 10, 1), 123457, Decimal("500.00")) # 123,456.5원 → 반올림, 617,282.5 ÷ 123,456.5 assert d1.metrics == {"비용": 123457, "노출수": 20000, "클릭수": 400, "클릭률(%)": 2.0, "전환수": 12.5, "전환 가치": 617283, "ROAS(%)": 500.0} 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 _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(), {"developer_token": "DEV", "customer_id": "1234567890"}, user="king") assert svc.accessor("google").get("developer_token") == "DEV" assert aad_for("google", "developer_token", "ad:") == "perf:ad:google:developer_token" with pytest.raises(Exception): crypto.decrypt(t.rows[("google", "developer_token")], aad=aad_for("google", "developer_token"), ring=ring) class FakeStore: def __init__(self): self.replaced, self.status = [], [] def ad_credential_keys_by_code(self): return {"google": {"developer_token", "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("토큰 DEVTOKEN 거부") 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 "DEVTOKEN" 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/meta/sync", json={}).status_code == 404 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"]