8 from test import test_support
10 # Used in ReferencesTestCase.test_ref_created_during_del() .
21 def __call__(self, x):
25 def create_function():
29 def create_bound_method():
32 def create_unbound_method():
36 class TestBase(unittest.TestCase):
41 def callback(self, ref):
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.
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):
70 ref1 = weakref.ref(o, self.callback)
71 ref2 = weakref.ref(o, self.callback)
73 self.assert_(ref1() is None,
74 "expected reference to be invalidated")
75 self.assert_(ref2() is None,
76 "expected reference to be invalidated")
77 self.assert_(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):
94 self.ref = weakref.ref(c, callback)
95 ref1 = weakref.ref(c, callback)
98 def test_proxy_ref(self):
101 ref1 = weakref.proxy(o, self.callback)
102 ref2 = weakref.proxy(o, self.callback)
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.assert_(self.cbcalled == 2)
113 def check_basic_ref(self, factory):
116 self.assert_(ref() is not None,
117 "weak reference to live object should be live")
119 self.assert_(o is o2,
120 "<ref>() should return original object if live")
122 def check_basic_callback(self, factory):
125 ref = weakref.ref(o, self.callback)
127 self.assert_(self.cbcalled == 1,
128 "callback did not properly set 'cbcalled'")
129 self.assert_(ref() is None,
130 "ref2 should be dead after deleting object reference")
132 def test_ref_reuse(self):
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.assert_(ref1 is ref2,
140 "reference object w/out callback should be re-used")
143 proxy = weakref.proxy(o)
144 ref1 = weakref.ref(o)
145 ref2 = weakref.ref(o)
146 self.assert_(ref1 is ref2,
147 "reference object w/out callback should be re-used")
148 self.assert_(weakref.getweakrefcount(o) == 2,
149 "wrong weak ref count for object")
151 self.assert_(weakref.getweakrefcount(o) == 1,
152 "wrong weak ref count for object after deleting proxy")
154 def test_proxy_reuse(self):
156 proxy1 = weakref.proxy(o)
158 proxy2 = weakref.proxy(o)
159 self.assert_(proxy1 is proxy2,
160 "proxy object w/out callback should have been re-used")
162 def test_basic_proxy(self):
164 self.check_proxy(o, weakref.proxy(o))
166 L = UserList.UserList()
168 self.failIf(p, "proxy for empty UserList should be false")
170 self.assertEqual(len(L), 1)
171 self.failUnless(p, "proxy for non-empty UserList should be true")
173 self.assertEqual(len(L), 2)
174 self.assertEqual(len(p), 2)
175 self.failUnless(3 in p,
176 "proxy didn't support __contains__() properly")
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_index(self):
197 self.assertEqual(operator.index(p), 10)
199 def test_proxy_div(self):
201 def __floordiv__(self, other):
203 def __ifloordiv__(self, other):
207 self.assertEqual(p // 5, 42)
209 self.assertEqual(p, 21)
211 # The PyWeakref_* C API is documented as allowing either NULL or
212 # None as the value for the callback, where either means "no
213 # callback". The "no callback" ref and proxy objects are supposed
214 # to be shared so long as they exist by all callers so long as
215 # they are active. In Python 2.3.3 and earlier, this guarantee
216 # was not honored, and was broken in different ways for
217 # PyWeakref_NewRef() and PyWeakref_NewProxy(). (Two tests.)
219 def test_shared_ref_without_callback(self):
220 self.check_shared_without_callback(weakref.ref)
222 def test_shared_proxy_without_callback(self):
223 self.check_shared_without_callback(weakref.proxy)
225 def check_shared_without_callback(self, makeref):
227 p1 = makeref(o, None)
228 p2 = makeref(o, None)
229 self.assert_(p1 is p2, "both callbacks were None in the C API")
232 p2 = makeref(o, None)
233 self.assert_(p1 is p2, "callbacks were NULL, None in the C API")
237 self.assert_(p1 is p2, "both callbacks were NULL in the C API")
239 p1 = makeref(o, None)
241 self.assert_(p1 is p2, "callbacks were None, NULL in the C API")
243 def test_callable_proxy(self):
245 ref1 = weakref.proxy(o)
247 self.check_proxy(o, ref1)
249 self.assert_(type(ref1) is weakref.CallableProxyType,
250 "proxy is not of callable type")
252 self.assert_(o.bar == 'twinkies!',
253 "call through proxy not passed through to original")
255 self.assert_(o.bar == 'Splat.',
256 "call through proxy not passed through to original")
258 # expect due to too few args
259 self.assertRaises(TypeError, ref1)
261 # expect due to too many args
262 self.assertRaises(TypeError, ref1, 1, 2, 3)
264 def check_proxy(self, o, proxy):
266 self.assert_(proxy.foo == 1,
267 "proxy does not reflect attribute addition")
269 self.assert_(proxy.foo == 2,
270 "proxy does not reflect attribute modification")
272 self.assert_(not hasattr(proxy, 'foo'),
273 "proxy does not reflect attribute removal")
276 self.assert_(o.foo == 1,
277 "object does not reflect attribute addition via proxy")
281 "object does not reflect attribute modification via proxy")
283 self.assert_(not hasattr(o, 'foo'),
284 "object does not reflect attribute removal via proxy")
286 def test_proxy_deletion(self):
287 # Test clearing of SF bug #762891
290 def __delitem__(self, accessor):
291 self.result = accessor
295 self.assertEqual(f.result, 0)
297 def test_proxy_bool(self):
298 # Test clearing of SF bug #1170766
299 class List(list): pass
301 self.assertEqual(bool(weakref.proxy(lyst)), bool(lyst))
303 def test_getweakrefcount(self):
305 ref1 = weakref.ref(o)
306 ref2 = weakref.ref(o, self.callback)
307 self.assert_(weakref.getweakrefcount(o) == 2,
308 "got wrong number of weak reference objects")
310 proxy1 = weakref.proxy(o)
311 proxy2 = weakref.proxy(o, self.callback)
312 self.assert_(weakref.getweakrefcount(o) == 4,
313 "got wrong number of weak reference objects")
315 del ref1, ref2, proxy1, proxy2
316 self.assert_(weakref.getweakrefcount(o) == 0,
317 "weak reference objects not unlinked from"
318 " referent when discarded.")
320 # assumes ints do not support weakrefs
321 self.assert_(weakref.getweakrefcount(1) == 0,
322 "got wrong number of weak reference objects for int")
324 def test_getweakrefs(self):
326 ref1 = weakref.ref(o, self.callback)
327 ref2 = weakref.ref(o, self.callback)
329 self.assert_(weakref.getweakrefs(o) == [ref2],
330 "list of refs does not match")
333 ref1 = weakref.ref(o, self.callback)
334 ref2 = weakref.ref(o, self.callback)
336 self.assert_(weakref.getweakrefs(o) == [ref1],
337 "list of refs does not match")
340 self.assert_(weakref.getweakrefs(o) == [],
341 "list of refs not cleared")
343 # assumes ints do not support weakrefs
344 self.assert_(weakref.getweakrefs(1) == [],
345 "list of refs does not match for int")
347 def test_newstyle_number_ops(self):
352 self.assert_(p + 1.0 == 3.0)
353 self.assert_(1.0 + p == 3.0) # this used to SEGV
355 def test_callbacks_protected(self):
356 # Callbacks protected from already-set exceptions?
357 # Regression test for SF bug #478534.
358 class BogusError(Exception):
365 data[weakref.ref(f, remove)] = None
372 self.fail("exception not properly restored")
378 self.fail("exception not properly restored")
380 def test_sf_bug_840829(self):
381 # "weakref callbacks and gc corrupt memory"
382 # subtype_dealloc erroneously exposed a new-style instance
383 # already in the process of getting deallocated to gc,
384 # causing double-deallocation if the instance had a weakref
385 # callback that triggered gc.
386 # If the bug exists, there probably won't be an obvious symptom
387 # in a release build. In a debug build, a segfault will occur
388 # when the second attempt to remove the instance from the "list
389 # of all objects" occurs.
397 wr = weakref.ref(c, lambda ignore: gc.collect())
400 # There endeth the first part. It gets worse.
405 wr = weakref.ref(c1.i, lambda ignore: gc.collect())
409 del c1 # still alive because c2 points to it
411 # Now when subtype_dealloc gets called on c2, it's not enough just
412 # that c2 is immune from gc while the weakref callbacks associated
413 # with c2 execute (there are none in this 2nd half of the test, btw).
414 # subtype_dealloc goes on to call the base classes' deallocs too,
415 # so any gc triggered by weakref callbacks associated with anything
416 # torn down by a base class dealloc can also trigger double
417 # deallocation of c2.
420 def test_callback_in_cycle_1(self):
427 def acallback(self, ignore):
432 I.wr = weakref.ref(J, I.acallback)
434 # Now J and II are each in a self-cycle (as all new-style class
435 # objects are, since their __mro__ points back to them). I holds
436 # both a weak reference (I.wr) and a strong reference (I.J) to class
437 # J. I is also in a cycle (I.wr points to a weakref that references
438 # I.acallback). When we del these three, they all become trash, but
439 # the cycles prevent any of them from getting cleaned up immediately.
440 # Instead they have to wait for cyclic gc to deduce that they're
443 # gc used to call tp_clear on all of them, and the order in which
444 # it does that is pretty accidental. The exact order in which we
445 # built up these things manages to provoke gc into running tp_clear
446 # in just the right order (I last). Calling tp_clear on II leaves
447 # behind an insane class object (its __mro__ becomes NULL). Calling
448 # tp_clear on J breaks its self-cycle, but J doesn't get deleted
449 # just then because of the strong reference from I.J. Calling
450 # tp_clear on I starts to clear I's __dict__, and just happens to
451 # clear I.J first -- I.wr is still intact. That removes the last
452 # reference to J, which triggers the weakref callback. The callback
453 # tries to do "self.J", and instances of new-style classes look up
454 # attributes ("J") in the class dict first. The class (II) wants to
455 # search II.__mro__, but that's NULL. The result was a segfault in
456 # a release build, and an assert failure in a debug build.
460 def test_callback_in_cycle_2(self):
463 # This is just like test_callback_in_cycle_1, except that II is an
464 # old-style class. The symptom is different then: an instance of an
465 # old-style class looks in its own __dict__ first. 'J' happens to
466 # get cleared from I.__dict__ before 'wr', and 'J' was never in II's
467 # __dict__, so the attribute isn't found. The difference is that
468 # the old-style II doesn't have a NULL __mro__ (it doesn't have any
469 # __mro__), so no segfault occurs. Instead it got:
470 # test_callback_in_cycle_2 (__main__.ReferencesTestCase) ...
471 # Exception exceptions.AttributeError:
472 # "II instance has no attribute 'J'" in <bound method II.acallback
473 # of <?.II instance at 0x00B9B4B8>> ignored
479 def acallback(self, ignore):
484 I.wr = weakref.ref(J, I.acallback)
489 def test_callback_in_cycle_3(self):
492 # This one broke the first patch that fixed the last two. In this
493 # case, the objects reachable from the callback aren't also reachable
494 # from the object (c1) *triggering* the callback: you can get to
495 # c1 from c2, but not vice-versa. The result was that c2's __dict__
496 # got tp_clear'ed by the time the c2.cb callback got invoked.
499 def cb(self, ignore):
508 c2.wr = weakref.ref(c1, c2.cb)
513 def test_callback_in_cycle_4(self):
516 # Like test_callback_in_cycle_3, except c2 and c1 have different
517 # classes. c2's class (C) isn't reachable from c1 then, so protecting
518 # objects reachable from the dying object (c1) isn't enough to stop
519 # c2's class (C) from getting tp_clear'ed before c2.cb is invoked.
520 # The result was a segfault (C.__mro__ was NULL when the callback
521 # tried to look up self.me).
524 def cb(self, ignore):
536 c2.wr = weakref.ref(c1, c2.cb)
541 def test_callback_in_cycle_resurrection(self):
544 # Do something nasty in a weakref callback: resurrect objects
545 # from dead cycles. For this to be attempted, the weakref and
546 # its callback must also be part of the cyclic trash (else the
547 # objects reachable via the callback couldn't be in cyclic trash
548 # to begin with -- the callback would act like an external root).
549 # But gc clears trash weakrefs with callbacks early now, which
550 # disables the callbacks, so the callbacks shouldn't get called
551 # at all (and so nothing actually gets resurrected).
555 def __init__(self, value):
556 self.attribute = value
558 def acallback(self, ignore):
564 c1.wr = weakref.ref(c2, c1.acallback)
565 c2.wr = weakref.ref(c1, c2.acallback)
567 def C_went_away(ignore):
568 alist.append("C went away")
569 wr = weakref.ref(C, C_went_away)
571 del c1, c2, C # make them all trash
572 self.assertEqual(alist, []) # del isn't enough to reclaim anything
575 # c1.wr and c2.wr were part of the cyclic trash, so should have
576 # been cleared without their callbacks executing. OTOH, the weakref
577 # to C is bound to a function local (wr), and wasn't trash, so that
578 # callback should have been invoked when C went away.
579 self.assertEqual(alist, ["C went away"])
580 # The remaining weakref should be dead now (its callback ran).
581 self.assertEqual(wr(), None)
585 self.assertEqual(alist, [])
587 def test_callbacks_on_callback(self):
590 # Set up weakref callbacks *on* weakref callbacks.
592 def safe_callback(ignore):
593 alist.append("safe_callback called")
596 def cb(self, ignore):
597 alist.append("cb called")
603 c.wr = weakref.ref(d, callback) # this won't trigger
604 d.wr = weakref.ref(callback, d.cb) # ditto
605 external_wr = weakref.ref(callback, safe_callback) # but this will
606 self.assert_(external_wr() is callback)
608 # The weakrefs attached to c and d should get cleared, so that
609 # C.cb is never called. But external_wr isn't part of the cyclic
610 # trash, and no cyclic trash is reachable from it, so safe_callback
611 # should get invoked when the bound method object callback (c.cb)
612 # -- which is itself a callback, and also part of the cyclic trash --
613 # gets reclaimed at the end of gc.
615 del callback, c, d, C
616 self.assertEqual(alist, []) # del isn't enough to clean up cycles
618 self.assertEqual(alist, ["safe_callback called"])
619 self.assertEqual(external_wr(), None)
623 self.assertEqual(alist, [])
625 def test_gc_during_ref_creation(self):
626 self.check_gc_during_creation(weakref.ref)
628 def test_gc_during_proxy_creation(self):
629 self.check_gc_during_creation(weakref.proxy)
631 def check_gc_during_creation(self, makeref):
632 thresholds = gc.get_threshold()
633 gc.set_threshold(1, 1, 1)
645 a.wr = makeref(referenced)
648 # now make sure the object and the ref get labeled as
651 weakref.ref(referenced, callback)
654 gc.set_threshold(*thresholds)
656 def test_ref_created_during_del(self):
658 # A weakref created in an object's __del__() would crash the
659 # interpreter when the weakref was cleaned up since it would refer to
660 # non-existent memory. This test should not segfault the interpreter.
661 class Target(object):
664 ref_from_del = weakref.ref(self)
670 # <weakref to class>.__init__() doesn't check errors correctly
671 r = weakref.ref(Exception)
672 self.assertRaises(TypeError, r.__init__, 0, 0, 0, 0, 0)
673 # No exception should be raised here
677 class SubclassableWeakrefTestCase(TestBase):
679 def test_subclass_refs(self):
680 class MyRef(weakref.ref):
681 def __init__(self, ob, callback=None, value=42):
683 super(MyRef, self).__init__(ob, callback)
686 return super(MyRef, self).__call__()
688 mr = MyRef(o, value=24)
689 self.assert_(mr() is o)
690 self.assert_(mr.called)
691 self.assertEqual(mr.value, 24)
693 self.assert_(mr() is None)
694 self.assert_(mr.called)
696 def test_subclass_refs_dont_replace_standard_refs(self):
697 class MyRef(weakref.ref):
702 self.assert_(r1 is not r2)
703 self.assertEqual(weakref.getweakrefs(o), [r2, r1])
704 self.assertEqual(weakref.getweakrefcount(o), 2)
706 self.assertEqual(weakref.getweakrefcount(o), 3)
707 refs = weakref.getweakrefs(o)
708 self.assertEqual(len(refs), 3)
709 self.assert_(r2 is refs[0])
710 self.assert_(r1 in refs[1:])
711 self.assert_(r3 in refs[1:])
713 def test_subclass_refs_dont_conflate_callbacks(self):
714 class MyRef(weakref.ref):
719 self.assert_(r1 is not r2)
720 refs = weakref.getweakrefs(o)
721 self.assert_(r1 in refs)
722 self.assert_(r2 in refs)
724 def test_subclass_refs_with_slots(self):
725 class MyRef(weakref.ref):
726 __slots__ = "slot1", "slot2"
727 def __new__(type, ob, callback, slot1, slot2):
728 return weakref.ref.__new__(type, ob, callback)
729 def __init__(self, ob, callback, slot1, slot2):
733 return self.slot1 + self.slot2
735 r = MyRef(o, None, "abc", "def")
736 self.assertEqual(r.slot1, "abc")
737 self.assertEqual(r.slot2, "def")
738 self.assertEqual(r.meth(), "abcdef")
739 self.failIf(hasattr(r, "__dict__"))
741 def test_subclass_refs_with_cycle(self):
743 # An instance of a weakref subclass can have attributes.
744 # If such a weakref holds the only strong reference to the object,
745 # deleting the weakref will delete the object. In this case,
746 # the callback must not be called, because the ref object is
748 class MyRef(weakref.ref):
751 # Use a local callback, for "regrtest -R::"
752 # to detect refcounting problems
757 r1 = MyRef(o, callback)
761 del r1 # Used to crash here
763 self.assertEqual(self.cbcalled, 0)
765 # Same test, with two weakrefs to the same object
766 # (since code paths are different)
768 r1 = MyRef(o, callback)
769 r2 = MyRef(o, callback)
775 del r1 # Used to crash here
777 self.assertEqual(self.cbcalled, 0)
781 def __init__(self, arg):
784 return "<Object %r>" % self.arg
787 class MappingTestCase(TestBase):
791 def test_weak_values(self):
793 # This exercises d.copy(), d.items(), d[], del d[], len(d).
795 dict, objects = self.make_weak_valued_dict()
797 self.assert_(weakref.getweakrefcount(o) == 1,
798 "wrong number of weak references to %r!" % o)
799 self.assert_(o is dict[o.arg],
800 "wrong object returned by weak dict!")
801 items1 = dict.items()
802 items2 = dict.copy().items()
805 self.assert_(items1 == items2,
806 "cloning of weak-valued dictionary did not work!")
808 self.assert_(len(dict) == self.COUNT)
810 self.assert_(len(dict) == (self.COUNT - 1),
811 "deleting object did not cause dictionary update")
813 self.assert_(len(dict) == 0,
814 "deleting the values did not clear the dictionary")
815 # regression on SF bug #447152:
816 dict = weakref.WeakValueDictionary()
817 self.assertRaises(KeyError, dict.__getitem__, 1)
819 self.assertRaises(KeyError, dict.__getitem__, 2)
821 def test_weak_keys(self):
823 # This exercises d.copy(), d.items(), d[] = v, d[], del d[],
824 # len(d), d.has_key().
826 dict, objects = self.make_weak_keyed_dict()
828 self.assert_(weakref.getweakrefcount(o) == 1,
829 "wrong number of weak references to %r!" % o)
830 self.assert_(o.arg is dict[o],
831 "wrong object returned by weak dict!")
832 items1 = dict.items()
833 items2 = dict.copy().items()
834 self.assert_(set(items1) == set(items2),
835 "cloning of weak-keyed dictionary did not work!")
837 self.assert_(len(dict) == self.COUNT)
839 self.assert_(len(dict) == (self.COUNT - 1),
840 "deleting object did not cause dictionary update")
842 self.assert_(len(dict) == 0,
843 "deleting the keys did not clear the dictionary")
845 dict[o] = "What is the meaning of the universe?"
846 self.assert_(dict.has_key(o))
847 self.assert_(not dict.has_key(34))
849 def test_weak_keyed_iters(self):
850 dict, objects = self.make_weak_keyed_dict()
851 self.check_iters(dict)
854 refs = dict.keyrefs()
855 self.assertEqual(len(refs), len(objects))
856 objects2 = list(objects)
859 self.assert_(dict.has_key(ob))
860 self.assert_(ob in dict)
861 self.assertEqual(ob.arg, dict[ob])
863 self.assertEqual(len(objects2), 0)
866 objects2 = list(objects)
867 self.assertEqual(len(list(dict.iterkeyrefs())), len(objects))
868 for wr in dict.iterkeyrefs():
870 self.assert_(dict.has_key(ob))
871 self.assert_(ob in dict)
872 self.assertEqual(ob.arg, dict[ob])
874 self.assertEqual(len(objects2), 0)
876 def test_weak_valued_iters(self):
877 dict, objects = self.make_weak_valued_dict()
878 self.check_iters(dict)
881 refs = dict.valuerefs()
882 self.assertEqual(len(refs), len(objects))
883 objects2 = list(objects)
886 self.assertEqual(ob, dict[ob.arg])
887 self.assertEqual(ob.arg, dict[ob.arg].arg)
889 self.assertEqual(len(objects2), 0)
891 # Test itervaluerefs()
892 objects2 = list(objects)
893 self.assertEqual(len(list(dict.itervaluerefs())), len(objects))
894 for wr in dict.itervaluerefs():
896 self.assertEqual(ob, dict[ob.arg])
897 self.assertEqual(ob.arg, dict[ob.arg].arg)
899 self.assertEqual(len(objects2), 0)
901 def check_iters(self, dict):
904 for item in dict.iteritems():
906 self.assert_(len(items) == 0, "iteritems() did not touch all items")
908 # key iterator, via __iter__():
912 self.assert_(len(keys) == 0, "__iter__() did not touch all keys")
914 # key iterator, via iterkeys():
916 for k in dict.iterkeys():
918 self.assert_(len(keys) == 0, "iterkeys() did not touch all keys")
921 values = dict.values()
922 for v in dict.itervalues():
924 self.assert_(len(values) == 0,
925 "itervalues() did not touch all values")
927 def test_make_weak_keyed_dict_from_dict(self):
929 dict = weakref.WeakKeyDictionary({o:364})
930 self.assert_(dict[o] == 364)
932 def test_make_weak_keyed_dict_from_weak_keyed_dict(self):
934 dict = weakref.WeakKeyDictionary({o:364})
935 dict2 = weakref.WeakKeyDictionary(dict)
936 self.assert_(dict[o] == 364)
938 def make_weak_keyed_dict(self):
939 dict = weakref.WeakKeyDictionary()
940 objects = map(Object, range(self.COUNT))
945 def make_weak_valued_dict(self):
946 dict = weakref.WeakValueDictionary()
947 objects = map(Object, range(self.COUNT))
952 def check_popitem(self, klass, key1, value1, key2, value2):
954 weakdict[key1] = value1
955 weakdict[key2] = value2
956 self.assert_(len(weakdict) == 2)
957 k, v = weakdict.popitem()
958 self.assert_(len(weakdict) == 1)
960 self.assert_(v is value1)
962 self.assert_(v is value2)
963 k, v = weakdict.popitem()
964 self.assert_(len(weakdict) == 0)
966 self.assert_(v is value1)
968 self.assert_(v is value2)
970 def test_weak_valued_dict_popitem(self):
971 self.check_popitem(weakref.WeakValueDictionary,
972 "key1", C(), "key2", C())
974 def test_weak_keyed_dict_popitem(self):
975 self.check_popitem(weakref.WeakKeyDictionary,
976 C(), "value 1", C(), "value 2")
978 def check_setdefault(self, klass, key, value1, value2):
979 self.assert_(value1 is not value2,
981 " -- value parameters must be distinct objects")
983 o = weakdict.setdefault(key, value1)
984 self.assert_(o is value1)
985 self.assert_(weakdict.has_key(key))
986 self.assert_(weakdict.get(key) is value1)
987 self.assert_(weakdict[key] is value1)
989 o = weakdict.setdefault(key, value2)
990 self.assert_(o is value1)
991 self.assert_(weakdict.has_key(key))
992 self.assert_(weakdict.get(key) is value1)
993 self.assert_(weakdict[key] is value1)
995 def test_weak_valued_dict_setdefault(self):
996 self.check_setdefault(weakref.WeakValueDictionary,
999 def test_weak_keyed_dict_setdefault(self):
1000 self.check_setdefault(weakref.WeakKeyDictionary,
1001 C(), "value 1", "value 2")
1003 def check_update(self, klass, dict):
1005 # This exercises d.update(), len(d), d.keys(), d.has_key(),
1009 weakdict.update(dict)
1010 self.assert_(len(weakdict) == len(dict))
1011 for k in weakdict.keys():
1012 self.assert_(dict.has_key(k),
1013 "mysterious new key appeared in weak dict")
1015 self.assert_(v is weakdict[k])
1016 self.assert_(v is weakdict.get(k))
1017 for k in dict.keys():
1018 self.assert_(weakdict.has_key(k),
1019 "original key disappeared in weak dict")
1021 self.assert_(v is weakdict[k])
1022 self.assert_(v is weakdict.get(k))
1024 def test_weak_valued_dict_update(self):
1025 self.check_update(weakref.WeakValueDictionary,
1026 {1: C(), 'a': C(), C(): C()})
1028 def test_weak_keyed_dict_update(self):
1029 self.check_update(weakref.WeakKeyDictionary,
1030 {C(): 1, C(): 2, C(): 3})
1032 def test_weak_keyed_delitem(self):
1033 d = weakref.WeakKeyDictionary()
1038 self.assert_(len(d) == 2)
1040 self.assert_(len(d) == 1)
1041 self.assert_(d.keys() == [o2])
1043 def test_weak_valued_delitem(self):
1044 d = weakref.WeakValueDictionary()
1048 d['something else'] = o2
1049 self.assert_(len(d) == 2)
1051 self.assert_(len(d) == 1)
1052 self.assert_(d.items() == [('something else', o2)])
1054 def test_weak_keyed_bad_delitem(self):
1055 d = weakref.WeakKeyDictionary()
1057 # An attempt to delete an object that isn't there should raise
1058 # KeyError. It didn't before 2.3.
1059 self.assertRaises(KeyError, d.__delitem__, o)
1060 self.assertRaises(KeyError, d.__getitem__, o)
1062 # If a key isn't of a weakly referencable type, __getitem__ and
1063 # __setitem__ raise TypeError. __delitem__ should too.
1064 self.assertRaises(TypeError, d.__delitem__, 13)
1065 self.assertRaises(TypeError, d.__getitem__, 13)
1066 self.assertRaises(TypeError, d.__setitem__, 13, 13)
1068 def test_weak_keyed_cascading_deletes(self):
1069 # SF bug 742860. For some reason, before 2.3 __delitem__ iterated
1070 # over the keys via self.data.iterkeys(). If things vanished from
1071 # the dict during this (or got added), that caused a RuntimeError.
1073 d = weakref.WeakKeyDictionary()
1077 def __init__(self, i):
1080 return hash(self.value)
1081 def __eq__(self, other):
1083 # Side effect that mutates the dict, by removing the
1084 # last strong reference to a key.
1086 return self.value == other.value
1088 objs = [C(i) for i in range(4)]
1091 del o # now the only strong references to keys are in objs
1092 # Find the order in which iterkeys sees the keys.
1094 # Reverse it, so that the iteration implementation of __delitem__
1095 # has to keep looping to find the first object we delete.
1098 # Turn on mutation in C.__eq__. The first time thru the loop,
1099 # under the iterkeys() business the first comparison will delete
1100 # the last item iterkeys() would see, and that causes a
1101 # RuntimeError: dictionary changed size during iteration
1102 # when the iterkeys() loop goes around to try comparing the next
1103 # key. After this was fixed, it just deletes the last object *our*
1104 # "for o in obj" loop would have gotten to.
1110 self.assertEqual(len(d), 0)
1111 self.assertEqual(count, 2)
1113 from test import mapping_tests
1115 class WeakValueDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
1116 """Check that WeakValueDictionary conforms to the mapping protocol"""
1117 __ref = {"key1":Object(1), "key2":Object(2), "key3":Object(3)}
1118 type2test = weakref.WeakValueDictionary
1119 def _reference(self):
1120 return self.__ref.copy()
1122 class WeakKeyDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
1123 """Check that WeakKeyDictionary conforms to the mapping protocol"""
1124 __ref = {Object("key1"):1, Object("key2"):2, Object("key3"):3}
1125 type2test = weakref.WeakKeyDictionary
1126 def _reference(self):
1127 return self.__ref.copy()
1129 libreftest = """ Doctest for examples in the library reference: weakref.rst
1132 >>> class Dict(dict):
1135 >>> obj = Dict(red=1, green=2, blue=3) # this object is weak referencable
1136 >>> r = weakref.ref(obj)
1137 >>> print r() is obj
1145 >>> r = weakref.ref(o)
1154 >>> class ExtendedRef(weakref.ref):
1155 ... def __init__(self, ob, callback=None, **annotations):
1156 ... super(ExtendedRef, self).__init__(ob, callback)
1157 ... self.__counter = 0
1158 ... for k, v in annotations.iteritems():
1159 ... setattr(self, k, v)
1160 ... def __call__(self):
1161 ... '''Return a pair containing the referent and the number of
1162 ... times the reference has been called.
1164 ... ob = super(ExtendedRef, self).__call__()
1165 ... if ob is not None:
1166 ... self.__counter += 1
1167 ... ob = (ob, self.__counter)
1170 >>> class A: # not in docs from here, just testing the ExtendedRef
1174 >>> r = ExtendedRef(a, foo=1, bar="baz")
1188 >>> _id2obj_dict = weakref.WeakValueDictionary()
1189 >>> def remember(obj):
1191 ... _id2obj_dict[oid] = obj
1194 >>> def id2obj(oid):
1195 ... return _id2obj_dict[oid]
1197 >>> a = A() # from here, just testing
1198 >>> a_id = remember(a)
1199 >>> id2obj(a_id) is a
1204 ... except KeyError:
1207 ... print 'WeakValueDictionary error'
1212 __test__ = {'libreftest' : libreftest}
1215 test_support.run_unittest(
1218 WeakValueDictionaryTestCase,
1219 WeakKeyDictionaryTestCase,
1220 SubclassableWeakrefTestCase,
1222 test_support.run_doctest(sys.modules[__name__])
1225 if __name__ == "__main__":