async def test_get_exception_handler_post_hooks_bad_book(): # hook has too few arguments handler = middleware.get_exception_handler(post_hooks=[lambda x: x]) with pytest.raises(TypeError) as err: await handler( request=Request(scope={ 'type': 'http', 'app': FastAPI() }, ), exc=ValueError('test error'), ) assert 'takes 1 positional argument but 3 were given' in str(err.value)
async def test_get_exception_handler_debug(): handler = middleware.get_exception_handler(debug=True) resp = await handler( request=Request(scope={ 'type': 'http', 'app': FastAPI(debug=True) }), exc=ValueError('test error'), ) assert isinstance(resp, middleware.ProblemResponse) assert resp.debug is True assert resp.body == b'{\n "exc_type": "ValueError",\n "type": "about:blank",\n "title": "Unexpected Server Error",\n "status": 500,\n "detail": "test error"\n}' # noqa
async def test_get_exception_handler_pre_hooks_error(): hook1 = mock.AsyncMock() hook2 = mock.MagicMock() hook3 = mock.MagicMock(side_effect=ValueError('hook error')) handler = middleware.get_exception_handler(pre_hooks=[hook1, hook2, hook3]) with pytest.raises(ValueError) as err: await handler( request=Request(scope={ 'type': 'http', 'app': FastAPI() }, ), exc=ValueError('test error'), ) assert 'hook error' == str(err.value) hook1.assert_called_once() hook2.assert_called_once() hook3.assert_called_once()
async def test_get_exception_handler_pre_hooks_ok(): hook1 = mock.AsyncMock() hook2 = mock.MagicMock() hook3 = mock.MagicMock() handler = middleware.get_exception_handler(pre_hooks=[hook1, hook2, hook3]) resp = await handler( request=Request(scope={ 'type': 'http', 'app': FastAPI() }, ), exc=ValueError('test error'), ) assert isinstance(resp, middleware.ProblemResponse) assert resp.debug is False assert resp.body == b'{"exc_type":"ValueError","type":"about:blank","title":"Unexpected Server Error","status":500,"detail":"test error"}' # noqa hook1.assert_called_once() hook2.assert_called_once() hook3.assert_called_once()