| 1 |
from typing import Annotated, Any |
| 2 |
|
| 3 |
import pytest |
| 4 |
from fastapi import Depends, FastAPI, HTTPException |
| 5 |
from fastapi.testclient import TestClient |
| 6 |
|
| 7 |
|
| 8 |
class CustomError(Exception): |
| 9 |
pass |
| 10 |
|
| 11 |
|
| 12 |
def catching_dep() -> Any: |
| 13 |
try: |
| 14 |
yield "s" |
| 15 |
except CustomError as err: |
| 16 |
raise HTTPException(status_code=418, detail="Session error") from err |
| 17 |
|
| 18 |
|
| 19 |
def broken_dep() -> Any: |
| 20 |
yield "s" |
| 21 |
raise ValueError("Broken after yield") |
| 22 |
|
| 23 |
|
| 24 |
app = FastAPI() |
| 25 |
|
| 26 |
|
| 27 |
@app.get("/catching") |
| 28 |
def catching(d: Annotated[str, Depends(catching_dep)]) -> Any: |
| 29 |
raise CustomError("Simulated error during streaming") |
| 30 |
|
| 31 |
|
| 32 |
@app.get("/broken") |
| 33 |
def broken(d: Annotated[str, Depends(broken_dep)]) -> Any: |
| 34 |
return {"message": "all good?"} |
| 35 |
|
| 36 |
|
| 37 |
client = TestClient(app) |
| 38 |
|
| 39 |
|
| 40 |
def test_catching(): |
| 41 |
response = client.get("/catching") |
| 42 |
assert response.status_code == 418 |
| 43 |
assert response.json() == {"detail": "Session error"} |
| 44 |
|
| 45 |
|
| 46 |
def test_broken_raise(): |
| 47 |
with pytest.raises(ValueError, match="Broken after yield"): |
| 48 |
client.get("/broken") |
| 49 |
|
| 50 |
|
| 51 |
def test_broken_no_raise(): |
| 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: |
| 59 |
response = client.get("/broken") |
| 60 |
assert response.status_code == 200 |
| 61 |
assert response.json() == {"message": "all good?"} |
| 62 |
|
| 63 |
|
| 64 |
def test_broken_return_finishes(): |
| 65 |
client = TestClient(app, raise_server_exceptions=False) |
| 66 |
response = client.get("/broken") |
| 67 |
assert response.status_code == 200 |
| 68 |
assert response.json() == {"message": "all good?"} |