Files
group_fqcd_jr/tests/unit/api/test_request_validation_envelope.py
T
张胜宇 e239eb778b docs: 品牌全量口径统一为「南方基金」+ 作废文档清理
1) 客服 Agent 四份交付文档 + 构建脚手架:品牌由包装占位 XX科技 / 旧名 南方财富
   统一为南方基金(热线 400-889-8899 / 官网 nffund.com),系统名改为「智能服务系统」;
   同步追加 §0.4 修订记录行,工程记录行保留原占位字面以支撑硬编码扫描验收。
2) 开发文档:清理 28 份已作废/残留文档(14 份移出归档 + 14 份仓库副本),
   新增《文档规整方案与开发前待决事项-2026-09-17》。
3) 客服agent 四份交付文档首次纳入本分支。
2026-09-17 15:15:22 +08:00

54 lines
2.2 KiB
Python

"""请求校验错误信封契约测试(文档 §3.4 / §3.5 / §3.6 `AGENT_INPUT_INVALID`)。
修复前 FastAPI 返回自己的 `{"detail": [...]}` 结构,与业务异常的 `{error, meta}` 信封
不一致,客户端必须为"参数错误"单独兼容一套解析逻辑。本测试锁定修复后的形状:
状态码 422、顶层只有 `error`/`meta`、字段级原因进 `error.field_errors`、
`meta.trace_id` 沿用 `X-Trace-ID` 回显规则,同时保证鉴权仍先于参数校验失败。
"""
from fastapi.testclient import TestClient
from app.api.dependencies.auth import build_request_context
from app.core.contracts import RequestContext
from app.main import create_app
AGENT_RUNS = "/api/v1/agent-runs"
def _authenticated_client() -> TestClient:
application = create_app()
async def context() -> RequestContext:
return RequestContext(
user_id="1", trace_id="validation-trace", permissions=("agent:run",)
)
application.dependency_overrides[build_request_context] = context
return TestClient(application)
def test_missing_body_fields_use_unified_envelope() -> None:
with _authenticated_client() as client:
response = client.post(AGENT_RUNS, json={}, headers={"X-Trace-ID": "val-trace"})
assert response.status_code == 422
body = response.json()
assert set(body) == {"error", "meta"}, "校验错误只允许 error/meta 两个顶层字段"
error = body["error"]
assert error["code"] == "AGENT_INPUT_INVALID"
assert error["retryable"] is False
assert error["message"] == "请求参数不满足接口约束"
fields = {item["field"] for item in error["field_errors"]}
assert {"body.agent_type", "body.message", "body.session_id"} <= fields
assert all(item["message"] for item in error["field_errors"])
assert body["meta"] == {"trace_id": "val-trace"}
def test_validation_handler_does_not_hijack_authentication() -> None:
"""未带令牌 + 参数也不合法:必须仍是 401,参数校验不得掩盖鉴权失败。"""
with TestClient(create_app()) as client:
response = client.post(AGENT_RUNS, json={})
assert response.status_code == 401
assert response.json()["error"]["code"] == "AUTHENTICATION_REQUIRED"