Skip to content

Commit 2f1487e

Browse files
committed
gh-156460: Await async callable side effects in AsyncMock
1 parent 2a37d67 commit 2f1487e

3 files changed

Lines changed: 12 additions & 1 deletion

File tree

Lib/test/test_unittest/testmock/testasync.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -468,6 +468,15 @@ async def addition(var):
468468
result = await mock(5)
469469
self.assertEqual(result, 6)
470470

471+
async def test_add_side_effect_async_callable(self):
472+
class AsyncCallable:
473+
async def __call__(self, var):
474+
return var + 1
475+
476+
mock = AsyncMock(side_effect=AsyncCallable())
477+
result = await mock(5)
478+
self.assertEqual(result, 6)
479+
471480
async def test_add_side_effect_normal_function(self):
472481
def addition(var):
473482
return var + 1

Lib/unittest/mock.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2331,7 +2331,8 @@ async def _execute_mock_call(self, /, *args, **kwargs):
23312331
raise StopAsyncIteration
23322332
if _is_exception(result):
23332333
raise result
2334-
elif iscoroutinefunction(effect):
2334+
elif (iscoroutinefunction(effect) or
2335+
iscoroutinefunction(getattr(effect, '__call__', None))):
23352336
result = await effect(*args, **kwargs)
23362337
else:
23372338
result = effect(*args, **kwargs)
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Await async callable objects used as :attr:`unittest.mock.AsyncMock.side_effect`.

0 commit comments

Comments
 (0)