Coverage for tests/test_dependency_contextvars.py: 100%
26 statements
« prev ^ index » next coverage.py v7.6.1, created at 2024-08-08 03:53 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2024-08-08 03:53 +0000
1from contextvars import ContextVar 1abcde
2from typing import Any, Awaitable, Callable, Dict, Optional 1abcde
4from fastapi import Depends, FastAPI, Request, Response 1abcde
5from fastapi.testclient import TestClient 1abcde
7legacy_request_state_context_var: ContextVar[Optional[Dict[str, Any]]] = ContextVar( 1abcde
8 "legacy_request_state_context_var", default=None
9)
11app = FastAPI() 1abcde
14async def set_up_request_state_dependency(): 1abcde
15 request_state = {"user": "deadpond"} 1abcde
16 contextvar_token = legacy_request_state_context_var.set(request_state) 1abcde
17 yield request_state 1abcde
18 legacy_request_state_context_var.reset(contextvar_token) 1abcde
21@app.middleware("http") 1abcde
22async def custom_middleware( 1abcde
23 request: Request, call_next: Callable[[Request], Awaitable[Response]]
24):
25 response = await call_next(request) 1abcde
26 response.headers["custom"] = "foo" 1abcde
27 return response 1abcde
30@app.get("/user", dependencies=[Depends(set_up_request_state_dependency)]) 1abcde
31def get_user(): 1abcde
32 request_state = legacy_request_state_context_var.get() 1abcde
33 assert request_state 1abcde
34 return request_state["user"] 1abcde
37client = TestClient(app) 1abcde
40def test_dependency_contextvars(): 1abcde
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") 1abcde
50 assert response.json() == "deadpond" 1abcde
51 assert response.headers["custom"] == "foo" 1abcde