Coverage for tests / test_dependency_contextvars.py: 100%
27 statements
« prev ^ index » next coverage.py v7.13.3, created at 2026-04-06 01:24 +0000
« prev ^ index » next coverage.py v7.13.3, created at 2026-04-06 01:24 +0000
1from collections.abc import Awaitable, Callable 1abcd
2from contextvars import ContextVar 1abcd
3from typing import Any 1abcd
5from fastapi import Depends, FastAPI, Request, Response 1abcd
6from fastapi.testclient import TestClient 1abcd
8legacy_request_state_context_var: ContextVar[dict[str, Any] | None] = ContextVar( 1abcd
9 "legacy_request_state_context_var", default=None
10)
12app = FastAPI() 1abcd
15async def set_up_request_state_dependency(): 1abcd
16 request_state = {"user": "deadpond"} 1efgh
17 contextvar_token = legacy_request_state_context_var.set(request_state) 1efgh
18 yield request_state 1efgh
19 legacy_request_state_context_var.reset(contextvar_token) 1efgh
22@app.middleware("http") 1abcd
23async def custom_middleware( 1abcd
24 request: Request, call_next: Callable[[Request], Awaitable[Response]]
25):
26 response = await call_next(request) 1efgh
27 response.headers["custom"] = "foo" 1efgh
28 return response 1efgh
31@app.get("/user", dependencies=[Depends(set_up_request_state_dependency)]) 1abcd
32def get_user(): 1abcd
33 request_state = legacy_request_state_context_var.get() 1efgh
34 assert request_state 1efgh
35 return request_state["user"] 1efgh
38client = TestClient(app) 1abcd
41def test_dependency_contextvars(): 1abcd
42 """
43 Check that custom middlewares don't affect the contextvar context for dependencies.
45 The code before yield and the code after yield should be run in the same contextvar
46 context, so that request_state_context_var.reset(contextvar_token).
48 If they are run in a different context, that raises an error.
49 """
50 response = client.get("/user") 1efgh
51 assert response.json() == "deadpond" 1efgh
52 assert response.headers["custom"] == "foo" 1efgh