fix: 2026-10-15 코드 검토 F01~F10 — 수집 실패 전파·트랜잭션 경계·저장 실패·공지 버전/확인 조건·테스트 체계
- F01 쿠팡: HTTP 200 비JSON·data 목록 없음은 수집 실패(기간 교체 안 함), 정상 빈 목록과 구분 - F02 회의록 [적용]: 업무 INSERT 와 줄 연결을 한 연결·한 트랜잭션(_insert_task), 확인은 잠그기 전·알림/메일은 커밋 뒤, 줄 바뀜 409 - F03 업무 등록 표: persist 실패 전파, 미저장이면 [적용] 중단, 초안 유지·다시 저장·이탈 경고 - F04 인증정보 변경 시 내부 토큰 삭제 + 네이버·토스 토큰을 발급 인증정보 지문(SHA-256)에 묶음, GS샵 방식 캐시도 키 지문 기준 - F05 쪽 수 상한·커서 반복 = 실패(쿠팡은 구간을 하루까지 나눠 재시도), 네이버·카카오·토스·GS샵 동일 기준 - F06 [중지] 확인과 저장 시작을 같은 잠금(begin_saving), 저장 시작 뒤 중지 불가 - F07/F08 긴급 공지: 내용 version·고친 공지 다시 그리기·확인에 version(409), 확인은 행 잠금 트랜잭션에서 수신자·표시 시각·취소 검증 - F09 쇼핑몰 연결 테스트도 clear 처리·저장 안 한 시험은 상태 유지(광고 테스트와 같은 계약) - F10 DB 테스트 skip·가짜 app.main/time.sleep 파일 범위 fixture, 오래된 기대값 갱신, pytest.ini·requirements-dev·tests/js/package.json·docs/TESTING.md - 결과·후속 과제: docs/CODE_REVIEW_2026-10-15_RESULT.md (마이그레이션·환경변수 변경 없음) Python 440 passed/63 skipped(DB 없음), 503 passed(로컬 PostgreSQL), jsdom 7종·Edge 6종 통과 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -596,6 +596,8 @@ def test_toss_reconcile_hides_personal():
|
||||
|
||||
ctx = AdapterContext(code="toss", credentials=_TossCreds(api_key="a", api_secret="b", access_token="T",
|
||||
access_token_expires_at=str(int(_t.time()) + 99999)))
|
||||
from app.modules.performance.adapters import toss as _toss # 지금 인증정보로 받은 토큰(검토 F04 — 지문이 같아야 재사용)
|
||||
ctx.credentials.set("access_token_for", _toss.credential_fingerprint(ctx.credentials, _toss.TOKEN_KEYS))
|
||||
rows = [_toss_item(1, 11, "2026-09-09T10:00:00", 20000, ship=3000, group=1),
|
||||
_toss_item(2, 21, "2026-09-09T11:00:00", 9900, status="CANCELED_PAYMENT", ship=3000, group=2)]
|
||||
steps = [_toss_step("REFUND", 2, 21, "2026-09-10T11:00:00", -9900), _toss_step("REFUND", 2, None, "2026-09-10T11:00:00", -3000)]
|
||||
@@ -1558,6 +1560,8 @@ def test_naver_reconcile_hides_personal():
|
||||
import time as _t
|
||||
ctx = AdapterContext(code="naver", credentials=Creds(client_id="x", client_secret="y", access_token="T",
|
||||
access_token_expires_at=str(int(_t.time()) + 9999)))
|
||||
# 저장된 토큰은 발급한 인증정보 지문과 같을 때만 다시 쓴다(검토 F04) — 지금 인증정보로 받은 토큰으로
|
||||
ctx.credentials.set("access_token_for", nv.credential_fingerprint(ctx.credentials, nv.TOKEN_KEYS))
|
||||
rows = [_naver_item("A", "A1", "2026-09-09", 20000, ship=3000), _naver_item("B", "B1", "2026-09-09", 9900, status="CANCELED")]
|
||||
orig = (httpx.get, nv.CALL_INTERVAL_SEC)
|
||||
httpx.get = lambda url, params=None, headers=None, timeout=None: httpx.Response(
|
||||
|
||||
@@ -0,0 +1,310 @@
|
||||
"""2026-10-15 코드 검토(docs/CODE_REVIEW_2026-10-15.md) 실적 항목 회귀 테스트 — DB·네트워크 없이(가짜 저장소·가짜 HTTP).
|
||||
|
||||
F01 쿠팡 잘못된 응답(HTTP 200 + JSON 아님·data 없음)은 수집 실패 — 기존 매출 유지(replace_events 안 부름)
|
||||
F04 인증정보가 바뀌면 이전 계정 토큰을 쓰지 않음(저장 때 내부 토큰 삭제 + 토큰-인증정보 지문), 같은 값 재저장은 유지
|
||||
F05 쪽 수 상한·커서 반복이면 부분 수집을 성공으로 내지 않음(쿠팡은 기간을 나눠 다시), 다른 어댑터도 실패로
|
||||
F06 collect() 끝 무렵 받아들인 [중지]는 저장 전에 반영, 저장을 시작했으면 [중지] 불가
|
||||
F09 쇼핑몰 연결 테스트도 clear(비운 칸)를 빈 값으로 시험하고, 저장하지 않은 시험은 연결 상태를 바꾸지 않음
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from datetime import date
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from app.modules.performance.adapters import coupang as cp
|
||||
from app.modules.performance.adapters import gsshop as gs
|
||||
from app.modules.performance.adapters import kakao as kk
|
||||
from app.modules.performance.adapters import naver as nv
|
||||
from app.modules.performance.adapters import toss as ts
|
||||
from app.modules.performance.adapters.base import AdapterContext, ApiError
|
||||
from app.modules.performance.adapters.registry import get_adapter
|
||||
from app.modules.performance.credentials import CredentialService
|
||||
from app.modules.performance.sync import SyncService
|
||||
from app.modules.performance.tests.test_performance import FakeStore, _naver_item, ring
|
||||
|
||||
|
||||
class Creds(dict):
|
||||
def get(self, k, default=""):
|
||||
return dict.get(self, k, default)
|
||||
|
||||
def has(self, k):
|
||||
return bool(dict.get(self, k))
|
||||
|
||||
def set(self, k, v):
|
||||
self[k] = v
|
||||
|
||||
def known_secrets(self):
|
||||
return []
|
||||
|
||||
|
||||
def _cp_ctx():
|
||||
return AdapterContext(code="coupang", credentials=Creds(vendor_id="A00012345", access_key="AK", secret_key="SK"))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def no_wait(monkeypatch):
|
||||
monkeypatch.setattr(cp, "CALL_INTERVAL_SEC", 0)
|
||||
monkeypatch.setattr(cp, "RG_CALL_INTERVAL_SEC", 0)
|
||||
monkeypatch.setattr(cp.time, "sleep", lambda *_a, **_k: None)
|
||||
|
||||
|
||||
def _coupang_store_with_sales():
|
||||
"""기존 쿠팡 매출 한 줄(10/12)이 있는 가짜 저장소 + 쿠팡 인증정보. replace_events 호출을 기록한다."""
|
||||
st = FakeStore()
|
||||
st.events[("coupang", "SALE", "coupang:9")] = {"sales_date": date(2026, 10, 12), "amount": 15000,
|
||||
"event_type": "SALE", "is_sample": False}
|
||||
st.replaced = []
|
||||
orig = st.replace_events
|
||||
|
||||
def replace(code, start, end, events, *, id_prefix=""):
|
||||
st.replaced.append((code, start, end, list(events)))
|
||||
return orig(code, start, end, events, id_prefix=id_prefix)
|
||||
|
||||
st.replace_events = replace
|
||||
creds = CredentialService(st, lambda: ring())
|
||||
creds.save(get_adapter("coupang"), {"vendor_id": "A00012345", "access_key": "AK-1", "secret_key": "SK-1"})
|
||||
return st, creds
|
||||
|
||||
|
||||
# ── F01 ─────────────────────────────────────────────────────
|
||||
@pytest.mark.parametrize("response", [
|
||||
httpx.Response(200, text="<html>maintenance</html>"), # JSON 아님
|
||||
httpx.Response(200, json={"message": "점검 중입니다"}), # 주문 목록(data) 없음
|
||||
httpx.Response(200, json={"code": 200, "data": {"unexpected": True}}), # data 가 목록 아님
|
||||
])
|
||||
def test_f01_bad_200_response_fails_and_keeps_existing_sales(monkeypatch, no_wait, response):
|
||||
st, creds = _coupang_store_with_sales()
|
||||
monkeypatch.setattr(httpx, "get", lambda *a, **k: response)
|
||||
r = SyncService(st, creds).sync_marketplace("coupang", date(2026, 10, 12), date(2026, 10, 12))
|
||||
assert not r["ok"] and r["status"] == "api_error", r
|
||||
assert st.replaced == [] # 기간 교체(삭제)를 아예 하지 않음
|
||||
assert ("coupang", "SALE", "coupang:9") in st.events # 기존 매출 그대로
|
||||
assert st.status["coupang"]["ok"] is False and "저장하지 않았습니다" in r["message"]
|
||||
|
||||
|
||||
def test_f01_empty_list_is_still_a_normal_empty_period(monkeypatch, no_wait):
|
||||
"""정상 빈 목록(data: [])은 주문 0건 — 기간 교체가 정상적으로 일어난다(실패와 구분)."""
|
||||
st, creds = _coupang_store_with_sales()
|
||||
monkeypatch.setattr(httpx, "get", lambda *a, **k: httpx.Response(200, json={"code": 200, "data": [], "nextToken": ""}))
|
||||
r = SyncService(st, creds).sync_marketplace("coupang", date(2026, 10, 12), date(2026, 10, 12))
|
||||
assert r["ok"], r
|
||||
assert len(st.replaced) == 1 and st.replaced[0][3] == []
|
||||
|
||||
|
||||
def test_f01_page_rows_contract():
|
||||
assert cp.CoupangAdapter._page_rows({"code": 200, "data": []}, "발주서") == []
|
||||
assert cp.CoupangAdapter._page_rows({"code": 200, "message": "OK", "data": None}, "발주서") == [] # 성공 표시 + null
|
||||
assert cp.CoupangAdapter._page_rows({"data": [{"a": 1}, "x"]}, "발주서") == [{"a": 1}]
|
||||
for body in ({}, {"data": None}, {"message": "maintenance"}, {"data": "x"}):
|
||||
with pytest.raises(ApiError):
|
||||
cp.CoupangAdapter._page_rows(body, "발주서")
|
||||
|
||||
|
||||
# ── F05 ─────────────────────────────────────────────────────
|
||||
def test_f05_coupang_page_limit_and_repeated_cursor_raise(monkeypatch, no_wait):
|
||||
ad = cp.CoupangAdapter()
|
||||
monkeypatch.setattr(cp, "MAX_PAGES", 2)
|
||||
n = {"i": 0}
|
||||
|
||||
def endless(*a, **k):
|
||||
n["i"] += 1
|
||||
return httpx.Response(200, json={"code": 200, "data": [{"orderId": n["i"]}], "nextToken": f"t{n['i']}"})
|
||||
|
||||
monkeypatch.setattr(httpx, "get", endless)
|
||||
with pytest.raises(cp.TooManyPages):
|
||||
ad._pages(_cp_ctx(), "/x", {})
|
||||
monkeypatch.setattr(httpx, "get", lambda *a, **k: httpx.Response(200, json={"code": 200, "data": [{"a": 1}], "nextToken": "same"}))
|
||||
with pytest.raises(cp.TooManyPages, match="반복"):
|
||||
ad._pages(_cp_ctx(), "/x", {})
|
||||
|
||||
|
||||
def test_f05_coupang_splits_period_until_complete_or_fails(monkeypatch, no_wait):
|
||||
"""2일 조회가 쪽 수 상한을 넘으면 하루씩 나눠 끝까지 받는다. 하루도 넘치면 명확한 실패."""
|
||||
ad = cp.CoupangAdapter()
|
||||
monkeypatch.setattr(cp, "MAX_PAGES", 3)
|
||||
calls = []
|
||||
|
||||
def get(url, headers=None, timeout=None):
|
||||
q = dict(p.split("=", 1) for p in url.split("?", 1)[1].split("&"))
|
||||
calls.append((q["paidDateFrom"], q["paidDateTo"]))
|
||||
if q["paidDateFrom"] != q["paidDateTo"]: # 여러 날 — 끝이 안 보임
|
||||
i = int(q.get("nextToken", "0")) + 1
|
||||
return httpx.Response(200, json={"data": [{"orderId": i}], "nextToken": str(i)})
|
||||
return httpx.Response(200, json={"data": [{"orderId": q["paidDateFrom"]}], "nextToken": ""})
|
||||
|
||||
monkeypatch.setattr(httpx, "get", get)
|
||||
rows = ad._rg_orders(_cp_ctx(), date(2026, 10, 11), date(2026, 10, 12))
|
||||
assert sorted(r["orderId"] for r in rows) == ["20261011", "20261012"] # 부분 목록이 아니라 하루씩 전부
|
||||
assert ("20261011", "20261011") in calls and ("20261012", "20261012") in calls
|
||||
|
||||
monkeypatch.setattr(httpx, "get", lambda url, headers=None, timeout=None: httpx.Response(
|
||||
200, json={"data": [{"orderId": 1}], "nextToken": str(time.perf_counter_ns())}))
|
||||
with pytest.raises(ApiError, match="하루"):
|
||||
ad._rg_orders(_cp_ctx(), date(2026, 10, 12), date(2026, 10, 12))
|
||||
|
||||
|
||||
def test_f05_other_adapters_fail_instead_of_partial(monkeypatch):
|
||||
"""네이버·카카오·토스·GS샵 — 상한 소진·커서 반복은 실패(일부만 받은 목록을 돌려주지 않음)."""
|
||||
ctx = AdapterContext(code="x", credentials=Creds())
|
||||
d = date(2026, 10, 12)
|
||||
|
||||
monkeypatch.setattr(nv, "MAX_PAGES", 2)
|
||||
a = nv.NaverAdapter()
|
||||
a._get = lambda ctx, path, params: {"data": {"contents": [_naver_item(f"O{params['page']}", f"P{params['page']}",
|
||||
"2026-10-12", 1000)],
|
||||
"pagination": {"page": params["page"], "hasNext": True}}}
|
||||
with pytest.raises(ApiError, match="끝까지"):
|
||||
a._day_items(ctx, d)
|
||||
|
||||
k = kk.KakaoAdapter()
|
||||
k._get = lambda ctx, path, params: {"contents": [{"orderId": "1"}], "token": "same"}
|
||||
with pytest.raises(ApiError, match="반복"):
|
||||
k._day_rows(ctx, d)
|
||||
|
||||
t = ts.TossAdapter()
|
||||
t._get = lambda ctx, path, params: {"results": [{"id": 1}], "nextCursor": "c"}
|
||||
with pytest.raises(ApiError, match="반복"):
|
||||
t._window_items(ctx, d, d)
|
||||
t._get = lambda ctx, path, params: {"items": [{"id": 1}], "nextToken": "n"}
|
||||
with pytest.raises(ApiError, match="반복"):
|
||||
t._settlement_items(ctx, d, d)
|
||||
with pytest.raises(ApiError, match="반복"):
|
||||
t._claims(ctx)
|
||||
|
||||
monkeypatch.setattr(gs, "MAX_PAGES", 2)
|
||||
g = gs.GsshopAdapter()
|
||||
g._get = lambda ctx, path, params: {"data": [{"ordNo": params["pageIdx"]}], "hasMorePage": True}
|
||||
with pytest.raises(ApiError, match="끝까지"):
|
||||
g._pages(ctx, gs.SALES_PATH, d, d)
|
||||
|
||||
|
||||
# ── F06 ─────────────────────────────────────────────────────
|
||||
def test_f06_stop_accepted_at_end_of_collect_is_not_saved(monkeypatch, no_wait):
|
||||
from app.modules.performance import jobs
|
||||
|
||||
st, creds = _coupang_store_with_sales()
|
||||
job = jobs.SyncJob(user="t", start=None, end=None)
|
||||
shop = job.set_targets([("coupang", "쿠팡", True)], date(2026, 10, 12), date(2026, 10, 12))["coupang"]
|
||||
ad = get_adapter("coupang")
|
||||
|
||||
def collect(ctx, start, end): # 마지막 API 호출·정리 중에 [중지]가 들어온 상황
|
||||
assert job.stop_shop("coupang") is True
|
||||
return 1, []
|
||||
|
||||
monkeypatch.setattr(ad, "collect", collect)
|
||||
r = SyncService(st, creds).sync_marketplace("coupang", date(2026, 10, 12), date(2026, 10, 12), progress=shop)
|
||||
assert r.get("cancelled") and r["status"] == "cancelled", r
|
||||
assert st.replaced == [] and ("coupang", "SALE", "coupang:9") in st.events # 저장 안 함
|
||||
assert shop.state == "cancelled" and shop.message == "중지됨"
|
||||
|
||||
|
||||
def test_f06_stop_after_saving_started_is_refused():
|
||||
from app.modules.performance import jobs
|
||||
|
||||
job = jobs.SyncJob(user="t", start=None, end=None)
|
||||
shop = job.set_targets([("coupang", "쿠팡", True)], date(2026, 10, 12), date(2026, 10, 12))["coupang"]
|
||||
shop.start()
|
||||
shop.begin_saving()
|
||||
assert shop.state == "saving"
|
||||
assert job.stop_shop("coupang") is False and shop.stop_requested is False # 저장 중이면 중지 불가를 알림
|
||||
|
||||
|
||||
# ── F04 ─────────────────────────────────────────────────────
|
||||
def _toss_svc():
|
||||
st = FakeStore()
|
||||
svc = CredentialService(st, lambda: ring())
|
||||
ad = get_adapter("toss")
|
||||
svc.save(ad, {"api_key": "k1", "api_secret": "s1"})
|
||||
acc = svc.accessor("toss")
|
||||
acc.set("access_token", "OLD_ACCOUNT_TOKEN")
|
||||
acc.set("access_token_expires_at", str(int(time.time()) + 86400))
|
||||
acc.set("access_token_for", ts.credential_fingerprint(acc, ts.TOKEN_KEYS))
|
||||
return st, svc, ad
|
||||
|
||||
|
||||
def test_f04_same_values_keep_token_changed_values_drop_it(monkeypatch):
|
||||
st, svc, ad = _toss_svc()
|
||||
issued = []
|
||||
monkeypatch.setattr(httpx, "post", lambda *a, **k: issued.append(1) or httpx.Response(
|
||||
200, json={"access_token": "NEW_ACCOUNT_TOKEN", "expires_in": 3600}))
|
||||
|
||||
svc.save(ad, {"api_key": "k1", "api_secret": "s1"}) # 같은 값 다시 저장
|
||||
assert ("toss", "access_token") in st.creds
|
||||
ctx = AdapterContext(code="toss", credentials=svc.accessor("toss"))
|
||||
assert ad._token(ctx) == "OLD_ACCOUNT_TOKEN" and issued == [] # 불필요한 재발급 없음
|
||||
|
||||
svc.save(ad, {"api_key": "k2"}) # 계정(키) 변경
|
||||
assert ("toss", "access_token") not in st.creds and ("toss", "access_token_expires_at") not in st.creds
|
||||
ctx = AdapterContext(code="toss", credentials=svc.accessor("toss"))
|
||||
assert ad._token(ctx) == "NEW_ACCOUNT_TOKEN" and issued == [1]
|
||||
|
||||
|
||||
def test_f04_token_bound_to_credentials_even_without_save(monkeypatch):
|
||||
"""연결 테스트(저장 안 한 새 입력값)·예전 토큰(지문 없음)도 이전 계정 토큰을 쓰지 않는다 — 실제 수집과 같은 기준."""
|
||||
st, svc, ad = _toss_svc()
|
||||
monkeypatch.setattr(httpx, "post", lambda *a, **k: httpx.Response(200, json={"access_token": "NEW", "expires_in": 3600}))
|
||||
trial = AdapterContext(code="toss", credentials=svc.accessor("toss", overrides={"api_key": "k2"}, persist=False))
|
||||
assert ad._token(trial) == "NEW"
|
||||
assert svc.accessor("toss").get("access_token") == "OLD_ACCOUNT_TOKEN" # 시험은 저장된 토큰을 건드리지 않음
|
||||
# 지문이 없는 예전 토큰(배포 전에 저장된 것)은 한 번 새로 받는다
|
||||
svc.accessor("toss").set("access_token_for", "")
|
||||
real = AdapterContext(code="toss", credentials=svc.accessor("toss"))
|
||||
assert ad._token(real) == "NEW" and svc.accessor("toss").get("access_token") == "NEW"
|
||||
|
||||
|
||||
def test_f04_fingerprint_hides_values_and_gs_mode_cache_follows_key():
|
||||
fp = ts.credential_fingerprint(Creds(api_key="secret-key-1", api_secret="s"), ts.TOKEN_KEYS)
|
||||
assert len(fp) == 64 and "secret" not in fp
|
||||
a = AdapterContext(code="gsshop", credentials=Creds(vendor_code="1036018", api_key="K1" * 16))
|
||||
b = AdapterContext(code="gsshop", credentials=Creds(vendor_code="1036018", api_key="K2" * 16))
|
||||
assert gs.GsshopAdapter._mode_key(a) != gs.GsshopAdapter._mode_key(b)
|
||||
|
||||
|
||||
# ── F09 ─────────────────────────────────────────────────────
|
||||
def test_f09_shop_test_uses_empty_value_for_cleared_and_keeps_status(monkeypatch):
|
||||
st = FakeStore()
|
||||
svc = CredentialService(st, lambda: ring())
|
||||
ad = get_adapter("naver")
|
||||
svc.save(ad, {"client_id": "cid", "client_secret": "$2a$04$abcdefghijklmnopqrstuu", "account_id": "OLD-SELLER"})
|
||||
st.status["naver"] = {"status": "ok", "ok": True, "error": ""}
|
||||
seen = []
|
||||
monkeypatch.setattr(ad, "test_connection", lambda ctx: seen.append(ctx.credentials.get("account_id")) or "연결됨")
|
||||
r = SyncService(st, svc).test_connection("naver", cleared={"account_id"})
|
||||
assert seen == [""] and r["ok"] and r["unsaved"] is True # 비운 칸은 빈 값, 저장 안 한 시험
|
||||
assert st.status["naver"] == {"status": "ok", "ok": True, "error": ""} # 연결 상태 그대로
|
||||
assert svc.accessor("naver").get("account_id") == "OLD-SELLER" # 저장값도 그대로
|
||||
r = SyncService(st, svc).test_connection("naver") # 저장값 그대로 시험은 상태 기록
|
||||
assert seen[-1] == "OLD-SELLER" and r["unsaved"] is False and st.status["naver"].get("test")
|
||||
|
||||
|
||||
def test_f09_router_passes_clear_like_ad_test(monkeypatch):
|
||||
import importlib
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.modules.performance import common
|
||||
|
||||
perf_router = importlib.import_module("app.modules.performance.router")
|
||||
calls = []
|
||||
|
||||
class Sync:
|
||||
def test_connection(self, code, *, values=None, user="", cleared=None):
|
||||
calls.append((code, values, cleared))
|
||||
return {"ok": True, "status": "ok", "label": "정상 연결", "message": "연결됨", "unsaved": bool(values or cleared)}
|
||||
|
||||
st = FakeStore()
|
||||
st.list_marketplaces = lambda: [{"code": "naver", "name": "네이버"}]
|
||||
monkeypatch.setattr(common, "require_store", lambda request, admin=False: (st, {"email": "king@x"}))
|
||||
monkeypatch.setattr(common, "services", lambda request, store: (None, Sync()))
|
||||
app = FastAPI()
|
||||
app.include_router(perf_router.router)
|
||||
c = TestClient(app)
|
||||
r = c.post("/performance/api/marketplaces/naver/test",
|
||||
json={"values": {"client_id": "new"}, "clear": ["account_id", "client_id", "nope"]})
|
||||
assert r.status_code == 200 and r.json()["unsaved"] is True
|
||||
assert calls[-1] == ("naver", {"client_id": "new"}, {"account_id"}) # 새 값이 있는 칸·모르는 칸은 빼고
|
||||
Reference in New Issue
Block a user