#!/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, "子进程契约验证失败(见上方输出)"