Coverage for tests / test_route_scope.py: 100%

32 statements  

« prev     ^ index     » next       coverage.py v7.13.3, created at 2026-04-06 01:24 +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"] 1ijkl

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

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"] 1efgh

18 await websocket.accept() 1efgh

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

20 

21 

22client = TestClient(app) 1abcd

23 

24 

25def test_get(): 1abcd

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

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

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

29 

30 

31def test_invalid_method_doesnt_match(): 1abcd

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

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

34 

35 

36def test_invalid_path_doesnt_match(): 1abcd

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

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

39 

40 

41def test_websocket(): 1abcd

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

43 data = websocket.receive_json() 1efgh

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

45 

46 

47def test_websocket_invalid_path_doesnt_match(): 1abcd

48 with pytest.raises(WebSocketDisconnect): 1uvwx

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

50 pass # pragma: no cover