Files
xbcr/tests/test_history_30d.py
T
zzy 44efe5f4f4 feat(前端): 切换到 TypeScript 构建产物(dist/app.js),JS 版保留可回滚
切换
- templates/map.html:四个 script(navigation/share/subscribe/map.js)
  → 一行 /static/dist/app.js;geo.js 保留(bundle 内同一份实现,幂等)
- routes/map_api.py 的 MAP_ASSETS 同步换成 dist/app.js,缓存戳跟着产物走

随切换修的
- walk-route:onSearchComplete 里 res.getStatus() 加存在性判断
  (起点≈终点时上游返回空壳,原 JS 版与 TS 版都会抛未捕获 TypeError),两版同步修
- compat/globals.ts 末尾挂 window.S = S:原版 91 个顶层 let/var 是全局词法绑定,
  bundle 里收进 state 对象,至少把 state 暴露出来便于排障
- tests/test_map_assets.py 断言改为 dist/app.js
- tests/test_history_30d.py:子进程加 import os + XBCR_DISABLE_BACKGROUND=1
  (原来采集线程会往临时库写 bike_history,导致统计断言偶发失败)
- app.py 支持 XBCR_DISABLE_BACKGROUND=1:只初始化数据库、不起后台线程(测试/工具用)
- tests/test_rounds_and_preview.py:remaining_seconds 允许 2 秒误差(跨秒抖动)

回滚
- 把 map.html 那行换回四个 script、MAP_ASSETS 换回四个文件名即可;
  static/js/ 一字未改,dist 留着也不会被加载

验证:167 pytest(连跑 3 次)+ 32 node 全绿;浏览器实测(390px,真实数据)
车 498、卡片 #51143 / 步行 488 米、导航条「前方 170 米 右转」、共享/订阅面板可开、
JS 异常 0
2026-11-16 11:14:59 +08:00

116 lines
4.8 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 os
import subprocess
os.environ["XBCR_DISABLE_BACKGROUND"] = "1"
import sys
from pathlib import Path
ROOT = Path(__file__).parent.parent
CHILD = r'''
import os, sys, tempfile, json
from pathlib import Path
ROOT = Path(r"{root}")
os.environ["XBCR_DISABLE_BACKGROUND"] = "1"
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, "子进程契约验证失败(见上方输出)"