8000 gh-83076: 3.8x speed improvement in (Async)Mock instantiation by carljm · Pull Request #100252 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

gh-83076: 3.8x speed improvement in (Async)Mock instantiation #100252

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 9 commits into from
Dec 23, 2022
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
Next Next commit
fix instance-only async attr
  • Loading branch information
carljm committed Dec 16, 2022
commit a03f84360e4830ffa63883ba52f6b5958c6bd16a
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