按 review 逐条修: P0-1 实时刷新取错电量字段 - refresh_bike_points 改读 electric_quantity(兼容 electricQuantity), 原来读 st["electric"] 永远是 None → 电量筛选全落空、排序退化成距离 P0-2 type=1 单车混进候选 - 只请求 type=3(电动车),每行带 bike_type;不再把共享单车算进 「附近有几辆」和自动开锁候选 P0-2b 取数顺序 - 先走 request_api(60 秒共享快照),失败才用用户凭据直连一次 P1-3 订阅单不在补还车白名单 - 新增 _should_auto_return(rental):source ∈ unlock/sync/shared/subscribe 且 order_id 非空,restore 与巡检共用 P1-4 reminder 单被当成真实订单 - _recover_overdue_rental 与 restore 都按白名单过滤, reminder 直接跳过,不再拿本地自增 id 当订单号白打三次上游 P1-5 补发没有下界 - _tick 加 CATCHUP_WINDOW_MIN=5:窗口内补发,超过窗口只记「今天已处理」 P2 收尾 - 重试成功补发「自动还车已成功」通知(避免用户去点旧邮件里的还车按钮) - 重试耗尽改为给管理员发告警邮件,不再只有一行 print - _mark_notified 支持复用已有连接/游标 - _return_candidates 惰性:先试原坐标,失败才算候选点 (不再每次还车都多打一次 /project/map) - 删除 map.js 死变量 _orderAlerted 文案 - 按「不写会话顶替、只写到期提醒」的口径: wechat.py 模块说明改为「AccessToken 30 天有效,到期前有提醒」; alerts.py 三处 lead 去掉「重新登录会顶掉旧会话」,只保留「请更新凭据」 测试:150 pytest(新增电量字段/车型隔离、补发窗口、reminder 跳过、 retry 收尾通知、耗尽告警)+ 32 node 全绿;浏览器冒烟 JS 异常 0
187 lines
7.4 KiB
Python
187 lines
7.4 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""订阅调度与自动开锁的关键回归。
|
|
|
|
覆盖两件事:
|
|
1) 整分钟漏触发后当天要能补(`minute_of_day <= 当前分钟`);
|
|
2) 开锁失败时必须撤销刚下的半成品订单,避免重试叠加。
|
|
"""
|
|
import datetime as dt
|
|
import sqlite3
|
|
import tempfile
|
|
import unittest
|
|
from pathlib import Path
|
|
from unittest.mock import patch
|
|
|
|
import subscribe
|
|
|
|
|
|
SCHEMA = """
|
|
CREATE TABLE subscribe_rules (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
user_id INTEGER NOT NULL,
|
|
location_id INTEGER,
|
|
weekday INTEGER DEFAULT 0,
|
|
minute_of_day INTEGER NOT NULL,
|
|
enabled INTEGER DEFAULT 1,
|
|
notify_enabled INTEGER DEFAULT 1,
|
|
auto_unlock INTEGER DEFAULT 0,
|
|
last_fired_on TEXT DEFAULT '',
|
|
kinds TEXT DEFAULT 'small,big,red',
|
|
min_electric INTEGER DEFAULT 0,
|
|
max_electric INTEGER DEFAULT 100,
|
|
sort_by TEXT DEFAULT 'electric_desc',
|
|
retry_times INTEGER DEFAULT 3
|
|
);
|
|
"""
|
|
|
|
|
|
class ImmediateThread:
|
|
def __init__(self, target=None, args=(), kwargs=None, **rest):
|
|
self.target = target
|
|
self.args = args
|
|
self.kwargs = kwargs or {}
|
|
|
|
def start(self):
|
|
if self.target:
|
|
self.target(*self.args, **self.kwargs)
|
|
|
|
|
|
class SubscribeFlowTests(unittest.TestCase):
|
|
def setUp(self):
|
|
self.tmp = tempfile.TemporaryDirectory()
|
|
self.db_path = Path(self.tmp.name) / "sub.db"
|
|
conn = sqlite3.connect(self.db_path)
|
|
conn.executescript(SCHEMA)
|
|
conn.commit()
|
|
conn.close()
|
|
|
|
def tearDown(self):
|
|
self.tmp.cleanup()
|
|
|
|
def _get_db(self):
|
|
conn = sqlite3.connect(self.db_path)
|
|
conn.row_factory = sqlite3.Row
|
|
return conn
|
|
|
|
def test_missed_minute_is_caught_up_later_same_day(self):
|
|
"""7:50 的规则,8:10 才跑到,仍然要发,且当天只发一次。"""
|
|
now = dt.datetime.now(dt.timezone(dt.timedelta(hours=8)))
|
|
conn = self._get_db()
|
|
past_minute = max(0, now.hour * 60 + now.minute - 5)
|
|
conn.execute("""
|
|
INSERT INTO subscribe_rules (user_id, location_id, weekday, minute_of_day,
|
|
enabled, notify_enabled, last_fired_on)
|
|
VALUES (7, 1, 0, ?, 1, 1, '')
|
|
""", (past_minute,))
|
|
conn.commit()
|
|
conn.close()
|
|
|
|
fired = []
|
|
with patch.object(subscribe, "get_db", self._get_db), \
|
|
patch.object(subscribe.threading, "Thread", ImmediateThread), \
|
|
patch.object(subscribe, "fire_rule", side_effect=lambda r: fired.append(r["id"]) or True):
|
|
subscribe._tick()
|
|
|
|
self.assertEqual(1, len(fired), "过点的规则应该补发一次")
|
|
|
|
# 同一天再扫一遍不应重复触发
|
|
with patch.object(subscribe, "get_db", self._get_db), \
|
|
patch.object(subscribe.threading, "Thread", ImmediateThread), \
|
|
patch.object(subscribe, "fire_rule", side_effect=lambda r: fired.append(r["id"]) or True):
|
|
subscribe._tick()
|
|
self.assertEqual(1, len(fired), "当天已经发过就不该再发")
|
|
|
|
def test_future_minute_is_not_fired_early(self):
|
|
now = dt.datetime.now(dt.timezone(dt.timedelta(hours=8)))
|
|
conn = self._get_db()
|
|
future_minute = min(23 * 60 + 59, now.hour * 60 + now.minute + 30)
|
|
conn.execute("""
|
|
INSERT INTO subscribe_rules (user_id, location_id, weekday, minute_of_day,
|
|
enabled, notify_enabled, last_fired_on)
|
|
VALUES (7, 1, 0, ?, 1, 1, '')
|
|
""", (future_minute,))
|
|
conn.commit()
|
|
conn.close()
|
|
|
|
fired = []
|
|
with patch.object(subscribe, "get_db", self._get_db), \
|
|
patch.object(subscribe.threading, "Thread", ImmediateThread), \
|
|
patch.object(subscribe, "fire_rule", side_effect=lambda r: fired.append(r["id"]) or True):
|
|
subscribe._tick()
|
|
self.assertEqual([], fired)
|
|
|
|
def test_failed_unlock_discards_the_pending_order(self):
|
|
"""下单成功但开锁失败:必须撤销那张单,否则重试会再叠一张。"""
|
|
responses = {
|
|
"/project/bicycle": {"rtn_code": 0, "data": {"status": 0, "code": "50001",
|
|
"latitude": 36.53, "longitude": 116.78}},
|
|
"/record/order": {"rtn_code": 0, "data": {"order_id": "777"}},
|
|
"/record/qrOrder": {"rtn_code": 500, "message": "open failed"},
|
|
"/record/return": {"rtn_code": 0, "message": "closed"},
|
|
}
|
|
|
|
def fake_auth(user_id, method, path, **kwargs):
|
|
return responses.get(path, {"rtn_code": 0, "data": {}})
|
|
|
|
with patch.object(subscribe, "_live_coord", return_value=(36.53, 116.78)), \
|
|
patch.object(subscribe, "AUTO_UNLOCK_ENABLED", True), \
|
|
patch("wechat.request_with_user_auth", side_effect=fake_auth), \
|
|
patch.object(subscribe, "_discard_pending_order", return_value=True) as discard:
|
|
result = subscribe._try_auto_unlock(7, "50001")
|
|
|
|
self.assertFalse(result["success"])
|
|
discard.assert_called_once()
|
|
self.assertEqual("777", str(discard.call_args.args[1]))
|
|
self.assertIn("已撤销本次下单", result["message"])
|
|
|
|
def test_realtime_points_use_electric_quantity_and_only_electric_bikes(self):
|
|
"""上游字段是 electric_quantity;写成 electric 会让电量筛选全部落空。
|
|
并且只取 type=3(电动车),别把共享单车混进候选。"""
|
|
payload = {"rtn_code": 0, "data": {"bicycleStation": [
|
|
{"code": "51287", "latitude": 36.53, "longitude": 116.78,
|
|
"electric_quantity": 66, "state": 1, "status": 0},
|
|
]}}
|
|
calls = []
|
|
|
|
def fake_api(method, path, params=None, data=None):
|
|
calls.append(params)
|
|
return payload
|
|
|
|
with patch("wechat.request_api", side_effect=fake_api):
|
|
rows = subscribe.refresh_bike_points(7)
|
|
|
|
self.assertEqual(1, len(rows))
|
|
self.assertEqual(66, rows[0]["electric"])
|
|
self.assertEqual("51287", rows[0]["bike_code"])
|
|
self.assertEqual("3", rows[0]["bike_type"])
|
|
self.assertEqual(["3"], [c["type"] for c in calls])
|
|
|
|
def test_missed_minute_beyond_window_is_skipped_without_email(self):
|
|
"""超过补发窗口(默认 5 分钟)的规则:只记今天已处理,不发信。"""
|
|
now = dt.datetime.now(dt.timezone(dt.timedelta(hours=8)))
|
|
conn = self._get_db()
|
|
old_minute = max(0, now.hour * 60 + now.minute - 30)
|
|
conn.execute("""
|
|
INSERT INTO subscribe_rules (user_id, location_id, weekday, minute_of_day,
|
|
enabled, notify_enabled, last_fired_on)
|
|
VALUES (7, 1, 0, ?, 1, 1, '')
|
|
""", (old_minute,))
|
|
conn.commit()
|
|
conn.close()
|
|
|
|
fired = []
|
|
with patch.object(subscribe, "get_db", self._get_db), \
|
|
patch.object(subscribe.threading, "Thread", ImmediateThread), \
|
|
patch.object(subscribe, "fire_rule", side_effect=lambda r: fired.append(r["id"]) or True):
|
|
subscribe._tick()
|
|
|
|
self.assertEqual([], fired, "过窗口太久的规则不该补发")
|
|
conn = self._get_db()
|
|
row = conn.execute("SELECT last_fired_on FROM subscribe_rules").fetchone()
|
|
conn.close()
|
|
self.assertEqual(now.strftime("%Y-%m-%d"), row["last_fired_on"])
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|