"""메타 광고 API 연동(2026-10-16) — 입력 검사·요청 매개변수·여러 계정 합산·쪽 넘김·구매 값·부가세·ROAS·오류 안내·저장 서비스. 메타 서버는 가짜(httpx MockTransport).""" from __future__ import annotations import hashlib import hmac import json from datetime import date from decimal import Decimal import httpx import pytest from app.modules.performance import ad_spend, ad_sync from app.modules.performance.ad_sources import meta_ads as ma from app.modules.performance.ad_sources.registry import get_source from app.modules.performance.adapters.base import AdapterContext, ApiError, AuthFailed, NotConfigured, TokenExpired from app.modules.performance.credentials import CredentialService TOKEN = "EAAGtesttoken0123456789abcdefSECRET" 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 k, v in self.values.items() if v and k in ("access_token", "app_secret")] def _ctx(**over): values = {"account_ids": "act_1111111111\n2222222222", "access_token": TOKEN} values.update(over) return AdapterContext(code="meta", credentials=Creds(values)) def _install(monkeypatch, handler): """가짜 메타 서버 — handler(request) 가 응답을 만든다. 보낸 요청을 돌려준다.""" seen = [] def route(request: httpx.Request) -> httpx.Response: seen.append(request) return handler(request) monkeypatch.setattr(ma, "_http", lambda ctx: httpx.Client(transport=httpx.MockTransport(route))) return seen def _row(day, spend, **extra): r = {"date_start": day, "date_stop": day, "account_currency": "KRW", "spend": spend} r.update(extra) return r # 계정 1: 두 쪽(paging.next), 계정 2: 한 쪽. 10-01 은 두 계정 모두 있음 → 날짜별 합산. PAGE1 = {"data": [_row("2026-10-01", "100000", impressions="20000", clicks="400", inline_link_clicks="300", actions=[{"action_type": "omni_purchase", "value": "10"}, {"action_type": "purchase", "value": "10"}, {"action_type": "offsite_conversion.fb_pixel_purchase", "value": "10"}, {"action_type": "link_click", "value": "300"}], action_values=[{"action_type": "omni_purchase", "value": "450000"}, {"action_type": "purchase", "value": "450000"}, {"action_type": "offsite_conversion.fb_pixel_purchase", "value": "450000"}])], "paging": {"next": "https://graph.facebook.com/v26.0/act_1111111111/insights?after=CUR&access_token=" + TOKEN}} PAGE2 = {"data": [_row("2026-10-02", "0", impressions="10")], "paging": {}} ACC2 = {"data": [_row("2026-10-01", "50000.5", impressions="5000", clicks="100", inline_link_clicks="80", actions=[{"action_type": "offsite_conversion.fb_pixel_purchase", "value": "2"}], action_values=[{"action_type": "offsite_conversion.fb_pixel_purchase", "value": "150000"}])]} def _insights_server(request: httpx.Request) -> httpx.Response: path, q = request.url.path, request.url.params if path == "/v26.0/act_1111111111/insights": return httpx.Response(200, json=PAGE2 if q.get("after") == "CUR" else PAGE1) if path == "/v26.0/act_2222222222/insights": return httpx.Response(200, json=ACC2) return httpx.Response(404, json={"error": {"message": "unknown path", "code": 100}}) def test_registered_and_detail_channel(): assert get_source("meta").name == "메타 광고" assert "meta" in ad_spend.DETAIL_CHANNELS and "meta" in ad_spend.FILE_ROAS # 머리글 → 일자별 표, ROAS 는 광고 쪽 값 def test_parse_account_ids(): assert ma.parse_account_ids("act_123456, 654321\n\nACT_123456;777777") == ["123456", "654321", "777777"] assert ma.parse_account_ids("") == [] for bad in ("act_abc", "12-34", "act_"): with pytest.raises(ValueError): ma.parse_account_ids(bad) with pytest.raises(ValueError): ma.parse_account_ids(",".join(str(100000 + i) for i in range(ma.MAX_ACCOUNTS + 1))) def test_validate_credentials(): src = ma.MetaAdsSource() ok = {"account_ids": "act_1111111111", "access_token": TOKEN} assert src.validate_credentials(ok) == [] assert src.validate_credentials({**ok, "access_token": "__stored__"}) == [] assert {f.key for f in src.visible_fields()} == {"account_ids", "access_token", "app_secret", "api_version"} assert {f.key for f in src.visible_fields() if f.secret} == {"access_token", "app_secret"} errs = src.validate_credentials({"account_ids": "act_x", "access_token": "short token", "api_version": "26"}) assert len(errs) == 3 and not any("short token" in e for e in errs) # 토큰 값은 문구에 없음 assert "입력하세요" in " ".join(src.validate_credentials({})) def test_fetch_days_sums_accounts_pages_and_converts(monkeypatch): seen = _install(monkeypatch, _insights_server) days = ma.MetaAdsSource().fetch_days(_ctx(), date(2026, 10, 1), date(2026, 10, 2)) first = seen[0] assert first.url.path == "/v26.0/act_1111111111/insights" q = first.url.params assert q["access_token"] == TOKEN and "appsecret_proof" not in q assert (q["level"], q["time_increment"]) == ("account", "1") assert json.loads(q["time_range"]) == {"since": "2026-10-01", "until": "2026-10-02"} assert {"spend", "action_values", "actions", "account_currency", "date_start"} <= set(q["fields"].split(",")) assert [r.url.params.get("after") for r in seen] == [None, "CUR", None] # 계정 1 두 쪽 → 계정 2 d1, d2 = days # 10-01: 지출 100,000 + 50,000.5 = 150,000.5 → 광고비(부가세 포함) 165,000.55 → 165,001 # 구매 전환값 = 계정1 omni_purchase 450,000(겹친 purchase·픽셀 값은 더하지 않음) + 계정2 픽셀 150,000 = 600,000 # ROAS = 600,000 ÷ 150,000.5 × 100 = 399.998... → 400.00 assert (d1.day, d1.amount, d1.roas) == (date(2026, 10, 1), 165001, Decimal("400.00")) assert d1.metrics == {"광고비(부가세 포함)": 165001, "지출 금액(부가세 별도)": 150001, "노출수": 25000, "클릭수": 500, "클릭률(%)": 2.0, "링크 클릭": 380, "구매수": 12, "구매 전환값": 600000, "ROAS(%)": 400.0} assert list(d1.metrics)[:2] == ["광고비(부가세 포함)", "지출 금액(부가세 별도)"] # 일자별 표 열 순서 assert (d2.day, d2.amount, d2.roas, d2.metrics["클릭률(%)"]) == (date(2026, 10, 2), 0, None, 0.0) # 지출 0 → ROAS 없음 def test_app_secret_proof_and_version(monkeypatch): seen = _install(monkeypatch, lambda req: httpx.Response(200, json={"data": []})) out = ma.MetaAdsSource().fetch_days(_ctx(account_ids="333333", app_secret="appsecret", api_version="v27.0"), date(2026, 10, 1), date(2026, 10, 1)) assert out == [] assert seen[0].url.path == "/v27.0/act_333333/insights" expected = hmac.new(b"appsecret", TOKEN.encode(), hashlib.sha256).hexdigest() assert seen[0].url.params["appsecret_proof"] == expected def test_non_krw_and_limits(monkeypatch): _install(monkeypatch, lambda req: httpx.Response(200, json={"data": [{**_row("2026-10-01", "10"), "account_currency": "USD"}]})) with pytest.raises(ApiError, match="USD"): ma.MetaAdsSource().fetch_days(_ctx(account_ids="333333"), date(2026, 10, 1), date(2026, 10, 1)) with pytest.raises(ApiError, match="366"): ma.MetaAdsSource().fetch_days(_ctx(), date(2025, 1, 1), date(2026, 10, 1)) with pytest.raises(NotConfigured): ma.MetaAdsSource().fetch_days(_ctx(access_token=""), date(2026, 10, 1), date(2026, 10, 1)) # 다음 쪽 주소가 메타가 아니면 따라가지 않는다(토큰을 다른 곳에 보내지 않게) _install(monkeypatch, lambda req: httpx.Response(200, json={"data": [], "paging": {"next": "https://evil.example/x"}})) with pytest.raises(ApiError, match="다음 쪽"): ma.MetaAdsSource().fetch_days(_ctx(account_ids="333333"), date(2026, 10, 1), date(2026, 10, 1)) @pytest.mark.parametrize("code,status,exc,hint", [ (190, 400, TokenExpired, "시스템 사용자"), (200, 403, AuthFailed, "ads_read"), (100, 400, ApiError, "광고 계정 ID"), (17, 400, ApiError, "호출 한도"), (80004, 403, ApiError, "호출 한도"), # 403 이어도 호출 한도는 인증 실패가 아님 ]) def test_errors_are_explained(monkeypatch, code, status, exc, hint): _install(monkeypatch, lambda req: httpx.Response(status, json={"error": {"message": "meta says no", "code": code}})) with pytest.raises(exc) as info: ma.MetaAdsSource().fetch_days(_ctx(account_ids="333333"), date(2026, 10, 1), date(2026, 10, 1)) assert hint in str(info.value) and f"({code})" in str(info.value) and TOKEN not in str(info.value) def test_network_error_has_no_token(monkeypatch): def boom(req): raise httpx.ConnectError("connect failed for " + str(req.url)) _install(monkeypatch, boom) with pytest.raises(ApiError) as info: ma.MetaAdsSource().fetch_days(_ctx(account_ids="333333"), date(2026, 10, 1), date(2026, 10, 1)) assert "ConnectError" in str(info.value) and TOKEN not in str(info.value) def test_connection_message(monkeypatch): accounts = {"/v26.0/act_1111111111": {"name": "본계정", "currency": "KRW", "timezone_name": "Asia/Seoul", "account_status": 1}, "/v26.0/act_2222222222": {"name": "해외", "currency": "USD", "timezone_name": "America/Los_Angeles", "account_status": 2}} seen = _install(monkeypatch, lambda req: httpx.Response(200, json=accounts[req.url.path])) msg = ma.MetaAdsSource().test_connection(_ctx()) assert "광고 계정 2개" in msg and "본계정(KRW·Asia/Seoul·운영 중)" in msg and "해외(USD" in msg and "사용 중지" in msg assert "원화가 아닌 계정" in msg assert seen[0].url.params["fields"] == "name,currency,timezone_name,account_status" class FakeStore: def __init__(self): self.replaced, self.status = [], [] 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 test_sync_service_end_to_end(monkeypatch): """실제 MetaAdsSource.fetch_days → AdSyncService 저장·상태. 실패 문구에서 토큰은 가린다.""" _install(monkeypatch, _insights_server) store = FakeStore() svc = ad_sync.AdSyncService(store, CredentialService(None, lambda: None)) svc._ctx = lambda code, values=None, user="", cleared=None: _ctx() res = svc.sync("meta", date(2026, 10, 1), date(2026, 10, 2), user="king@x") assert res["ok"] and res["days"] == 2 and res["total"] == 165001 and res["name"] == "메타 광고" code, start, end, days, user = store.replaced[0] assert (code, start, end, user) == ("meta", date(2026, 10, 1), date(2026, 10, 2), "king@x") assert [(d, amt, roas) for d, amt, roas, _m in days] == [(date(2026, 10, 1), 165001, Decimal("400.00")), (date(2026, 10, 2), 0, None)] assert store.status[-1] == ("meta", "ok", True, "", "sync") # 메타가 오류 문구에 토큰을 되돌려 줘도 저장·화면 문구에서는 가린다 _install(monkeypatch, lambda req: httpx.Response(400, json={"error": {"message": "bad token " + TOKEN, "code": 190}})) res = svc.sync("meta", date(2026, 10, 1), date(2026, 10, 1)) assert not res["ok"] and res["status"] == "token_expired" and TOKEN not in res["message"] assert len(store.replaced) == 1 and store.status[-1][1:3] == ("token_expired", False) and TOKEN not in store.status[-1][3]