Files
dbx-main/tests/test_live.py
T
king 61f5b3c320 feat(라이브커머스): 달력 보기와 호스트 비용 계산 추가
2시간 칸 × 날짜 달력(카드 머리 = Tiktok Handle, SALES·COM·Fee), 끌어 옮기기·
맞바꾸기, Jump to Date, 날짜별 합계·광고비·ROAS 를 넣는다.
호스트 비용 = 시간 × RM 25 + 판매금액 10%, 표 보기에도 표시한다.
끝 시간을 필수로 바꾸고 광고비 표는 마이그레이션 002 로 추가한다.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 16:58:07 +09:00

346 lines
21 KiB
Python
Raw 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.
"""라이브 커머스(live, 2026-11-04).
1) store — 호스트·방송 입력 검사, 판매금액, 달 범위, 표시 형식, 작은 그림.
2) 실제 앱(격리된 하위 프로세스) — 메뉴·권한 칩·"설정 필요" 안내(DB 없이 늘 실행).
3) 전체 흐름(LIVE_TEST_DB_URL 이 localhost 일 때만) — 호스트 등록·권한·스케줄·이미지·지우기.
"""
import io
import os
import subprocess
import sys
import tempfile
import unittest
from datetime import date, time
from decimal import Decimal
from pathlib import Path
from urllib.parse import urlparse
from PIL import Image
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from app.modules.live import store # noqa: E402
DSN = os.getenv("LIVE_TEST_DB_URL", "")
DB_ENABLED = bool(DSN) and urlparse(DSN).hostname in ("localhost", "127.0.0.1")
PRELUDE = '''
from unittest.mock import patch
from fastapi.testclient import TestClient
import app.main as main
def U(email, role="user", live=True):
return {"email": email, "name": email.split("@")[0], "role": role, "is_super_admin": False, "modules": {"live": live}}
who = {"u": None}
def run(body):
with patch.object(main, "get_current_user_record", side_effect=lambda r: who["u"]), \\
patch.object(main, "get_session_user", side_effect=lambda r: who["u"]), \\
patch.object(main.user_store, "get", side_effect=lambda e: who["u"]), \\
patch.object(main.user_store, "list_all", side_effect=lambda: [who["u"]]):
body(TestClient(main.app))
'''
def _run(code: str, extra_env: dict[str, str] | None = None) -> subprocess.CompletedProcess:
env = dict(os.environ)
for key in ("ASSET", "CAFE24", "CUPANG", "VACATION", "PROJECT", "DISPATCH", "PERFORMANCE", "MALAYSIA_STOCK",
"ITEMCODE", "EXPENSE", "INOUT", "OUTREACH", "LIVE"):
env[key + "_DB_URL"] = ""
env.update(SESSION_SECRET_KEY="local-live-test-only", SESSION_COOKIE_SECURE="false", PERFORMANCE_AUTO_SYNC="false")
env.update(extra_env or {})
with tempfile.TemporaryDirectory(prefix="live-web-") as directory:
env["DATA_DIR"] = directory
return subprocess.run([sys.executable, "-c", PRELUDE + code], cwd=ROOT, env=env, capture_output=True,
text=True, encoding="utf-8", timeout=90)
class StoreTests(unittest.TestCase):
def test_clean_host(self):
got = store.clean_host({"full_name": " Siti Aisyah ", "phone": "+60 12-345 6789", "email": "siti@example.my", "address": "KL",
"bank_name": "Maybank", "bank_account": "1234-5678", "tiktok_handle": "@siti.live"})
self.assertEqual((got["full_name"], got["tiktok_handle"]), ("Siti Aisyah", "siti.live"))
self.assertEqual(store.clean_host({"full_name": "A"})["phone"], "") # Full Name 만 필수
for bad in ({}, {"full_name": " "}, {"full_name": "A", "email": "nope"}, {"full_name": "A", "phone": "abc"},
{"full_name": "A", "bank_account": "12a"}, {"full_name": "A", "tiktok_handle": "한글"},
{"full_name": "x" * 201}):
with self.assertRaises(ValueError, msg=bad):
store.clean_host(bad)
def test_clean_handle(self):
for raw in ("@siti.live", "siti.live", "https://www.tiktok.com/@siti.live?lang=en", "tiktok.com/@siti.live/video/1"):
self.assertEqual(store.clean_handle(raw), "siti.live", raw)
def test_parse_money(self):
self.assertIsNone(store.parse_money(""))
self.assertEqual(store.parse_money("RM 1,234.5"), Decimal("1234.50"))
self.assertEqual(store.parse_money("0"), Decimal("0.00"))
for bad in ("-1", "abc", "NaN", "Infinity", "1e20"):
with self.assertRaises(ValueError, msg=bad):
store.parse_money(bad)
def test_clean_broadcast(self):
got = store.clean_broadcast({"host_id": "3", "broadcast_date": "2026-11-04", "start_time": "20:00", "end_time": "22:00",
"venue": " Studio ", "sales_amount": "100"})
self.assertEqual(got, {"host_id": 3, "broadcast_date": date(2026, 11, 4), "start_time": time(20, 0), "end_time": time(22, 0),
"venue": "Studio", "sales_amount": Decimal("100.00")})
good = {"host_id": "3", "broadcast_date": "2026-11-04", "start_time": "20:00", "end_time": "22:00"}
for over in ({"host_id": ""}, {"host_id": "x"}, {"broadcast_date": ""}, {"broadcast_date": "2026-13-01"}, {"start_time": ""},
{"start_time": "25:00"}, {"end_time": ""}, {"end_time": "nope"}, {"end_time": "20:00"}, {"venue": "x" * 201}, {"sales_amount": "-5"}):
with self.assertRaises(ValueError, msg=over):
store.clean_broadcast({**good, **over})
def test_month_range(self):
today = date(2026, 11, 4)
self.assertEqual(store.month_range("", today)["label"], "2026년 11월")
self.assertEqual(store.month_range("bad", today)["start"], date(2026, 11, 1))
self.assertEqual(store.month_range("2026-13", today)["start"], date(2026, 11, 1))
dec = store.month_range("2026-12", today)
self.assertEqual((dec["start"], dec["end"], dec["prev"], dec["next"]), (date(2026, 12, 1), date(2027, 1, 1), "2026-11", "2027-01"))
jan = store.month_range("2027-01", today)
self.assertEqual((jan["end"], jan["prev"], jan["next"]), (date(2027, 2, 1), "2026-12", "2027-02"))
def test_format(self):
self.assertEqual(store.fmt_date(date(2026, 11, 4)), "2026.11.04(수)")
self.assertEqual(store.fmt_times(time(20, 0), time(22, 30)), "20:00 ~ 22:30")
self.assertEqual(store.fmt_times(time(20, 0), None), "20:00")
self.assertEqual(store.fmt_money(Decimal("1234.5")), "1,234.50")
self.assertEqual(store.fmt_money(None), "")
def test_session_pay(self):
"""호스트 비용 = 시간 × RM 25 + 판매금액 10%. 받은 화면의 예: 2시간·판매 48 → 50 + 4.8."""
p = store.session_pay(time(12, 0), time(14, 0), Decimal("48"))
self.assertEqual((p["base"], p["commission"], p["fee"]), (Decimal("50.00"), Decimal("4.80"), Decimal("54.80")))
self.assertEqual(store.session_pay(time(22, 0), time(0, 0), None)["fee"], Decimal("50.00")) # 자정까지
self.assertEqual(store.session_pay(time(23, 0), time(1, 30), None)["base"], Decimal("62.50")) # 자정 넘김·30분
self.assertEqual(store.session_pay(time(12, 0), None, Decimal("10"))["fee"], Decimal("1.00")) # 끝 시간 없음 = 기본 요금 없음
self.assertEqual(store.session_pay(time(12, 0), time(14, 0), Decimal("0.05"))["commission"], Decimal("0.01")) # 반올림
self.assertEqual((store.fmt_short(Decimal("48")), store.fmt_short(Decimal("4.80")), store.fmt_short(Decimal("1234.5"))), ("48", "4.80", "1,234.50"))
def test_moved_end(self):
self.assertEqual(store.moved_end(time(12, 0), time(14, 30), time(20, 0)), time(22, 30))
self.assertEqual(store.moved_end(time(12, 0), time(14, 0), time(22, 0)), time(0, 0)) # 자정으로 넘어감
self.assertIsNone(store.moved_end(time(12, 0), None, time(20, 0)))
self.assertEqual(store.parse_move("2026-11-04", "20:00"), (date(2026, 11, 4), time(20, 0)))
for bad in (("", "20:00"), ("2026-11-04", ""), ("nope", "20:00")):
with self.assertRaises(ValueError):
store.parse_move(*bad)
def test_build_calendar(self):
def b(id, day, start, end, sales=None, host=1, handle="yaya"):
return {"id": id, "host_id": host, "host_name": "Yaya", "tiktok_handle": handle, "broadcast_date": day, "start_time": start,
"end_time": end, "venue": "", "sales_amount": sales, "images": []}
span = store.month_range("2026-11", date(2026, 11, 4))
cal = store.build_calendar(span, [b(1, date(2026, 11, 4), time(12, 0), time(14, 0), Decimal("48")),
b(2, date(2026, 11, 4), time(22, 0), time(0, 0), handle=""),
b(3, date(2026, 11, 7), time(13, 30), time(15, 0))],
{date(2026, 11, 4): Decimal("24")}, date(2026, 11, 4))
self.assertEqual(len(cal["days"]), 30)
self.assertEqual([s["label"] for s in cal["slots"]][0], "06:00 - 08:00")
self.assertEqual([s["label"] for s in cal["slots"]][-1], "22:00 - 00:00")
self.assertEqual(len(cal["slots"]), 9)
self.assertEqual(cal["slot_note"], "2 Hours (RM50 Base)")
d4 = cal["days"][3]
self.assertEqual((d4["weekday"], d4["label"], d4["count"], d4["is_today"], d4["is_weekend"]), ("WEDNESDAY", "4 NOV", 2, True, False))
self.assertEqual((d4["sales_text"], d4["spend_text"], d4["fee_text"], d4["roas"]), ("48", "24", "104.80", "2.00"))
self.assertEqual(cal["days"][6]["is_weekend"], True) # 11-07 토
self.assertEqual(cal["days"][0]["roas"], "-") # 광고비 없음
noon = next(s for s in cal["slots"] if s["start"] == "12:00")
self.assertEqual(noon["cells"][3]["cards"][0]["label"], "yaya") # 카드 머리 = Tiktok Handle
self.assertEqual((noon["cells"][3]["cards"][0]["card_sales"], noon["cells"][3]["cards"][0]["card_commission"], noon["cells"][3]["cards"][0]["card_fee"]),
("48", "4.80", "54.80"))
late = next(s for s in cal["slots"] if s["start"] == "22:00")
self.assertEqual((late["end"], late["cells"][3]["cards"][0]["label"]), ("00:00", "Yaya")) # 핸들 없으면 이름
self.assertEqual(next(s for s in cal["slots"] if s["start"] == "12:00")["cells"][6]["cards"][0]["id"], 3) # 13:30 = 12~14 칸
self.assertEqual(cal["totals"]["sales"], "48")
# 06시보다 이른 칸은 방송이 있을 때만
early = store.build_calendar(span, [b(9, date(2026, 11, 1), time(3, 0), time(5, 0))], {}, date(2026, 11, 4))
self.assertEqual(early["slots"][0]["label"], "02:00 - 04:00")
self.assertEqual(len(early["slots"]), 10)
def test_thumbnail(self):
for mode, fmt in (("RGB", "JPEG"), ("RGBA", "PNG")):
raw = io.BytesIO()
Image.new(mode, (800, 400)).save(raw, format=fmt)
with Image.open(io.BytesIO(store.thumbnail(raw.getvalue()))) as im:
self.assertEqual((im.format, im.size), ("JPEG", (160, 80)))
class WebTests(unittest.TestCase):
def test_registered_and_unconfigured(self):
res = _run('''
from app.store import MODULE_KEYS
assert "live" in MODULE_KEYS and main.MODULE_LABELS["live"] == "라이브 커머스"
def body(c):
who["u"] = U("a@test.local", role="admin")
assert c.get("/live/health").json() == {"status": "not_configured"}
r = c.get("/live/")
assert r.status_code == 503 and "LIVE_DB_URL" in r.text and "라이브 커머스" in r.text, r.status_code
assert c.post("/live/broadcasts", data={}).status_code == 503
who["u"] = U("b@test.local", live=False)
assert c.get("/live/").status_code == 403
assert c.post("/live/broadcasts", data={}).status_code == 403
assert c.get("/live/images/1").status_code == 403
print("OK")
run(body)
''')
self.assertEqual(res.returncode, 0, res.stdout + res.stderr)
self.assertIn("OK", res.stdout)
@unittest.skipUnless(DB_ENABLED, "LIVE_TEST_DB_URL(localhost) not set")
def test_full_flow(self):
res = _run('''
import io, re, uuid
from PIL import Image
from app.modules.live.db import LiveDBStore
st = LiveDBStore(__import__("os").environ["LIVE_TEST_DB_URL"])
main.app.state.live_store = st
tag = uuid.uuid4().hex[:8]
admin, staff, outsider = U("admin-%s@t.local" % tag, role="admin"), U("staff-%s@t.local" % tag), U("out-%s@t.local" % tag, live=False)
ACCOUNT = "9988%s" % int(tag, 16)
NAME = "Siti <b>" + tag
def jpeg():
raw = io.BytesIO()
exif = Image.Exif(); exif[0x010F] = "SECRET-CAMERA"
Image.new("RGB", (3000, 1500), "red").save(raw, format="JPEG", exif=exif)
return raw.getvalue()
def body(c):
host = {"full_name": NAME, "phone": "+60 12-345", "email": "siti@example.my", "address": "Kuala Lumpur",
"bank_name": "Maybank", "bank_account": ACCOUNT, "tiktok_handle": "@siti.%s" % tag, "is_active": "1"}
# ── 호스트 설정 = ERP 관리자만 ──
who["u"] = staff
assert c.get("/live/settings").status_code == 403
assert c.post("/live/settings/hosts", data=host).status_code == 403
assert c.post("/live/settings/hosts/1/delete").status_code == 403
assert 'href="/live/settings"' not in c.get("/live/").text
who["u"] = admin
bad = c.post("/live/settings/hosts", data={**host, "email": "nope"})
assert bad.status_code == 400 and "Email" in bad.json()["message"]
r = c.post("/live/settings/hosts", data=host)
assert r.json()["ok"], r.text
hid = next(h["id"] for h in st.list_hosts() if h["full_name"] == NAME)
page = c.get("/live/settings").text
for field in ("Full Name (as per IC)", "Phone Number", "Email", "Address", "Bank Name", "Bank Account Number", "Tiktok Handle"):
assert field in page, field
assert ACCOUNT in page and "Siti &lt;b&gt;" in page and "<b>" + tag not in page
assert st.list_hosts() and next(h for h in st.list_hosts() if h["id"] == hid)["tiktok_handle"] == "siti." + tag
# ── 스케줄: 일반 권한자도 추가·고치기, 화면에 계좌·주소 없음 ──
who["u"] = staff
page = c.get("/live/?month=2031-03").text
assert 'value="%d"' % hid in page and "@siti." + tag in page
assert ACCOUNT not in page and "Kuala Lumpur" not in page and "Maybank" not in page
show = {"host_id": hid, "broadcast_date": "2031-03-05", "start_time": "20:00", "end_time": "22:30", "venue": "KL Studio", "sales_amount": "1,234.5"}
assert c.post("/live/broadcasts", data={**show, "host_id": ""}).status_code == 400
assert c.post("/live/broadcasts", data={**show, "host_id": 99999999}).status_code == 400
junk = c.post("/live/broadcasts", data=show, files=[("images", ("x.jpg", b"not an image", "image/jpeg"))])
assert junk.status_code == 400 and "x.jpg" in junk.json()["message"]
assert "KL Studio" not in c.get("/live/?month=2031-03").text # 이미지가 틀리면 방송도 저장 안 됨
r = c.post("/live/broadcasts", data=show, files=[("images", ("../../evil.jpg", jpeg(), "image/jpeg"))])
assert r.json()["ok"], r.text
page = c.get("/live/?month=2031-03").text
assert "2031.03.05(수)" in page and "20:00 ~ 22:30" in page and "KL Studio" in page and "1,234.50" in page
assert ">123.45</td>" in page and ">185.95</td>" in page # 커미션 10%·호스트 비용(2.5시간 × 25 + 123.45)
assert "KL Studio" not in c.get("/live/?month=2031-04").text
row = st.list_broadcasts(__import__("datetime").date(2031, 3, 1), __import__("datetime").date(2031, 4, 1))
row = next(b for b in row if b["host_id"] == hid)
bid, img = row["id"], row["images"][0]
assert img["filename"] == "evil.jpg" and len(row["images"]) == 1 # 파일 이름의 경로 제거
# ── 이미지: 크기 줄임·EXIF 제거·권한 ──
r = c.get("/live/images/%d" % img["id"])
assert r.status_code == 200 and r.headers["content-type"] == "image/jpeg" and "private" in r.headers["cache-control"]
assert b"SECRET-CAMERA" not in r.content
assert Image.open(io.BytesIO(r.content)).size == (2400, 1200)
assert Image.open(io.BytesIO(c.get("/live/images/%d?thumb=1" % img["id"]).content)).size == (160, 80)
assert c.get("/live/images/99999999").status_code == 404
who["u"] = outsider
assert c.get("/live/images/%d" % img["id"]).status_code == 403
assert c.post("/live/images/%d/delete" % img["id"]).status_code == 403
who["u"] = staff
# ── 고치기: 값 바뀜, 이미지 유지 + 더하기, 판매금액 지우기, 10장 제한 ──
r = c.post("/live/broadcasts", data={**show, "id": bid, "venue": "PJ Studio", "sales_amount": "", "end_time": "21:00"})
assert r.json()["ok"], r.text
page = c.get("/live/?month=2031-03").text
assert "PJ Studio" in page and "1,234.50" not in page and "20:00 ~ 21:00" in page
assert c.post("/live/broadcasts", data={**show, "end_time": ""}).status_code == 400 # 끝 시간 필수
# ── 달력: 카드 머리 = Tiktok Handle, Fee, 옮기기(길이 유지)·맞바꾸기, 광고비·ROAS, 권한 ──
c.post("/live/broadcasts", data={**show, "id": bid, "sales_amount": "48", "start_time": "12:00", "end_time": "14:00", "broadcast_date": "2031-03-05"})
cal = c.get("/live/calendar?month=2031-03").text
assert "Jump to Date" in cal and "SATURDAY" in cal and "12:00 - 14:00" in cal and "2 Hours (RM50 Base)" in cal
assert '<span class="lv-card-name">siti.%s</span>' % tag in cal and "RM54.80" in cal and ">4.80</b>" in cal
assert ACCOUNT not in cal and "Maybank" not in cal
day = __import__("datetime").date
def one(i):
return next(b for b in st.list_broadcasts(day(2031, 3, 1), day(2031, 4, 1)) if b["id"] == i)
assert c.post("/live/broadcasts/%d/move" % bid, data={"broadcast_date": "2031-03-07", "start_time": "22:00"}).json()["ok"]
got = one(bid)
assert (got["broadcast_date"], str(got["start_time"]), str(got["end_time"])) == (day(2031, 3, 7), "22:00:00", "00:00:00")
assert c.post("/live/broadcasts/%d/move" % bid, data={"broadcast_date": "bad", "start_time": "22:00"}).status_code == 400
assert c.post("/live/broadcasts/99999999/move", data={"broadcast_date": "2031-03-07", "start_time": "22:00"}).status_code == 400
c.post("/live/broadcasts", data={**show, "broadcast_date": "2031-03-09", "start_time": "08:00", "end_time": "09:00", "venue": "Second"})
other = next(b["id"] for b in st.list_broadcasts(day(2031, 3, 9), day(2031, 3, 10)) if b["venue"] == "Second")
assert c.post("/live/broadcasts/%d/move" % bid, data={"swap_with": other}).json()["ok"]
a, b2 = one(bid), one(other)
assert (a["broadcast_date"], str(a["start_time"]), str(a["end_time"])) == (day(2031, 3, 9), "08:00:00", "09:00:00")
assert (b2["broadcast_date"], str(b2["start_time"]), str(b2["end_time"])) == (day(2031, 3, 7), "22:00:00", "00:00:00")
assert c.post("/live/broadcasts/%d/move" % bid, data={"swap_with": 99999999}).status_code == 400
assert c.post("/live/broadcasts/%d/move" % bid, data={"swap_with": bid}).json()["ok"]
assert c.post("/live/ad-spend", data={"day": "2031-03-09", "amount": "24"}).json()["ok"]
assert c.post("/live/ad-spend", data={"day": "2031-03-09", "amount": "12"}).json()["ok"] # 덮어쓰기
assert st.ad_spends(day(2031, 3, 1), day(2031, 4, 1)) == {day(2031, 3, 9): __import__("decimal").Decimal("12.00")}
assert c.post("/live/ad-spend", data={"day": "2031-03-09", "amount": "-1"}).status_code == 400
assert c.post("/live/ad-spend", data={"day": "bad", "amount": "1"}).status_code == 400
assert "4.00" in c.get("/live/calendar?month=2031-03").text # ROAS 48 ÷ 12
assert c.post("/live/ad-spend", data={"day": "2031-03-09", "amount": ""}).json()["ok"] # 빈칸 = 지우기
assert st.ad_spends(day(2031, 3, 1), day(2031, 4, 1)) == {}
assert c.post("/live/broadcasts/%d/delete" % other).json()["ok"]
c.post("/live/broadcasts", data={**show, "id": bid}) # 아래 시험을 위해 원래 값으로
who["u"] = outsider
assert c.get("/live/calendar").status_code == 403
assert c.post("/live/broadcasts/%d/move" % bid, data={"swap_with": bid}).status_code == 403
assert c.post("/live/ad-spend", data={"day": "2031-03-09", "amount": "1"}).status_code == 403
who["u"] = staff
many = [("images", ("%d.jpg" % i, jpeg(), "image/jpeg")) for i in range(10)]
r = c.post("/live/broadcasts", data={**show, "id": bid}, files=many)
assert r.status_code == 400 and "10장" in r.json()["message"], r.text # 이미 1장 + 10장
assert c.post("/live/broadcasts", data={**show, "id": 99999999}).status_code == 400
assert c.post("/live/broadcasts", data={**show, "id": "x"}).status_code == 400
# ── 호스트: 방송이 있으면 못 지움, 사용 안 함이면 새 방송 불가·기존 방송 고치기는 가능 ──
who["u"] = admin
r = c.post("/live/settings/hosts/%d/delete" % hid)
assert r.status_code == 400 and "사용 안 함" in r.json()["message"]
assert c.post("/live/settings/hosts", data={**host, "id": hid, "is_active": ""}).json()["ok"]
who["u"] = staff
assert 'data-inactive="1"' in c.get("/live/?month=2031-03").text
r = c.post("/live/broadcasts", data=show)
assert r.status_code == 400 and "사용 안 함" in r.json()["message"]
assert c.post("/live/broadcasts", data={**show, "id": bid}).json()["ok"]
# ── 지우기: 이미지 하나, 방송(이미지도), 그 뒤 호스트 ──
assert c.post("/live/images/%d/delete" % img["id"]).json()["ok"]
assert c.get("/live/images/%d" % img["id"]).status_code == 404
assert c.post("/live/broadcasts", data={**show, "id": bid}, files=[("images", ("a.png", jpeg(), "image/jpeg"))]).json()["ok"]
assert c.post("/live/broadcasts/%d/delete" % bid).json()["ok"]
assert c.post("/live/broadcasts/%d/delete" % bid).status_code == 400
who["u"] = admin
assert c.post("/live/settings/hosts/%d/delete" % hid).json()["ok"]
assert c.post("/live/settings/hosts/%d/delete" % hid).status_code == 400
print("OK")
run(body)
''', {"LIVE_TEST_DB_URL": DSN})
self.assertEqual(res.returncode, 0, res.stdout + res.stderr)
self.assertIn("OK", res.stdout)
if __name__ == "__main__":
unittest.main()