| 1 |
from collections.abc import Generator |
| 2 |
from contextlib import contextmanager |
| 3 |
from typing import Annotated, Any |
| 4 |
|
| 5 |
import pytest |
| 6 |
from fastapi import Depends, FastAPI, WebSocket |
| 7 |
from fastapi.testclient import TestClient |
| 8 |
|
| 9 |
|
| 10 |
class Session: |
| 11 |
def __init__(self) -> None: |
| 12 |
self.data = ["foo", "bar", "baz"] |
| 13 |
self.open = True |
| 14 |
|
| 15 |
def __iter__(self) -> Generator[str, None, None]: |
| 16 |
for item in self.data: |
| 17 |
if self.open: |
| 18 |
yield item |
| 19 |
else: |
| 20 |
raise ValueError("Session closed") |
| 21 |
|
| 22 |
|
| 23 |
@contextmanager |
| 24 |
def acquire_session() -> Generator[Session, None, None]: |
| 25 |
session = Session() |
| 26 |
try: |
| 27 |
yield session |
| 28 |
finally: |
| 29 |
session.open = False |
| 30 |
|
| 31 |
|
| 32 |
def dep_session() -> Any: |
| 33 |
with acquire_session() as s: |
| 34 |
yield s |
| 35 |
|
| 36 |
|
| 37 |
def broken_dep_session() -> Any: |
| 38 |
with acquire_session() as s: |
| 39 |
s.open = False |
| 40 |
yield s |
| 41 |
|
| 42 |
|
| 43 |
SessionDep = Annotated[Session, Depends(dep_session)] |
| 44 |
BrokenSessionDep = Annotated[Session, Depends(broken_dep_session)] |
| 45 |
|
| 46 |
app = FastAPI() |
| 47 |
|
| 48 |
|
| 49 |
@app.websocket("/ws") |
| 50 |
async def websocket_endpoint(websocket: WebSocket, session: SessionDep): |
| 51 |
await websocket.accept() |
| 52 |
for item in session: |
| 53 |
await websocket.send_text(f"{item}") |
| 54 |
|
| 55 |
|
| 56 |
@app.websocket("/ws-broken") |
| 57 |
async def websocket_endpoint_broken(websocket: WebSocket, session: BrokenSessionDep): |
| 58 |
await websocket.accept() |
| 59 |
for item in session: |
| 60 |
await websocket.send_text(f"{item}") # pragma no cover |
| 61 |
|
| 62 |
|
| 63 |
client = TestClient(app) |
| 64 |
|
| 65 |
|
| 66 |
def test_websocket_dependency_after_yield(): |
| 67 |
with client.websocket_connect("/ws") as websocket: |
| 68 |
data = websocket.receive_text() |
| 69 |
assert data == "foo" |
| 70 |
data = websocket.receive_text() |
| 71 |
assert data == "bar" |
| 72 |
data = websocket.receive_text() |
| 73 |
assert data == "baz" |
| 74 |
|
| 75 |
|
| 76 |
def test_websocket_dependency_after_yield_broken(): |
| 77 |
with pytest.raises(ValueError, match="Session closed"): |
| 78 |
with client.websocket_connect("/ws-broken"): |
| 79 |
pass # pragma no cover |