Debian Codegraph @

lib-python/3/test/test_context.py

raw symbols SCIP
1 import concurrent.futures
2 import contextvars
3 import functools
4 import gc
5 import random
6 import time
7 import sys
8 import unittest
9 import weakref
10 from test import support
11 from test.support import threading_helper
12
13 try:
14 from _testcapi import hamt
15 except ImportError:
16 hamt = None
17
18
19 def isolated_context(func):
20 """Needed to make reftracking test mode work."""
21 @functools.wraps(func)
22 def wrapper(*args, **kwargs):
23 ctx = contextvars.Context()
24 return ctx.run(func, *args, **kwargs)
25 return wrapper
26
27
28 class ContextTest(unittest.TestCase):
29 def test_context_var_new_1(self):
30 if sys.implementation.name == 'pypy':
31 msg = 'missing 1 required positional argument'
32 else:
33 msg = 'takes exactly 1'
34 with self.assertRaisesRegex(TypeError, msg):
35 contextvars.ContextVar()
36
37 with self.assertRaisesRegex(TypeError, 'must be a str'):
38 contextvars.ContextVar(1)
39
40 c = contextvars.ContextVar('aaa')
41 self.assertEqual(c.name, 'aaa')
42
43 with self.assertRaises(AttributeError):
44 c.name = 'bbb'
45
46 self.assertNotEqual(hash(c), hash('aaa'))
47
48 @isolated_context
49 def test_context_var_repr_1(self):
50 c = contextvars.ContextVar('a')
51 self.assertIn('a', repr(c))
52
53 c = contextvars.ContextVar('a', default=123)
54 self.assertIn('123', repr(c))
55
56 lst = []
57 c = contextvars.ContextVar('a', default=lst)
58 lst.append(c)
59 self.assertIn('...', repr(c))
60 self.assertIn('...', repr(lst))
61
62 t = c.set(1)
63 self.assertIn(repr(c), repr(t))
64 self.assertNotIn(' used ', repr(t))
65 c.reset(t)
66 self.assertIn(' used ', repr(t))
67
68 def test_context_subclassing_1(self):
69 with self.assertRaisesRegex(TypeError, 'not an acceptable base type'):
70 class MyContextVar(contextvars.ContextVar):
71 # Potentially we might want ContextVars to be subclassable.
72 pass
73
74 with self.assertRaisesRegex(TypeError, 'not an acceptable base type'):
75 class MyContext(contextvars.Context):
76 pass
77
78 with self.assertRaisesRegex(TypeError, 'not an acceptable base type'):
79 class MyToken(contextvars.Token):
80 pass
81
82 def test_context_new_1(self):
83 if sys.implementation.name == 'pypy':
84 msg = ''
85 else:
86 msg = 'any arguments'
87 with self.assertRaisesRegex(TypeError, msg):
88 contextvars.Context(1)
89 with self.assertRaisesRegex(TypeError, msg):
90 contextvars.Context(1, a=1)
91 with self.assertRaisesRegex(TypeError, msg):
92 contextvars.Context(a=1)
93 contextvars.Context(**{})
94
95 def test_context_typerrors_1(self):
96 ctx = contextvars.Context()
97
98 with self.assertRaisesRegex(TypeError, 'ContextVar key was expected'):
99 ctx[1]
100 with self.assertRaisesRegex(TypeError, 'ContextVar key was expected'):
101 1 in ctx
102 with self.assertRaisesRegex(TypeError, 'ContextVar key was expected'):
103 ctx.get(1)
104
105 def test_context_get_context_1(self):
106 ctx = contextvars.copy_context()
107 self.assertIsInstance(ctx, contextvars.Context)
108
109 def test_context_run_1(self):
110 ctx = contextvars.Context()
111
112 with self.assertRaisesRegex(TypeError, 'missing 1 required'):
113 ctx.run()
114
115 def test_context_run_2(self):
116 ctx = contextvars.Context()
117
118 def func(*args, **kwargs):
119 kwargs['spam'] = 'foo'
120 args += ('bar',)
121 return args, kwargs
122
123 for f in (func, functools.partial(func)):
124 # partial doesn't support FASTCALL
125
126 self.assertEqual(ctx.run(f), (('bar',), {'spam': 'foo'}))
127 self.assertEqual(ctx.run(f, 1), ((1, 'bar'), {'spam': 'foo'}))
128
129 self.assertEqual(
130 ctx.run(f, a=2),
131 (('bar',), {'a': 2, 'spam': 'foo'}))
132
133 self.assertEqual(
134 ctx.run(f, 11, a=2),
135 ((11, 'bar'), {'a': 2, 'spam': 'foo'}))
136
137 a = {}
138 self.assertEqual(
139 ctx.run(f, 11, **a),
140 ((11, 'bar'), {'spam': 'foo'}))
141 self.assertEqual(a, {})
142
143 def test_context_run_3(self):
144 ctx = contextvars.Context()
145
146 def func(*args, **kwargs):
147 1 / 0
148
149 with self.assertRaises(ZeroDivisionError):
150 ctx.run(func)
151 with self.assertRaises(ZeroDivisionError):
152 ctx.run(func, 1, 2)
153 with self.assertRaises(ZeroDivisionError):
154 ctx.run(func, 1, 2, a=123)
155
156 @isolated_context
157 def test_context_run_4(self):
158 ctx1 = contextvars.Context()
159 ctx2 = contextvars.Context()
160 var = contextvars.ContextVar('var')
161
162 def func2():
163 self.assertIsNone(var.get(None))
164
165 def func1():
166 self.assertIsNone(var.get(None))
167 var.set('spam')
168 ctx2.run(func2)
169 self.assertEqual(var.get(None), 'spam')
170
171 cur = contextvars.copy_context()
172 self.assertEqual(len(cur), 1)
173 self.assertEqual(cur[var], 'spam')
174 return cur
175
176 returned_ctx = ctx1.run(func1)
177 self.assertEqual(ctx1, returned_ctx)
178 self.assertEqual(returned_ctx[var], 'spam')
179 self.assertIn(var, returned_ctx)
180
181 def test_context_run_5(self):
182 ctx = contextvars.Context()
183 var = contextvars.ContextVar('var')
184
185 def func():
186 self.assertIsNone(var.get(None))
187 var.set('spam')
188 1 / 0
189
190 with self.assertRaises(ZeroDivisionError):
191 ctx.run(func)
192
193 self.assertIsNone(var.get(None))
194
195 def test_context_run_6(self):
196 ctx = contextvars.Context()
197 c = contextvars.ContextVar('a', default=0)
198
199 def fun():
200 self.assertEqual(c.get(), 0)
201 self.assertIsNone(ctx.get(c))
202
203 c.set(42)
204 self.assertEqual(c.get(), 42)
205 self.assertEqual(ctx.get(c), 42)
206
207 ctx.run(fun)
208
209 def test_context_run_7(self):
210 ctx = contextvars.Context()
211
212 def fun():
213 with self.assertRaisesRegex(RuntimeError, 'is already entered'):
214 ctx.run(fun)
215
216 ctx.run(fun)
217
218 @isolated_context
219 def test_context_getset_1(self):
220 c = contextvars.ContextVar('c')
221 with self.assertRaises(LookupError):
222 c.get()
223
224 self.assertIsNone(c.get(None))
225
226 t0 = c.set(42)
227 self.assertEqual(c.get(), 42)
228 self.assertEqual(c.get(None), 42)
229 self.assertIs(t0.old_value, t0.MISSING)
230 self.assertIs(t0.old_value, contextvars.Token.MISSING)
231 self.assertIs(t0.var, c)
232
233 t = c.set('spam')
234 self.assertEqual(c.get(), 'spam')
235 self.assertEqual(c.get(None), 'spam')
236 self.assertEqual(t.old_value, 42)
237 c.reset(t)
238
239 self.assertEqual(c.get(), 42)
240 self.assertEqual(c.get(None), 42)
241
242 c.set('spam2')
243 with self.assertRaisesRegex(RuntimeError, 'has already been used'):
244 c.reset(t)
245 self.assertEqual(c.get(), 'spam2')
246
247 ctx1 = contextvars.copy_context()
248 self.assertIn(c, ctx1)
249
250 c.reset(t0)
251 with self.assertRaisesRegex(RuntimeError, 'has already been used'):
252 c.reset(t0)
253 self.assertIsNone(c.get(None))
254
255 self.assertIn(c, ctx1)
256 self.assertEqual(ctx1[c], 'spam2')
257 self.assertEqual(ctx1.get(c, 'aa'), 'spam2')
258 self.assertEqual(len(ctx1), 1)
259 self.assertEqual(list(ctx1.items()), [(c, 'spam2')])
260 self.assertEqual(list(ctx1.values()), ['spam2'])
261 self.assertEqual(list(ctx1.keys()), [c])
262 self.assertEqual(list(ctx1), [c])
263
264 ctx2 = contextvars.copy_context()
265 self.assertNotIn(c, ctx2)
266 with self.assertRaises(KeyError):
267 ctx2[c]
268 self.assertEqual(ctx2.get(c, 'aa'), 'aa')
269 self.assertEqual(len(ctx2), 0)
270 self.assertEqual(list(ctx2), [])
271
272 @isolated_context
273 def test_context_getset_2(self):
274 v1 = contextvars.ContextVar('v1')
275 v2 = contextvars.ContextVar('v2')
276
277 t1 = v1.set(42)
278 with self.assertRaisesRegex(ValueError, 'by a different'):
279 v2.reset(t1)
280
281 @isolated_context
282 def test_context_getset_3(self):
283 c = contextvars.ContextVar('c', default=42)
284 ctx = contextvars.Context()
285
286 def fun():
287 self.assertEqual(c.get(), 42)
288 with self.assertRaises(KeyError):
289 ctx[c]
290 self.assertIsNone(ctx.get(c))
291 self.assertEqual(ctx.get(c, 'spam'), 'spam')
292 self.assertNotIn(c, ctx)
293 self.assertEqual(list(ctx.keys()), [])
294
295 t = c.set(1)
296 self.assertEqual(list(ctx.keys()), [c])
297 self.assertEqual(ctx[c], 1)
298
299 c.reset(t)
300 self.assertEqual(list(ctx.keys()), [])
301 with self.assertRaises(KeyError):
302 ctx[c]
303
304 ctx.run(fun)
305
306 @isolated_context
307 def test_context_getset_4(self):
308 c = contextvars.ContextVar('c', default=42)
309 ctx = contextvars.Context()
310
311 tok = ctx.run(c.set, 1)
312
313 with self.assertRaisesRegex(ValueError, 'different Context'):
314 c.reset(tok)
315
316 @isolated_context
317 def test_context_getset_5(self):
318 c = contextvars.ContextVar('c', default=42)
319 c.set([])
320
321 def fun():
322 c.set([])
323 c.get().append(42)
324 self.assertEqual(c.get(), [42])
325
326 contextvars.copy_context().run(fun)
327 self.assertEqual(c.get(), [])
328
329 def test_context_copy_1(self):
330 ctx1 = contextvars.Context()
331 c = contextvars.ContextVar('c', default=42)
332
333 def ctx1_fun():
334 c.set(10)
335
336 ctx2 = ctx1.copy()
337 self.assertEqual(ctx2[c], 10)
338
339 c.set(20)
340 self.assertEqual(ctx1[c], 20)
341 self.assertEqual(ctx2[c], 10)
342
343 ctx2.run(ctx2_fun)
344 self.assertEqual(ctx1[c], 20)
345 self.assertEqual(ctx2[c], 30)
346
347 def ctx2_fun():
348 self.assertEqual(c.get(), 10)
349 c.set(30)
350 self.assertEqual(c.get(), 30)
351
352 ctx1.run(ctx1_fun)
353
354 @isolated_context
355 @threading_helper.requires_working_threading()
356 def test_context_threads_1(self):
357 cvar = contextvars.ContextVar('cvar')
358
359 def sub(num):
360 for i in range(10):
361 cvar.set(num + i)
362 time.sleep(random.uniform(0.001, 0.05))
363 self.assertEqual(cvar.get(), num + i)
364 return num
365
366 tp = concurrent.futures.ThreadPoolExecutor(max_workers=10)
367 try:
368 results = list(tp.map(sub, range(10)))
369 finally:
370 tp.shutdown()
371 self.assertEqual(results, list(range(10)))
372
373
374 # HAMT Tests
375
376
377 class HashKey:
378 _crasher = None
379
380 def __init__(self, hash, name, *, error_on_eq_to=None):
381 assert hash != -1
382 self.name = name
383 self.hash = hash
384 self.error_on_eq_to = error_on_eq_to
385
386 def __repr__(self):
387 return f'<Key name:{self.name} hash:{self.hash}>'
388
389 def __hash__(self):
390 if self._crasher is not None and self._crasher.error_on_hash:
391 raise HashingError
392
393 return self.hash
394
395 def __eq__(self, other):
396 if not isinstance(other, HashKey):
397 return NotImplemented
398
399 if self._crasher is not None and self._crasher.error_on_eq:
400 raise EqError
401
402 if self.error_on_eq_to is not None and self.error_on_eq_to is other:
403 raise ValueError(f'cannot compare {self!r} to {other!r}')
404 if other.error_on_eq_to is not None and other.error_on_eq_to is self:
405 raise ValueError(f'cannot compare {other!r} to {self!r}')
406
407 return (self.name, self.hash) == (other.name, other.hash)
408
409
410 class KeyStr(str):
411 def __hash__(self):
412 if HashKey._crasher is not None and HashKey._crasher.error_on_hash:
413 raise HashingError
414 return super().__hash__()
415
416 def __eq__(self, other):
417 if HashKey._crasher is not None and HashKey._crasher.error_on_eq:
418 raise EqError
419 return super().__eq__(other)
420
421
422 class HaskKeyCrasher:
423 def __init__(self, *, error_on_hash=False, error_on_eq=False):
424 self.error_on_hash = error_on_hash
425 self.error_on_eq = error_on_eq
426
427 def __enter__(self):
428 if HashKey._crasher is not None:
429 raise RuntimeError('cannot nest crashers')
430 HashKey._crasher = self
431
432 def __exit__(self, *exc):
433 HashKey._crasher = None
434
435
436 class HashingError(Exception):
437 pass
438
439
440 class EqError(Exception):
441 pass
442
443
444 @unittest.skipIf(hamt is None, '_testcapi lacks "hamt()" function')
445 class HamtTest(unittest.TestCase):
446
447 def test_hashkey_helper_1(self):
448 k1 = HashKey(10, 'aaa')
449 k2 = HashKey(10, 'bbb')
450
451 self.assertNotEqual(k1, k2)
452 self.assertEqual(hash(k1), hash(k2))
453
454 d = dict()
455 d[k1] = 'a'
456 d[k2] = 'b'
457
458 self.assertEqual(d[k1], 'a')
459 self.assertEqual(d[k2], 'b')
460
461 def test_hamt_basics_1(self):
462 h = hamt()
463 h = None # NoQA
464
465 def test_hamt_basics_2(self):
466 h = hamt()
467 self.assertEqual(len(h), 0)
468
469 h2 = h.set('a', 'b')
470 self.assertIsNot(h, h2)
471 self.assertEqual(len(h), 0)
472 self.assertEqual(len(h2), 1)
473
474 self.assertIsNone(h.get('a'))
475 self.assertEqual(h.get('a', 42), 42)
476
477 self.assertEqual(h2.get('a'), 'b')
478
479 h3 = h2.set('b', 10)
480 self.assertIsNot(h2, h3)
481 self.assertEqual(len(h), 0)
482 self.assertEqual(len(h2), 1)
483 self.assertEqual(len(h3), 2)
484 self.assertEqual(h3.get('a'), 'b')
485 self.assertEqual(h3.get('b'), 10)
486
487 self.assertIsNone(h.get('b'))
488 self.assertIsNone(h2.get('b'))
489
490 self.assertIsNone(h.get('a'))
491 self.assertEqual(h2.get('a'), 'b')
492
493 h = h2 = h3 = None
494
495 def test_hamt_basics_3(self):
496 h = hamt()
497 o = object()
498 h1 = h.set('1', o)
499 h2 = h1.set('1', o)
500 self.assertIs(h1, h2)
501
502 def test_hamt_basics_4(self):
503 h = hamt()
504 h1 = h.set('key', [])
505 h2 = h1.set('key', [])
506 self.assertIsNot(h1, h2)
507 self.assertEqual(len(h1), 1)
508 self.assertEqual(len(h2), 1)
509 self.assertIsNot(h1.get('key'), h2.get('key'))
510
511 def test_hamt_collision_1(self):
512 k1 = HashKey(10, 'aaa')
513 k2 = HashKey(10, 'bbb')
514 k3 = HashKey(10, 'ccc')
515
516 h = hamt()
517 h2 = h.set(k1, 'a')
518 h3 = h2.set(k2, 'b')
519
520 self.assertEqual(h.get(k1), None)
521 self.assertEqual(h.get(k2), None)
522
523 self.assertEqual(h2.get(k1), 'a')
524 self.assertEqual(h2.get(k2), None)
525
526 self.assertEqual(h3.get(k1), 'a')
527 self.assertEqual(h3.get(k2), 'b')
528
529 h4 = h3.set(k2, 'cc')
530 h5 = h4.set(k3, 'aa')
531
532 self.assertEqual(h3.get(k1), 'a')
533 self.assertEqual(h3.get(k2), 'b')
534 self.assertEqual(h4.get(k1), 'a')
535 self.assertEqual(h4.get(k2), 'cc')
536 self.assertEqual(h4.get(k3), None)
537 self.assertEqual(h5.get(k1), 'a')
538 self.assertEqual(h5.get(k2), 'cc')
539 self.assertEqual(h5.get(k2), 'cc')
540 self.assertEqual(h5.get(k3), 'aa')
541
542 self.assertEqual(len(h), 0)
543 self.assertEqual(len(h2), 1)
544 self.assertEqual(len(h3), 2)
545 self.assertEqual(len(h4), 2)
546 self.assertEqual(len(h5), 3)
547
548 def test_hamt_collision_3(self):
549 # Test that iteration works with the deepest tree possible.
550 # https://github.com/python/cpython/issues/93065
551
552 C = HashKey(0b10000000_00000000_00000000_00000000, 'C')
553 D = HashKey(0b10000000_00000000_00000000_00000000, 'D')
554
555 E = HashKey(0b00000000_00000000_00000000_00000000, 'E')
556
557 h = hamt()
558 h = h.set(C, 'C')
559 h = h.set(D, 'D')
560 h = h.set(E, 'E')
561
562 # BitmapNode(size=2 count=1 bitmap=0b1):
563 # NULL:
564 # BitmapNode(size=2 count=1 bitmap=0b1):
565 # NULL:
566 # BitmapNode(size=2 count=1 bitmap=0b1):
567 # NULL:
568 # BitmapNode(size=2 count=1 bitmap=0b1):
569 # NULL:
570 # BitmapNode(size=2 count=1 bitmap=0b1):
571 # NULL:
572 # BitmapNode(size=2 count=1 bitmap=0b1):
573 # NULL:
574 # BitmapNode(size=4 count=2 bitmap=0b101):
575 # <Key name:E hash:0>: 'E'
576 # NULL:
577 # CollisionNode(size=4 id=0x107a24520):
578 # <Key name:C hash:2147483648>: 'C'
579 # <Key name:D hash:2147483648>: 'D'
580
581 self.assertEqual({k.name for k in h.keys()}, {'C', 'D', 'E'})
582
583 @support.requires_resource('cpu')
584 def test_hamt_stress(self):
585 COLLECTION_SIZE = 7000
586 TEST_ITERS_EVERY = 647
587 CRASH_HASH_EVERY = 97
588 CRASH_EQ_EVERY = 11
589 RUN_XTIMES = 3
590
591 for _ in range(RUN_XTIMES):
592 h = hamt()
593 d = dict()
594
595 for i in range(COLLECTION_SIZE):
596 key = KeyStr(i)
597
598 if not (i % CRASH_HASH_EVERY):
599 with HaskKeyCrasher(error_on_hash=True):
600 with self.assertRaises(HashingError):
601 h.set(key, i)
602
603 h = h.set(key, i)
604
605 if not (i % CRASH_EQ_EVERY):
606 with HaskKeyCrasher(error_on_eq=True):
607 with self.assertRaises(EqError):
608 h.get(KeyStr(i)) # really trigger __eq__
609
610 d[key] = i
611 self.assertEqual(len(d), len(h))
612
613 if not (i % TEST_ITERS_EVERY):
614 self.assertEqual(set(h.items()), set(d.items()))
615 self.assertEqual(len(h.items()), len(d.items()))
616
617 self.assertEqual(len(h), COLLECTION_SIZE)
618
619 for key in range(COLLECTION_SIZE):
620 self.assertEqual(h.get(KeyStr(key), 'not found'), key)
621
622 keys_to_delete = list(range(COLLECTION_SIZE))
623 random.shuffle(keys_to_delete)
624 for iter_i, i in enumerate(keys_to_delete):
625 key = KeyStr(i)
626
627 if not (iter_i % CRASH_HASH_EVERY):
628 with HaskKeyCrasher(error_on_hash=True):
629 with self.assertRaises(HashingError):
630 h.delete(key)
631
632 if not (iter_i % CRASH_EQ_EVERY):
633 with HaskKeyCrasher(error_on_eq=True):
634 with self.assertRaises(EqError):
635 h.delete(KeyStr(i))
636
637 h = h.delete(key)
638 self.assertEqual(h.get(key, 'not found'), 'not found')
639 del d[key]
640 self.assertEqual(len(d), len(h))
641
642 if iter_i == COLLECTION_SIZE // 2:
643 hm = h
644 dm = d.copy()
645
646 if not (iter_i % TEST_ITERS_EVERY):
647 self.assertEqual(set(h.keys()), set(d.keys()))
648 self.assertEqual(len(h.keys()), len(d.keys()))
649
650 self.assertEqual(len(d), 0)
651 self.assertEqual(len(h), 0)
652
653 # ============
654
655 for key in dm:
656 self.assertEqual(hm.get(str(key)), dm[key])
657 self.assertEqual(len(dm), len(hm))
658
659 for i, key in enumerate(keys_to_delete):
660 hm = hm.delete(str(key))
661 self.assertEqual(hm.get(str(key), 'not found'), 'not found')
662 dm.pop(str(key), None)
663 self.assertEqual(len(d), len(h))
664
665 if not (i % TEST_ITERS_EVERY):
666 self.assertEqual(set(h.values()), set(d.values()))
667 self.assertEqual(len(h.values()), len(d.values()))
668
669 self.assertEqual(len(d), 0)
670 self.assertEqual(len(h), 0)
671 self.assertEqual(list(h.items()), [])
672
673 def test_hamt_delete_1(self):
674 A = HashKey(100, 'A')
675 B = HashKey(101, 'B')
676 C = HashKey(102, 'C')
677 D = HashKey(103, 'D')
678 E = HashKey(104, 'E')
679 Z = HashKey(-100, 'Z')
680
681 Er = HashKey(103, 'Er', error_on_eq_to=D)
682
683 h = hamt()
684 h = h.set(A, 'a')
685 h = h.set(B, 'b')
686 h = h.set(C, 'c')
687 h = h.set(D, 'd')
688 h = h.set(E, 'e')
689
690 orig_len = len(h)
691
692 # BitmapNode(size=10 bitmap=0b111110000 id=0x10eadc618):
693 # <Key name:A hash:100>: 'a'
694 # <Key name:B hash:101>: 'b'
695 # <Key name:C hash:102>: 'c'
696 # <Key name:D hash:103>: 'd'
697 # <Key name:E hash:104>: 'e'
698
699 h = h.delete(C)
700 self.assertEqual(len(h), orig_len - 1)
701
702 with self.assertRaisesRegex(ValueError, 'cannot compare'):
703 h.delete(Er)
704
705 h = h.delete(D)
706 self.assertEqual(len(h), orig_len - 2)
707
708 h2 = h.delete(Z)
709 self.assertIs(h2, h)
710
711 h = h.delete(A)
712 self.assertEqual(len(h), orig_len - 3)
713
714 self.assertEqual(h.get(A, 42), 42)
715 self.assertEqual(h.get(B), 'b')
716 self.assertEqual(h.get(E), 'e')
717
718 def test_hamt_delete_2(self):
719 A = HashKey(100, 'A')
720 B = HashKey(201001, 'B')
721 C = HashKey(101001, 'C')
722 D = HashKey(103, 'D')
723 E = HashKey(104, 'E')
724 Z = HashKey(-100, 'Z')
725
726 Er = HashKey(201001, 'Er', error_on_eq_to=B)
727
728 h = hamt()
729 h = h.set(A, 'a')
730 h = h.set(B, 'b')
731 h = h.set(C, 'c')
732 h = h.set(D, 'd')
733 h = h.set(E, 'e')
734
735 orig_len = len(h)
736
737 # BitmapNode(size=8 bitmap=0b1110010000):
738 # <Key name:A hash:100>: 'a'
739 # <Key name:D hash:103>: 'd'
740 # <Key name:E hash:104>: 'e'
741 # NULL:
742 # BitmapNode(size=4 bitmap=0b100000000001000000000):
743 # <Key name:B hash:201001>: 'b'
744 # <Key name:C hash:101001>: 'c'
745
746 with self.assertRaisesRegex(ValueError, 'cannot compare'):
747 h.delete(Er)
748
749 h = h.delete(Z)
750 self.assertEqual(len(h), orig_len)
751
752 h = h.delete(C)
753 self.assertEqual(len(h), orig_len - 1)
754
755 h = h.delete(B)
756 self.assertEqual(len(h), orig_len - 2)
757
758 h = h.delete(A)
759 self.assertEqual(len(h), orig_len - 3)
760
761 self.assertEqual(h.get(D), 'd')
762 self.assertEqual(h.get(E), 'e')
763
764 h = h.delete(A)
765 h = h.delete(B)
766 h = h.delete(D)
767 h = h.delete(E)
768 self.assertEqual(len(h), 0)
769
770 def test_hamt_delete_3(self):
771 A = HashKey(100, 'A')
772 B = HashKey(101, 'B')
773 C = HashKey(100100, 'C')
774 D = HashKey(100100, 'D')
775 E = HashKey(104, 'E')
776
777 h = hamt()
778 h = h.set(A, 'a')
779 h = h.set(B, 'b')
780 h = h.set(C, 'c')
781 h = h.set(D, 'd')
782 h = h.set(E, 'e')
783
784 orig_len = len(h)
785
786 # BitmapNode(size=6 bitmap=0b100110000):
787 # NULL:
788 # BitmapNode(size=4 bitmap=0b1000000000000000000001000):
789 # <Key name:A hash:100>: 'a'
790 # NULL:
791 # CollisionNode(size=4 id=0x108572410):
792 # <Key name:C hash:100100>: 'c'
793 # <Key name:D hash:100100>: 'd'
794 # <Key name:B hash:101>: 'b'
795 # <Key name:E hash:104>: 'e'
796
797 h = h.delete(A)
798 self.assertEqual(len(h), orig_len - 1)
799
800 h = h.delete(E)
801 self.assertEqual(len(h), orig_len - 2)
802
803 self.assertEqual(h.get(C), 'c')
804 self.assertEqual(h.get(B), 'b')
805
806 def test_hamt_delete_4(self):
807 A = HashKey(100, 'A')
808 B = HashKey(101, 'B')
809 C = HashKey(100100, 'C')
810 D = HashKey(100100, 'D')
811 E = HashKey(100100, 'E')
812
813 h = hamt()
814 h = h.set(A, 'a')
815 h = h.set(B, 'b')
816 h = h.set(C, 'c')
817 h = h.set(D, 'd')
818 h = h.set(E, 'e')
819
820 orig_len = len(h)
821
822 # BitmapNode(size=4 bitmap=0b110000):
823 # NULL:
824 # BitmapNode(size=4 bitmap=0b1000000000000000000001000):
825 # <Key name:A hash:100>: 'a'
826 # NULL:
827 # CollisionNode(size=6 id=0x10515ef30):
828 # <Key name:C hash:100100>: 'c'
829 # <Key name:D hash:100100>: 'd'
830 # <Key name:E hash:100100>: 'e'
831 # <Key name:B hash:101>: 'b'
832
833 h = h.delete(D)
834 self.assertEqual(len(h), orig_len - 1)
835
836 h = h.delete(E)
837 self.assertEqual(len(h), orig_len - 2)
838
839 h = h.delete(C)
840 self.assertEqual(len(h), orig_len - 3)
841
842 h = h.delete(A)
843 self.assertEqual(len(h), orig_len - 4)
844
845 h = h.delete(B)
846 self.assertEqual(len(h), 0)
847
848 def test_hamt_delete_5(self):
849 h = hamt()
850
851 keys = []
852 for i in range(17):
853 key = HashKey(i, str(i))
854 keys.append(key)
855 h = h.set(key, f'val-{i}')
856
857 collision_key16 = HashKey(16, '18')
858 h = h.set(collision_key16, 'collision')
859
860 # ArrayNode(id=0x10f8b9318):
861 # 0::
862 # BitmapNode(size=2 count=1 bitmap=0b1):
863 # <Key name:0 hash:0>: 'val-0'
864 #
865 # ... 14 more BitmapNodes ...
866 #
867 # 15::
868 # BitmapNode(size=2 count=1 bitmap=0b1):
869 # <Key name:15 hash:15>: 'val-15'
870 #
871 # 16::
872 # BitmapNode(size=2 count=1 bitmap=0b1):
873 # NULL:
874 # CollisionNode(size=4 id=0x10f2f5af8):
875 # <Key name:16 hash:16>: 'val-16'
876 # <Key name:18 hash:16>: 'collision'
877
878 self.assertEqual(len(h), 18)
879
880 h = h.delete(keys[2])
881 self.assertEqual(len(h), 17)
882
883 h = h.delete(collision_key16)
884 self.assertEqual(len(h), 16)
885 h = h.delete(keys[16])
886 self.assertEqual(len(h), 15)
887
888 h = h.delete(keys[1])
889 self.assertEqual(len(h), 14)
890 h = h.delete(keys[1])
891 self.assertEqual(len(h), 14)
892
893 for key in keys:
894 h = h.delete(key)
895 self.assertEqual(len(h), 0)
896
897 def test_hamt_items_1(self):
898 A = HashKey(100, 'A')
899 B = HashKey(201001, 'B')
900 C = HashKey(101001, 'C')
901 D = HashKey(103, 'D')
902 E = HashKey(104, 'E')
903 F = HashKey(110, 'F')
904
905 h = hamt()
906 h = h.set(A, 'a')
907 h = h.set(B, 'b')
908 h = h.set(C, 'c')
909 h = h.set(D, 'd')
910 h = h.set(E, 'e')
911 h = h.set(F, 'f')
912
913 it = h.items()
914 self.assertEqual(
915 set(list(it)),
916 {(A, 'a'), (B, 'b'), (C, 'c'), (D, 'd'), (E, 'e'), (F, 'f')})
917
918 def test_hamt_items_2(self):
919 A = HashKey(100, 'A')
920 B = HashKey(101, 'B')
921 C = HashKey(100100, 'C')
922 D = HashKey(100100, 'D')
923 E = HashKey(100100, 'E')
924 F = HashKey(110, 'F')
925
926 h = hamt()
927 h = h.set(A, 'a')
928 h = h.set(B, 'b')
929 h = h.set(C, 'c')
930 h = h.set(D, 'd')
931 h = h.set(E, 'e')
932 h = h.set(F, 'f')
933
934 it = h.items()
935 self.assertEqual(
936 set(list(it)),
937 {(A, 'a'), (B, 'b'), (C, 'c'), (D, 'd'), (E, 'e'), (F, 'f')})
938
939 def test_hamt_keys_1(self):
940 A = HashKey(100, 'A')
941 B = HashKey(101, 'B')
942 C = HashKey(100100, 'C')
943 D = HashKey(100100, 'D')
944 E = HashKey(100100, 'E')
945 F = HashKey(110, 'F')
946
947 h = hamt()
948 h = h.set(A, 'a')
949 h = h.set(B, 'b')
950 h = h.set(C, 'c')
951 h = h.set(D, 'd')
952 h = h.set(E, 'e')
953 h = h.set(F, 'f')
954
955 self.assertEqual(set(list(h.keys())), {A, B, C, D, E, F})
956 self.assertEqual(set(list(h)), {A, B, C, D, E, F})
957
958 def test_hamt_items_3(self):
959 h = hamt()
960 self.assertEqual(len(h.items()), 0)
961 self.assertEqual(list(h.items()), [])
962
963 def test_hamt_eq_1(self):
964 A = HashKey(100, 'A')
965 B = HashKey(101, 'B')
966 C = HashKey(100100, 'C')
967 D = HashKey(100100, 'D')
968 E = HashKey(120, 'E')
969
970 h1 = hamt()
971 h1 = h1.set(A, 'a')
972 h1 = h1.set(B, 'b')
973 h1 = h1.set(C, 'c')
974 h1 = h1.set(D, 'd')
975
976 h2 = hamt()
977 h2 = h2.set(A, 'a')
978
979 self.assertFalse(h1 == h2)
980 self.assertTrue(h1 != h2)
981
982 h2 = h2.set(B, 'b')
983 self.assertFalse(h1 == h2)
984 self.assertTrue(h1 != h2)
985
986 h2 = h2.set(C, 'c')
987 self.assertFalse(h1 == h2)
988 self.assertTrue(h1 != h2)
989
990 h2 = h2.set(D, 'd2')
991 self.assertFalse(h1 == h2)
992 self.assertTrue(h1 != h2)
993
994 h2 = h2.set(D, 'd')
995 self.assertTrue(h1 == h2)
996 self.assertFalse(h1 != h2)
997
998 h2 = h2.set(E, 'e')
999 self.assertFalse(h1 == h2)
1000 self.assertTrue(h1 != h2)
1001
1002 h2 = h2.delete(D)
1003 self.assertFalse(h1 == h2)
1004 self.assertTrue(h1 != h2)
1005
1006 h2 = h2.set(E, 'd')
1007 self.assertFalse(h1 == h2)
1008 self.assertTrue(h1 != h2)
1009
1010 def test_hamt_eq_2(self):
1011 A = HashKey(100, 'A')
1012 Er = HashKey(100, 'Er', error_on_eq_to=A)
1013
1014 h1 = hamt()
1015 h1 = h1.set(A, 'a')
1016
1017 h2 = hamt()
1018 h2 = h2.set(Er, 'a')
1019
1020 with self.assertRaisesRegex(ValueError, 'cannot compare'):
1021 h1 == h2
1022
1023 with self.assertRaisesRegex(ValueError, 'cannot compare'):
1024 h1 != h2
1025
1026 def test_hamt_gc_1(self):
1027 A = HashKey(100, 'A')
1028
1029 h = hamt()
1030 h = h.set(0, 0) # empty HAMT node is memoized in hamt.c
1031 ref = weakref.ref(h)
1032
1033 a = []
1034 a.append(a)
1035 a.append(h)
1036 b = []
1037 a.append(b)
1038 b.append(a)
1039 h = h.set(A, b)
1040
1041 del h, a, b
1042
1043 gc.collect()
1044 gc.collect()
1045 gc.collect()
1046
1047 self.assertIsNone(ref())
1048
1049 def test_hamt_gc_2(self):
1050 A = HashKey(100, 'A')
1051 B = HashKey(101, 'B')
1052
1053 h = hamt()
1054 h = h.set(A, 'a')
1055 h = h.set(A, h)
1056
1057 ref = weakref.ref(h)
1058 hi = h.items()
1059 next(hi)
1060
1061 del h, hi
1062
1063 gc.collect()
1064 gc.collect()
1065 gc.collect()
1066
1067 self.assertIsNone(ref())
1068
1069 def test_hamt_in_1(self):
1070 A = HashKey(100, 'A')
1071 AA = HashKey(100, 'A')
1072
1073 B = HashKey(101, 'B')
1074
1075 h = hamt()
1076 h = h.set(A, 1)
1077
1078 self.assertTrue(A in h)
1079 self.assertFalse(B in h)
1080
1081 with self.assertRaises(EqError):
1082 with HaskKeyCrasher(error_on_eq=True):
1083 AA in h
1084
1085 with self.assertRaises(HashingError):
1086 with HaskKeyCrasher(error_on_hash=True):
1087 AA in h
1088
1089 def test_hamt_getitem_1(self):
1090 A = HashKey(100, 'A')
1091 AA = HashKey(100, 'A')
1092
1093 B = HashKey(101, 'B')
1094
1095 h = hamt()
1096 h = h.set(A, 1)
1097
1098 self.assertEqual(h[A], 1)
1099 self.assertEqual(h[AA], 1)
1100
1101 with self.assertRaises(KeyError):
1102 h[B]
1103
1104 with self.assertRaises(EqError):
1105 with HaskKeyCrasher(error_on_eq=True):
1106 h[AA]
1107
1108 with self.assertRaises(HashingError):
1109 with HaskKeyCrasher(error_on_hash=True):
1110 h[AA]
1111
1112
1113 if __name__ == "__main__":
1114 unittest.main()