Skip to content

Commit 2b75fc2

Browse files
authored
Minor fixes to dataclass tests. (GH-6243)
Also, re-enable a test for ClassVars with default_factory.
1 parent dfb6e54 commit 2b75fc2

File tree

1 file changed

+41
-42
lines changed

1 file changed

+41
-42
lines changed

Lib/test/test_dataclasses.py

Lines changed: 41 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -133,8 +133,8 @@ def __eq__(self):
133133
self.assertEqual(hash(C(10)), hash((10,)))
134134

135135
# Creating this class should generate an exception, because
136-
# __hash__ exists and is not None, which it would be if it had
137-
# been auto-generated do due __eq__ being defined.
136+
# __hash__ exists and is not None, which it would be if it
137+
# had been auto-generated due to __eq__ being defined.
138138
with self.assertRaisesRegex(TypeError,
139139
'Cannot overwrite attribute __hash__'):
140140
@dataclass(unsafe_hash=True)
@@ -145,7 +145,6 @@ def __eq__(self):
145145
def __hash__(self):
146146
pass
147147

148-
149148
def test_overwrite_fields_in_derived_class(self):
150149
# Note that x from C1 replaces x in Base, but the order remains
151150
# the same as defined in Base.
@@ -624,7 +623,7 @@ class C:
624623
self.assertIs(o1.x, o2.x)
625624

626625
def test_no_options(self):
627-
# call with dataclass()
626+
# Call with dataclass().
628627
@dataclass()
629628
class C:
630629
x: int
@@ -639,7 +638,7 @@ class Point:
639638
y: int
640639
self.assertNotEqual(Point(1, 2), (1, 2))
641640

642-
# And that we can't compare to another unrelated dataclass
641+
# And that we can't compare to another unrelated dataclass.
643642
@dataclass
644643
class C:
645644
x: int
@@ -664,7 +663,7 @@ class Date:
664663
self.assertNotEqual(Point3D(2017, 6, 3), Date(2017, 6, 3))
665664
self.assertNotEqual(Point3D(1, 2, 3), (1, 2, 3))
666665

667-
# Make sure we can't unpack
666+
# Make sure we can't unpack.
668667
with self.assertRaisesRegex(TypeError, 'unpack'):
669668
x, y, z = Point3D(4, 5, 6)
670669

@@ -695,7 +694,7 @@ def validate_class(cls):
695694
# Verify __init__.
696695

697696
signature = inspect.signature(cls.__init__)
698-
# Check the return type, should be None
697+
# Check the return type, should be None.
699698
self.assertIs(signature.return_annotation, None)
700699

701700
# Check each parameter.
@@ -716,12 +715,12 @@ def validate_class(cls):
716715
param = next(params)
717716
self.assertEqual(param.name, 'k')
718717
self.assertIs (param.annotation, F)
719-
# Don't test for the default, since it's set to MISSING
718+
# Don't test for the default, since it's set to MISSING.
720719
self.assertEqual(param.kind, inspect.Parameter.POSITIONAL_OR_KEYWORD)
721720
param = next(params)
722721
self.assertEqual(param.name, 'l')
723722
self.assertIs (param.annotation, float)
724-
# Don't test for the default, since it's set to MISSING
723+
# Don't test for the default, since it's set to MISSING.
725724
self.assertEqual(param.kind, inspect.Parameter.POSITIONAL_OR_KEYWORD)
726725
self.assertRaises(StopIteration, next, params)
727726

@@ -867,7 +866,7 @@ def __post_init__(self):
867866

868867
self.assertEqual(C().x, 5)
869868

870-
# Now call super(), and it will raise
869+
# Now call super(), and it will raise.
871870
@dataclass
872871
class C(B):
873872
def __post_init__(self):
@@ -928,8 +927,8 @@ class C:
928927

