Skip to content

Commit

Permalink
Merge pull request #196 from CrimsonJacket/feat/allow_for_callbacks_b…
Browse files Browse the repository at this point in the history
…efore_exception

Allow for callbacks to be called before raising of exceptions
  • Loading branch information
pnuckowski committed Nov 2, 2021
2 parents fa5c85b + 4c3369e commit 51f44f1
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
7 changes: 4 additions & 3 deletions aioresponses/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,16 +179,17 @@ 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)
else:
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,
Expand Down
9 changes: 9 additions & 0 deletions tests/test_aioresponses.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down

0 comments on commit 51f44f1

Please sign in to comment.