线上事故:部署后全站收到「微信凭据已过期」邮件,实际 token 没过期。 根因(实测复现) - 只填 token_id、没有 access_token 的用户,请求只能用假签名(fake_signature), 上游对假签名一律回 102001;而 alerts.check_user_credentials_alive 把 102001 当成「凭据过期」,于是每个 token-only 用户都收到一封「已过期」。 收件人是「alert_email 或用户自己的 email」→ 看起来就是给全站群发。 改动 1) check_user_credentials_alive 不再发信、也不再探测 - 没有 access_token 就无法区分「token 过期」和「假签名被拒」,探测纯属浪费上游配额; 改为只统计并打印一条日志。真正的到期提醒交给 check_user_credentials(能解析 exp 的) 2) 注册遗留的默认 token - 老库 users.token_id 列带 DEFAULT '1291378',注册没写该列的用户被灌了假凭据 - init_db 迁移:token_id='1291378' 且无 access_token → 置 NULL(本地库实测清掉 3 个) - 告警三处(user/global/alive)统一用 _is_legacy_default_token 跳过这类值 3) 补还车前先看小程序状态(用户手动还过车的情况) - 新增 _upstream_ride_active(user_id, order_id):查 /user/info 的 nonDealOrder - _run_recovery 先问上游:上游说这单已结束 → 只做本地收尾(expired=1 + returned_at + 取消计时器),不再发 /record/return(避免 204010 与重复还车) - sweep / 重启补还车 / 巡检三条路径都带 order_id - _close_local_reminder 改名 _close_rental_locally,reminder 单与「已在小程序还车」共用 4) 顺手修:test_history_30d 的 subprocess 在 Windows 用 GBK 读 UTF-8 输出报错 本地库实测 - 迁移清理 3 个默认 token;check_user_credentials_alive() 返回 0(14 个 token-only 用户只记日志) - 全局凭据 10.9 天后到期 → 不触发三级告警(符合预期) 测试:161 pytest(新增凭据误报回归 2 条、上游优先补还车 2 条)+ 32 node 全绿
112 lines
4.7 KiB
Python
112 lines
4.7 KiB
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
"""30 天保留窗口 + 数据新鲜度接口的契约测试(子进程隔离)。
|
|
|
|
教训:此前尝试在父进程里 patch db.DB_PATH + 各模块 get_db 绑定,
|
|
跨测试文件污染(其他测试文件 fixture 也改 DB_PATH,互相踩)。
|
|
app.py 在 import 期还会重包装 stdout,曾破坏 pytest 捕获。
|
|
|
|
因此本文件把整个验证放进一个独立的 python 子进程运行:
|
|
父进程零污染,失败时完整透出子进程输出。
|
|
"""
|
|
import subprocess
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).parent.parent
|
|
|
|
CHILD = r'''
|
|
import sys, tempfile, json
|
|
from pathlib import Path
|
|
ROOT = Path(r"{root}")
|
|
sys.path.insert(0, str(ROOT))
|
|
|
|
import db as db_mod
|
|
handle = tempfile.NamedTemporaryFile(suffix=".db", delete=False)
|
|
handle.close()
|
|
db_mod.DB_PATH = Path(handle.name)
|
|
|
|
import app as app_mod
|
|
db_mod.init_db()
|
|
|
|
conn = db_mod.get_db()
|
|
conn.executescript("""
|
|
INSERT INTO bike_history (bike_code, latitude, longitude, state, status, electric, recorded_at) VALUES
|
|
('50001', 36.5318, 116.7801, 1, 0, 85, datetime('now','+8 hours','-2 hours')),
|
|
('50001', 36.5319, 116.7802, 1, 1, 85, datetime('now','+8 hours','-30 hours')),
|
|
('50002', 36.5320, 116.7803, 10, 0, 15, datetime('now','+8 hours','-3 hours')),
|
|
('50003', 36.5321, 116.7804, 1, 0, 60, datetime('now','+8 hours','-47 hours')),
|
|
('50004', 36.5322, 116.7805, 1, 0, 50, datetime('now','+8 hours','-29 days'));
|
|
""")
|
|
conn.commit(); conn.close()
|
|
|
|
client = app_mod.app.test_client()
|
|
failures = []
|
|
|
|
def check(label, cond, detail=""):
|
|
status = "PASS" if cond else "FAIL"
|
|
print(f"[{{status}}] {{label}}" + (f" | {{detail}}" if detail else ""))
|
|
if not cond:
|
|
failures.append(label)
|
|
|
|
# ---- freshness ----
|
|
r = client.get("/api/map/freshness").get_json()
|
|
check("freshness rtn_code=0", r["rtn_code"] == 0)
|
|
d = r["data"]
|
|
check("freshness latest 19字符", bool(d["latest"]) and len(str(d["latest"])) == 19, str(d["latest"]))
|
|
check("freshness stale 为数字", isinstance(d["stale_seconds"], int))
|
|
|
|
# ---- stats days=1 ----
|
|
r = client.get("/api/history/stats?days=1").get_json()["data"]
|
|
check("stats days=1 回显", r["days"] == 1)
|
|
check("stats 24桶", "00" in r["hourly_distribution"] and "23" in r["hourly_distribution"])
|
|
expected_states = {"available", "used", "locked", "reserved", "low"}
|
|
check("stats 桶含5状态", set(r["hourly_distribution"]["08"].keys()) == expected_states)
|
|
|
|
# ---- stats days=30 ----
|
|
r = client.get("/api/history/stats?days=30").get_json()["data"]
|
|
check("stats days=30 回显", r["days"] == 30)
|
|
check("stats 30桶", "0" in r["hourly_distribution"] and "29" in r["hourly_distribution"])
|
|
check("今天桶 available=1", r["hourly_distribution"]["0"]["available"] == 1, str(r["hourly_distribution"]["0"]))
|
|
check("今天桶 low=1", r["hourly_distribution"]["0"]["low"] == 1)
|
|
check("昨天桶 used=1", r["hourly_distribution"]["1"]["used"] == 1, str(r["hourly_distribution"]["1"]))
|
|
check("昨天桶 available=1", r["hourly_distribution"]["1"]["available"] == 1)
|
|
check("最老桶 available=1", r["hourly_distribution"]["29"]["available"] == 1, str(r["hourly_distribution"]["29"]))
|
|
|
|
# ---- bikes 新结构 ----
|
|
r = client.get("/api/history/bikes").get_json()["data"]
|
|
check("bikes days=30", r["days"] == 30)
|
|
codes = [b["bike_code"] for b in r["bikes"]]
|
|
check("bikes 30天含最老一条", "50004" in codes, str(codes))
|
|
|
|
# ---- trajectory ----
|
|
r = client.get("/api/history/trajectory?bike_code=50001&days=30").get_json()["data"]
|
|
check("trajectory days=30", r["days"] == 30)
|
|
check("trajectory truncated=False", r["truncated"] is False)
|
|
check("trajectory 窗口含 -30h 点", len(r["points"]) == 2)
|
|
|
|
# ---- all_trajectory ----
|
|
r = client.get("/api/history/all_trajectory?days=30").get_json()["data"]
|
|
check("all_trajectory days=30", r["days"] == 30)
|
|
check("all_trajectory truncated 字段", "truncated" in r)
|
|
check("all_trajectory 含最老车", "50004" in r["trajectories"])
|
|
|
|
# ---- 越界收敛 ----
|
|
r = client.get("/api/history/trajectory?bike_code=50001&days=999").get_json()["data"]
|
|
check("days=999 收敛30", r["days"] == 30)
|
|
r = client.get("/api/history/stats?days=0").get_json()["data"]
|
|
check("days=0 收敛1", r["days"] == 1)
|
|
|
|
Path(handle.name).unlink(missing_ok=True)
|
|
print(f"RESULT: {{'FAIL' if failures else 'ALL PASS'}} ({{len(failures)}} failures)")
|
|
sys.exit(1 if failures else 0)
|
|
'''.replace("{root}", str(ROOT).replace("\\", "\\\\"))
|
|
|
|
|
|
def test_history_30d_contract():
|
|
r = subprocess.run([sys.executable, "-c", CHILD],
|
|
capture_output=True, text=True, timeout=180,
|
|
cwd=str(ROOT), encoding="utf-8", errors="replace")
|
|
out = (r.stdout or "") + (r.stderr or "")
|
|
print(out[-4000:] if len(out) > 4000 else out)
|
|
assert r.returncode == 0, "子进程契约验证失败(见上方输出)" |