Coverage for tests / test_dependency_after_yield_websockets.py: 100%
52 statements
« prev ^ index » next coverage.py v7.13.3, created at 2026-02-12 18:15 +0000
« prev ^ index » next coverage.py v7.13.3, created at 2026-02-12 18:15 +0000
1from collections.abc import Generator 1abcd
2from contextlib import contextmanager 1abcd
3from typing import Annotated, Any 1abcd
5import pytest 1abcd
6from fastapi import Depends, FastAPI, WebSocket 1abcd
7from fastapi.testclient import TestClient 1abcd
10class Session: 1abcd
11 def __init__(self) -> None: 1abcd
12 self.data = ["foo", "bar", "baz"] 1ejfhgi
13 self.open = True 1ejfhgi
15 def __iter__(self) -> Generator[str, None, None]: 1abcd
16 for item in self.data: 1ejfhgi
17 if self.open: 1ejfhgi
18 yield item 1efg
19 else:
20 raise ValueError("Session closed") 1jhi
23@contextmanager 1abcd
24def acquire_session() -> Generator[Session, None, None]: 1abcd
25 session = Session() 1ejfhgi
26 try: 1ejfhgi
27 yield session 1ejfhgi
28 finally:
29 session.open = False 1ejfhgi
32def dep_session() -> Any: 1abcd
33 with acquire_session() as s: 1efg
34 yield s 1efg
37def broken_dep_session() -> Any: 1abcd
38 with acquire_session() as s: 1jhi
39 s.open = False 1jhi
40 yield s 1jhi
43SessionDep = Annotated[Session, Depends(dep_session)] 1abcd
44BrokenSessionDep = Annotated[Session, Depends(broken_dep_session)] 1abcd
46app = FastAPI() 1abcd
49@app.websocket("/ws") 1abcd
50async def websocket_endpoint(websocket: WebSocket, session: SessionDep): 1abcd
51 await websocket.accept() 1efg
52 for item in session: 1efg
53 await websocket.send_text(f"{item}") 1efg
56@app.websocket("/ws-broken") 1abcd
57async def websocket_endpoint_broken(websocket: WebSocket, session: BrokenSessionDep): 1abcd
58 await websocket.accept() 1jhi
59 for item in session: 1jhi
60 await websocket.send_text(f"{item}") # pragma no cover
63client = TestClient(app) 1abcd
66def test_websocket_dependency_after_yield(): 1abcd
67 with client.websocket_connect("/ws") as websocket: 1efg
68 data = websocket.receive_text() 1efg
69 assert data == "foo" 1efg
70 data = websocket.receive_text() 1efg
71 assert data == "bar" 1efg
72 data = websocket.receive_text() 1efg
73 assert data == "baz" 1efg
76def test_websocket_dependency_after_yield_broken(): 1abcd
77 with pytest.raises(ValueError, match="Session closed"): 1jhi
78 with client.websocket_connect("/ws-broken"): 1jhi
79 pass # pragma no cover 1hi