-
Notifications
You must be signed in to change notification settings - Fork 140
Expand file tree
/
Copy pathtest_struct.py
More file actions
2746 lines (2073 loc) · 73.4 KB
/
test_struct.py
File metadata and controls
2746 lines (2073 loc) · 73.4 KB
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
import copy
import datetime
import enum
import gc
import operator
import pickle
import sys
import weakref
from contextlib import contextmanager
from inspect import Parameter, Signature
from typing import Any, Generic, List, Optional, TypeVar
import pytest
import msgspec
from msgspec import NODEFAULT, UNSET, Struct, defstruct, field
from msgspec.structs import StructConfig
from .utils import temp_module
if hasattr(copy, "replace"):
# Added in Python 3.13
copy_replace = copy.replace
else:
def copy_replace(s, **changes):
return s.__replace__(**changes)
@contextmanager
def nogc():
"""Temporarily disable GC"""
try:
gc.disable()
yield
finally:
gc.enable()
class Fruit(enum.IntEnum):
APPLE = 1
BANANA = 2
def as_tuple(x):
return tuple(getattr(x, f) for f in x.__struct_fields__)
@pytest.mark.parametrize("obj, str_obj", [(UNSET, "UNSET"), (NODEFAULT, "NODEFAULT")])
def test_singletons(obj, str_obj):
assert str(obj) == str_obj
assert pickle.loads(pickle.dumps(obj)) is obj
cls = type(obj)
assert cls() is obj
with pytest.raises(TypeError):
cls(1)
with pytest.raises(TypeError):
cls(foo=1)
if obj is UNSET:
assert bool(obj) is False
else:
assert bool(obj) is True
def test_field():
f1 = msgspec.field()
assert f1.default is NODEFAULT
assert f1.default_factory is NODEFAULT
assert f1.name is None
f2 = msgspec.field(default=1)
assert f2.default == 1
assert f2.default_factory is NODEFAULT
assert f2.name is None
f3 = msgspec.field(default_factory=int)
assert f3.default is NODEFAULT
assert f3.default_factory is int
assert f3.name is None
f4 = msgspec.field(name="foo")
assert f4.name == "foo"
f5 = msgspec.field(name=None)
assert f5.name is None
with pytest.raises(TypeError, match="Cannot set both"):
msgspec.field(default=1, default_factory=int)
with pytest.raises(TypeError, match="must be callable"):
msgspec.field(default_factory=1)
with pytest.raises(TypeError, match="must be a str or None"):
msgspec.field(name=b"bad")
def test_struct_class_attributes():
assert Struct.__struct_fields__ == ()
assert Struct.__struct_encode_fields__ == ()
assert Struct.__struct_defaults__ == ()
assert Struct.__match_args__ == ()
assert Struct.__slots__ == ()
assert Struct.__module__ == "msgspec"
assert isinstance(Struct.__struct_config__, StructConfig)
def test_struct_class_and_instance_dir():
expected = {"__struct_fields__", "__struct_config__"}
assert expected.issubset(dir(Struct))
assert expected.issubset(dir(Struct()))
def test_struct_instance_attributes():
class Test(Struct):
c: int
b: float
a: str = "hello"
x = Test(1, 2.0, a="goodbye")
assert x.__struct_fields__ == ("c", "b", "a")
assert x.__struct_encode_fields__ == ("c", "b", "a")
assert x.__struct_fields__ is x.__struct_encode_fields__
assert x.__struct_defaults__ == ("hello",)
assert x.__slots__ == ("a", "b", "c")
assert isinstance(x.__struct_config__, StructConfig)
assert x.c == 1
assert x.b == 2.0
assert x.a == "goodbye"
def test_struct_subclass_forbids_init_new_slots():
with pytest.raises(TypeError, match="__init__"):
class Test1(Struct):
a: int
def __init__(self, a):
pass
with pytest.raises(TypeError, match="__new__"):
class Test2(Struct):
a: int
def __new__(self, a):
pass
with pytest.raises(TypeError, match="__slots__"):
class Test3(Struct):
__slots__ = ("a",)
a: int
def test_struct_subclass_forbidden_field_names():
with pytest.raises(
TypeError, match="Cannot have a struct field named '__weakref__'"
):
class Test1(Struct):
__weakref__: int
with pytest.raises(TypeError, match="Cannot have a struct field named '__dict__'"):
class Test2(Struct):
__dict__: int
with pytest.raises(
TypeError, match="Cannot have a struct field named '__msgspec_cached_hash__'"
):
class Test3(Struct):
__msgspec_cached_hash__: int
class TestMixins:
def test_mixin_no_slots(self):
class Mixin(object):
def method(self):
pass
class Test1(Struct, Mixin):
pass
assert issubclass(Test1, Mixin)
assert Test1.__dictoffset__ != 0
assert Test1.__weakrefoffset__ != 0
class Test2(Struct, Mixin, dict=True, weakref=True):
pass
assert Test2.__dictoffset__ != 0
assert Test2.__weakrefoffset__ != 0
def test_mixin_slots(self):
class Mixin(object):
__slots__ = ()
def method(self):
pass
class Test1(Struct, Mixin):
pass
assert issubclass(Test1, Mixin)
assert Test1.__dictoffset__ == 0
assert Test1.__weakrefoffset__ == 0
class Test2(Struct, Mixin, dict=True, weakref=True):
pass
assert Test2.__dictoffset__ != 0
assert Test2.__weakrefoffset__ != 0
def test_mixin_nonempty_slots(self):
class Mixin(object):
__slots__ = "_state"
def method(self):
try:
return self._state
except AttributeError:
self._state = self.x + 1
return self._state
class Test(Struct, Mixin):
x: int
assert Test.__dictoffset__ == 0
t = Test(1)
assert t.method() == 2
assert t.method() == 2
def test_mixin_forbids_init(self):
class Mixin(object):
def __init__(self):
pass
with pytest.raises(TypeError, match="cannot define __init__"):
class Test(Struct, Mixin):
pass
def test_mixin_forbids_new(self):
class Mixin(object):
def __new__(self):
pass
with pytest.raises(TypeError, match="cannot define __new__"):
class Test(Struct, Mixin):
pass
def test_mixin_builtin_type_errors(self):
with pytest.raises(TypeError):
class Test(Struct, Exception):
pass
def test_struct_subclass_forbids_non_types():
# Currently this failcase is handled by CPython's internals, but it's good
# to make sure this user error actually errors.
class Foo:
pass
with pytest.raises(TypeError):
class Test(msgspec.Struct, Foo()):
pass
def test_struct_subclass_forbids_mixed_layouts():
class A(Struct):
a: int
b: int
class B(Struct):
c: int
d: int
# This error is raised by cpython
with pytest.raises(TypeError, match="lay-out conflict"):
class C(A, B):
pass
def test_struct_errors_nicely_if_used_in_init_subclass():
ran = False
class Test(Struct):
def __init_subclass__(cls):
# Class attributes aren't yet defined, error nicely
for attr in [
"__struct_fields__",
"__struct_encode_fields__",
"__match_args__",
"__struct_defaults__",
]:
with pytest.raises(AttributeError):
getattr(cls, attr)
# Init doesn't work
with pytest.raises(Exception):
cls()
# Decoder/decode doesn't work
for proto in [msgspec.json, msgspec.msgpack]:
with pytest.raises(ValueError, match="isn't fully defined"):
proto.Decoder(cls)
with pytest.raises(ValueError, match="isn't fully defined"):
proto.decode(b"", type=cls)
nonlocal ran
ran = True
class Subclass(Test):
x: int
assert ran
class TestStructParameterOrdering:
"""Tests for parsing parameter types & defaults from one or more class
definitions."""
def test_no_args(self):
class Test(Struct):
pass
assert Test.__struct_fields__ == ()
assert Test.__struct_defaults__ == ()
assert Test.__match_args__ == ()
assert Test.__slots__ == ()
def test_all_positional(self):
class Test(Struct):
y: float
x: int
assert Test.__struct_fields__ == ("y", "x")
assert Test.__struct_defaults__ == ()
assert Test.__match_args__ == ("y", "x")
assert Test.__slots__ == ("x", "y")
def test_all_positional_with_defaults(self):
class Test(Struct):
y: int = 1
x: float = 2.0
assert Test.__struct_fields__ == ("y", "x")
assert Test.__struct_defaults__ == (1, 2.0)
assert Test.__match_args__ == ("y", "x")
assert Test.__slots__ == ("x", "y")
def test_subclass_no_change(self):
class Test(Struct):
y: float
x: int
class Test2(Test):
pass
assert Test2.__struct_fields__ == ("y", "x")
assert Test2.__struct_defaults__ == ()
assert Test2.__match_args__ == ("y", "x")
assert Test2.__slots__ == ()
def test_subclass_extends(self):
class Test(Struct):
c: int
b: float
d: int = 1
a: float = 2.0
class Test2(Test):
e: str = "3.0"
f: float = 4.0
assert Test2.__struct_fields__ == ("c", "b", "d", "a", "e", "f")
assert Test2.__struct_defaults__ == (1, 2.0, "3.0", 4.0)
assert Test2.__match_args__ == ("c", "b", "d", "a", "e", "f")
assert Test2.__slots__ == ("e", "f")
def test_subclass_overrides(self):
class Test(Struct):
c: int
b: int
d: int = 1
a: float = 2.0
class Test2(Test):
b: float = 3 # switch to keyword, change type
d: int = 4 # change default
e: float = 5.0 # new
assert Test2.__struct_fields__ == ("c", "b", "d", "a", "e")
assert Test2.__struct_defaults__ == (3, 4, 2.0, 5.0)
assert Test2.__match_args__ == ("c", "b", "d", "a", "e")
assert Test2.__slots__ == ("e",)
def test_subclass_with_mixin(self):
class A(Struct):
b: int
a: float = 1.0
class Mixin(Struct):
pass
class B(A, Mixin):
a: float = 2.0
assert B.__struct_fields__ == ("b", "a")
assert B.__struct_defaults__ == (2.0,)
assert B.__match_args__ == ("b", "a")
assert B.__slots__ == ()
def test_positional_after_keyword_errors(self):
with pytest.raises(TypeError) as rec:
class Test(Struct):
a: int
b: int = 1
c: float
assert "Required field 'c' cannot follow optional fields" in str(rec.value)
def test_positional_after_keyword_subclass_errors(self):
class Base(Struct):
a: int
b: int = 1
with pytest.raises(TypeError) as rec:
class Test(Base):
c: float
assert "Required field 'c' cannot follow optional fields" in str(rec.value)
def test_kw_only_positional(self):
class Test(Struct, kw_only=True):
b: int
a: int
assert Test.__struct_fields__ == ("b", "a")
assert Test.__struct_defaults__ == ()
assert Test.__match_args__ == ()
assert Test.__slots__ == ("a", "b")
def test_kw_only_mixed(self):
class Test(Struct, kw_only=True):
b: int
a: int = 0
c: int
d: int = 1
assert Test.__struct_fields__ == ("b", "a", "c", "d")
assert Test.__struct_defaults__ == (0, NODEFAULT, 1)
assert Test.__match_args__ == ()
assert Test.__slots__ == ("a", "b", "c", "d")
def test_kw_only_positional_base_class(self):
class Base(Struct, kw_only=True):
b: int
a: int
class S1(Base):
d: int
c: int
class S2(Base):
d: int
c: int = 1
assert S1.__struct_fields__ == ("d", "c", "b", "a")
assert S1.__struct_defaults__ == ()
assert S1.__match_args__ == ("d", "c")
assert S1.__slots__ == ("c", "d")
assert S2.__struct_fields__ == ("d", "c", "b", "a")
assert S2.__struct_defaults__ == (1, NODEFAULT, NODEFAULT)
assert S2.__match_args__ == ("d", "c")
assert S2.__slots__ == ("c", "d")
def test_kw_only_base_class(self):
class Base(Struct, kw_only=True):
b: int = 1
a: int
class S1(Base):
d: int
c: int = 2
assert S1.__struct_fields__ == ("d", "c", "b", "a")
assert S1.__struct_defaults__ == (2, 1, NODEFAULT)
assert S1.__match_args__ == ("d", "c")
assert S1.__slots__ == ("c", "d")
def test_kw_only_subclass(self):
class Base(Struct):
b: int
a: int
class S1(Base, kw_only=True):
d: int
c: int
assert S1.__struct_fields__ == ("b", "a", "d", "c")
assert S1.__struct_defaults__ == ()
assert S1.__match_args__ == ("b", "a")
assert S1.__slots__ == ("c", "d")
def test_kw_only_defaults_subclass(self):
class Base(Struct):
b: int
a: int = 0
class S1(Base, kw_only=True):
d: int
c: int = 1
assert S1.__struct_fields__ == ("b", "a", "d", "c")
assert S1.__struct_defaults__ == (0, NODEFAULT, 1)
assert S1.__match_args__ == ("b", "a")
assert S1.__slots__ == ("c", "d")
def test_kw_only_overrides(self):
class Base(Struct):
b: int
a: int = 2
class S1(Base, kw_only=True):
b: int
c: int = 3
assert S1.__struct_fields__ == ("a", "b", "c")
assert S1.__struct_defaults__ == (2, NODEFAULT, 3)
assert S1.__match_args__ == ("a",)
assert S1.__slots__ == ("c",)
def test_kw_only_overridden(self):
class Base(Struct, kw_only=True):
b: int
a: int = 2
class S1(Base):
b: int
c: int = 3
assert S1.__struct_fields__ == ("b", "c", "a")
assert S1.__struct_defaults__ == (3, 2)
assert S1.__match_args__ == ("b", "c")
assert S1.__slots__ == ("c",)
class TestStructInit:
def test_init_positional(self):
class Test(Struct):
a: int
b: float
c: int = 3
d: float = 4.0
assert as_tuple(Test(1, 2.0)) == (1, 2.0, 3, 4.0)
assert as_tuple(Test(1, b=2.0)) == (1, 2.0, 3, 4.0)
assert as_tuple(Test(a=1, b=2.0)) == (1, 2.0, 3, 4.0)
assert as_tuple(Test(1, b=2.0, c=5)) == (1, 2.0, 5, 4.0)
assert as_tuple(Test(1, b=2.0, d=5.0)) == (1, 2.0, 3, 5.0)
assert as_tuple(Test(1, 2.0, 5)) == (1, 2.0, 5, 4.0)
assert as_tuple(Test(1, 2.0, 5, 6.0)) == (1, 2.0, 5, 6.0)
with pytest.raises(TypeError, match="Missing required argument 'a'"):
Test()
with pytest.raises(TypeError, match="Missing required argument 'b'"):
Test(1)
with pytest.raises(TypeError, match="Extra positional arguments provided"):
Test(1, 2, 3, 4, 5)
with pytest.raises(TypeError, match="Argument 'a' given by name and position"):
Test(1, 2, a=3)
with pytest.raises(TypeError, match="Unexpected keyword argument 'e'"):
Test(1, 2, e=5)
def test_init_kw_only(self):
class Test(Struct, kw_only=True):
a: int
b: float = 2.0
c: int = 3
assert as_tuple(Test(a=1)) == (1, 2.0, 3)
assert as_tuple(Test(a=1, b=4.0)) == (1, 4.0, 3)
assert as_tuple(Test(a=1, c=4)) == (1, 2.0, 4)
assert as_tuple(Test(a=1, b=4.0, c=5)) == (1, 4.0, 5)
with pytest.raises(TypeError, match="Missing required argument 'a'"):
Test()
with pytest.raises(TypeError, match="Extra positional arguments provided"):
Test(1)
with pytest.raises(TypeError, match="Unexpected keyword argument 'e'"):
Test(a=1, e=5)
def test_init_kw_only_mixed(self):
class Base(Struct, kw_only=True):
c: int = 3
d: float = 4.0
class Test(Base):
a: int
b: float = 2.0
assert as_tuple(Test(1)) == (1, 2.0, 3, 4.0)
assert as_tuple(Test(1, 5.0)) == (1, 5.0, 3, 4.0)
assert as_tuple(Test(a=1)) == (1, 2.0, 3, 4.0)
assert as_tuple(Test(a=1, b=5.0)) == (1, 5.0, 3, 4.0)
assert as_tuple(Test(1, c=5)) == (1, 2.0, 5, 4.0)
with pytest.raises(TypeError, match="Missing required argument 'a'"):
Test()
with pytest.raises(TypeError, match="Argument 'a' given by name and position"):
Test(1, b=3.0, c=4, a=3)
with pytest.raises(TypeError, match="Extra positional arguments provided"):
Test(1, 5.0, 3)
with pytest.raises(TypeError, match="Unexpected keyword argument 'e'"):
Test(1, e=5)
class TestSignature:
def test_signature_no_args(self):
class Test(Struct):
pass
sig = Signature(parameters=[])
assert Test.__signature__ == sig
def test_signature_positional(self):
class Test(Struct):
b: float
a: int = 1
sig = Signature(
parameters=[
Parameter("b", Parameter.POSITIONAL_OR_KEYWORD, annotation=float),
Parameter(
"a",
Parameter.POSITIONAL_OR_KEYWORD,
default=1,
annotation=int,
),
]
)
assert Test.__signature__ == sig
def test_signature_kw_only(self):
class Base(Struct, kw_only=True):
c: float
d: int = 2
class Test(Base):
b: float
a: int = 1
sig = Signature(
parameters=[
Parameter("b", Parameter.POSITIONAL_OR_KEYWORD, annotation=float),
Parameter(
"a",
Parameter.POSITIONAL_OR_KEYWORD,
default=1,
annotation=int,
),
Parameter("c", Parameter.KEYWORD_ONLY, annotation=float),
Parameter("d", Parameter.KEYWORD_ONLY, default=2, annotation=int),
]
)
assert Test.__signature__ == sig
class TestRepr:
def test_repr_base(self):
x = Struct()
assert repr(x) == "Struct()"
assert x.__rich_repr__() == []
def test_repr_empty(self):
class Test(Struct):
pass
x = Test()
assert repr(x) == "Test()"
assert x.__rich_repr__() == []
def test_repr_one_field(self):
class Test(Struct):
a: int
x = Test(1)
assert repr(x) == "Test(a=1)"
assert x.__rich_repr__() == [("a", 1)]
def test_repr_two_fields(self):
class Test(Struct):
a: int
b: str
x = Test(1, "y")
assert repr(x) == "Test(a=1, b='y')"
assert x.__rich_repr__() == [("a", 1), ("b", "y")]
def test_repr_omit_defaults_empty(self):
class Test(Struct, repr_omit_defaults=True):
pass
x = Test()
assert repr(x) == "Test()"
assert x.__rich_repr__() == []
def test_repr_omit_defaults_one_field(self):
class Test(Struct, repr_omit_defaults=True):
a: int = 0
x = Test(0)
assert repr(x) == "Test()"
assert x.__rich_repr__() == []
x = Test(1)
assert repr(x) == "Test(a=1)"
assert x.__rich_repr__() == [("a", 1)]
def test_repr_omit_defaults_multiple_fields(self):
class Test(Struct, repr_omit_defaults=True):
a: int
b: int = 0
c: str = ""
x = Test(0)
assert repr(x) == "Test(a=0)"
assert x.__rich_repr__() == [("a", 0)]
x = Test(0, b=1)
assert repr(x) == "Test(a=0, b=1)"
assert x.__rich_repr__() == [("a", 0), ("b", 1)]
x = Test(0, c="two")
assert repr(x) == "Test(a=0, c='two')"
assert x.__rich_repr__() == [("a", 0), ("c", "two")]
x = Test(0, b=1, c="two")
assert repr(x) == "Test(a=0, b=1, c='two')"
assert x.__rich_repr__() == [("a", 0), ("b", 1), ("c", "two")]
def test_repr_recursive(self):
class Test(Struct):
a: int
b: Any
t = Test(1, Test(2, None))
t.b.b = t
assert repr(t) == "Test(a=1, b=Test(a=2, b=...))"
def test_repr_missing_attr_errors(self):
class Test(Struct):
a: int
b: str
t = Test(1, "hello")
del t.b
with pytest.raises(AttributeError):
repr(t)
with pytest.raises(AttributeError):
t.__rich_repr__()
def test_repr_errors(self):
msg = "Oh no!"
class Bad:
def __repr__(self):
raise ValueError(msg)
class Test(Struct):
a: object
b: object
t = Test(1, Bad())
with pytest.raises(ValueError, match=msg):
repr(t)
def test_struct_copy():
x = copy.copy(Struct())
assert type(x) is Struct
class Test(Struct):
b: int
a: int
o = Test(1, 2)
x = copy.copy(o)
assert type(x) is Test
assert x is not o
assert x.b == 1
assert x.a == 2
def test_struct_deepcopy():
o = Struct()
x = copy.deepcopy(Struct())
assert type(x) is Struct
assert x is not o
class Sub(Struct):
one: str
two: list[int]
class Test(Struct):
a: int
b: int
c: list[str]
sub: Sub
o = Test(
a=1,
b=2,
c=["1", "2"],
sub=Sub(one="hello", two=[3]),
)
x = copy.deepcopy(o)
assert type(x) is Test
assert x.a == 1
assert x.b == 2
assert x.c == ["1", "2"]
assert x.c is not o.c
assert x.sub is not o.sub
assert x.sub.one == "hello"
assert x.sub.two == [3]
assert x.sub.two is not o.sub.two
def test_struct_deepcopy_custom_impl():
# ensure we respect custom __deepcopy__ methods
class CustomThing:
def __init__(self, value):
self.value = value
def __deepcopy__(self, memo):
return CustomThing(value=self.value + 1)
class TestWithCustom(Struct):
custom: CustomThing
t = TestWithCustom(CustomThing(1))
tc = copy.deepcopy(t)
assert tc.custom.value == 2
class FrozenPoint(Struct, frozen=True):
x: int
y: int
@pytest.mark.parametrize(
"default",
[
None,
False,
True,
1,
2.0,
1.5 + 2.32j,
b"test",
"test",
(),
frozenset(),
frozenset((1, (2, 3, 4), 5)),
Fruit.APPLE,
datetime.time(1),
datetime.date.today(),
datetime.timedelta(seconds=2),
datetime.datetime.now(),
FrozenPoint(1, 2),
],
)
def test_struct_immutable_defaults_use_instance(default):
class Test(Struct):
value: object = default
t = Test()
assert t.value is default
@pytest.mark.parametrize("default", [[], {}, set()])
def test_struct_empty_mutable_defaults_fast_copy(default):
class Test(Struct):
value: object = default
t = Test()
assert t.value == default
assert t.value is not default
class Point(Struct):
x: int
y: int
class PointKWOnly(Struct, kw_only=True):
x: int
y: int
@pytest.mark.parametrize("default", [[], {}, set(), bytearray()])
def test_struct_empty_mutable_defaults_work(default):
class Test(Struct):
value: object = default
x = Test().value
x == default
assert x is not default
@pytest.mark.parametrize(
"default",
[Point(1, 2), [1], {"a": "b"}, {1, 2}, bytearray(b"test")],
)
def test_struct_nonempty_mutable_defaults_error(default):
with pytest.raises(TypeError) as rec:
class Test(Struct):
value: object = default
assert "as a default value is unsafe" in str(rec.value)
assert repr(default) in str(rec.value)
def test_struct_defaults_from_field():
default = []
class Test(Struct):
req: int = field()
x: int = field(default=1)
y: int = field(default_factory=lambda: 2)
z: List[int] = field(default=default)
t = Test(100)
assert t.req == 100
assert t.x == 1
assert t.y == 2
assert t.z == []
assert t.z is not default
def test_struct_default_factory_errors():
def bad():
raise ValueError("Oh no")
class Test(Struct):
x: int = field(default_factory=bad)
with pytest.raises(ValueError):
Test()
def test_struct_reference_counting():
"""Test that struct operations that access fields properly decref"""
class Test(Struct):
value: list
data = [1, 2, 3]
t = Test(data)
assert sys.getrefcount(data) <= 3
repr(t)
assert sys.getrefcount(data) <= 3
t2 = t.__copy__()
assert sys.getrefcount(data) <= 4
assert t == t2
assert sys.getrefcount(data) <= 4
def test_struct_gc_not_added_if_not_needed():