Issue #5788: `datetime.timedelta` objects get a new `total_seconds()` method returning
[python.git] / Lib / test / test_weakref.py
blob2106d8cd9bd50796234b7820fd8066712d60dd9f
1 import gc
2 import sys
3 import unittest
4 import UserList
5 import weakref
6 import operator
8 from test import test_support
10 # Used in ReferencesTestCase.test_ref_created_during_del() .
11 ref_from_del = None
13 class C:
14 def method(self):
15 pass
18 class Callable:
19 bar = None
21 def __call__(self, x):
22 self.bar = x
25 def create_function():
26 def f(): pass
27 return f
29 def create_bound_method():
30 return C().method
32 def create_unbound_method():
33 return C.method
36 class TestBase(unittest.TestCase):
38 def setUp(self):
39 self.cbcalled = 0
41 def callback(self, ref):
42 self.cbcalled += 1
45 class ReferencesTestCase(TestBase):
47 def test_basic_ref(self):
48 self.check_basic_ref(C)
49 self.check_basic_ref(create_function)
50 self.check_basic_ref(create_bound_method)
51 self.check_basic_ref(create_unbound_method)
53 # Just make sure the tp_repr handler doesn't raise an exception.
54 # Live reference:
55 o = C()
56 wr = weakref.ref(o)
57 `wr`
58 # Dead reference:
59 del o
60 `wr`
62 def test_basic_callback(self):
63 self.check_basic_callback(C)
64 self.check_basic_callback(create_function)
65 self.check_basic_callback(create_bound_method)
66 self.check_basic_callback(create_unbound_method)
68 def test_multiple_callbacks(self):
69 o = C()
70 ref1 = weakref.ref(o, self.callback)
71 ref2 = weakref.ref(o, self.callback)
72 del o
73 self.assertTrue(ref1() is None,
74 "expected reference to be invalidated")
75 self.assertTrue(ref2() is None,
76 "expected reference to be invalidated")
77 self.assertTrue(self.cbcalled == 2,
78 "callback not called the right number of times")
80 def test_multiple_selfref_callbacks(self):
81 # Make sure all references are invalidated before callbacks are called
83 # What's important here is that we're using the first
84 # reference in the callback invoked on the second reference
85 # (the most recently created ref is cleaned up first). This
86 # tests that all references to the object are invalidated
87 # before any of the callbacks are invoked, so that we only
88 # have one invocation of _weakref.c:cleanup_helper() active
89 # for a particular object at a time.
91 def callback(object, self=self):
92 self.ref()
93 c = C()
94 self.ref = weakref.ref(c, callback)
95 ref1 = weakref.ref(c, callback)
96 del c
98 def test_proxy_ref(self):
99 o = C()
100 o.bar = 1
101 ref1 = weakref.proxy(o, self.callback)
102 ref2 = weakref.proxy(o, self.callback)
103 del o
105 def check(proxy):
106 proxy.bar
108 self.assertRaises(weakref.ReferenceError, check, ref1)
109 self.assertRaises(weakref.ReferenceError, check, ref2)
110 self.assertRaises(weakref.ReferenceError, bool, weakref.proxy(C()))
111 self.assertTrue(self.cbcalled == 2)
113 def check_basic_ref(self, factory):
114 o = factory()
115 ref = weakref.ref(o)
116 self.assertTrue(ref() is not None,
117 "weak reference to live object should be live")
118 o2 = ref()
119 self.assertTrue(o is o2,
120 "<ref>() should return original object if live")
122 def check_basic_callback(self, factory):
123 self.cbcalled = 0
124 o = factory()
125 ref = weakref.ref(o, self.callback)
126 del o
127 self.assertTrue(self.cbcalled == 1,
128 "callback did not properly set 'cbcalled'")
129 self.assertTrue(ref() is None,
130 "ref2 should be dead after deleting object reference")
132 def test_ref_reuse(self):
133 o = C()
134 ref1 = weakref.ref(o)
135 # create a proxy to make sure that there's an intervening creation
136 # between these two; it should make no difference
137 proxy = weakref.proxy(o)
138 ref2 = weakref.ref(o)
139 self.assertTrue(ref1 is ref2,
140 "reference object w/out callback should be re-used")
142 o = C()
143 proxy = weakref.proxy(o)
144 ref1 = weakref.ref(o)
145 ref2 = weakref.ref(o)
146 self.assertTrue(ref1 is ref2,
147 "reference object w/out callback should be re-used")
148 self.assertTrue(weakref.getweakrefcount(o) == 2,
149 "wrong weak ref count for object")
150 del proxy
151 self.assertTrue(weakref.getweakrefcount(o) == 1,
152 "wrong weak ref count for object after deleting proxy")
154 def test_proxy_reuse(self):
155 o = C()
156 proxy1 = weakref.proxy(o)
157 ref = weakref.ref(o)
158 proxy2 = weakref.proxy(o)
159 self.assertTrue(proxy1 is proxy2,
160 "proxy object w/out callback should have been re-used")
162 def test_basic_proxy(self):
163 o = C()
164 self.check_proxy(o, weakref.proxy(o))
166 L = UserList.UserList()
167 p = weakref.proxy(L)
168 self.assertFalse(p, "proxy for empty UserList should be false")
169 p.append(12)
170 self.assertEqual(len(L), 1)
171 self.assertTrue(p, "proxy for non-empty UserList should be true")
172 p[:] = [2, 3]
173 self.assertEqual(len(L), 2)
174 self.assertEqual(len(p), 2)
175 self.assertTrue(3 in p,
176 "proxy didn't support __contains__() properly")
177 p[1] = 5
178 self.assertEqual(L[1], 5)
179 self.assertEqual(p[1], 5)
180 L2 = UserList.UserList(L)
181 p2 = weakref.proxy(L2)
182 self.assertEqual(p, p2)
183 ## self.assertEqual(repr(L2), repr(p2))
184 L3 = UserList.UserList(range(10))
185 p3 = weakref.proxy(L3)
186 self.assertEqual(L3[:], p3[:])
187 self.assertEqual(L3[5:], p3[5:])
188 self.assertEqual(L3[:5], p3[:5])
189 self.assertEqual(L3[2:5], p3[2:5])
191 def test_proxy_unicode(self):
192 # See bug 5037
193 class C(object):
194 def __str__(self):
195 return "string"
196 def __unicode__(self):
197 return u"unicode"
198 instance = C()
199 self.assertTrue("__unicode__" in dir(weakref.proxy(instance)))
200 self.assertEqual(unicode(weakref.proxy(instance)), u"unicode")
202 def test_proxy_index(self):
203 class C:
204 def __index__(self):
205 return 10
206 o = C()
207 p = weakref.proxy(o)
208 self.assertEqual(operator.index(p), 10)
210 def test_proxy_div(self):
211 class C:
212 def __floordiv__(self, other):
213 return 42
214 def __ifloordiv__(self, other):
215 return 21
216 o = C()
217 p = weakref.proxy(o)
218 self.assertEqual(p // 5, 42)
219 p //= 5
220 self.assertEqual(p, 21)
222 # The PyWeakref_* C API is documented as allowing either NULL or
223 # None as the value for the callback, where either means "no
224 # callback". The "no callback" ref and proxy objects are supposed
225 # to be shared so long as they exist by all callers so long as
226 # they are active. In Python 2.3.3 and earlier, this guarantee
227 # was not honored, and was broken in different ways for
228 # PyWeakref_NewRef() and PyWeakref_NewProxy(). (Two tests.)
230 def test_shared_ref_without_callback(self):
231 self.check_shared_without_callback(weakref.ref)
233 def test_shared_proxy_without_callback(self):
234 self.check_shared_without_callback(weakref.proxy)
236 def check_shared_without_callback(self, makeref):
237 o = Object(1)
238 p1 = makeref(o, None)
239 p2 = makeref(o, None)
240 self.assertTrue(p1 is p2, "both callbacks were None in the C API")
241 del p1, p2
242 p1 = makeref(o)
243 p2 = makeref(o, None)
244 self.assertTrue(p1 is p2, "callbacks were NULL, None in the C API")
245 del p1, p2
246 p1 = makeref(o)
247 p2 = makeref(o)
248 self.assertTrue(p1 is p2, "both callbacks were NULL in the C API")
249 del p1, p2
250 p1 = makeref(o, None)
251 p2 = makeref(o)
252 self.assertTrue(p1 is p2, "callbacks were None, NULL in the C API")
254 def test_callable_proxy(self):
255 o = Callable()
256 ref1 = weakref.proxy(o)
258 self.check_proxy(o, ref1)
260 self.assertTrue(type(ref1) is weakref.CallableProxyType,
261 "proxy is not of callable type")
262 ref1('twinkies!')
263 self.assertTrue(o.bar == 'twinkies!',
264 "call through proxy not passed through to original")
265 ref1(x='Splat.')
266 self.assertTrue(o.bar == 'Splat.',
267 "call through proxy not passed through to original")
269 # expect due to too few args
270 self.assertRaises(TypeError, ref1)
272 # expect due to too many args
273 self.assertRaises(TypeError, ref1, 1, 2, 3)
275 def check_proxy(self, o, proxy):
276 o.foo = 1
277 self.assertTrue(proxy.foo == 1,
278 "proxy does not reflect attribute addition")
279 o.foo = 2
280 self.assertTrue(proxy.foo == 2,
281 "proxy does not reflect attribute modification")
282 del o.foo
283 self.assertTrue(not hasattr(proxy, 'foo'),
284 "proxy does not reflect attribute removal")
286 proxy.foo = 1
287 self.assertTrue(o.foo == 1,
288 "object does not reflect attribute addition via proxy")
289 proxy.foo = 2
290 self.assertTrue(
291 o.foo == 2,
292 "object does not reflect attribute modification via proxy")
293 del proxy.foo
294 self.assertTrue(not hasattr(o, 'foo'),
295 "object does not reflect attribute removal via proxy")
297 def test_proxy_deletion(self):
298 # Test clearing of SF bug #762891
299 class Foo:
300 result = None
301 def __delitem__(self, accessor):
302 self.result = accessor
303 g = Foo()
304 f = weakref.proxy(g)
305 del f[0]
306 self.assertEqual(f.result, 0)
308 def test_proxy_bool(self):
309 # Test clearing of SF bug #1170766
310 class List(list): pass
311 lyst = List()
312 self.assertEqual(bool(weakref.proxy(lyst)), bool(lyst))
314 def test_getweakrefcount(self):
315 o = C()
316 ref1 = weakref.ref(o)
317 ref2 = weakref.ref(o, self.callback)
318 self.assertTrue(weakref.getweakrefcount(o) == 2,
319 "got wrong number of weak reference objects")
321 proxy1 = weakref.proxy(o)
322 proxy2 = weakref.proxy(o, self.callback)
323 self.assertTrue(weakref.getweakrefcount(o) == 4,
324 "got wrong number of weak reference objects")
326 del ref1, ref2, proxy1, proxy2
327 self.assertTrue(weakref.getweakrefcount(o) == 0,
328 "weak reference objects not unlinked from"
329 " referent when discarded.")
331 # assumes ints do not support weakrefs
332 self.assertTrue(weakref.getweakrefcount(1) == 0,
333 "got wrong number of weak reference objects for int")
335 def test_getweakrefs(self):
336 o = C()
337 ref1 = weakref.ref(o, self.callback)
338 ref2 = weakref.ref(o, self.callback)
339 del ref1
340 self.assertTrue(weakref.getweakrefs(o) == [ref2],
341 "list of refs does not match")
343 o = C()
344 ref1 = weakref.ref(o, self.callback)
345 ref2 = weakref.ref(o, self.callback)
346 del ref2
347 self.assertTrue(weakref.getweakrefs(o) == [ref1],
348 "list of refs does not match")
350 del ref1
351 self.assertTrue(weakref.getweakrefs(o) == [],
352 "list of refs not cleared")
354 # assumes ints do not support weakrefs
355 self.assertTrue(weakref.getweakrefs(1) == [],
356 "list of refs does not match for int")
358 def test_newstyle_number_ops(self):
359 class F(float):
360 pass
361 f = F(2.0)
362 p = weakref.proxy(f)
363 self.assertTrue(p + 1.0 == 3.0)
364 self.assertTrue(1.0 + p == 3.0) # this used to SEGV
366 def test_callbacks_protected(self):
367 # Callbacks protected from already-set exceptions?
368 # Regression test for SF bug #478534.
369 class BogusError(Exception):
370 pass
371 data = {}
372 def remove(k):
373 del data[k]
374 def encapsulate():
375 f = lambda : ()
376 data[weakref.ref(f, remove)] = None
377 raise BogusError
378 try:
379 encapsulate()
380 except BogusError:
381 pass
382 else:
383 self.fail("exception not properly restored")
384 try:
385 encapsulate()
386 except BogusError:
387 pass
388 else:
389 self.fail("exception not properly restored")
391 def test_sf_bug_840829(self):
392 # "weakref callbacks and gc corrupt memory"
393 # subtype_dealloc erroneously exposed a new-style instance
394 # already in the process of getting deallocated to gc,
395 # causing double-deallocation if the instance had a weakref
396 # callback that triggered gc.
397 # If the bug exists, there probably won't be an obvious symptom
398 # in a release build. In a debug build, a segfault will occur
399 # when the second attempt to remove the instance from the "list
400 # of all objects" occurs.
402 import gc
404 class C(object):
405 pass
407 c = C()
408 wr = weakref.ref(c, lambda ignore: gc.collect())
409 del c
411 # There endeth the first part. It gets worse.
412 del wr
414 c1 = C()
415 c1.i = C()
416 wr = weakref.ref(c1.i, lambda ignore: gc.collect())
418 c2 = C()
419 c2.c1 = c1
420 del c1 # still alive because c2 points to it
422 # Now when subtype_dealloc gets called on c2, it's not enough just
423 # that c2 is immune from gc while the weakref callbacks associated
424 # with c2 execute (there are none in this 2nd half of the test, btw).
425 # subtype_dealloc goes on to call the base classes' deallocs too,
426 # so any gc triggered by weakref callbacks associated with anything
427 # torn down by a base class dealloc can also trigger double
428 # deallocation of c2.
429 del c2
431 def test_callback_in_cycle_1(self):
432 import gc
434 class J(object):
435 pass
437 class II(object):
438 def acallback(self, ignore):
439 self.J
441 I = II()
442 I.J = J
443 I.wr = weakref.ref(J, I.acallback)
445 # Now J and II are each in a self-cycle (as all new-style class
446 # objects are, since their __mro__ points back to them). I holds
447 # both a weak reference (I.wr) and a strong reference (I.J) to class
448 # J. I is also in a cycle (I.wr points to a weakref that references
449 # I.acallback). When we del these three, they all become trash, but
450 # the cycles prevent any of them from getting cleaned up immediately.
451 # Instead they have to wait for cyclic gc to deduce that they're
452 # trash.
454 # gc used to call tp_clear on all of them, and the order in which
455 # it does that is pretty accidental. The exact order in which we
456 # built up these things manages to provoke gc into running tp_clear
457 # in just the right order (I last). Calling tp_clear on II leaves
458 # behind an insane class object (its __mro__ becomes NULL). Calling
459 # tp_clear on J breaks its self-cycle, but J doesn't get deleted
460 # just then because of the strong reference from I.J. Calling
461 # tp_clear on I starts to clear I's __dict__, and just happens to
462 # clear I.J first -- I.wr is still intact. That removes the last
463 # reference to J, which triggers the weakref callback. The callback
464 # tries to do "self.J", and instances of new-style classes look up
465 # attributes ("J") in the class dict first. The class (II) wants to
466 # search II.__mro__, but that's NULL. The result was a segfault in
467 # a release build, and an assert failure in a debug build.
468 del I, J, II
469 gc.collect()
471 def test_callback_in_cycle_2(self):
472 import gc
474 # This is just like test_callback_in_cycle_1, except that II is an
475 # old-style class. The symptom is different then: an instance of an
476 # old-style class looks in its own __dict__ first. 'J' happens to
477 # get cleared from I.__dict__ before 'wr', and 'J' was never in II's
478 # __dict__, so the attribute isn't found. The difference is that
479 # the old-style II doesn't have a NULL __mro__ (it doesn't have any
480 # __mro__), so no segfault occurs. Instead it got:
481 # test_callback_in_cycle_2 (__main__.ReferencesTestCase) ...
482 # Exception exceptions.AttributeError:
483 # "II instance has no attribute 'J'" in <bound method II.acallback
484 # of <?.II instance at 0x00B9B4B8>> ignored
486 class J(object):
487 pass
489 class II:
490 def acallback(self, ignore):
491 self.J
493 I = II()
494 I.J = J
495 I.wr = weakref.ref(J, I.acallback)
497 del I, J, II
498 gc.collect()
500 def test_callback_in_cycle_3(self):
501 import gc
503 # This one broke the first patch that fixed the last two. In this
504 # case, the objects reachable from the callback aren't also reachable
505 # from the object (c1) *triggering* the callback: you can get to
506 # c1 from c2, but not vice-versa. The result was that c2's __dict__
507 # got tp_clear'ed by the time the c2.cb callback got invoked.
509 class C:
510 def cb(self, ignore):
511 self.me
512 self.c1
513 self.wr
515 c1, c2 = C(), C()
517 c2.me = c2
518 c2.c1 = c1
519 c2.wr = weakref.ref(c1, c2.cb)
521 del c1, c2
522 gc.collect()
524 def test_callback_in_cycle_4(self):
525 import gc
527 # Like test_callback_in_cycle_3, except c2 and c1 have different
528 # classes. c2's class (C) isn't reachable from c1 then, so protecting
529 # objects reachable from the dying object (c1) isn't enough to stop
530 # c2's class (C) from getting tp_clear'ed before c2.cb is invoked.
531 # The result was a segfault (C.__mro__ was NULL when the callback
532 # tried to look up self.me).
534 class C(object):
535 def cb(self, ignore):
536 self.me
537 self.c1
538 self.wr
540 class D:
541 pass
543 c1, c2 = D(), C()
545 c2.me = c2
546 c2.c1 = c1
547 c2.wr = weakref.ref(c1, c2.cb)
549 del c1, c2, C, D
550 gc.collect()
552 def test_callback_in_cycle_resurrection(self):
553 import gc
555 # Do something nasty in a weakref callback: resurrect objects
556 # from dead cycles. For this to be attempted, the weakref and
557 # its callback must also be part of the cyclic trash (else the
558 # objects reachable via the callback couldn't be in cyclic trash
559 # to begin with -- the callback would act like an external root).
560 # But gc clears trash weakrefs with callbacks early now, which
561 # disables the callbacks, so the callbacks shouldn't get called
562 # at all (and so nothing actually gets resurrected).
564 alist = []
565 class C(object):
566 def __init__(self, value):
567 self.attribute = value
569 def acallback(self, ignore):
570 alist.append(self.c)
572 c1, c2 = C(1), C(2)
573 c1.c = c2
574 c2.c = c1
575 c1.wr = weakref.ref(c2, c1.acallback)
576 c2.wr = weakref.ref(c1, c2.acallback)
578 def C_went_away(ignore):
579 alist.append("C went away")
580 wr = weakref.ref(C, C_went_away)
582 del c1, c2, C # make them all trash
583 self.assertEqual(alist, []) # del isn't enough to reclaim anything
585 gc.collect()
586 # c1.wr and c2.wr were part of the cyclic trash, so should have
587 # been cleared without their callbacks executing. OTOH, the weakref
588 # to C is bound to a function local (wr), and wasn't trash, so that
589 # callback should have been invoked when C went away.
590 self.assertEqual(alist, ["C went away"])
591 # The remaining weakref should be dead now (its callback ran).
592 self.assertEqual(wr(), None)
594 del alist[:]
595 gc.collect()
596 self.assertEqual(alist, [])
598 def test_callbacks_on_callback(self):
599 import gc
601 # Set up weakref callbacks *on* weakref callbacks.
602 alist = []
603 def safe_callback(ignore):
604 alist.append("safe_callback called")
606 class C(object):
607 def cb(self, ignore):
608 alist.append("cb called")
610 c, d = C(), C()
611 c.other = d
612 d.other = c
613 callback = c.cb
614 c.wr = weakref.ref(d, callback) # this won't trigger
615 d.wr = weakref.ref(callback, d.cb) # ditto
616 external_wr = weakref.ref(callback, safe_callback) # but this will
617 self.assertTrue(external_wr() is callback)
619 # The weakrefs attached to c and d should get cleared, so that
620 # C.cb is never called. But external_wr isn't part of the cyclic
621 # trash, and no cyclic trash is reachable from it, so safe_callback
622 # should get invoked when the bound method object callback (c.cb)
623 # -- which is itself a callback, and also part of the cyclic trash --
624 # gets reclaimed at the end of gc.
626 del callback, c, d, C
627 self.assertEqual(alist, []) # del isn't enough to clean up cycles
628 gc.collect()
629 self.assertEqual(alist, ["safe_callback called"])
630 self.assertEqual(external_wr(), None)
632 del alist[:]
633 gc.collect()
634 self.assertEqual(alist, [])
636 def test_gc_during_ref_creation(self):
637 self.check_gc_during_creation(weakref.ref)
639 def test_gc_during_proxy_creation(self):
640 self.check_gc_during_creation(weakref.proxy)
642 def check_gc_during_creation(self, makeref):
643 thresholds = gc.get_threshold()
644 gc.set_threshold(1, 1, 1)
645 gc.collect()
646 class A:
647 pass
649 def callback(*args):
650 pass
652 referenced = A()
654 a = A()
655 a.a = a
656 a.wr = makeref(referenced)
658 try:
659 # now make sure the object and the ref get labeled as
660 # cyclic trash:
661 a = A()
662 weakref.ref(referenced, callback)
664 finally:
665 gc.set_threshold(*thresholds)
667 def test_ref_created_during_del(self):
668 # Bug #1377858
669 # A weakref created in an object's __del__() would crash the
670 # interpreter when the weakref was cleaned up since it would refer to
671 # non-existent memory. This test should not segfault the interpreter.
672 class Target(object):
673 def __del__(self):
674 global ref_from_del
675 ref_from_del = weakref.ref(self)
677 w = Target()
679 def test_init(self):
680 # Issue 3634
681 # <weakref to class>.__init__() doesn't check errors correctly
682 r = weakref.ref(Exception)
683 self.assertRaises(TypeError, r.__init__, 0, 0, 0, 0, 0)
684 # No exception should be raised here
685 gc.collect()
688 class SubclassableWeakrefTestCase(TestBase):
690 def test_subclass_refs(self):
691 class MyRef(weakref.ref):
692 def __init__(self, ob, callback=None, value=42):
693 self.value = value
694 super(MyRef, self).__init__(ob, callback)
695 def __call__(self):
696 self.called = True
697 return super(MyRef, self).__call__()
698 o = Object("foo")
699 mr = MyRef(o, value=24)
700 self.assertTrue(mr() is o)
701 self.assertTrue(mr.called)
702 self.assertEqual(mr.value, 24)
703 del o
704 self.assertTrue(mr() is None)
705 self.assertTrue(mr.called)
707 def test_subclass_refs_dont_replace_standard_refs(self):
708 class MyRef(weakref.ref):
709 pass
710 o = Object(42)
711 r1 = MyRef(o)
712 r2 = weakref.ref(o)
713 self.assertTrue(r1 is not r2)
714 self.assertEqual(weakref.getweakrefs(o), [r2, r1])
715 self.assertEqual(weakref.getweakrefcount(o), 2)
716 r3 = MyRef(o)
717 self.assertEqual(weakref.getweakrefcount(o), 3)
718 refs = weakref.getweakrefs(o)
719 self.assertEqual(len(refs), 3)
720 self.assertTrue(r2 is refs[0])
721 self.assertTrue(r1 in refs[1:])
722 self.assertTrue(r3 in refs[1:])
724 def test_subclass_refs_dont_conflate_callbacks(self):
725 class MyRef(weakref.ref):
726 pass
727 o = Object(42)
728 r1 = MyRef(o, id)
729 r2 = MyRef(o, str)
730 self.assertTrue(r1 is not r2)
731 refs = weakref.getweakrefs(o)
732 self.assertTrue(r1 in refs)
733 self.assertTrue(r2 in refs)
735 def test_subclass_refs_with_slots(self):
736 class MyRef(weakref.ref):
737 __slots__ = "slot1", "slot2"
738 def __new__(type, ob, callback, slot1, slot2):
739 return weakref.ref.__new__(type, ob, callback)
740 def __init__(self, ob, callback, slot1, slot2):
741 self.slot1 = slot1
742 self.slot2 = slot2
743 def meth(self):
744 return self.slot1 + self.slot2
745 o = Object(42)
746 r = MyRef(o, None, "abc", "def")
747 self.assertEqual(r.slot1, "abc")
748 self.assertEqual(r.slot2, "def")
749 self.assertEqual(r.meth(), "abcdef")
750 self.assertFalse(hasattr(r, "__dict__"))
752 def test_subclass_refs_with_cycle(self):
753 # Bug #3110
754 # An instance of a weakref subclass can have attributes.
755 # If such a weakref holds the only strong reference to the object,
756 # deleting the weakref will delete the object. In this case,
757 # the callback must not be called, because the ref object is
758 # being deleted.
759 class MyRef(weakref.ref):
760 pass
762 # Use a local callback, for "regrtest -R::"
763 # to detect refcounting problems
764 def callback(w):
765 self.cbcalled += 1
767 o = C()
768 r1 = MyRef(o, callback)
769 r1.o = o
770 del o
772 del r1 # Used to crash here
774 self.assertEqual(self.cbcalled, 0)
776 # Same test, with two weakrefs to the same object
777 # (since code paths are different)
778 o = C()
779 r1 = MyRef(o, callback)
780 r2 = MyRef(o, callback)
781 r1.r = r2
782 r2.o = o
783 del o
784 del r2
786 del r1 # Used to crash here
788 self.assertEqual(self.cbcalled, 0)
791 class Object:
792 def __init__(self, arg):
793 self.arg = arg
794 def __repr__(self):
795 return "<Object %r>" % self.arg
798 class MappingTestCase(TestBase):
800 COUNT = 10
802 def test_weak_values(self):
804 # This exercises d.copy(), d.items(), d[], del d[], len(d).
806 dict, objects = self.make_weak_valued_dict()
807 for o in objects:
808 self.assertTrue(weakref.getweakrefcount(o) == 1,
809 "wrong number of weak references to %r!" % o)
810 self.assertTrue(o is dict[o.arg],
811 "wrong object returned by weak dict!")
812 items1 = dict.items()
813 items2 = dict.copy().items()
814 items1.sort()
815 items2.sort()
816 self.assertTrue(items1 == items2,
817 "cloning of weak-valued dictionary did not work!")
818 del items1, items2
819 self.assertTrue(len(dict) == self.COUNT)
820 del objects[0]
821 self.assertTrue(len(dict) == (self.COUNT - 1),
822 "deleting object did not cause dictionary update")
823 del objects, o
824 self.assertTrue(len(dict) == 0,
825 "deleting the values did not clear the dictionary")
826 # regression on SF bug #447152:
827 dict = weakref.WeakValueDictionary()
828 self.assertRaises(KeyError, dict.__getitem__, 1)
829 dict[2] = C()
830 self.assertRaises(KeyError, dict.__getitem__, 2)
832 def test_weak_keys(self):
834 # This exercises d.copy(), d.items(), d[] = v, d[], del d[],
835 # len(d), d.has_key().
837 dict, objects = self.make_weak_keyed_dict()
838 for o in objects:
839 self.assertTrue(weakref.getweakrefcount(o) == 1,
840 "wrong number of weak references to %r!" % o)
841 self.assertTrue(o.arg is dict[o],
842 "wrong object returned by weak dict!")
843 items1 = dict.items()
844 items2 = dict.copy().items()
845 self.assertTrue(set(items1) == set(items2),
846 "cloning of weak-keyed dictionary did not work!")
847 del items1, items2
848 self.assertTrue(len(dict) == self.COUNT)
849 del objects[0]
850 self.assertTrue(len(dict) == (self.COUNT - 1),
851 "deleting object did not cause dictionary update")
852 del objects, o
853 self.assertTrue(len(dict) == 0,
854 "deleting the keys did not clear the dictionary")
855 o = Object(42)
856 dict[o] = "What is the meaning of the universe?"
857 self.assertTrue(dict.has_key(o))
858 self.assertTrue(not dict.has_key(34))
860 def test_weak_keyed_iters(self):
861 dict, objects = self.make_weak_keyed_dict()
862 self.check_iters(dict)
864 # Test keyrefs()
865 refs = dict.keyrefs()
866 self.assertEqual(len(refs), len(objects))
867 objects2 = list(objects)
868 for wr in refs:
869 ob = wr()
870 self.assertTrue(dict.has_key(ob))
871 self.assertTrue(ob in dict)
872 self.assertEqual(ob.arg, dict[ob])
873 objects2.remove(ob)
874 self.assertEqual(len(objects2), 0)
876 # Test iterkeyrefs()
877 objects2 = list(objects)
878 self.assertEqual(len(list(dict.iterkeyrefs())), len(objects))
879 for wr in dict.iterkeyrefs():
880 ob = wr()
881 self.assertTrue(dict.has_key(ob))
882 self.assertTrue(ob in dict)
883 self.assertEqual(ob.arg, dict[ob])
884 objects2.remove(ob)
885 self.assertEqual(len(objects2), 0)
887 def test_weak_valued_iters(self):
888 dict, objects = self.make_weak_valued_dict()
889 self.check_iters(dict)
891 # Test valuerefs()
892 refs = dict.valuerefs()
893 self.assertEqual(len(refs), len(objects))
894 objects2 = list(objects)
895 for wr in refs:
896 ob = wr()
897 self.assertEqual(ob, dict[ob.arg])
898 self.assertEqual(ob.arg, dict[ob.arg].arg)
899 objects2.remove(ob)
900 self.assertEqual(len(objects2), 0)
902 # Test itervaluerefs()
903 objects2 = list(objects)
904 self.assertEqual(len(list(dict.itervaluerefs())), len(objects))
905 for wr in dict.itervaluerefs():
906 ob = wr()
907 self.assertEqual(ob, dict[ob.arg])
908 self.assertEqual(ob.arg, dict[ob.arg].arg)
909 objects2.remove(ob)
910 self.assertEqual(len(objects2), 0)
912 def check_iters(self, dict):
913 # item iterator:
914 items = dict.items()
915 for item in dict.iteritems():
916 items.remove(item)
917 self.assertTrue(len(items) == 0, "iteritems() did not touch all items")
919 # key iterator, via __iter__():
920 keys = dict.keys()
921 for k in dict:
922 keys.remove(k)
923 self.assertTrue(len(keys) == 0, "__iter__() did not touch all keys")
925 # key iterator, via iterkeys():
926 keys = dict.keys()
927 for k in dict.iterkeys():
928 keys.remove(k)
929 self.assertTrue(len(keys) == 0, "iterkeys() did not touch all keys")
931 # value iterator:
932 values = dict.values()
933 for v in dict.itervalues():
934 values.remove(v)
935 self.assertTrue(len(values) == 0,
936 "itervalues() did not touch all values")
938 def test_make_weak_keyed_dict_from_dict(self):
939 o = Object(3)
940 dict = weakref.WeakKeyDictionary({o:364})
941 self.assertTrue(dict[o] == 364)
943 def test_make_weak_keyed_dict_from_weak_keyed_dict(self):
944 o = Object(3)
945 dict = weakref.WeakKeyDictionary({o:364})
946 dict2 = weakref.WeakKeyDictionary(dict)
947 self.assertTrue(dict[o] == 364)
949 def make_weak_keyed_dict(self):
950 dict = weakref.WeakKeyDictionary()
951 objects = map(Object, range(self.COUNT))
952 for o in objects:
953 dict[o] = o.arg
954 return dict, objects
956 def make_weak_valued_dict(self):
957 dict = weakref.WeakValueDictionary()
958 objects = map(Object, range(self.COUNT))
959 for o in objects:
960 dict[o.arg] = o
961 return dict, objects
963 def check_popitem(self, klass, key1, value1, key2, value2):
964 weakdict = klass()
965 weakdict[key1] = value1
966 weakdict[key2] = value2
967 self.assertTrue(len(weakdict) == 2)
968 k, v = weakdict.popitem()
969 self.assertTrue(len(weakdict) == 1)
970 if k is key1:
971 self.assertTrue(v is value1)
972 else:
973 self.assertTrue(v is value2)
974 k, v = weakdict.popitem()
975 self.assertTrue(len(weakdict) == 0)
976 if k is key1:
977 self.assertTrue(v is value1)
978 else:
979 self.assertTrue(v is value2)
981 def test_weak_valued_dict_popitem(self):
982 self.check_popitem(weakref.WeakValueDictionary,
983 "key1", C(), "key2", C())
985 def test_weak_keyed_dict_popitem(self):
986 self.check_popitem(weakref.WeakKeyDictionary,
987 C(), "value 1", C(), "value 2")
989 def check_setdefault(self, klass, key, value1, value2):
990 self.assertTrue(value1 is not value2,
991 "invalid test"
992 " -- value parameters must be distinct objects")
993 weakdict = klass()
994 o = weakdict.setdefault(key, value1)
995 self.assertTrue(o is value1)
996 self.assertTrue(weakdict.has_key(key))
997 self.assertTrue(weakdict.get(key) is value1)
998 self.assertTrue(weakdict[key] is value1)
1000 o = weakdict.setdefault(key, value2)
1001 self.assertTrue(o is value1)
1002 self.assertTrue(weakdict.has_key(key))
1003 self.assertTrue(weakdict.get(key) is value1)
1004 self.assertTrue(weakdict[key] is value1)
1006 def test_weak_valued_dict_setdefault(self):
1007 self.check_setdefault(weakref.WeakValueDictionary,
1008 "key", C(), C())
1010 def test_weak_keyed_dict_setdefault(self):
1011 self.check_setdefault(weakref.WeakKeyDictionary,
1012 C(), "value 1", "value 2")
1014 def check_update(self, klass, dict):
1016 # This exercises d.update(), len(d), d.keys(), d.has_key(),
1017 # d.get(), d[].
1019 weakdict = klass()
1020 weakdict.update(dict)
1021 self.assertTrue(len(weakdict) == len(dict))
1022 for k in weakdict.keys():
1023 self.assertTrue(dict.has_key(k),
1024 "mysterious new key appeared in weak dict")
1025 v = dict.get(k)
1026 self.assertTrue(v is weakdict[k])
1027 self.assertTrue(v is weakdict.get(k))
1028 for k in dict.keys():
1029 self.assertTrue(weakdict.has_key(k),
1030 "original key disappeared in weak dict")
1031 v = dict[k]
1032 self.assertTrue(v is weakdict[k])
1033 self.assertTrue(v is weakdict.get(k))
1035 def test_weak_valued_dict_update(self):
1036 self.check_update(weakref.WeakValueDictionary,
1037 {1: C(), 'a': C(), C(): C()})
1039 def test_weak_keyed_dict_update(self):
1040 self.check_update(weakref.WeakKeyDictionary,
1041 {C(): 1, C(): 2, C(): 3})
1043 def test_weak_keyed_delitem(self):
1044 d = weakref.WeakKeyDictionary()
1045 o1 = Object('1')
1046 o2 = Object('2')
1047 d[o1] = 'something'
1048 d[o2] = 'something'
1049 self.assertTrue(len(d) == 2)
1050 del d[o1]
1051 self.assertTrue(len(d) == 1)
1052 self.assertTrue(d.keys() == [o2])
1054 def test_weak_valued_delitem(self):
1055 d = weakref.WeakValueDictionary()
1056 o1 = Object('1')
1057 o2 = Object('2')
1058 d['something'] = o1
1059 d['something else'] = o2
1060 self.assertTrue(len(d) == 2)
1061 del d['something']
1062 self.assertTrue(len(d) == 1)
1063 self.assertTrue(d.items() == [('something else', o2)])
1065 def test_weak_keyed_bad_delitem(self):
1066 d = weakref.WeakKeyDictionary()
1067 o = Object('1')
1068 # An attempt to delete an object that isn't there should raise
1069 # KeyError. It didn't before 2.3.
1070 self.assertRaises(KeyError, d.__delitem__, o)
1071 self.assertRaises(KeyError, d.__getitem__, o)
1073 # If a key isn't of a weakly referencable type, __getitem__ and
1074 # __setitem__ raise TypeError. __delitem__ should too.
1075 self.assertRaises(TypeError, d.__delitem__, 13)
1076 self.assertRaises(TypeError, d.__getitem__, 13)
1077 self.assertRaises(TypeError, d.__setitem__, 13, 13)
1079 def test_weak_keyed_cascading_deletes(self):
1080 # SF bug 742860. For some reason, before 2.3 __delitem__ iterated
1081 # over the keys via self.data.iterkeys(). If things vanished from
1082 # the dict during this (or got added), that caused a RuntimeError.
1084 d = weakref.WeakKeyDictionary()
1085 mutate = False
1087 class C(object):
1088 def __init__(self, i):
1089 self.value = i
1090 def __hash__(self):
1091 return hash(self.value)
1092 def __eq__(self, other):
1093 if mutate:
1094 # Side effect that mutates the dict, by removing the
1095 # last strong reference to a key.
1096 del objs[-1]
1097 return self.value == other.value
1099 objs = [C(i) for i in range(4)]
1100 for o in objs:
1101 d[o] = o.value
1102 del o # now the only strong references to keys are in objs
1103 # Find the order in which iterkeys sees the keys.
1104 objs = d.keys()
1105 # Reverse it, so that the iteration implementation of __delitem__
1106 # has to keep looping to find the first object we delete.
1107 objs.reverse()
1109 # Turn on mutation in C.__eq__. The first time thru the loop,
1110 # under the iterkeys() business the first comparison will delete
1111 # the last item iterkeys() would see, and that causes a
1112 # RuntimeError: dictionary changed size during iteration
1113 # when the iterkeys() loop goes around to try comparing the next
1114 # key. After this was fixed, it just deletes the last object *our*
1115 # "for o in obj" loop would have gotten to.
1116 mutate = True
1117 count = 0
1118 for o in objs:
1119 count += 1
1120 del d[o]
1121 self.assertEqual(len(d), 0)
1122 self.assertEqual(count, 2)
1124 from test import mapping_tests
1126 class WeakValueDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
1127 """Check that WeakValueDictionary conforms to the mapping protocol"""
1128 __ref = {"key1":Object(1), "key2":Object(2), "key3":Object(3)}
1129 type2test = weakref.WeakValueDictionary
1130 def _reference(self):
1131 return self.__ref.copy()
1133 class WeakKeyDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
1134 """Check that WeakKeyDictionary conforms to the mapping protocol"""
1135 __ref = {Object("key1"):1, Object("key2"):2, Object("key3"):3}
1136 type2test = weakref.WeakKeyDictionary
1137 def _reference(self):
1138 return self.__ref.copy()
1140 libreftest = """ Doctest for examples in the library reference: weakref.rst
1142 >>> import weakref
1143 >>> class Dict(dict):
1144 ... pass
1146 >>> obj = Dict(red=1, green=2, blue=3) # this object is weak referencable
1147 >>> r = weakref.ref(obj)
1148 >>> print r() is obj
1149 True
1151 >>> import weakref
1152 >>> class Object:
1153 ... pass
1155 >>> o = Object()
1156 >>> r = weakref.ref(o)
1157 >>> o2 = r()
1158 >>> o is o2
1159 True
1160 >>> del o, o2
1161 >>> print r()
1162 None
1164 >>> import weakref
1165 >>> class ExtendedRef(weakref.ref):
1166 ... def __init__(self, ob, callback=None, **annotations):
1167 ... super(ExtendedRef, self).__init__(ob, callback)
1168 ... self.__counter = 0
1169 ... for k, v in annotations.iteritems():
1170 ... setattr(self, k, v)
1171 ... def __call__(self):
1172 ... '''Return a pair containing the referent and the number of
1173 ... times the reference has been called.
1174 ... '''
1175 ... ob = super(ExtendedRef, self).__call__()
1176 ... if ob is not None:
1177 ... self.__counter += 1
1178 ... ob = (ob, self.__counter)
1179 ... return ob
1181 >>> class A: # not in docs from here, just testing the ExtendedRef
1182 ... pass
1184 >>> a = A()
1185 >>> r = ExtendedRef(a, foo=1, bar="baz")
1186 >>> r.foo
1188 >>> r.bar
1189 'baz'
1190 >>> r()[1]
1192 >>> r()[1]
1194 >>> r()[0] is a
1195 True
1198 >>> import weakref
1199 >>> _id2obj_dict = weakref.WeakValueDictionary()
1200 >>> def remember(obj):
1201 ... oid = id(obj)
1202 ... _id2obj_dict[oid] = obj
1203 ... return oid
1205 >>> def id2obj(oid):
1206 ... return _id2obj_dict[oid]
1208 >>> a = A() # from here, just testing
1209 >>> a_id = remember(a)
1210 >>> id2obj(a_id) is a
1211 True
1212 >>> del a
1213 >>> try:
1214 ... id2obj(a_id)
1215 ... except KeyError:
1216 ... print 'OK'
1217 ... else:
1218 ... print 'WeakValueDictionary error'
1223 __test__ = {'libreftest' : libreftest}
1225 def test_main():
1226 test_support.run_unittest(
1227 ReferencesTestCase,
1228 MappingTestCase,
1229 WeakValueDictionaryTestCase,
1230 WeakKeyDictionaryTestCase,
1231 SubclassableWeakrefTestCase,
1233 test_support.run_doctest(sys.modules[__name__])
1236 if __name__ == "__main__":
1237 test_main()