Coverage for tests / test_route_scope.py: 100%

32 statements  

« prev     ^ index     » next       coverage.py v7.13.3, created at 2026-02-12 18:15 +0000

1import pytest 1abcd

2from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect 1abcd

3from fastapi.routing import APIRoute, APIWebSocketRoute 1abcd

4from fastapi.testclient import TestClient 1abcd

5 

6app = FastAPI() 1abcd

7 

8 

9@app.get("/users/{user_id}") 1abcd

10async def get_user(user_id: str, request: Request): 1abcd

11 route: APIRoute = request.scope["route"] 1hij

12 return {"user_id": user_id, "path": route.path} 1hij

13 

14 

15@app.websocket("/items/{item_id}") 1abcd

16async def websocket_item(item_id: str, websocket: WebSocket): 1abcd

17 route: APIWebSocketRoute = websocket.scope["route"] 1efg

18 await websocket.accept() 1efg

19 await websocket.send_json({"item_id": item_id, "path": route.path}) 1efg

20 

21 

22client = TestClient(app) 1abcd

23 

24 

25def test_get(): 1abcd

26 response = client.get("/users/rick") 1hij

27 assert response.status_code == 200, response.text 1hij

28 assert response.json() == {"user_id": "rick", "path": "/users/{user_id}"} 1hij

29 

30 

31def test_invalid_method_doesnt_match(): 1abcd

32 response = client.post("/users/rick") 1klm

33 assert response.status_code == 405, response.text 1klm

34 

35 

36def test_invalid_path_doesnt_match(): 1abcd

37 response = client.post("/usersx/rick") 1nop

38 assert response.status_code == 404, response.text 1nop

39 

40 

41def test_websocket(): 1abcd

42 with client.websocket_connect("/items/portal-gun") as websocket: 1efg

43 data = websocket.receive_json() 1efg

44 assert data == {"item_id": "portal-gun", "path": "/items/{item_id}"} 1efg

45 

46 

47def test_websocket_invalid_path_doesnt_match(): 1abcd

48 with pytest.raises(WebSocketDisconnect): 1qrs

49 with client.websocket_connect("/itemsx/portal-gun"): 1qrs

50 pass # pragma: no cover