Coverage for tests / test_http_connection_injection.py: 100%

24 statements  

« prev     ^ index     » next       coverage.py v7.13.3, created at 2026-04-06 01:24 +0000

1from fastapi import Depends, FastAPI 1abcd

2from fastapi.requests import HTTPConnection 1abcd

3from fastapi.testclient import TestClient 1abcd

4from starlette.websockets import WebSocket 1abcd

5 

6app = FastAPI() 1abcd

7app.state.value = 42 1abcd

8 

9 

10async def extract_value_from_http_connection(conn: HTTPConnection): 1abcd

11 return conn.app.state.value 1heijfkg

12 

13 

14@app.get("/http") 1abcd

15async def get_value_by_http(value: int = Depends(extract_value_from_http_connection)): 1abcd

16 return value 1hijk

17 

18 

19@app.websocket("/ws") 1abcd

20async def get_value_by_ws( 1abcd

21 websocket: WebSocket, value: int = Depends(extract_value_from_http_connection) 

22): 

23 await websocket.accept() 1elfg

24 await websocket.send_json(value) 1elfg

25 await websocket.close() 1elfg

26 

27 

28client = TestClient(app) 1abcd

29 

30 

31def test_value_extracting_by_http(): 1abcd

32 response = client.get("/http") 1hijk

33 assert response.status_code == 200 1hijk

34 assert response.json() == 42 1hijk

35 

36 

37def test_value_extracting_by_ws(): 1abcd

38 with client.websocket_connect("/ws") as websocket: 1elfg

39 assert websocket.receive_json() == 42 1elfg