238 lines
12 KiB
Python
238 lines
12 KiB
Python
# 接口契约:错误信息语言、健康检查、导出权限 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
|
||
|
||
|