unis_manager/tests/test_api_contract.py

202 lines
10 KiB
Python
Raw Normal View History

# 接口契约:错误信息语言、健康检查、导出权限 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
fix(backend): 复审批次 B——审计 deny/revoke/500 三连 + assist AI 通路 + 启动兜底防崩 审计(audit.py): - 403 一律改记 action=deny(含只读越权探测,此前 GET 403 零留痕、写 403 记成 create), 与 README「越权返回 403 并记 deny」及 models 注释对齐;rbac/meta 筛选下拉补「越权」。 - /revoke 判定提到 METHOD_ACTION 之前——此前 POST 先命中 create,action=revoke 恒 0 条, 前端「下线」筛选是死选项(旧测试还断言 total==0 把 bug 当规范);测试改为真下线断言可查。 - call_next 包 try/except:写操作抛穿中间件时按 status=500 补记,不再丢失败的写操作。 权限(security.py): - assist 白名单补 POST /custom/ai/parse、/custom/ai/commit——「只有更新录入」账号的 AI 录入两路此前必 403(7ff0242 立意只做了直接写入);前端已保证带既有 project id, 不走新建旁路。 - assist 403 文案按读/写分句(只读请求不再误导「需要可编辑权限」)。 启动健壮性: - drop_stale_columns 逐列 try/except(索引/UNIQUE/视图引用是 DROP COLUMN 报错老库常态, 跳过并中文警告,绝不掀翻导入期启动);非 SQLite 方言直接跳过。 - ensure_seed 兜底重写:优先补给「启用但无管理员」的最早账号;全员停用则复活最早账号; 插 UserRole 前查重,杜绝 UNIQUE 冲突炸启动(复现场景已建测试)。 测试(93 → 99):deny 双方法留痕 / revoke 可查 / 500 留痕 / assist 读写文案+AI 通路 / STALE_COLUMNS 与模型一致性守卫 / drop 索引挡路不崩。README assist 清单同步。
2026-11-03 18:05:05 +00:00
# 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) == [] # 幂等
fix(backend): 复审批次 B——审计 deny/revoke/500 三连 + assist AI 通路 + 启动兜底防崩 审计(audit.py): - 403 一律改记 action=deny(含只读越权探测,此前 GET 403 零留痕、写 403 记成 create), 与 README「越权返回 403 并记 deny」及 models 注释对齐;rbac/meta 筛选下拉补「越权」。 - /revoke 判定提到 METHOD_ACTION 之前——此前 POST 先命中 create,action=revoke 恒 0 条, 前端「下线」筛选是死选项(旧测试还断言 total==0 把 bug 当规范);测试改为真下线断言可查。 - call_next 包 try/except:写操作抛穿中间件时按 status=500 补记,不再丢失败的写操作。 权限(security.py): - assist 白名单补 POST /custom/ai/parse、/custom/ai/commit——「只有更新录入」账号的 AI 录入两路此前必 403(7ff0242 立意只做了直接写入);前端已保证带既有 project id, 不走新建旁路。 - assist 403 文案按读/写分句(只读请求不再误导「需要可编辑权限」)。 启动健壮性: - drop_stale_columns 逐列 try/except(索引/UNIQUE/视图引用是 DROP COLUMN 报错老库常态, 跳过并中文警告,绝不掀翻导入期启动);非 SQLite 方言直接跳过。 - ensure_seed 兜底重写:优先补给「启用但无管理员」的最早账号;全员停用则复活最早账号; 插 UserRole 前查重,杜绝 UNIQUE 冲突炸启动(复现场景已建测试)。 测试(93 → 99):deny 双方法留痕 / revoke 可查 / 500 留痕 / assist 读写文案+AI 通路 / STALE_COLUMNS 与模型一致性守卫 / drop 索引挡路不崩。README assist 清单同步。
2026-11-03 18:05:05 +00:00
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