217 lines
7.4 KiB
Python
217 lines
7.4 KiB
Python
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, 503, "service_unavailable"),
|
|
(502, 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
|