Coverage for tests / test_dependency_after_yield_raise.py: 100%
39 statements
« prev ^ index » next coverage.py v7.13.3, created at 2026-04-06 01:24 +0000
« prev ^ index » next coverage.py v7.13.3, created at 2026-04-06 01:24 +0000
1from typing import Annotated, Any 1abcd
3import pytest 1abcd
4from fastapi import Depends, FastAPI, HTTPException 1abcd
5from fastapi.testclient import TestClient 1abcd
8class CustomError(Exception): 1abcd
9 pass 1abcd
12def catching_dep() -> Any: 1abcd
13 try: 1efgh
14 yield "s" 1efgh
15 except CustomError as err: 1efgh
16 raise HTTPException(status_code=418, detail="Session error") from err 1efgh
19def broken_dep() -> Any: 1abcd
20 yield "s" 1ipjkqlrmnso
21 raise ValueError("Broken after yield") 1ipjkqlrmnso
24app = FastAPI() 1abcd
27@app.get("/catching") 1abcd
28def catching(d: Annotated[str, Depends(catching_dep)]) -> Any: 1abcd
29 raise CustomError("Simulated error during streaming") 1efgh
32@app.get("/broken") 1abcd
33def broken(d: Annotated[str, Depends(broken_dep)]) -> Any: 1abcd
34 return {"message": "all good?"} 1ipjkqlrmnso
37client = TestClient(app) 1abcd
40def test_catching(): 1abcd
41 response = client.get("/catching") 1efgh
42 assert response.status_code == 418 1efgh
43 assert response.json() == {"detail": "Session error"} 1efgh
46def test_broken_raise(): 1abcd
47 with pytest.raises(ValueError, match="Broken after yield"): 1pqrs
48 client.get("/broken") 1pqrs
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: 1ikln
59 response = client.get("/broken") 1ikln
60 assert response.status_code == 200 1ikln
61 assert response.json() == {"message": "all good?"} 1ikln
64def test_broken_return_finishes(): 1abcd
65 client = TestClient(app, raise_server_exceptions=False) 1jtmo
66 response = client.get("/broken") 1jtmo
67 assert response.status_code == 200 1jtmo
68 assert response.json() == {"message": "all good?"} 1jtmo