Coverage for tests/test_route_scope.py: 100%

32 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2025-12-04 08:29 +0000

1import pytest 1abcdefg

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

3from fastapi.routing import APIRoute, APIWebSocketRoute 1abcdefg

4from fastapi.testclient import TestClient 1abcdefg

5 

6app = FastAPI() 1abcdefg

7 

8 

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

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

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

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

13 

14 

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

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

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

18 await websocket.accept() 1hijklmn

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

20 

21 

22client = TestClient(app) 1abcdefg

23 

24 

25def test_get(): 1abcdefg

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

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

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

29 

30 

31def test_invalid_method_doesnt_match(): 1abcdefg

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

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

34 

35 

36def test_invalid_path_doesnt_match(): 1abcdefg

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

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

39 

40 

41def test_websocket(): 1abcdefg

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

43 data = websocket.receive_json() 1hijklmn

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

45 

46 

47def test_websocket_invalid_path_doesnt_match(): 1abcdefg

48 with pytest.raises(WebSocketDisconnect): 1KvLMNOP

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

50 pass # pragma: no cover 1v