- 新增 .gitattributes:* text=auto eol=lf,二进制类型显式标 binary - 24 个 CRLF 文件归一为 LF(内容零变化,忽略行尾后 diff 只有本文件与 .gitignore) - .gitignore 补 temp/、.pytest_cache/、token_config.txt.old-bak、scripts/.pack_baseline.json 等
280 lines
8.0 KiB
Python
280 lines
8.0 KiB
Python
#!/usr/bin/env python3
|
||
# -*- coding: utf-8 -*-
|
||
"""冒烟测试:验证应用可启动、路由无冲突、关键接口可响应。"""
|
||
import sys
|
||
from pathlib import Path
|
||
|
||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # 项目根
|
||
|
||
# 注意: app.py 导入时会重新包装 sys.stdout, 这里不能自己再包一层,
|
||
# 否则旧包装器被 GC 时会关闭底层 buffer。编码由 PYTHONIOENCODING 控制。
|
||
_ORIG_STDOUT = sys.stdout # 持有引用, 防止被 GC 后关闭底层流
|
||
|
||
from collections import defaultdict
|
||
|
||
PASS, FAIL = [], []
|
||
|
||
|
||
def check(name, fn):
|
||
try:
|
||
detail = fn()
|
||
PASS.append((name, detail))
|
||
print(f" [PASS] {name}" + (f" — {detail}" if detail else ""))
|
||
except Exception as e:
|
||
FAIL.append((name, f"{type(e).__name__}: {e}"))
|
||
print(f" [FAIL] {name} — {type(e).__name__}: {e}")
|
||
|
||
|
||
print("=" * 60)
|
||
print("1) 模块导入检查")
|
||
print("=" * 60)
|
||
|
||
|
||
def import_app():
|
||
import app as app_module
|
||
return f"app 模块导入成功, 蓝图 {len(app_module.app.blueprints)} 个: {', '.join(app_module.app.blueprints)}"
|
||
|
||
|
||
check("导入 app.py 及全部依赖 (db/wechat/timer/routes.*)", import_app)
|
||
|
||
|
||
def import_side_modules():
|
||
import rental_mail, email_utils, generate_icons # noqa: F401
|
||
return "rental_mail / email_utils / generate_icons 导入成功"
|
||
|
||
|
||
check("导入其余业务模块", import_side_modules)
|
||
|
||
app_obj = None
|
||
try:
|
||
import app as app_module
|
||
app_obj = app_module.app
|
||
except Exception:
|
||
pass
|
||
|
||
print()
|
||
print("=" * 60)
|
||
print("2) 路由冲突检查")
|
||
print("=" * 60)
|
||
|
||
|
||
def route_conflicts():
|
||
rules = defaultdict(list)
|
||
for r in app_obj.url_map.iter_rules():
|
||
if r.endpoint == "static":
|
||
continue
|
||
methods = sorted(m for m in r.methods if m not in ("HEAD", "OPTIONS"))
|
||
for m in methods:
|
||
rules[(m, r.rule)].append(r.endpoint)
|
||
dupes = {k: v for k, v in rules.items() if len(v) > 1}
|
||
if dupes:
|
||
raise AssertionError(f"发现 {len(dupes)} 处路由冲突: {dupes}")
|
||
return f"共 {len(rules)} 条 (method, path) 规则, 无重复注册"
|
||
|
||
|
||
check("检查重复路由 (Flask 静默覆盖, 需显式检测)", route_conflicts)
|
||
|
||
|
||
def route_summary():
|
||
rules = sorted(r.rule for r in app_obj.url_map.iter_rules() if r.endpoint != "static")
|
||
return f"{len(rules)} 条路由"
|
||
|
||
|
||
check("路由注册成功", route_summary)
|
||
|
||
print()
|
||
print("=" * 60)
|
||
print("3) 数据库连通性")
|
||
print("=" * 60)
|
||
|
||
|
||
def db_check():
|
||
import sqlite3
|
||
from pathlib import Path
|
||
p = Path("users.db")
|
||
if not p.exists():
|
||
raise AssertionError("users.db 不存在")
|
||
conn = sqlite3.connect(str(p))
|
||
conn.row_factory = sqlite3.Row
|
||
cur = conn.cursor()
|
||
tables = [r[0] for r in cur.execute(
|
||
"SELECT name FROM sqlite_master WHERE type='table'").fetchall()]
|
||
counts = {}
|
||
for t in ("users", "rentals", "bike_history", "sessions"):
|
||
if t in tables:
|
||
counts[t] = cur.execute(f"SELECT COUNT(*) FROM {t}").fetchone()[0]
|
||
cur.execute("PRAGMA integrity_check")
|
||
integrity = cur.fetchone()[0]
|
||
conn.close()
|
||
if integrity != "ok":
|
||
raise AssertionError(f"数据库完整性异常: {integrity}")
|
||
return f"表 {len(tables)} 张, 行数: {counts}"
|
||
|
||
|
||
check("users.db 完整性与核心表", db_check)
|
||
|
||
|
||
def db_init_check():
|
||
"""init_db() 应可重复执行(幂等)而不报错 —— 用临时库验证。"""
|
||
import db, tempfile, os
|
||
from pathlib import Path
|
||
fd, tmp = tempfile.mkstemp(suffix=".db")
|
||
os.close(fd)
|
||
old = db.DB_PATH
|
||
db.DB_PATH = Path(tmp)
|
||
try:
|
||
db.init_db()
|
||
db.init_db() # 二次调用验证幂等
|
||
return "init_db 在临时库上执行两次均成功(幂等)"
|
||
finally:
|
||
db.DB_PATH = old
|
||
try:
|
||
os.remove(tmp)
|
||
except OSError:
|
||
pass
|
||
|
||
|
||
check("init_db 幂等性 (临时库)", db_init_check)
|
||
|
||
print()
|
||
print("=" * 60)
|
||
print("4) 模板与静态资源")
|
||
print("=" * 60)
|
||
|
||
|
||
def templates_check():
|
||
from pathlib import Path
|
||
tdir = Path("templates")
|
||
files = sorted(p.name for p in tdir.glob("*.html"))
|
||
if not files:
|
||
raise AssertionError("templates 目录为空")
|
||
return f"{len(files)} 个模板: {', '.join(files)}"
|
||
|
||
|
||
check("模板文件存在", templates_check)
|
||
|
||
|
||
def static_check():
|
||
from pathlib import Path
|
||
sdir = Path("static")
|
||
total = sum(1 for _ in sdir.rglob("*") if _.is_file())
|
||
if total == 0:
|
||
raise AssertionError("static 目录为空")
|
||
return f"{total} 个静态文件"
|
||
|
||
|
||
check("静态资源存在", static_check)
|
||
|
||
print()
|
||
print("=" * 60)
|
||
print("5) 关键接口冒烟 (Flask test client, 不真正监听端口)")
|
||
print("=" * 60)
|
||
|
||
|
||
def client():
|
||
app_obj.config["TESTING"] = True
|
||
return app_obj.test_client()
|
||
|
||
|
||
c = client()
|
||
|
||
EXPECTED = {
|
||
# (path): 说明。允许 200/3xx;404 属于页面/路由缺失
|
||
"/": "主页(地图)",
|
||
"/admin": "管理后台(未登录应跳转登录)",
|
||
"/admin/login": "管理员登录页",
|
||
"/analysis.html": "数据分析页",
|
||
"/rental/email-return": "邮件还车页",
|
||
"/ring_progress.html": "寻车进度页",
|
||
}
|
||
|
||
|
||
def page(path):
|
||
def fn():
|
||
r = c.get(path)
|
||
if r.status_code in (200, 301, 302, 304):
|
||
return f"{path} -> {r.status_code}"
|
||
if r.status_code == 404:
|
||
raise AssertionError(f"{path} -> 404 (页面/路由缺失)")
|
||
raise AssertionError(f"{path} -> {r.status_code}")
|
||
return fn
|
||
|
||
|
||
for path, name in EXPECTED.items():
|
||
check(f"页面 {name} {path}", page(path))
|
||
|
||
# API 类: 401/400 = 接口在且鉴权/校验正常; 404/500 = 有问题
|
||
API_ALLOW = {200, 400, 401, 302, 301}
|
||
APIS = [
|
||
("/api/bike_history", "无参数应返回400"),
|
||
("/api/analysis/overview", "分析总览"),
|
||
("/api/analysis/heatmap", "热力图"),
|
||
("/api/history/stats", "历史统计"),
|
||
("/api/history/bikes", "历史车辆列表"),
|
||
("/api/history/heatmap", "历史热力图"),
|
||
("/api/history/all_trajectory", "全量轨迹"),
|
||
]
|
||
|
||
|
||
def api(path):
|
||
def fn():
|
||
r = c.get(path)
|
||
if r.status_code in API_ALLOW:
|
||
return f"{path} -> {r.status_code}"
|
||
raise AssertionError(f"{path} -> {r.status_code}")
|
||
return fn
|
||
|
||
|
||
for path, desc in APIS:
|
||
check(f"API {desc} {path}", api(path))
|
||
|
||
|
||
def protected_api_check():
|
||
"""未登录访问受保护接口应返回 401(或明确拒绝) 而不是 500/404"""
|
||
paths = (
|
||
"/api/auth/rental_settings", "/api/rental/status",
|
||
"/api/share/active", "/api/auth/profile", "/api/order/status",
|
||
)
|
||
for path in paths:
|
||
r = c.get(path)
|
||
if r.status_code == 404:
|
||
raise AssertionError(f"{path} -> 404, 接口不存在")
|
||
if r.status_code >= 500:
|
||
raise AssertionError(f"{path} -> {r.status_code}, 服务端错误")
|
||
if r.status_code == 200:
|
||
body = r.get_json(silent=True) or {}
|
||
if body.get("rtn_code") not in (401, 403):
|
||
raise AssertionError(
|
||
f"{path} 未登录返回 200 且 rtn_code={body.get('rtn_code')}, 疑似未鉴权")
|
||
return "受保护接口未登录时均正确拒绝(无 500/404/越权)"
|
||
|
||
|
||
check("受保护接口鉴权兜底", protected_api_check)
|
||
|
||
|
||
def login_flow_check():
|
||
"""登录接口对错误凭据应返回明确失败而非 500"""
|
||
r = c.post("/api/auth/login",
|
||
json={"email": "smoke_nonexist@example.test", "password": "wrong"})
|
||
if r.status_code >= 500:
|
||
raise AssertionError(f"/api/auth/login -> {r.status_code}")
|
||
body = r.get_json(silent=True) or {}
|
||
if r.status_code == 200 and body.get("rtn_code") == 0:
|
||
raise AssertionError("错误凭据竟然登录成功!")
|
||
return f"/api/auth/login 错误凭据 -> {r.status_code} rtn_code={body.get('rtn_code')} (拒绝正常)"
|
||
|
||
|
||
check("登录接口错误凭据处理", login_flow_check)
|
||
|
||
print()
|
||
print("=" * 60)
|
||
print("冒烟测试结果汇总")
|
||
print("=" * 60)
|
||
print(f"通过: {len(PASS)} 失败: {len(FAIL)}")
|
||
if FAIL:
|
||
print("\n失败项:")
|
||
for name, err in FAIL:
|
||
print(f" - {name}: {err}")
|
||
sys.exit(1)
|
||
print("全部通过 ✅")
|