8043110197
- python -m app.modules.cafe24.sync_variant_flags --shops 3,4 [--apply] - 옵션 상품 전체의 기본몰(1) 품목 진열·판매를 지정 쇼핑몰에 같은 값으로(다른 값만 PUT) - 기본 미리보기, BEFORE 줄로 원래 값 출력(되돌리기용), 감사 actor SYNC_SHOPS Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
755 lines
38 KiB
Python
755 lines
38 KiB
Python
"""카페24 모듈 — 실제 PostgreSQL 잠금·lease·JSONB 병합 + FastAPI 라우트 통합 테스트.
|
|
|
|
운영 DB 와 분리된 **로컬 테스트용 PostgreSQL** 에서만 돈다. 카페24 API·FTP 는 가짜
|
|
(app/modules/cafe24/tests/fakes.py)이며 실제 쇼핑몰·디자인 파일은 건드리지 않는다.
|
|
|
|
# 1) 로컬 테스트 DB 에 스키마 적용(최초 1회)
|
|
# psql -v app_password=... -f scripts/sql/cafe24_db_init.sql
|
|
# psql -d cafe24_db -f scripts/sql/cafe24_db_002_… 003 … 004 … 005_write_safety.sql
|
|
# 2) 실행
|
|
CAFE24_TEST_DB_URL=postgresql://postgres@localhost:55432/cafe24_db python tests/test_cafe24_db.py
|
|
|
|
CAFE24_TEST_DB_URL 이 없거나 localhost/127.0.0.1 이 아니면 전부 건너뛴다(운영 DB 보호).
|
|
테스트마다 새 상품번호를 쓰고 기존 행을 지우지 않는다.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import logging
|
|
import os
|
|
import random
|
|
import sys
|
|
import threading
|
|
import types
|
|
from datetime import timedelta
|
|
from urllib.parse import parse_qs, urlparse
|
|
|
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
|
|
|
DSN = os.getenv("CAFE24_TEST_DB_URL", "")
|
|
_host = urlparse(DSN).hostname if DSN else None
|
|
ENABLED = bool(DSN) and _host in ("localhost", "127.0.0.1")
|
|
|
|
logging.getLogger("cafe24").setLevel(logging.CRITICAL)
|
|
|
|
if ENABLED:
|
|
from fastapi.responses import HTMLResponse
|
|
|
|
USERS = {
|
|
"king@test.local": {"email": "king@test.local", "role": "admin", "modules": {"cafe24": True}},
|
|
"amy@test.local": {"email": "amy@test.local", "role": "user", "modules": {"cafe24": True}},
|
|
"nope@test.local": {"email": "nope@test.local", "role": "user", "modules": {}},
|
|
}
|
|
fake_main = types.ModuleType("app.main")
|
|
fake_main.get_current_user_record = lambda request: USERS.get(request.headers.get("x-test-user", ""))
|
|
fake_main.build_erp_nav = lambda user, active="": []
|
|
|
|
def _render(request, name, ctx, status_code=200):
|
|
keep = {k: ctx.get(k) for k in ("sync_state", "fingerprint", "html_pc", "editor_error", "open_attempts",
|
|
"revisions", "reason", "flash", "flash_error", "rows")}
|
|
return HTMLResponse(name + "\n" + json.dumps(keep, ensure_ascii=False, default=str), status_code=status_code)
|
|
|
|
fake_main.render_template = _render
|
|
sys.modules["app.main"] = fake_main
|
|
os.environ.update({
|
|
"CAFE24_MALL_ID": "testmall", "CAFE24_CLIENT_ID": "cid", "CAFE24_CLIENT_SECRET": "cs",
|
|
"CAFE24_REDIRECT_URI": "http://localhost/cb", "CAFE24_TOKEN_SECRET": "unit-test-secret",
|
|
"CAFE24_WRITE_LOCK_WAIT_SEC": "3",
|
|
})
|
|
os.environ.pop("CAFE24_READ_LAG_GRACE_MIN", None)
|
|
|
|
from fastapi import FastAPI # noqa: E402
|
|
from fastapi.testclient import TestClient # noqa: E402
|
|
|
|
from app.integrations.cafe24 import products # noqa: E402
|
|
from app.modules.cafe24 import ( # noqa: E402
|
|
routes_design_files, routes_product_info, routes_products, routes_schedules, store, worker, writes,
|
|
)
|
|
from app.modules.cafe24.db import Cafe24Store # noqa: E402
|
|
from app.modules.cafe24.router import router as cafe24_router # noqa: E402
|
|
from app.modules.cafe24.tests import fakes # noqa: E402
|
|
from app.timezone import now_kst # noqa: E402
|
|
|
|
# 카페24 쓰기 직후 읽기 지연 재시도의 실제 sleep 을 건너뛴다 — time 은 공유 모듈이라 import 때 바꾸지 않고
|
|
# 이 파일 테스트 동안만(pytest fixture / 직접 실행은 _run_all) 바꾼다(검토 F10).
|
|
_NO_SLEEP = lambda *_a, **_k: None # noqa: E731
|
|
ST = Cafe24Store(DSN)
|
|
ST2 = Cafe24Store(DSN) # 두 번째 "프로세스"(별도 연결 풀)
|
|
|
|
class _Multi:
|
|
"""상품번호별 FakeCafe24 로 요청을 나눠 준다(모르는 상품은 빈 응답)."""
|
|
|
|
def __init__(self):
|
|
self.by_no: dict[int, fakes.FakeCafe24] = {}
|
|
|
|
def _pick(self, path):
|
|
parts = path.split("/")
|
|
try:
|
|
return self.by_no.get(int(parts[3]))
|
|
except (IndexError, ValueError):
|
|
return None
|
|
|
|
def __getattr__(self, method):
|
|
if method not in ("get", "put", "post", "delete"):
|
|
raise AttributeError(method)
|
|
|
|
def call(path, **kw):
|
|
target = self._pick(path)
|
|
return getattr(target, method)(path, **kw) if target else {}
|
|
|
|
return call
|
|
|
|
MULTI = _Multi()
|
|
for _mod in (routes_products, routes_product_info, routes_schedules):
|
|
_mod.build_cafe24_api = lambda st, **kw: fakes.FakeApi(MULTI)
|
|
|
|
APP = FastAPI()
|
|
APP.include_router(cafe24_router)
|
|
APP.state.cafe24_store = ST
|
|
CLIENT = TestClient(APP)
|
|
|
|
# ── pytest 실행 범위(2026-10-15 검토 F10) ─────────────────────────────────
|
|
# DB 가 없으면 이 파일 전체를 명시적으로 skip(예전엔 import 준비만 건너뛰어 ST·ADMIN 등이 없어 NameError).
|
|
# 가짜 app.main 은 이 파일 테스트 동안만 sys.modules 에 둔다 — pytest 는 모든 파일을 먼저 import 하므로 import 때 바꿔 끼우면
|
|
# 다른 DB 테스트 파일(test_cafe24_db ↔ test_project_module)의 가짜가 서로 덮어써 사용자 조회가 틀렸다.
|
|
# 직접 실행(python tests/…)은 위 import 때 설치한 가짜를 그대로 쓴다.
|
|
try:
|
|
import pytest
|
|
except ImportError: # 직접 실행은 pytest 없이도 돈다
|
|
pytest = None
|
|
|
|
if pytest is not None:
|
|
pytestmark = pytest.mark.skipif(not ENABLED, reason="CAFE24_TEST_DB_URL(localhost) 미설정 — 실제 PostgreSQL 통합 테스트는 건너뜀")
|
|
|
|
@pytest.fixture(autouse=True, scope="module")
|
|
def _own_app_main_and_sleep():
|
|
if not ENABLED:
|
|
yield
|
|
return
|
|
prev, prev_sleep = sys.modules.get("app.main"), products.time.sleep
|
|
sys.modules["app.main"] = fake_main
|
|
products.time.sleep = _NO_SLEEP
|
|
try:
|
|
yield
|
|
finally:
|
|
products.time.sleep = prev_sleep
|
|
if prev is None:
|
|
sys.modules.pop("app.main", None)
|
|
else:
|
|
sys.modules["app.main"] = prev
|
|
|
|
_BASE = random.randint(100_000, 900_000) * 10
|
|
|
|
|
|
def _new_product(description="<p>A</p>") -> tuple[int, "fakes.FakeCafe24"]:
|
|
global _BASE
|
|
_BASE += 1
|
|
cafe = fakes.FakeCafe24(description, product_no=_BASE)
|
|
MULTI.by_no[_BASE] = cafe
|
|
return _BASE, cafe
|
|
|
|
|
|
def req(method, url, who="king@test.local", **kw):
|
|
return CLIENT.request(method, url, headers={"x-test-user": who}, follow_redirects=False, **kw)
|
|
|
|
|
|
def q(sql, *args):
|
|
with ST._pool.connection() as conn: # noqa: SLF001 — 테스트 확인용
|
|
cur = conn.execute(sql, args)
|
|
return cur.fetchall() if cur.description else []
|
|
|
|
|
|
def _location(resp) -> dict:
|
|
loc = resp.headers.get("location", "")
|
|
return {k: v[0] for k, v in parse_qs(urlparse(loc).query).items()}
|
|
|
|
|
|
def _pane(no):
|
|
resp = req("GET", f"/cafe24/products/{no}/pane")
|
|
assert resp.status_code == 200, resp.text
|
|
return json.loads(resp.text.split("\n", 1)[1])
|
|
|
|
|
|
def _apply(no, html, fp, who="king@test.local", memo=""):
|
|
return req("POST", f"/cafe24/products/{no}/apply",
|
|
data={"html": html, "base_fingerprint": fp, "memo": memo}, who=who)
|
|
|
|
|
|
# ════════════════════════════════════════════════════════════
|
|
# DB — 잠금(lease)
|
|
# ════════════════════════════════════════════════════════════
|
|
def test_lock_exclusive_across_pools_and_expiry_fencing():
|
|
key = f"test:lock:{_BASE}:{random.random()}"
|
|
t1 = ST.acquire_lock(key, owner="a|h:1", purpose="p", ttl_seconds=60)
|
|
assert t1
|
|
assert ST2.acquire_lock(key, owner="b|h:2", purpose="p", ttl_seconds=60) is None
|
|
assert ST2.lock_holder(key)["owner"].startswith("a|")
|
|
assert ST.renew_lock(key, t1, ttl_seconds=60)
|
|
q("UPDATE cafe24_write_locks SET expires_at = now() - interval '1 second' WHERE lock_key = %s", key)
|
|
t2 = ST2.acquire_lock(key, owner="b|h:2", purpose="p", ttl_seconds=60)
|
|
assert t2 and t2 != t1
|
|
assert ST.renew_lock(key, t1, ttl_seconds=60) is False # 펜싱: 넘어간 잠금은 연장 불가
|
|
ST.release_lock(key, t1) # 남의 잠금은 못 푼다
|
|
assert ST2.lock_holder(key)["owner"].startswith("b|")
|
|
ST2.release_lock(key, t2)
|
|
assert ST.lock_holder(key) == {}
|
|
|
|
|
|
def test_lock_race_only_one_winner():
|
|
key = f"test:race:{_BASE}:{random.random()}"
|
|
tokens, barrier = [], threading.Barrier(8)
|
|
|
|
def grab(s):
|
|
barrier.wait()
|
|
tokens.append(s.acquire_lock(key, owner="x", purpose="p", ttl_seconds=30))
|
|
|
|
threads = [threading.Thread(target=grab, args=(ST if i % 2 else ST2,)) for i in range(8)]
|
|
[t.start() for t in threads]
|
|
[t.join() for t in threads]
|
|
assert sum(1 for t in tokens if t) == 1, tokens
|
|
|
|
|
|
# ════════════════════════════════════════════════════════════
|
|
# DB — 예약 lease
|
|
# ════════════════════════════════════════════════════════════
|
|
def _schedule(no, **kw):
|
|
fields = dict(product_no=no, scheduled_at=now_kst() - timedelta(minutes=1), revision_id=None,
|
|
set_display=True, set_selling=None)
|
|
fields.update(kw)
|
|
return ST.create_schedule(**fields)
|
|
|
|
|
|
def test_schedule_claim_is_exclusive_between_workers():
|
|
no, _ = _new_product()
|
|
ids = {_schedule(no) for _ in range(6)}
|
|
got, barrier = [], threading.Barrier(2)
|
|
|
|
def run(s, name):
|
|
barrier.wait()
|
|
while True:
|
|
row = s.claim_due_schedule(now=now_kst(), owner=name, ttl_seconds=60)
|
|
if row is None:
|
|
return
|
|
got.append(row["id"])
|
|
|
|
threads = [threading.Thread(target=run, args=(ST, "w1")), threading.Thread(target=run, args=(ST2, "w2"))]
|
|
[t.start() for t in threads]
|
|
[t.join() for t in threads]
|
|
mine = [i for i in got if i in ids]
|
|
assert sorted(mine) == sorted(ids) and len(mine) == len(set(mine)), got
|
|
|
|
|
|
def test_schedule_lease_expiry_and_stale_finish():
|
|
no, _ = _new_product()
|
|
sid = _schedule(no, scheduled_at=now_kst() - timedelta(days=3650)) # 가장 먼저 잡히게
|
|
row = ST.claim_due_schedule(now=now_kst(), owner="w1", ttl_seconds=60)
|
|
assert row["id"] == sid and row["lease_token"]
|
|
assert ST.renew_schedule_lease(sid, row["lease_token"], ttl_seconds=60)
|
|
q("UPDATE cafe24_product_schedules SET lease_expires_at = now() - interval '1 second' WHERE id = %s", sid)
|
|
taken = [r for r in ST2.claim_expired_schedules(owner="w2", ttl_seconds=60, legacy_minutes=30) if r["id"] == sid]
|
|
assert taken and taken[0]["lease_token"] != row["lease_token"]
|
|
assert ST.renew_schedule_lease(sid, row["lease_token"], ttl_seconds=60) is False
|
|
assert ST.finish_schedule(sid, token=row["lease_token"], status="FAILED") is False # 늦은 결과 무시
|
|
assert ST2.finish_schedule(sid, token=taken[0]["lease_token"], status="SUCCESS") is True
|
|
assert q("SELECT status, lease_token FROM cafe24_product_schedules WHERE id = %s", sid)[0] == \
|
|
{"status": "SUCCESS", "lease_token": ""}
|
|
|
|
|
|
def test_legacy_processing_row_is_recovered():
|
|
"""005 이전에 PROCESSING 이 된 행(lease 없음)도 오래됐으면 복구 대상."""
|
|
no, _ = _new_product()
|
|
sid = _schedule(no)
|
|
q("UPDATE cafe24_product_schedules SET status='PROCESSING', started_at = now() - interval '40 minutes' "
|
|
"WHERE id = %s RETURNING id", sid)
|
|
rows = [r for r in ST.claim_expired_schedules(owner="w", ttl_seconds=60, legacy_minutes=30) if r["id"] == sid]
|
|
assert rows and rows[0]["lease_token"]
|
|
|
|
|
|
# ════════════════════════════════════════════════════════════
|
|
# DB — 시도 기록 · 확인된 쓰기 · 스냅샷
|
|
# ════════════════════════════════════════════════════════════
|
|
def test_record_attempt_revision_is_idempotent_under_race():
|
|
no, _ = _new_product()
|
|
aid = ST.start_attempt(product_no=no, origin="MANUAL", actor="k", target_html="<p>X</p>",
|
|
target_digest=store.content_digest("<p>X</p>"))
|
|
ST.update_attempt(aid, status="REMOTE_OK", remote_ok=True)
|
|
out, barrier = [], threading.Barrier(2)
|
|
|
|
def rec(s):
|
|
barrier.wait()
|
|
out.append(s.record_attempt_revision(aid, revision_type="MANUAL", memo="", created_by="k"))
|
|
|
|
threads = [threading.Thread(target=rec, args=(s,)) for s in (ST, ST2)]
|
|
[t.start() for t in threads]
|
|
[t.join() for t in threads]
|
|
assert len(set(out)) == 1
|
|
assert q("SELECT count(*) AS n FROM cafe24_product_revisions WHERE product_no = %s AND revision_type='MANUAL'",
|
|
no)[0]["n"] == 1
|
|
assert q("SELECT status, target_html FROM cafe24_write_attempts WHERE id = %s", aid)[0] == \
|
|
{"status": "RECORDED", "target_html": ""}
|
|
|
|
|
|
def test_write_lineage_only_confirmed():
|
|
no, _ = _new_product()
|
|
since = now_kst() - timedelta(hours=1)
|
|
for status, html in (("REMOTE_FAILED", "F"), ("UNKNOWN", "U"), ("STARTED", "S"), ("RECORDED", "OK1"), ("REMOTE_OK", "OK2")):
|
|
aid = ST.start_attempt(product_no=no, origin="MANUAL", target_html=html,
|
|
target_digest=store.content_digest(html), observed_digest=store.content_digest("OBS-" + html))
|
|
if status != "STARTED":
|
|
ST.update_attempt(aid, status=status, remote_ok=status in ("RECORDED", "REMOTE_OK"))
|
|
ST.add_revision(product_no=no, html_content="CONFLICT-BACKUP", revision_type="BACKUP")
|
|
lineage = ST.write_lineage(no, since=since)
|
|
assert [store.content_digest(x) for x in ("OK2", "OK1")] == [a["target_digest"] for a in lineage]
|
|
assert lineage[0]["html_content"] == "OK2"
|
|
digests = store.lineage_digests(lineage)
|
|
assert store.content_digest("CONFLICT-BACKUP") not in digests
|
|
assert store.content_digest("F") not in digests and store.content_digest("U") not in digests
|
|
|
|
|
|
def test_snapshot_jsonb_field_merge_replace_and_deleted():
|
|
no, _ = _new_product()
|
|
ST.save_write_snapshot(no, "variants", {"V1": {"custom_variant_code": "C1"}, "V2": {"display": "F"}})
|
|
ST.save_write_snapshot(no, "variants", {"V1": {"display": "F"}})
|
|
data = ST.get_write_snapshot(no)["variants"]["data"]
|
|
assert data["V1"]["custom_variant_code"] == "C1" and data["V1"]["display"] == "F" and "V2" in data
|
|
ST.save_write_snapshot(no, "variants", {"V2": {"_deleted": True}})
|
|
ST.save_write_snapshot(no, "variants", {"V2": {"display": "T"}})
|
|
assert ST.get_write_snapshot(no)["variants"]["data"]["V2"].get("_deleted") is True
|
|
ST.save_write_snapshot(no, "variants", {})
|
|
assert "V1" in ST.get_write_snapshot(no)["variants"]["data"]
|
|
ST.save_write_snapshot(no, "variants", {}, replace=True)
|
|
assert ST.get_write_snapshot(no)["variants"]["data"] == {}
|
|
|
|
|
|
def test_snapshot_concurrent_saves_both_persist():
|
|
no, _ = _new_product()
|
|
barrier = threading.Barrier(2)
|
|
|
|
def save(s, code):
|
|
barrier.wait()
|
|
s.save_write_snapshot(no, "variants", {code: {"display": "F"}})
|
|
|
|
threads = [threading.Thread(target=save, args=(ST, "VA")), threading.Thread(target=save, args=(ST2, "VB"))]
|
|
[t.start() for t in threads]
|
|
[t.join() for t in threads]
|
|
assert set(ST.get_write_snapshot(no)["variants"]["data"]) == {"VA", "VB"}
|
|
|
|
|
|
# ════════════════════════════════════════════════════════════
|
|
# 라우트 — [01] 충돌 백업이 외부 수정을 가리지 않는다 / 권한
|
|
# ════════════════════════════════════════════════════════════
|
|
def test_route_permission_required():
|
|
no, _ = _new_product()
|
|
assert req("POST", f"/cafe24/products/{no}/apply", who="nope@test.local",
|
|
data={"html": "x"}).status_code == 403
|
|
assert req("GET", f"/cafe24/products/{no}/revisions/1", who="nope@test.local").status_code == 403
|
|
|
|
|
|
def test_route_01_conflict_then_external_edit_not_overwritten():
|
|
no, cafe = _new_product("<p>A</p>")
|
|
p0 = _pane(no)
|
|
assert _location(_apply(no, "<p>W1</p>", p0["fingerprint"])).get("msg")
|
|
stale_fp = _pane(no)["fingerprint"]
|
|
cafe.external_edit("<p>X</p>")
|
|
assert "변경" in _location(_apply(no, "<p>Y</p>", stale_fp)).get("err", "")
|
|
pane = _pane(no)
|
|
assert pane["sync_state"] == store.SYNC_EXTERNAL and "<p>X</p>" in pane["html_pc"]
|
|
assert "변경" in _location(_apply(no, "<p>Y</p>", stale_fp)).get("err", "")
|
|
assert cafe.state["description"] == "<p>X</p>"
|
|
|
|
|
|
def test_route_02_concurrent_applies_one_wins():
|
|
no, cafe = _new_product("<p>A</p>")
|
|
fp = _pane(no)["fingerprint"]
|
|
import time as _time
|
|
|
|
real_put = cafe.put
|
|
|
|
def slow_put(path, **kw):
|
|
_time.sleep(0.4)
|
|
return real_put(path, **kw)
|
|
|
|
cafe.put = slow_put
|
|
results, barrier = [], threading.Barrier(2)
|
|
|
|
def go(text, who):
|
|
barrier.wait()
|
|
results.append(_location(_apply(no, text, fp, who=who)))
|
|
|
|
threads = [threading.Thread(target=go, args=("<p>AMY</p>", "amy@test.local")),
|
|
threading.Thread(target=go, args=("<p>KING</p>", "king@test.local"))]
|
|
[t.start() for t in threads]
|
|
[t.join() for t in threads]
|
|
ok = [r for r in results if r.get("msg")]
|
|
err = [r for r in results if r.get("err")]
|
|
assert len(ok) == 1 and len(err) == 1, results
|
|
desc_puts = [c for c in cafe.calls if c[0] == "PUT" and "description" in (c[2] or {}).get("request", {})]
|
|
assert len(desc_puts) == 1
|
|
|
|
|
|
# ════════════════════════════════════════════════════════════
|
|
# 라우트 — [13] 버전 원문 · 선택 복원 · [07] 결과 확정
|
|
# ════════════════════════════════════════════════════════════
|
|
def test_route_13_revision_detail_scoped_and_restore():
|
|
no, cafe = _new_product("<p>A</p>")
|
|
other, _ = _new_product("<p>O</p>")
|
|
_apply(no, "<p>B<script>x</script></p>", _pane(no)["fingerprint"])
|
|
backup = next(r for r in _pane(no)["revisions"] if r["revision_type"] == "BACKUP")
|
|
detail = req("GET", f"/cafe24/products/{no}/revisions/{backup['id']}").json()["revision"]
|
|
assert detail["html"] == "<p>A</p>" and detail["type_label"]
|
|
assert req("GET", f"/cafe24/products/{other}/revisions/{backup['id']}").status_code == 404
|
|
foreign = ST.add_revision(product_no=no, html_content="<p>F</p>", revision_type="MANUAL", mall_id="othermall")
|
|
assert req("GET", f"/cafe24/products/{no}/revisions/{foreign}").status_code == 404
|
|
shop2 = ST.add_revision(product_no=no, html_content="<p>S</p>", revision_type="MANUAL", shop_no=2)
|
|
assert req("GET", f"/cafe24/products/{no}/revisions/{shop2}").status_code == 404
|
|
# 복원 — 지문 없이는 거부, 옛 지문이면 충돌, 현재 지문이면 ROLLBACK
|
|
assert _location(req("POST", f"/cafe24/products/{no}/revisions/{backup['id']}/restore", data={})).get("err")
|
|
assert "변경" in _location(req("POST", f"/cafe24/products/{no}/revisions/{backup['id']}/restore",
|
|
data={"base_fingerprint": store.fingerprint("<p>A</p>")})).get("err", "")
|
|
fp = _pane(no)["fingerprint"]
|
|
loc = _location(req("POST", f"/cafe24/products/{no}/revisions/{backup['id']}/restore",
|
|
data={"base_fingerprint": fp, "memo": "되돌림"}))
|
|
assert "복원" in loc.get("msg", ""), loc
|
|
assert cafe.state["description"] == "<p>A</p>"
|
|
rb = q("SELECT revision_type, source, source_revision_id, memo FROM cafe24_product_revisions "
|
|
"WHERE product_no = %s ORDER BY id DESC LIMIT 1", no)[0]
|
|
assert rb["revision_type"] == "ROLLBACK" and rb["source_revision_id"] == backup["id"] and "되돌림" in rb["memo"]
|
|
# 다른 상품 버전을 이 상품 주소로 복원 시도 → 거부
|
|
assert _location(req("POST", f"/cafe24/products/{other}/revisions/{backup['id']}/restore",
|
|
data={"base_fingerprint": fp})).get("err")
|
|
|
|
|
|
def test_route_07_unknown_attempt_blocks_until_resolved():
|
|
no, cafe = _new_product("<p>A</p>")
|
|
fp = _pane(no)["fingerprint"]
|
|
cafe.put_error = fakes.network_error(maybe_applied=True)
|
|
assert "알 수 없습니다" in _location(_apply(no, "<p>B</p>", fp)).get("err", "")
|
|
cafe.put_error = None
|
|
pane = _pane(no)
|
|
assert len(pane["open_attempts"]) == 1
|
|
assert "확인하지 못했습니다" in _location(_apply(no, "<p>C</p>", pane["fingerprint"])).get("err", "")
|
|
aid = pane["open_attempts"][0]["id"]
|
|
loc = _location(req("POST", f"/cafe24/products/{no}/attempts/{aid}/resolve", data={"result": "not_applied"}))
|
|
assert loc.get("msg"), loc
|
|
assert _pane(no)["open_attempts"] == []
|
|
assert _location(_apply(no, "<p>C</p>", _pane(no)["fingerprint"])).get("msg")
|
|
assert cafe.state["description"] == "<p>C</p>"
|
|
|
|
|
|
def test_route_07_record_failure_reported_as_success():
|
|
no, cafe = _new_product("<p>A</p>")
|
|
fp = _pane(no)["fingerprint"]
|
|
real = ST.record_attempt_revision
|
|
|
|
def boom(*a, **kw):
|
|
raise RuntimeError("DB 장애")
|
|
|
|
ST.record_attempt_revision = boom
|
|
try:
|
|
loc = _location(_apply(no, "<p>B</p>", fp))
|
|
finally:
|
|
ST.record_attempt_revision = real
|
|
assert "다시 적용하지 마세요" in loc.get("msg", ""), loc
|
|
status = q("SELECT status FROM cafe24_write_attempts WHERE product_no = %s ORDER BY id DESC LIMIT 1", no)
|
|
assert status[0]["status"] == "REMOTE_OK"
|
|
# worker 의 기록 복구가 채운다(다시 PUT 하지 않음)
|
|
worker.record_pending_attempts(ST)
|
|
assert q("SELECT status FROM cafe24_write_attempts WHERE product_no = %s ORDER BY id DESC LIMIT 1",
|
|
no)[0]["status"] == "RECORDED"
|
|
assert len([c for c in cafe.calls if c[0] == "PUT"]) == 1
|
|
|
|
|
|
# ════════════════════════════════════════════════════════════
|
|
# 라우트 — [09] 행별 결과 · [10] 품목 표기 · [11] 삭제 품목
|
|
# ════════════════════════════════════════════════════════════
|
|
def _create_options(no, values):
|
|
resp = req("POST", f"/cafe24/products/{no}/options", json={"option_name": "구성", "values": values})
|
|
assert resp.status_code == 200, resp.text
|
|
return resp.json()
|
|
|
|
|
|
def test_route_09_variants_partial_success():
|
|
no, cafe = _new_product()
|
|
created = _create_options(no, [f"v{i}" for i in range(150)])
|
|
rows = [{"variant_code": v["variant_code"], "custom_variant_code": f"C{i}"}
|
|
for i, v in enumerate(created["variants"])]
|
|
cafe.fail_variant_chunk = 2
|
|
resp = req("PUT", f"/cafe24/products/{no}/variants", json={"rows": rows})
|
|
assert resp.status_code == 200, resp.text
|
|
body = resp.json()
|
|
assert body["partial"] and len(body["updated"]) == 100 and len(body["failed"]) == 50
|
|
snap = ST.get_write_snapshot(no)["variants"]["data"]
|
|
assert len([c for c in snap if c in body["updated"]]) == 100
|
|
assert not any(c in snap for c in body["failed"])
|
|
audit = q("SELECT result FROM cafe24_audit_logs WHERE product_no = %s AND action='update_variants' "
|
|
"ORDER BY id DESC LIMIT 1", no)[0]
|
|
assert audit["result"] == "PARTIAL"
|
|
cafe.fail_variant_chunk = 0
|
|
cafe._variant_puts = 0
|
|
cafe.fail_variant_chunk = 1
|
|
resp = req("PUT", f"/cafe24/products/{no}/variants", json={"rows": rows[:5]})
|
|
assert resp.status_code == 502
|
|
|
|
|
|
def test_route_09b_display_selling_to_all_shops(monkeypatch):
|
|
monkeypatch.setenv("CAFE24_SHOP_NOS", "1,2,3")
|
|
no, cafe = _new_product()
|
|
created = _create_options(no, ["A", "B"])
|
|
a, b = (v["variant_code"] for v in created["variants"])
|
|
cafe.calls.clear()
|
|
resp = req("PUT", f"/cafe24/products/{no}/variants", json={"rows": [
|
|
{"variant_code": a, "display": "off", "additional_amount": "500"},
|
|
{"variant_code": b, "custom_variant_code": "X1"}]})
|
|
assert resp.status_code == 200, resp.text
|
|
assert resp.json()["shop_failed"] == {}
|
|
puts = [c[2] for c in cafe.calls if c[0] == "PUT" and c[1].endswith("/variants")]
|
|
assert [p["shop_no"] for p in puts] == [1, 2, 3]
|
|
# 다른 쇼핑몰엔 진열·판매만, 진열/판매를 안 바꾼 행(b)은 안 보낸다
|
|
assert puts[1]["requests"] == puts[2]["requests"] == [{"variant_code": a, "display": "F"}]
|
|
# 다른 쇼핑몰 실패는 경고로만(기본몰 반영은 성공)
|
|
cafe._variant_puts = 0
|
|
cafe.fail_variant_chunk = 2
|
|
resp = req("PUT", f"/cafe24/products/{no}/variants", json={"rows": [{"variant_code": a, "selling": "off"}]})
|
|
cafe.fail_variant_chunk = 0
|
|
assert resp.status_code == 200 and resp.json()["ok"]
|
|
assert list(resp.json()["shop_failed"]) == ["2"]
|
|
|
|
|
|
def test_sync_variant_flags_script(monkeypatch, capsys):
|
|
from app.integrations import cafe24 as integ
|
|
from app.integrations.cafe24 import products as cp
|
|
from app.modules.cafe24 import sync_variant_flags
|
|
|
|
no, cafe = _new_product()
|
|
created = _create_options(no, ["A", "B"])
|
|
a = created["variants"][0]["variant_code"]
|
|
before = [dict(v) for v in cafe.variants]
|
|
assert req("PUT", f"/cafe24/products/{no}/variants",
|
|
json={"rows": [{"variant_code": a, "display": "off"}]}).status_code == 200
|
|
cafe.stale_variants = before # 다른 쇼핑몰(과 지연된 GET)은 아직 진열함
|
|
monkeypatch.setenv("CAFE24_DB_URL", os.environ["CAFE24_TEST_DB_URL"])
|
|
monkeypatch.setattr(integ, "build_cafe24_api", lambda st, **kw: fakes.FakeApi(MULTI))
|
|
monkeypatch.setattr(cp, "list_all_products", lambda client: ([{"product_no": no}], False))
|
|
|
|
cafe.calls.clear()
|
|
assert sync_variant_flags.main(["--shops", "3"]) == 0
|
|
assert not [c for c in cafe.calls if c[0] == "PUT"] # 미리보기는 쓰지 않음
|
|
assert sync_variant_flags.main(["--shops", "3", "--apply"]) == 0
|
|
puts = [c[2] for c in cafe.calls if c[0] == "PUT"]
|
|
assert puts == [{"shop_no": 3, "requests": [{"variant_code": a, "display": "F"}]}]
|
|
assert "BEFORE" in capsys.readouterr().out
|
|
|
|
|
|
def test_route_10_rename_with_lagging_variants_keeps_rows():
|
|
no, cafe = _new_product()
|
|
created = _create_options(no, ["Black", "Red"])
|
|
before_variants = [dict(v, options=[dict(o) for o in v["options"]]) for v in cafe.variants]
|
|
before_option = json.loads(json.dumps(cafe.option))
|
|
resp = req("PUT", f"/cafe24/products/{no}/options", json={"options": [{
|
|
"option_name": "구성", "option_value": [{"option_text": "Jet"}, {"option_text": "Crimson"}]}]})
|
|
assert resp.status_code == 200, resp.text
|
|
# 카페24 GET 이 아직 옛 옵션·옛 품목 표기를 돌려준다(읽기 지연)
|
|
cafe.stale_option = before_option
|
|
cafe.stale_variants = before_variants
|
|
got = req("GET", f"/cafe24/products/{no}/options").json()
|
|
texts = [v["option_text"] for v in got["option"]["options"][0]["option_value"]]
|
|
labels = sorted(v["options"][0]["value"] for v in got["variants"])
|
|
assert texts == ["Jet", "Crimson"] and labels == ["Crimson", "Jet"], (texts, labels)
|
|
assert all(v["value_no"] for v in got["variants"]) # 옵션값 번호로 짝지을 수 있다
|
|
# 관리자에서 다시 Onyx 로 고침 — 그 값은 믿는다
|
|
cafe.stale_option = None
|
|
cafe.stale_variants = None
|
|
cafe.option["options"][0]["option_value"][0]["option_text"] = "Onyx"
|
|
cafe.variants[0]["options"][0]["value"] = "Onyx"
|
|
got = req("GET", f"/cafe24/products/{no}/options").json()
|
|
assert got["option"]["options"][0]["option_value"][0]["option_text"] == "Onyx"
|
|
assert "Onyx" in [v["options"][0]["value"] for v in got["variants"]]
|
|
assert created["variants"]
|
|
|
|
|
|
def test_route_08_append_value_rejected_before_put():
|
|
# 카페24 PUT 은 옵션값 추가를 오류 없이 무시한다 — "저장했는데 사라짐" 대신 400 으로 재생성 안내.
|
|
no, cafe = _new_product()
|
|
_create_options(no, ["A"])
|
|
puts = len([c for c in cafe.calls if c[0] == "PUT"])
|
|
resp = req("PUT", f"/cafe24/products/{no}/options", json={"options": [{
|
|
"option_name": "구성", "option_value": [{"option_text": "A"}, {"option_text": "B"}]}]})
|
|
assert resp.status_code == 400 and "옵션 재생성" in resp.text, resp.text
|
|
assert len([c for c in cafe.calls if c[0] == "PUT"]) == puts
|
|
|
|
|
|
def test_route_11_deleted_variant_stays_hidden():
|
|
no, cafe = _new_product()
|
|
created = _create_options(no, ["A", "B"])
|
|
code = created["variants"][0]["variant_code"]
|
|
stale = [dict(v) for v in cafe.variants]
|
|
assert req("DELETE", f"/cafe24/products/{no}/variants/{code}").status_code == 200
|
|
ST.save_write_snapshot(no, "variants", {code: {"display": "T"}}) # 늦게 도착한 수정
|
|
cafe.stale_variants = stale
|
|
got = req("GET", f"/cafe24/products/{no}/options").json()
|
|
assert code not in [v["variant_code"] for v in got["variants"]]
|
|
|
|
|
|
def test_route_lock_busy_returns_409():
|
|
no, _ = _new_product()
|
|
token = ST2.acquire_lock(f"product:{no}", owner="amy|h:1", purpose="상세설명 적용", ttl_seconds=60)
|
|
os.environ["CAFE24_WRITE_LOCK_WAIT_SEC"] = "0"
|
|
try:
|
|
resp = req("POST", f"/cafe24/products/{no}/basic", json={"price": "1000"})
|
|
assert resp.status_code == 409 and "amy" in resp.json()["detail"], resp.text
|
|
finally:
|
|
os.environ["CAFE24_WRITE_LOCK_WAIT_SEC"] = "3"
|
|
ST2.release_lock(f"product:{no}", token)
|
|
|
|
|
|
# ════════════════════════════════════════════════════════════
|
|
# worker — 실제 DB
|
|
# ════════════════════════════════════════════════════════════
|
|
def _draft(no, html):
|
|
return ST.add_revision(product_no=no, html_content=html, revision_type="DRAFT", mall_id="testmall")
|
|
|
|
|
|
def test_worker_real_db_success_and_needs_review():
|
|
no, cafe = _new_product("<p>A</p>")
|
|
sid = _schedule(no, revision_id=_draft(no, "<p>S</p>"), scheduled_at=now_kst() - timedelta(days=3000))
|
|
worker.process_once(ST, fakes.FakeApi(MULTI))
|
|
row = ST.get_schedule(sid)
|
|
assert row["status"] == "SUCCESS" and cafe.state["description"] == "<p>S</p>", row
|
|
assert q("SELECT count(*) AS n FROM cafe24_product_revisions WHERE product_no=%s AND revision_type='SCHEDULED'",
|
|
no)[0]["n"] == 1
|
|
|
|
no2, cafe2 = _new_product("<p>A</p>")
|
|
cafe2.put_error = fakes.network_error(maybe_applied=True)
|
|
cafe2.put_error_after_apply = True
|
|
sid2 = _schedule(no2, revision_id=_draft(no2, "<p>S2</p>"), scheduled_at=now_kst() - timedelta(days=3000))
|
|
worker.process_once(ST, fakes.FakeApi(MULTI))
|
|
assert ST.get_schedule(sid2)["status"] == "NEEDS_REVIEW"
|
|
# 사람이 쇼핑몰을 보고 "반영됨" 확정
|
|
resp = req("POST", f"/cafe24/schedules/{sid2}/review", data={"action": "applied"})
|
|
assert _location(resp).get("msg"), resp.headers
|
|
assert ST.get_schedule(sid2)["status"] == "SUCCESS"
|
|
assert q("SELECT status FROM cafe24_write_attempts WHERE schedule_id=%s", sid2)[0]["status"] == "RECORDED"
|
|
|
|
|
|
def test_schedule_main_image_route_and_worker():
|
|
"""대표 이미지 예약(006): 등록 → 파일 DB 보관 → 그 시각에 worker 가 교체 → 목록 미리보기."""
|
|
no, cafe = _new_product("<p>A</p>")
|
|
at = (now_kst() + timedelta(days=1)).strftime("%Y-%m-%dT%H:%M")
|
|
png = b"\x89PNG\r\n\x1a\n" + b"x" * 64
|
|
form = {"product_no": str(no), "scheduled_at": at, "set_display": "", "set_selling": ""}
|
|
# 내용 없는 예약(이미지도 안 고름 — 이름 없는 빈 파트) 거부
|
|
resp = req("POST", "/cafe24/schedules", data=form, files={"image": ("", b"", "application/octet-stream")})
|
|
assert "하나 이상" in _location(resp).get("err", ""), resp.headers
|
|
# 이미지 아닌 파일 거부
|
|
resp = req("POST", "/cafe24/schedules", data=form, files={"image": ("a.txt", b"hi", "text/plain")})
|
|
assert "이미지만" in _location(resp).get("err", ""), resp.headers
|
|
resp = req("POST", "/cafe24/schedules", data=form, files={"image": ("가을.png", png, "image/png")})
|
|
assert "대표이미지" in _location(resp).get("msg", ""), resp.headers
|
|
sid = q("SELECT id FROM cafe24_product_schedules WHERE product_no=%s", no)[0]["id"]
|
|
row = ST.get_schedule(sid)
|
|
assert row["image_type"] == "image/png" and row["image_name"] == "가을.png" and row["revision_id"] is None
|
|
got = req("GET", f"/cafe24/schedules/{sid}/image")
|
|
assert got.status_code == 200 and got.content == png and got.headers["content-type"] == "image/png"
|
|
listed = json.loads(req("GET", "/cafe24/schedules").text.split("\n", 1)[1])["rows"]
|
|
mine = [r for r in listed if r["id"] == sid][0]
|
|
assert mine["image_type"] == "image/png" and mine["action_label"] == "대표이미지", mine
|
|
|
|
q("UPDATE cafe24_product_schedules SET scheduled_at = now() - interval '3000 days' WHERE id=%s RETURNING id", sid)
|
|
worker.process_once(ST, fakes.FakeApi(MULTI))
|
|
row = ST.get_schedule(sid)
|
|
assert row["status"] == "SUCCESS", row
|
|
posts = [c for c in cafe.calls if c[0] == "POST" and c[1].endswith("/images")]
|
|
assert len(posts) == 1 and posts[0][2]["request"]["detail_image"].startswith("data:image/png;base64,")
|
|
assert cafe.state["detail_image"] == f"/web/product/detail/{no}_1.png"
|
|
assert [c for c in cafe.calls if c[0] == "PUT"] == [] # 이미지만 — 상세설명·진열 PUT 없음
|
|
assert ST.get_write_snapshot(no)["product"]["data"]["detail_image"] == cafe.state["detail_image"]
|
|
|
|
# 이미지 + 진열을 한 예약에: 이미지 먼저, 그다음 진열 PUT
|
|
no2, cafe2 = _new_product("<p>A</p>")
|
|
sid2 = ST.create_schedule(product_no=no2, scheduled_at=now_kst() - timedelta(days=3000), revision_id=None,
|
|
set_display=False, set_selling=None, image=png, image_type="image/png", image_name="b.png")
|
|
worker.process_once(ST, fakes.FakeApi(MULTI))
|
|
assert ST.get_schedule(sid2)["status"] == "SUCCESS"
|
|
kinds = [(c[0], c[1].rsplit("/", 1)[-1]) for c in cafe2.calls if c[0] in ("POST", "PUT")]
|
|
assert kinds == [("POST", "images"), ("PUT", str(no2))], kinds
|
|
assert cafe2.state["display"] == "F" and cafe2.state["detail_image"].endswith(f"{no2}_1.png")
|
|
|
|
|
|
def test_worker_real_db_recovers_crash_after_remote_ok():
|
|
no, cafe = _new_product("<p>A</p>")
|
|
rid = _draft(no, "<p>R</p>")
|
|
sid = _schedule(no, revision_id=rid, scheduled_at=now_kst() - timedelta(days=3000))
|
|
row = ST.claim_due_schedule(now=now_kst(), owner="dead", ttl_seconds=60)
|
|
assert row["id"] == sid
|
|
aid = ST.start_attempt(product_no=no, schedule_id=sid, origin="SCHEDULED", target_revision_id=rid,
|
|
target_digest=store.content_digest("<p>R</p>"))
|
|
ST.update_attempt(aid, status="REMOTE_OK", remote_ok=True) # 반영 직후 죽음
|
|
q("UPDATE cafe24_product_schedules SET lease_expires_at = now() - interval '1 second' WHERE id=%s RETURNING id", sid)
|
|
worker.process_once(ST, fakes.FakeApi(MULTI))
|
|
assert ST.get_schedule(sid)["status"] == "SUCCESS"
|
|
assert q("SELECT status FROM cafe24_write_attempts WHERE id=%s", aid)[0]["status"] == "RECORDED"
|
|
assert [c for c in cafe.calls if c[0] == "PUT"] == [] # 재적용 없음
|
|
|
|
|
|
# ════════════════════════════════════════════════════════════
|
|
# 디자인 파일 — [04] 잠금 + 임시 파일 교체
|
|
# ════════════════════════════════════════════════════════════
|
|
def test_design_apply_route_temp_replace_and_conflict():
|
|
os.environ.update({"CAFE24_FTP_USER": "u", "CAFE24_FTP_PASSWORD": "p", "CAFE24_FTP_HOST": "h"})
|
|
path = routes_design_files.design_file_path("swiper")
|
|
with fakes.patched_ftp() as ftp:
|
|
ftp.reset({path: b"OLD"})
|
|
fp = store.fingerprint("OLD")
|
|
loc = _location(req("POST", "/cafe24/design/swiper/apply", data={"content": "NEW", "base_fingerprint": fp}))
|
|
assert loc.get("msg"), loc
|
|
assert ftp.files == {path: b"NEW"}
|
|
# 교체 직전 남이 바꿈 → 충돌, 원본(남의 값) 그대로
|
|
ftp.on_before_rename = None
|
|
fp = store.fingerprint("NEW")
|
|
|
|
real_retr = fakes.FakeFTP.retrbinary
|
|
calls = {"n": 0}
|
|
|
|
def sneaky(self, cmd, cb):
|
|
calls["n"] += 1
|
|
if calls["n"] == 3: # 1: 현재값 조회, 2: 임시 파일 검증, 3: 교체 직전 재확인
|
|
self.files[path] = b"THEIRS"
|
|
return real_retr(self, cmd, cb)
|
|
|
|
fakes.FakeFTP.retrbinary = sneaky
|
|
try:
|
|
loc = _location(req("POST", "/cafe24/design/swiper/apply", data={"content": "MINE", "base_fingerprint": fp}))
|
|
finally:
|
|
fakes.FakeFTP.retrbinary = real_retr
|
|
assert "바뀌었습니다" in loc.get("err", ""), loc
|
|
assert ftp.files == {path: b"THEIRS"}
|
|
|
|
|
|
def _run_all() -> None:
|
|
if not ENABLED:
|
|
print("SKIP — CAFE24_TEST_DB_URL(localhost) 이 없어 건너뜁니다.")
|
|
return
|
|
products.time.sleep = _NO_SLEEP # 직접 실행 = 이 프로세스는 이 파일 테스트만
|
|
fns = [v for k, v in sorted(globals().items()) if k.startswith("test_") and callable(v)]
|
|
failed = 0
|
|
for fn in fns:
|
|
try:
|
|
fn()
|
|
print("PASS", fn.__name__)
|
|
except Exception as exc: # noqa: BLE001
|
|
failed += 1
|
|
import traceback
|
|
|
|
print("FAIL", fn.__name__, "→", repr(exc))
|
|
traceback.print_exc()
|
|
print(f"\n{len(fns) - failed}/{len(fns)} passed.")
|
|
ST.close()
|
|
ST2.close()
|
|
if failed:
|
|
raise SystemExit(1)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
_run_all()
|