Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions Lib/test/test_unittest/testmock/testasync.py
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,24 @@ async def addition(var):
result = await mock(5)
self.assertEqual(result, 6)

async def test_add_side_effect_async_callable(self):
class AsyncCallable:
async def __call__(self, var):
Comment on lines +472 to +473

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add a test where you use an async mock with a sync callable object? i.e. AsyncMock + SyncCallable.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added a regression test using a synchronous callable object as AsyncMock.side_effect in commit 7e15b35.

return var + 1

mock = AsyncMock(side_effect=AsyncCallable())
result = await mock(5)
self.assertEqual(result, 6)

async def test_add_side_effect_sync_callable(self):
class SyncCallable:
def __call__(self, var):
return var + 1

mock = AsyncMock(side_effect=SyncCallable())
result = await mock(5)
self.assertEqual(result, 6)

async def test_add_side_effect_normal_function(self):
def addition(var):
return var + 1
Expand Down
3 changes: 2 additions & 1 deletion Lib/unittest/mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -2331,7 +2331,8 @@ async def _execute_mock_call(self, /, *args, **kwargs):
raise StopAsyncIteration
if _is_exception(result):
raise result
elif iscoroutinefunction(effect):
elif (iscoroutinefunction(effect) or
iscoroutinefunction(getattr(effect, '__call__', None))):
result = await effect(*args, **kwargs)
else:
result = effect(*args, **kwargs)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Correctly handle async callable objects used as the ``side_effect`` of
:class:`unittest.mock.AsyncMock`.
Loading