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

gh-124176: create_autospec must not change how dataclass defaults are mocked #124724

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
15 changes: 15 additions & 0 deletions Lib/test/test_unittest/testmock/testhelpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -1107,6 +1107,21 @@ class WithNonFields:
with self.assertRaisesRegex(AttributeError, msg):
mock.b

def test_dataclass_with_wider_default(self):
sobolevn marked this conversation as resolved.
Show resolved Hide resolved
# If field defines an actual default, we don't need to change
# the default type. Since this is how it used to work before #124176
@dataclass
class WithWiderDefault:
narrow_default: int | None = field(default=30)

for mock in [
create_autospec(WithWiderDefault, instance=True),
create_autospec(WithWiderDefault()),
sobolevn marked this conversation as resolved.
Show resolved Hide resolved
]:
with self.subTest(mock=mock):
self.assertIs(mock.narrow_default.__class__, int)


class TestCallList(unittest.TestCase):

def test_args_list_contains_call_list(self):
Expand Down
8 changes: 5 additions & 3 deletions Lib/unittest/mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -2758,13 +2758,15 @@ def create_autospec(spec, spec_set=False, instance=False, _parent=None,
f'[object={spec!r}]')
is_async_func = _is_async_func(spec)

entries = [(entry, _missing) for entry in dir(spec)]
base_entries = {entry: _missing for entry in dir(spec)}
if is_type and instance and is_dataclass(spec):
dataclass_fields = fields(spec)
sobolevn marked this conversation as resolved.
Show resolved Hide resolved
entries.extend((f.name, f.type) for f in dataclass_fields)
entries = {f.name: f.type for f in dataclass_fields}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How come we don't end up using UnionType here from the int | None annotation?

Copy link
Member Author

@sobolevn sobolevn Sep 30, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because I override entries with default_entries here: https://github.com/python/cpython/pull/124724/files#diff-347d0254250a1ab7ab8e31b405e2c35b74cd2838df4ee74f1b658a459eb91f1aR2765

This way field(default=0) has the priority over the annotation.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two questions from that:

  1. What happens with a class such as this?

    @dataclass
    class SampleClass:
        sample_attr: int | None
        
  2. What does the mock machinery do with the field object it gets in the case you show above?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. In this case spec would be UnionType, because we have no default
  2. Mock does nothing special to field, dataclass itself sets SampleClass.sample_attr = default, and we just use getattr to get the existing default

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it be possible to add a unit test (or more if necessary) showing this?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done!

entries.update(base_entries)
_kwargs = {'spec': [f.name for f in dataclass_fields]}
else:
_kwargs = {'spec': spec}
entries = base_entries

if spec_set:
_kwargs = {'spec_set': spec}
Expand Down Expand Up @@ -2822,7 +2824,7 @@ def create_autospec(spec, spec_set=False, instance=False, _parent=None,
_name='()', _parent=mock,
wraps=wrapped)

for entry, original in entries:
for entry, original in entries.items():
if _is_magic(entry):
# MagicMock already does the useful magic methods for us
continue
Expand Down
Loading