Complete worked example
python
from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException
from fastapi.testclient import TestClient
from pydantic import BaseModel
class PublicRole(BaseModel):
id: int
title: str
user: str
def inspect_example(request):
app = FastAPI()
def principal():
return "demo"
@app.get("/roles/{role_id}", response_model=PublicRole,
responses={404: {"description": "Role not found"}})
def read(role_id: int, user: Annotated[str, Depends(principal)]):
if role_id != 1:
raise HTTPException(404, "Role not found")
return {"id": 1, "title": "QA", "user": user, "private_note": "hidden"}
if request.get("override"):
app.dependency_overrides[principal] = lambda: "review"
try:
with TestClient(app) as client:
response = client.get(f"/roles/{request.get('id', 1)}")
finally:
app.dependency_overrides.clear()
schema = app.openapi()
declared = schema["paths"]["/roles/{role_id}"]["get"]["responses"]
properties = schema["components"]["schemas"]["PublicRole"]["properties"]
return {"status": response.status_code, "body": response.json(),
"documented_404": "404" in declared, "documented_410": "410" in declared,
"private_in_schema": "private_note" in properties,
"overrides_cleared": not app.dependency_overrides}- Reasoning
- The override map uses the original callable as its key. The request runs with the chosen override, and finally clears that test state. The helper then inspects the OpenAPI response declarations and the public schema, reporting whether a private internal note appears. The result includes overrides_cleared so cleanup is an observable requirement. A successful isolated request is not enough when leftover overrides can change later tests. Test setup should preserve any pre-existing state in a shared application; this fixture creates a new app and therefore begins with an empty override map.