"""请求校验错误信封契约测试(文档 §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"