Coverage for tests/test_ws_dependencies.py: 100%
47 statements
« prev ^ index » next coverage.py v7.6.1, created at 2024-08-08 03:53 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2024-08-08 03:53 +0000
1import json 1abcde
2from typing import List 1abcde
4from fastapi import APIRouter, Depends, FastAPI, WebSocket 1abcde
5from fastapi.testclient import TestClient 1abcde
6from typing_extensions import Annotated 1abcde
9def dependency_list() -> List[str]: 1abcde
10 return [] 1abcde
13DepList = Annotated[List[str], Depends(dependency_list)] 1abcde
16def create_dependency(name: str): 1abcde
17 def fun(deps: DepList): 1abcde
18 deps.append(name) 1abcde
20 return Depends(fun) 1abcde
23router = APIRouter(dependencies=[create_dependency("router")]) 1abcde
24prefix_router = APIRouter(dependencies=[create_dependency("prefix_router")]) 1abcde
25app = FastAPI(dependencies=[create_dependency("app")]) 1abcde
28@app.websocket("/", dependencies=[create_dependency("index")]) 1abcde
29async def index(websocket: WebSocket, deps: DepList): 1abcde
30 await websocket.accept() 1abcde
31 await websocket.send_text(json.dumps(deps)) 1abcde
32 await websocket.close() 1abcde
35@router.websocket("/router", dependencies=[create_dependency("routerindex")]) 1abcde
36async def routerindex(websocket: WebSocket, deps: DepList): 1abcde
37 await websocket.accept() 1abcde
38 await websocket.send_text(json.dumps(deps)) 1abcde
39 await websocket.close() 1abcde
42@prefix_router.websocket("/", dependencies=[create_dependency("routerprefixindex")]) 1abcde
43async def routerprefixindex(websocket: WebSocket, deps: DepList): 1abcde
44 await websocket.accept() 1abcde
45 await websocket.send_text(json.dumps(deps)) 1abcde
46 await websocket.close() 1abcde
49app.include_router(router, dependencies=[create_dependency("router2")]) 1abcde
50app.include_router( 1abcde
51 prefix_router, prefix="/prefix", dependencies=[create_dependency("prefix_router2")]
52)
55def test_index(): 1abcde
56 client = TestClient(app) 1abcde
57 with client.websocket_connect("/") as websocket: 1abcde
58 data = json.loads(websocket.receive_text()) 1abcde
59 assert data == ["app", "index"] 1abcde
62def test_routerindex(): 1abcde
63 client = TestClient(app) 1abcde
64 with client.websocket_connect("/router") as websocket: 1abcde
65 data = json.loads(websocket.receive_text()) 1abcde
66 assert data == ["app", "router2", "router", "routerindex"] 1abcde
69def test_routerprefixindex(): 1abcde
70 client = TestClient(app) 1abcde
71 with client.websocket_connect("/prefix/") as websocket: 1abcde
72 data = json.loads(websocket.receive_text()) 1abcde
73 assert data == ["app", "prefix_router2", "prefix_router", "routerprefixindex"] 1abcde