unis_manager/tests/test_api_contract.py

54 lines
2.4 KiB
Python
Raw 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)