-
-
Notifications
You must be signed in to change notification settings - Fork 34.4k
Expand file tree
/
Copy pathtest_context.py
More file actions
1551 lines (1210 loc) · 44.9 KB
/
test_context.py
File metadata and controls
1551 lines (1210 loc) · 44.9 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 sys
import collections.abc
import concurrent.futures
import contextvars
import functools
import gc
import random
import time
import unittest
import weakref
from test import support
from test.support import threading_helper
try:
from _testinternalcapi import hamt
except ImportError:
hamt = None
def isolated_context(func):
"""Needed to make reftracking test mode work."""
@functools.wraps(func)
def wrapper(*args, **kwargs):
ctx = contextvars.Context()
return ctx.run(func, *args, **kwargs)
return wrapper
class ContextTest(unittest.TestCase):
def test_context_var_new_1(self):
with self.assertRaisesRegex(TypeError, 'takes exactly 1'):
contextvars.ContextVar()
with self.assertRaisesRegex(TypeError, 'must be a str'):
contextvars.ContextVar(1)
c = contextvars.ContextVar('aaa')
self.assertEqual(c.name, 'aaa')
with self.assertRaises(AttributeError):
c.name = 'bbb'
self.assertNotEqual(hash(c), hash('aaa'))
@isolated_context
def test_context_var_repr_1(self):
c = contextvars.ContextVar('a')
self.assertIn('a', repr(c))
c = contextvars.ContextVar('a', default=123)
self.assertIn('123', repr(c))
lst = []
c = contextvars.ContextVar('a', default=lst)
lst.append(c)
self.assertIn('...', repr(c))
self.assertIn('...', repr(lst))
t = c.set(1)
self.assertIn(repr(c), repr(t))
self.assertNotIn(' used ', repr(t))
c.reset(t)
self.assertIn(' used ', repr(t))
@isolated_context
def test_token_repr_1(self):
c = contextvars.ContextVar('a')
tok = c.set(1)
self.assertRegex(repr(tok),
r"^<Token var=<ContextVar name='a' "
r"at 0x[0-9a-fA-F]+> at 0x[0-9a-fA-F]+>$")
def test_context_subclassing_1(self):
with self.assertRaisesRegex(TypeError, 'not an acceptable base type'):
class MyContextVar(contextvars.ContextVar):
# Potentially we might want ContextVars to be subclassable.
pass
with self.assertRaisesRegex(TypeError, 'not an acceptable base type'):
class MyContext(contextvars.Context):
pass
with self.assertRaisesRegex(TypeError, 'not an acceptable base type'):
class MyToken(contextvars.Token):
pass
def test_context_new_1(self):
with self.assertRaisesRegex(TypeError, 'any arguments'):
contextvars.Context(1)
with self.assertRaisesRegex(TypeError, 'any arguments'):
contextvars.Context(1, a=1)
with self.assertRaisesRegex(TypeError, 'any arguments'):
contextvars.Context(a=1)
contextvars.Context(**{})
def test_context_new_unhashable_str_subclass(self):
# gh-132002: it used to crash on unhashable str subtypes.
class weird_str(str):
def __eq__(self, other):
pass
with self.assertRaisesRegex(TypeError, 'unhashable type'):
contextvars.ContextVar(weird_str())
def test_context_typerrors_1(self):
ctx = contextvars.Context()
with self.assertRaisesRegex(TypeError, 'ContextVar key was expected'):
ctx[1]
with self.assertRaisesRegex(TypeError, 'ContextVar key was expected'):
1 in ctx
with self.assertRaisesRegex(TypeError, 'ContextVar key was expected'):
ctx.get(1)
def test_context_get_context_1(self):
ctx = contextvars.copy_context()
self.assertIsInstance(ctx, contextvars.Context)
def test_context_run_1(self):
ctx = contextvars.Context()
with self.assertRaisesRegex(TypeError, 'missing 1 required'):
ctx.run()
def test_context_run_2(self):
ctx = contextvars.Context()
def func(*args, **kwargs):
kwargs['spam'] = 'foo'
args += ('bar',)
return args, kwargs
for f in (func, functools.partial(func)):
# partial doesn't support FASTCALL
self.assertEqual(ctx.run(f), (('bar',), {'spam': 'foo'}))
self.assertEqual(ctx.run(f, 1), ((1, 'bar'), {'spam': 'foo'}))
self.assertEqual(
ctx.run(f, a=2),
(('bar',), {'a': 2, 'spam': 'foo'}))
self.assertEqual(
ctx.run(f, 11, a=2),
((11, 'bar'), {'a': 2, 'spam': 'foo'}))
a = {}
self.assertEqual(
ctx.run(f, 11, **a),
((11, 'bar'), {'spam': 'foo'}))
self.assertEqual(a, {})
def test_context_run_3(self):
ctx = contextvars.Context()
def func(*args, **kwargs):
1 / 0
with self.assertRaises(ZeroDivisionError):
ctx.run(func)
with self.assertRaises(ZeroDivisionError):
ctx.run(func, 1, 2)
with self.assertRaises(ZeroDivisionError):
ctx.run(func, 1, 2, a=123)
@isolated_context
def test_context_run_4(self):
ctx1 = contextvars.Context()
ctx2 = contextvars.Context()
var = contextvars.ContextVar('var')
def func2():
self.assertIsNone(var.get(None))
def func1():
self.assertIsNone(var.get(None))
var.set('spam')
ctx2.run(func2)
self.assertEqual(var.get(None), 'spam')
cur = contextvars.copy_context()
self.assertEqual(len(cur), 1)
self.assertEqual(cur[var], 'spam')
return cur
returned_ctx = ctx1.run(func1)
self.assertEqual(ctx1, returned_ctx)
self.assertEqual(returned_ctx[var], 'spam')
self.assertIn(var, returned_ctx)
def test_context_run_5(self):
ctx = contextvars.Context()
var = contextvars.ContextVar('var')
def func():
self.assertIsNone(var.get(None))
var.set('spam')
1 / 0
with self.assertRaises(ZeroDivisionError):
ctx.run(func)
self.assertIsNone(var.get(None))
def test_context_run_6(self):
ctx = contextvars.Context()
c = contextvars.ContextVar('a', default=0)
def fun():
self.assertEqual(c.get(), 0)
self.assertIsNone(ctx.get(c))
c.set(42)
self.assertEqual(c.get(), 42)
self.assertEqual(ctx.get(c), 42)
ctx.run(fun)
def test_context_run_7(self):
ctx = contextvars.Context()
def fun():
with self.assertRaisesRegex(RuntimeError, 'is already entered'):
ctx.run(fun)
ctx.run(fun)
@isolated_context
def test_context_getset_1(self):
c = contextvars.ContextVar('c')
with self.assertRaises(LookupError):
c.get()
self.assertIsNone(c.get(None))
t0 = c.set(42)
self.assertEqual(c.get(), 42)
self.assertEqual(c.get(None), 42)
self.assertIs(t0.old_value, t0.MISSING)
self.assertIs(t0.old_value, contextvars.Token.MISSING)
self.assertIs(t0.var, c)
t = c.set('spam')
self.assertEqual(c.get(), 'spam')
self.assertEqual(c.get(None), 'spam')
self.assertEqual(t.old_value, 42)
c.reset(t)
self.assertEqual(c.get(), 42)
self.assertEqual(c.get(None), 42)
c.set('spam2')
with self.assertRaisesRegex(RuntimeError, 'has already been used'):
c.reset(t)
self.assertEqual(c.get(), 'spam2')
ctx1 = contextvars.copy_context()
self.assertIn(c, ctx1)
c.reset(t0)
with self.assertRaisesRegex(RuntimeError, 'has already been used'):
c.reset(t0)
self.assertIsNone(c.get(None))
self.assertIn(c, ctx1)
self.assertEqual(ctx1[c], 'spam2')
self.assertEqual(ctx1.get(c, 'aa'), 'spam2')
self.assertEqual(len(ctx1), 1)
self.assertEqual(list(ctx1.items()), [(c, 'spam2')])
self.assertEqual(list(ctx1.values()), ['spam2'])
self.assertEqual(list(ctx1.keys()), [c])
self.assertEqual(list(ctx1), [c])
ctx2 = contextvars.copy_context()
self.assertNotIn(c, ctx2)
with self.assertRaises(KeyError):
ctx2[c]
self.assertEqual(ctx2.get(c, 'aa'), 'aa')
self.assertEqual(len(ctx2), 0)
self.assertEqual(list(ctx2), [])
@isolated_context
def test_context_getset_2(self):
v1 = contextvars.ContextVar('v1')
v2 = contextvars.ContextVar('v2')
t1 = v1.set(42)
with self.assertRaisesRegex(ValueError, 'by a different'):
v2.reset(t1)
@isolated_context
def test_context_getset_3(self):
c = contextvars.ContextVar('c', default=42)
ctx = contextvars.Context()
def fun():
self.assertEqual(c.get(), 42)
with self.assertRaises(KeyError):
ctx[c]
self.assertIsNone(ctx.get(c))
self.assertEqual(ctx.get(c, 'spam'), 'spam')
self.assertNotIn(c, ctx)
self.assertEqual(list(ctx.keys()), [])
t = c.set(1)
self.assertEqual(list(ctx.keys()), [c])
self.assertEqual(ctx[c], 1)
c.reset(t)
self.assertEqual(list(ctx.keys()), [])
with self.assertRaises(KeyError):
ctx[c]
ctx.run(fun)
@isolated_context
def test_context_getset_4(self):
c = contextvars.ContextVar('c', default=42)
ctx = contextvars.Context()
tok = ctx.run(c.set, 1)
with self.assertRaisesRegex(ValueError, 'different Context'):
c.reset(tok)
@isolated_context
def test_context_getset_5(self):
c = contextvars.ContextVar('c', default=42)
c.set([])
def fun():
c.set([])
c.get().append(42)
self.assertEqual(c.get(), [42])
contextvars.copy_context().run(fun)
self.assertEqual(c.get(), [])
def test_context_copy_1(self):
ctx1 = contextvars.Context()
c = contextvars.ContextVar('c', default=42)
def ctx1_fun():
c.set(10)
ctx2 = ctx1.copy()
self.assertEqual(ctx2[c], 10)
c.set(20)
self.assertEqual(ctx1[c], 20)
self.assertEqual(ctx2[c], 10)
ctx2.run(ctx2_fun)
self.assertEqual(ctx1[c], 20)
self.assertEqual(ctx2[c], 30)
def ctx2_fun():
self.assertEqual(c.get(), 10)
c.set(30)
self.assertEqual(c.get(), 30)
ctx1.run(ctx1_fun)
def test_context_isinstance(self):
ctx = contextvars.Context()
self.assertIsInstance(ctx, collections.abc.Mapping)
self.assertTrue(issubclass(contextvars.Context, collections.abc.Mapping))
mapping_methods = (
'__contains__', '__eq__', '__getitem__', '__iter__', '__len__',
'__ne__', 'get', 'items', 'keys', 'values',
)
for name in mapping_methods:
with self.subTest(name=name):
self.assertTrue(callable(getattr(ctx, name)))
@isolated_context
@threading_helper.requires_working_threading()
def test_context_threads_1(self):
cvar = contextvars.ContextVar('cvar')
def sub(num):
for i in range(10):
cvar.set(num + i)
time.sleep(random.uniform(0.001, 0.05))
self.assertEqual(cvar.get(), num + i)
return num
tp = concurrent.futures.ThreadPoolExecutor(max_workers=10)
try:
results = list(tp.map(sub, range(10)))
finally:
tp.shutdown()
self.assertEqual(results, list(range(10)))
@isolated_context
@threading_helper.requires_working_threading()
def test_context_thread_inherit(self):
import threading
cvar = contextvars.ContextVar('cvar')
def run_context_none():
if sys.flags.thread_inherit_context:
expected = 1
else:
expected = None
self.assertEqual(cvar.get(None), expected)
# By default, context is inherited based on the
# sys.flags.thread_inherit_context option.
cvar.set(1)
thread = threading.Thread(target=run_context_none)
thread.start()
thread.join()
# Passing 'None' explicitly should have same behaviour as not
# passing parameter.
thread = threading.Thread(target=run_context_none, context=None)
thread.start()
thread.join()
# An explicit Context value can also be passed
custom_ctx = contextvars.Context()
custom_var = None
def setup_context():
nonlocal custom_var
custom_var = contextvars.ContextVar('custom')
custom_var.set(2)
custom_ctx.run(setup_context)
def run_custom():
self.assertEqual(custom_var.get(), 2)
thread = threading.Thread(target=run_custom, context=custom_ctx)
thread.start()
thread.join()
# You can also pass a new Context() object to start with an empty context
def run_empty():
with self.assertRaises(LookupError):
cvar.get()
thread = threading.Thread(target=run_empty, context=contextvars.Context())
thread.start()
thread.join()
def test_token_contextmanager_with_default(self):
ctx = contextvars.Context()
c = contextvars.ContextVar('c', default=42)
def fun():
with c.set(36):
self.assertEqual(c.get(), 36)
self.assertEqual(c.get(), 42)
ctx.run(fun)
def test_token_contextmanager_without_default(self):
ctx = contextvars.Context()
c = contextvars.ContextVar('c')
def fun():
with c.set(36):
self.assertEqual(c.get(), 36)
with self.assertRaisesRegex(LookupError, "<ContextVar name='c'"):
c.get()
ctx.run(fun)
def test_token_contextmanager_on_exception(self):
ctx = contextvars.Context()
c = contextvars.ContextVar('c', default=42)
def fun():
with c.set(36):
self.assertEqual(c.get(), 36)
raise ValueError("custom exception")
self.assertEqual(c.get(), 42)
with self.assertRaisesRegex(ValueError, "custom exception"):
ctx.run(fun)
def test_token_contextmanager_reentrant(self):
ctx = contextvars.Context()
c = contextvars.ContextVar('c', default=42)
def fun():
token = c.set(36)
with self.assertRaisesRegex(
RuntimeError,
"<Token .+ has already been used once"
):
with token:
with token:
self.assertEqual(c.get(), 36)
self.assertEqual(c.get(), 42)
ctx.run(fun)
def test_token_contextmanager_multiple_c_set(self):
ctx = contextvars.Context()
c = contextvars.ContextVar('c', default=42)
def fun():
with c.set(36):
self.assertEqual(c.get(), 36)
c.set(24)
self.assertEqual(c.get(), 24)
c.set(12)
self.assertEqual(c.get(), 12)
self.assertEqual(c.get(), 42)
ctx.run(fun)
def test_token_contextmanager_with_explicit_reset_the_same_token(self):
ctx = contextvars.Context()
c = contextvars.ContextVar('c', default=42)
def fun():
with self.assertRaisesRegex(
RuntimeError,
"<Token .+ has already been used once"
):
with c.set(36) as token:
self.assertEqual(c.get(), 36)
c.reset(token)
self.assertEqual(c.get(), 42)
self.assertEqual(c.get(), 42)
ctx.run(fun)
def test_token_contextmanager_with_explicit_reset_another_token(self):
ctx = contextvars.Context()
c = contextvars.ContextVar('c', default=42)
def fun():
with c.set(36):
self.assertEqual(c.get(), 36)
token = c.set(24)
self.assertEqual(c.get(), 24)
c.reset(token)
self.assertEqual(c.get(), 36)
self.assertEqual(c.get(), 42)
ctx.run(fun)
def test_context_eq_reentrant_contextvar_set(self):
var = contextvars.ContextVar("v")
ctx1 = contextvars.Context()
ctx2 = contextvars.Context()
class ReentrantEq:
def __eq__(self, other):
ctx1.run(lambda: var.set(object()))
return True
ctx1.run(var.set, ReentrantEq())
ctx2.run(var.set, object())
ctx1 == ctx2
def test_context_eq_reentrant_contextvar_set_in_hash(self):
var = contextvars.ContextVar("v")
ctx1 = contextvars.Context()
ctx2 = contextvars.Context()
class ReentrantHash:
def __hash__(self):
ctx1.run(lambda: var.set(object()))
return 0
def __eq__(self, other):
return isinstance(other, ReentrantHash)
ctx1.run(var.set, ReentrantHash())
ctx2.run(var.set, ReentrantHash())
ctx1 == ctx2
def test_get_changed_outside_run(self):
# Outside any Context.run(), bindings are considered "changed"
v = contextvars.ContextVar('v', default='dflt')
val, changed = v.get_changed()
self.assertEqual(val, 'dflt')
self.assertFalse(changed) # default value, not changed
v.set(42)
val, changed = v.get_changed()
self.assertEqual(val, 42)
self.assertTrue(changed) # set in base context
def test_get_changed_inherited(self):
# Inherited bindings are not considered "changed"
v = contextvars.ContextVar('v')
v.set('parent')
ctx = contextvars.copy_context()
def check():
val, changed = v.get_changed()
self.assertEqual(val, 'parent')
self.assertFalse(changed)
ctx.run(check)
def test_get_changed_after_set(self):
# After set() inside Context.run(), changed is True
v = contextvars.ContextVar('v')
v.set('parent')
ctx = contextvars.copy_context()
def check():
val, changed = v.get_changed()
self.assertFalse(changed)
v.set('child')
val, changed = v.get_changed()
self.assertEqual(val, 'child')
self.assertTrue(changed)
ctx.run(check)
def test_get_changed_new_var_in_run(self):
# A variable set for the first time inside run() is "changed"
v = contextvars.ContextVar('v')
ctx = contextvars.copy_context()
def check():
with self.assertRaises(LookupError):
v.get_changed()
v.set('new')
val, changed = v.get_changed()
self.assertEqual(val, 'new')
self.assertTrue(changed)
ctx.run(check)
def test_get_changed_not_set_with_default(self):
# A variable not set but with default: changed is False
v = contextvars.ContextVar('v', default='dflt')
ctx = contextvars.copy_context()
def check():
val, changed = v.get_changed()
self.assertEqual(val, 'dflt')
self.assertFalse(changed)
ctx.run(check)
def test_get_changed_not_set_no_default(self):
# A variable that has never been set and has no default
v = contextvars.ContextVar('v')
ctx = contextvars.copy_context()
def check():
with self.assertRaises(LookupError):
v.get_changed()
ctx.run(check)
def test_get_changed_explicit_default_arg(self):
# Passing a default argument to get_changed()
v = contextvars.ContextVar('v')
ctx = contextvars.copy_context()
def check():
val, changed = v.get_changed('fallback')
self.assertEqual(val, 'fallback')
self.assertFalse(changed)
ctx.run(check)
def test_get_changed_set_same_object(self):
# Setting to the exact same object does not count as "changed"
# because the HAMT recognizes the identical key-value pair
obj = object()
v = contextvars.ContextVar('v')
v.set(obj)
ctx = contextvars.copy_context()
def check():
val, changed = v.get_changed()
self.assertIs(val, obj)
self.assertFalse(changed)
v.set(obj) # same object
val, changed = v.get_changed()
self.assertIs(val, obj)
self.assertFalse(changed)
ctx.run(check)
def test_get_changed_set_different_object(self):
# Setting to a different object counts as "changed"
v = contextvars.ContextVar('v')
v.set([1, 2, 3])
ctx = contextvars.copy_context()
def check():
val, changed = v.get_changed()
self.assertFalse(changed)
v.set([1, 2, 3]) # equal value, different object
val, changed = v.get_changed()
self.assertTrue(changed)
ctx.run(check)
def test_get_changed_after_reset(self):
# After reset(), the variable reverts to its inherited state
v = contextvars.ContextVar('v')
v.set('original')
ctx = contextvars.copy_context()
def check():
val, changed = v.get_changed()
self.assertFalse(changed)
tok = v.set('modified')
val, changed = v.get_changed()
self.assertTrue(changed)
v.reset(tok)
val, changed = v.get_changed()
self.assertFalse(changed)
ctx.run(check)
def test_get_changed_multiple_vars(self):
# Changing one variable does not affect get_changed() for others
v1 = contextvars.ContextVar('v1')
v2 = contextvars.ContextVar('v2')
v1.set('a')
v2.set('b')
ctx = contextvars.copy_context()
def check():
_, changed1 = v1.get_changed()
_, changed2 = v2.get_changed()
self.assertFalse(changed1)
self.assertFalse(changed2)
v1.set('a2')
_, changed1 = v1.get_changed()
_, changed2 = v2.get_changed()
self.assertTrue(changed1)
self.assertFalse(changed2)
ctx.run(check)
def test_get_changed_nested_run(self):
# get_changed() reflects the innermost Context.run() scope
v = contextvars.ContextVar('v')
v.set('root')
ctx1 = contextvars.copy_context()
def outer():
_, changed = v.get_changed()
self.assertFalse(changed)
v.set('outer')
_, changed = v.get_changed()
self.assertTrue(changed)
ctx2 = contextvars.copy_context()
def inner():
# inherited 'outer' from ctx1, not changed in ctx2
val, changed = v.get_changed()
self.assertEqual(val, 'outer')
self.assertFalse(changed)
v.set('inner')
val, changed = v.get_changed()
self.assertEqual(val, 'inner')
self.assertTrue(changed)
ctx2.run(inner)
# after inner run exits, outer's state is restored
_, changed = v.get_changed()
self.assertTrue(changed)
ctx1.run(outer)
@threading_helper.requires_working_threading()
def test_get_changed_with_threads(self):
# get_changed() works correctly in a thread with copied context
import threading
v = contextvars.ContextVar('v')
v.set('parent')
ctx = contextvars.copy_context()
results = {}
def thread_func():
val, changed = v.get_changed()
results['inherited'] = changed
results['value'] = val
v.set('thread')
val, changed = v.get_changed()
results['after_set'] = changed
t = threading.Thread(target=ctx.run, args=(thread_func,))
t.start()
t.join()
self.assertFalse(results['inherited'])
self.assertEqual(results['value'], 'parent')
self.assertTrue(results['after_set'])
def test_get_changed_empty_context_run(self):
# Running in a brand new empty context
v = contextvars.ContextVar('v')
ctx = contextvars.Context()
def check():
with self.assertRaises(LookupError):
v.get_changed()
v.set('value')
val, changed = v.get_changed()
self.assertEqual(val, 'value')
self.assertTrue(changed)
ctx.run(check)
# HAMT Tests
class HashKey:
_crasher = None
def __init__(self, hash, name, *, error_on_eq_to=None):
assert hash != -1
self.name = name
self.hash = hash
self.error_on_eq_to = error_on_eq_to
def __repr__(self):
return f'<Key name:{self.name} hash:{self.hash}>'
def __hash__(self):
if self._crasher is not None and self._crasher.error_on_hash:
raise HashingError
return self.hash
def __eq__(self, other):
if not isinstance(other, HashKey):
return NotImplemented
if self._crasher is not None and self._crasher.error_on_eq:
raise EqError
if self.error_on_eq_to is not None and self.error_on_eq_to is other:
raise ValueError(f'cannot compare {self!r} to {other!r}')
if other.error_on_eq_to is not None and other.error_on_eq_to is self:
raise ValueError(f'cannot compare {other!r} to {self!r}')
return (self.name, self.hash) == (other.name, other.hash)
class KeyStr(str):
def __hash__(self):
if HashKey._crasher is not None and HashKey._crasher.error_on_hash:
raise HashingError
return super().__hash__()
def __eq__(self, other):
if HashKey._crasher is not None and HashKey._crasher.error_on_eq:
raise EqError
return super().__eq__(other)
class HaskKeyCrasher:
def __init__(self, *, error_on_hash=False, error_on_eq=False):
self.error_on_hash = error_on_hash
self.error_on_eq = error_on_eq
def __enter__(self):
if HashKey._crasher is not None:
raise RuntimeError('cannot nest crashers')
HashKey._crasher = self
def __exit__(self, *exc):
HashKey._crasher = None
class HashingError(Exception):
pass
class EqError(Exception):
pass
@unittest.skipIf(hamt is None, '_testinternalcapi.hamt() not available')
class HamtTest(unittest.TestCase):
def test_hashkey_helper_1(self):
k1 = HashKey(10, 'aaa')
k2 = HashKey(10, 'bbb')
self.assertNotEqual(k1, k2)
self.assertEqual(hash(k1), hash(k2))
d = dict()
d[k1] = 'a'
d[k2] = 'b'
self.assertEqual(d[k1], 'a')
self.assertEqual(d[k2], 'b')
def test_hamt_basics_1(self):
h = hamt()
h = None # NoQA
def test_hamt_basics_2(self):
h = hamt()
self.assertEqual(len(h), 0)
h2 = h.set('a', 'b')
self.assertIsNot(h, h2)
self.assertEqual(len(h), 0)
self.assertEqual(len(h2), 1)
self.assertIsNone(h.get('a'))
self.assertEqual(h.get('a', 42), 42)
self.assertEqual(h2.get('a'), 'b')
h3 = h2.set('b', 10)
self.assertIsNot(h2, h3)
self.assertEqual(len(h), 0)
self.assertEqual(len(h2), 1)
self.assertEqual(len(h3), 2)
self.assertEqual(h3.get('a'), 'b')
self.assertEqual(h3.get('b'), 10)
self.assertIsNone(h.get('b'))
self.assertIsNone(h2.get('b'))
self.assertIsNone(h.get('a'))
self.assertEqual(h2.get('a'), 'b')
h = h2 = h3 = None
def test_hamt_basics_3(self):
h = hamt()
o = object()
h1 = h.set('1', o)
h2 = h1.set('1', o)
self.assertIs(h1, h2)
def test_hamt_basics_4(self):
h = hamt()
h1 = h.set('key', [])
h2 = h1.set('key', [])
self.assertIsNot(h1, h2)
self.assertEqual(len(h1), 1)
self.assertEqual(len(h2), 1)
self.assertIsNot(h1.get('key'), h2.get('key'))
def test_hamt_collision_1(self):
k1 = HashKey(10, 'aaa')
k2 = HashKey(10, 'bbb')
k3 = HashKey(10, 'ccc')
h = hamt()
h2 = h.set(k1, 'a')
h3 = h2.set(k2, 'b')
self.assertEqual(h.get(k1), None)
self.assertEqual(h.get(k2), None)
self.assertEqual(h2.get(k1), 'a')
self.assertEqual(h2.get(k2), None)
self.assertEqual(h3.get(k1), 'a')
self.assertEqual(h3.get(k2), 'b')
h4 = h3.set(k2, 'cc')
h5 = h4.set(k3, 'aa')
self.assertEqual(h3.get(k1), 'a')
self.assertEqual(h3.get(k2), 'b')
self.assertEqual(h4.get(k1), 'a')
self.assertEqual(h4.get(k2), 'cc')
self.assertEqual(h4.get(k3), None)
self.assertEqual(h5.get(k1), 'a')
self.assertEqual(h5.get(k2), 'cc')
self.assertEqual(h5.get(k2), 'cc')
self.assertEqual(h5.get(k3), 'aa')
self.assertEqual(len(h), 0)
self.assertEqual(len(h2), 1)
self.assertEqual(len(h3), 2)
self.assertEqual(len(h4), 2)
self.assertEqual(len(h5), 3)
def test_hamt_collision_3(self):
# Test that iteration works with the deepest tree possible.
# https://github.com/python/cpython/issues/93065
C = HashKey(0b10000000_00000000_00000000_00000000, 'C')
D = HashKey(0b10000000_00000000_00000000_00000000, 'D')
E = HashKey(0b00000000_00000000_00000000_00000000, 'E')
h = hamt()
h = h.set(C, 'C')
h = h.set(D, 'D')
h = h.set(E, 'E')
# BitmapNode(size=2 count=1 bitmap=0b1):
# NULL: