forked from fastapi/fastapi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_http_connection_injection.py
More file actions
39 lines (26 loc) · 972 Bytes
/
test_http_connection_injection.py
File metadata and controls
39 lines (26 loc) · 972 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
from fastapi import Depends, FastAPI
from fastapi.requests import HTTPConnection
from fastapi.testclient import TestClient
from starlette.websockets import WebSocket
app = FastAPI()
app.state.value = 42
async def extract_value_from_http_connection(conn: HTTPConnection):
return conn.app.state.value
@app.get("/http")
async def get_value_by_http(value: int = Depends(extract_value_from_http_connection)):
return value
@app.websocket("/ws")
async def get_value_by_ws(
websocket: WebSocket, value: int = Depends(extract_value_from_http_connection)
):
await websocket.accept()
await websocket.send_json(value)
await websocket.close()
client = TestClient(app)
def test_value_extracting_by_http():
response = client.get("/http")
assert response.status_code == 200
assert response.json() == 42
def test_value_extracting_by_ws():
with client.websocket_connect("/ws") as websocket:
assert websocket.receive_json() == 42