This repository was archived by the owner on Jun 27, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtest_struct.py
673 lines (514 loc) · 16.1 KB
/
test_struct.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
import enum
import copy
import datetime
import gc
import inspect
import pickle
import sys
import pytest
import quickle
from quickle import Struct, PickleBuffer
class Fruit(enum.IntEnum):
APPLE = 1
BANANA = 2
def as_tuple(x):
return tuple(getattr(x, f) for f in x.__struct_fields__)
def test_struct_class_attributes():
assert Struct.__struct_fields__ == ()
assert Struct.__struct_defaults__ == ()
assert Struct.__slots__ == ()
assert Struct.__module__ == "quickle"
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_defaults__ == ("hello",)
assert x.__slots__ == ("a", "b", "c")
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_forbids_non_struct_bases():
class Mixin(object):
def method(self):
pass
with pytest.raises(TypeError, match="All base classes must be"):
class Test(Struct, Mixin):
a: int
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_structmeta_no_args():
class Test(Struct):
pass
assert Test.__struct_fields__ == ()
assert Test.__struct_defaults__ == ()
assert Test.__slots__ == ()
sig = inspect.Signature(parameters=[])
assert Test.__signature__ == sig
def test_structmeta_positional_only():
class Test(Struct):
y: float
x: int
assert Test.__struct_fields__ == ("y", "x")
assert Test.__struct_defaults__ == ()
assert Test.__slots__ == ("x", "y")
sig = inspect.Signature(
parameters=[
inspect.Parameter(
"y", inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=float
),
inspect.Parameter(
"x", inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=int
),
]
)
assert Test.__signature__ == sig
def test_structmeta_positional_and_keyword():
class Test(Struct):
c: int
d: int = 1
b: float
a: float = 2.0
assert Test.__struct_fields__ == ("c", "b", "d", "a")
assert Test.__struct_defaults__ == (1, 2.0)
assert Test.__slots__ == ("a", "b", "c", "d")
sig = inspect.Signature(
parameters=[
inspect.Parameter(
"c", inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=int
),
inspect.Parameter(
"b", inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=float
),
inspect.Parameter(
"d", inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=int, default=1
),
inspect.Parameter(
"a",
inspect.Parameter.POSITIONAL_OR_KEYWORD,
annotation=float,
default=2.0,
),
]
)
assert Test.__signature__ == sig
def test_structmeta_keyword_only():
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.__slots__ == ("x", "y")
sig = inspect.Signature(
parameters=[
inspect.Parameter(
"y", inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=int, default=1
),
inspect.Parameter(
"x",
inspect.Parameter.POSITIONAL_OR_KEYWORD,
annotation=float,
default=2.0,
),
]
)
assert Test.__signature__ == sig
def test_structmeta_subclass_no_change():
class Test(Struct):
y: float
x: int
class Test2(Test):
pass
assert Test2.__struct_fields__ == ("y", "x")
assert Test2.__struct_defaults__ == ()
assert Test2.__slots__ == ()
sig = inspect.Signature(
parameters=[
inspect.Parameter(
"y", inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=float
),
inspect.Parameter(
"x", inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=int
),
]
)
assert Test2.__signature__ == sig
assert as_tuple(Test2(1, 2)) == (1, 2)
assert as_tuple(Test2(y=1, x=2)) == (1, 2)
def test_structmeta_subclass_extends():
class Test(Struct):
c: int
d: int = 1
b: float
a: float = 2.0
class Test2(Test):
e: str
f: float = 3.0
assert Test2.__struct_fields__ == ("c", "b", "e", "d", "a", "f")
assert Test2.__struct_defaults__ == (1, 2.0, 3.0)
assert Test2.__slots__ == ("e", "f")
sig = inspect.Signature(
parameters=[
inspect.Parameter(
"c", inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=int
),
inspect.Parameter(
"b", inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=float
),
inspect.Parameter(
"e", inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=str
),
inspect.Parameter(
"d", inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=int, default=1
),
inspect.Parameter(
"a",
inspect.Parameter.POSITIONAL_OR_KEYWORD,
annotation=float,
default=2.0,
),
inspect.Parameter(
"f",
inspect.Parameter.POSITIONAL_OR_KEYWORD,
annotation=float,
default=3.0,
),
]
)
assert Test2.__signature__ == sig
assert as_tuple(Test2(1, 2, 3, 4, 5, 6)) == (1, 2, 3, 4, 5, 6)
assert as_tuple(Test2(4, 5, 6)) == (4, 5, 6, 1, 2.0, 3.0)
def test_structmeta_subclass_overrides():
class Test(Struct):
c: int
d: int = 1
b: float
a: float = 2.0
class Test2(Test):
d: int = 2 # change default
c: int = 3 # switch to keyword
a: float # switch to positional
assert Test2.__struct_fields__ == ("b", "a", "d", "c")
assert Test2.__struct_defaults__ == (2, 3)
assert Test2.__slots__ == ()
sig = inspect.Signature(
parameters=[
inspect.Parameter(
"b", inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=float
),
inspect.Parameter(
"a", inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=float
),
inspect.Parameter(
"d", inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=int, default=2
),
inspect.Parameter(
"c", inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=int, default=3
),
]
)
assert Test2.__signature__ == sig
assert as_tuple(Test2(1, 2, 3, 4)) == (1, 2, 3, 4)
assert as_tuple(Test2(4, 5)) == (4, 5, 2, 3)
def test_structmeta_subclass_mixin_struct_base():
class A(Struct):
b: int
a: float = 1.0
class Mixin(Struct):
def as_dict(self):
return {f: getattr(self, f) for f in self.__struct_fields__}
class B(A, Mixin):
a: float = 2.0
assert B.__struct_fields__ == ("b", "a")
assert B.__struct_defaults__ == (2.0,)
assert B.__slots__ == ()
sig = inspect.Signature(
parameters=[
inspect.Parameter(
"b", inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=int
),
inspect.Parameter(
"a",
inspect.Parameter.POSITIONAL_OR_KEYWORD,
annotation=float,
default=2.0,
),
]
)
assert B.__signature__ == sig
b = B(1)
assert b.as_dict() == {"b": 1, "a": 2.0}
def test_struct_init():
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="Extra keyword arguments provided"):
Test(1, 2, e=5)
def test_struct_repr():
assert repr(Struct()) == "Struct()"
class Test(Struct):
pass
assert repr(Test()) == "Test()"
class Test(Struct):
a: int
b: str
assert repr(Test(1, "hello")) == "Test(a=1, b='hello')"
def test_struct_repr_errors():
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
x = copy.copy(Test(1, 2))
assert type(x) is Test
assert x.b == 1
assert x.a == 2
def test_struct_compare():
def assert_eq(a, b):
assert a == b
assert not a != b
def assert_neq(a, b):
assert a != b
assert not a == b
class Test(Struct):
a: int
b: int
class Test2(Test):
pass
x = Struct()
assert_eq(x, Struct())
assert_neq(x, None)
x = Test(1, 2)
assert_eq(x, Test(1, 2))
assert_neq(x, None)
assert_neq(x, Test(1, 3))
assert_neq(x, Test(2, 2))
assert_neq(x, Test2(1, 2))
def test_struct_compare_errors():
msg = "Oh no!"
class Bad:
def __eq__(self, other):
raise ValueError(msg)
__ne__ = __eq__
class Test(Struct):
a: object
b: object
t = Test(1, Bad())
t2 = Test(1, 2)
with pytest.raises(ValueError, match=msg):
t == t2
with pytest.raises(ValueError, match=msg):
t != t2
with pytest.raises(ValueError, match=msg):
t2 == t
with pytest.raises(ValueError, match=msg):
t2 != t
@pytest.mark.parametrize(
"default",
[
None,
False,
True,
1,
2.0,
1.5 + 2.32j,
b"test",
"test",
bytearray(b"test"),
PickleBuffer(b"test"),
(),
frozenset(),
Fruit.APPLE,
datetime.time(1),
datetime.date.today(),
datetime.timedelta(seconds=2),
datetime.datetime.now(),
],
)
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
@pytest.mark.parametrize(
"default",
[
(Point(1, 2),),
[Point(1, 2)],
{frozenset("a"): None},
set([frozenset("a")]),
frozenset([frozenset("a")]),
],
)
def test_struct_mutable_defaults_deep_copy(default):
class Test(Struct):
value: object = default
t = Test()
assert t.value == default
assert t.value is not default
for x, y in zip(t.value, default):
assert x == y
assert x is not y
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
quickle.dumps(t, registry=[Test])
assert sys.getrefcount(data) == 4
def test_struct_gc_not_added_if_not_needed():
"""Structs aren't tracked by GC until/unless they reference a container type"""
class Test(Struct):
x: object
y: object
assert not gc.is_tracked(Test(1, 2))
assert not gc.is_tracked(Test("hello", "world"))
assert gc.is_tracked(Test([1, 2, 3], 1))
assert gc.is_tracked(Test(1, [1, 2, 3]))
# Tuples are all tracked on creation, but through GC passes eventually
# become untracked if they don't contain tracked types
untracked_tuple = (1, 2, 3)
for i in range(5):
gc.collect()
if not gc.is_tracked(untracked_tuple):
break
else:
assert False, "something has changed with Python's GC, investigate"
assert not gc.is_tracked(Test(1, untracked_tuple))
tracked_tuple = ([],)
assert gc.is_tracked(Test(1, tracked_tuple))
# On mutation, if a tracked objected is stored on a struct, an untracked
# struct will become tracked
t = Test(1, 2)
assert not gc.is_tracked(t)
t.x = 3
assert not gc.is_tracked(t)
t.x = untracked_tuple
assert not gc.is_tracked(t)
t.x = []
assert gc.is_tracked(t)
# An error in setattr doesn't change tracked status
t = Test(1, 2)
assert not gc.is_tracked(t)
with pytest.raises(AttributeError):
t.z = []
assert not gc.is_tracked(t)
def test_struct_gc_set_on_unpickle():
"""Unpickling doesn't go through the struct constructor"""
class Test(quickle.Struct):
x: object
y: object
ts = [Test(1, 2), Test(3, "hello"), Test([], ()), Test((), ())]
a, b, c, d = quickle.loads(quickle.dumps(ts, registry=[Test]), registry=[Test])
assert not gc.is_tracked(a)
assert not gc.is_tracked(b)
assert gc.is_tracked(c)
assert not gc.is_tracked(d)
def test_struct_gc_set_on_copy():
"""Copying doesn't go through the struct constructor"""
class Test(quickle.Struct):
x: object
y: object
assert not gc.is_tracked(copy.copy(Test(1, 2)))
assert not gc.is_tracked(copy.copy(Test(1, ())))
assert gc.is_tracked(copy.copy(Test(1, [])))
class MyStruct(Struct):
x: int
y: int
z: str = "default"
def test_structs_are_pickleable():
"""While designed for use with quickle, they should still work with pickle"""
t = MyStruct(1, 2, "hello")
t2 = MyStruct(3, 4)
assert pickle.loads(pickle.dumps(t)) == t
assert pickle.loads(pickle.dumps(t2)) == t2
def test_struct_handles_missing_attributes():
"""If an attribute is unset, raise an AttributeError appropriately"""
t = MyStruct(1, 2)
del t.y
t2 = MyStruct(1, 2)
match = "Struct field 'y' is unset"
with pytest.raises(AttributeError, match=match):
repr(t)
with pytest.raises(AttributeError, match=match):
copy.copy(t)
with pytest.raises(AttributeError, match=match):
t == t2
with pytest.raises(AttributeError, match=match):
t2 == t
with pytest.raises(AttributeError, match=match):
pickle.dumps(t)
with pytest.raises(AttributeError, match=match):
quickle.dumps(t, registry=[MyStruct])