From 2f1487ee7d5d0bdca6af943abf0db67e8489e008 Mon Sep 17 00:00:00 2001 From: cananoo <2059997196@qq.com> Date: Thu, 27 Aug 2026 20:56:50 +0800 Subject: [PATCH 1/2] gh-156460: Await async callable side effects in AsyncMock --- Lib/test/test_unittest/testmock/testasync.py | 9 +++++++++ Lib/unittest/mock.py | 3 ++- .../2026-08-27-20-47-01.gh-issue-156460.A7kP3m.rst | 1 + 3 files changed, 12 insertions(+), 1 deletion(-) create mode 100644 Misc/NEWS.d/next/Library/2026-08-27-20-47-01.gh-issue-156460.A7kP3m.rst diff --git a/Lib/test/test_unittest/testmock/testasync.py b/Lib/test/test_unittest/testmock/testasync.py index f96aef7325ff4c..02d8e273436a4b 100644 --- a/Lib/test/test_unittest/testmock/testasync.py +++ b/Lib/test/test_unittest/testmock/testasync.py @@ -468,6 +468,15 @@ 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): + return var + 1 + + mock = AsyncMock(side_effect=AsyncCallable()) + result = await mock(5) + self.assertEqual(result, 6) + async def test_add_side_effect_normal_function(self): def addition(var): return var + 1 diff --git a/Lib/unittest/mock.py b/Lib/unittest/mock.py index d0ca94668e05bc..3aab147f187cc6 100644 --- a/Lib/unittest/mock.py +++ b/Lib/unittest/mock.py @@ -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) diff --git a/Misc/NEWS.d/next/Library/2026-08-27-20-47-01.gh-issue-156460.A7kP3m.rst b/Misc/NEWS.d/next/Library/2026-08-27-20-47-01.gh-issue-156460.A7kP3m.rst new file mode 100644 index 00000000000000..e8845f566ca21c --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-08-27-20-47-01.gh-issue-156460.A7kP3m.rst @@ -0,0 +1 @@ +Await async callable objects used as :attr:`unittest.mock.AsyncMock.side_effect`. From c7fcd7d43413714cf6727f59c51331ee0ffff794 Mon Sep 17 00:00:00 2001 From: cananoo <2059997196@qq.com> Date: Thu, 27 Aug 2026 21:11:41 +0800 Subject: [PATCH 2/2] Fix NEWS reference for AsyncMock side_effect --- .../Library/2026-08-27-20-47-01.gh-issue-156460.A7kP3m.rst | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Misc/NEWS.d/next/Library/2026-08-27-20-47-01.gh-issue-156460.A7kP3m.rst b/Misc/NEWS.d/next/Library/2026-08-27-20-47-01.gh-issue-156460.A7kP3m.rst index e8845f566ca21c..f6871145236ba5 100644 --- a/Misc/NEWS.d/next/Library/2026-08-27-20-47-01.gh-issue-156460.A7kP3m.rst +++ b/Misc/NEWS.d/next/Library/2026-08-27-20-47-01.gh-issue-156460.A7kP3m.rst @@ -1 +1,2 @@ -Await async callable objects used as :attr:`unittest.mock.AsyncMock.side_effect`. +Await async callable objects used as the ``side_effect`` of +:class:`unittest.mock.AsyncMock`.