Coverage for tests / test_dependency_after_yield_websockets.py: 100%

52 statements  

« prev     ^ index     » next       coverage.py v7.13.3, created at 2026-04-06 01:24 +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"] 1ielfjgkh

13 self.open = True 1ielfjgkh

14 

15 def __iter__(self) -> Generator[str, None, None]: 1abcd

16 for item in self.data: 1ielfjgkh

17 if self.open: 1ielfjgkh

18 yield item 1efgh

19 else: 

20 raise ValueError("Session closed") 1iljk

21 

22 

23@contextmanager 1abcd

24def acquire_session() -> Generator[Session, None, None]: 1abcd

25 session = Session() 1ielfjgkh

26 try: 1ielfjgkh

27 yield session 1ielfjgkh

28 finally: 

29 session.open = False 1ielfjgkh

30 

31 

32def dep_session() -> Any: 1abcd

33 with acquire_session() as s: 1efgh

34 yield s 1efgh

35 

36 

37def broken_dep_session() -> Any: 1abcd

38 with acquire_session() as s: 1iljk

39 s.open = False 1iljk

40 yield s 1iljk

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() 1efgh

52 for item in session: 1efgh

53 await websocket.send_text(f"{item}") 1efgh

54 

55 

56@app.websocket("/ws-broken") 1abcd

57async def websocket_endpoint_broken(websocket: WebSocket, session: BrokenSessionDep): 1abcd

58 await websocket.accept() 1iljk

59 for item in session: 1iljk

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: 1efgh

68 data = websocket.receive_text() 1efgh

69 assert data == "foo" 1efgh

70 data = websocket.receive_text() 1efgh

71 assert data == "bar" 1efgh

72 data = websocket.receive_text() 1efgh

73 assert data == "baz" 1efgh

74 

75 

76def test_websocket_dependency_after_yield_broken(): 1abcd

77 with pytest.raises(ValueError, match="Session closed"): 1iljk

78 with client.websocket_connect("/ws-broken"): 1iljk

79 pass # pragma no cover 1ijk