Skip to content

Commit 19be85c

Browse files
mkokotovichcjw296
authored andcommitted
[3.8] bpo-39082: Allow AsyncMock to correctly patch static/class methods (GH-18190)
(cherry picked from commit 62865f4) Co-authored-by: Matthew Kokotovich <[email protected]>
1 parent eebcff8 commit 19be85c

File tree

3 files changed

+26
-0
lines changed

3 files changed

+26
-0
lines changed

Lib/unittest/mock.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,8 @@
4848
def _is_async_obj(obj):
4949
if _is_instance_mock(obj) and not isinstance(obj, AsyncMock):
5050
return False
51+
if hasattr(obj, '__func__'):
52+
obj = getattr(obj, '__func__')
5153
return asyncio.iscoroutinefunction(obj) or inspect.isawaitable(obj)
5254

5355

Lib/unittest/test/testmock/testasync.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,15 @@ async def async_method(self):
1919
def normal_method(self):
2020
pass
2121

22+
@classmethod
23+
async def async_class_method(cls):
24+
pass
25+
26+
@staticmethod
27+
async def async_static_method():
28+
pass
29+
30+
2231
class AwaitableClass:
2332
def __await__(self):
2433
yield
@@ -71,6 +80,20 @@ def test_async(mock_method):
7180

7281
test_async()
7382

83+
def test_is_AsyncMock_patch_staticmethod(self):
84+
@patch.object(AsyncClass, 'async_static_method')
85+
def test_async(mock_method):
86+
self.assertIsInstance(mock_method, AsyncMock)
87+
88+
test_async()
89+
90+
def test_is_AsyncMock_patch_classmethod(self):
91+
@patch.object(AsyncClass, 'async_class_method')
92+
def test_async(mock_method):
93+
self.assertIsInstance(mock_method, AsyncMock)
94+
95+
test_async()
96+
7497
def test_async_def_patch(self):
7598
@patch(f"{__name__}.async_func", return_value=1)
7699
@patch(f"{__name__}.async_func_args", return_value=2)
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Allow AsyncMock to correctly patch static/class methods

0 commit comments

Comments
 (0)