"""실적 모듈 테스트 — 암호화·가리기·계산·인증정보·동기화. 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 # ════════════════════════════════════════════════════════════ # 카페24 어댑터(가짜 API 응답) # ════════════════════════════════════════════════════════════ def _c24_item(code, status="N40", price="30000.00", qty=1, pay="29000.00", **kw): return {"order_item_code": code, "order_status": status, "product_name": "냄비", "option_value": "", "product_price": price, "option_price": "0.00", "quantity": qty, "payment_amount": pay, "coupon_discount_price": "1000.00", "claim_quantity": 0, **kw} def _c24_order(oid, items, market="self", paid="T", **kw): return {"order_id": oid, "market_id": market, "paid": paid, "order_date": "2026-09-27T10:00:00+09:00", "payment_date": "2026-09-28T11:21:35+09:00", "buyer_name": "홍길동", "receiver_address": "서울시", "bank_account_no": "1234567890", "items": items, **kw} class _FakeCafe24(__import__("app.modules.performance.adapters.cafe24", fromlist=["Cafe24Adapter"]).Cafe24Adapter): def __init__(self, pages): self.pages = pages # date_type → [응답 orders 목록(페이지별)] self.calls = [] def authenticate(self, ctx): return None def _get(self, ctx, params): self.calls.append(params) pages = self.pages.get(params["date_type"], []) idx = params.get("offset", 0) // 1000 return {"orders": pages[idx] if idx < len(pages) else []} def test_cafe24_normalize(): from app.modules.performance.adapters.cafe24 import Cafe24Adapter, item_amount paid = _c24_order("20260928-01", [_c24_item("20260928-01-01"), _c24_item("20260928-01-02", pay="10000.00")]) market = _c24_order("20260928-02", [_c24_item("20260928-02-01")], market="shopn") # 스마트스토어 연동 주문 unpaid = _c24_order("20260928-03", [_c24_item("20260928-03-01", status="N00")], paid="F") canceled = _c24_order("20260928-01", [ _c24_item("20260928-01-01", status="C40", cancel_date="2026-09-29 09:00:00"), _c24_item("20260928-01-02", status="N40")]) precancel = _c24_order("20260928-04", [_c24_item("20260928-04-01", status="C48", cancel_date="2026-09-29 09:00:00")]) returned = _c24_order("20260928-05", [_c24_item("20260928-05-01", status="R40", qty=3, pay="90000.00", claim_quantity=1, return_confirmed_date="2026-09-30 10:00:00")]) fake = _FakeCafe24({"pay_date": [[paid, market, unpaid]], "cancel_complete_date": [[canceled, precancel]], "return_complete_date": [[returned]]}) ctx = __import__("app.modules.performance.adapters.base", fromlist=["AdapterContext"]).AdapterContext( code="cafe24", credentials=None) fetched, events = fake.collect(ctx, date(2026, 9, 23), date(2026, 9, 30)) by = {(e.event_type, e.external_line_id): e for e in events} assert fetched == 6 assert by[("SALE", "20260928-01-01")].amount == 29_000 and by[("SALE", "20260928-01-02")].amount == 10_000 assert by[("SALE", "20260928-01-01")].event_date == date(2026, 9, 28) # 결제일 assert ("SALE", "20260928-02-01") not in by and ("SALE", "20260928-03-01") not in by # 마켓 주문·미결제 제외 c = by[("CANCEL", "20260928-01-01")] assert c.amount == -29_000 and c.event_date == date(2026, 9, 29) and c.external_event_id == "20260928-01-01-C" assert ("CANCEL", "20260928-01-02") not in by and ("CANCEL", "20260928-04-01") not in by # 미취소·입금전취소 제외 r = by[("RETURN", "20260928-05-01")] assert r.amount == -30_000 and r.quantity == -1 and r.event_date == date(2026, 9, 30) # 3개 중 1개 반품 for e in events: assert "buyer_name" not in e.raw and "receiver_address" not in e.raw and "bank_account_no" not in e.raw # 금액: payment_amount 없으면 (판매가+옵션)×수량 − 할인 assert item_amount({"product_price": "10000.00", "option_price": "500.00", "quantity": 2, "coupon_discount_price": "1000.00"}) == 20_000 # 60일 단위 분할 + 페이지 넘김(1000건이면 다음 페이지) page1 = [_c24_order(f"x-{i}", []) for i in range(1000)] fake2 = _FakeCafe24({"pay_date": [page1, [paid]]}) got = list(fake2.fetch_orders(ctx, date(2026, 7, 1), date(2026, 9, 30))) pay_calls = [c for c in fake2.calls if c["date_type"] == "pay_date"] assert len(got) == 2002 # 60일 구간 2개 × (1000건 페이지 + 다음 페이지 1건) assert pay_calls[0]["start_date"] == "2026-07-01" and pay_calls[0]["end_date"] == "2026-08-29" assert pay_calls[1]["offset"] == 1000 and all(c["limit"] == 1000 and c["embed"] == "items" for c in pay_calls) assert any(c["start_date"] == "2026-08-30" for c in pay_calls) # 주문 권한 없는 토큰 → 인증 실패(재연결 안내) real = Cafe24Adapter() real.shared_status = lambda ctx: {"connected": True, "scopes": "mall.read_product,mall.write_product"} try: real.authenticate(ctx) except AuthFailed as exc: assert "mall.read_order" in exc.message else: raise AssertionError("주문 권한 없으면 인증 실패여야 합니다") real.shared_status = lambda ctx: {"connected": True, "scopes": "mall.read_product,mall.read_order"} real.authenticate(ctx) 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")