929928
c = C(5)
930929
self.assertEqual(repr(c), 'TestCase.test_class_var.<locals>.C(x=5, y=10)')
931-
self.assertEqual(len(fields(C)), 2) # We have 2 fields
932-
self.assertEqual(len(C.__annotations__), 5) # And 3 ClassVars
930+
self.assertEqual(len(fields(C)), 2) # We have 2 fields.
931+
self.assertEqual(len(C.__annotations__), 5) # And 3 ClassVars.
933932
self.assertEqual(c.z, 1000)
934933
self.assertEqual(c.w, 2000)
935934
self.assertEqual(c.t, 3000)
@@ -1205,14 +1204,13 @@ class D(C):
12051204
d = D(4, 5)
12061205
self.assertEqual((d.x, d.z), (4, 5))
12071206

1208-
1209-
def x_test_classvar_default_factory(self):
1210-
# XXX: it's an error for a ClassVar to have a factory function
1211-
@dataclass
1212-
class C:
1213-
x: ClassVar[int] = field(default_factory=int)
1214-
1215-
self.assertIs(C().x, int)
1207+
def test_classvar_default_factory(self):
1208+
# It's an error for a ClassVar to have a factory function.
1209+
with self.assertRaisesRegex(TypeError,
1210+
'cannot have a default factory'):
1211+
@dataclass
1212+
class C:
1213+
x: ClassVar[int] = field(default_factory=int)
12161214

12171215
def test_is_dataclass(self):
12181216
class NotDataClass:
@@ -1264,7 +1262,7 @@ class C: pass
12641262
fields(C())
12651263

12661264
def test_helper_asdict(self):
1267-
# Basic tests for asdict(), it should return a new dictionary
1265+
# Basic tests for asdict(), it should return a new dictionary.
12681266
@dataclass
12691267
class C:
12701268
x: int
@@ -1279,7 +1277,7 @@ class C:
12791277
self.assertIs(type(asdict(c)), dict)
12801278

12811279
def test_helper_asdict_raises_on_classes(self):
1282-
# asdict() should raise on a class object
1280+
# asdict() should raise on a class object.
12831281
@dataclass
12841282
class C:
12851283
x: int
@@ -1377,7 +1375,7 @@ class C:
13771375
self.assertIs(type(d), OrderedDict)
13781376

13791377
def test_helper_astuple(self):
1380-
# Basic tests for astuple(), it should return a new tuple
1378+
# Basic tests for astuple(), it should return a new tuple.
13811379
@dataclass
13821380
class C:
13831381
x: int
@@ -1392,7 +1390,7 @@ class C:
13921390
self.assertIs(type(astuple(c)), tuple)
13931391

13941392
def test_helper_astuple_raises_on_classes(self):
1395-
# astuple() should raise on a class object
1393+
# astuple() should raise on a class object.
13961394
@dataclass
13971395
class C:
13981396
x: int
@@ -1489,7 +1487,7 @@ def nt(lst):
14891487
self.assertIs(type(t), NT)
14901488

