unis_manager/tests/test_api_contract.py

349 lines
19 KiB
Python
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# 接口契约:错误信息语言、健康检查、导出权限 fail-closed、操作日志服务端分页
import pytest
from fastapi import HTTPException
from app.security import EXPORT_MENU, resolve_rule
def test_健康检查与首页可达(h):
"""README 承诺 GET /health 与 GET /,一直没进回归;补上。"""
r = h.admin.get("/health")
assert r.status_code == 200
body = r.json()
assert body["ok"] is True and "boot" in body and "db" in body
r = h.admin.get("/")
assert r.status_code == 200
assert "DMS管理平台" in r.text
def test_校验失败返回中文detail(h):
"""FastAPI 默认 422 detail 是英文(Field required),前端会原样 toast——必须已换成中文。"""
r = h.admin.post("/api/projects", json={})
assert r.status_code == 422
detail = r.json()["detail"]
assert detail.startswith("提交的数据有误") and "name" in detail
assert "Field required" not in detail
# 查询参数越界同样走中文(limit ge=1)
r = h.admin.get("/api/rbac/logs", params={"limit": 0})
assert r.status_code == 422 and "格式不正确" in r.json()["detail"]
def test_未登记导出接口fail_closed():
"""/export/* 一律按 EXPORT_MENU 判权限;没登记的导出名不允许 fail-open 成「登录即可下载」。"""
assert set(EXPORT_MENU) >= {"custom", "custom-updates", "projects", "updates", "staff", "focus"}
for name, menu in EXPORT_MENU.items():
assert resolve_rule("/api/export/" + name, "GET") == (menu, False)
with pytest.raises(HTTPException) as e:
resolve_rule("/api/export/not-registered", "GET")
assert e.value.status_code == 403
def test_操作日志服务端分页(h):
"""前端翻页发 limit/offset:跨页不重不漏,total 是全量而非当前页。"""
for i in range(3):
h.category(f"日志分页{i}")
total = h.admin.get("/api/rbac/logs", params={"days": 30, "limit": 1000}).json()["total"]
assert total >= 3
p0 = h.admin.get("/api/rbac/logs", params={"days": 30, "limit": 2, "offset": 0}).json()
p1 = h.admin.get("/api/rbac/logs", params={"days": 30, "limit": 2, "offset": 2}).json()
assert p0["total"] == p1["total"] == total
assert len(p0["items"]) == 2 and len(p1["items"]) == 2
ids0 = {x["id"] for x in p0["items"]}
ids1 = {x["id"] for x in p1["items"]}
assert not (ids0 & ids1)
def test_录入页跨菜单依赖(h):
"""只给「更新录入 rw」的账号:能读定制 meta/清单、能写定制交付记录(录入闭环),
但定制项目详情 / 新建仍归 custom 菜单。"""
pid = h.today_period_id
cp = h.custom("录入联动用定制项目")
c = h.user_client("intake_only", menus={"intake": "rw"})
assert c.get("/api/custom/meta").status_code == 200
assert c.get("/api/custom/projects").status_code == 200
r = c.post("/api/custom/updates", json={"custom_project_id": cp["id"], "period_id": pid, "content": "只凭录入权限写的交付记录"})
assert r.status_code == 200, r.text
# AI 录入两路也在 assist 里:录入页 AI 整理 / 落库对「只更新录入」账号要通
pr = c.post("/api/custom/ai/parse", json={"custom_project_id": cp["id"], "period_id": pid, "raw_text": "本周完成部署", "use_ai": False})
assert pr.status_code == 200, pr.text
parsed = pr.json()["parsed"]
cm = c.post("/api/custom/ai/commit", json={"custom_project_id": cp["id"], "period_id": pid, "raw_text": "本周完成部署", "parsed": parsed, "mode": "rule"})
assert cm.status_code == 200, cm.text
# 定制项目本体操作不在 assist 白名单里
assert c.get(f"/api/custom/projects/{cp['id']}").status_code == 403
assert c.post("/api/custom/projects", json={"name": "越界新建"}).status_code == 403
# 连 custom 读都没有的其它菜单账号(如只有 staff rw)不享受 assist
s = h.user_client("staff_only", menus={"staff": "rw"})
assert s.get("/api/custom/projects").status_code == 403
def test_定制meta下拉全集(h):
"""录入页 / 定制页的下拉选项唯一来源;前端不再各写一份。"""
d = h.admin.get("/api/custom/meta").json()
for key in ("stages", "regions", "region_groups", "pipeline", "aging_days",
"statuses", "origins", "placed_origins", "industries", "risks"):
assert key in d, key
assert d["stages"] and all({"code", "name", "color", "base_ratio"} <= set(s) for s in d["stages"])
assert d["pipeline"] and all("date_field" in s for s in d["pipeline"])
assert isinstance(d["aging_days"], int) and d["aging_days"] > 0
def test_定制项目删除连带交付记录(h):
cp = h.custom("待删除的定制项目")
h.custom_update(cp["id"], h.today_period_id, content="删之前的一条记录")
r = h.admin.delete("/api/custom/projects/" + str(cp["id"]))
assert r.status_code == 200, r.text
body = r.json()
assert body["ok"] and body["name"] == "待删除的定制项目" and body["deleted_updates"] == 1
ids = [x["id"] for x in h.admin.get("/api/custom/projects?archived=all").json()]
assert cp["id"] not in ids
assert h.admin.delete("/api/custom/projects/" + str(cp["id"])).status_code == 404
def test_导出项目默认不含归档(h):
"""GET /export/projects 与其余导出统一:不传 archived 时只导在用项目。"""
keep = h.project("导出默认口径-在用")
gone = h.project("导出默认口径-归档")
h.admin.patch("/api/projects/" + str(gone["id"]), json={"archived": True})
xlsx = h.admin.get("/api/export/projects")
assert xlsx.status_code == 200
from openpyxl import load_workbook
import io
names = {c.value for row in load_workbook(io.BytesIO(xlsx.content)).active.iter_rows(min_row=2) for c in row if isinstance(c.value, str)}
assert "导出默认口径-在用" in names and "导出默认口径-归档" not in names
both = load_workbook(io.BytesIO(h.admin.get("/api/export/projects?archived=all").content)).active
names_all = {c.value for row in both.iter_rows(min_row=2) for c in row if isinstance(c.value, str)}
assert "导出默认口径-归档" in names_all
def test_ensure_columns_补列与幂等(h):
"""老库补列通道:缺的可空列会补上;再跑一次不重复补、不报错。"""
from sqlalchemy import Column, Integer, MetaData, String, Table, create_engine, inspect, text
from app.schema_patch import ensure_columns
eng = create_engine("sqlite:///:memory:")
with eng.begin() as conn:
conn.execute(text("CREATE TABLE demo (id INTEGER PRIMARY KEY, name TEXT)"))
md = MetaData()
Table("demo", md, Column("id", Integer, primary_key=True),
Column("name", String), Column("extra", String))
assert ensure_columns(eng, md) == ["demo.extra"]
assert "extra" in {c["name"] for c in inspect(eng).get_columns("demo")}
assert ensure_columns(eng, md) == [] # 幂等
def test_STALE_COLUMNS白名单与模型不冲突(h):
"""守卫:白名单里登记的「死列」必须真的不在模型里——防止将来误把活列登记进去,
启动时被 DROP COLUMN 无声清掉。清理完成后也应把条目移出白名单。"""
from app.db import Base
from app.schema_patch import STALE_COLUMNS
for table, col in STALE_COLUMNS:
t = Base.metadata.tables.get(table)
assert t is None or col not in t.columns, f"{table}.{col} 还在模型里,不该登记为死列"
def test_drop_stale_columns_索引挡路只警告不崩(tmp_path):
"""DROP COLUMN 撞上索引/唯一约束是老库常态:逐列 try,跳过继续,绝不掀翻启动。"""
from sqlalchemy import create_engine, inspect, text
from app.schema_patch import STALE_COLUMNS, drop_stale_columns
table, col = STALE_COLUMNS[0]
# ① 列上有索引 → 返回 [](跳过),不抛
e1 = create_engine(f"sqlite:///{tmp_path / 'idx.db'}")
with e1.begin() as conn:
conn.execute(text(f"CREATE TABLE {table} (id INTEGER PRIMARY KEY, {col} TEXT)"))
conn.execute(text(f"CREATE INDEX ix_stale_{col} ON {table}({col})"))
assert drop_stale_columns(e1) == []
assert col in {c["name"] for c in inspect(e1).get_columns(table)}
# ② 干净列 → 删掉且幂等;③ 表不存在 → 静默跳过
e2 = create_engine(f"sqlite:///{tmp_path / 'ok.db'}")
with e2.begin() as conn:
conn.execute(text(f"CREATE TABLE {table} (id INTEGER PRIMARY KEY, {col} TEXT)"))
assert drop_stale_columns(e2) == [f"{table}.{col}"]
assert drop_stale_columns(e2) == []
e3 = create_engine(f"sqlite:///{tmp_path / 'empty.db'}")
assert drop_stale_columns(e3) == []
def test_assist_只读与写操作报错分句(h):
"""零权限账号读 assist 接口 → 提示「查看权限」;只读账号写 → 提示「可编辑权限」。"""
z = h.user_client("assist_zero", menus={})
r = z.get("/api/custom/meta")
assert r.status_code == 403 and "查看" in r.json()["detail"] and "编辑" not in r.json()["detail"]
ro = h.user_client("assist_ro", menus={"intake": "ro"})
assert ro.get("/api/custom/meta").status_code == 200 # 读走较高级别,ro 就够
r = ro.post("/api/custom/updates", json={"custom_project_id": 1, "period_id": 1, "content": "x"})
assert r.status_code == 403 and "可编辑" in r.json()["detail"]
# 编辑/删除单条交付记录不属 assist 三接口,仍严格走 custom
assert ro.patch("/api/custom/updates/1", json={"content": "y"}).status_code == 403
assert ro.delete("/api/custom/updates/1").status_code == 403
def test_写操作抛500也留审计(h):
"""业务代码抛穿中间件时,写操作必须按 status=500 补一条,不能丢痕。"""
from fastapi import FastAPI
from fastapi.testclient import TestClient
from starlette.routing import Mount
api_app = next(rt.app for rt in h.app.routes if isinstance(rt, Mount) and rt.path == "/api")
def boom():
raise RuntimeError("测试炸点")
route = api_app.router.routes
before = len(route)
api_app.add_route("/boom-test", boom, methods=["POST"])
try:
c = TestClient(h.app, raise_server_exceptions=False)
c.post("/api/boom-test")
finally:
del route[before:]
logs = h.admin.get("/api/rbac/logs", params={"action": "create"}).json()
hit = [x for x in logs["items"] if x["path"] == "/api/boom-test"]
assert hit and hit[0]["status"] == 500
def test_脏数值与空内容报400中文(h):
"""写入口对畸形输入给 400 中文,不裸抛 float('abc') 变 500(README「报错一律中文」)。"""
pid = h.today_period_id
cp = h.custom("脏数据靶子")
bad = [
("/api/custom/updates", {"custom_project_id": cp["id"], "period_id": pid, "content": "x", "progress": "abc"}),
("/api/custom/updates", {"custom_project_id": cp["id"], "period_id": pid, "content": "x", "amount_delta": "好多"}),
]
for url, body in bad:
r = h.admin.post(url, json=body)
assert r.status_code == 400 and "数字" in r.json()["detail"], r.text
# 正文/摘要/原文全空 → 400,不写出全空记录
r = h.admin.post("/api/custom/updates", json={"custom_project_id": cp["id"], "period_id": pid})
assert r.status_code == 400 and "空" in r.json()["detail"]
# 项目 PATCH 脏数值 / 脏布尔
assert "数字" in h.admin.patch(f"/api/custom/projects/{cp['id']}", json={"progress": "高"}).json()["detail"]
assert h.admin.patch(f"/api/custom/projects/{cp['id']}", json={"is_key": "也许"}).status_code == 400
# 是/否能接受 0/1/true 字符串
assert h.admin.patch(f"/api/custom/projects/{cp['id']}", json={"is_key": 1}).json()["is_key"] is True
def test_AI落库校验状态与进度(h):
"""POST /api/ai/commit:非法状态 400(与 POST /updates 同口径),进度非数字 400。"""
p = h.project("AI靶项目")
pid = h.today_period_id
r = h.admin.post("/api/ai/commit", json={
"project_id": p["id"], "period_id": pid, "raw_text": "推进", "mode": "rule",
"parsed": {"status": "外星状态", "progress": 50, "updates": []}})
assert r.status_code == 400 and "状态" in r.json()["detail"], r.text
r = h.admin.post("/api/ai/commit", json={
"project_id": p["id"], "period_id": pid, "raw_text": "推进", "mode": "rule",
"parsed": {"progress": "五成", "updates": []}})
assert r.status_code == 400 and "数字" in r.json()["detail"], r.text
def test_前端查询参数必须在后端有声明(h):
"""批次 D 抓到过「前端一直发 keyword=、后端一直丢」的整类 bug——立静态防线。
前端换成 React + Vite(web/src)后,查询键集中在接口层 web/src/api/endpoints.ts:
接口层点名发出的每个键必须在后端 OpenAPI 里声明过;视图传上来但接口层没点名的键会被丢掉
(等于不发),所以守住接口层这一张表就够,口径见 web/src/api/endpoints.ts 顶部注释。"""
import pathlib
import re
src = pathlib.Path("web/src/api/endpoints.ts").read_text(encoding="utf-8")
views = pathlib.Path("web/src")
spec = h.admin.get("/api/openapi.json").json()
routes: dict[str, set] = {}
for path, ops in spec["paths"].items():
for op in ops.values():
rt = re.sub(r"\{[a-zA-Z_]+\}", "0", "/api" + path)
routes.setdefault(rt, set()).update(p["name"] for p in op.get("parameters", []))
body_routes: dict[str, set] = {}
body_keys: dict[str, set] = {}
problems = []
strict = 0
def check(route, keys_blob, where):
nonlocal strict
if "{" in route:
return # 路径参数拼在路由里,不是查询串,不误报
rt = re.sub(r"\{[a-zA-Z_]+\}", "0", "/api" + route)
if rt not in routes:
return # 路由拼在变量里匹配不上,不误报
strict += 1
for key in re.findall(r"([a-z_]+)\s*:", keys_blob):
if key not in routes[rt]:
problems.append(where + ":" + rt + " 发 " + key + "= 后端未声明")
# 形态一:接口层函数调用 + 对象字面量。get/del 的字面量是查询参数(对 OpenAPI parameters);
# post/patch/put 的字面量是 JSON body(对 requestBody schema 的属性,schema 没属性就跳过)
for m in re.finditer(r'(get|post|patch|del|put)(?:<[^>]*>)?\(\s*"(/[a-z0-9_/{}.-]+)"\s*,\s*\{([^)]*?)\}', src, re.S):
verb, route, blob = m.group(1), m.group(2), m.group(3)
if verb in ("get", "del"):
check(route, blob, "接口层查询")
else:
for sub in re.finditer(r'\{\s*([a-z_]+)\s*:', " " + blob):
pass # 嵌套对象(如 settings 的 values)由内层再扫一次
body_routes.setdefault(re.sub(r"\{[a-zA-Z_]+\}", "0", "/api" + route), set()).add(verb)
body_keys.setdefault(re.sub(r"\{[a-zA-Z_]+\}", "0", "/api" + route), set()).update(re.findall(r"([a-z_]+)\s*:", blob))
# 形态二:导出 URL —— "/export/xxx" + tail({ key: ... })
for m in re.finditer(r'"(/[a-z0-9_/-]+)"\s*\+\s*tail\(\{([^)]*?)\}', src, re.S):
check(m.group(1), m.group(2), "导出")
# 形态三:视图里手写的 ?k= 完整串(正常应该没有,出现就必须对得上)
for f in sorted(views.rglob("*.ts*")):
if f.name == "endpoints.ts":
continue
for m in re.finditer(r'["`@](/[a-z0-9_/-]+)\?([a-z_]+=[^"`]*)["]$]', f.read_text(encoding="utf-8")):
check(m.group(1), m.group(2), f.name)
# 写请求的 body 键:与 requestBody schema 的属性名对表(schema 未声明属性的接口跳过)
body_props: dict[str, set] = {}
for path, ops in spec["paths"].items():
for verb, op in ops.items():
if not isinstance(op, dict):
continue
rt = re.sub(r"\{[a-zA-Z_]+\}", "0", "/api" + path) + "#" + verb
sch = ((op.get("requestBody") or {}).get("content") or {}).get("application/json", {}).get("schema") or {}
name = (sch.get("$ref") or "").split("/")[-1]
props = ((spec.get("components", {}).get("schemas", {}).get(name) or {}).get("properties") or {}) if name else {}
if props:
body_props.setdefault(rt, set()).update(props.keys())
for rt, keys in body_keys.items():
for verb in body_routes.get(rt, set()):
props = body_props.get(rt + "#" + verb)
if not props:
continue
strict += 1
for k in sorted(keys - props):
if k not in {"values", "parsed", "targets"}: # 再嵌套一层的容器键由内层键把关
problems.append("接口层body:" + rt + " 的 " + k + " 后端 body 未声明")
assert strict >= 12, "只扫到 " + str(strict) + " 处带查询键的调用,正则可能失效"
assert not problems, "\n".join(problems)
def test_正文富文本按约定存_按纯文本出表(h):
"""正文支持简单富文本:前端编辑器只发 <b>/<i>/<u>/<br>/<span data-c="语义色"> 这一小组标签
(约定见 web/src/utils/richtext.ts),库里原样存,Excel 出表必须降级成纯文本。
这条约定是编辑器、展示端、导出三处共用的,改任何一边都要同步,所以钉在契约测试里。"""
from io import BytesIO
from openpyxl import load_workbook
from app.export import plain
rich = '<b>完成联调</b>与<span data-c="danger">3 项阻塞</span><br>下周<i>验收</i>&amp;交付'
assert plain(rich) == "完成联调与3 项阻塞\n下周验收&交付"
# 编辑器(Tiptap)产出每行一个 <p>:相邻段落只算一个换行,空段落算一个空行,别凭空多打行
assert plain("<p>L1</p><p>L2</p><p><br></p><p><b>L4</b></p>") == "L1\nL2\n\nL4"
assert plain("<p>就一行</p>") == "就一行"
assert plain("A<b 项目") == "A<b 项目" # 名称里的尖括号不能被误伤
assert plain(None) is None and plain(12.5) == 12.5 # 非字符串原样走
r = h.admin.post("/api/focus", json={"content": "富文本导出验证", "detail": rich})
assert r.status_code == 200, r.text
fid = r.json()["id"]
try:
x = h.admin.get("/api/export/focus", params={"archived": "all"})
assert x.status_code == 200
ws = load_workbook(BytesIO(x.content)).active
cells = [c.value for row in ws.iter_rows() for c in row if isinstance(c.value, str)]
assert any("富文本导出验证" in v for v in cells), "新建的重点工作没进导出"
detail = [v for v in cells if "下周" in v]
assert detail, "说明列没导出到"
assert "<" not in detail[0] and "data-c" not in detail[0], detail[0]
assert "完成联调与3 项阻塞" in detail[0]
finally:
assert h.admin.delete("/api/focus/" + str(fid)).status_code == 200