Files
dbx-main/app/modules/performance/tests/test_performance.py
T
king aa669553db feat(performance): 실적(쇼핑몰 통합 매출) 모듈 1단계 — 대시보드·설정·보안·어댑터 구조
- 네 영역 분리: ① 수집(adapters/ 쇼핑몰 10곳 + sync.py) ② 보안(security/ + credentials.py)
  ③ 계산·저장(calc.py + db.py) ④ 화면(dashboard.py, router.py, templates, performance.css/js)
- 대시보드: 기간(오늘/이번주/이번달/올해/직접선택, 이전·다음), 쇼핑몰 필터, KPI 5개(진행 중 기간은
  직전 기간 같은 경과일 대비), 일자×쇼핑몰 표(주간합계, 총매출/수수료/차감매출 전환), 일별 추이·
  쇼핑몰 비중(SVG), 월 누적(비중)·연간 누적, 금액 클릭 → 주문 상세
- 설정(관리자): 사용/매출 집계, 수수료율 이력(적용 시작일), 쇼핑몰별 API 인증정보 입력·연결 테스트·
  연결 상태, 마스터 키 상태·재암호화, 테스트(모의) 데이터 생성/삭제
- 인증정보: 설정 화면 입력 → AES-256-GCM(키 버전, AAD=쇼핑몰+항목) 암호화 저장, secret 원문은
  화면으로 다시 보내지 않음, 오류·로그·raw 는 비밀값 가린 뒤 저장. 마스터 키는 APP_ENCRYPTION_KEY(.env)
- 매출 기준일: 결제=결제일, 취소·반품=발생일. 금액 원 단위 정수, 수수료 반올림은 calc.commission 한 곳
- 동기화: 같은 쇼핑몰 동시 실행 차단(running 부분 유니크), 쇼핑몰별 실패 격리, 중복 방지 UNIQUE+UPSERT
- 카페24 어댑터는 기존 app/integrations/cafe24 OAuth 토큰 재사용, 나머지는 입력칸만(수집은 다음 단계)
- performance_db 초기화 스크립트, 권한키 performance(설정은 is_admin), 문서·.env.example

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 16:07:46 +09:00

407 lines
20 KiB
Python

