Skip to content

Commit

Permalink
Apply suggestions from code review
Browse files Browse the repository at this point in the history
Co-authored-by: Alyssa Coghlan <[email protected]>
  • Loading branch information
sobolevn and ncoghlan authored Oct 12, 2024
1 parent 81b4e00 commit bfa9385
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 11 deletions.
22 changes: 11 additions & 11 deletions Lib/test/test_unittest/testmock/testhelpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -1107,30 +1107,30 @@ class WithNonFields:
with self.assertRaisesRegex(AttributeError, msg):
mock.b

def test_dataclass_with_wider_default(self):
def test_dataclass_default_value_type_overrides_field_annotation(self):
# 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:
class WithUnionAnnotation:
narrow_default: int | None = field(default=30)

for mock in [
create_autospec(WithWiderDefault, instance=True),
create_autospec(WithWiderDefault()),
create_autospec(WithUnionAnnotation, instance=True),
create_autospec(WithUnionAnnotation()),
]:
with self.subTest(mock=mock):
self.assertIs(mock.narrow_default.__class__, int)

def test_dataclass_with_no_default(self):
def test_dataclass_field_with_no_default_value(self):
@dataclass
class WithWiderDefault:
narrow_default: int | None
class WithUnionAnnotation:
no_default: int | None

mock = create_autospec(WithWiderDefault, instance=True)
self.assertIs(mock.narrow_default.__class__, type(int | None))
mock = create_autospec(WithUnionAnnotation, instance=True)
self.assertIs(mock.no_default.__class__, type(int | None))

mock = create_autospec(WithWiderDefault(1))
self.assertIs(mock.narrow_default.__class__, int)
mock = create_autospec(WithUnionAnnotation(1))
self.assertIs(mock.no_default.__class__, int)


class TestCallList(unittest.TestCase):
Expand Down
4 changes: 4 additions & 0 deletions Lib/unittest/mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -2760,6 +2760,10 @@ def create_autospec(spec, spec_set=False, instance=False, _parent=None,

base_entries = {entry: _missing for entry in dir(spec)}
if is_type and instance and is_dataclass(spec):
# Dataclass instance mocks created from a class may not have all of their fields
# prepopulated with default values. Create an initial set of attribute entries from
# the dataclass field annotations, but override them with the actual attribute types
# when fields have already been populated.
dataclass_fields = fields(spec)
entries = {f.name: f.type for f in dataclass_fields}
entries.update(base_entries)
Expand Down

0 comments on commit bfa9385

Please sign in to comment.