Coverage for tests / test_dependency_after_yield_raise.py: 100%

39 statements  

« prev     ^ index     » next       coverage.py v7.13.3, created at 2026-02-12 18:15 +0000

1from typing import Annotated, Any 1abcd

2 

3import pytest 1abcd

4from fastapi import Depends, FastAPI, HTTPException 1abcd

5from fastapi.testclient import TestClient 1abcd

6 

7 

8class CustomError(Exception): 1abcd

9 pass 1abcd

10 

11 

12def catching_dep() -> Any: 1abcd

13 try: 1efg

14 yield "s" 1efg

15 except CustomError as err: 1efg

16 raise HTTPException(status_code=418, detail="Session error") from err 1efg

17 

18 

19def broken_dep() -> Any: 1abcd

20 yield "s" 1hnijoklpm

21 raise ValueError("Broken after yield") 1hnijoklpm

22 

23 

24app = FastAPI() 1abcd

25 

26 

27@app.get("/catching") 1abcd

28def catching(d: Annotated[str, Depends(catching_dep)]) -> Any: 1abcd

29 raise CustomError("Simulated error during streaming") 1efg

30 

31 

32@app.get("/broken") 1abcd

33def broken(d: Annotated[str, Depends(broken_dep)]) -> Any: 1abcd

34 return {"message": "all good?"} 1hnijoklpm

35 

36 

37client = TestClient(app) 1abcd

38 

39 

40def test_catching(): 1abcd

41 response = client.get("/catching") 1efg

42 assert response.status_code == 418 1efg

43 assert response.json() == {"detail": "Session error"} 1efg

44 

45 

46def test_broken_raise(): 1abcd

47 with pytest.raises(ValueError, match="Broken after yield"): 1nop

48 client.get("/broken") 1nop

49 

50 

51def test_broken_no_raise(): 1abcd

52 """ 

53 When a dependency with yield raises after the yield (not in an except), the 

54 response is already "successfully" sent back to the client, but there's still 

55 an error in the server afterwards, an exception is raised and captured or shown 

56 in the server logs. 

57 """ 

58 with TestClient(app, raise_server_exceptions=False) as client: 1hjl

59 response = client.get("/broken") 1hjl

60 assert response.status_code == 200 1hjl

61 assert response.json() == {"message": "all good?"} 1hjl

62 

63 

64def test_broken_return_finishes(): 1abcd

65 client = TestClient(app, raise_server_exceptions=False) 1ikm

66 response = client.get("/broken") 1ikm

67 assert response.status_code == 200 1ikm

68 assert response.json() == {"message": "all good?"} 1ikm