From 47fa482878513528741806f9a817266bf1b0ab7d Mon Sep 17 00:00:00 2001 From: Daniel Tan Date: Wed, 22 Sep 2021 15:32:21 +0800 Subject: [PATCH 1/2] (feat) allow for callbacks to be called before raising of exception --- aioresponses/core.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/aioresponses/core.py b/aioresponses/core.py index 6e4d592..518e2f2 100644 --- a/aioresponses/core.py +++ b/aioresponses/core.py @@ -178,9 +178,6 @@ def _build_response(self, url: 'Union[URL, str]', async def build_response( self, url: URL, **kwargs ) -> 'Union[ClientResponse, Exception]': - if self.exception is not None: - return self.exception - if callable(self.callback): if asyncio.iscoroutinefunction(self.callback): result = await self.callback(url, **kwargs) @@ -188,6 +185,10 @@ async def build_response( result = self.callback(url, **kwargs) else: result = None + + if self.exception is not None: + return self.exception + result = self if result is None else result resp = self._build_response( url=url, From 4c3369e0ab858016cb2624a8fbe08d5d1e397d89 Mon Sep 17 00:00:00 2001 From: Daniel Tan Date: Wed, 22 Sep 2021 15:56:43 +0800 Subject: [PATCH 2/2] (feat) add unit tests --- tests/test_aioresponses.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/tests/test_aioresponses.py b/tests/test_aioresponses.py index 01a343a..887babc 100644 --- a/tests/test_aioresponses.py +++ b/tests/test_aioresponses.py @@ -251,6 +251,15 @@ async def test_raising_exception(self): with self.assertRaises(HttpProcessingError): await self.session.get(url) + callback_called = asyncio.Event() + url = 'http://example.com/HttpProcessingError' + aiomock.get(url, exception=HttpProcessingError(message='foo'), + callback=lambda *_, **__: callback_called.set()) + with self.assertRaises(HttpProcessingError): + await self.session.get(url) + + await callback_called.wait() + async def test_multiple_requests(self): """Ensure that requests are saved the way they would have been sent.""" with aioresponses() as m: