Files
dbx-main/tests/test_live.py
T
king cf0e3f2139 feat(라이브): 달력 보기 오른쪽에 공용 달력과 말레이시아 공휴일
표 오른쪽에 erp-datepop 붙박이 달력을 두고, 날짜를 누르면 그 날이 표 맨 왼쪽에 오게 한다.
다른 달을 누르면 그 달 화면으로 이동해 같은 위치로 맞춘다. 마지막 날도 맨 왼쪽에 오도록 표 끝에 여백을 둔다.
말레이시아 공휴일·대체휴일 표(holidays.py, 쿠알라룸푸르 기준 2026·2027)를 표시한다.
공용 달력에 선택 옵션 locale 을 추가해 영문 화면도 영어로 그린다. 기존 화면 동작은 그대로.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 18:50:29 +09:00

613 lines
36 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 re
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 i18n, 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({"display_name": " Siti ", "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["display_name"], got["full_name"]), ("Siti", "Siti Aisyah"))
self.assertNotIn("tiktok_handle", got) # 계정은 방송마다 — 호스트에는 저장 안 함
self.assertEqual(store.clean_host({"display_name": "A", "full_name": "A"})["phone"], "") # 두 이름만 필수
ok = {"display_name": "A", "full_name": "A"}
for bad in ({}, {"full_name": "A"}, {"display_name": "A"}, {**ok, "full_name": " "}, {**ok, "email": "nope"}, {**ok, "phone": "abc"},
{**ok, "bank_account": "12a"}, {**ok, "full_name": "x" * 201}, {**ok, "display_name": "x" * 51}):
with self.assertRaises(ValueError, msg=bad):
store.clean_host(bad)
def test_broadcast_account(self):
good = {"host_id": "3", "broadcast_date": "2026-11-04", "start_time": "20:00", "end_time": "22:00"}
self.assertEqual(store.clean_broadcast(good)["tiktok_handle"], "") # 선택 칸
self.assertEqual(store.clean_broadcast({**good, "tiktok_handle": "https://www.tiktok.com/@alt.acc?lang=en"})["tiktok_handle"], "alt.acc")
for bad in ("한글", "x" * 65):
with self.assertRaises(ValueError, msg=bad):
store.clean_broadcast({**good, "tiktok_handle": bad})
def test_edit_keeps_broadcast_account(self):
"""고치기 창에 계정이 채워져야 저장하면서 지워지지 않는다."""
view = store.broadcast_view({"id": 1, "host_id": 2, "host_name": "Yaya", "tiktok_handle": "alt.acc", "broadcast_date": date(2026, 11, 4),
"start_time": time(20, 0), "end_time": time(22, 0), "venue": "", "sales_amount": None, "images": []})
self.assertEqual((view["tiktok_handle"], view["edit"]["tiktok_handle"], view["label"]), ("alt.acc", "alt.acc", "Yaya")) # 카드 머리 = 호스트, 계정은 아래
def test_my_holidays(self):
from app.modules.live import holidays
ko, en = holidays.holiday_names("ko"), holidays.holiday_names("en")
self.assertEqual(set(ko), set(en))
for day in ko:
date.fromisoformat(day)
self.assertEqual((ko["2026-11-08"], ko["2026-11-09"]), ("디파발리", "디파발리 대체"))
self.assertEqual((en["2026-11-08"], en["2026-11-09"]), ("Deepavali", "Deepavali (Replacement)"))
self.assertIn("Federal Territory Day", en["2026-02-01"])
self.assertFalse([n for n in en.values() if re.search("[가-힣]", n)])
# 대체휴일은 평일에 — 토·일이면 표가 틀린 것
for day, name in en.items():
if "Replacement" in name:
self.assertLess(date.fromisoformat(day).weekday(), 5, day)
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", "tiktok_handle": "", "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("", today, "en")["label"], "November 2026")
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_date(date(2026, 11, 4), "en"), "2026.11.04 (Wed)")
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), "en")
ko = store.build_calendar(span, [], {}, date(2026, 11, 4))
self.assertEqual((ko["days"][3]["weekday"], ko["days"][3]["label"], ko["slot_note"]), ("수요일", "11월 4일", "2시간 (기본 RM50)"))
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") # 카드 머리 = 호스트 간단한 이름
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 I18nTests(unittest.TestCase):
def test_every_text_has_english(self):
"""템플릿·오류·권한 문구가 모두 영문 표에 있다 — 새 문구를 넣고 빠뜨리면 여기서 걸린다."""
live = ROOT / "app" / "modules" / "live"
keys = set(i18n.JS_KEYS) | set(store._LABELS.values()) | {"시작 시간", "끝 시간"}
for path in (live / "templates" / "live").glob("*.html"):
keys |= set(re.findall(r"\bt\('([^']+)'\)", path.read_text(encoding="utf-8")))
for name in ("store.py", "db.py", "router.py"):
text = (live / name).read_text(encoding="utf-8")
keys |= set(re.findall(r'LiveError\("([^"]+)"', text))
keys |= set(re.findall(r'_t\(request, "([^"]+)"\)', text))
keys |= set(re.findall(r'_ok\(request, "([^"]+)"\)', text))
keys |= set(re.findall(r'raise ValueError\("([^"]+)"', text))
keys |= set(re.findall(r'ValueError\("([^"]+)"', (ROOT / "app" / "modules" / "asset" / "media.py").read_text(encoding="utf-8")))
self.assertGreater(len(keys), 80)
self.assertEqual(sorted(k for k in keys if k not in i18n.EN), [])
self.assertEqual(sorted(k for k, v in i18n.EN.items() if re.search("[가-힣]", v)), [])
def test_error_text(self):
err = i18n.LiveError("{label} 이(가) 너무 깁니다({limit}자까지).", label="이메일", limit=254)
self.assertEqual(str(err), "이메일 이(가) 너무 깁니다(254자까지).")
self.assertEqual(i18n.error_text(err, "en"), "Email is too long (up to 254 characters).")
self.assertEqual(i18n.error_text(err, "ko"), str(err))
self.assertEqual(i18n.error_text(ValueError("잘못된 요청입니다."), "en"), "Invalid request.")
nested = i18n.LiveError("{name}: {detail}", name="a{b}.jpg", detail="JPG, PNG, WebP 사진만 등록할 수 있습니다.")
self.assertEqual(nested.text("en"), "a{b}.jpg: Only JPG, PNG and WebP images are allowed.")
self.assertEqual((i18n.norm_lang("en"), i18n.norm_lang("ko"), i18n.norm_lang("<x>"), i18n.norm_lang(None)), ("en", "ko", "ko", "ko"))
class WebTests(unittest.TestCase):
def test_main_card_title_both_languages(self):
res = _run('''
def body(c):
who["u"] = U("a@test.local", role="admin")
page = c.get("/modules").text # 카드 화면(수퍼관리자 홈과 같은 main.html)
assert "라이브 커머스 · Live Commerce" in page, page[:300]
nav = [i for i in main.build_erp_nav(who["u"], active="live") if i["key"] == "live"]
assert nav and nav[0]["label"] == "라이브 커머스" # 사이드바는 짧게
print("OK")
run(body)
''')
self.assertEqual(res.returncode, 0, res.stdout + res.stderr)
self.assertIn("OK", res.stdout)
def test_live_host_chip_adds_only(self):
"""`live_host` 칩 = 새 호스트 등록만 — 계좌 안 보임, 고치기·지우기·사용 안 함 불가. DB 없이 가짜 저장소로."""
res = _run('''
from app.store import MODULE_KEYS
assert "live_host" in MODULE_KEYS and "live_host" in main.MODULE_LABELS
class Fake:
saved = []
def host_choices(self):
return [{"id": 1, "display_name": "Siti", "full_name": "Siti Binti Awa", "is_active": True}]
def list_hosts(self):
return [{"id": 1, "display_name": "Siti", "full_name": "Siti Binti Awa", "phone": "012", "email": "s@e.my", "address": "KL", "bank_name": "Maybank",
"bank_account": "998877", "is_active": True}]
def list_broadcasts(self, start, end):
return []
def account_choices(self):
return ["MainAccount", "alt.acc"]
def save_host(self, host_id, values, *, is_active, by):
self.saved.append((host_id, values["full_name"], is_active, by))
return 2
def delete_host(self, host_id):
self.saved.append(("deleted", host_id))
fake = main.app.state.live_store = Fake()
adder = U("adder@t.local"); adder["modules"]["live_host"] = True
chip_only = U("chip@t.local", live=False); chip_only["modules"]["live_host"] = True
new = {"display_name": "Newbie", "full_name": "New Host", "bank_account": "111"}
def body(c):
who["u"] = adder
sched = c.get("/live/").text
assert 'href="/live/settings"' in sched and 'name="tiktok_handle"' in sched and '<option value="alt.acc">' in sched
page = c.get("/live/settings")
assert page.status_code == 200 and "Siti" in page.text and 'name="full_name"' in page.text
for hidden in ("998877", "Maybank", "s@e.my", 'name="tiktok_handle"', "data-edit='", "/delete", 'name="is_active"'):
assert hidden not in page.text, hidden
assert c.post("/live/settings/hosts", data=new).json()["ok"]
assert fake.saved == [(None, "New Host", True, "adder@t.local")], fake.saved
assert c.post("/live/settings/hosts", data={**new, "id": "1"}).status_code == 403
assert c.post("/live/settings/hosts/1/delete").status_code == 403
assert len(fake.saved) == 1, fake.saved
for no_add in (U("staff@t.local"), chip_only):
who["u"] = no_add
assert c.get("/live/settings").status_code == 403
assert c.post("/live/settings/hosts", data=new).status_code == 403
assert len(fake.saved) == 1, fake.saved
# 관리자는 그대로 — 계좌 보임, 고치기, 사용 안 함
who["u"] = U("a@t.local", role="admin")
page = c.get("/live/settings").text
assert "998877" in page and "data-edit='" in page and 'name="is_active"' in page
assert c.post("/live/settings/hosts", data={**new, "id": "1"}).json()["ok"]
assert fake.saved[-1] == (1, "New Host", False, "a@t.local"), fake.saved
print("OK")
run(body)
''')
self.assertEqual(res.returncode, 0, res.stdout + res.stderr)
self.assertIn("OK", res.stdout)
def test_live_host_edit_chip(self):
"""`live_host_edit` 칩 = 고치기 — 개인정보는 페이지에 없고, 빈칸은 그대로·입력하면 바뀜, 등록·지우기는 안 됨."""
res = _run('''
from app.store import MODULE_KEYS
assert "live_host_edit" in MODULE_KEYS and main.MODULE_LABELS["live_host_edit"] == "라이브 호스트 수정"
OLD = {"id": 1, "display_name": "Siti", "full_name": "Siti Binti Awa", "phone": "012", "email": "s@e.my", "address": "KL", "bank_name": "Maybank",
"bank_account": "998877", "is_active": True}
class Fake:
saved = []
def host_choices(self):
return [{k: OLD[k] for k in ("id", "display_name", "full_name", "is_active")}]
def list_hosts(self):
return [OLD]
def get_host(self, host_id):
return OLD if host_id == 1 else None
def list_broadcasts(self, start, end):
return []
def account_choices(self):
return []
def save_host(self, host_id, values, *, is_active, by):
self.saved.append((host_id, values, is_active))
return 1
def delete_host(self, host_id):
self.saved.append(("deleted", host_id))
fake = main.app.state.live_store = Fake()
editor = U("edit@t.local"); editor["modules"]["live_host_edit"] = True
chip_only = U("chip@t.local", live=False); chip_only["modules"]["live_host_edit"] = True
form = {"id": "1", "display_name": "Nabella", "full_name": "Siti Binti Awa", "is_active": "1"}
def body(c):
who["u"] = editor
assert \'href="/live/settings"\' in c.get("/live/").text
page = c.get("/live/settings").text
for hidden in ("998877", "Maybank", "s@e.my", "/delete", \'id="lv-add"\'):
assert hidden not in page, hidden
assert "data-edit=\'" in page and "Siti Binti Awa" in page and \'name="is_active"\' in page and "data-edit-only" in page
assert c.post("/live/settings/hosts", data=form).json()["ok"]
host_id, values, active = fake.saved[-1]
assert host_id == 1 and active is True and values["display_name"] == "Nabella"
assert (values["bank_account"], values["phone"], values["address"]) == ("998877", "012", "KL") # 빈칸 = 그대로
assert c.post("/live/settings/hosts", data={**form, "bank_account": "111-222"}).json()["ok"]
assert fake.saved[-1][1]["bank_account"] == "111-222" and fake.saved[-1][1]["phone"] == "012" # 입력 = 바뀜
assert c.post("/live/settings/hosts", data={**form, "is_active": ""}).json()["ok"] and fake.saved[-1][2] is False
assert c.post("/live/settings/hosts", data={**form, "id": "9"}).status_code == 400 # 없는 호스트
assert c.post("/live/settings/hosts", data={**form, "display_name": ""}).status_code == 400 # 간단한 이름 필수
count = len(fake.saved)
assert c.post("/live/settings/hosts", data={**form, "id": ""}).status_code == 403 # 등록 권한 없음
assert c.post("/live/settings/hosts/1/delete").status_code == 403
for no_edit in (U("staff@t.local"), chip_only):
who["u"] = no_edit
assert c.get("/live/settings").status_code == 403
assert c.post("/live/settings/hosts", data=form).status_code == 403
assert len(fake.saved) == count
# 관리자는 빈칸 = 지우기 그대로
who["u"] = U("a@t.local", role="admin")
assert c.post("/live/settings/hosts", data=form).json()["ok"] and fake.saved[-1][1]["bank_account"] == ""
print("OK")
run(body)
''')
self.assertEqual(res.returncode, 0, res.stdout + res.stderr)
self.assertIn("OK", res.stdout)
def test_calendar_page_side_calendar(self):
res = _run('''
import json, re
class Fake:
def host_choices(self):
return []
def list_broadcasts(self, start, end):
return []
def ad_spends(self, start, end):
return {}
def account_choices(self):
return []
main.app.state.live_store = Fake()
def names(page):
return json.loads(re.search(r'id="lv-my-holidays">(.*?)</script>', page).group(1))
def body(c):
who["u"] = U("s@t.local")
page = c.get("/live/calendar?month=2026-11").text
assert 'id="lv-side-cal"' in page and "/static/erp-datepop.js" in page
assert names(page)["2026-11-09"] == "디파발리 대체"
c.cookies.set("live_lang", "en")
assert names(c.get("/live/calendar?month=2026-11").text)["2026-11-09"] == "Deepavali (Replacement)"
print("OK")
run(body)
''')
self.assertEqual(res.returncode, 0, res.stdout + res.stderr)
self.assertIn("OK", res.stdout)
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 = {"display_name": "S" + tag, "full_name": NAME, "phone": "+60 12-345", "email": "siti@example.my", "address": "Kuala Lumpur",
"bank_name": "Maybank", "bank_account": ACCOUNT, "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 "이메일" 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 ("이름 (IC 기준)", "전화번호", "이메일", "주소", "은행명", "계좌번호"):
assert field in page, field
assert ACCOUNT in page and "Siti &lt;b&gt;" in page and "<b>" + tag not in page
assert "틱톡 핸들" not in page and 'name="tiktok_handle"' not in page # 계정은 방송마다
# ── 스케줄: 일반 권한자도 추가·고치기, 화면에 계좌·주소 없음 ──
who["u"] = staff
page = c.get("/live/?month=2031-03").text
assert 'value="%d"' % hid 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", "tiktok_handle": "@siti.%s" % tag, "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 "날짜로 이동" in cal and "토요일" in cal and "12:00 - 14:00" in cal and "2시간 (기본 RM50)" in cal
assert '<span class="lv-card-name">S%s<small>@siti.%s</small></span>' % (tag, tag) in cal and "RM54.80" in cal and ">4.80</b>" in cal
# ── 영문: 화면 세 개 모두 한글 없음(입력한 데이터 제외)·날짜·오류·권한 문구 ──
def no_korean(url):
page = c.get(url).text
assert 'class="lv-lang"' in page and "window.LV_T" in page
part = page[page.index('<section class="lv"'):page.index("</dialog>")].replace(">한글<", "><") # 화면 + 창(공용 셸 제외)
left = re.findall("[가-힣][^<>\\"]*", part)
assert not left, (url, left[:5])
return page
c.cookies.set("live_lang", "en")
page = no_korean("/live/?month=2031-03")
assert 'lang="en"' in page and "March 2031" in page and "2031.03.05 (Wed)" in page and "Commission 10% (RM)" in page
cal = no_korean("/live/calendar?month=2031-03")
assert "Jump to Date" in cal and "SATURDAY" in cal and "1 MAR" in cal and "2 Hours (RM50 Base)" in cal and ">Sales<" in cal and "Com (10%)" in cal and "Fee: <b>RM54.80" in cal
assert "Total Sales:" in cal and "Ad Spend:" in cal and "Host Fee:" in cal and "Total &amp; ROAS" in cal
assert c.post("/live/broadcasts", data={**show, "id": bid, "sales_amount": "abc"}).json()["message"] == "Sales must be a number."
assert c.post("/live/broadcasts", data={**show, "id": bid, "end_time": ""}).json()["message"] == "Enter the End Time."
junk = c.post("/live/broadcasts", data=show, files=[("images", ("x.jpg", b"not an image", "image/jpeg"))]).json()["message"]
assert junk == "x.jpg: The image can't be read. Please choose a valid JPG, PNG or WebP file.", junk
assert c.post("/live/settings/hosts", data=host).json()["detail"] == "Only ERP admins can view host information."
assert c.post("/live/ad-spend", data={"day": "2031-03-09", "amount": "1"}).json()["message"] == "Ad spend saved."
assert c.post("/live/ad-spend", data={"day": "2031-03-09", "amount": ""}).json()["ok"]
who["u"] = admin
page = no_korean("/live/settings")
for field in ("Full Name (as per IC)", "Phone Number", "Email", "Address", "Bank Name", "Bank Account Number", "Tiktok Handle"):
assert field in page, field
who["u"] = staff
c.cookies.set("live_lang", "<bad>") # 모르는 값 = 한글
assert "2031년 3월" in c.get("/live/?month=2031-03").text
c.cookies.delete("live_lang")
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()