14911489
def test_dynamic_class_creation(self):
1492-
cls_dict = {'__annotations__': {'x':int, 'y':int},
1490+
cls_dict = {'__annotations__': {'x': int, 'y': int},
14931491
}
14941492

14951493
# Create the class.
@@ -1502,7 +1500,7 @@ def test_dynamic_class_creation(self):
15021500
self.assertEqual(asdict(cls(1, 2)), {'x': 1, 'y': 2})
15031501

15041502
def test_dynamic_class_creation_using_field(self):
1505-
cls_dict = {'__annotations__': {'x':int, 'y':int},
1503+
cls_dict = {'__annotations__': {'x': int, 'y': int},
15061504
'y': field(default=5),
15071505
}
15081506

@@ -1569,8 +1567,8 @@ class C:
15691567

15701568
def test_alternate_classmethod_constructor(self):
15711569
# Since __post_init__ can't take params, use a classmethod
1572-
# alternate constructor. This is mostly an example to show how
1573-
# to use this technique.
1570+
# alternate constructor. This is mostly an example to show
1571+
# how to use this technique.
15741572
@dataclass
15751573
class C:
15761574
x: int
@@ -1604,7 +1602,7 @@ def test_field_metadata_mapping(self):
16041602
class C:
16051603
i: int = field(metadata=0)
16061604

1607-
# Make sure an empty dict works
1605+
# Make sure an empty dict works.
16081606
@dataclass
16091607
class C:
16101608
i: int = field(metadata={})
@@ -1666,7 +1664,7 @@ class LabeledBox(Generic[T]):
16661664
self.assertEqual(box.content, 42)
16671665
self.assertEqual(box.label, '<unknown>')
16681666

1669-
# subscripting the resulting class should work, etc.
1667+
# Subscripting the resulting class should work, etc.
16701668
Alias = List[LabeledBox[int]]
16711669

16721670
def test_generic_extending(self):
@@ -1931,7 +1929,7 @@ class B:
19311929
with self.assertRaisesRegex(TypeError,
19321930
"'f' is a field but has no type annotation"):
19331931
# This is still an error: make sure we don't pick up the
1934-
# type annotation in the base class.
1932+
# type annotation in the base class.
19351933
@dataclass
19361934
class C(B):
19371935
f = field()
@@ -1944,7 +1942,7 @@ class B:
19441942
with self.assertRaisesRegex(TypeError,
19451943
"'f' is a field but has no type annotation"):
19461944
# This is still an error: make sure we don't pick up the
1947-
# type annotation in the base class.
1945+
# type annotation in the base class.
19481946
@dataclass
19491947
class C(B):
19501948
f = field()
@@ -2178,7 +2176,7 @@ def __repr__(self):
21782176

21792177
class TestFrozen(unittest.TestCase):
21802178
def test_overwriting_frozen(self):
2181-
# frozen uses __setattr__ and __delattr__
2179+
# frozen uses __setattr__ and __delattr__.
21822180
with self.assertRaisesRegex(TypeError,
21832181
'Cannot overwrite attribute __setattr__'):
21842182
@dataclass(frozen=True)
@@ -2473,16 +2471,16 @@ class C:
24732471

24742472
def test_hash_no_args(self):
24752473
# Test dataclasses with no hash= argument. This exists to
2476-
# make sure that if the @dataclass parameter name is changed
2477-
# or the non-default hashing behavior changes, the default
2478-
# hashability keeps working the same way.
2474+
# make sure that if the @dataclass parameter name is changed
2475+
# or the non-default hashing behavior changes, the default
2476+
# hashability keeps working the same way.
24792477

24802478
class Base:
24812479
def __hash__(self):
24822480
return 301
24832481

24842482
# If frozen or eq is None, then use the default value (do not
2485-
# specify any value in the decorator).
2483+
# specify any value in the decorator).
24862484
for frozen, eq, base, expected in [
24872485
(None, None, object, 'unhashable'),
24882486
(None, None, Base, 'unhashable'),
@@ -2534,9 +2532,9 @@ class C(base):
25342532

25352533
elif expected == 'object':
25362534
# I'm not sure what test to use here. object's
2537-
# hash isn't based on id(), so calling hash()
2538-
# won't tell us much. So, just check the function
2539-
# used is object's.
2535+
# hash isn't based on id(), so calling hash()
2536+
# won't tell us much. So, just check the
2537+
# function used is object's.
25402538
self.assertIs(C.__hash__, object.__hash__)
25412539

25422540
elif expected == 'tuple':
@@ -2665,8 +2663,9 @@ class C:
26652663
__slots__ = ('x',)
26662664
x: Any
26672665

2668-
# There was a bug where a variable in a slot was assumed
2669-
# to also have a default value (of type types.MemberDescriptorType).
2666+
# There was a bug where a variable in a slot was assumed to
2667+
# also have a default value (of type
2668+
# types.MemberDescriptorType).
26702669
with self.assertRaisesRegex(TypeError,
26712670
r"__init__\(\) missing 1 required positional argument: 'x'"):
26722671
C()

0 commit comments

Comments
 (0)