Skip to content

Commit ee3259a

Browse files
committed
Extend dataclass mock_methods
1 parent 89b688a commit ee3259a

File tree

2 files changed

+11
-6
lines changed

2 files changed

+11
-6
lines changed

Lib/test/test_unittest/testmock/testhelpers.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1125,6 +1125,8 @@ class Description:
11251125
self.assertIs(mock.__class__, Description)
11261126
self.assertIsInstance(mock.__dataclass_fields__, MagicMock)
11271127
self.assertIsInstance(mock.__dataclass_params__, MagicMock)
1128+
self.assertIsInstance(mock.__match_args__, MagicMock)
1129+
self.assertIsInstance(mock.__hash__, MagicMock)
11281130

11291131
class TestCallList(unittest.TestCase):
11301132

Lib/unittest/mock.py

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -569,6 +569,11 @@ def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False,
569569
__dict__['_mock_methods'] = spec
570570
__dict__['_spec_asyncs'] = _spec_asyncs
571571

572+
def _mock_extend_spec_methods(self, spec_methods):
573+
methods = self.__dict__.get('_mock_methods') or []
574+
methods.extend(spec_methods)
575+
self.__dict__['_mock_methods'] = methods
576+
572577
def __get_return_value(self):
573578
ret = self._mock_return_value
574579
if self._mock_delegate is not None:
@@ -2766,17 +2771,15 @@ def create_autospec(spec, spec_set=False, instance=False, _parent=None,
27662771
raise InvalidSpecError(f'Cannot autospec a Mock object. '
27672772
f'[object={spec!r}]')
27682773
is_async_func = _is_async_func(spec)
2774+
_kwargs = {'spec': spec}
27692775

27702776
entries = [(entry, _missing) for entry in dir(spec)]
27712777
if is_type and instance and is_dataclass(spec):
2778+
is_dataclass_spec = True
27722779
dataclass_fields = fields(spec)
27732780
entries.extend((f.name, f.type) for f in dataclass_fields)
2774-
spec_list = [f.name for f in dataclass_fields]
2775-
spec_list.extend(['__dataclass_fields__', '__dataclass_params__'])
2776-
_kwargs = {'spec': spec_list} # we set `__class__` further
2777-
is_dataclass_spec = True
2781+
dataclass_spec_list = [f.name for f in dataclass_fields]
27782782
else:
2779-
_kwargs = {'spec': spec}
27802783
is_dataclass_spec = False
27812784

27822785
if spec_set:
@@ -2815,7 +2818,7 @@ def create_autospec(spec, spec_set=False, instance=False, _parent=None,
28152818
mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
28162819
name=_name, **_kwargs)
28172820
if is_dataclass_spec:
2818-
mock.__class__ = spec # we need this for `isinstance` to work
2821+
mock._mock_extend_spec_methods(dataclass_spec_list)
28192822

28202823
if isinstance(spec, FunctionTypes):
28212824
# should only happen at the top level because we don't

0 commit comments

Comments
 (0)