From b89e5740b8c09024dcf3d3dcaa4a67e9af5b2010 Mon Sep 17 00:00:00 2001 From: Aniket Panse Date: Tue, 17 Dec 2019 17:21:29 -0800 Subject: [PATCH] bpo-39082: AsyncMock is unable to correctly patch static or class methods https://bugs.python.org/issue39082 --- Lib/unittest/mock.py | 2 ++ Lib/unittest/test/testmock/testasync.py | 22 ++++++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/Lib/unittest/mock.py b/Lib/unittest/mock.py index cd5a2aeb6084d7..aacbf8b96d0812 100644 --- a/Lib/unittest/mock.py +++ b/Lib/unittest/mock.py @@ -48,6 +48,8 @@ def _is_async_obj(obj): if _is_instance_mock(obj) and not isinstance(obj, AsyncMock): return False + if isinstance(obj, (classmethod, staticmethod)): + return asyncio.iscoroutinefunction(obj.__func__) return asyncio.iscoroutinefunction(obj) or inspect.isawaitable(obj) diff --git a/Lib/unittest/test/testmock/testasync.py b/Lib/unittest/test/testmock/testasync.py index 149fd4deff1021..d28efb487e92ca 100644 --- a/Lib/unittest/test/testmock/testasync.py +++ b/Lib/unittest/test/testmock/testasync.py @@ -19,6 +19,14 @@ async def async_method(self): def normal_method(self): pass + @classmethod + async def async_class_method(cls): + pass + + @staticmethod + async def async_static_method(): + pass + class AwaitableClass: def __await__(self): yield @@ -71,6 +79,20 @@ def test_async(mock_method): test_async() + def test_is_AsyncMock_patch_staticmethod(self): + @patch.object(AsyncClass, 'async_static_method') + def test_async(mock_method): + self.assertIsInstance(mock_method, AsyncMock) + + test_async() + + def test_is_AsyncMock_patch_classmethod(self): + @patch.object(AsyncClass, 'async_class_method') + def test_async(mock_method): + self.assertIsInstance(mock_method, AsyncMock) + + test_async() + def test_async_def_patch(self): @patch(f"{__name__}.async_func", AsyncMock()) async def test_async():