Debian Codegraph @

tests/test_route_scope.py

raw
1 import pytest
2 from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect
3 from fastapi.routing import APIRoute, APIWebSocketRoute
4 from fastapi.testclient import TestClient
5
6 app = FastAPI()
7
8
9 @app.get("/users/{user_id}")
10 async def get_user(user_id: str, request: Request):
11 route: APIRoute = request.scope["route"]
12 return {"user_id": user_id, "path": route.path}
13
14
15 @app.websocket("/items/{item_id}")
16 async def websocket_item(item_id: str, websocket: WebSocket):
17 route: APIWebSocketRoute = websocket.scope["route"]
18 await websocket.accept()
19 await websocket.send_json({"item_id": item_id, "path": route.path})
20
21
22 client = TestClient(app)
23
24
25 def test_get():
26 response = client.get("/users/rick")
27 assert response.status_code == 200, response.text
28 assert response.json() == {"user_id": "rick", "path": "/users/{user_id}"}
29
30
31 def test_invalid_method_doesnt_match():
32 response = client.post("/users/rick")
33 assert response.status_code == 405, response.text
34
35
36 def test_invalid_path_doesnt_match():
37 response = client.post("/usersx/rick")
38 assert response.status_code == 404, response.text
39
40
41 def test_websocket():
42 with client.websocket_connect("/items/portal-gun") as websocket:
43 data = websocket.receive_json()
44 assert data == {"item_id": "portal-gun", "path": "/items/{item_id}"}
45
46
47 def test_websocket_invalid_path_doesnt_match():
48 with pytest.raises(WebSocketDisconnect):
49 with client.websocket_connect("/itemsx/portal-gun"):
50 pass # pragma: no cover