[Python-checkins] [3.8] bpo-39082: Allow AsyncMock to correctly patch static/class methods (GH-18190)

Chris Withers webhook-mailer at python.org
Sun Jan 26 10:30:34 EST 2020


https://github.com/python/cpython/commit/19be85c76503535c101b38194d282187de0ff631
commit: 19be85c76503535c101b38194d282187de0ff631
branch: 3.8
author: Matthew Kokotovich <mkokotovich at gmail.com>
committer: Chris Withers <chris at withers.org>
date: 2020-01-26T15:30:27Z
summary:

[3.8] bpo-39082: Allow AsyncMock to correctly patch static/class methods (GH-18190)

(cherry picked from commit 62865f4532094017a9b780b704686ca9734bc329)

Co-authored-by: Matthew Kokotovich <mkokotovich at gmail.com>

files:
A Misc/NEWS.d/next/Library/2020-01-24-13-24-35.bpo-39082.qKgrq_.rst
M Lib/unittest/mock.py
M Lib/unittest/test/testmock/testasync.py

diff --git a/Lib/unittest/mock.py b/Lib/unittest/mock.py
index 34f2dd77ec6cd..66ace80cb5f9c 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 hasattr(obj, '__func__'):
+        obj = getattr(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 0bd7ae4929c3e..e68022afdccea 100644
--- a/Lib/unittest/test/testmock/testasync.py
+++ b/Lib/unittest/test/testmock/testasync.py
@@ -19,6 +19,15 @@ def __init__(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 +80,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", return_value=1)
         @patch(f"{__name__}.async_func_args", return_value=2)
diff --git a/Misc/NEWS.d/next/Library/2020-01-24-13-24-35.bpo-39082.qKgrq_.rst b/Misc/NEWS.d/next/Library/2020-01-24-13-24-35.bpo-39082.qKgrq_.rst
new file mode 100644
index 0000000000000..52c4ee1b33bda
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2020-01-24-13-24-35.bpo-39082.qKgrq_.rst
@@ -0,0 +1 @@
+Allow AsyncMock to correctly patch static/class methods



More information about the Python-checkins mailing list