Complete worked example
python
from typing import Annotated
from fastapi import Depends, FastAPI
from fastapi.responses import StreamingResponse
from fastapi.testclient import TestClient
def inspect_example(requests):
app = FastAPI()
events = []
def resource():
state = {"open": True}
events.append("acquire")
try:
yield state
finally:
state["open"] = False
events.append("release")
@app.get("/stream")
def read(state: Annotated[dict, Depends(resource, scope="request")]):
def chunks():
events.append("stream")
yield "open" if state["open"] else "closed"
return StreamingResponse(chunks(), media_type="text/plain")
with TestClient(app) as client:
bodies = [client.get("/stream").text for _ in range(requests)]
return {"bodies": bodies, "events": events}- Reasoning
- The synthetic resource has one open flag. Its dependency records acquisition, yields the resource and closes it in finally. The streaming generator records when it runs and emits open or closed according to the resource state at that instant. A local TestClient reads the response fully before the helper inspects the trace. With scope=request, acquisition precedes streaming and release follows it. The test observes a concrete sequence and body. It does not rely on wall-clock timing or a real connection pool.