Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Handle async methods decorated with @classmethod or @staticmethod
  • Loading branch information
melwitt committed May 16, 2023
commit a20b360008ec9232e3b80043a4c2951ef3125802
14 changes: 14 additions & 0 deletions Lib/test/test_unittest/testmock/testmock.py
Original file line number Diff line number Diff line change
Expand Up @@ -2311,5 +2311,19 @@ def test_property_not_called_with_spec_mock(self):
self.assertIsNone(obj._instance, msg='after mock')
self.assertEqual('object', obj.instance)

def test_decorated_async_methods_with_spec_mock(self):
class Foo():
@classmethod
async def class_method(cls):
pass
@staticmethod
async def static_method():
pass
async def method(self):
pass
mock = Mock(spec=Foo)
for m in (mock.method, mock.class_method, mock.static_method):
self.assertIsInstance(m, AsyncMock)

if __name__ == '__main__':
unittest.main()
8 changes: 7 additions & 1 deletion Lib/unittest/mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -526,7 +526,13 @@ def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False,
spec_list = dir(spec)

for attr in spec_list:
if iscoroutinefunction(inspect.getattr_static(spec, attr, None)):
static_attr = inspect.getattr_static(spec, attr, None)
unwrapped_attr = static_attr
try:
unwrapped_attr = inspect.unwrap(unwrapped_attr)
except ValueError:
pass
if iscoroutinefunction(unwrapped_attr):
_spec_asyncs.append(attr)

spec = spec_list
Expand Down