|
3 | 3 | from fastapi import FastAPI |
4 | 4 | from fastapi.testclient import TestClient |
5 | 5 |
|
| 6 | +from common.errors import ApplicationError |
| 7 | + |
6 | 8 |
|
7 | 9 | @patch("logging.exception") |
8 | | -async def test_exception_is_logged_handler_returns_500( |
| 10 | +async def test_unhandled_exception_is_logged_handler_returns_500( |
9 | 11 | mocked_logging_exception: MagicMock, |
10 | 12 | testapp: FastAPI, |
11 | 13 | ): |
12 | 14 | my_exc = Exception("Some random exception") |
13 | 15 |
|
14 | | - @testapp.get("/ppp") |
| 16 | + @testapp.get("/unhandled_exception") |
15 | 17 | async def fake_endpoint(): |
16 | 18 | raise my_exc |
17 | 19 |
|
18 | 20 | ac = TestClient(app=testapp, base_url="http://test") |
19 | | - response = ac.get("/ppp") |
| 21 | + response = ac.get("/unhandled_exception") |
20 | 22 |
|
21 | 23 | assert response.status_code == 500 |
22 | 24 | assert response.json() == {"error": "Internal server error"} |
23 | 25 | mocked_logging_exception.assert_called_once_with(my_exc) |
| 26 | + |
| 27 | + |
| 28 | +@patch("logging.exception") |
| 29 | +async def test_application_error_is_logged_handler_returns_500( |
| 30 | + mocked_logging_exception: MagicMock, |
| 31 | + testapp: FastAPI, |
| 32 | +): |
| 33 | + my_exc = ApplicationError( |
| 34 | + public_message="Some random exception", |
| 35 | + internal_message="Some random internal exception", |
| 36 | + code="ERR_1234567890", |
| 37 | + metadata={ |
| 38 | + "user_id": "1234567890", |
| 39 | + }, |
| 40 | + ) |
| 41 | + |
| 42 | + @testapp.get("/application_error") |
| 43 | + async def fake_endpoint(): |
| 44 | + raise my_exc |
| 45 | + |
| 46 | + ac = TestClient(app=testapp, base_url="http://test") |
| 47 | + response = ac.get("/application_error") |
| 48 | + |
| 49 | + assert response.status_code == 500 |
| 50 | + assert response.json() == {"error": {"code": "ERR_1234567890", "message": "Some random exception"}} |
| 51 | + mocked_logging_exception.assert_called_once_with( |
| 52 | + my_exc.internal_message, extra={"code": my_exc.code, "metadata": my_exc.metadata} |
| 53 | + ) |
0 commit comments