127 lines
6.3 KiB
Python
127 lines
6.3 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
|
||
# 定制项目本体操作不在 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) == [] # 幂等
|