"""실적 모듈 테스트 — 암호화·가리기·계산·인증정보·동기화. DB/네트워크 없이 가짜 저장소로.
python -m app.modules.performance.tests.test_performance
또는 pytest 로 실행 가능.
"""
from __future__ import annotations
import os
from datetime import date, timedelta
from decimal import Decimal
from app.modules.performance import calc
from app.modules.performance.adapters import mock
from app.modules.performance.adapters.base import (
AuthFailed,
CredentialField,
MarketplaceAdapter,
SaleEvent,
)
from app.modules.performance.adapters.registry import all_adapters
from app.modules.performance.credentials import CredentialService, aad_for
from app.modules.performance.security import crypto
from app.modules.performance.security.redact import MASK, mask, redact_mapping, redact_text
from app.modules.performance.sync import SyncService, event_row, sales_date_for
KEY1 = "11" * 32
KEY2 = "22" * 32
def ring(version: int = 1, **old: str) -> crypto.KeyRing:
env = {"APP_ENCRYPTION_KEY": KEY1 if version == 1 else KEY2, "APP_ENCRYPTION_KEY_VERSION": str(version)}
env.update(old)
return crypto.KeyRing.from_env(env)
# ════════════════════════════════════════════════════════════
# 암호화
# ════════════════════════════════════════════════════════════
def test_crypto_roundtrip_and_format():
r = ring()
token = crypto.encrypt("my-secret-value", aad="perf:coupang:secret_key", ring=r)
assert token.startswith("v1:")
assert "my-secret-value" not in token
assert crypto.decrypt(token, aad="perf:coupang:secret_key", ring=r) == "my-secret-value"
# 같은 평문도 매번 다른 암호문(nonce)
assert token != crypto.encrypt("my-secret-value", aad="perf:coupang:secret_key", ring=r)
def test_crypto_rejects_wrong_aad_tamper_and_key():
r = ring()
token = crypto.encrypt("abc", aad="perf:coupang:secret_key", ring=r)
for bad in (lambda: crypto.decrypt(token, aad="perf:naver:client_secret", ring=r),
lambda: crypto.decrypt(token[:-2] + ("A" if token[-2] != "A" else "B") + token[-1], aad="perf:coupang:secret_key", ring=r),
lambda: crypto.decrypt(token, aad="perf:coupang:secret_key",
ring=crypto.KeyRing.from_env({"APP_ENCRYPTION_KEY": KEY2}))):
try:
bad()
except crypto.DecryptError as exc:
assert "abc" not in str(exc)
else:
raise AssertionError("복호화가 실패해야 합니다")
def test_crypto_missing_or_bad_key():
for env in ({}, {"APP_ENCRYPTION_KEY": "short"}, {"APP_ENCRYPTION_KEY": KEY1, "APP_ENCRYPTION_KEY_VERSION": "0"}):
try:
crypto.KeyRing.from_env(env)
except crypto.CryptoConfigError:
pass
else:
raise AssertionError(f"설정 오류여야 합니다: {list(env)}")
# base64 32바이트 키도 받는다
import base64
b64 = base64.urlsafe_b64encode(bytes(range(32))).decode()
assert crypto.KeyRing.from_env({"APP_ENCRYPTION_KEY": b64}).current_version == 1
assert "11" * 4 not in repr(ring()) # 키 값이 repr 에 나오지 않음
def test_crypto_rotation():
old = ring(1)
token = crypto.encrypt("rotate-me", aad="a", ring=old)
new = ring(2, APP_ENCRYPTION_KEY_V1=KEY1)
assert new.versions == [1, 2]
assert crypto.needs_reencrypt(token, new)
assert crypto.decrypt(token, aad="a", ring=new) == "rotate-me"
token2 = crypto.encrypt("rotate-me", aad="a", ring=new)
assert token2.startswith("v2:") and not crypto.needs_reencrypt(token2, new)
try:
crypto.decrypt(token, aad="a", ring=ring(2)) # 예전 키를 안 남기면 실패
except crypto.DecryptError as exc:
assert "v1" in str(exc)
else:
raise AssertionError("예전 키 없이는 복호화 실패해야 합니다")
# ════════════════════════════════════════════════════════════
# 가리기
# ════════════════════════════════════════════════════════════
def test_redact():
secret = "SK-live-9f8e7d6c5b4a"
msg = f"401 Unauthorized secret={secret} Authorization: Bearer abcdef123456 token=zzz999 other=ok"
out = redact_text(msg, [secret])
assert secret not in out and "abcdef123456" not in out and "zzz999" not in out
assert "other=ok" in out and MASK in out
assert "Cookie" not in redact_text("Cookie: sid=abc; x=1").replace(f"Cookie: {MASK}", "")
j = redact_text('{"access_token": "tok-123456", "vendor": "A001"}')
assert "tok-123456" not in j and "A001" in j
data = redact_mapping({"order": "1", "headers": {"Authorization": "x", "X-Api-Key": "y"}, "items": [{"password": "p"}]})
assert data["order"] == "1" and data["headers"]["Authorization"] == MASK
assert data["headers"]["X-Api-Key"] == MASK and data["items"][0]["password"] == MASK
assert mask("ABCDEFGHIJKL1234") == "ABCD****1234" and mask("short") == MASK
assert len(redact_text("x" * 1000)) <= 301
# ════════════════════════════════════════════════════════════
# 계산
# ════════════════════════════════════════════════════════════
def test_commission_rounding():
assert calc.commission(1_000_000, Decimal("10")) == 100_000
assert calc.commission(12_345, Decimal("10.8")) == 1_333 # 1333.26 → 1333
assert calc.commission(15, Decimal("10")) == 2 # 1.5 → 2 (half up)
assert calc.commission(-15, Decimal("10")) == -2 # 취소도 같은 규칙
assert calc.commission(100_000, Decimal("15.35")) == 15_350
assert calc.commission(0, Decimal("10")) == 0 and calc.commission(1000, Decimal("0")) == 0
m = calc.Money(gross=1_000_000, commission=100_000)
assert m.net == 900_000
def test_rate_history():
rates = {"coupang": [(date(2026, 1, 1), Decimal("8")), (date(2026, 7, 1), Decimal("10"))]}
assert calc.rate_on(rates, "coupang", date(2025, 12, 31)) == 0
assert calc.rate_on(rates, "coupang", date(2026, 6, 30)) == 8
assert calc.rate_on(rates, "coupang", date(2026, 7, 1)) == 10
assert calc.rate_on(rates, "naver", date(2026, 7, 1)) == 0
cells = calc.build_cells({(date(2026, 6, 30), "coupang"): 100_000, (date(2026, 7, 1), "coupang"): 100_000}, rates)
assert cells[(date(2026, 6, 30), "coupang")].commission == 8_000
assert cells[(date(2026, 7, 1), "coupang")].commission == 10_000
def test_periods():
wed = date(2026, 9, 30)
p = calc.resolve_period("week", wed)
assert (p.start, p.end) == (date(2026, 9, 28), date(2026, 10, 4)) # 월~일
assert p.start.weekday() == 0 and p.end.weekday() == 6 and p.days == 7
assert p.prev_anchor == date(2026, 9, 21)
m = calc.resolve_period("month", date(2026, 2, 15))
assert (m.start, m.end) == (date(2026, 2, 1), date(2026, 2, 28))
y = calc.resolve_period("year", wed)
assert (y.start, y.end) == (date(2026, 1, 1), date(2026, 12, 31))
c = calc.resolve_period("custom", wed, custom_from=date(2026, 9, 29), custom_to=date(2026, 9, 1))
assert (c.start, c.end) == (date(2026, 9, 1), date(2026, 9, 29))
# 진행 중인 주 — 전주 같은 요일까지만 비교
s, e, label = p.compare_range(today=wed)
assert (s, e) == (date(2026, 9, 21), date(2026, 9, 23)) and label.startswith("전주")
# 지난 주 — 전주 전체
s, e, _ = calc.resolve_period("week", date(2026, 9, 20)).compare_range(today=wed)
assert (s, e) == (date(2026, 9, 7), date(2026, 9, 13))
# 진행 중인 달 — 전월 같은 날까지(말일 넘지 않게)
s, e, _ = calc.resolve_period("month", date(2026, 3, 31)).compare_range(today=date(2026, 3, 31))
assert (s, e) == (date(2026, 2, 1), date(2026, 2, 28))
assert calc.pct_change(110, 100) == 10.0 and calc.pct_change(5, 0) is None and calc.pct_change(0, 0) is None
def _cells_for(days, codes, amount=10_000):
return calc.build_cells({(d, c): amount for d in days for c in codes}, {"a": [(date(2000, 1, 1), Decimal("10"))]})
def test_main_table_week():
p = calc.resolve_period("week", date(2026, 9, 30))
days = list(calc.daterange(p.start, p.end))
cells = _cells_for(days, ["a", "b"])
rows = calc.main_table(p, ["a", "b"], cells, today=date(2026, 9, 30), holidays={"2026-10-03": "개천절"})
assert [r["kind"] for r in rows] == ["day"] * 7 + ["week"]
assert rows[0]["label"] == "월 9/28" and rows[6]["label"] == "일 10/4"
assert rows[5]["holiday"] == "개천절" and rows[2]["today"] and rows[3]["future"]
week = rows[-1]
assert week["cells"]["a"] == {"gross": 70_000, "commission": 7_000, "net": 63_000}
assert week["cells"]["b"]["commission"] == 0 # 요율 없는 쇼핑몰 = 0%
assert week["total"]["gross"] == 140_000
assert rows[0]["total"]["gross"] == 20_000
def test_main_table_month_and_year():
p = calc.resolve_period("month", date(2026, 9, 10))
cells = _cells_for(list(calc.daterange(p.start, p.end)), ["a"])
rows = calc.main_table(p, ["a"], cells, today=date(2026, 9, 30))
weeks = [r for r in rows if r["kind"] == "week"]
assert rows[-1]["kind"] == "total" and rows[-1]["total"]["gross"] == 300_000
assert sum(w["total"]["gross"] for w in weeks) == 300_000
assert weeks[0]["from"] == "2026-09-01" and weeks[0]["to"] == "2026-09-06" # 첫 주는 월 시작부터
y = calc.resolve_period("year", date(2026, 9, 10))
yrows = calc.main_table(y, ["a"], cells, today=date(2026, 9, 30))
assert len(yrows) == 13 and yrows[8]["total"]["gross"] == 300_000 and yrows[9]["future"]
ym = calc.year_months(2026, ["a"], cells, today=date(2026, 9, 30))
assert ym["rows"][9]["gross"] is None and ym["rows"][8]["gross"] == 300_000 and ym["total"]["gross"] == 300_000
ms = calc.month_summary(2026, 9, ["a"], cells)
assert ms["rows"][0]["share"] == 100.0 and ms["total"]["net"] == 270_000
# ════════════════════════════════════════════════════════════
# 가짜 저장소 + 인증정보
# ════════════════════════════════════════════════════════════
class FakeStore:
def __init__(self):
self.creds: dict[tuple[str, str], dict] = {}
self.events: dict[tuple[str, str, str], dict] = {}
self.status: dict[str, dict] = {}
self.running: set[str] = set()
self.markets = [{"code": a.code, "name": a.name, "enabled": True, "include_in_sales": True} for a in all_adapters()]
def credential_rows(self, code):
return {k: {**v, "updated_at": None} for (c, k), v in self.creds.items() if c == code}
def credential_keys_by_code(self):
out = {}
for c, k in self.creds:
out.setdefault(c, set()).add(k)
return out
def upsert_credential(self, code, key, *, encrypted_value, key_version, user=""):
self.creds[(code, key)] = {"encrypted_value": encrypted_value, "key_version": key_version}
def delete_credential(self, code, key):
self.creds.pop((code, key), None)
def all_credential_rows(self):
return [{"marketplace_code": c, "credential_key": k, **v} for (c, k), v in self.creds.items()]
def list_marketplaces(self):
return self.markets
def start_run(self, code, **_):
if code in self.running:
return None
self.running.add(code)
return len(self.running)
def finish_run(self, run_id, **_):
self.running.clear()
def record_sync(self, code, *, status, ok, error=""):
self.status[code] = {"status": status, "ok": ok, "error": error}
def record_test(self, code, *, status, ok, error=""):
self.status[code] = {"status": status, "ok": ok, "error": error, "test": True}
def upsert_events(self, code, events, *, is_sample=False):
n = 0
for e in events:
self.events[(code, e["event_type"], e["external_event_id"])] = {**e, "is_sample": is_sample}
n += 1
return n
def _coupang():
return next(a for a in all_adapters() if a.code == "coupang")
def test_credentials_encrypted_and_never_returned():
st = FakeStore()
svc = CredentialService(st, lambda: ring())
ad = _coupang()
saved = svc.save(ad, {"vendor_id": "A00012345", "access_key": "AK-plain-111", "secret_key": "SK-plain-222",
"unknown": "x"}, user="t@x")
assert sorted(saved) == ["access_key", "secret_key", "vendor_id"]
for (code, key), row in st.creds.items():
assert "plain" not in row["encrypted_value"] and "A00012345" not in row["encrypted_value"]
assert row["encrypted_value"].startswith("v1:") and row["key_version"] == 1
info = svc.describe(ad)
as_text = repr(info)
assert "AK-plain-111" not in as_text and "SK-plain-222" not in as_text
by_key = {f["key"]: f for f in info["fields"]}
assert by_key["secret_key"]["has_value"] and "value" not in by_key["secret_key"]
assert by_key["vendor_id"]["value"] == "A00012345" and info["configured"]
# 빈 칸 = 유지, 다른 쇼핑몰 칸으로 옮긴 암호문은 풀리지 않음(AAD)
svc.save(ad, {"secret_key": "", "access_key": "AK-new"})
acc = svc.accessor("coupang")
assert acc.get("secret_key") == "SK-plain-222" and acc.get("access_key") == "AK-new"
moved = st.creds[("coupang", "secret_key")]["encrypted_value"]
try:
crypto.decrypt(moved, aad=aad_for("naver", "client_secret"), ring=ring())
except crypto.DecryptError:
pass
else:
raise AssertionError("다른 칸의 암호문은 복호화되면 안 됩니다")
# 재암호화(키 교체)
svc2 = CredentialService(st, lambda: ring(2, APP_ENCRYPTION_KEY_V1=KEY1))
assert svc2.reencrypt_all() == {"reencrypted": 3, "failed": 0}
assert all(r["key_version"] == 2 for r in st.creds.values())
assert svc2.accessor("coupang").get("secret_key") == "SK-plain-222"
assert svc2.configured_codes(list(all_adapters()))["coupang"] is True
assert svc2.configured_codes(list(all_adapters()))["naver"] is False
assert svc2.configured_codes(list(all_adapters()))["cafe24"] is True # 공통 연동
# ════════════════════════════════════════════════════════════
# 동기화
# ════════════════════════════════════════════════════════════
class _Leaky(MarketplaceAdapter):
code, name = "coupang", "쿠팡"
def credential_fields(self):
return [CredentialField("secret_key", "Secret", secret=True)]
def collect(self, ctx, start, end):
secret = ctx.credentials.get("secret_key")
raise AuthFailed(f"401 invalid signature for key {secret} Authorization: CEA abcdefg123")
class _Good(MarketplaceAdapter):
code, name = "naver", "네이버"
def collect(self, ctx, start, end):
d = date(2026, 9, 29)
return 1, [
SaleEvent("SALE", "o1-S", "o1", d, 10_000, payment_date=d - timedelta(days=1), raw={"token": "t"}),
SaleEvent("CANCEL", "o1-C", "o1", d, -10_000),
]
def test_sync_isolation_redaction_and_dedupe():
import app.modules.performance.sync as syncmod
st = FakeStore()
creds = CredentialService(st, lambda: ring())
creds.save(_coupang(), {"vendor_id": "V", "access_key": "AK", "secret_key": "SUPER-SECRET-KEY-123"})
leaky, good = _Leaky(), _Good()
orig = syncmod.get_adapter
syncmod.get_adapter = lambda c: {"coupang": leaky, "naver": good}.get(c)
try:
svc = SyncService(st, creds)
r1 = svc.sync_marketplace("coupang", date(2026, 9, 23), date(2026, 9, 29))
r2 = svc.sync_marketplace("naver", date(2026, 9, 23), date(2026, 9, 29))
svc.sync_marketplace("naver", date(2026, 9, 23), date(2026, 9, 29)) # 두 번 = 중복 없음
finally:
syncmod.get_adapter = orig
assert not r1["ok"] and r1["status"] == "auth_failed"
assert "SUPER-SECRET-KEY-123" not in r1["message"] and "abcdefg123" not in r1["message"]
assert "SUPER-SECRET-KEY-123" not in st.status["coupang"]["error"]
assert r2["ok"] and r2["upserted"] == 2 and st.status["naver"]["status"] == "ok"
assert len([k for k in st.events if k[0] == "naver"]) == 2
sale = st.events[("naver", "SALE", "o1-S")]
assert sale["sales_date"] == date(2026, 9, 28) # 결제일 기준
assert st.events[("naver", "CANCEL", "o1-C")]["sales_date"] == date(2026, 9, 29) # 발생일 기준
assert sale["raw"]["token"] == MASK
# 이미 도는 중이면 건너뜀
st.running.add("naver")
syncmod.get_adapter = lambda c: good
try:
r3 = SyncService(st, creds).sync_marketplace("naver", date(2026, 9, 29), date(2026, 9, 29))
finally:
syncmod.get_adapter = orig
assert r3["skipped"]
def test_not_implemented_and_mock():
st = FakeStore()
creds = CredentialService(st, lambda: ring())
svc = SyncService(st, creds)
r = svc.sync_marketplace("elevenst", date(2026, 9, 29), date(2026, 9, 29))
assert r["status"] == "not_configured" # 키 미입력
creds.save(next(a for a in all_adapters() if a.code == "elevenst"), {"api_key": "k-123456"})
r = svc.sync_marketplace("elevenst", date(2026, 9, 29), date(2026, 9, 29))
assert r["status"] == "not_implemented" and "k-123456" not in r["message"]
t = svc.test_connection("elevenst", values={"api_key": "typed-only"})
assert t["unsaved"] and "test" not in st.status.get("elevenst", {}) # 저장 안 한 값 시험은 상태 기록 안 함
a = mock.generate("naver", date(2026, 9, 1), date(2026, 9, 30))
b = mock.generate("naver", date(2026, 9, 1), date(2026, 9, 30))
assert [e.amount for e in a] == [e.amount for e in b] and a
for e in a:
e.validate()
assert (e.amount < 0) == (e.event_type in ("CANCEL", "RETURN"))
assert any(e.event_type == "CANCEL" for e in a)
n = svc.generate_samples(date(2026, 9, 1), date(2026, 9, 30), ["naver"])
assert n == len(a) and all(v["is_sample"] for v in st.events.values())
assert sales_date_for(a[0]) == a[0].payment_date
assert event_row(a[0])["sales_date"] == a[0].payment_date
def test_registry_and_event_validation():
codes = [a.code for a in all_adapters()]
assert len(codes) == len(set(codes)) == 10
for a in all_adapters():
keys = [f.key for f in a.credential_fields()]
assert len(keys) == len(set(keys)), a.code
assert a.uses_shared_integration or any(f.secret for f in a.visible_fields()), a.code
for bad in (SaleEvent("SALE", "x", "o", date.today(), -1), SaleEvent("CANCEL", "x", "o", date.today(), 5),
SaleEvent("SALE", "x", "o", date.today(), 1.5), SaleEvent("BOGUS", "x", "o", date.today(), 1)):
try:
bad.validate()
except ValueError:
pass
else:
raise AssertionError(f"검증 실패해야 함: {bad.event_type} {bad.amount}")
if __name__ == "__main__":
os.environ.pop("APP_ENCRYPTION_KEY", None)
n = 0
for name, fn in sorted(globals().items()):
if name.startswith("test_") and callable(fn):
fn()
n += 1
print("ok", name)
print(f"{n} tests passed")