|
4 | 4 | from fastapi.testclient import TestClient |
5 | 5 | from app.middlewares.unhandled_exceptions_middleware import UnhandledExceptionsMiddleware |
6 | 6 |
|
7 | | -# Endpoint that will always raise an error to test error handling |
| 7 | +# Handlers for various exception types |
| 8 | + |
| 9 | +# 1. RuntimeError |
8 | 10 | async def fail(request: Request): |
9 | 11 | raise RuntimeError("boom") |
10 | 12 |
|
11 | | -# Endpoint for a healthy request |
| 13 | +# 2. ValueError |
| 14 | +async def fail_value_error(request: Request): |
| 15 | + raise ValueError("Invalid value test") |
| 16 | + |
| 17 | +# 3. KeyError |
| 18 | +async def fail_key_error(request: Request): |
| 19 | + raise KeyError("Missing key test") |
| 20 | + |
| 21 | +# 4. Healthy endpoint |
12 | 22 | async def ok(request: Request): |
13 | 23 | return JSONResponse({"ok": True}) |
14 | 24 |
|
15 | 25 | @pytest.fixture |
16 | 26 | def client(): |
17 | 27 | app = FastAPI() |
18 | | - app.add_middleware(UnhandledExceptionsMiddleware) # Only exception middleware |
| 28 | + app.add_middleware(UnhandledExceptionsMiddleware) |
19 | 29 | app.add_api_route("/fail", fail, methods=["GET"]) |
| 30 | + app.add_api_route("/fail_value_error", fail_value_error, methods=["GET"]) |
| 31 | + app.add_api_route("/fail_key_error", fail_key_error, methods=["GET"]) |
20 | 32 | app.add_api_route("/ok", ok, methods=["GET"]) |
21 | 33 | return TestClient(app) |
22 | 34 |
|
23 | | -def test_exception_returns_expected_json(client): |
| 35 | +def test_runtime_error_returns_expected_json(client): |
24 | 36 | resp = client.get("/fail") |
25 | 37 | assert resp.status_code == 500 |
26 | 38 | response_json = resp.json() |
| 39 | + assert response_json.get("success") is False |
| 40 | + assert "detail" in response_json |
| 41 | + assert "server error" in response_json["detail"].lower() |
| 42 | + |
| 43 | +def test_value_error_returns_expected_json(client): |
| 44 | + resp = client.get("/fail_value_error") |
| 45 | + assert resp.status_code == 500 |
| 46 | + response_json = resp.json() |
| 47 | + assert response_json.get("success") is False |
| 48 | + assert "detail" in response_json |
| 49 | + assert "server error" in response_json["detail"].lower() |
| 50 | + |
| 51 | +def test_key_error_returns_expected_json(client): |
| 52 | + resp = client.get("/fail_key_error") |
| 53 | + assert resp.status_code == 500 |
| 54 | + response_json = resp.json() |
| 55 | + assert response_json.get("success") is False |
27 | 56 | assert "detail" in response_json |
28 | 57 | assert "server error" in response_json["detail"].lower() |
29 | 58 |
|
|
0 commit comments