Skip to content
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

bpo-39082: Fix: AsyncMock is unable to correctly patch static/class methods #17717

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
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 isinstance(obj, (classmethod, staticmethod)):
return asyncio.iscoroutinefunction(obj.__func__)
return asyncio.iscoroutinefunction(obj) or inspect.isawaitable(obj)


Expand Down
22 changes: 22 additions & 0 deletions Lib/unittest/test/testmock/testasync.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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():
Expand Down