Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 26, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Lib/unittest/mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)


Expand Down
23 changes: 23 additions & 0 deletions Lib/unittest/test/testmock/testasync.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,15 @@ 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
Expand Down Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Allow AsyncMock to correctly patch static/class methods