Coverage for tests/test_route_scope.py: 100%

33 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-08-08 03:53 +0000

1import pytest 1bacde

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

3from fastapi.routing import APIRoute, APIWebSocketRoute 1bacde

4from fastapi.testclient import TestClient 1bacde

5 

6app = FastAPI() 1bacde

7 

8 

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

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

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

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

13 

14 

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

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

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

18 await websocket.accept() 1bacde

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

20 

21 

22client = TestClient(app) 1bacde

23 

24 

25def test_get(): 1bacde

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

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

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

29 

30 

31def test_invalid_method_doesnt_match(): 1bacde

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

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

34 

35 

36def test_invalid_path_doesnt_match(): 1bacde

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

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

39 

40 

41def test_websocket(): 1bacde

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

43 data = websocket.receive_json() 1bacde

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

45 

46 

47def test_websocket_invalid_path_doesnt_match(): 1bacde

48 with pytest.raises(WebSocketDisconnect): 1bacde

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

50 pass 1a