Debian Codegraph @

lib-python/3/test/test_weakref.py

raw symbols SCIP
1 import gc
2 import sys
3 import doctest
4 import unittest
5 import collections
6 import weakref
7 import operator
8 import contextlib
9 import copy
10 import threading
11 import time
12 import random
13
14 from test import support
15 from test.support import script_helper, ALWAYS_EQ
16 from test.support import gc_collect
17 from test.support import threading_helper
18
19 # Used in ReferencesTestCase.test_ref_created_during_del() .
20 ref_from_del = None
21
22 # Used by FinalizeTestCase as a global that may be replaced by None
23 # when the interpreter shuts down.
24 _global_var = 'foobar'
25
26 class C:
27 def method(self):
28 pass
29
30
31 class Callable:
32 bar = None
33
34 def __call__(self, x):
35 self.bar = x
36
37
38 def create_function():
39 def f(): pass
40 return f
41
42 def create_bound_method():
43 return C().method
44
45
46 class Object:
47 def __init__(self, arg):
48 self.arg = arg
49 def __repr__(self):
50 return "<Object %r>" % self.arg
51 def __eq__(self, other):
52 if isinstance(other, Object):
53 return self.arg == other.arg
54 return NotImplemented
55 def __lt__(self, other):
56 if isinstance(other, Object):
57 return self.arg < other.arg
58 return NotImplemented
59 def __hash__(self):
60 return hash(self.arg)
61 def some_method(self):
62 return 4
63 def other_method(self):
64 return 5
65
66
67 class RefCycle:
68 def __init__(self):
69 self.cycle = self
70
71
72 class TestBase(unittest.TestCase):
73
74 def setUp(self):
75 self.cbcalled = 0
76
77 def callback(self, ref):
78 self.cbcalled += 1
79
80
81 @contextlib.contextmanager
82 def collect_in_thread(period=0.0001):
83 """
84 Ensure GC collections happen in a different thread, at a high frequency.
85 """
86 please_stop = False
87
88 def collect():
89 while not please_stop:
90 time.sleep(period)
91 gc.collect()
92
93 with support.disable_gc():
94 t = threading.Thread(target=collect)
95 t.start()
96 try:
97 yield
98 finally:
99 please_stop = True
100 t.join()
101
102
103 class ReferencesTestCase(TestBase):
104
105 def test_basic_ref(self):
106 self.check_basic_ref(C)
107 self.check_basic_ref(create_function)
108 self.check_basic_ref(create_bound_method)
109
110 # Just make sure the tp_repr handler doesn't raise an exception.
111 # Live reference:
112 o = C()
113 wr = weakref.ref(o)
114 repr(wr)
115 # Dead reference:
116 del o
117 repr(wr)
118
119 def test_repr_failure_gh99184(self):
120 class MyConfig(dict):
121 def __getattr__(self, x):
122 return self[x]
123
124 obj = MyConfig(offset=5)
125 obj_weakref = weakref.ref(obj)
126
127 self.assertIn('MyConfig', repr(obj_weakref))
128 self.assertIn('MyConfig', str(obj_weakref))
129
130 def test_basic_callback(self):
131 self.check_basic_callback(C)
132 self.check_basic_callback(create_function)
133 self.check_basic_callback(create_bound_method)
134
135 @support.cpython_only
136 def test_cfunction(self):
137 import _testcapi
138 create_cfunction = _testcapi.create_cfunction
139 f = create_cfunction()
140 wr = weakref.ref(f)
141 self.assertIs(wr(), f)
142 del f
143 self.assertIsNone(wr())
144 self.check_basic_ref(create_cfunction)
145 self.check_basic_callback(create_cfunction)
146
147 def test_multiple_callbacks(self):
148 o = C()
149 ref1 = weakref.ref(o, self.callback)
150 ref2 = weakref.ref(o, self.callback)
151 del o
152 gc_collect() # For PyPy or other GCs.
153 self.assertIsNone(ref1(), "expected reference to be invalidated")
154 self.assertIsNone(ref2(), "expected reference to be invalidated")
155 self.assertEqual(self.cbcalled, 2,
156 "callback not called the right number of times")
157
158 def test_multiple_selfref_callbacks(self):
159 # Make sure all references are invalidated before callbacks are called
160 #
161 # What's important here is that we're using the first
162 # reference in the callback invoked on the second reference
163 # (the most recently created ref is cleaned up first). This
164 # tests that all references to the object are invalidated
165 # before any of the callbacks are invoked, so that we only
166 # have one invocation of _weakref.c:cleanup_helper() active
167 # for a particular object at a time.
168 #
169 def callback(object, self=self):
170 self.ref()
171 c = C()
172 self.ref = weakref.ref(c, callback)
173 ref1 = weakref.ref(c, callback)
174 del c
175
176 def test_constructor_kwargs(self):
177 c = C()
178 self.assertRaises(TypeError, weakref.ref, c, callback=None)
179
180 def test_proxy_ref(self):
181 o = C()
182 o.bar = 1
183 ref1 = weakref.proxy(o, self.callback)
184 ref2 = weakref.proxy(o, self.callback)
185 del o
186 gc_collect() # For PyPy or other GCs.
187
188 def check(proxy):
189 proxy.bar
190
191 self.assertRaises(ReferenceError, check, ref1)
192 self.assertRaises(ReferenceError, check, ref2)
193 ref3 = weakref.proxy(C())
194 gc_collect() # For PyPy or other GCs.
195 self.assertRaises(ReferenceError, bool, ref3)
196 self.assertEqual(self.cbcalled, 2)
197
198 def check_basic_ref(self, factory):
199 o = factory()
200 ref = weakref.ref(o)
201 self.assertIsNotNone(ref(),
202 "weak reference to live object should be live")
203 o2 = ref()
204 self.assertIs(o, o2,
205 "<ref>() should return original object if live")
206
207 def check_basic_callback(self, factory):
208 self.cbcalled = 0
209 o = factory()
210 ref = weakref.ref(o, self.callback)
211 del o
212 gc_collect() # For PyPy or other GCs.
213 self.assertEqual(self.cbcalled, 1,
214 "callback did not properly set 'cbcalled'")
215 self.assertIsNone(ref(),
216 "ref2 should be dead after deleting object reference")
217
218 def test_ref_reuse(self):
219 o = C()
220 ref1 = weakref.ref(o)
221 # create a proxy to make sure that there's an intervening creation
222 # between these two; it should make no difference
223 proxy = weakref.proxy(o)
224 ref2 = weakref.ref(o)
225 self.assertIs(ref1, ref2,
226 "reference object w/out callback should be re-used")
227
228 o = C()
229 proxy = weakref.proxy(o)
230 ref1 = weakref.ref(o)
231 ref2 = weakref.ref(o)
232 self.assertIs(ref1, ref2,
233 "reference object w/out callback should be re-used")
234 self.assertEqual(weakref.getweakrefcount(o), 2,
235 "wrong weak ref count for object")
236 del proxy
237 gc_collect() # For PyPy or other GCs.
238 self.assertEqual(weakref.getweakrefcount(o), 1,
239 "wrong weak ref count for object after deleting proxy")
240
241 def test_proxy_reuse(self):
242 o = C()
243 proxy1 = weakref.proxy(o)
244 ref = weakref.ref(o)
245 proxy2 = weakref.proxy(o)
246 self.assertIs(proxy1, proxy2,
247 "proxy object w/out callback should have been re-used")
248
249 def test_basic_proxy(self):
250 o = C()
251 self.check_proxy(o, weakref.proxy(o))
252
253 L = collections.UserList()
254 p = weakref.proxy(L)
255 self.assertFalse(p, "proxy for empty UserList should be false")
256 p.append(12)
257 self.assertEqual(len(L), 1)
258 self.assertTrue(p, "proxy for non-empty UserList should be true")
259 p[:] = [2, 3]
260 self.assertEqual(len(L), 2)
261 self.assertEqual(len(p), 2)
262 self.assertIn(3, p, "proxy didn't support __contains__() properly")
263 p[1] = 5
264 self.assertEqual(L[1], 5)
265 self.assertEqual(p[1], 5)
266 L2 = collections.UserList(L)
267 p2 = weakref.proxy(L2)
268 self.assertEqual(p, p2)
269 ## self.assertEqual(repr(L2), repr(p2))
270 L3 = collections.UserList(range(10))
271 p3 = weakref.proxy(L3)
272 self.assertEqual(L3[:], p3[:])
273 self.assertEqual(L3[5:], p3[5:])
274 self.assertEqual(L3[:5], p3[:5])
275 self.assertEqual(L3[2:5], p3[2:5])
276
277 def test_proxy_unicode(self):
278 # See bug 5037
279 class C(object):
280 def __str__(self):
281 return "string"
282 def __bytes__(self):
283 return b"bytes"
284 instance = C()
285 self.assertIn("__bytes__", dir(weakref.proxy(instance)))
286 self.assertEqual(bytes(weakref.proxy(instance)), b"bytes")
287
288 def test_proxy_index(self):
289 class C:
290 def __index__(self):
291 return 10
292 o = C()
293 p = weakref.proxy(o)
294 self.assertEqual(operator.index(p), 10)
295
296 def test_proxy_div(self):
297 class C:
298 def __floordiv__(self, other):
299 return 42
300 def __ifloordiv__(self, other):
301 return 21
302 o = C()
303 p = weakref.proxy(o)
304 self.assertEqual(p // 5, 42)
305 p //= 5
306 self.assertEqual(p, 21)
307
308 def test_proxy_matmul(self):
309 class C:
310 def __matmul__(self, other):
311 return 1729
312 def __rmatmul__(self, other):
313 return -163
314 def __imatmul__(self, other):
315 return 561
316 o = C()
317 p = weakref.proxy(o)
318 self.assertEqual(p @ 5, 1729)
319 self.assertEqual(5 @ p, -163)
320 p @= 5
321 self.assertEqual(p, 561)
322
323 # The PyWeakref_* C API is documented as allowing either NULL or
324 # None as the value for the callback, where either means "no
325 # callback". The "no callback" ref and proxy objects are supposed
326 # to be shared so long as they exist by all callers so long as
327 # they are active. In Python 2.3.3 and earlier, this guarantee
328 # was not honored, and was broken in different ways for
329 # PyWeakref_NewRef() and PyWeakref_NewProxy(). (Two tests.)
330
331 def test_shared_ref_without_callback(self):
332 self.check_shared_without_callback(weakref.ref)
333
334 def test_shared_proxy_without_callback(self):
335 self.check_shared_without_callback(weakref.proxy)
336
337 def check_shared_without_callback(self, makeref):
338 o = Object(1)
339 p1 = makeref(o, None)
340 p2 = makeref(o, None)
341 self.assertIs(p1, p2, "both callbacks were None in the C API")
342 del p1, p2
343 p1 = makeref(o)
344 p2 = makeref(o, None)
345 self.assertIs(p1, p2, "callbacks were NULL, None in the C API")
346 del p1, p2
347 p1 = makeref(o)
348 p2 = makeref(o)
349 self.assertIs(p1, p2, "both callbacks were NULL in the C API")
350 del p1, p2
351 p1 = makeref(o, None)
352 p2 = makeref(o)
353 self.assertIs(p1, p2, "callbacks were None, NULL in the C API")
354
355 def test_callable_proxy(self):
356 o = Callable()
357 ref1 = weakref.proxy(o)
358
359 self.check_proxy(o, ref1)
360
361 self.assertIs(type(ref1), weakref.CallableProxyType,
362 "proxy is not of callable type")
363 ref1('twinkies!')
364 self.assertEqual(o.bar, 'twinkies!',
365 "call through proxy not passed through to original")
366 ref1(x='Splat.')
367 self.assertEqual(o.bar, 'Splat.',
368 "call through proxy not passed through to original")
369
370 # expect due to too few args
371 self.assertRaises(TypeError, ref1)
372
373 # expect due to too many args
374 self.assertRaises(TypeError, ref1, 1, 2, 3)
375
376 def check_proxy(self, o, proxy):
377 o.foo = 1
378 self.assertEqual(proxy.foo, 1,
379 "proxy does not reflect attribute addition")
380 o.foo = 2
381 self.assertEqual(proxy.foo, 2,
382 "proxy does not reflect attribute modification")
383 del o.foo
384 self.assertFalse(hasattr(proxy, 'foo'),
385 "proxy does not reflect attribute removal")
386
387 proxy.foo = 1
388 self.assertEqual(o.foo, 1,
389 "object does not reflect attribute addition via proxy")
390 proxy.foo = 2
391 self.assertEqual(o.foo, 2,
392 "object does not reflect attribute modification via proxy")
393 del proxy.foo
394 self.assertFalse(hasattr(o, 'foo'),
395 "object does not reflect attribute removal via proxy")
396
397 def test_proxy_deletion(self):
398 # Test clearing of SF bug #762891
399 class Foo:
400 result = None
401 def __delitem__(self, accessor):
402 self.result = accessor
403 g = Foo()
404 f = weakref.proxy(g)
405 del f[0]
406 self.assertEqual(f.result, 0)
407
408 def test_proxy_bool(self):
409 # Test clearing of SF bug #1170766
410 class List(list): pass
411 lyst = List()
412 self.assertEqual(bool(weakref.proxy(lyst)), bool(lyst))
413
414 def test_proxy_iter(self):
415 # Test fails with a debug build of the interpreter
416 # (see bpo-38395).
417
418 obj = None
419
420 class MyObj:
421 def __iter__(self):
422 nonlocal obj
423 del obj
424 return NotImplemented
425
426 obj = MyObj()
427 p = weakref.proxy(obj)
428 with self.assertRaises(TypeError):
429 # "blech" in p calls MyObj.__iter__ through the proxy,
430 # without keeping a reference to the real object, so it
431 # can be killed in the middle of the call
432 "blech" in p
433
434 def test_proxy_next(self):
435 arr = [4, 5, 6]
436 def iterator_func():
437 yield from arr
438 it = iterator_func()
439
440 class IteratesWeakly:
441 def __iter__(self):
442 return weakref.proxy(it)
443
444 weak_it = IteratesWeakly()
445
446 # Calls proxy.__next__
447 self.assertEqual(list(weak_it), [4, 5, 6])
448
449 def test_proxy_bad_next(self):
450 # bpo-44720: PyIter_Next() shouldn't be called if the reference
451 # isn't an iterator.
452
453 not_an_iterator = lambda: 0
454
455 class A:
456 def __iter__(self):
457 return weakref.proxy(not_an_iterator)
458 a = A()
459
460 msg = "Weakref proxy referenced a non-iterator"
461 with self.assertRaisesRegex(TypeError, msg):
462 list(a)
463
464 def test_proxy_reversed(self):
465 class MyObj:
466 def __len__(self):
467 return 3
468 def __reversed__(self):
469 return iter('cba')
470
471 obj = MyObj()
472 self.assertEqual("".join(reversed(weakref.proxy(obj))), "cba")
473
474 def test_proxy_hash(self):
475 class MyObj:
476 def __hash__(self):
477 return 42
478
479 obj = MyObj()
480 with self.assertRaises(TypeError):
481 hash(weakref.proxy(obj))
482
483 class MyObj:
484 __hash__ = None
485
486 obj = MyObj()
487 with self.assertRaises(TypeError):
488 hash(weakref.proxy(obj))
489
490 def test_getweakrefcount(self):
491 o = C()
492 ref1 = weakref.ref(o)
493 ref2 = weakref.ref(o, self.callback)
494 self.assertEqual(weakref.getweakrefcount(o), 2,
495 "got wrong number of weak reference objects")
496
497 proxy1 = weakref.proxy(o)
498 proxy2 = weakref.proxy(o, self.callback)
499 self.assertEqual(weakref.getweakrefcount(o), 4,
500 "got wrong number of weak reference objects")
501
502 del ref1, ref2, proxy1, proxy2
503 gc_collect() # For PyPy or other GCs.
504 self.assertEqual(weakref.getweakrefcount(o), 0,
505 "weak reference objects not unlinked from"
506 " referent when discarded.")
507
508 # assumes ints do not support weakrefs
509 self.assertEqual(weakref.getweakrefcount(1), 0,
510 "got wrong number of weak reference objects for int")
511
512 def test_getweakrefs(self):
513 o = C()
514 ref1 = weakref.ref(o, self.callback)
515 ref2 = weakref.ref(o, self.callback)
516 del ref1
517 gc_collect() # For PyPy or other GCs.
518 self.assertEqual(weakref.getweakrefs(o), [ref2],
519 "list of refs does not match")
520
521 o = C()
522 ref1 = weakref.ref(o, self.callback)
523 ref2 = weakref.ref(o, self.callback)
524 del ref2
525 gc_collect() # For PyPy or other GCs.
526 self.assertEqual(weakref.getweakrefs(o), [ref1],
527 "list of refs does not match")
528
529 del ref1
530 gc_collect() # For PyPy or other GCs.
531 self.assertEqual(weakref.getweakrefs(o), [],
532 "list of refs not cleared")
533
534 # assumes ints do not support weakrefs
535 self.assertEqual(weakref.getweakrefs(1), [],
536 "list of refs does not match for int")
537
538 def test_newstyle_number_ops(self):
539 class F(float):
540 pass
541 f = F(2.0)
542 p = weakref.proxy(f)
543 self.assertEqual(p + 1.0, 3.0)
544 self.assertEqual(1.0 + p, 3.0) # this used to SEGV
545
546 def test_callbacks_protected(self):
547 # Callbacks protected from already-set exceptions?
548 # Regression test for SF bug #478534.
549 class BogusError(Exception):
550 pass
551 data = {}
552 def remove(k):
553 del data[k]
554 def encapsulate():
555 f = lambda : ()
556 data[weakref.ref(f, remove)] = None
557 raise BogusError
558 try:
559 encapsulate()
560 except BogusError:
561 pass
562 else:
563 self.fail("exception not properly restored")
564 try:
565 encapsulate()
566 except BogusError:
567 pass
568 else:
569 self.fail("exception not properly restored")
570
571 def test_sf_bug_840829(self):
572 # "weakref callbacks and gc corrupt memory"
573 # subtype_dealloc erroneously exposed a new-style instance
574 # already in the process of getting deallocated to gc,
575 # causing double-deallocation if the instance had a weakref
576 # callback that triggered gc.
577 # If the bug exists, there probably won't be an obvious symptom
578 # in a release build. In a debug build, a segfault will occur
579 # when the second attempt to remove the instance from the "list
580 # of all objects" occurs.
581
582 import gc
583
584 class C(object):
585 pass
586
587 c = C()
588 wr = weakref.ref(c, lambda ignore: gc.collect())
589 del c
590
591 # There endeth the first part. It gets worse.
592 del wr
593
594 c1 = C()
595 c1.i = C()
596 wr = weakref.ref(c1.i, lambda ignore: gc.collect())
597
598 c2 = C()
599 c2.c1 = c1
600 del c1 # still alive because c2 points to it
601
602 # Now when subtype_dealloc gets called on c2, it's not enough just
603 # that c2 is immune from gc while the weakref callbacks associated
604 # with c2 execute (there are none in this 2nd half of the test, btw).
605 # subtype_dealloc goes on to call the base classes' deallocs too,
606 # so any gc triggered by weakref callbacks associated with anything
607 # torn down by a base class dealloc can also trigger double
608 # deallocation of c2.
609 del c2
610
611 def test_callback_in_cycle(self):
612 import gc
613
614 class J(object):
615 pass
616
617 class II(object):
618 def acallback(self, ignore):
619 self.J
620
621 I = II()
622 I.J = J
623 I.wr = weakref.ref(J, I.acallback)
624
625 # Now J and II are each in a self-cycle (as all new-style class
626 # objects are, since their __mro__ points back to them). I holds
627 # both a weak reference (I.wr) and a strong reference (I.J) to class
628 # J. I is also in a cycle (I.wr points to a weakref that references
629 # I.acallback). When we del these three, they all become trash, but
630 # the cycles prevent any of them from getting cleaned up immediately.
631 # Instead they have to wait for cyclic gc to deduce that they're
632 # trash.
633 #
634 # gc used to call tp_clear on all of them, and the order in which
635 # it does that is pretty accidental. The exact order in which we
636 # built up these things manages to provoke gc into running tp_clear
637 # in just the right order (I last). Calling tp_clear on II leaves
638 # behind an insane class object (its __mro__ becomes NULL). Calling
639 # tp_clear on J breaks its self-cycle, but J doesn't get deleted
640 # just then because of the strong reference from I.J. Calling
641 # tp_clear on I starts to clear I's __dict__, and just happens to
642 # clear I.J first -- I.wr is still intact. That removes the last
643 # reference to J, which triggers the weakref callback. The callback
644 # tries to do "self.J", and instances of new-style classes look up
645 # attributes ("J") in the class dict first. The class (II) wants to
646 # search II.__mro__, but that's NULL. The result was a segfault in
647 # a release build, and an assert failure in a debug build.
648 del I, J, II
649 gc.collect()
650
651 def test_callback_reachable_one_way(self):
652 import gc
653
654 # This one broke the first patch that fixed the previous test. In this case,
655 # the objects reachable from the callback aren't also reachable
656 # from the object (c1) *triggering* the callback: you can get to
657 # c1 from c2, but not vice-versa. The result was that c2's __dict__
658 # got tp_clear'ed by the time the c2.cb callback got invoked.
659
660 class C:
661 def cb(self, ignore):
662 self.me
663 self.c1
664 self.wr
665
666 c1, c2 = C(), C()
667
668 c2.me = c2
669 c2.c1 = c1
670 c2.wr = weakref.ref(c1, c2.cb)
671
672 del c1, c2
673 gc.collect()
674
675 def test_callback_different_classes(self):
676 import gc
677
678 # Like test_callback_reachable_one_way, except c2 and c1 have different
679 # classes. c2's class (C) isn't reachable from c1 then, so protecting
680 # objects reachable from the dying object (c1) isn't enough to stop
681 # c2's class (C) from getting tp_clear'ed before c2.cb is invoked.
682 # The result was a segfault (C.__mro__ was NULL when the callback
683 # tried to look up self.me).
684
685 class C(object):
686 def cb(self, ignore):
687 self.me
688 self.c1
689 self.wr
690
691 class D:
692 pass
693
694 c1, c2 = D(), C()
695
696 c2.me = c2
697 c2.c1 = c1
698 c2.wr = weakref.ref(c1, c2.cb)
699
700 del c1, c2, C, D
701 gc.collect()
702
703 def test_callback_in_cycle_resurrection(self):
704 import gc
705
706 # Do something nasty in a weakref callback: resurrect objects
707 # from dead cycles. For this to be attempted, the weakref and
708 # its callback must also be part of the cyclic trash (else the
709 # objects reachable via the callback couldn't be in cyclic trash
710 # to begin with -- the callback would act like an external root).
711 # But gc clears trash weakrefs with callbacks early now, which
712 # disables the callbacks, so the callbacks shouldn't get called
713 # at all (and so nothing actually gets resurrected).
714
715 alist = []
716 class C(object):
717 def __init__(self, value):
718 self.attribute = value
719
720 def acallback(self, ignore):
721 alist.append(self.c)
722
723 c1, c2 = C(1), C(2)
724 c1.c = c2
725 c2.c = c1
726 c1.wr = weakref.ref(c2, c1.acallback)
727 c2.wr = weakref.ref(c1, c2.acallback)
728
729 def C_went_away(ignore):
730 alist.append("C went away")
731 wr = weakref.ref(C, C_went_away)
732
733 del c1, c2, C # make them all trash
734 self.assertEqual(alist, []) # del isn't enough to reclaim anything
735
736 gc.collect()
737 # c1.wr and c2.wr were part of the cyclic trash, so should have
738 # been cleared without their callbacks executing. OTOH, the weakref
739 # to C is bound to a function local (wr), and wasn't trash, so that
740 # callback should have been invoked when C went away.
741 self.assertEqual(alist, ["C went away"])
742 # The remaining weakref should be dead now (its callback ran).
743 self.assertEqual(wr(), None)
744
745 del alist[:]
746 gc.collect()
747 self.assertEqual(alist, [])
748
749 def test_callbacks_on_callback(self):
750 import gc
751
752 # Set up weakref callbacks *on* weakref callbacks.
753 alist = []
754 def safe_callback(ignore):
755 alist.append("safe_callback called")
756
757 class C(object):
758 def cb(self, ignore):
759 alist.append("cb called")
760
761 c, d = C(), C()
762 c.other = d
763 d.other = c
764 callback = c.cb
765 c.wr = weakref.ref(d, callback) # this won't trigger
766 d.wr = weakref.ref(callback, d.cb) # ditto
767 external_wr = weakref.ref(callback, safe_callback) # but this will
768 self.assertIs(external_wr(), callback)
769
770 # The weakrefs attached to c and d should get cleared, so that
771 # C.cb is never called. But external_wr isn't part of the cyclic
772 # trash, and no cyclic trash is reachable from it, so safe_callback
773 # should get invoked when the bound method object callback (c.cb)
774 # -- which is itself a callback, and also part of the cyclic trash --
775 # gets reclaimed at the end of gc.
776
777 del callback, c, d, C
778 self.assertEqual(alist, []) # del isn't enough to clean up cycles
779 gc.collect()
780 self.assertEqual(alist, ["safe_callback called"])
781 self.assertEqual(external_wr(), None)
782
783 del alist[:]
784 gc.collect()
785 self.assertEqual(alist, [])
786
787 @support.impl_detail(pypy=False)
788 def test_gc_during_ref_creation(self):
789 self.check_gc_during_creation(weakref.ref)
790
791 @support.impl_detail(pypy=False)
792 def test_gc_during_proxy_creation(self):
793 self.check_gc_during_creation(weakref.proxy)
794
795 def check_gc_during_creation(self, makeref):
796 thresholds = gc.get_threshold()
797 gc.set_threshold(1, 1, 1)
798 gc.collect()
799 class A:
800 pass
801
802 def callback(*args):
803 pass
804
805 referenced = A()
806
807 a = A()
808 a.a = a
809 a.wr = makeref(referenced)
810
811 try:
812 # now make sure the object and the ref get labeled as
813 # cyclic trash:
814 a = A()
815 weakref.ref(referenced, callback)
816
817 finally:
818 gc.set_threshold(*thresholds)
819
820 def test_ref_created_during_del(self):
821 # Bug #1377858
822 # A weakref created in an object's __del__() would crash the
823 # interpreter when the weakref was cleaned up since it would refer to
824 # non-existent memory. This test should not segfault the interpreter.
825 class Target(object):
826 def __del__(self):
827 global ref_from_del
828 ref_from_del = weakref.ref(self)
829
830 w = Target()
831
832 def test_init(self):
833 # Issue 3634
834 # <weakref to class>.__init__() doesn't check errors correctly
835 r = weakref.ref(Exception)
836 self.assertRaises(TypeError, r.__init__, 0, 0, 0, 0, 0)
837 # No exception should be raised here
838 gc.collect()
839
840 def test_classes(self):
841 # Check that classes are weakrefable.
842 class A(object):
843 pass
844 l = []
845 weakref.ref(int)
846 a = weakref.ref(A, l.append)
847 A = None
848 gc.collect()
849 self.assertEqual(a(), None)
850 self.assertEqual(l, [a])
851
852 def test_equality(self):
853 # Alive weakrefs defer equality testing to their underlying object.
854 x = Object(1)
855 y = Object(1)
856 z = Object(2)
857 a = weakref.ref(x)
858 b = weakref.ref(y)
859 c = weakref.ref(z)
860 d = weakref.ref(x)
861 # Note how we directly test the operators here, to stress both
862 # __eq__ and __ne__.
863 self.assertTrue(a == b)
864 self.assertFalse(a != b)
865 self.assertFalse(a == c)
866 self.assertTrue(a != c)
867 self.assertTrue(a == d)
868 self.assertFalse(a != d)
869 self.assertFalse(a == x)
870 self.assertTrue(a != x)
871 self.assertTrue(a == ALWAYS_EQ)
872 self.assertFalse(a != ALWAYS_EQ)
873 del x, y, z
874 gc.collect()
875 for r in a, b, c:
876 # Sanity check
877 self.assertIs(r(), None)
878 # Dead weakrefs compare by identity: whether `a` and `d` are the
879 # same weakref object is an implementation detail, since they pointed
880 # to the same original object and didn't have a callback.
881 # (see issue #16453).
882 self.assertFalse(a == b)
883 self.assertTrue(a != b)
884 self.assertFalse(a == c)
885 self.assertTrue(a != c)
886 self.assertEqual(a == d, a is d)
887 self.assertEqual(a != d, a is not d)
888
889 def test_ordering(self):
890 # weakrefs cannot be ordered, even if the underlying objects can.
891 ops = [operator.lt, operator.gt, operator.le, operator.ge]
892 x = Object(1)
893 y = Object(1)
894 a = weakref.ref(x)
895 b = weakref.ref(y)
896 for op in ops:
897 self.assertRaises(TypeError, op, a, b)
898 # Same when dead.
899 del x, y
900 gc.collect()
901 for op in ops:
902 self.assertRaises(TypeError, op, a, b)
903
904 def test_hashing(self):
905 # Alive weakrefs hash the same as the underlying object
906 x = Object(42)
907 y = Object(42)
908 a = weakref.ref(x)
909 b = weakref.ref(y)
910 self.assertEqual(hash(a), hash(42))
911 del x, y
912 gc.collect()
913 # Dead weakrefs:
914 # - retain their hash is they were hashed when alive;
915 # - otherwise, cannot be hashed.
916 self.assertEqual(hash(a), hash(42))
917 self.assertRaises(TypeError, hash, b)
918
919 def test_trashcan_16602(self):
920 # Issue #16602: when a weakref's target was part of a long
921 # deallocation chain, the trashcan mechanism could delay clearing
922 # of the weakref and make the target object visible from outside
923 # code even though its refcount had dropped to 0. A crash ensued.
924 class C:
925 def __init__(self, parent):
926 if not parent:
927 return
928 wself = weakref.ref(self)
929 def cb(wparent):
930 o = wself()
931 self.wparent = weakref.ref(parent, cb)
932
933 d = weakref.WeakKeyDictionary()
934 root = c = C(None)
935 for n in range(100):
936 d[c] = c = C(c)
937 del root
938 gc.collect()
939
940 def test_callback_attribute(self):
941 x = Object(1)
942 callback = lambda ref: None
943 ref1 = weakref.ref(x, callback)
944 self.assertIs(ref1.__callback__, callback)
945
946 ref2 = weakref.ref(x)
947 self.assertIsNone(ref2.__callback__)
948
949 def test_callback_attribute_after_deletion(self):
950 x = Object(1)
951 ref = weakref.ref(x, self.callback)
952 self.assertIsNotNone(ref.__callback__)
953 del x
954 support.gc_collect()
955 self.assertIsNone(ref.__callback__)
956
957 def test_set_callback_attribute(self):
958 x = Object(1)
959 callback = lambda ref: None
960 ref1 = weakref.ref(x, callback)
961 with self.assertRaises(AttributeError):
962 ref1.__callback__ = lambda ref: None
963
964 def test_callback_gcs(self):
965 class ObjectWithDel(Object):
966 def __del__(self): pass
967 x = ObjectWithDel(1)
968 ref1 = weakref.ref(x, lambda ref: support.gc_collect())
969 del x
970 support.gc_collect()
971
972
973 class SubclassableWeakrefTestCase(TestBase):
974
975 def test_subclass_refs(self):
976 class MyRef(weakref.ref):
977 def __init__(self, ob, callback=None, value=42):
978 self.value = value
979 super().__init__(ob, callback)
980 def __call__(self):
981 self.called = True
982 return super().__call__()
983 o = Object("foo")
984 mr = MyRef(o, value=24)
985 self.assertIs(mr(), o)
986 self.assertTrue(mr.called)
987 self.assertEqual(mr.value, 24)
988 del o
989 gc_collect() # For PyPy or other GCs.
990 self.assertIsNone(mr())
991 self.assertTrue(mr.called)
992
993 def test_subclass_refs_dont_replace_standard_refs(self):
994 class MyRef(weakref.ref):
995 pass
996 o = Object(42)
997 r1 = MyRef(o)
998 r2 = weakref.ref(o)
999 self.assertIsNot(r1, r2)
1000 self.assertEqual(weakref.getweakrefs(o), [r2, r1])
1001 self.assertEqual(weakref.getweakrefcount(o), 2)
1002 r3 = MyRef(o)
1003 self.assertEqual(weakref.getweakrefcount(o), 3)
1004 refs = weakref.getweakrefs(o)
1005 self.assertEqual(len(refs), 3)
1006 self.assertIs(r2, refs[0])
1007 self.assertIn(r1, refs[1:])
1008 self.assertIn(r3, refs[1:])
1009
1010 def test_subclass_refs_dont_conflate_callbacks(self):
1011 class MyRef(weakref.ref):
1012 pass
1013 o = Object(42)
1014 r1 = MyRef(o, id)
1015 r2 = MyRef(o, str)
1016 self.assertIsNot(r1, r2)
1017 refs = weakref.getweakrefs(o)
1018 self.assertIn(r1, refs)
1019 self.assertIn(r2, refs)
1020
1021 def test_subclass_refs_with_slots(self):
1022 class MyRef(weakref.ref):
1023 __slots__ = "slot1", "slot2"
1024 def __new__(type, ob, callback, slot1, slot2):
1025 return weakref.ref.__new__(type, ob, callback)
1026 def __init__(self, ob, callback, slot1, slot2):
1027 self.slot1 = slot1
1028 self.slot2 = slot2
1029 def meth(self):
1030 return self.slot1 + self.slot2
1031 o = Object(42)
1032 r = MyRef(o, None, "abc", "def")
1033 self.assertEqual(r.slot1, "abc")
1034 self.assertEqual(r.slot2, "def")
1035 self.assertEqual(r.meth(), "abcdef")
1036 self.assertFalse(hasattr(r, "__dict__"))
1037
1038 def test_subclass_refs_with_cycle(self):
1039 """Confirm https://bugs.python.org/issue3100 is fixed."""
1040 # An instance of a weakref subclass can have attributes.
1041 # If such a weakref holds the only strong reference to the object,
1042 # deleting the weakref will delete the object. In this case,
1043 # the callback must not be called, because the ref object is
1044 # being deleted.
1045 class MyRef(weakref.ref):
1046 pass
1047
1048 # Use a local callback, for "regrtest -R::"
1049 # to detect refcounting problems
1050 def callback(w):
1051 self.cbcalled += 1
1052
1053 o = C()
1054 r1 = MyRef(o, callback)
1055 r1.o = o
1056 del o
1057
1058 del r1 # Used to crash here
1059
1060 self.assertEqual(self.cbcalled, 0)
1061
1062 # Same test, with two weakrefs to the same object
1063 # (since code paths are different)
1064 o = C()
1065 r1 = MyRef(o, callback)
1066 r2 = MyRef(o, callback)
1067 r1.r = r2
1068 r2.o = o
1069 del o
1070 del r2
1071
1072 del r1 # Used to crash here
1073
1074 self.assertEqual(self.cbcalled, 0)
1075
1076
1077 class WeakMethodTestCase(unittest.TestCase):
1078
1079 def _subclass(self):
1080 """Return an Object subclass overriding `some_method`."""
1081 class C(Object):
1082 def some_method(self):
1083 return 6
1084 return C
1085
1086 def test_alive(self):
1087 o = Object(1)
1088 r = weakref.WeakMethod(o.some_method)
1089 self.assertIsInstance(r, weakref.ReferenceType)
1090 self.assertIsInstance(r(), type(o.some_method))
1091 self.assertIs(r().__self__, o)
1092 self.assertIs(r().__func__, o.some_method.__func__)
1093 self.assertEqual(r()(), 4)
1094
1095 def test_object_dead(self):
1096 o = Object(1)
1097 r = weakref.WeakMethod(o.some_method)
1098 del o
1099 gc.collect()
1100 self.assertIs(r(), None)
1101
1102 def test_method_dead(self):
1103 C = self._subclass()
1104 o = C(1)
1105 r = weakref.WeakMethod(o.some_method)
1106 del C.some_method
1107 gc.collect()
1108 self.assertIs(r(), None)
1109
1110 def test_callback_when_object_dead(self):
1111 # Test callback behaviour when object dies first.
1112 C = self._subclass()
1113 calls = []
1114 def cb(arg):
1115 calls.append(arg)
1116 o = C(1)
1117 r = weakref.WeakMethod(o.some_method, cb)
1118 del o
1119 gc.collect()
1120 self.assertEqual(calls, [r])
1121 # Callback is only called once.
1122 C.some_method = Object.some_method
1123 gc.collect()
1124 self.assertEqual(calls, [r])
1125
1126 def test_callback_when_method_dead(self):
1127 # Test callback behaviour when method dies first.
1128 C = self._subclass()
1129 calls = []
1130 def cb(arg):
1131 calls.append(arg)
1132 o = C(1)
1133 r = weakref.WeakMethod(o.some_method, cb)
1134 del C.some_method
1135 gc.collect()
1136 self.assertEqual(calls, [r])
1137 # Callback is only called once.
1138 del o
1139 gc.collect()
1140 self.assertEqual(calls, [r])
1141
1142 @support.cpython_only
1143 def test_no_cycles(self):
1144 # A WeakMethod doesn't create any reference cycle to itself.
1145 o = Object(1)
1146 def cb(_):
1147 pass
1148 r = weakref.WeakMethod(o.some_method, cb)
1149 wr = weakref.ref(r)
1150 del r
1151 self.assertIs(wr(), None)
1152
1153 def test_equality(self):
1154 def _eq(a, b):
1155 self.assertTrue(a == b)
1156 self.assertFalse(a != b)
1157 def _ne(a, b):
1158 self.assertTrue(a != b)
1159 self.assertFalse(a == b)
1160 x = Object(1)
1161 y = Object(1)
1162 a = weakref.WeakMethod(x.some_method)
1163 b = weakref.WeakMethod(y.some_method)
1164 c = weakref.WeakMethod(x.other_method)
1165 d = weakref.WeakMethod(y.other_method)
1166 # Objects equal, same method
1167 _eq(a, b)
1168 _eq(c, d)
1169 # Objects equal, different method
1170 _ne(a, c)
1171 _ne(a, d)
1172 _ne(b, c)
1173 _ne(b, d)
1174 # Objects unequal, same or different method
1175 z = Object(2)
1176 e = weakref.WeakMethod(z.some_method)
1177 f = weakref.WeakMethod(z.other_method)
1178 _ne(a, e)
1179 _ne(a, f)
1180 _ne(b, e)
1181 _ne(b, f)
1182 # Compare with different types
1183 _ne(a, x.some_method)
1184 _eq(a, ALWAYS_EQ)
1185 del x, y, z
1186 gc.collect()
1187 # Dead WeakMethods compare by identity
1188 refs = a, b, c, d, e, f
1189 for q in refs:
1190 for r in refs:
1191 self.assertEqual(q == r, q is r)
1192 self.assertEqual(q != r, q is not r)
1193
1194 def test_hashing(self):
1195 # Alive WeakMethods are hashable if the underlying object is
1196 # hashable.
1197 x = Object(1)
1198 y = Object(1)
1199 a = weakref.WeakMethod(x.some_method)
1200 b = weakref.WeakMethod(y.some_method)
1201 c = weakref.WeakMethod(y.other_method)
1202 # Since WeakMethod objects are equal, the hashes should be equal.
1203 self.assertEqual(hash(a), hash(b))
1204 ha = hash(a)
1205 # Dead WeakMethods retain their old hash value
1206 del x, y
1207 gc.collect()
1208 self.assertEqual(hash(a), ha)
1209 self.assertEqual(hash(b), ha)
1210 # If it wasn't hashed when alive, a dead WeakMethod cannot be hashed.
1211 self.assertRaises(TypeError, hash, c)
1212
1213
1214 class MappingTestCase(TestBase):
1215
1216 COUNT = 10
1217
1218 def check_len_cycles(self, dict_type, cons):
1219 N = 20
1220 items = [RefCycle() for i in range(N)]
1221 dct = dict_type(cons(o) for o in items)
1222 # Keep an iterator alive
1223 it = dct.items()
1224 try:
1225 print(next(it))
1226 except StopIteration:
1227 pass
1228 del items
1229 gc.collect()
1230 n1 = len(dct)
1231 del it
1232 gc.collect()
1233 gc.collect()
1234 print(list(dct.items()))
1235 n2 = len(dct)
1236 print(len(dct))
1237 print(weakref)
1238 # one item may be kept alive inside the iterator
1239 self.assertIn(n1, (0, 1))
1240 self.assertEqual(n2, 0)
1241
1242 def test_weak_keyed_len_cycles(self):
1243 self.check_len_cycles(weakref.WeakKeyDictionary, lambda k: (k, 1))
1244
1245 def test_weak_valued_len_cycles(self):
1246 self.check_len_cycles(weakref.WeakValueDictionary, lambda k: (1, k))
1247
1248 @support.impl_detail(pypy=False)
1249 def check_len_race(self, dict_type, cons):
1250 # Extended sanity checks for len() in the face of cyclic collection
1251 self.addCleanup(gc.set_threshold, *gc.get_threshold())
1252 for th in range(1, 100):
1253 N = 20
1254 gc.collect(0)
1255 gc.set_threshold(th, th, th)
1256 items = [RefCycle() for i in range(N)]
1257 dct = dict_type(cons(o) for o in items)
1258 del items
1259 # All items will be collected at next garbage collection pass
1260 it = dct.items()
1261 try:
1262 next(it)
1263 except StopIteration:
1264 pass
1265 n1 = len(dct)
1266 del it
1267 n2 = len(dct)
1268 self.assertGreaterEqual(n1, 0)
1269 self.assertLessEqual(n1, N)
1270 self.assertGreaterEqual(n2, 0)
1271 self.assertLessEqual(n2, n1)
1272
1273 def test_weak_keyed_len_race(self):
1274 self.check_len_race(weakref.WeakKeyDictionary, lambda k: (k, 1))
1275
1276 def test_weak_valued_len_race(self):
1277 self.check_len_race(weakref.WeakValueDictionary, lambda k: (1, k))
1278
1279 def test_weak_values(self):
1280 #
1281 # This exercises d.copy(), d.items(), d[], del d[], len(d).
1282 #
1283 dict, objects = self.make_weak_valued_dict()
1284 for o in objects:
1285 self.assertEqual(weakref.getweakrefcount(o), 1)
1286 self.assertIs(o, dict[o.arg],
1287 "wrong object returned by weak dict!")
1288 items1 = list(dict.items())
1289 items2 = list(dict.copy().items())
1290 items1.sort()
1291 items2.sort()
1292 self.assertEqual(items1, items2,
1293 "cloning of weak-valued dictionary did not work!")
1294 del items1, items2
1295 self.assertEqual(len(dict), self.COUNT)
1296 del objects[0]
1297 gc_collect() # For PyPy or other GCs.
1298 self.assertEqual(len(dict), self.COUNT - 1,
1299 "deleting object did not cause dictionary update")
1300 del objects, o
1301 gc_collect() # For PyPy or other GCs.
1302 self.assertEqual(len(dict), 0,
1303 "deleting the values did not clear the dictionary")
1304 # regression on SF bug #447152:
1305 dict = weakref.WeakValueDictionary()
1306 self.assertRaises(KeyError, dict.__getitem__, 1)
1307 dict[2] = C()
1308 gc_collect() # For PyPy or other GCs.
1309 self.assertRaises(KeyError, dict.__getitem__, 2)
1310
1311 def test_weak_keys(self):
1312 #
1313 # This exercises d.copy(), d.items(), d[] = v, d[], del d[],
1314 # len(d), k in d.
1315 #
1316 dict, objects = self.make_weak_keyed_dict()
1317 for o in objects:
1318 self.assertEqual(weakref.getweakrefcount(o), 1,
1319 "wrong number of weak references to %r!" % o)
1320 self.assertIs(o.arg, dict[o],
1321 "wrong object returned by weak dict!")
1322 items1 = dict.items()
1323 items2 = dict.copy().items()
1324 self.assertEqual(set(items1), set(items2),
1325 "cloning of weak-keyed dictionary did not work!")
1326 del items1, items2
1327 self.assertEqual(len(dict), self.COUNT)
1328 del objects[0]
1329 gc_collect() # For PyPy or other GCs.
1330 self.assertEqual(len(dict), (self.COUNT - 1),
1331 "deleting object did not cause dictionary update")
1332 del objects, o
1333 gc_collect() # For PyPy or other GCs.
1334 self.assertEqual(len(dict), 0,
1335 "deleting the keys did not clear the dictionary")
1336 o = Object(42)
1337 dict[o] = "What is the meaning of the universe?"
1338 self.assertIn(o, dict)
1339 self.assertNotIn(34, dict)
1340
1341 def test_weak_keyed_iters(self):
1342 dict, objects = self.make_weak_keyed_dict()
1343 self.check_iters(dict)
1344
1345 # Test keyrefs()
1346 refs = dict.keyrefs()
1347 self.assertEqual(len(refs), len(objects))
1348 objects2 = list(objects)
1349 for wr in refs:
1350 ob = wr()
1351 self.assertIn(ob, dict)
1352 self.assertIn(ob, dict)
1353 self.assertEqual(ob.arg, dict[ob])
1354 objects2.remove(ob)
1355 self.assertEqual(len(objects2), 0)
1356
1357 # Test iterkeyrefs()
1358 objects2 = list(objects)
1359 self.assertEqual(len(list(dict.keyrefs())), len(objects))
1360 for wr in dict.keyrefs():
1361 ob = wr()
1362 self.assertIn(ob, dict)
1363 self.assertIn(ob, dict)
1364 self.assertEqual(ob.arg, dict[ob])
1365 objects2.remove(ob)
1366 self.assertEqual(len(objects2), 0)
1367
1368 def test_weak_valued_iters(self):
1369 dict, objects = self.make_weak_valued_dict()
1370 self.check_iters(dict)
1371
1372 # Test valuerefs()
1373 refs = dict.valuerefs()
1374 self.assertEqual(len(refs), len(objects))
1375 objects2 = list(objects)
1376 for wr in refs:
1377 ob = wr()
1378 self.assertEqual(ob, dict[ob.arg])
1379 self.assertEqual(ob.arg, dict[ob.arg].arg)
1380 objects2.remove(ob)
1381 self.assertEqual(len(objects2), 0)
1382
1383 # Test itervaluerefs()
1384 objects2 = list(objects)
1385 self.assertEqual(len(list(dict.itervaluerefs())), len(objects))
1386 for wr in dict.itervaluerefs():
1387 ob = wr()
1388 self.assertEqual(ob, dict[ob.arg])
1389 self.assertEqual(ob.arg, dict[ob.arg].arg)
1390 objects2.remove(ob)
1391 self.assertEqual(len(objects2), 0)
1392
1393 def check_iters(self, dict):
1394 # item iterator:
1395 items = list(dict.items())
1396 for item in dict.items():
1397 items.remove(item)
1398 self.assertFalse(items, "items() did not touch all items")
1399
1400 # key iterator, via __iter__():
1401 keys = list(dict.keys())
1402 for k in dict:
1403 keys.remove(k)
1404 self.assertFalse(keys, "__iter__() did not touch all keys")
1405
1406 # key iterator, via iterkeys():
1407 keys = list(dict.keys())
1408 for k in dict.keys():
1409 keys.remove(k)
1410 self.assertFalse(keys, "iterkeys() did not touch all keys")
1411
1412 # value iterator:
1413 values = list(dict.values())
1414 for v in dict.values():
1415 values.remove(v)
1416 self.assertFalse(values,
1417 "itervalues() did not touch all values")
1418
1419 def check_weak_destroy_while_iterating(self, dict, objects, iter_name):
1420 n = len(dict)
1421 it = iter(getattr(dict, iter_name)())
1422 next(it) # Trigger internal iteration
1423 # Destroy an object
1424 del objects[-1]
1425 gc.collect() # just in case
1426 # We have removed either the first consumed object, or another one
1427 self.assertIn(len(list(it)), [len(objects), len(objects) - 1])
1428 del it
1429 # The removal has been committed
1430 self.assertEqual(len(dict), n - 1)
1431
1432 def check_weak_destroy_and_mutate_while_iterating(self, dict, testcontext):
1433 # Check that we can explicitly mutate the weak dict without
1434 # interfering with delayed removal.
1435 # `testcontext` should create an iterator, destroy one of the
1436 # weakref'ed objects and then return a new key/value pair corresponding
1437 # to the destroyed object.
1438 with testcontext() as (k, v):
1439 self.assertNotIn(k, dict)
1440 with testcontext() as (k, v):
1441 self.assertRaises(KeyError, dict.__delitem__, k)
1442 self.assertNotIn(k, dict)
1443 with testcontext() as (k, v):
1444 self.assertRaises(KeyError, dict.pop, k)
1445 self.assertNotIn(k, dict)
1446 with testcontext() as (k, v):
1447 dict[k] = v
1448 self.assertEqual(dict[k], v)
1449 ddict = copy.copy(dict)
1450 with testcontext() as (k, v):
1451 dict.update(ddict)
1452 self.assertEqual(dict, ddict)
1453 with testcontext() as (k, v):
1454 dict.clear()
1455 self.assertEqual(len(dict), 0)
1456
1457 def check_weak_del_and_len_while_iterating(self, dict, testcontext):
1458 # Check that len() works when both iterating and removing keys
1459 # explicitly through various means (.pop(), .clear()...), while
1460 # implicit mutation is deferred because an iterator is alive.
1461 # (each call to testcontext() should schedule one item for removal
1462 # for this test to work properly)
1463 o = Object(123456)
1464 with testcontext():
1465 n = len(dict)
1466 # Since underlying dict is ordered, first item is popped
1467 dict.pop(next(dict.keys()))
1468 self.assertEqual(len(dict), n - 1)
1469 dict[o] = o
1470 self.assertEqual(len(dict), n)
1471 # last item in objects is removed from dict in context shutdown
1472 with testcontext():
1473 self.assertEqual(len(dict), n - 1)
1474 # Then, (o, o) is popped
1475 dict.popitem()
1476 self.assertEqual(len(dict), n - 2)
1477 with testcontext():
1478 self.assertEqual(len(dict), n - 3)
1479 del dict[next(dict.keys())]
1480 self.assertEqual(len(dict), n - 4)
1481 with testcontext():
1482 self.assertEqual(len(dict), n - 5)
1483 dict.popitem()
1484 self.assertEqual(len(dict), n - 6)
1485 with testcontext():
1486 dict.clear()
1487 self.assertEqual(len(dict), 0)
1488 self.assertEqual(len(dict), 0)
1489
1490 def test_weak_keys_destroy_while_iterating(self):
1491 # Issue #7105: iterators shouldn't crash when a key is implicitly removed
1492 dict, objects = self.make_weak_keyed_dict()
1493 self.check_weak_destroy_while_iterating(dict, objects, 'keys')
1494 self.check_weak_destroy_while_iterating(dict, objects, 'items')
1495 self.check_weak_destroy_while_iterating(dict, objects, 'values')
1496 self.check_weak_destroy_while_iterating(dict, objects, 'keyrefs')
1497 dict, objects = self.make_weak_keyed_dict()
1498 @contextlib.contextmanager
1499 def testcontext():
1500 try:
1501 it = iter(dict.items())
1502 next(it)
1503 # Schedule a key/value for removal and recreate it
1504 v = objects.pop().arg
1505 gc.collect() # just in case
1506 yield Object(v), v
1507 finally:
1508 it = None # should commit all removals
1509 gc.collect()
1510 self.check_weak_destroy_and_mutate_while_iterating(dict, testcontext)
1511 # Issue #21173: len() fragile when keys are both implicitly and
1512 # explicitly removed.
1513 dict, objects = self.make_weak_keyed_dict()
1514 self.check_weak_del_and_len_while_iterating(dict, testcontext)
1515
1516 def test_weak_values_destroy_while_iterating(self):
1517 # Issue #7105: iterators shouldn't crash when a key is implicitly removed
1518 dict, objects = self.make_weak_valued_dict()
1519 self.check_weak_destroy_while_iterating(dict, objects, 'keys')
1520 self.check_weak_destroy_while_iterating(dict, objects, 'items')
1521 self.check_weak_destroy_while_iterating(dict, objects, 'values')
1522 self.check_weak_destroy_while_iterating(dict, objects, 'itervaluerefs')
1523 self.check_weak_destroy_while_iterating(dict, objects, 'valuerefs')
1524 dict, objects = self.make_weak_valued_dict()
1525 @contextlib.contextmanager
1526 def testcontext():
1527 try:
1528 it = iter(dict.items())
1529 next(it)
1530 # Schedule a key/value for removal and recreate it
1531 k = objects.pop().arg
1532 gc.collect() # just in case
1533 yield k, Object(k)
1534 finally:
1535 it = None # should commit all removals
1536 gc.collect()
1537 self.check_weak_destroy_and_mutate_while_iterating(dict, testcontext)
1538 dict, objects = self.make_weak_valued_dict()
1539 self.check_weak_del_and_len_while_iterating(dict, testcontext)
1540
1541 def test_make_weak_keyed_dict_from_dict(self):
1542 o = Object(3)
1543 dict = weakref.WeakKeyDictionary({o:364})
1544 self.assertEqual(dict[o], 364)
1545
1546 def test_make_weak_keyed_dict_from_weak_keyed_dict(self):
1547 o = Object(3)
1548 dict = weakref.WeakKeyDictionary({o:364})
1549 dict2 = weakref.WeakKeyDictionary(dict)
1550 self.assertEqual(dict[o], 364)
1551
1552 def make_weak_keyed_dict(self):
1553 dict = weakref.WeakKeyDictionary()
1554 objects = list(map(Object, range(self.COUNT)))
1555 for o in objects:
1556 dict[o] = o.arg
1557 return dict, objects
1558
1559 def test_make_weak_valued_dict_from_dict(self):
1560 o = Object(3)
1561 dict = weakref.WeakValueDictionary({364:o})
1562 self.assertEqual(dict[364], o)
1563
1564 def test_make_weak_valued_dict_from_weak_valued_dict(self):
1565 o = Object(3)
1566 dict = weakref.WeakValueDictionary({364:o})
1567 dict2 = weakref.WeakValueDictionary(dict)
1568 self.assertEqual(dict[364], o)
1569
1570 def test_make_weak_valued_dict_misc(self):
1571 # errors
1572 self.assertRaises(TypeError, weakref.WeakValueDictionary.__init__)
1573 self.assertRaises(TypeError, weakref.WeakValueDictionary, {}, {})
1574 self.assertRaises(TypeError, weakref.WeakValueDictionary, (), ())
1575 # special keyword arguments
1576 o = Object(3)
1577 for kw in 'self', 'dict', 'other', 'iterable':
1578 d = weakref.WeakValueDictionary(**{kw: o})
1579 self.assertEqual(list(d.keys()), [kw])
1580 self.assertEqual(d[kw], o)
1581
1582 def make_weak_valued_dict(self):
1583 dict = weakref.WeakValueDictionary()
1584 objects = list(map(Object, range(self.COUNT)))
1585 for o in objects:
1586 dict[o.arg] = o
1587 return dict, objects
1588
1589 def check_popitem(self, klass, key1, value1, key2, value2):
1590 weakdict = klass()
1591 weakdict[key1] = value1
1592 weakdict[key2] = value2
1593 self.assertEqual(len(weakdict), 2)
1594 k, v = weakdict.popitem()
1595 self.assertEqual(len(weakdict), 1)
1596 if k is key1:
1597 self.assertIs(v, value1)
1598 else:
1599 self.assertIs(v, value2)
1600 k, v = weakdict.popitem()
1601 self.assertEqual(len(weakdict), 0)
1602 if k is key1:
1603 self.assertIs(v, value1)
1604 else:
1605 self.assertIs(v, value2)
1606
1607 def test_weak_valued_dict_popitem(self):
1608 self.check_popitem(weakref.WeakValueDictionary,
1609 "key1", C(), "key2", C())
1610
1611 def test_weak_keyed_dict_popitem(self):
1612 self.check_popitem(weakref.WeakKeyDictionary,
1613 C(), "value 1", C(), "value 2")
1614
1615 def check_setdefault(self, klass, key, value1, value2):
1616 self.assertIsNot(value1, value2,
1617 "invalid test"
1618 " -- value parameters must be distinct objects")
1619 weakdict = klass()
1620 o = weakdict.setdefault(key, value1)
1621 self.assertIs(o, value1)
1622 self.assertIn(key, weakdict)
1623 self.assertIs(weakdict.get(key), value1)
1624 self.assertIs(weakdict[key], value1)
1625
1626 o = weakdict.setdefault(key, value2)
1627 self.assertIs(o, value1)
1628 self.assertIn(key, weakdict)
1629 self.assertIs(weakdict.get(key), value1)
1630 self.assertIs(weakdict[key], value1)
1631
1632 def test_weak_valued_dict_setdefault(self):
1633 self.check_setdefault(weakref.WeakValueDictionary,
1634 "key", C(), C())
1635
1636 def test_weak_keyed_dict_setdefault(self):
1637 self.check_setdefault(weakref.WeakKeyDictionary,
1638 C(), "value 1", "value 2")
1639
1640 def check_update(self, klass, dict):
1641 #
1642 # This exercises d.update(), len(d), d.keys(), k in d,
1643 # d.get(), d[].
1644 #
1645 weakdict = klass()
1646 weakdict.update(dict)
1647 self.assertEqual(len(weakdict), len(dict))
1648 for k in weakdict.keys():
1649 self.assertIn(k, dict, "mysterious new key appeared in weak dict")
1650 v = dict.get(k)
1651 self.assertIs(v, weakdict[k])
1652 self.assertIs(v, weakdict.get(k))
1653 for k in dict.keys():
1654 self.assertIn(k, weakdict, "original key disappeared in weak dict")
1655 v = dict[k]
1656 self.assertIs(v, weakdict[k])
1657 self.assertIs(v, weakdict.get(k))
1658
1659 def test_weak_valued_dict_update(self):
1660 self.check_update(weakref.WeakValueDictionary,
1661 {1: C(), 'a': C(), C(): C()})
1662 # errors
1663 self.assertRaises(TypeError, weakref.WeakValueDictionary.update)
1664 d = weakref.WeakValueDictionary()
1665 self.assertRaises(TypeError, d.update, {}, {})
1666 self.assertRaises(TypeError, d.update, (), ())
1667 self.assertEqual(list(d.keys()), [])
1668 # special keyword arguments
1669 o = Object(3)
1670 for kw in 'self', 'dict', 'other', 'iterable':
1671 d = weakref.WeakValueDictionary()
1672 d.update(**{kw: o})
1673 self.assertEqual(list(d.keys()), [kw])
1674 self.assertEqual(d[kw], o)
1675
1676 def test_weak_valued_union_operators(self):
1677 a = C()
1678 b = C()
1679 c = C()
1680 wvd1 = weakref.WeakValueDictionary({1: a})
1681 wvd2 = weakref.WeakValueDictionary({1: b, 2: a})
1682 wvd3 = wvd1.copy()
1683 d1 = {1: c, 3: b}
1684 pairs = [(5, c), (6, b)]
1685
1686 tmp1 = wvd1 | wvd2 # Between two WeakValueDictionaries
1687 self.assertEqual(dict(tmp1), dict(wvd1) | dict(wvd2))
1688 self.assertIs(type(tmp1), weakref.WeakValueDictionary)
1689 wvd1 |= wvd2
1690 self.assertEqual(wvd1, tmp1)
1691
1692 tmp2 = wvd2 | d1 # Between WeakValueDictionary and mapping
1693 self.assertEqual(dict(tmp2), dict(wvd2) | d1)
1694 self.assertIs(type(tmp2), weakref.WeakValueDictionary)
1695 wvd2 |= d1
1696 self.assertEqual(wvd2, tmp2)
1697
1698 tmp3 = wvd3.copy() # Between WeakValueDictionary and iterable key, value
1699 tmp3 |= pairs
1700 self.assertEqual(dict(tmp3), dict(wvd3) | dict(pairs))
1701 self.assertIs(type(tmp3), weakref.WeakValueDictionary)
1702
1703 tmp4 = d1 | wvd3 # Testing .__ror__
1704 self.assertEqual(dict(tmp4), d1 | dict(wvd3))
1705 self.assertIs(type(tmp4), weakref.WeakValueDictionary)
1706
1707 del a
1708 gc_collect() # For PyPy or other GCs.
1709 self.assertNotIn(2, tmp1)
1710 self.assertNotIn(2, tmp2)
1711 self.assertNotIn(1, tmp3)
1712 self.assertNotIn(1, tmp4)
1713
1714 def test_weak_keyed_dict_update(self):
1715 self.check_update(weakref.WeakKeyDictionary,
1716 {C(): 1, C(): 2, C(): 3})
1717
1718 def test_weak_keyed_delitem(self):
1719 d = weakref.WeakKeyDictionary()
1720 o1 = Object('1')
1721 o2 = Object('2')
1722 d[o1] = 'something'
1723 d[o2] = 'something'
1724 self.assertEqual(len(d), 2)
1725 del d[o1]
1726 self.assertEqual(len(d), 1)
1727 self.assertEqual(list(d.keys()), [o2])
1728
1729 def test_weak_keyed_union_operators(self):
1730 o1 = C()
1731 o2 = C()
1732 o3 = C()
1733 wkd1 = weakref.WeakKeyDictionary({o1: 1, o2: 2})
1734 wkd2 = weakref.WeakKeyDictionary({o3: 3, o1: 4})
1735 wkd3 = wkd1.copy()
1736 d1 = {o2: '5', o3: '6'}
1737 pairs = [(o2, 7), (o3, 8)]
1738
1739 tmp1 = wkd1 | wkd2 # Between two WeakKeyDictionaries
1740 self.assertEqual(dict(tmp1), dict(wkd1) | dict(wkd2))
1741 self.assertIs(type(tmp1), weakref.WeakKeyDictionary)
1742 wkd1 |= wkd2
1743 self.assertEqual(wkd1, tmp1)
1744
1745 tmp2 = wkd2 | d1 # Between WeakKeyDictionary and mapping
1746 self.assertEqual(dict(tmp2), dict(wkd2) | d1)
1747 self.assertIs(type(tmp2), weakref.WeakKeyDictionary)
1748 wkd2 |= d1
1749 self.assertEqual(wkd2, tmp2)
1750
1751 tmp3 = wkd3.copy() # Between WeakKeyDictionary and iterable key, value
1752 tmp3 |= pairs
1753 self.assertEqual(dict(tmp3), dict(wkd3) | dict(pairs))
1754 self.assertIs(type(tmp3), weakref.WeakKeyDictionary)
1755
1756 tmp4 = d1 | wkd3 # Testing .__ror__
1757 self.assertEqual(dict(tmp4), d1 | dict(wkd3))
1758 self.assertIs(type(tmp4), weakref.WeakKeyDictionary)
1759
1760 del o1
1761 gc_collect() # For PyPy or other GCs.
1762 self.assertNotIn(4, tmp1.values())
1763 self.assertNotIn(4, tmp2.values())
1764 self.assertNotIn(1, tmp3.values())
1765 self.assertNotIn(1, tmp4.values())
1766
1767 def test_weak_valued_delitem(self):
1768 d = weakref.WeakValueDictionary()
1769 o1 = Object('1')
1770 o2 = Object('2')
1771 d['something'] = o1
1772 d['something else'] = o2
1773 self.assertEqual(len(d), 2)
1774 del d['something']
1775 self.assertEqual(len(d), 1)
1776 self.assertEqual(list(d.items()), [('something else', o2)])
1777
1778 def test_weak_keyed_bad_delitem(self):
1779 d = weakref.WeakKeyDictionary()
1780 o = Object('1')
1781 # An attempt to delete an object that isn't there should raise
1782 # KeyError. It didn't before 2.3.
1783 self.assertRaises(KeyError, d.__delitem__, o)
1784 self.assertRaises(KeyError, d.__getitem__, o)
1785
1786 # If a key isn't of a weakly referencable type, __getitem__ and
1787 # __setitem__ raise TypeError. __delitem__ should too.
1788 self.assertRaises(TypeError, d.__delitem__, 13)
1789 self.assertRaises(TypeError, d.__getitem__, 13)
1790 self.assertRaises(TypeError, d.__setitem__, 13, 13)
1791
1792 def test_weak_keyed_cascading_deletes(self):
1793 # SF bug 742860. For some reason, before 2.3 __delitem__ iterated
1794 # over the keys via self.data.iterkeys(). If things vanished from
1795 # the dict during this (or got added), that caused a RuntimeError.
1796
1797 d = weakref.WeakKeyDictionary()
1798 mutate = False
1799
1800 class C(object):
1801 def __init__(self, i):
1802 self.value = i
1803 def __hash__(self):
1804 return hash(self.value)
1805 def __eq__(self, other):
1806 if mutate:
1807 # Side effect that mutates the dict, by removing the
1808 # last strong reference to a key.
1809 del objs[-1]
1810 return self.value == other.value
1811
1812 objs = [C(i) for i in range(4)]
1813 for o in objs:
1814 d[o] = o.value
1815 del o # now the only strong references to keys are in objs
1816 # Find the order in which iterkeys sees the keys.
1817 objs = list(d.keys())
1818 # Reverse it, so that the iteration implementation of __delitem__
1819 # has to keep looping to find the first object we delete.
1820 objs.reverse()
1821
1822 # Turn on mutation in C.__eq__. The first time through the loop,
1823 # under the iterkeys() business the first comparison will delete
1824 # the last item iterkeys() would see, and that causes a
1825 # RuntimeError: dictionary changed size during iteration
1826 # when the iterkeys() loop goes around to try comparing the next
1827 # key. After this was fixed, it just deletes the last object *our*
1828 # "for o in obj" loop would have gotten to.
1829 mutate = True
1830 count = 0
1831 for o in objs:
1832 count += 1
1833 del d[o]
1834 gc_collect() # For PyPy or other GCs.
1835 self.assertEqual(len(d), 0)
1836 self.assertEqual(count, 2)
1837
1838 def test_make_weak_valued_dict_repr(self):
1839 dict = weakref.WeakValueDictionary()
1840 self.assertRegex(repr(dict), '<WeakValueDictionary at 0x.*>')
1841
1842 def test_make_weak_keyed_dict_repr(self):
1843 dict = weakref.WeakKeyDictionary()
1844 self.assertRegex(repr(dict), '<WeakKeyDictionary at 0x.*>')
1845
1846 @threading_helper.requires_working_threading()
1847 def test_threaded_weak_valued_setdefault(self):
1848 d = weakref.WeakValueDictionary()
1849 with collect_in_thread():
1850 for i in range(100000):
1851 x = d.setdefault(10, RefCycle())
1852 self.assertIsNot(x, None) # we never put None in there!
1853 del x
1854
1855 @threading_helper.requires_working_threading()
1856 def test_threaded_weak_valued_pop(self):
1857 d = weakref.WeakValueDictionary()
1858 with collect_in_thread():
1859 for i in range(100000):
1860 d[10] = RefCycle()
1861 x = d.pop(10, 10)
1862 self.assertIsNot(x, None) # we never put None in there!
1863
1864 @threading_helper.requires_working_threading()
1865 def test_threaded_weak_valued_consistency(self):
1866 # Issue #28427: old keys should not remove new values from
1867 # WeakValueDictionary when collecting from another thread.
1868 d = weakref.WeakValueDictionary()
1869 with collect_in_thread():
1870 for i in range(200000):
1871 o = RefCycle()
1872 d[10] = o
1873 # o is still alive, so the dict can't be empty
1874 self.assertEqual(len(d), 1)
1875 o = None # lose ref
1876
1877 def check_threaded_weak_dict_copy(self, type_, deepcopy):
1878 # `type_` should be either WeakKeyDictionary or WeakValueDictionary.
1879 # `deepcopy` should be either True or False.
1880 exc = []
1881
1882 class DummyKey:
1883 def __init__(self, ctr):
1884 self.ctr = ctr
1885
1886 class DummyValue:
1887 def __init__(self, ctr):
1888 self.ctr = ctr
1889
1890 def dict_copy(d, exc):
1891 try:
1892 if deepcopy is True:
1893 _ = copy.deepcopy(d)
1894 else:
1895 _ = d.copy()
1896 except Exception as ex:
1897 exc.append(ex)
1898
1899 def pop_and_collect(lst):
1900 gc_ctr = 0
1901 while lst:
1902 i = random.randint(0, len(lst) - 1)
1903 gc_ctr += 1
1904 lst.pop(i)
1905 if gc_ctr % 10000 == 0:
1906 gc.collect() # just in case
1907
1908 self.assertIn(type_, (weakref.WeakKeyDictionary, weakref.WeakValueDictionary))
1909
1910 d = type_()
1911 keys = []
1912 values = []
1913 # Initialize d with many entries
1914 for i in range(70000):
1915 k, v = DummyKey(i), DummyValue(i)
1916 keys.append(k)
1917 values.append(v)
1918 d[k] = v
1919 del k
1920 del v
1921
1922 t_copy = threading.Thread(target=dict_copy, args=(d, exc,))
1923 if type_ is weakref.WeakKeyDictionary:
1924 t_collect = threading.Thread(target=pop_and_collect, args=(keys,))
1925 else: # weakref.WeakValueDictionary
1926 t_collect = threading.Thread(target=pop_and_collect, args=(values,))
1927
1928 t_copy.start()
1929 t_collect.start()
1930
1931 t_copy.join()
1932 t_collect.join()
1933
1934 # Test exceptions
1935 if exc:
1936 raise exc[0]
1937
1938 @threading_helper.requires_working_threading()
1939 def test_threaded_weak_key_dict_copy(self):
1940 # Issue #35615: Weakref keys or values getting GC'ed during dict
1941 # copying should not result in a crash.
1942 self.check_threaded_weak_dict_copy(weakref.WeakKeyDictionary, False)
1943
1944 @threading_helper.requires_working_threading()
1945 @support.requires_resource('cpu')
1946 def test_threaded_weak_key_dict_deepcopy(self):
1947 # Issue #35615: Weakref keys or values getting GC'ed during dict
1948 # copying should not result in a crash.
1949 self.check_threaded_weak_dict_copy(weakref.WeakKeyDictionary, True)
1950
1951 @threading_helper.requires_working_threading()
1952 def test_threaded_weak_value_dict_copy(self):
1953 # Issue #35615: Weakref keys or values getting GC'ed during dict
1954 # copying should not result in a crash.
1955 self.check_threaded_weak_dict_copy(weakref.WeakValueDictionary, False)
1956
1957 @threading_helper.requires_working_threading()
1958 @support.requires_resource('cpu')
1959 def test_threaded_weak_value_dict_deepcopy(self):
1960 # Issue #35615: Weakref keys or values getting GC'ed during dict
1961 # copying should not result in a crash.
1962 self.check_threaded_weak_dict_copy(weakref.WeakValueDictionary, True)
1963
1964 @support.cpython_only
1965 def test_remove_closure(self):
1966 d = weakref.WeakValueDictionary()
1967 self.assertIsNone(d._remove.__closure__)
1968
1969
1970 from test import mapping_tests
1971
1972 class WeakValueDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
1973 """Check that WeakValueDictionary conforms to the mapping protocol"""
1974 __ref = {"key1":Object(1), "key2":Object(2), "key3":Object(3)}
1975 type2test = weakref.WeakValueDictionary
1976 def _reference(self):
1977 return self.__ref.copy()
1978
1979 class WeakKeyDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
1980 """Check that WeakKeyDictionary conforms to the mapping protocol"""
1981 __ref = {Object("key1"):1, Object("key2"):2, Object("key3"):3}
1982 type2test = weakref.WeakKeyDictionary
1983 def _reference(self):
1984 return self.__ref.copy()
1985
1986
1987 class FinalizeTestCase(unittest.TestCase):
1988
1989 class A:
1990 pass
1991
1992 def _collect_if_necessary(self):
1993 # we create no ref-cycles so in CPython no gc should be needed
1994 if sys.implementation.name != 'cpython':
1995 support.gc_collect()
1996
1997 def test_finalize(self):
1998 def add(x,y,z):
1999 res.append(x + y + z)
2000 return x + y + z
2001
2002 a = self.A()
2003
2004 res = []
2005 f = weakref.finalize(a, add, 67, 43, z=89)
2006 self.assertEqual(f.alive, True)
2007 self.assertEqual(f.peek(), (a, add, (67,43), {'z':89}))
2008 self.assertEqual(f(), 199)
2009 self.assertEqual(f(), None)
2010 self.assertEqual(f(), None)
2011 self.assertEqual(f.peek(), None)
2012 self.assertEqual(f.detach(), None)
2013 self.assertEqual(f.alive, False)
2014 self.assertEqual(res, [199])
2015
2016 res = []
2017 f = weakref.finalize(a, add, 67, 43, 89)
2018 self.assertEqual(f.peek(), (a, add, (67,43,89), {}))
2019 self.assertEqual(f.detach(), (a, add, (67,43,89), {}))
2020 self.assertEqual(f(), None)
2021 self.assertEqual(f(), None)
2022 self.assertEqual(f.peek(), None)
2023 self.assertEqual(f.detach(), None)
2024 self.assertEqual(f.alive, False)
2025 self.assertEqual(res, [])
2026
2027 res = []
2028 f = weakref.finalize(a, add, x=67, y=43, z=89)
2029 del a
2030 self._collect_if_necessary()
2031 self.assertEqual(f(), None)
2032 self.assertEqual(f(), None)
2033 self.assertEqual(f.peek(), None)
2034 self.assertEqual(f.detach(), None)
2035 self.assertEqual(f.alive, False)
2036 self.assertEqual(res, [199])
2037
2038 def test_arg_errors(self):
2039 def fin(*args, **kwargs):
2040 res.append((args, kwargs))
2041
2042 a = self.A()
2043
2044 res = []
2045 f = weakref.finalize(a, fin, 1, 2, func=3, obj=4)
2046 self.assertEqual(f.peek(), (a, fin, (1, 2), {'func': 3, 'obj': 4}))
2047 f()
2048 self.assertEqual(res, [((1, 2), {'func': 3, 'obj': 4})])
2049
2050 with self.assertRaises(TypeError):
2051 weakref.finalize(a, func=fin, arg=1)
2052 with self.assertRaises(TypeError):
2053 weakref.finalize(obj=a, func=fin, arg=1)
2054 self.assertRaises(TypeError, weakref.finalize, a)
2055 self.assertRaises(TypeError, weakref.finalize)
2056
2057 def test_order(self):
2058 a = self.A()
2059 res = []
2060
2061 f1 = weakref.finalize(a, res.append, 'f1')
2062 f2 = weakref.finalize(a, res.append, 'f2')
2063 f3 = weakref.finalize(a, res.append, 'f3')
2064 f4 = weakref.finalize(a, res.append, 'f4')
2065 f5 = weakref.finalize(a, res.append, 'f5')
2066
2067 # make sure finalizers can keep themselves alive
2068 del f1, f4
2069
2070 self.assertTrue(f2.alive)
2071 self.assertTrue(f3.alive)
2072 self.assertTrue(f5.alive)
2073
2074 self.assertTrue(f5.detach())
2075 self.assertFalse(f5.alive)
2076
2077 f5() # nothing because previously unregistered
2078 res.append('A')
2079 f3() # => res.append('f3')
2080 self.assertFalse(f3.alive)
2081 res.append('B')
2082 f3() # nothing because previously called
2083 res.append('C')
2084 del a
2085 self._collect_if_necessary()
2086 # => res.append('f4')
2087 # => res.append('f2')
2088 # => res.append('f1')
2089 self.assertFalse(f2.alive)
2090 res.append('D')
2091 f2() # nothing because previously called by gc
2092
2093 expected = ['A', 'f3', 'B', 'C', 'f4', 'f2', 'f1', 'D']
2094 self.assertEqual(res, expected)
2095
2096 def test_all_freed(self):
2097 # we want a weakrefable subclass of weakref.finalize
2098 class MyFinalizer(weakref.finalize):
2099 pass
2100
2101 a = self.A()
2102 res = []
2103 def callback():
2104 res.append(123)
2105 f = MyFinalizer(a, callback)
2106
2107 wr_callback = weakref.ref(callback)
2108 wr_f = weakref.ref(f)
2109 del callback, f
2110
2111 self.assertIsNotNone(wr_callback())
2112 self.assertIsNotNone(wr_f())
2113
2114 del a
2115 self._collect_if_necessary()
2116
2117 self.assertIsNone(wr_callback())
2118 self.assertIsNone(wr_f())
2119 self.assertEqual(res, [123])
2120
2121 @classmethod
2122 def run_in_child(cls):
2123 def error():
2124 # Create an atexit finalizer from inside a finalizer called
2125 # at exit. This should be the next to be run.
2126 g1 = weakref.finalize(cls, print, 'g1')
2127 print('f3 error')
2128 1/0
2129
2130 # cls should stay alive till atexit callbacks run
2131 f1 = weakref.finalize(cls, print, 'f1', _global_var)
2132 f2 = weakref.finalize(cls, print, 'f2', _global_var)
2133 f3 = weakref.finalize(cls, error)
2134 f4 = weakref.finalize(cls, print, 'f4', _global_var)
2135
2136 assert f1.atexit == True
2137 f2.atexit = False
2138 assert f3.atexit == True
2139 assert f4.atexit == True
2140
2141 def test_atexit(self):
2142 prog = ('from test.test_weakref import FinalizeTestCase;'+
2143 'FinalizeTestCase.run_in_child()')
2144 rc, out, err = script_helper.assert_python_ok('-c', prog)
2145 out = out.decode('ascii').splitlines()
2146 self.assertEqual(out, ['f4 foobar', 'f3 error', 'g1', 'f1 foobar'])
2147 self.assertTrue(b'ZeroDivisionError' in err)
2148
2149
2150 class ModuleTestCase(unittest.TestCase):
2151 def test_names(self):
2152 for name in ('ReferenceType', 'ProxyType', 'CallableProxyType',
2153 'WeakMethod', 'WeakSet', 'WeakKeyDictionary', 'WeakValueDictionary'):
2154 obj = getattr(weakref, name)
2155 if name != 'WeakSet':
2156 self.assertEqual(obj.__module__, 'weakref')
2157 self.assertEqual(obj.__name__, name)
2158 self.assertEqual(obj.__qualname__, name)
2159
2160
2161 libreftest = """ Doctest for examples in the library reference: weakref.rst
2162
2163 >>> from test.support import gc_collect
2164 >>> import weakref
2165 >>> class Dict(dict):
2166 ... pass
2167 ...
2168 >>> obj = Dict(red=1, green=2, blue=3) # this object is weak referencable
2169 >>> r = weakref.ref(obj)
2170 >>> print(r() is obj)
2171 True
2172
2173 >>> import weakref
2174 >>> class Object:
2175 ... pass
2176 ...
2177 >>> o = Object()
2178 >>> r = weakref.ref(o)
2179 >>> o2 = r()
2180 >>> o is o2
2181 True
2182 >>> del o, o2
2183 >>> gc_collect() # For PyPy or other GCs.
2184 >>> print(r())
2185 None
2186
2187 >>> import weakref
2188 >>> class ExtendedRef(weakref.ref):
2189 ... def __init__(self, ob, callback=None, **annotations):
2190 ... super().__init__(ob, callback)
2191 ... self.__counter = 0
2192 ... for k, v in annotations.items():
2193 ... setattr(self, k, v)
2194 ... def __call__(self):
2195 ... '''Return a pair containing the referent and the number of
2196 ... times the reference has been called.
2197 ... '''
2198 ... ob = super().__call__()
2199 ... if ob is not None:
2200 ... self.__counter += 1
2201 ... ob = (ob, self.__counter)
2202 ... return ob
2203 ...
2204 >>> class A: # not in docs from here, just testing the ExtendedRef
2205 ... pass
2206 ...
2207 >>> a = A()
2208 >>> r = ExtendedRef(a, foo=1, bar="baz")
2209 >>> r.foo
2210 1
2211 >>> r.bar
2212 'baz'
2213 >>> r()[1]
2214 1
2215 >>> r()[1]
2216 2
2217 >>> r()[0] is a
2218 True
2219
2220
2221 >>> import weakref
2222 >>> _id2obj_dict = weakref.WeakValueDictionary()
2223 >>> def remember(obj):
2224 ... oid = id(obj)
2225 ... _id2obj_dict[oid] = obj
2226 ... return oid
2227 ...
2228 >>> def id2obj(oid):
2229 ... return _id2obj_dict[oid]
2230 ...
2231 >>> a = A() # from here, just testing
2232 >>> a_id = remember(a)
2233 >>> id2obj(a_id) is a
2234 True
2235 >>> del a
2236 >>> gc_collect() # For PyPy or other GCs.
2237 >>> try:
2238 ... id2obj(a_id)
2239 ... except KeyError:
2240 ... print('OK')
2241 ... else:
2242 ... print('WeakValueDictionary error')
2243 OK
2244
2245 """
2246
2247 __test__ = {'libreftest' : libreftest}
2248
2249 def load_tests(loader, tests, pattern):
2250 tests.addTest(doctest.DocTestSuite())
2251 return tests
2252
2253
2254 if __name__ == "__main__":
2255 unittest.main()