File: test_http_connection_injection.py

package info (click to toggle)
fastapi 0.118.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 34,212 kB
  • sloc: python: 69,848; javascript: 369; sh: 18; makefile: 17
file content (39 lines) | stat: -rw-r--r-- 972 bytes parent folder | download | duplicates (4)
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