- 拆包 fengxiang/:config/client/store/notify/monitor/admin/tts,统一入口 order_monitor.py - 服务器形态:Docker 常驻,Cookie 由本机登录后 POST 上传并热加载,不再依赖桌面弹窗 - 修复:首次启动重推历史订单、speak() 阻塞主循环、夜间 sleep 10h 不可中断 - 修复:test_push.py 残留 miservice 依赖(小爱已移除)、run_monitor.bat 写死盘符 - 配置化:webhook/shopId 移出源码(环境变量 > config.yaml > 默认值) - 可观测:滚动文件日志 + /healthz + Docker HEALTHCHECK + 告警冷却 - 飞书通道保留配置位,默认关闭(原 token 已失效 code=19001) - 新增 22 项单元测试(不联网)
292 lines
9.9 KiB
Python
292 lines
9.9 KiB
Python
"""核心逻辑单元测试(不联网,全部用假客户端/假通道)。
|
|
|
|
运行:python -m unittest discover -s tests -v
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import sys
|
|
import tempfile
|
|
import threading
|
|
import unittest
|
|
import urllib.error
|
|
import urllib.request
|
|
from dataclasses import replace
|
|
from pathlib import Path
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
|
|
|
from fengxiang.config import load_config # noqa: E402
|
|
from fengxiang.monitor import Monitor, fmt_money # noqa: E402
|
|
from fengxiang.store import State # noqa: E402
|
|
|
|
|
|
# --------------------------------------------------------------------------- 假对象
|
|
class FakeClient:
|
|
def __init__(self, orders=None):
|
|
self.orders = orders or []
|
|
self.cookies = {}
|
|
self.cookie_ok = True
|
|
|
|
def set_cookies(self, cookies):
|
|
self.cookies = dict(cookies)
|
|
|
|
def check_cookie(self, cookies):
|
|
return self.cookie_ok and bool(cookies)
|
|
|
|
def list_orders(self, page_size=5, page=1):
|
|
return self.orders[:page_size]
|
|
|
|
|
|
class FakeDispatcher:
|
|
def __init__(self):
|
|
self.messages = []
|
|
self.alerts = []
|
|
self.channels = []
|
|
|
|
def notify(self, text):
|
|
self.messages.append(text)
|
|
return {"fake": True}
|
|
|
|
def alert(self, key, text):
|
|
self.alerts.append((key, text))
|
|
return True, "sent"
|
|
|
|
|
|
class FakeSpeaker:
|
|
def __init__(self):
|
|
self.said = []
|
|
|
|
def start(self):
|
|
pass
|
|
|
|
def stop(self):
|
|
pass
|
|
|
|
def say(self, text):
|
|
self.said.append(text)
|
|
|
|
|
|
def make_order(oid: str, cents: int = 2400):
|
|
return {"orderId": oid, "amountPayable": cents, "shopName": "益选便利店"}
|
|
|
|
|
|
class BaseCase(unittest.TestCase):
|
|
def setUp(self):
|
|
self.tmp = tempfile.TemporaryDirectory()
|
|
self.addCleanup(self.tmp.cleanup)
|
|
self._env_backup = dict(os.environ)
|
|
os.environ["FX_DATA_DIR"] = self.tmp.name
|
|
os.environ["FX_CONFIG"] = str(Path(self.tmp.name) / "none.yaml")
|
|
os.environ["FX_WECOM_WEBHOOK"] = "https://example.invalid/hook"
|
|
self.cfg = load_config()
|
|
|
|
def tearDown(self):
|
|
os.environ.clear()
|
|
os.environ.update(self._env_backup)
|
|
|
|
def build(self, orders=None, **kwargs):
|
|
client = FakeClient(orders)
|
|
dispatcher = FakeDispatcher()
|
|
speaker = FakeSpeaker()
|
|
mon = Monitor(self.cfg, client=client, dispatcher=dispatcher, speaker=speaker, **kwargs)
|
|
return mon, client, dispatcher, speaker
|
|
|
|
|
|
# --------------------------------------------------------------------------- 配置
|
|
class TestConfig(BaseCase):
|
|
def test_defaults(self):
|
|
self.assertEqual(self.cfg.shop_id, "20434543575189")
|
|
self.assertIn("wecom", self.cfg.notify.channels)
|
|
|
|
def test_feishu_disabled_by_default(self):
|
|
self.assertFalse(self.cfg.notify.feishu_enabled)
|
|
self.assertNotIn("feishu", self.cfg.notify.channels)
|
|
|
|
def test_env_wecom_only_channel(self):
|
|
self.assertEqual(len(self.cfg.notify.channels), 1)
|
|
|
|
def test_paths_point_to_data_dir(self):
|
|
self.assertTrue(str(self.cfg.paths.cookies).startswith(self.tmp.name))
|
|
|
|
|
|
# --------------------------------------------------------------------------- 状态
|
|
class TestState(BaseCase):
|
|
def test_roundtrip(self):
|
|
s = State(last_order_id="100", pushed_ids=["100"])
|
|
s.mark_pushed(["101", "102"])
|
|
s.save(self.cfg.paths.state)
|
|
|
|
loaded = State.load(self.cfg.paths.state)
|
|
self.assertEqual(loaded.last_order_id, "100")
|
|
self.assertEqual(loaded.pushed_ids, ["100", "101", "102"])
|
|
self.assertEqual(loaded.total_pushed, 2) # 初始 pushed_ids 不计入累计
|
|
|
|
def test_pushed_ids_bounded(self):
|
|
s = State()
|
|
s.mark_pushed([str(i) for i in range(700)])
|
|
self.assertEqual(len(s.pushed_ids), 500)
|
|
self.assertTrue(s.has_pushed("699"))
|
|
self.assertFalse(s.has_pushed("0"))
|
|
|
|
def test_corrupt_file_is_tolerated(self):
|
|
Path(self.cfg.paths.state).write_text("{not json", encoding="utf-8")
|
|
s = State.load(self.cfg.paths.state)
|
|
self.assertIsNone(s.last_order_id)
|
|
|
|
|
|
# --------------------------------------------------------------------------- 主循环业务
|
|
class TestProcess(BaseCase):
|
|
def test_bootstrap_does_not_push_history(self):
|
|
mon, client, dispatcher, _ = self.build([make_order("A3"), make_order("A2")])
|
|
mon._bootstrap()
|
|
self.assertEqual(dispatcher.messages, [])
|
|
self.assertEqual(mon.state.last_order_id, "A3")
|
|
self.assertTrue(mon.state.has_pushed("A3"))
|
|
|
|
def test_new_orders_pushed_old_to_new(self):
|
|
mon, _, dispatcher, speaker = self.build()
|
|
mon.state.last_order_id = "A3"
|
|
mon._process([make_order("A5", 3000), make_order("A4", 2000), make_order("A3", 1000)], 10)
|
|
self.assertEqual(len(dispatcher.messages), 2)
|
|
self.assertIn("20.00元", dispatcher.messages[0])
|
|
self.assertIn("30.00元", dispatcher.messages[1])
|
|
self.assertEqual(mon.state.last_order_id, "A5")
|
|
self.assertEqual(len(speaker.said), 2)
|
|
|
|
def test_dedupe_after_restart(self):
|
|
mon, _, dispatcher, _ = self.build()
|
|
mon.state.last_order_id = "A3"
|
|
mon.state.mark_pushed(["A4"]) # A4 已在重启前推过
|
|
mon._process([make_order("A5"), make_order("A4"), make_order("A3")], 50)
|
|
self.assertEqual(len(dispatcher.messages), 1)
|
|
self.assertIn("24.00", dispatcher.messages[0])
|
|
|
|
def test_no_new_orders_silent(self):
|
|
mon, _, dispatcher, _ = self.build()
|
|
mon.state.last_order_id = "A9"
|
|
mon._process([make_order("A9")], 10)
|
|
self.assertEqual(dispatcher.messages, [])
|
|
|
|
def test_bulk_summary_instead_of_spam(self):
|
|
mon, _, dispatcher, _ = self.build()
|
|
mon.state.last_order_id = "A0"
|
|
orders = [make_order(f"A{i}", 1000) for i in range(8, 0, -1)]
|
|
mon._process(orders, 20)
|
|
self.assertEqual(len(dispatcher.messages), 1)
|
|
self.assertIn("8 笔订单", dispatcher.messages[0])
|
|
self.assertIn("80.00元", dispatcher.messages[0])
|
|
|
|
def test_missing_order_id_ignored(self):
|
|
mon, _, dispatcher, _ = self.build()
|
|
mon.state.last_order_id = "A1"
|
|
mon._process([{"amountPayable": 100}, make_order("A1")], 10)
|
|
self.assertEqual(dispatcher.messages, [])
|
|
|
|
|
|
# --------------------------------------------------------------------------- 时间窗口
|
|
class TestWindows(BaseCase):
|
|
def _at(self, hh, mm=0):
|
|
mon, *_ = self.build()
|
|
|
|
import datetime
|
|
fixed = datetime.datetime(2026, 11, 16, hh, mm)
|
|
mon._now_impl = lambda: fixed
|
|
return mon
|
|
|
|
def test_night_true_after_21(self):
|
|
mon = self._at(22, 30)
|
|
self.assertTrue(mon.is_night())
|
|
|
|
def test_night_true_before_0740(self):
|
|
mon = self._at(3, 0)
|
|
self.assertTrue(mon.is_night())
|
|
|
|
def test_daytime_not_night(self):
|
|
mon = self._at(12, 0)
|
|
self.assertFalse(mon.is_night())
|
|
self.assertTrue(mon.is_peak())
|
|
|
|
def test_offpeak(self):
|
|
mon = self._at(15, 0)
|
|
self.assertFalse(mon.is_peak())
|
|
self.assertFalse(mon.is_night())
|
|
|
|
|
|
# --------------------------------------------------------------------------- 金额
|
|
class TestMoney(unittest.TestCase):
|
|
def test_formats(self):
|
|
self.assertEqual(fmt_money(2400), "24.00元")
|
|
self.assertEqual(fmt_money(0), "0.00元")
|
|
self.assertEqual(fmt_money(None), "0.00元")
|
|
self.assertEqual(fmt_money("x"), "0.00元")
|
|
|
|
|
|
# --------------------------------------------------------------------------- 管理接口
|
|
class TestAdminAPI(BaseCase):
|
|
def setUp(self):
|
|
super().setUp()
|
|
self.cfg = replace(self.cfg, admin=replace(self.cfg.admin, port=0, token="t0k"))
|
|
|
|
def _start(self):
|
|
from fengxiang.admin import AdminServer
|
|
mon, client, dispatcher, speaker = self.build()
|
|
mon.update_cookies = lambda cookies: bool(cookies) # 避免真实校验
|
|
mon.status = lambda: {"cookie_valid": True, "mode": "idle", "last_poll_age_sec": 1}
|
|
srv = AdminServer(self.cfg, mon)
|
|
port = srv.httpd.server_address[1]
|
|
srv.start()
|
|
self.addCleanup(srv.stop)
|
|
return mon, port
|
|
|
|
def _post(self, port, path, body, token=None):
|
|
req = urllib.request.Request(
|
|
f"http://127.0.0.1:{port}{path}",
|
|
data=json.dumps(body).encode(),
|
|
headers={"Content-Type": "application/json",
|
|
**({"X-Auth-Token": token} if token else {})},
|
|
method="POST",
|
|
)
|
|
with urllib.request.urlopen(req, timeout=5) as resp:
|
|
return resp.status, json.load(resp)
|
|
|
|
def _get(self, port, path):
|
|
with urllib.request.urlopen(f"http://127.0.0.1:{port}{path}", timeout=5) as resp:
|
|
return resp.status, json.load(resp)
|
|
|
|
def test_healthz_no_auth(self):
|
|
_, port = self._start()
|
|
status, data = self._get(port, "/healthz")
|
|
self.assertEqual(status, 200)
|
|
self.assertTrue(data["cookie_valid"])
|
|
|
|
def test_post_cookies_requires_token(self):
|
|
_, port = self._start()
|
|
with self.assertRaises(urllib.error.HTTPError) as ctx:
|
|
self._post(port, "/api/cookies", {"cookies": {"USS": "x"}})
|
|
self.assertEqual(ctx.exception.code, 401)
|
|
|
|
def test_post_cookies_with_token(self):
|
|
_, port = self._start()
|
|
status, data = self._post(port, "/api/cookies", {"cookies": {"USS": "x"}}, token="t0k")
|
|
self.assertEqual(status, 200)
|
|
self.assertTrue(data["ok"])
|
|
|
|
def test_post_bad_body(self):
|
|
_, port = self._start()
|
|
req = urllib.request.Request(
|
|
f"http://127.0.0.1:{port}/api/cookies",
|
|
data=b"[]",
|
|
headers={"Content-Type": "application/json", "X-Auth-Token": "t0k"},
|
|
method="POST",
|
|
)
|
|
with self.assertRaises(urllib.error.HTTPError) as ctx:
|
|
urllib.request.urlopen(req, timeout=5)
|
|
self.assertEqual(ctx.exception.code, 400)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main(verbosity=2)
|