Coverage for tests/test_dependency_contextvars.py: 100%
26 statements
« prev ^ index » next coverage.py v7.6.1, created at 2025-05-05 00:03 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2025-05-05 00:03 +0000
1from contextvars import ContextVar 1abcdef
2from typing import Any, Awaitable, Callable, Dict, Optional 1abcdef
4from fastapi import Depends, FastAPI, Request, Response 1abcdef
5from fastapi.testclient import TestClient 1abcdef
7legacy_request_state_context_var: ContextVar[Optional[Dict[str, Any]]] = ContextVar( 1abcdef
8 "legacy_request_state_context_var", default=None
9)
11app = FastAPI() 1abcdef
14async def set_up_request_state_dependency(): 1abcdef
15 request_state = {"user": "deadpond"} 1ghijkl
16 contextvar_token = legacy_request_state_context_var.set(request_state) 1ghijkl
17 yield request_state 1ghijkl
18 legacy_request_state_context_var.reset(contextvar_token) 1ghijkl
21@app.middleware("http") 1abcdef
22async def custom_middleware( 1abcdef
23 request: Request, call_next: Callable[[Request], Awaitable[Response]]
24):
25 response = await call_next(request) 1ghijkl
26 response.headers["custom"] = "foo" 1ghijkl
27 return response 1ghijkl
30@app.get("/user", dependencies=[Depends(set_up_request_state_dependency)]) 1abcdef
31def get_user(): 1abcdef
32 request_state = legacy_request_state_context_var.get() 1ghijkl
33 assert request_state 1ghijkl
34 return request_state["user"] 1ghijkl
37client = TestClient(app) 1abcdef
40def test_dependency_contextvars(): 1abcdef
41 """
42 Check that custom middlewares don't affect the contextvar context for dependencies.
44 The code before yield and the code after yield should be run in the same contextvar
45 context, so that request_state_context_var.reset(contextvar_token).
47 If they are run in a different context, that raises an error.
48 """
49 response = client.get("/user") 1ghijkl
50 assert response.json() == "deadpond" 1ghijkl
51 assert response.headers["custom"] == "foo" 1ghijkl