614332a1e6
카페24 화면과 몇몇 날짜만 안 맞는데 어느 날·어느 쪽(결제/환불)인지,
저장값이 예전 규칙이라서인지 규칙 자체가 틀린 건지 구분할 방법이 없었다.
- GET /performance/api/marketplaces/{code}/daily-check?from=&to=&live=1 (관리자, 62일)
db = 저장된 날짜별 결제합계·결제 건수·환불합계(c24: 사건 전체 = 카페24 화면 범위)
live = 지금 API·현재 규칙으로 다시 계산(adapter.collect, 저장 안 함)
- 설정 → 카페24 매출 대조 카드에 "일별 한 번에 비교": 카페24 표 붙여넣기 →
날짜별 차이(저장값/API), 판정(일치 / 다시 가져오면 해결 / 규칙 차이(결제·환불)),
[다시 가져오기] 버튼, 날짜 클릭 시 그날 상세 대조
- 테스트 추가
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
705 lines
40 KiB
Python
705 lines
40 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 replace_events(self, code, start, end, events, *, id_prefix=""):
|
||
def mine(k, v):
|
||
return k[0] == code or (id_prefix and k[2].startswith(id_prefix))
|
||
self.events = {k: v for k, v in self.events.items()
|
||
if not (mine(k, v) and not v["is_sample"] and start <= v["sales_date"] <= end)}
|
||
return self.upsert_events(code, events)
|
||
|
||
def daily_breakdown(self, code, start, end, *, id_prefix=""):
|
||
days = {}
|
||
for (c, _, eid), v in self.events.items():
|
||
if v["is_sample"] or not (start <= v["sales_date"] <= end):
|
||
continue
|
||
if not (c == code or (id_prefix and eid.startswith(id_prefix))):
|
||
continue
|
||
r = days.setdefault(v["sales_date"].isoformat(), {"date": v["sales_date"].isoformat(), "paid": 0,
|
||
"orders": 0, "refund": 0, "synced_at": None})
|
||
if v["event_type"] == "SALE":
|
||
r["paid"] += v["amount"]
|
||
r["orders"] += 1
|
||
else:
|
||
r["refund"] -= v["amount"]
|
||
return sorted(days.values(), key=lambda r: r["date"])
|
||
|
||
def upsert_events(self, code, events, *, is_sample=False):
|
||
n = 0
|
||
for e in events:
|
||
target = e.get("marketplace_code") or code
|
||
self.events[(target, 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 응답) — 카페24 "일별 매출내역" 기준
|
||
# ════════════════════════════════════════════════════════════
|
||
def _c24_order(oid, market="self", paid="T", price=50_000, ship=3_000, coupon=5_000, member=1_000, items=2, **kw):
|
||
amt = {"order_price_amount": f"{price}.00", "shipping_fee": f"{ship}.00", "coupon_discount_price": f"{coupon}.00",
|
||
"membership_discount_amount": f"{member}.00", "points_spent_amount": "0.00", "payment_amount": "0.00"}
|
||
return {"order_id": oid, "market_id": market, "paid": paid, "order_date": "2026-09-28T10:00:00+09:00",
|
||
"payment_date": "2026-09-29T11:21:35+09:00", "buyer_name": "홍길동", "receiver_address": "서울시",
|
||
"bank_account_no": "1234567890", "initial_order_amount": amt,
|
||
"actual_order_amount": {**amt, "order_price_amount": "0.00"}, # 취소 후 금액은 쓰지 않는다
|
||
"items": [{"order_item_code": f"{oid}-{i:02d}", "product_name": f"상품{i}", "quantity": 1}
|
||
for i in range(1, items + 1)], **kw}
|
||
|
||
|
||
def _c24_refund(code, oid, amount, status="T", order_date="2026-09-20T09:00:00+09:00"):
|
||
return {"refund_code": code, "order_id": oid, "order_date": order_date, "refund_date": "2026-09-29T17:31:50+09:00",
|
||
"actual_refund_amount": f"{amount}.00", "used_points": "0.00", "used_credits": "0.00", "quantity": 1,
|
||
"order_item_code": [f"{oid}-01"], "status": status, "refund_bank_account_no": "1234567890"}
|
||
|
||
|
||
class _FakeCafe24(__import__("app.modules.performance.adapters.cafe24", fromlist=["Cafe24Adapter"]).Cafe24Adapter):
|
||
def __init__(self, orders_pages, refunds_pages=(), lookup=None, claims=None):
|
||
self.orders_pages = orders_pages # 결제일 조회 페이지들
|
||
self.claims = claims or {} # date_type(취소/반품/교환 완료일) → 주문 목록
|
||
self.refunds_pages = list(refunds_pages)
|
||
self.lookup = lookup or {} # order_id → market_id (환불 원 주문 조회)
|
||
self.calls = []
|
||
|
||
def authenticate(self, ctx):
|
||
return None
|
||
|
||
def _get(self, ctx, path, params):
|
||
self.calls.append((path, params))
|
||
idx = params.get("offset", 0) // max(1, params.get("limit", 1))
|
||
if path == "/admin/refunds":
|
||
return {"refunds": self.refunds_pages[idx] if idx < len(self.refunds_pages) else []}
|
||
if params.get("date_type") == "order_date": # 원 주문 market_id 조회
|
||
ids = params["order_id"].split(",")
|
||
return {"orders": [{"order_id": i, "market_id": self.lookup.get(i, "self")} for i in ids]}
|
||
if params.get("date_type", "").endswith("_complete_date") or params.get("date_type") == "cancel_date":
|
||
return {"orders": self.claims.get(params["date_type"], []) if idx == 0 else []}
|
||
return {"orders": self.orders_pages[idx] if idx < len(self.orders_pages) else []}
|
||
|
||
|
||
def test_cafe24_normalize_matches_daily_report():
|
||
from app.modules.performance.adapters.base import AdapterContext
|
||
from app.modules.performance.adapters.cafe24 import order_total, target_code
|
||
|
||
ctx = AdapterContext(code="cafe24", credentials=None)
|
||
fake = _FakeCafe24(
|
||
[[_c24_order("A", order_from_mobile="T", payment_method_name=["신용카드"]), _c24_order("B", market="shopn"),
|
||
_c24_order("C", paid="F"), _c24_order("D", market="auction", payment_method_name=["신용카드"]),
|
||
_c24_order("E", market="NCHECKOUT", payment_method_name=["네이버페이"]),
|
||
_c24_order("F", market="KAKAOPAY", payment_method_name=["카카오페이", "적립금"]),
|
||
_c24_order("G", market="mobile", order_from_mobile="T", payment_method_name=["무통장입금"])]],
|
||
[[_c24_refund("C20260929-01", "A", 12_610), _c24_refund("R20260929-02", "X", 20_000),
|
||
_c24_refund("C20260929-03", "M", 9_000), _c24_refund("C20260929-04", "A", 5_000, status="F")]],
|
||
lookup={"M": "shopn"},
|
||
)
|
||
fetched, events = fake.collect(ctx, date(2026, 9, 29), date(2026, 9, 29))
|
||
by = {(e.event_type, e.external_event_id): e for e in events}
|
||
# 결제합계 = 상품구매금액 + 배송비 − 할인 − 쿠폰 (결제 당시 금액), 사건 ID 는 c24: 접두어
|
||
sale = by[("SALE", "c24:A-PAY")]
|
||
assert sale.amount == 50_000 + 3_000 - 1_000 - 5_000 == 47_000 and sale.marketplace_code == "cafe24"
|
||
assert sale.event_date == date(2026, 9, 29) and sale.quantity == 2 and sale.product_name == "상품1 외 1건"
|
||
# 마켓 연동 주문은 해당 쇼핑몰 열로, 연결표에 없는 마켓(옥션)은 카페24 열, 미결제는 제외
|
||
assert by[("SALE", "c24:B-PAY")].marketplace_code == "naver"
|
||
assert by[("SALE", "c24:D-PAY")].marketplace_code == "cafe24"
|
||
# 네이버페이·톡체크아웃·모바일웹은 카페24 자체몰 주문(실데이터 확인) — 네이버/카카오 열로 가면 안 된다
|
||
for oid in ("E", "F", "G"):
|
||
assert by[("SALE", f"c24:{oid}-PAY")].marketplace_code == "cafe24", oid
|
||
assert ("SALE", "c24:C-PAY") not in by
|
||
# 환불: 환불완료일, 실제 환불액, R→반품 / 그 밖→취소, 원 주문의 마켓 열로, 미완료 환불 제외
|
||
assert by[("CANCEL", "c24:C20260929-01")].amount == -12_610
|
||
assert by[("CANCEL", "c24:C20260929-01")].marketplace_code == "cafe24"
|
||
assert by[("RETURN", "c24:R20260929-02")].amount == -20_000
|
||
assert by[("CANCEL", "c24:C20260929-03")].marketplace_code == "naver"
|
||
assert ("CANCEL", "c24:C20260929-04") not in by
|
||
assert by[("CANCEL", "c24:C20260929-01")].event_date == date(2026, 9, 29)
|
||
for e in events:
|
||
assert "buyer_name" not in str(e.raw) and "1234567890" not in str(e.raw) # 개인정보 미저장
|
||
assert order_total({"initial_order_amount": {"order_price_amount": "1578300.00", "shipping_fee": "45500.00",
|
||
"coupon_discount_price": "57000.00"}}) == 1_566_800 # 9/29 화면값
|
||
assert target_code("self") == "cafe24" and target_code("SK11ST") == "elevenst"
|
||
assert target_code("unknown", "coupang") == "coupang" and target_code("unknown") == "cafe24"
|
||
assert target_code("NCHECKOUT", "NCHECKOUT") == "cafe24" and target_code("KAKAOPAY") == "cafe24"
|
||
assert target_code("naver") == "cafe24" and target_code("kakao") == "cafe24" # 결제수단과 헷갈리는 일반 이름 X
|
||
# 대조: 카페24 열(자체몰 채널+모르는 채널)/다른 쇼핑몰 열 + 주문 채널별
|
||
import app.timezone as _tz
|
||
_orig_today, _tz.today_kst = _tz.today_kst, (lambda: date(2026, 9, 29))
|
||
try:
|
||
rec = fake.reconcile(ctx, date(2026, 9, 29))
|
||
finally:
|
||
_tz.today_kst = _orig_today
|
||
assert rec["orders"]["self"]["orders"] == 5 and rec["orders"]["self"]["total"] == 5 * 47_000 # A,D,E,F,G
|
||
assert rec["orders"]["market"]["orders"] == 1 and rec["unpaid_orders"] == 1 # B(스마트스토어)
|
||
assert rec["refunds"]["self"]["actual_refund_amount"] == 32_610 and rec["refunds"]["market"]["count"] == 1
|
||
ch = {b["market_id"]: b for b in rec["by_channel"]}
|
||
assert ch["shopn"]["kind"] == "market" and ch["shopn"]["target"] == "naver" and ch["shopn"]["refund_amount"] == 9_000
|
||
assert ch["auction"]["kind"] == "unknown" and ch["auction"]["target"] == "cafe24"
|
||
assert ch["NCHECKOUT"]["kind"] == "self" and ch["NCHECKOUT"]["label"] == "네이버페이"
|
||
assert ch["KAKAOPAY"]["label"] == "톡체크아웃" and ch["mobile"]["label"] == "모바일웹"
|
||
# 환불 기준 비교: 완료일(완료만) vs 접수일(전체 상태) — 가짜 API 는 두 기준에 같은 목록을 돌려준다
|
||
rb = rec["refund_basis"]
|
||
assert rb["completed"]["count"] == 3 and rb["completed"]["actual_refund_amount"] == 12_610 + 20_000 + 9_000
|
||
assert rb["accepted_all"]["count"] == 4 and rb["accepted_all"]["with_points"] == 12_610 + 20_000 + 9_000 + 5_000
|
||
assert {s["status"]: s["count"] for s in rb["accepted_by_status"]} == {"T": 3, "F": 1}
|
||
assert {c["key"] for c in rec["refund_candidates"]} >= {"completed", "completed_pts", "claim_pay"}
|
||
# 결제일 기준: 그날 결제된 카페24 열 주문(A,D,E,F,G)의 환불만 — X(결제 없음)·M(스마트스토어)·미완료 제외
|
||
bp = rec["refund_basis"]["by_pay_date"]
|
||
assert bp["count"] == 1 and bp["actual_refund_amount"] == 12_610
|
||
assert bp["amount_diff"] == 5 * 50_000 # 결제 당시 − 현재(가짜 현재 상품금액 0)
|
||
red = {x["order_id"]: x for x in rec["reduced_orders"]}
|
||
assert set(red) == {"A", "D", "E", "F", "G"} and red["A"]["refunded"] == 12_610 and red["D"]["refunded"] == 0
|
||
assert rec["reduced_orders"][-1]["order_id"] == "A" # 환불 기록으로 설명 안 되는 금액이 큰 순
|
||
assert {r["refund_code"] for r in rec["refund_list"]} == {"C20260929-01", "R20260929-02", "C20260929-03", "C20260929-04"}
|
||
assert "1234567890" not in str(rec["refund_list"]) # 환불 계좌 미노출
|
||
# 클레임 완료 품목: 환불 API 에 없는 취소(네이버페이 등)를 찾는다. 입금전취소·미완료는 합계 제외
|
||
item = lambda code, st, pay, price=10_000, qty=1: {"order_item_code": code, "order_status": st, "quantity": qty,
|
||
"product_price": f"{price}.00", "option_price": "0.00",
|
||
"payment_amount": f"{pay}.00", "product_name": "상품"}
|
||
fake4 = _FakeCafe24([[]], [[_c24_refund("C1", "A", 9_000)]], claims={
|
||
"cancel_complete_date": [
|
||
{**_c24_order("A"), "items": [item("A-01", "C40", 9_000)]},
|
||
{**_c24_order("N"), "market_id": "NCHECKOUT", "items": [item("N-01", "C40", 19_800, 20_000), item("N-02", "C40", 5_000, 5_000)]},
|
||
{**_c24_order("U"), "items": [item("U-01", "C48", 7_000)]},
|
||
{**_c24_order("P"), "items": [item("P-01", "C34", 3_000), item("P-02", "N40", 4_000)]}],
|
||
"return_complete_date": [{**_c24_order("N"), "items": [item("N-01", "C40", 19_800, 20_000)]},
|
||
{**_c24_order("R"), "items": [item("R-01", "R40", 12_000, 6_000, 2)]}],
|
||
})
|
||
rec4 = fake4.reconcile(ctx, date(2026, 9, 29))
|
||
cl = {c["item_code"]: c for c in rec4["claims"]["items"]}
|
||
assert set(cl) == {"A-01", "N-01", "N-02", "P-01", "R-01"} # 입금전취소(U)·정상 품목 제외, 중복 제거
|
||
assert cl["A-01"]["has_refund"] and not cl["N-01"]["has_refund"] and not cl["P-01"]["done"]
|
||
assert cl["R-01"]["product_amount"] == 12_000
|
||
assert rec4["claims"]["full_cancel_shipping"] == 3_000 * 2 # A, N 전체취소(배송비 3,000씩)
|
||
cand = {c["key"]: c["amount"] for c in rec4["refund_candidates"]}
|
||
assert cand["claim_pay"] == 9_000 + 19_800 + 5_000 + 12_000
|
||
assert cand["completed_plus_noref"] == 9_000 + 19_800 + 5_000 + 12_000
|
||
# 기기: PC 채널(self)이어도 휴대폰 주문(order_from_mobile=T)은 모바일
|
||
assert ch["self"]["mobile_orders"] == 1 and ch["self"]["pc_orders"] == 0 and ch["self"]["mobile_total"] == 47_000
|
||
assert ch["NCHECKOUT"]["pc_orders"] == 1 and ch["mobile"]["mobile_orders"] == 1
|
||
# self 는 PC 전용이 아니다 — 주문경로(PC쇼핑몰/모바일웹)별로 한 줄씩(실데이터 확인)
|
||
fake3 = _FakeCafe24([[_c24_order("P1", order_place_name="PC쇼핑몰"), _c24_order("P2", order_place_name="PC쇼핑몰"),
|
||
_c24_order("M1", order_place_name="모바일웹", order_from_mobile="T")]])
|
||
rows3 = {(b["market_id"], b["place"]): b for b in fake3.reconcile(ctx, date(2026, 9, 29))["by_channel"]}
|
||
assert rows3[("self", "PC쇼핑몰")]["orders"] == 2 and rows3[("self", "모바일웹")]["mobile_orders"] == 1
|
||
assert rows3[("self", "PC쇼핑몰")]["label"] == "자체몰"
|
||
# 결제수단별(카페24 열만 — 외부 마켓 B 제외)
|
||
pay = {p["method"]: p for p in rec["by_payment"]}
|
||
assert pay["신용카드"]["orders"] == 2 and pay["신용카드"]["total"] == 94_000
|
||
assert pay["카카오페이 + 적립금"]["orders"] == 1 and "네이버페이" in pay and "무통장입금" in pay
|
||
assert sum(p["orders"] for p in rec["by_payment"]) == 5
|
||
# 60일 단위 분할 + 페이지 넘김(1000건이면 다음 페이지)
|
||
page1 = [_c24_order(f"x-{i}") for i in range(1000)]
|
||
fake2 = _FakeCafe24([page1, [_c24_order("y")]])
|
||
got = list(fake2.paid_orders(ctx, date(2026, 7, 1), date(2026, 9, 30)))
|
||
calls = [p for path, p in fake2.calls if path == "/admin/orders"]
|
||
assert len(got) == 2002 # 60일 구간 2개 × (1000건 페이지 + 다음 페이지 1건)
|
||
assert calls[0]["start_date"] == "2026-07-01" and calls[0]["end_date"] == "2026-08-29"
|
||
assert calls[1]["offset"] == 1000 and all(c["limit"] == 1000 and c["date_type"] == "pay_date" for c in calls)
|
||
|
||
|
||
def test_cafe24_refund_total_includes_points_and_naverpay_cancels():
|
||
"""카페24 일별 매출 환불합계 = 환불 목록(실제 + 적립금·예치금) + 환불 목록에 없는 취소·반품(네이버페이 등).
|
||
실데이터: 9/26 = 178,220 + 1,080 + 네이버페이 취소 96,500 = 275,800, 9/27 = 145,000 + 네이버페이 55,800."""
|
||
import app.timezone as _tz
|
||
from app.modules.performance.adapters.base import AdapterContext
|
||
|
||
ctx = AdapterContext(code="cafe24", credentials=None)
|
||
item = lambda code, st, price, qty=1, day="2026-09-26 15:00:00", **kw: {
|
||
"order_item_code": code, "order_status": st, "quantity": qty, "product_price": f"{price}.00",
|
||
"option_price": "0.00", "product_name": "상품", "cancel_date": day, **kw}
|
||
refund = {**_c24_refund("C20260926-01", "O1", 63_720), "used_points": "1080.00",
|
||
"refund_date": "2026-09-26T20:25:08+09:00"}
|
||
fake = _FakeCafe24([[]], [[refund]], claims={
|
||
"cancel_date": [
|
||
{**_c24_order("O1"), "items": [item("O1-01", "C40", 64_800)]}, # 환불 목록 있음 → 제외
|
||
{**_c24_order("NP1", market="NCHECKOUT"), "items": [item("NP1-01", "C40", 55_800),
|
||
item("NP1-02", "N40", 9_000)]}, # 정상 품목 제외
|
||
{**_c24_order("NP2", market="NCHECKOUT"), "items": [item("NP2-01", "C40", 20_000, 2,
|
||
coupon_discount_price="1000.00")]},
|
||
{**_c24_order("NP3", market="NCHECKOUT"), "items": [item("NP3-01", "C40", 5_000, day="2026-09-27 01:00:00")]},
|
||
{**_c24_order("NP4", market="NCHECKOUT"), "items": [item("NP4-01", "C00", 5_000)]}, # 취소신청만 → 제외
|
||
],
|
||
"return_complete_date": [{**_c24_order("NP1", market="NCHECKOUT"), "items": [item("NP1-01", "C40", 55_800)]}],
|
||
})
|
||
orig, _tz.today_kst = _tz.today_kst, (lambda: date(2026, 9, 29))
|
||
try:
|
||
_, events = fake.collect(ctx, date(2026, 9, 26), date(2026, 9, 26))
|
||
rec = fake.reconcile(ctx, date(2026, 9, 26))
|
||
finally:
|
||
_tz.today_kst = orig
|
||
by = {e.external_event_id: e for e in events if e.event_type != "SALE"}
|
||
assert by["c24:C20260926-01"].amount == -(63_720 + 1_080) # 적립금 환불 포함
|
||
assert by["c24:NP1-01-CL"].amount == -55_800 and by["c24:NP1-01-CL"].event_type == "CANCEL"
|
||
assert by["c24:NP1-01-CL"].event_date == date(2026, 9, 26) and by["c24:NP1-01-CL"].marketplace_code == "cafe24"
|
||
assert by["c24:NP2-01-CL"].amount == -(40_000 - 1_000) # 판매가×수량 − 품목 쿠폰
|
||
assert set(by) == {"c24:C20260926-01", "c24:NP1-01-CL", "c24:NP2-01-CL"} # 다른 날·신청·환불 기록 있는 주문 제외
|
||
rs = rec["refunds"]["self"]
|
||
assert rs["no_record_count"] == 2 and rs["no_record"] == 55_800 + 39_000
|
||
assert rs["total"] == 63_720 + 1_080 + 55_800 + 39_000
|
||
cand = {c["key"]: c["amount"] for c in rec["refund_candidates"]}
|
||
assert cand["applied"] == rs["total"]
|
||
assert {c["item_code"] for c in rec["no_record_claims"]} == {"NP1-01", "NP2-01"}
|
||
|
||
|
||
def test_cafe24_scope_and_replace_range():
|
||
import app.modules.performance.sync as syncmod
|
||
from app.modules.performance.adapters.base import AdapterContext
|
||
from app.modules.performance.adapters.cafe24 import Cafe24Adapter
|
||
|
||
ctx = AdapterContext(code="cafe24", credentials=None)
|
||
real = Cafe24Adapter()
|
||
real.shared_status = lambda c: {"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 c: {"connected": True, "scopes": "mall.read_product,mall.read_order"}
|
||
real.authenticate(ctx)
|
||
|
||
def ev(eid, day, **kw):
|
||
return {"event_type": "SALE", "external_event_id": eid, "external_order_id": "o",
|
||
"event_date": day, "sales_date": day, "amount": 1, **kw}
|
||
|
||
# 기간 교체: 기간 안 카페24 행(예전 품목 단위)·카페24 경유 네이버 행은 지우고,
|
||
# 네이버 직접 연동분·테스트 데이터·기간 밖은 남긴다
|
||
st = FakeStore()
|
||
d, out = date(2026, 9, 29), date(2026, 9, 1)
|
||
st.upsert_events("cafe24", [ev("old-item-S", d), ev("outside", out)])
|
||
st.upsert_events("naver", [ev("c24:OLD-PAY", d), ev("direct-naver-1", d)])
|
||
st.upsert_events("cafe24", [ev("sample", d)], is_sample=True)
|
||
fake = _FakeCafe24([[_c24_order("A"), _c24_order("B", market="shopn")]])
|
||
orig = syncmod.get_adapter
|
||
syncmod.get_adapter = lambda c: fake
|
||
try:
|
||
r = SyncService(st, CredentialService(st, lambda: ring())).sync_marketplace("cafe24", d, d)
|
||
finally:
|
||
syncmod.get_adapter = orig
|
||
got = {(k[0], k[2]) for k in st.events}
|
||
assert r["ok"], r
|
||
assert got == {("cafe24", "c24:A-PAY"), ("naver", "c24:B-PAY"), ("cafe24", "outside"),
|
||
("naver", "direct-naver-1"), ("cafe24", "sample")}, got
|
||
|
||
|
||
def test_daily_check_db_vs_live():
|
||
"""일별 비교: 저장값(카페24 경유 다른 마켓 열 포함) + 지금 API 값(저장 안 함)."""
|
||
import app.modules.performance.sync as syncmod
|
||
|
||
st = FakeStore()
|
||
d = date(2026, 9, 29)
|
||
ev = lambda eid, t, amt, **kw: {"event_type": t, "external_event_id": eid, "external_order_id": "o",
|
||
"event_date": d, "sales_date": d, "amount": amt, **kw}
|
||
st.upsert_events("cafe24", [ev("c24:A-PAY", "SALE", 40_000), ev("c24:R1", "CANCEL", -5_000)])
|
||
st.upsert_events("naver", [ev("c24:B-PAY", "SALE", 10_000), ev("direct-1", "SALE", 99_999)])
|
||
fake = _FakeCafe24([[_c24_order("A"), _c24_order("B", market="shopn"), _c24_order("C")]],
|
||
[[_c24_refund("C20260929-01", "A", 7_000)]])
|
||
orig = syncmod.get_adapter
|
||
syncmod.get_adapter = lambda c: fake
|
||
try:
|
||
svc = SyncService(st, CredentialService(st, lambda: ring()))
|
||
only_db = svc.daily_check("cafe24", d, d)
|
||
both = svc.daily_check("cafe24", d, d, live=True)
|
||
finally:
|
||
syncmod.get_adapter = orig
|
||
assert "live" not in only_db
|
||
assert both["db"] == [{"date": "2026-09-29", "paid": 50_000, "orders": 2, "refund": 5_000, "synced_at": None}]
|
||
assert both["live"] == [{"date": "2026-09-29", "paid": 3 * 47_000, "orders": 3, "refund": 7_000}]
|
||
assert len(st.events) == 4 # 저장값은 바뀌지 않음
|
||
|
||
|
||
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")
|