-
Notifications
You must be signed in to change notification settings - Fork 52
/
Copy pathtest_dataclasses.py
3061 lines (2592 loc) · 98.6 KB
/
test_dataclasses.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Deliberately use "from dataclasses import *". Every name in __all__
# is tested, so they all must be present. This is a way to catch
# missing ones.
from dataclasses import *
import pickle
import inspect
import unittest
from unittest.mock import Mock
from typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional
from collections import deque, OrderedDict, namedtuple
from functools import total_ordering
import typing # Needed for the string "typing.ClassVar[int]" to work as an annotation.
import dataclasses # Needed for the string "dataclasses.InitVar[int]" to work as an annotation.
# Just any custom exception we can catch.
class CustomError(Exception): pass
class TestCase(unittest.TestCase):
def test_no_fields(self):
@dataclass
class C:
pass
o = C()
self.assertEqual(len(fields(C)), 0)
def test_no_fields_but_member_variable(self):
@dataclass
class C:
i = 0
o = C()
self.assertEqual(len(fields(C)), 0)
def test_one_field_no_default(self):
@dataclass
class C:
x: int
o = C(42)
self.assertEqual(o.x, 42)
def test_named_init_params(self):
@dataclass
class C:
x: int
o = C(x=32)
self.assertEqual(o.x, 32)
def test_two_fields_one_default(self):
@dataclass
class C:
x: int
y: int = 0
o = C(3)
self.assertEqual((o.x, o.y), (3, 0))
# Non-defaults following defaults.
with self.assertRaisesRegex(TypeError,
"non-default argument 'y' follows "
"default argument"):
@dataclass
class C:
x: int = 0
y: int
# A derived class adds a non-default field after a default one.
with self.assertRaisesRegex(TypeError,
"non-default argument 'y' follows "
"default argument"):
@dataclass
class B:
x: int = 0
@dataclass
class C(B):
y: int
# Override a base class field and add a default to
# a field which didn't use to have a default.
with self.assertRaisesRegex(TypeError,
"non-default argument 'y' follows "
"default argument"):
@dataclass
class B:
x: int
y: int
@dataclass
class C(B):
x: int = 0
def test_overwrite_hash(self):
# Test that declaring this class isn't an error. It should
# use the user-provided __hash__.
@dataclass(frozen=True)
class C:
x: int
def __hash__(self):
return 301
self.assertEqual(hash(C(100)), 301)
# Test that declaring this class isn't an error. It should
# use the generated __hash__.
@dataclass(frozen=True)
class C:
x: int
def __eq__(self, other):
return False
self.assertEqual(hash(C(100)), hash((100,)))
# But this one should generate an exception, because with
# unsafe_hash=True, it's an error to have a __hash__ defined.
with self.assertRaisesRegex(TypeError,
'Cannot overwrite attribute __hash__'):
@dataclass(unsafe_hash=True)
class C:
def __hash__(self):
pass
# Creating this class should not generate an exception,
# because even though __hash__ exists before @dataclass is
# called, (due to __eq__ being defined), since it's None
# that's okay.
@dataclass(unsafe_hash=True)
class C:
x: int
def __eq__(self):
pass
# The generated hash function works as we'd expect.
self.assertEqual(hash(C(10)), hash((10,)))
# Creating this class should generate an exception, because
# __hash__ exists and is not None, which it would be if it
# had been auto-generated due to __eq__ being defined.
with self.assertRaisesRegex(TypeError,
'Cannot overwrite attribute __hash__'):
@dataclass(unsafe_hash=True)
class C:
x: int
def __eq__(self):
pass
def __hash__(self):
pass
def test_overwrite_fields_in_derived_class(self):
# Note that x from C1 replaces x in Base, but the order remains
# the same as defined in Base.
@dataclass
class Base:
x: Any = 15.0
y: int = 0
@dataclass
class C1(Base):
z: int = 10
x: int = 15
o = Base()
self.assertEqual(repr(o), 'TestCase.test_overwrite_fields_in_derived_class.<locals>.Base(x=15.0, y=0)')
o = C1()
self.assertEqual(repr(o), 'TestCase.test_overwrite_fields_in_derived_class.<locals>.C1(x=15, y=0, z=10)')
o = C1(x=5)
self.assertEqual(repr(o), 'TestCase.test_overwrite_fields_in_derived_class.<locals>.C1(x=5, y=0, z=10)')
def test_field_named_self(self):
@dataclass
class C:
self: str
c=C('foo')
self.assertEqual(c.self, 'foo')
# Make sure the first parameter is not named 'self'.
sig = inspect.signature(C.__init__)
first = next(iter(sig.parameters))
self.assertNotEqual('self', first)
# But we do use 'self' if no field named self.
@dataclass
class C:
selfx: str
# Make sure the first parameter is named 'self'.
sig = inspect.signature(C.__init__)
first = next(iter(sig.parameters))
self.assertEqual('self', first)
def test_0_field_compare(self):
# Ensure that order=False is the default.
@dataclass
class C0:
pass
@dataclass(order=False)
class C1:
pass
for cls in [C0, C1]:
with self.subTest(cls=cls):
self.assertEqual(cls(), cls())
for idx, fn in enumerate([lambda a, b: a < b,
lambda a, b: a <= b,
lambda a, b: a > b,
lambda a, b: a >= b]):
with self.subTest(idx=idx):
with self.assertRaisesRegex(TypeError,
f"not supported between instances of '{cls.__name__}' and '{cls.__name__}'"):
fn(cls(), cls())
@dataclass(order=True)
class C:
pass
self.assertLessEqual(C(), C())
self.assertGreaterEqual(C(), C())
def test_1_field_compare(self):
# Ensure that order=False is the default.
@dataclass
class C0:
x: int
@dataclass(order=False)
class C1:
x: int
for cls in [C0, C1]:
with self.subTest(cls=cls):
self.assertEqual(cls(1), cls(1))
self.assertNotEqual(cls(0), cls(1))
for idx, fn in enumerate([lambda a, b: a < b,
lambda a, b: a <= b,
lambda a, b: a > b,
lambda a, b: a >= b]):
with self.subTest(idx=idx):
with self.assertRaisesRegex(TypeError,
f"not supported between instances of '{cls.__name__}' and '{cls.__name__}'"):
fn(cls(0), cls(0))
@dataclass(order=True)
class C:
x: int
self.assertLess(C(0), C(1))
self.assertLessEqual(C(0), C(1))
self.assertLessEqual(C(1), C(1))
self.assertGreater(C(1), C(0))
self.assertGreaterEqual(C(1), C(0))
self.assertGreaterEqual(C(1), C(1))
def test_simple_compare(self):
# Ensure that order=False is the default.
@dataclass
class C0:
x: int
y: int
@dataclass(order=False)
class C1:
x: int
y: int
for cls in [C0, C1]:
with self.subTest(cls=cls):
self.assertEqual(cls(0, 0), cls(0, 0))
self.assertEqual(cls(1, 2), cls(1, 2))
self.assertNotEqual(cls(1, 0), cls(0, 0))
self.assertNotEqual(cls(1, 0), cls(1, 1))
for idx, fn in enumerate([lambda a, b: a < b,
lambda a, b: a <= b,
lambda a, b: a > b,
lambda a, b: a >= b]):
with self.subTest(idx=idx):
with self.assertRaisesRegex(TypeError,
f"not supported between instances of '{cls.__name__}' and '{cls.__name__}'"):
fn(cls(0, 0), cls(0, 0))
@dataclass(order=True)
class C:
x: int
y: int
for idx, fn in enumerate([lambda a, b: a == b,
lambda a, b: a <= b,
lambda a, b: a >= b]):
with self.subTest(idx=idx):
self.assertTrue(fn(C(0, 0), C(0, 0)))
for idx, fn in enumerate([lambda a, b: a < b,
lambda a, b: a <= b,
lambda a, b: a != b]):
with self.subTest(idx=idx):
self.assertTrue(fn(C(0, 0), C(0, 1)))
self.assertTrue(fn(C(0, 1), C(1, 0)))
self.assertTrue(fn(C(1, 0), C(1, 1)))
for idx, fn in enumerate([lambda a, b: a > b,
lambda a, b: a >= b,
lambda a, b: a != b]):
with self.subTest(idx=idx):
self.assertTrue(fn(C(0, 1), C(0, 0)))
self.assertTrue(fn(C(1, 0), C(0, 1)))
self.assertTrue(fn(C(1, 1), C(1, 0)))
def test_compare_subclasses(self):
# Comparisons fail for subclasses, even if no fields
# are added.
@dataclass
class B:
i: int
@dataclass
class C(B):
pass
for idx, (fn, expected) in enumerate([(lambda a, b: a == b, False),
(lambda a, b: a != b, True)]):
with self.subTest(idx=idx):
self.assertEqual(fn(B(0), C(0)), expected)
for idx, fn in enumerate([lambda a, b: a < b,
lambda a, b: a <= b,
lambda a, b: a > b,
lambda a, b: a >= b]):
with self.subTest(idx=idx):
with self.assertRaisesRegex(TypeError,
"not supported between instances of 'B' and 'C'"):
fn(B(0), C(0))
def test_eq_order(self):
# Test combining eq and order.
for (eq, order, result ) in [
(False, False, 'neither'),
(False, True, 'exception'),
(True, False, 'eq_only'),
(True, True, 'both'),
]:
with self.subTest(eq=eq, order=order):
if result == 'exception':
with self.assertRaisesRegex(ValueError, 'eq must be true if order is true'):
@dataclass(eq=eq, order=order)
class C:
pass
else:
@dataclass(eq=eq, order=order)
class C:
pass
if result == 'neither':
self.assertNotIn('__eq__', C.__dict__)
self.assertNotIn('__lt__', C.__dict__)
self.assertNotIn('__le__', C.__dict__)
self.assertNotIn('__gt__', C.__dict__)
self.assertNotIn('__ge__', C.__dict__)
elif result == 'both':
self.assertIn('__eq__', C.__dict__)
self.assertIn('__lt__', C.__dict__)
self.assertIn('__le__', C.__dict__)
self.assertIn('__gt__', C.__dict__)
self.assertIn('__ge__', C.__dict__)
elif result == 'eq_only':
self.assertIn('__eq__', C.__dict__)
self.assertNotIn('__lt__', C.__dict__)
self.assertNotIn('__le__', C.__dict__)
self.assertNotIn('__gt__', C.__dict__)
self.assertNotIn('__ge__', C.__dict__)
else:
assert False, f'unknown result {result!r}'
def test_field_no_default(self):
@dataclass
class C:
x: int = field()
self.assertEqual(C(5).x, 5)
with self.assertRaisesRegex(TypeError,
r"__init__\(\) missing 1 required "
"positional argument: 'x'"):
C()
def test_field_default(self):
default = object()
@dataclass
class C:
x: object = field(default=default)
self.assertIs(C.x, default)
c = C(10)
self.assertEqual(c.x, 10)
# If we delete the instance attribute, we should then see the
# class attribute.
del c.x
self.assertIs(c.x, default)
self.assertIs(C().x, default)
def test_not_in_repr(self):
@dataclass
class C:
x: int = field(repr=False)
with self.assertRaises(TypeError):
C()
c = C(10)
self.assertEqual(repr(c), 'TestCase.test_not_in_repr.<locals>.C()')
@dataclass
class C:
x: int = field(repr=False)
y: int
c = C(10, 20)
self.assertEqual(repr(c), 'TestCase.test_not_in_repr.<locals>.C(y=20)')
def test_not_in_compare(self):
@dataclass
class C:
x: int = 0
y: int = field(compare=False, default=4)
self.assertEqual(C(), C(0, 20))
self.assertEqual(C(1, 10), C(1, 20))
self.assertNotEqual(C(3), C(4, 10))
self.assertNotEqual(C(3, 10), C(4, 10))
def test_hash_field_rules(self):
# Test all 6 cases of:
# hash=True/False/None
# compare=True/False
for (hash_, compare, result ) in [
(True, False, 'field' ),
(True, True, 'field' ),
(False, False, 'absent'),
(False, True, 'absent'),
(None, False, 'absent'),
(None, True, 'field' ),
]:
with self.subTest(hash=hash_, compare=compare):
@dataclass(unsafe_hash=True)
class C:
x: int = field(compare=compare, hash=hash_, default=5)
if result == 'field':
# __hash__ contains the field.
self.assertEqual(hash(C(5)), hash((5,)))
elif result == 'absent':
# The field is not present in the hash.
self.assertEqual(hash(C(5)), hash(()))
else:
assert False, f'unknown result {result!r}'
def test_init_false_no_default(self):
# If init=False and no default value, then the field won't be
# present in the instance.
@dataclass
class C:
x: int = field(init=False)
self.assertNotIn('x', C().__dict__)
@dataclass
class C:
x: int
y: int = 0
z: int = field(init=False)
t: int = 10
self.assertNotIn('z', C(0).__dict__)
self.assertEqual(vars(C(5)), {'t': 10, 'x': 5, 'y': 0})
def test_class_marker(self):
@dataclass
class C:
x: int
y: str = field(init=False, default=None)
z: str = field(repr=False)
the_fields = fields(C)
# the_fields is a tuple of 3 items, each value
# is in __annotations__.
self.assertIsInstance(the_fields, tuple)
for f in the_fields:
self.assertIs(type(f), Field)
self.assertIn(f.name, C.__annotations__)
self.assertEqual(len(the_fields), 3)
self.assertEqual(the_fields[0].name, 'x')
self.assertEqual(the_fields[0].type, int)
self.assertFalse(hasattr(C, 'x'))
self.assertTrue (the_fields[0].init)
self.assertTrue (the_fields[0].repr)
self.assertEqual(the_fields[1].name, 'y')
self.assertEqual(the_fields[1].type, str)
self.assertIsNone(getattr(C, 'y'))
self.assertFalse(the_fields[1].init)
self.assertTrue (the_fields[1].repr)
self.assertEqual(the_fields[2].name, 'z')
self.assertEqual(the_fields[2].type, str)
self.assertFalse(hasattr(C, 'z'))
self.assertTrue (the_fields[2].init)
self.assertFalse(the_fields[2].repr)
def test_field_order(self):
@dataclass
class B:
a: str = 'B:a'
b: str = 'B:b'
c: str = 'B:c'
@dataclass
class C(B):
b: str = 'C:b'
self.assertEqual([(f.name, f.default) for f in fields(C)],
[('a', 'B:a'),
('b', 'C:b'),
('c', 'B:c')])
@dataclass
class D(B):
c: str = 'D:c'
self.assertEqual([(f.name, f.default) for f in fields(D)],
[('a', 'B:a'),
('b', 'B:b'),
('c', 'D:c')])
@dataclass
class E(D):
a: str = 'E:a'
d: str = 'E:d'
self.assertEqual([(f.name, f.default) for f in fields(E)],
[('a', 'E:a'),
('b', 'B:b'),
('c', 'D:c'),
('d', 'E:d')])
def test_class_attrs(self):
# We only have a class attribute if a default value is
# specified, either directly or via a field with a default.
default = object()
@dataclass
class C:
x: int
y: int = field(repr=False)
z: object = default
t: int = field(default=100)
self.assertFalse(hasattr(C, 'x'))
self.assertFalse(hasattr(C, 'y'))
self.assertIs (C.z, default)
self.assertEqual(C.t, 100)
def test_disallowed_mutable_defaults(self):
# For the known types, don't allow mutable default values.
for typ, empty, non_empty in [(list, [], [1]),
(dict, {}, {0:1}),
(set, set(), set([1])),
]:
with self.subTest(typ=typ):
# Can't use a zero-length value.
with self.assertRaisesRegex(ValueError,
f'mutable default {typ} for field '
'x is not allowed'):
@dataclass
class Point:
x: typ = empty
# Nor a non-zero-length value
with self.assertRaisesRegex(ValueError,
f'mutable default {typ} for field '
'y is not allowed'):
@dataclass
class Point:
y: typ = non_empty
# Check subtypes also fail.
class Subclass(typ): pass
with self.assertRaisesRegex(ValueError,
f"mutable default .*Subclass'>"
' for field z is not allowed'
):
@dataclass
class Point:
z: typ = Subclass()
# Because this is a ClassVar, it can be mutable.
@dataclass
class C:
z: ClassVar[typ] = typ()
# Because this is a ClassVar, it can be mutable.
@dataclass
class C:
x: ClassVar[typ] = Subclass()
def test_deliberately_mutable_defaults(self):
# If a mutable default isn't in the known list of
# (list, dict, set), then it's okay.
class Mutable:
def __init__(self):
self.l = []
@dataclass
class C:
x: Mutable
# These 2 instances will share this value of x.
lst = Mutable()
o1 = C(lst)
o2 = C(lst)
self.assertEqual(o1, o2)
o1.x.l.extend([1, 2])
self.assertEqual(o1, o2)
self.assertEqual(o1.x.l, [1, 2])
self.assertIs(o1.x, o2.x)
def test_no_options(self):
# Call with dataclass().
@dataclass()
class C:
x: int
self.assertEqual(C(42).x, 42)
def test_not_tuple(self):
# Make sure we can't be compared to a tuple.
@dataclass
class Point:
x: int
y: int
self.assertNotEqual(Point(1, 2), (1, 2))
# And that we can't compare to another unrelated dataclass.
@dataclass
class C:
x: int
y: int
self.assertNotEqual(Point(1, 3), C(1, 3))
def test_not_tuple(self):
# Test that some of the problems with namedtuple don't happen
# here.
@dataclass
class Point3D:
x: int
y: int
z: int
@dataclass
class Date:
year: int
month: int
day: int
self.assertNotEqual(Point3D(2017, 6, 3), Date(2017, 6, 3))
self.assertNotEqual(Point3D(1, 2, 3), (1, 2, 3))
# Make sure we can't unpack.
with self.assertRaisesRegex(TypeError, 'is not iterable'):
x, y, z = Point3D(4, 5, 6)
# Make sure another class with the same field names isn't
# equal.
@dataclass
class Point3Dv1:
x: int = 0
y: int = 0
z: int = 0
self.assertNotEqual(Point3D(0, 0, 0), Point3Dv1())
def test_function_annotations(self):
# Some dummy class and instance to use as a default.
class F:
pass
f = F()
def validate_class(cls):
# First, check __annotations__, even though they're not
# function annotations.
self.assertEqual(cls.__annotations__['i'], int)
self.assertEqual(cls.__annotations__['j'], str)
self.assertEqual(cls.__annotations__['k'], F)
self.assertEqual(cls.__annotations__['l'], float)
self.assertEqual(cls.__annotations__['z'], complex)
# Verify __init__.
signature = inspect.signature(cls.__init__)
# Check the return type, should be None.
self.assertIs(signature.return_annotation, None)
# Check each parameter.
params = iter(signature.parameters.values())
param = next(params)
# This is testing an internal name, and probably shouldn't be tested.
self.assertEqual(param.name, 'self')
param = next(params)
self.assertEqual(param.name, 'i')
self.assertIs (param.annotation, int)
self.assertEqual(param.default, inspect.Parameter.empty)
self.assertEqual(param.kind, inspect.Parameter.POSITIONAL_OR_KEYWORD)
param = next(params)
self.assertEqual(param.name, 'j')
self.assertIs (param.annotation, str)
self.assertEqual(param.default, inspect.Parameter.empty)
self.assertEqual(param.kind, inspect.Parameter.POSITIONAL_OR_KEYWORD)
param = next(params)
self.assertEqual(param.name, 'k')
self.assertIs (param.annotation, F)
# Don't test for the default, since it's set to MISSING.
self.assertEqual(param.kind, inspect.Parameter.POSITIONAL_OR_KEYWORD)
param = next(params)
self.assertEqual(param.name, 'l')
self.assertIs (param.annotation, float)
# Don't test for the default, since it's set to MISSING.
self.assertEqual(param.kind, inspect.Parameter.POSITIONAL_OR_KEYWORD)
self.assertRaises(StopIteration, next, params)
@dataclass
class C:
i: int
j: str
k: F = f
l: float=field(default=None)
z: complex=field(default=3+4j, init=False)
validate_class(C)
# Now repeat with __hash__.
@dataclass(frozen=True, unsafe_hash=True)
class C:
i: int
j: str
k: F = f
l: float=field(default=None)
z: complex=field(default=3+4j, init=False)
validate_class(C)
def test_missing_default(self):
# Test that MISSING works the same as a default not being
# specified.
@dataclass
class C:
x: int=field(default=MISSING)
with self.assertRaisesRegex(TypeError,
r'__init__\(\) missing 1 required '
'positional argument'):
C()
self.assertNotIn('x', C.__dict__)
@dataclass
class D:
x: int
with self.assertRaisesRegex(TypeError,
r'__init__\(\) missing 1 required '
'positional argument'):
D()
self.assertNotIn('x', D.__dict__)
def test_missing_default_factory(self):
# Test that MISSING works the same as a default factory not
# being specified (which is really the same as a default not
# being specified, too).
@dataclass
class C:
x: int=field(default_factory=MISSING)
with self.assertRaisesRegex(TypeError,
r'__init__\(\) missing 1 required '
'positional argument'):
C()
self.assertNotIn('x', C.__dict__)
@dataclass
class D:
x: int=field(default=MISSING, default_factory=MISSING)
with self.assertRaisesRegex(TypeError,
r'__init__\(\) missing 1 required '
'positional argument'):
D()
self.assertNotIn('x', D.__dict__)
def test_missing_repr(self):
self.assertIn('MISSING_TYPE object', repr(MISSING))
def test_dont_include_other_annotations(self):
@dataclass
class C:
i: int
def foo(self) -> int:
return 4
@property
def bar(self) -> int:
return 5
self.assertEqual(list(C.__annotations__), ['i'])
self.assertEqual(C(10).foo(), 4)
self.assertEqual(C(10).bar, 5)
self.assertEqual(C(10).i, 10)
def test_post_init(self):
# Just make sure it gets called
@dataclass
class C:
def __post_init__(self):
raise CustomError()
with self.assertRaises(CustomError):
C()
@dataclass
class C:
i: int = 10
def __post_init__(self):
if self.i == 10:
raise CustomError()
with self.assertRaises(CustomError):
C()
# post-init gets called, but doesn't raise. This is just
# checking that self is used correctly.
C(5)
# If there's not an __init__, then post-init won't get called.
@dataclass(init=False)
class C:
def __post_init__(self):
raise CustomError()
# Creating the class won't raise
C()
@dataclass
class C:
x: int = 0
def __post_init__(self):
self.x *= 2
self.assertEqual(C().x, 0)
self.assertEqual(C(2).x, 4)
# Make sure that if we're frozen, post-init can't set
# attributes.
@dataclass(frozen=True)
class C:
x: int = 0
def __post_init__(self):
self.x *= 2
with self.assertRaises(FrozenInstanceError):
C()
def test_post_init_super(self):
# Make sure super() post-init isn't called by default.
class B:
def __post_init__(self):
raise CustomError()
@dataclass
class C(B):
def __post_init__(self):
self.x = 5
self.assertEqual(C().x, 5)
# Now call super(), and it will raise.
@dataclass
class C(B):
def __post_init__(self):
super().__post_init__()
with self.assertRaises(CustomError):
C()
# Make sure post-init is called, even if not defined in our
# class.
@dataclass
class C(B):
pass
with self.assertRaises(CustomError):
C()
def test_post_init_staticmethod(self):
flag = False
@dataclass
class C:
x: int
y: int
@staticmethod
def __post_init__():
nonlocal flag
flag = True
self.assertFalse(flag)
c = C(3, 4)
self.assertEqual((c.x, c.y), (3, 4))
self.assertTrue(flag)
def test_post_init_classmethod(self):
@dataclass
class C:
flag = False
x: int
y: int
@classmethod
def __post_init__(cls):
cls.flag = True
self.assertFalse(C.flag)
c = C(3, 4)
self.assertEqual((c.x, c.y), (3, 4))
self.assertTrue(C.flag)
def test_class_var(self):
# Make sure ClassVars are ignored in __init__, __repr__, etc.
@dataclass
class C:
x: int
y: int = 10
z: ClassVar[int] = 1000
w: ClassVar[int] = 2000
t: ClassVar[int] = 3000
s: ClassVar = 4000
c = C(5)
self.assertEqual(repr(c), 'TestCase.test_class_var.<locals>.C(x=5, y=10)')
self.assertEqual(len(fields(C)), 2) # We have 2 fields.
self.assertEqual(len(C.__annotations__), 6) # And 4 ClassVars.
self.assertEqual(c.z, 1000)
self.assertEqual(c.w, 2000)
self.assertEqual(c.t, 3000)
self.assertEqual(c.s, 4000)
C.z += 1
self.assertEqual(c.z, 1001)
c = C(20)
self.assertEqual((c.x, c.y), (20, 10))
self.assertEqual(c.z, 1001)
self.assertEqual(c.w, 2000)
self.assertEqual(c.t, 3000)
self.assertEqual(c.s, 4000)
def test_class_var_no_default(self):
# If a ClassVar has no default value, it should not be set on the class.
@dataclass
class C:
x: ClassVar[int]
self.assertNotIn('x', C.__dict__)
def test_class_var_default_factory(self):
# It makes no sense for a ClassVar to have a default factory. When
# would it be called? Call it yourself, since it's class-wide.
with self.assertRaisesRegex(TypeError,
'cannot have a default factory'):
@dataclass
class C:
x: ClassVar[int] = field(default_factory=int)
self.assertNotIn('x', C.__dict__)
def test_class_var_with_default(self):
# If a ClassVar has a default value, it should be set on the class.
@dataclass
class C:
x: ClassVar[int] = 10
self.assertEqual(C.x, 10)
@dataclass
class C:
x: ClassVar[int] = field(default=10)
self.assertEqual(C.x, 10)
def test_class_var_frozen(self):
# Make sure ClassVars work even if we're frozen.
@dataclass(frozen=True)
class C:
x: int
y: int = 10
z: ClassVar[int] = 1000
w: ClassVar[int] = 2000
t: ClassVar[int] = 3000
c = C(5)
self.assertEqual(repr(C(5)), 'TestCase.test_class_var_frozen.<locals>.C(x=5, y=10)')
self.assertEqual(len(fields(C)), 2) # We have 2 fields
self.assertEqual(len(C.__annotations__), 5) # And 3 ClassVars
self.assertEqual(c.z, 1000)
self.assertEqual(c.w, 2000)
self.assertEqual(c.t, 3000)
# We can still modify the ClassVar, it's only instances that are
# frozen.
C.z += 1
self.assertEqual(c.z, 1001)
c = C(20)