| 1 |
from fastapi import Depends, FastAPI |
| 2 |
from fastapi.requests import HTTPConnection |
| 3 |
from fastapi.testclient import TestClient |
| 4 |
from starlette.websockets import WebSocket |
| 5 |
|
| 6 |
app = FastAPI() |
| 7 |
app.state.value = 42 |
| 8 |
|
| 9 |
|
| 10 |
async def extract_value_from_http_connection(conn: HTTPConnection): |
| 11 |
return conn.app.state.value |
| 12 |
|
| 13 |
|
| 14 |
@app.get("/http") |
| 15 |
async def get_value_by_http(value: int = Depends(extract_value_from_http_connection)): |
| 16 |
return value |
| 17 |
|
| 18 |
|
| 19 |
@app.websocket("/ws") |
| 20 |
async def get_value_by_ws( |
| 21 |
websocket: WebSocket, value: int = Depends(extract_value_from_http_connection) |
| 22 |
): |
| 23 |
await websocket.accept() |
| 24 |
await websocket.send_json(value) |
| 25 |
await websocket.close() |
| 26 |
|
| 27 |
|
| 28 |
client = TestClient(app) |
| 29 |
|
| 30 |
|
| 31 |
def test_value_extracting_by_http(): |
| 32 |
response = client.get("/http") |
| 33 |
assert response.status_code == 200 |
| 34 |
assert response.json() == 42 |
| 35 |
|
| 36 |
|
| 37 |
def test_value_extracting_by_ws(): |
| 38 |
with client.websocket_connect("/ws") as websocket: |
| 39 |
assert websocket.receive_json() == 42 |