Coverage for tests/test_http_connection_injection.py: 100%
24 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 fastapi import Depends, FastAPI 1abcde
2from fastapi.requests import HTTPConnection 1abcde
3from fastapi.testclient import TestClient 1abcde
4from starlette.websockets import WebSocket 1abcde
6app = FastAPI() 1abcde
7app.state.value = 42 1abcde
10async def extract_value_from_http_connection(conn: HTTPConnection): 1abcde
11 return conn.app.state.value 1abcde
14@app.get("/http") 1abcde
15async def get_value_by_http(value: int = Depends(extract_value_from_http_connection)): 1abcde
16 return value 1abcde
19@app.websocket("/ws") 1abcde
20async def get_value_by_ws( 1abcde
21 websocket: WebSocket, value: int = Depends(extract_value_from_http_connection)
22):
23 await websocket.accept() 1abcde
24 await websocket.send_json(value) 1abcde
25 await websocket.close() 1abcde
28client = TestClient(app) 1abcde
31def test_value_extracting_by_http(): 1abcde
32 response = client.get("/http") 1abcde
33 assert response.status_code == 200 1abcde
34 assert response.json() == 42 1abcde
37def test_value_extracting_by_ws(): 1abcde
38 with client.websocket_connect("/ws") as websocket: 1abcde
39 assert websocket.receive_json() == 42 1abcde