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

1from collections.abc import Generator 1abcd

2from contextlib import contextmanager 1abcd

3from typing import Annotated, Any 1abcd

4 

5import pytest 1abcd

6from fastapi import Depends, FastAPI, WebSocket 1abcd

7from fastapi.testclient import TestClient 1abcd

8 

9 

10class Session: 1abcd

11 def __init__(self) -> None: 1abcd

12 self.data = ["foo", "bar", "baz"] 1ejfhgi

13 self.open = True 1ejfhgi

14 

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

21 

22 

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

30 

31 

32def dep_session() -> Any: 1abcd

33 with acquire_session() as s: 1efg

34 yield s 1efg

35 

36 

37def broken_dep_session() -> Any: 1abcd

38 with acquire_session() as s: 1jhi

39 s.open = False 1jhi

40 yield s 1jhi

41 

42 

43SessionDep = Annotated[Session, Depends(dep_session)] 1abcd

44BrokenSessionDep = Annotated[Session, Depends(broken_dep_session)] 1abcd

45 

46app = FastAPI() 1abcd

47 

48 

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

54 

55 

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 

61 

62 

63client = TestClient(app) 1abcd

64 

65 

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

74 

75 

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