Files
dbx-main/app/modules/performance/tests/test_malaysia_variant.py
T
king f9b087157b feat(말레이시아 실적): 한글·영문 전환 + OS 언어 기본값
- 말레이시아 실적 탭 줄에 [한글|EN] 토글(쿠키 mperf_lang), 고른 적 없으면
  브라우저·OS 첫 언어(Accept-Language) ko → 한글, 그 밖 → 영어(app/lang.py)
- 영문이면 performance-en.js(사전·패턴·낱말 치환, 창·알림까지) — 한국 실적 화면은 그대로
- 말레이시아 실적 공휴일 = 말레이시아 공휴일(live/holidays.py, 화면 언어로)
- 라이브 커머스·말레이시아 재고도 같은 기본 언어 규칙

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 16:48:37 +09:00

224 lines
10 KiB
Python

"""[말레이시아 실적](2026-11-20) — 실적 라우터를 /malaysia/performance 에 한 번 더 붙인 인스턴스(variant.MY).
틱톡·쇼피·라자다 그룹(쇼핑몰 + 라이브커머스 하위), 금액 = 센 정수(RM 소수 2자리), 광고비 채널 = 틱톡·쇼피·라자다.
"""
from __future__ import annotations
import importlib
from datetime import date
from types import SimpleNamespace
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from app.modules.performance import common, dashboard, formula, manual_upload, variant
TODAY = date(2026, 10, 7)
D5 = date(2026, 10, 5)
def _row(code, name, sort, **kw):
return {"code": code, "name": name, "sort_order": sort, "enabled": True, "include_in_sales": True,
"manual_input": True, "is_custom": True, "is_group": False, "parent_code": None, **kw}
class _Store:
"""scripts/sql/malaysia_performance_db_seed.sql 과 같은 행 — 그룹 3 + 하위(쇼핑몰·라이브) 6."""
def __init__(self):
self.rows = []
for i, (c, n) in enumerate((("tiktok", "틱톡"), ("shopee", "쇼피"), ("lazada", "라자다"))):
self.rows += [_row(f"group_{c}", n, i * 10 + 10, is_group=True, include_in_sales=False, manual_input=False),
_row(f"custom_{c}_shop", f"{n} 쇼핑몰", i * 10 + 11, parent_code=f"group_{c}"),
_row(f"custom_{c}_live", f"{n} 라이브커머스", i * 10 + 12, parent_code=f"group_{c}")]
self.manual = {(D5, "custom_tiktok_shop"): 123_450, (D5, "custom_tiktok_live"): 10_005, # RM 1,234.50 · 100.05
(D5, "custom_shopee_shop"): 50_000}
self.ads = {(D5, "tiktok"): 26_691} # RM 266.91 → ROAS = 1,334.55 ÷ 266.91 = 500%
self.saved = []
def get_setting(self, key):
return None
def list_marketplaces(self):
return sorted((dict(r) for r in self.rows), key=lambda r: (r["sort_order"], r["code"]))
def daily_amounts(self, start, end, codes):
return {k: v for k, v in self.manual.items() if start <= k[0] <= end and k[1] in codes}
manual_amounts = lambda self, start, end, codes, active_only=True: self.daily_amounts(start, end, codes) # noqa: E731
def rate_table(self):
return {}
def statuses(self):
return {}
def last_update_at(self):
return None
def running_codes(self):
return []
def ad_amounts(self, start, end):
rows = {k: v for k, v in self.ads.items() if start <= k[0] <= end}
return rows, {k: "manual" for k in rows}
def set_manual_sale(self, code, d, amount, user="", formula=None):
self.saved.append(("sale", code, d, amount, formula))
def api_amount(self, code, d):
return 0
def set_ad_spend(self, channel, d, amount, *, source, user="", formula=None):
self.saved.append(("ad", channel, d, amount, formula))
@pytest.fixture()
def my():
token = variant._current.set(variant.MY)
yield
variant._current.reset(token)
@pytest.fixture()
def client(monkeypatch):
perf_router = importlib.import_module("app.modules.performance.router")
from app.modules.malaysia_performance import router as my_router
store = _Store()
user = {"email": "king@x", "name": "King", "is_admin": True}
class _Creds:
def configured_codes(self, adapters):
return {}
monkeypatch.setattr(common, "guard", lambda request, admin=False: (store, user))
monkeypatch.setattr(common, "require_store", lambda request, admin=False: (store, user))
monkeypatch.setattr(common, "services", lambda request, st: (_Creds(), None))
monkeypatch.setattr(perf_router, "today_kst", lambda: TODAY)
app = FastAPI()
app.include_router(perf_router.router)
app.include_router(my_router)
c = TestClient(app)
c.store = store
return c
def test_amount_parsing_scales_to_sen():
assert formula.parse_amount("1,234.5", 100) == (123_450, None)
assert formula.parse_amount("RM 10.005", 100) == (1001, None) # 센 미만 반올림
assert formula.parse_amount("10.5+20", 100) == (3050, "10.5+20")
assert formula.parse_amount("1000+2000") == (3000, "1000+2000") # 한국 실적 그대로(원)
assert manual_upload.parse_amount("RM 12.34", 100) == 1234 and manual_upload.parse_amount(12.345, 100) == 1235
assert manual_upload.parse_amount("12,000") == 12000
def test_text_helpers(my):
assert variant.num_text(123_450) == "1,234.50" and variant.money_text(5) == "RM 0.05"
assert variant.input_text(123_450) == "1234.50" and variant.input_text(None) == ""
assert dashboard.amount_text(-10_005, dashboard.load_unit(None)) == "-100.05"
def test_text_helpers_kr_unchanged():
assert variant.current() is variant.KR
assert variant.num_text(1234) == "1,234" and variant.money_text(1234) == "₩1,234" and variant.input_text(5) == "5"
def test_get_store_follows_variant(my):
state = SimpleNamespace(performance_store="kr", malaysia_performance_store="my")
assert common.get_store(SimpleNamespace(app=SimpleNamespace(state=state))) == "my"
def test_group_sums_and_ad_line_under_group(my):
ctx = dashboard.build_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY)
day5 = next(r for r in ctx["table"] if r.get("date") == D5.isoformat())
assert day5["cells"]["group_tiktok"]["gross"] == 133_455 # 쇼핑몰 + 라이브커머스
assert day5["total"]["gross"] == 183_455 # 그룹은 일 합계에 또 안 더함
assert day5["ads"]["group_tiktok"] == [{"label": "", "amount": 26_691, "roas": 500}]
def test_ad_dashboard_channels(my):
from app.modules.performance.ad_spend import build_ad_dashboard
ctx = build_ad_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY,
sales_codes=[m["code"] for m in dashboard._sales_marketplaces(_Store())])
assert ctx["codes"] == ["tiktok", "shopee", "lazada"] and ctx["upload_channels"] == []
day5 = next(r for r in ctx["table"] if r.get("date") == D5.isoformat())
assert day5["roas"]["tiktok"] == 500 and day5["roas"]["shopee"] is None
assert ctx["kpis"][1]["note"].startswith("총매출 RM ")
def test_pages_render_malaysia(client):
html = client.get("/malaysia/performance/?period=week&d=2026-10-07").text
assert 'data-base="/malaysia/performance"' in html and 'data-cents="1"' in html
assert 'href="/malaysia/performance/ads"' in html and 'id="perf-sync-btn"' not in html
assert "1,234.50" in html and "1,334.55" in html and 'data-manual-value="1234.50"' in html
assert 'data-group-cell="group_tiktok"' in html and "266.91" in html
ads = client.get("/malaysia/performance/ads?period=week&d=2026-10-07").text
assert ">틱톡" in ads and "구글" not in ads.split("<thead>", 1)[1].split("</thead>", 1)[0]
assert '"manual_api": "/malaysia/performance/api/ad-spend/"' in ads
settings = client.get("/malaysia/performance/settings").text
assert "광고 API 연동" not in settings and "자동 업데이트" not in settings and "매출 단위" not in settings
# 같은 앱의 한국 실적은 그대로
kr = client.get("/performance/?period=week&d=2026-10-07").text
assert 'data-base="/performance"' in kr and "data-cents" not in kr
def test_api_saves_sen(client):
r = client.put("/malaysia/performance/api/manual-sales/custom_tiktok_live/2026-10-07", json={"amount": "12.34"})
assert r.status_code == 200, r.text
assert client.store.saved[-1] == ("sale", "custom_tiktok_live", TODAY, 1234, None)
r = client.put("/malaysia/performance/api/ad-spend/shopee/2026-10-07", json={"amount": "1.5*2"})
assert r.status_code == 200, r.text
assert client.store.saved[-1] == ("ad", "shopee", TODAY, 300, "1.5*2")
assert client.put("/malaysia/performance/api/ad-spend/google/2026-10-07", json={"amount": "1"}).status_code == 404
assert client.get("/malaysia/performance/health").json()["module"] == "malaysia_performance"
def test_sample_lists_malaysia_shops(client):
import io
import openpyxl
r = client.get("/malaysia/performance/api/manual-sales/sample.xlsx")
assert r.status_code == 200
head = next(openpyxl.load_workbook(io.BytesIO(r.content)).active.iter_rows(values_only=True))
assert head[:3] == ("날짜", "틱톡 쇼핑몰", "틱톡 라이브커머스") and len(head) == 7
def test_detect_lang_rule():
"""한영 전환(2026-11-20) — 고른 값(쿠키) 먼저, 없으면 브라우저·OS 첫 언어: ko… = 한국어, 그 밖 = 영어, 머리글 없음 = 한국어."""
from app.lang import detect_lang
assert detect_lang(None, "ko-KR,ko;q=0.9,en-US;q=0.8") == "ko" and detect_lang(None, "ko") == "ko"
assert detect_lang(None, "en-US,en;q=0.9,ko;q=0.8") == "en" and detect_lang(None, "ms-MY,ms") == "en"
assert detect_lang(None, "") == "ko" and detect_lang(None, None) == "ko" and detect_lang("<x>", "zh-CN") == "en"
assert detect_lang("ko", "en-US") == "ko" and detect_lang("en", "ko-KR") == "en"
def test_malaysia_page_language(client):
url = "/malaysia/performance/?period=week&d=2026-10-07"
en = client.get(url, headers={"Accept-Language": "en-US,en;q=0.9"}).text
assert 'data-lang="en"' in en and "performance-en.js" in en and 'data-perf-lang="en" class="is-active"' in en
assert "Malaysia Sales" in en and "Deepavali" not in en # 머리 제목 영문, 공휴일은 말레이시아 표(10월 주엔 없음)
ko = client.get(url, headers={"Accept-Language": "ko-KR,ko"}).text
assert 'data-lang="ko"' in ko and "performance-en.js" not in ko
client.cookies.set("mperf_lang", "ko")
assert "performance-en.js" not in client.get(url, headers={"Accept-Language": "en-US"}).text # 고른 값이 먼저
client.cookies.clear()
kr = client.get("/performance/?period=week&d=2026-10-07", headers={"Accept-Language": "en-US"}).text
assert 'data-lang="ko"' in kr and "performance-en.js" not in kr and 'data-perf-lang' not in kr # 한국 실적은 늘 한글·토글 없음
def test_malaysia_holidays(my):
perf_router = importlib.import_module("app.modules.performance.router")
assert perf_router._holidays()["2026-08-31"] == "독립기념일"
token = variant._lang.set("en")
try:
assert perf_router._holidays()["2026-08-31"] == "Merdeka Day"
finally:
variant._lang.reset(token)