|
| 1 | +import pytest |
| 2 | +from fastapi import FastAPI, Request |
| 3 | +from fastapi.responses import JSONResponse |
| 4 | +from fastapi.testclient import TestClient |
| 5 | +from app.middlewares.unhandled_exceptions_middleware import UnhandledExceptionsMiddleware |
| 6 | + |
| 7 | +# Exception handlers to trigger different exceptions |
| 8 | + |
| 9 | +async def fail(request: Request): |
| 10 | + raise RuntimeError("boom") |
| 11 | + |
| 12 | +async def fail_value_error(request: Request): |
| 13 | + raise ValueError("Invalid value test") |
| 14 | + |
| 15 | +async def fail_key_error(request: Request): |
| 16 | + raise KeyError("Missing key test") |
| 17 | + |
| 18 | +async def ok(request: Request): |
| 19 | + return JSONResponse({"ok": True}) |
| 20 | + |
| 21 | +@pytest.fixture |
| 22 | +def client(): |
| 23 | + app = FastAPI() |
| 24 | + app.add_middleware(UnhandledExceptionsMiddleware) |
| 25 | + app.add_api_route("/fail", fail, methods=["GET"]) |
| 26 | + app.add_api_route("/fail_value_error", fail_value_error, methods=["GET"]) |
| 27 | + app.add_api_route("/fail_key_error", fail_key_error, methods=["GET"]) |
| 28 | + app.add_api_route("/ok", ok, methods=["GET"]) |
| 29 | + return TestClient(app) |
| 30 | + |
| 31 | +ERROR_RESPONSE = { |
| 32 | + "success": False, |
| 33 | + "detail": "internal server error, please reach out to support team at nivedit@exosphere.host" |
| 34 | +} |
| 35 | + |
| 36 | +def test_runtime_error_returns_expected_json(client): |
| 37 | + resp = client.get("/fail") |
| 38 | + assert resp.status_code == 500 |
| 39 | + assert resp.json() == ERROR_RESPONSE |
| 40 | + |
| 41 | +def test_value_error_returns_expected_json(client): |
| 42 | + resp = client.get("/fail_value_error") |
| 43 | + assert resp.status_code == 500 |
| 44 | + assert resp.json() == ERROR_RESPONSE |
| 45 | + |
| 46 | +def test_key_error_returns_expected_json(client): |
| 47 | + resp = client.get("/fail_key_error") |
| 48 | + assert resp.status_code == 500 |
| 49 | + assert resp.json() == ERROR_RESPONSE |
| 50 | + |
| 51 | +def test_normal_request_passes_through(client): |
| 52 | + resp = client.get("/ok") |
| 53 | + assert resp.status_code == 200 |
| 54 | + assert resp.json() == {"ok": True} |
0 commit comments