Skip to content

Commit

Permalink
fix instance-only async attr
Browse files Browse the repository at this point in the history
  • Loading branch information
carljm committed Dec 16, 2022
1 parent 2260a54 commit a03f843
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
7 changes: 7 additions & 0 deletions Lib/test/test_unittest/testmock/testasync.py
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,13 @@ def test_spec_normal_methods_on_class_with_mock(self):
self.assertIsInstance(mock.async_method, AsyncMock)
self.assertIsInstance(mock.normal_method, Mock)

def test_spec_async_attributes_instance(self):
async_instance = AsyncClass()
async_instance.async_func_attr = async_func

mock_async_instance = Mock(async_instance)
self.assertIsInstance(mock_async_instance.async_func_attr, AsyncMock)

def test_spec_mock_type_kw(self):
def inner_test(mock_type):
async_mock = mock_type(spec=async_func)
Expand Down
5 changes: 4 additions & 1 deletion Lib/unittest/mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -506,8 +506,10 @@ def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False,

_spec_class = None
_spec_signature = None
_spec_obj = None

if spec is not None and not _is_list(spec):
_spec_obj = spec
if isinstance(spec, type):
_spec_class = spec
else:
Expand All @@ -520,6 +522,7 @@ def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False,

__dict__ = self.__dict__
__dict__['_spec_class'] = _spec_class
__dict__['_spec_obj'] = _spec_obj
__dict__['_spec_set'] = spec_set
__dict__['_spec_signature'] = _spec_signature
__dict__['_mock_methods'] = spec
Expand Down Expand Up @@ -1012,7 +1015,7 @@ def _get_child_mock(self, /, **kw):
For non-callable mocks the callable variant will be used (rather than
any custom subclass)."""
_new_name = kw.get("_new_name")
_spec_val = getattr(self.__dict__["_spec_class"], _new_name, None)
_spec_val = getattr(self.__dict__["_spec_obj"], _new_name, None)
if _spec_val is not None and asyncio.iscoroutinefunction(_spec_val):
return AsyncMock(**kw)

Expand Down

0 comments on commit a03f843

Please sign in to comment.