Files
dbx-main/app/modules/performance/tests/test_meta_ads.py
T
king 8a597007cb fix(performance): 메타 연결 테스트 진단이 잘리던 문제
- 비밀값 가림(redact_text)의 기본 300자 한도에서 긴 메타 원문·안내 뒤의 [진단]이 "[진…"으로 잘렸다.
- 연결 테스트 문구를 [진단] 먼저 + 메타 원문(긴 안내 주소 제거) 뒤로 바꾸고,
  광고 연동 오류 문구 한도를 ad_sync.AD_MESSAGE_MAX(1200자)로.
- 테스트: 설정 연결 테스트 경로(AdSyncService)에서 진단 전체·순서·주소 제거·토큰 미포함 확인.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 13:26:49 +09:00

333 lines
18 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""메타 광고 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]
# ── 권한 오류(#200) 진단 — 연결 테스트가 메타에 토큰 정보를 물어 원인 하나를 짚는다(2026-10-16) ──
DENIED = {"error": {"message": "(#200) Ad account owner has NOT grant ads_management or ads_read permission", "code": 200}}
def _diag_server(debug=None, perms=None, adaccounts=None):
"""debug/perms/adaccounts = 응답 dict, None 이면 그 조회도 실패(권한 오류)."""
def handler(req: httpx.Request) -> httpx.Response:
path = req.url.path
if path.endswith("/debug_token"):
assert req.url.params["input_token"] == TOKEN
return httpx.Response(200, json=debug) if debug is not None else httpx.Response(400, json=DENIED)
if path.endswith("/me/permissions"):
return httpx.Response(200, json=perms) if perms is not None else httpx.Response(400, json=DENIED)
if path.endswith("/me/adaccounts"):
return httpx.Response(200, json=adaccounts) if adaccounts is not None else httpx.Response(400, json=DENIED)
return httpx.Response(400, json=DENIED) # 광고 계정 조회 = 권한 오류
return handler
def _diag(monkeypatch, **server):
_install(monkeypatch, _diag_server(**server))
with pytest.raises(AuthFailed) as info:
ma.MetaAdsSource().test_connection(_ctx(account_ids="1111111111,2222222222"))
msg = str(info.value)
assert "(#200)" in msg and "[진단]" in msg and TOKEN not in msg
return msg
def _debug(scopes, granular=None, exp=0):
return {"data": {"app_id": "777", "application": "DBX ERP", "is_valid": True, "expires_at": exp,
"scopes": scopes, "granular_scopes": granular or []}}
ALL_VISIBLE = {"data": [{"account_id": "1111111111"}, {"account_id": "2222222222"}]}
def test_diagnose_missing_ads_read(monkeypatch):
msg = _diag(monkeypatch, debug=_debug(["public_profile", "business_management"]), adaccounts=ALL_VISIBLE)
assert "광고 권한: 없음" in msg and "ads_read 권한이 없습니다" in msg and "DBX ERP(777)" in msg and "만료 없음" in msg
def test_diagnose_account_not_assigned(monkeypatch):
msg = _diag(monkeypatch, debug=_debug(["ads_read"]), adaccounts={"data": [{"account_id": "1111111111"}]})
assert "광고 권한: ads_read" in msg and "보이는 광고 계정 1개" in msg
assert "배정되지 않은 계정: act_2222222222" in msg and "act_1111111111" not in msg.split("배정되지 않은 계정")[1].split("→")[0]
assert "자산 할당" in msg
def test_diagnose_scope_targets_other_accounts(monkeypatch):
granular = [{"scope": "ads_read", "target_ids": ["1111111111"]}]
msg = _diag(monkeypatch, debug=_debug(["ads_read"], granular), adaccounts=ALL_VISIBLE)
assert "다른 계정에만" in msg and "act_2222222222" in msg
def test_diagnose_points_to_app_when_token_and_accounts_ok(monkeypatch):
msg = _diag(monkeypatch, debug=_debug(["ads_read", "ads_management"]), adaccounts=ALL_VISIBLE)
assert "광고 권한: ads_management, ads_read" in msg and "앱 쪽 문제" in msg
def test_diagnose_falls_back_to_permissions(monkeypatch):
perms = {"data": [{"permission": "ads_read", "status": "declined"}, {"permission": "public_profile", "status": "granted"}]}
msg = _diag(monkeypatch, debug=None, perms=perms, adaccounts=None)
assert "광고 권한: 없음" in msg and "ads_read 권한이 없습니다" in msg # 거절(declined)은 받은 권한이 아님
def test_diagnose_unknown_when_meta_says_nothing(monkeypatch):
msg = _diag(monkeypatch, debug=None, perms=None, adaccounts=None)
assert "원인을 좁히지 못했습니다" in msg
def test_diag_hint_only_outside_connection_test(monkeypatch):
"""불러오기(fetch_days) 권한 오류엔 '연결 테스트가 진단' 안내, 연결 테스트 자체엔 그 안내 대신 진단 결과."""
_install(monkeypatch, _diag_server(debug=_debug(["ads_read"]), adaccounts=ALL_VISIBLE))
with pytest.raises(AuthFailed) as info:
ma.MetaAdsSource().fetch_days(_ctx(account_ids="1111111111"), date(2026, 10, 1), date(2026, 10, 1))
assert ma._DIAG_HINT in str(info.value) and "[진단]" not in str(info.value)
msg = _diag(monkeypatch, debug=_debug(["ads_read"]), adaccounts=ALL_VISIBLE)
assert ma._DIAG_HINT not in msg
def test_connection_test_shows_full_diagnosis_first(monkeypatch):
"""설정 [연결 테스트](AdSyncService) 문구 — 진단이 맨 앞, 잘리지 않음, 메타 원문의 긴 주소는 뺌(2026-10-16 "[진…" 잘림)."""
long_denied = {"error": {"code": 200, "message": "(#200) Ad account owner has NOT grant ads_management or ads_read permission, "
"refer to https://developers.facebook.com/docs/marketing-api/get-started/authorization/"
"#permissions-and-features for details"}}
def handler(req):
if req.url.path.endswith("/debug_token"):
return httpx.Response(200, json=_debug(["ads_read"]))
if req.url.path.endswith("/me/adaccounts"):
return httpx.Response(200, json={"data": []})
return httpx.Response(400, json=long_denied)
_install(monkeypatch, handler)
store = FakeStore()
svc = ad_sync.AdSyncService(store, CredentialService(None, lambda: None))
svc._ctx = lambda code, values=None, user="", cleared=None: _ctx(account_ids="1111111111,2222222222")
res = svc.test_connection("meta")
msg = res["message"]
assert not res["ok"] and res["status"] == "auth_failed"
assert msg.startswith("[진단]") and not msg.endswith("…") and len(msg) > 300 # 예전 300자 한도면 잘렸을 길이
assert "배정되지 않은 계정: act_1111111111, act_2222222222" in msg and "자산 할당" in msg
assert "(메타 원문: 메타 API 오류(200): (#200) Ad account owner has NOT grant" in msg
assert "https://" not in msg and ma._DIAG_HINT not in msg and TOKEN not in msg