feat(api): define public problem errors, pagination, and retry contract
This commit is contained in:
1 parent
b2f6e87bfe
commit
565ca94bbb
86 files changed
+8200
-154
No files matched your search
@@ -6,7 +6,7 @@ import pytest
|
||||
import yaml
|
||||
from pydantic import BaseModel, ValidationError
|
||||
|
||||
from lincodex_ml.api.models import MLHealthResponse, MLReadinessResponse
|
||||
from lincodex_ml.api.models import MLHealthResponse, MLReadinessResponse, Problem
|
||||
from lincodex_ml.main import app
|
||||
|
||||
CONTRACT_PATH = Path(__file__).resolve().parents[2] / "api" / "ml" / "openapi.bundle.yml"
|
||||
@@ -20,6 +20,14 @@ def _resolve_schema(document: dict[str, Any], schema: dict[str, Any]) -> dict[st
|
||||
return document["components"]["schemas"][component_name]
|
||||
|
||||
|
||||
def _resolve_response(document: dict[str, Any], response: dict[str, Any]) -> dict[str, Any]:
|
||||
reference = response.get("$ref")
|
||||
if reference is None:
|
||||
return response
|
||||
component_name = reference.rsplit("/", maxsplit=1)[-1]
|
||||
return document["components"]["responses"][component_name]
|
||||
|
||||
|
||||
def _status_values(document: dict[str, Any], response: dict[str, Any]) -> list[str]:
|
||||
content = response["content"]["application/json"]["schema"]
|
||||
response_schema = _resolve_schema(document, content)
|
||||
@@ -47,6 +55,10 @@ def test_health_and_readiness_match_shared_openapi_contract() -> None:
|
||||
assert actual_operation["operationId"] == expected_operation["operationId"]
|
||||
|
||||
for response_code, expected_response in expected_operation["responses"].items():
|
||||
# The default problem response is checked at runtime below; FastAPI
|
||||
# cannot describe it with the problem media type.
|
||||
if response_code == "default":
|
||||
continue
|
||||
actual_response = actual_operation["responses"][response_code]
|
||||
assert _status_values(contract, expected_response) == _status_values(
|
||||
implementation, actual_response
|
||||
@@ -68,6 +80,27 @@ async def test_unready_probe_returns_the_contractual_503_response() -> None:
|
||||
assert response.json()["status"] in _status_values(contract, readiness["503"])
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@pytest.mark.parametrize(("method", "path"), [("POST", "/healthz"), ("GET", "/missing")])
|
||||
async def test_error_responses_match_the_contractual_default_response(
|
||||
method: str, path: str
|
||||
) -> None:
|
||||
contract = yaml.safe_load(CONTRACT_PATH.read_text(encoding="utf-8"))
|
||||
default = _resolve_response(
|
||||
contract, contract["paths"]["/healthz"]["get"]["responses"]["default"]
|
||||
)
|
||||
(media_type,) = default["content"]
|
||||
|
||||
async with httpx.AsyncClient(
|
||||
transport=httpx.ASGITransport(app=app), base_url="http://test"
|
||||
) as client:
|
||||
response = await client.request(method, path)
|
||||
|
||||
assert response.headers["content-type"] == media_type
|
||||
problem = Problem.model_validate(response.json())
|
||||
assert problem.status == response.status_code
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("model", "valid_status"),
|
||||
[(MLHealthResponse, "ok"), (MLReadinessResponse, "ready"), (MLReadinessResponse, "not_ready")],
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
import logging
|
||||
import logging.config
|
||||
from typing import Annotated
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from fastapi import FastAPI, HTTPException, Query
|
||||
from pydantic import BaseModel
|
||||
from uvicorn.config import LOGGING_CONFIG
|
||||
|
||||
from lincodex_ml.api.models import Problem
|
||||
from lincodex_ml.api.problems import PROBLEM_MEDIA_TYPE
|
||||
from lincodex_ml.infra.logging import UVICORN_LOGGERS, JsonFormatter, configure_logging
|
||||
from lincodex_ml.main import create_app
|
||||
|
||||
SENSITIVE_TEXT = "resume of Jane Doe, phone +7 900 000-00-00"
|
||||
|
||||
|
||||
class ProbeInput(BaseModel):
|
||||
name: str
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def anyio_backend() -> str:
|
||||
return "asyncio"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def probe_app() -> FastAPI:
|
||||
"""The service app plus test-only routes that the ML contract does not have."""
|
||||
application = create_app()
|
||||
|
||||
@application.get("/probe")
|
||||
async def probe(limit: Annotated[int, Query(ge=1, le=100)]) -> dict[str, int]:
|
||||
return {"limit": limit}
|
||||
|
||||
@application.post("/probe")
|
||||
async def create_probe(payload: ProbeInput) -> dict[str, str]:
|
||||
return {"name": payload.name}
|
||||
|
||||
@application.get("/failure")
|
||||
async def failure() -> None:
|
||||
raise RuntimeError(SENSITIVE_TEXT)
|
||||
|
||||
@application.get("/status/{code}")
|
||||
async def raise_status(code: int) -> None:
|
||||
headers = {"Retry-After": "30"} if code == 429 else None
|
||||
raise HTTPException(status_code=code, detail=SENSITIVE_TEXT, headers=headers)
|
||||
|
||||
return application
|
||||
|
||||
|
||||
async def _request(
|
||||
application: FastAPI,
|
||||
method: str,
|
||||
path: str,
|
||||
json: object = None,
|
||||
content: str | None = None,
|
||||
headers: dict[str, str] | None = None,
|
||||
) -> httpx.Response:
|
||||
# Unhandled errors must reach the problem handler instead of the test client.
|
||||
async with httpx.AsyncClient(
|
||||
transport=httpx.ASGITransport(app=application, raise_app_exceptions=False),
|
||||
base_url="http://test",
|
||||
) as client:
|
||||
return await client.request(method, path, json=json, content=content, headers=headers)
|
||||
|
||||
|
||||
def _problem(response: httpx.Response, status: int, code: str) -> Problem:
|
||||
assert response.status_code == status
|
||||
assert response.headers["content-type"] == PROBLEM_MEDIA_TYPE
|
||||
problem = Problem.model_validate(response.json())
|
||||
assert problem.status == status
|
||||
assert problem.code.root == code
|
||||
assert problem.type == f"urn:lincodex:problem:{code}"
|
||||
return problem
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_unhandled_exception_ends_at_the_problem_boundary(probe_app: FastAPI) -> None:
|
||||
# The default transport re-raises anything that escapes the application,
|
||||
# so a problem response here proves that nothing reaches Starlette's
|
||||
# ServerErrorMiddleware, which would re-raise to uvicorn.
|
||||
async with httpx.AsyncClient(
|
||||
transport=httpx.ASGITransport(app=probe_app), base_url="http://test"
|
||||
) as client:
|
||||
response = await client.get("/failure", headers={"X-Request-ID": "req-1"})
|
||||
|
||||
problem = _problem(response, 500, "internal")
|
||||
assert problem.trace_id == "req-1"
|
||||
assert "Jane" not in response.text
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_unhandled_exception_text_reaches_no_log_record(
|
||||
probe_app: FastAPI, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
# create_app replaced the root handlers, so capture at the root again.
|
||||
logging.getLogger().addHandler(caplog.handler)
|
||||
caplog.set_level(logging.DEBUG)
|
||||
try:
|
||||
response = await _request(probe_app, "GET", "/failure")
|
||||
finally:
|
||||
logging.getLogger().removeHandler(caplog.handler)
|
||||
|
||||
_problem(response, 500, "internal")
|
||||
assert any("RuntimeError" in record.getMessage() for record in caplog.records)
|
||||
formatter = JsonFormatter()
|
||||
for record in caplog.records:
|
||||
assert "Jane" not in record.getMessage()
|
||||
assert "Jane" not in formatter.format(record)
|
||||
assert record.exc_info is None or "Jane" not in str(record.exc_info[1])
|
||||
|
||||
|
||||
def test_uvicorn_loggers_are_redacted_after_uvicorn_configures_them(
|
||||
capsys: pytest.CaptureFixture[str],
|
||||
) -> None:
|
||||
# uvicorn applies its logging configuration before it imports the
|
||||
# application; configure_logging then takes its loggers over.
|
||||
logging.config.dictConfig(LOGGING_CONFIG)
|
||||
configure_logging()
|
||||
capsys.readouterr()
|
||||
|
||||
try:
|
||||
raise RuntimeError(SENSITIVE_TEXT)
|
||||
except RuntimeError:
|
||||
logging.getLogger("uvicorn.error").exception("Exception in ASGI application")
|
||||
|
||||
output = capsys.readouterr().err
|
||||
assert '"exception_type":"RuntimeError"' in output
|
||||
assert "Exception in ASGI application" in output
|
||||
assert "Jane" not in output
|
||||
assert "Traceback" not in output
|
||||
for name in UVICORN_LOGGERS:
|
||||
assert logging.getLogger(name).handlers == []
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@pytest.mark.parametrize(
|
||||
("raised", "status", "code"),
|
||||
[
|
||||
(400, 400, "validation_failed"),
|
||||
(401, 401, "unauthenticated"),
|
||||
(403, 403, "forbidden"),
|
||||
(409, 409, "state_conflict"),
|
||||
(413, 413, "payload_too_large"),
|
||||
(415, 415, "unsupported_media_type"),
|
||||
(422, 400, "validation_failed"),
|
||||
(428, 428, "precondition_required"),
|
||||
(429, 429, "rate_limited"),
|
||||
(501, 501, "not_implemented"),
|
||||
(418, 400, "validation_failed"),
|
||||
(503, 500, "internal"),
|
||||
],
|
||||
)
|
||||
async def test_http_exceptions_map_to_contract_problems(
|
||||
probe_app: FastAPI, raised: int, status: int, code: str
|
||||
) -> None:
|
||||
response = await _request(probe_app, "GET", f"/status/{raised}")
|
||||
|
||||
_problem(response, status, code)
|
||||
assert "Jane" not in response.text
|
||||
if raised == 429:
|
||||
assert response.headers["retry-after"] == "30"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@pytest.mark.parametrize(
|
||||
("method", "path", "body", "expected"),
|
||||
[
|
||||
("GET", "/probe?limit=0", None, [{"in": "query", "pointer": "/limit", "code": "invalid"}]),
|
||||
("GET", "/probe", None, [{"in": "query", "pointer": "/limit", "code": "required"}]),
|
||||
("POST", "/probe", {}, [{"in": "body", "pointer": "/name", "code": "required"}]),
|
||||
("POST", "/probe", {"name": 1}, [{"in": "body", "pointer": "/name", "code": "invalid"}]),
|
||||
("POST", "/probe", '{"name":', [{"in": "body", "pointer": "", "code": "invalid"}]),
|
||||
],
|
||||
)
|
||||
async def test_request_validation_returns_validation_problem(
|
||||
probe_app: FastAPI,
|
||||
method: str,
|
||||
path: str,
|
||||
body: object,
|
||||
expected: list[dict[str, str]],
|
||||
) -> None:
|
||||
if isinstance(body, str):
|
||||
response = await _request(
|
||||
probe_app, method, path, content=body, headers={"Content-Type": "application/json"}
|
||||
)
|
||||
else:
|
||||
response = await _request(probe_app, method, path, json=body)
|
||||
|
||||
problem = _problem(response, 400, "validation_failed")
|
||||
fields = [
|
||||
{"in": field.in_.root, "pointer": field.pointer, "code": field.code}
|
||||
for field in problem.errors or []
|
||||
]
|
||||
assert fields == expected
|
||||
assert all(field.message for field in problem.errors or [])
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_unknown_route_and_method_return_problems(probe_app: FastAPI) -> None:
|
||||
missing = await _request(probe_app, "GET", "/missing")
|
||||
_problem(missing, 404, "not_found")
|
||||
|
||||
not_allowed = await _request(probe_app, "DELETE", "/healthz")
|
||||
_problem(not_allowed, 405, "method_not_allowed")
|
||||
assert not_allowed.headers["allow"] == "GET"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_invalid_request_id_is_not_echoed(probe_app: FastAPI) -> None:
|
||||
response = await _request(probe_app, "GET", "/missing", headers={"X-Request-ID": "bad id"})
|
||||
|
||||
assert _problem(response, 404, "not_found").trace_id is None
|
||||
Reference in new issue
Block a user