|
14 | 14 | from aiohttp import web |
15 | 15 | from aiohttp.test_utils import TestClient |
16 | 16 | from common_library.json_serialization import json_dumps |
| 17 | +from pytest_mock import MockerFixture |
17 | 18 | from servicelib.aiohttp import status |
18 | 19 | from servicelib.aiohttp.rest_middlewares import ( |
19 | 20 | envelope_middleware_factory, |
@@ -339,3 +340,41 @@ async def test_http_ok_with_text_is_enveloped(client: TestClient): |
339 | 340 | assert not error |
340 | 341 | assert data |
341 | 342 | assert data.get("ok") is True |
| 343 | + |
| 344 | + |
| 345 | +async def test_exception_in_handler_returns_500( |
| 346 | + client: TestClient, mocker: MockerFixture |
| 347 | +): |
| 348 | + """Test that exceptions in the handler functions are caught and return 500.""" |
| 349 | + |
| 350 | + # Mock _handle_http_successful to raise an exception |
| 351 | + def mocked_handler(*args, **kwargs): |
| 352 | + msg = "Simulated error in handler" |
| 353 | + raise ValueError(msg) |
| 354 | + |
| 355 | + mocker.patch( |
| 356 | + "servicelib.aiohttp.rest_middlewares._handle_http_successful", |
| 357 | + side_effect=mocked_handler, |
| 358 | + ) |
| 359 | + |
| 360 | + # Trigger a successful HTTP response that will be processed by our mocked handler |
| 361 | + response = await client.get( |
| 362 | + "/v1/raise_exception", params={"exc": web.HTTPOk.__name__} |
| 363 | + ) |
| 364 | + |
| 365 | + # Should return 500 since our handler raised an exception |
| 366 | + assert response.status == status.HTTP_500_INTERNAL_SERVER_ERROR |
| 367 | + |
| 368 | + # Check that the response is properly enveloped |
| 369 | + payload = await response.json() |
| 370 | + assert is_enveloped(payload) |
| 371 | + |
| 372 | + # Verify error details |
| 373 | + data, error = unwrap_envelope(payload) |
| 374 | + assert not data |
| 375 | + assert error |
| 376 | + assert error.get("status") == status.HTTP_500_INTERNAL_SERVER_ERROR |
| 377 | + |
| 378 | + # Make sure there are no detailed error logs in production mode |
| 379 | + assert not error.get("errors") |
| 380 | + assert not error.get("logs") |
0 commit comments