Files
dbx-main/tests/test_cupang_weight.py
king 0c6dacb824 feat(cupang): shipment box list shows weights in kg with a totals row
Box weights on the shipment detail screen are now shown in kg, rounded
half-up to one decimal. A footer row sums quantity and weight (marks
"일부 미입력" when some product weights are missing).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 20:57:56 +09:00

181 lines
7.2 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""쿠팡 밀크런 — 제품 포장무게(g) (마이그레이션 007).
DB 없이 돈다: 입력 읽기(parse_weight_g)와, 가짜 연결로 등록·수정 SQL 이 무게 칸 유무에 맞게
만들어지는지(열·자리표시자·값 개수) 확인한다.
"""
from __future__ import annotations
import re
from typing import Any
import pytest
from app.modules.cupang.db import CupangDBStore
from app.modules.cupang.store import parse_weight_g
def test_parse_weight_g():
assert parse_weight_g("1,070") == 1070
assert parse_weight_g(" 1,070 ") == 1070
assert parse_weight_g("1070g") == 1070
assert parse_weight_g("1070 G") == 1070
assert parse_weight_g("1070.0") == 1070
assert parse_weight_g(450) == 450
assert parse_weight_g("0") == 0
for empty in ("", " ", None):
assert parse_weight_g(empty) is None
for bad in ("abc", "-5", "0.5", "1,000,001", "nan"):
with pytest.raises(ValueError):
parse_weight_g(bad)
class _Cur:
def __init__(self, row):
self._row = row
self.rowcount = 1
def fetchone(self):
return self._row
class _Conn:
def __init__(self, log, row):
self.log, self.row = log, row
def execute(self, sql, params=None):
self.log.append((sql, params))
if "information_schema" in sql:
return _Cur(None)
if sql.lstrip().startswith("SELECT 1 FROM cupang"):
return _Cur(None) # 제품코드 중복·상자 규칙 없음
return _Cur(dict(self.row))
def transaction(self):
return self
def __enter__(self):
return self
def __exit__(self, *a):
return False
class _Pool:
def __init__(self, row):
self.log: list[tuple[str, Any]] = []
self.row = row
def connection(self):
return _Conn(self.log, self.row)
ROW = {"id": 7, "product_code": "MS-9809", "product_name": "미라클통", "coupang_item_code": "",
"active": True, "sort_order": 0, "weight_g": 1070}
def _store(weight: bool) -> tuple[CupangDBStore, _Pool]:
st = CupangDBStore.__new__(CupangDBStore)
pool = _Pool(ROW if weight else {k: v for k, v in ROW.items() if k != "weight_g"})
st._pool = pool
st._weight_col = weight or False
return st, pool
def _main_sql(pool: _Pool, verb: str) -> tuple[str, Any]:
return next((q, p) for q, p in pool.log if q.lstrip().startswith(verb))
def test_upsert_with_weight():
st, pool = _store(True)
out = st.upsert_product(product_code="MS-9809", product_name="미라클통", weight_g=1070)
sql, params = _main_sql(pool, "INSERT")
assert "weight_g)" in sql and "%(w)s)" in sql
assert "weight_g = COALESCE(%(w)s, cupang_products.weight_g)" in sql # 비워 두면 기존 무게 유지
assert params["w"] == 1070
assert set(re.findall(r"%\((\w+)\)s", sql)) <= set(params)
assert out["weight_g"] == 1070
def test_upsert_without_column_ignores_weight():
st, pool = _store(False)
out = st.upsert_product(product_code="MS-9809", product_name="미라클통", weight_g=1070)
sql, _ = _main_sql(pool, "INSERT")
assert "weight_g" not in sql
assert out["weight_g"] is None
def test_update_weight_set_clear_keep():
for weight_arg, expect_col, expect_val in ((950, True, 950), (None, True, None), (..., False, None)):
st, pool = _store(True)
st.update_product(product_id=7, product_name="미라클통", product_code="MS-9809",
weight_g=weight_arg)
sql, params = _main_sql(pool, "UPDATE cupang_products")
assert ("weight_g = %s" in sql) is expect_col, weight_arg
assert sql.count("%s") == len(params) # 자리표시자 = 값 개수
if expect_col:
assert params[-2] == expect_val and params[-1] == 7
def test_update_without_column_ignores_weight():
st, pool = _store(False)
st.update_product(product_id=7, product_name="미라클통", product_code="MS-9809", weight_g=950)
sql, params = _main_sql(pool, "UPDATE cupang_products")
assert "weight_g" not in sql and sql.count("%s") == len(params) == 4
# ── 상자 목록 무게 합계(상자별) ──────────────────────────────────────
class _WStore:
def __init__(self, enabled: bool, weights: dict[str, int | None]):
self.enabled, self.weights = enabled, weights
def weight_enabled(self) -> bool:
return self.enabled
def list_products(self, include_inactive: bool = False):
return [{"product_code": c, "weight_g": w} for c, w in self.weights.items()]
def _boxes():
mt = {"product_name": "멀티 5,000ml x4", "product_code": "MT-5000_4", "quantity": 2}
mix = [{"product_name": "미라클 통 점보 x2", "product_code": "MT-7000_2", "quantity": 6},
{"product_name": "무게 없음", "product_code": "XX-0001", "quantity": 1}]
return [{"no": 1, "kind": "product", "items": [mt]},
{"no": 2, "kind": "mix", "items": mix},
{"no": 3, "kind": "product", "items": [{"product_name": "없음", "product_code": "XX-0001", "quantity": 3}]}]
def test_box_weights():
from app.modules.cupang.router import _attach_box_weights
boxes = _boxes()
assert _attach_box_weights(_WStore(True, {"MT-5000_4": 1800, "MT-7000_2": 1060, "XX-0001": None}), boxes) is True
assert boxes[0]["weight_g"] == 3600 and boxes[0]["weight_missing"] == [] # 2 × 1,800
assert boxes[1]["weight_g"] == 6360 and boxes[1]["weight_missing"] == ["XX-0001"] # 6 × 1,060, 무게 없는 제품은 빼고
assert boxes[2]["weight_g"] is None and boxes[2]["weight_missing"] == ["XX-0001"] # 하나도 모르면 None
plain = _boxes()
assert _attach_box_weights(_WStore(False, {}), plain) is False and "weight_g" not in plain[0]
def test_box_list_workbook_weight_column():
from app.modules.cupang.export import build_box_list_workbook
from app.modules.cupang.router import _attach_box_weights
boxes = _boxes()
_attach_box_weights(_WStore(True, {"MT-5000_4": 1800, "MT-7000_2": 1060}), boxes)
ws = build_box_list_workbook({"ship_date": "2026-10-02", "center_name_snapshot": "대구3"}, boxes, with_weight=True).active
assert [ws.cell(row=2, column=c).value for c in range(1, 6)] == ["상자번호", "제품명", "제품코드", "수량", "무게(g)"]
assert ws.cell(row=3, column=5).value == 3600 and ws.cell(row=4, column=5).value == 6360
assert any(str(r) == "E4:E5" for r in ws.merged_cells.ranges) # 혼합 상자 무게 칸 세로 병합
assert ws.cell(row=6, column=5).value is None
ws2 = build_box_list_workbook({"ship_date": "2026-10-02"}, _boxes()).active # 예전처럼 4열
assert ws2.cell(row=2, column=5).value is None and ws2.cell(row=2, column=4).value == "수량"
def test_g_to_kg_rounds_half_up_to_one_decimal():
"""출고 상세 상자 목록 무게(kg) — 소수 둘째 자리에서 반올림해 첫째 자리까지."""
from app.modules.cupang.router import _g_to_kg
assert _g_to_kg(3000) == "3.0"
assert _g_to_kg(1250) == "1.3" # 1.25 → 1.3 (사사오입)
assert _g_to_kg(1249) == "1.2"
assert _g_to_kg(1234567) == "1,234.6"
assert _g_to_kg(None) is None