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
.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
):
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
.assertTrue(self
.cbcalled
== 2)
113 def check_basic_ref(self
, factory
):
116 self
.assertTrue(ref() is not None,
117 "weak reference to live object should be live")
119 self
.assertTrue(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
.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
):
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")
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")
151 self
.assertTrue(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
.assertTrue(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
.assertFalse(p
, "proxy for empty UserList should be false")
170 self
.assertEqual(len(L
), 1)
171 self
.assertTrue(p
, "proxy for non-empty UserList should be true")
172 with test_support
.check_py3k_warnings():
174 self
.assertEqual(len(L
), 2)
175 self
.assertEqual(len(p
), 2)
176 self
.assertIn(3, p
, "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 with test_support
.check_py3k_warnings():
187 self
.assertEqual(L3
[:], p3
[:])
188 self
.assertEqual(L3
[5:], p3
[5:])
189 self
.assertEqual(L3
[:5], p3
[:5])
190 self
.assertEqual(L3
[2:5], p3
[2:5])
192 def test_proxy_unicode(self
):
197 def __unicode__(self
):
200 self
.assertIn("__unicode__", dir(weakref
.proxy(instance
)))
201 self
.assertEqual(unicode(weakref
.proxy(instance
)), u
"unicode")
203 def test_proxy_index(self
):
209 self
.assertEqual(operator
.index(p
), 10)
211 def test_proxy_div(self
):
213 def __floordiv__(self
, other
):
215 def __ifloordiv__(self
, other
):
219 self
.assertEqual(p
// 5, 42)
221 self
.assertEqual(p
, 21)
223 # The PyWeakref_* C API is documented as allowing either NULL or
224 # None as the value for the callback, where either means "no
225 # callback". The "no callback" ref and proxy objects are supposed
226 # to be shared so long as they exist by all callers so long as
227 # they are active. In Python 2.3.3 and earlier, this guarantee
228 # was not honored, and was broken in different ways for
229 # PyWeakref_NewRef() and PyWeakref_NewProxy(). (Two tests.)
231 def test_shared_ref_without_callback(self
):
232 self
.check_shared_without_callback(weakref
.ref
)
234 def test_shared_proxy_without_callback(self
):
235 self
.check_shared_without_callback(weakref
.proxy
)
237 def check_shared_without_callback(self
, makeref
):
239 p1
= makeref(o
, None)
240 p2
= makeref(o
, None)
241 self
.assertTrue(p1
is p2
, "both callbacks were None in the C API")
244 p2
= makeref(o
, None)
245 self
.assertTrue(p1
is p2
, "callbacks were NULL, None in the C API")
249 self
.assertTrue(p1
is p2
, "both callbacks were NULL in the C API")
251 p1
= makeref(o
, None)
253 self
.assertTrue(p1
is p2
, "callbacks were None, NULL in the C API")
255 def test_callable_proxy(self
):
257 ref1
= weakref
.proxy(o
)
259 self
.check_proxy(o
, ref1
)
261 self
.assertTrue(type(ref1
) is weakref
.CallableProxyType
,
262 "proxy is not of callable type")
264 self
.assertTrue(o
.bar
== 'twinkies!',
265 "call through proxy not passed through to original")
267 self
.assertTrue(o
.bar
== 'Splat.',
268 "call through proxy not passed through to original")
270 # expect due to too few args
271 self
.assertRaises(TypeError, ref1
)
273 # expect due to too many args
274 self
.assertRaises(TypeError, ref1
, 1, 2, 3)
276 def check_proxy(self
, o
, proxy
):
278 self
.assertTrue(proxy
.foo
== 1,
279 "proxy does not reflect attribute addition")
281 self
.assertTrue(proxy
.foo
== 2,
282 "proxy does not reflect attribute modification")
284 self
.assertTrue(not hasattr(proxy
, 'foo'),
285 "proxy does not reflect attribute removal")
288 self
.assertTrue(o
.foo
== 1,
289 "object does not reflect attribute addition via proxy")
293 "object does not reflect attribute modification via proxy")
295 self
.assertTrue(not hasattr(o
, 'foo'),
296 "object does not reflect attribute removal via proxy")
298 def test_proxy_deletion(self
):
299 # Test clearing of SF bug #762891
302 def __delitem__(self
, accessor
):
303 self
.result
= accessor
307 self
.assertEqual(f
.result
, 0)
309 def test_proxy_bool(self
):
310 # Test clearing of SF bug #1170766
311 class List(list): pass
313 self
.assertEqual(bool(weakref
.proxy(lyst
)), bool(lyst
))
315 def test_getweakrefcount(self
):
317 ref1
= weakref
.ref(o
)
318 ref2
= weakref
.ref(o
, self
.callback
)
319 self
.assertTrue(weakref
.getweakrefcount(o
) == 2,
320 "got wrong number of weak reference objects")
322 proxy1
= weakref
.proxy(o
)
323 proxy2
= weakref
.proxy(o
, self
.callback
)
324 self
.assertTrue(weakref
.getweakrefcount(o
) == 4,
325 "got wrong number of weak reference objects")
327 del ref1
, ref2
, proxy1
, proxy2
328 self
.assertTrue(weakref
.getweakrefcount(o
) == 0,
329 "weak reference objects not unlinked from"
330 " referent when discarded.")
332 # assumes ints do not support weakrefs
333 self
.assertTrue(weakref
.getweakrefcount(1) == 0,
334 "got wrong number of weak reference objects for int")
336 def test_getweakrefs(self
):
338 ref1
= weakref
.ref(o
, self
.callback
)
339 ref2
= weakref
.ref(o
, self
.callback
)
341 self
.assertTrue(weakref
.getweakrefs(o
) == [ref2
],
342 "list of refs does not match")
345 ref1
= weakref
.ref(o
, self
.callback
)
346 ref2
= weakref
.ref(o
, self
.callback
)
348 self
.assertTrue(weakref
.getweakrefs(o
) == [ref1
],
349 "list of refs does not match")
352 self
.assertTrue(weakref
.getweakrefs(o
) == [],
353 "list of refs not cleared")
355 # assumes ints do not support weakrefs
356 self
.assertTrue(weakref
.getweakrefs(1) == [],
357 "list of refs does not match for int")
359 def test_newstyle_number_ops(self
):
364 self
.assertTrue(p
+ 1.0 == 3.0)
365 self
.assertTrue(1.0 + p
== 3.0) # this used to SEGV
367 def test_callbacks_protected(self
):
368 # Callbacks protected from already-set exceptions?
369 # Regression test for SF bug #478534.
370 class BogusError(Exception):
377 data
[weakref
.ref(f
, remove
)] = None
384 self
.fail("exception not properly restored")
390 self
.fail("exception not properly restored")
392 def test_sf_bug_840829(self
):
393 # "weakref callbacks and gc corrupt memory"
394 # subtype_dealloc erroneously exposed a new-style instance
395 # already in the process of getting deallocated to gc,
396 # causing double-deallocation if the instance had a weakref
397 # callback that triggered gc.
398 # If the bug exists, there probably won't be an obvious symptom
399 # in a release build. In a debug build, a segfault will occur
400 # when the second attempt to remove the instance from the "list
401 # of all objects" occurs.
409 wr
= weakref
.ref(c
, lambda ignore
: gc
.collect())
412 # There endeth the first part. It gets worse.
417 wr
= weakref
.ref(c1
.i
, lambda ignore
: gc
.collect())
421 del c1
# still alive because c2 points to it
423 # Now when subtype_dealloc gets called on c2, it's not enough just
424 # that c2 is immune from gc while the weakref callbacks associated
425 # with c2 execute (there are none in this 2nd half of the test, btw).
426 # subtype_dealloc goes on to call the base classes' deallocs too,
427 # so any gc triggered by weakref callbacks associated with anything
428 # torn down by a base class dealloc can also trigger double
429 # deallocation of c2.
432 def test_callback_in_cycle_1(self
):
439 def acallback(self
, ignore
):
444 I
.wr
= weakref
.ref(J
, I
.acallback
)
446 # Now J and II are each in a self-cycle (as all new-style class
447 # objects are, since their __mro__ points back to them). I holds
448 # both a weak reference (I.wr) and a strong reference (I.J) to class
449 # J. I is also in a cycle (I.wr points to a weakref that references
450 # I.acallback). When we del these three, they all become trash, but
451 # the cycles prevent any of them from getting cleaned up immediately.
452 # Instead they have to wait for cyclic gc to deduce that they're
455 # gc used to call tp_clear on all of them, and the order in which
456 # it does that is pretty accidental. The exact order in which we
457 # built up these things manages to provoke gc into running tp_clear
458 # in just the right order (I last). Calling tp_clear on II leaves
459 # behind an insane class object (its __mro__ becomes NULL). Calling
460 # tp_clear on J breaks its self-cycle, but J doesn't get deleted
461 # just then because of the strong reference from I.J. Calling
462 # tp_clear on I starts to clear I's __dict__, and just happens to
463 # clear I.J first -- I.wr is still intact. That removes the last
464 # reference to J, which triggers the weakref callback. The callback
465 # tries to do "self.J", and instances of new-style classes look up
466 # attributes ("J") in the class dict first. The class (II) wants to
467 # search II.__mro__, but that's NULL. The result was a segfault in
468 # a release build, and an assert failure in a debug build.
472 def test_callback_in_cycle_2(self
):
475 # This is just like test_callback_in_cycle_1, except that II is an
476 # old-style class. The symptom is different then: an instance of an
477 # old-style class looks in its own __dict__ first. 'J' happens to
478 # get cleared from I.__dict__ before 'wr', and 'J' was never in II's
479 # __dict__, so the attribute isn't found. The difference is that
480 # the old-style II doesn't have a NULL __mro__ (it doesn't have any
481 # __mro__), so no segfault occurs. Instead it got:
482 # test_callback_in_cycle_2 (__main__.ReferencesTestCase) ...
483 # Exception exceptions.AttributeError:
484 # "II instance has no attribute 'J'" in <bound method II.acallback
485 # of <?.II instance at 0x00B9B4B8>> ignored
491 def acallback(self
, ignore
):
496 I
.wr
= weakref
.ref(J
, I
.acallback
)
501 def test_callback_in_cycle_3(self
):
504 # This one broke the first patch that fixed the last two. In this
505 # case, the objects reachable from the callback aren't also reachable
506 # from the object (c1) *triggering* the callback: you can get to
507 # c1 from c2, but not vice-versa. The result was that c2's __dict__
508 # got tp_clear'ed by the time the c2.cb callback got invoked.
511 def cb(self
, ignore
):
520 c2
.wr
= weakref
.ref(c1
, c2
.cb
)
525 def test_callback_in_cycle_4(self
):
528 # Like test_callback_in_cycle_3, except c2 and c1 have different
529 # classes. c2's class (C) isn't reachable from c1 then, so protecting
530 # objects reachable from the dying object (c1) isn't enough to stop
531 # c2's class (C) from getting tp_clear'ed before c2.cb is invoked.
532 # The result was a segfault (C.__mro__ was NULL when the callback
533 # tried to look up self.me).
536 def cb(self
, ignore
):
548 c2
.wr
= weakref
.ref(c1
, c2
.cb
)
553 def test_callback_in_cycle_resurrection(self
):
556 # Do something nasty in a weakref callback: resurrect objects
557 # from dead cycles. For this to be attempted, the weakref and
558 # its callback must also be part of the cyclic trash (else the
559 # objects reachable via the callback couldn't be in cyclic trash
560 # to begin with -- the callback would act like an external root).
561 # But gc clears trash weakrefs with callbacks early now, which
562 # disables the callbacks, so the callbacks shouldn't get called
563 # at all (and so nothing actually gets resurrected).
567 def __init__(self
, value
):
568 self
.attribute
= value
570 def acallback(self
, ignore
):
576 c1
.wr
= weakref
.ref(c2
, c1
.acallback
)
577 c2
.wr
= weakref
.ref(c1
, c2
.acallback
)
579 def C_went_away(ignore
):
580 alist
.append("C went away")
581 wr
= weakref
.ref(C
, C_went_away
)
583 del c1
, c2
, C
# make them all trash
584 self
.assertEqual(alist
, []) # del isn't enough to reclaim anything
587 # c1.wr and c2.wr were part of the cyclic trash, so should have
588 # been cleared without their callbacks executing. OTOH, the weakref
589 # to C is bound to a function local (wr), and wasn't trash, so that
590 # callback should have been invoked when C went away.
591 self
.assertEqual(alist
, ["C went away"])
592 # The remaining weakref should be dead now (its callback ran).
593 self
.assertEqual(wr(), None)
597 self
.assertEqual(alist
, [])
599 def test_callbacks_on_callback(self
):
602 # Set up weakref callbacks *on* weakref callbacks.
604 def safe_callback(ignore
):
605 alist
.append("safe_callback called")
608 def cb(self
, ignore
):
609 alist
.append("cb called")
615 c
.wr
= weakref
.ref(d
, callback
) # this won't trigger
616 d
.wr
= weakref
.ref(callback
, d
.cb
) # ditto
617 external_wr
= weakref
.ref(callback
, safe_callback
) # but this will
618 self
.assertTrue(external_wr() is callback
)
620 # The weakrefs attached to c and d should get cleared, so that
621 # C.cb is never called. But external_wr isn't part of the cyclic
622 # trash, and no cyclic trash is reachable from it, so safe_callback
623 # should get invoked when the bound method object callback (c.cb)
624 # -- which is itself a callback, and also part of the cyclic trash --
625 # gets reclaimed at the end of gc.
627 del callback
, c
, d
, C
628 self
.assertEqual(alist
, []) # del isn't enough to clean up cycles
630 self
.assertEqual(alist
, ["safe_callback called"])
631 self
.assertEqual(external_wr(), None)
635 self
.assertEqual(alist
, [])
637 def test_gc_during_ref_creation(self
):
638 self
.check_gc_during_creation(weakref
.ref
)
640 def test_gc_during_proxy_creation(self
):
641 self
.check_gc_during_creation(weakref
.proxy
)
643 def check_gc_during_creation(self
, makeref
):
644 thresholds
= gc
.get_threshold()
645 gc
.set_threshold(1, 1, 1)
657 a
.wr
= makeref(referenced
)
660 # now make sure the object and the ref get labeled as
663 weakref
.ref(referenced
, callback
)
666 gc
.set_threshold(*thresholds
)
668 def test_ref_created_during_del(self
):
670 # A weakref created in an object's __del__() would crash the
671 # interpreter when the weakref was cleaned up since it would refer to
672 # non-existent memory. This test should not segfault the interpreter.
673 class Target(object):
676 ref_from_del
= weakref
.ref(self
)
682 # <weakref to class>.__init__() doesn't check errors correctly
683 r
= weakref
.ref(Exception)
684 self
.assertRaises(TypeError, r
.__init
__, 0, 0, 0, 0, 0)
685 # No exception should be raised here
688 def test_classes(self
):
689 # Check that both old-style classes and new-style classes
697 a
= weakref
.ref(A
, l
.append
)
700 self
.assertEqual(a(), None)
701 self
.assertEqual(l
, [a
])
702 b
= weakref
.ref(B
, l
.append
)
705 self
.assertEqual(b(), None)
706 self
.assertEqual(l
, [a
, b
])
709 class SubclassableWeakrefTestCase(TestBase
):
711 def test_subclass_refs(self
):
712 class MyRef(weakref
.ref
):
713 def __init__(self
, ob
, callback
=None, value
=42):
715 super(MyRef
, self
).__init
__(ob
, callback
)
718 return super(MyRef
, self
).__call
__()
720 mr
= MyRef(o
, value
=24)
721 self
.assertTrue(mr() is o
)
722 self
.assertTrue(mr
.called
)
723 self
.assertEqual(mr
.value
, 24)
725 self
.assertTrue(mr() is None)
726 self
.assertTrue(mr
.called
)
728 def test_subclass_refs_dont_replace_standard_refs(self
):
729 class MyRef(weakref
.ref
):
734 self
.assertTrue(r1
is not r2
)
735 self
.assertEqual(weakref
.getweakrefs(o
), [r2
, r1
])
736 self
.assertEqual(weakref
.getweakrefcount(o
), 2)
738 self
.assertEqual(weakref
.getweakrefcount(o
), 3)
739 refs
= weakref
.getweakrefs(o
)
740 self
.assertEqual(len(refs
), 3)
741 self
.assertTrue(r2
is refs
[0])
742 self
.assertIn(r1
, refs
[1:])
743 self
.assertIn(r3
, refs
[1:])
745 def test_subclass_refs_dont_conflate_callbacks(self
):
746 class MyRef(weakref
.ref
):
751 self
.assertTrue(r1
is not r2
)
752 refs
= weakref
.getweakrefs(o
)
753 self
.assertIn(r1
, refs
)
754 self
.assertIn(r2
, refs
)
756 def test_subclass_refs_with_slots(self
):
757 class MyRef(weakref
.ref
):
758 __slots__
= "slot1", "slot2"
759 def __new__(type, ob
, callback
, slot1
, slot2
):
760 return weakref
.ref
.__new
__(type, ob
, callback
)
761 def __init__(self
, ob
, callback
, slot1
, slot2
):
765 return self
.slot1
+ self
.slot2
767 r
= MyRef(o
, None, "abc", "def")
768 self
.assertEqual(r
.slot1
, "abc")
769 self
.assertEqual(r
.slot2
, "def")
770 self
.assertEqual(r
.meth(), "abcdef")
771 self
.assertFalse(hasattr(r
, "__dict__"))
773 def test_subclass_refs_with_cycle(self
):
775 # An instance of a weakref subclass can have attributes.
776 # If such a weakref holds the only strong reference to the object,
777 # deleting the weakref will delete the object. In this case,
778 # the callback must not be called, because the ref object is
780 class MyRef(weakref
.ref
):
783 # Use a local callback, for "regrtest -R::"
784 # to detect refcounting problems
789 r1
= MyRef(o
, callback
)
793 del r1
# Used to crash here
795 self
.assertEqual(self
.cbcalled
, 0)
797 # Same test, with two weakrefs to the same object
798 # (since code paths are different)
800 r1
= MyRef(o
, callback
)
801 r2
= MyRef(o
, callback
)
807 del r1
# Used to crash here
809 self
.assertEqual(self
.cbcalled
, 0)
813 def __init__(self
, arg
):
816 return "<Object %r>" % self
.arg
819 class MappingTestCase(TestBase
):
823 def test_weak_values(self
):
825 # This exercises d.copy(), d.items(), d[], del d[], len(d).
827 dict, objects
= self
.make_weak_valued_dict()
829 self
.assertTrue(weakref
.getweakrefcount(o
) == 1,
830 "wrong number of weak references to %r!" % o
)
831 self
.assertTrue(o
is dict[o
.arg
],
832 "wrong object returned by weak dict!")
833 items1
= dict.items()
834 items2
= dict.copy().items()
837 self
.assertTrue(items1
== items2
,
838 "cloning of weak-valued dictionary did not work!")
840 self
.assertTrue(len(dict) == self
.COUNT
)
842 self
.assertTrue(len(dict) == (self
.COUNT
- 1),
843 "deleting object did not cause dictionary update")
845 self
.assertTrue(len(dict) == 0,
846 "deleting the values did not clear the dictionary")
847 # regression on SF bug #447152:
848 dict = weakref
.WeakValueDictionary()
849 self
.assertRaises(KeyError, dict.__getitem
__, 1)
851 self
.assertRaises(KeyError, dict.__getitem
__, 2)
853 def test_weak_keys(self
):
855 # This exercises d.copy(), d.items(), d[] = v, d[], del d[],
858 dict, objects
= self
.make_weak_keyed_dict()
860 self
.assertTrue(weakref
.getweakrefcount(o
) == 1,
861 "wrong number of weak references to %r!" % o
)
862 self
.assertTrue(o
.arg
is dict[o
],
863 "wrong object returned by weak dict!")
864 items1
= dict.items()
865 items2
= dict.copy().items()
866 self
.assertTrue(set(items1
) == set(items2
),
867 "cloning of weak-keyed dictionary did not work!")
869 self
.assertTrue(len(dict) == self
.COUNT
)
871 self
.assertTrue(len(dict) == (self
.COUNT
- 1),
872 "deleting object did not cause dictionary update")
874 self
.assertTrue(len(dict) == 0,
875 "deleting the keys did not clear the dictionary")
877 dict[o
] = "What is the meaning of the universe?"
878 self
.assertIn(o
, dict)
879 self
.assertNotIn(34, dict)
881 def test_weak_keyed_iters(self
):
882 dict, objects
= self
.make_weak_keyed_dict()
883 self
.check_iters(dict)
886 refs
= dict.keyrefs()
887 self
.assertEqual(len(refs
), len(objects
))
888 objects2
= list(objects
)
891 self
.assertIn(ob
, dict)
892 self
.assertEqual(ob
.arg
, dict[ob
])
894 self
.assertEqual(len(objects2
), 0)
897 objects2
= list(objects
)
898 self
.assertEqual(len(list(dict.iterkeyrefs())), len(objects
))
899 for wr
in dict.iterkeyrefs():
901 self
.assertIn(ob
, dict)
902 self
.assertEqual(ob
.arg
, dict[ob
])
904 self
.assertEqual(len(objects2
), 0)
906 def test_weak_valued_iters(self
):
907 dict, objects
= self
.make_weak_valued_dict()
908 self
.check_iters(dict)
911 refs
= dict.valuerefs()
912 self
.assertEqual(len(refs
), len(objects
))
913 objects2
= list(objects
)
916 self
.assertEqual(ob
, dict[ob
.arg
])
917 self
.assertEqual(ob
.arg
, dict[ob
.arg
].arg
)
919 self
.assertEqual(len(objects2
), 0)
921 # Test itervaluerefs()
922 objects2
= list(objects
)
923 self
.assertEqual(len(list(dict.itervaluerefs())), len(objects
))
924 for wr
in dict.itervaluerefs():
926 self
.assertEqual(ob
, dict[ob
.arg
])
927 self
.assertEqual(ob
.arg
, dict[ob
.arg
].arg
)
929 self
.assertEqual(len(objects2
), 0)
931 def check_iters(self
, dict):
934 for item
in dict.iteritems():
936 self
.assertTrue(len(items
) == 0, "iteritems() did not touch all items")
938 # key iterator, via __iter__():
942 self
.assertTrue(len(keys
) == 0, "__iter__() did not touch all keys")
944 # key iterator, via iterkeys():
946 for k
in dict.iterkeys():
948 self
.assertTrue(len(keys
) == 0, "iterkeys() did not touch all keys")
951 values
= dict.values()
952 for v
in dict.itervalues():
954 self
.assertTrue(len(values
) == 0,
955 "itervalues() did not touch all values")
957 def test_make_weak_keyed_dict_from_dict(self
):
959 dict = weakref
.WeakKeyDictionary({o
:364})
960 self
.assertTrue(dict[o
] == 364)
962 def test_make_weak_keyed_dict_from_weak_keyed_dict(self
):
964 dict = weakref
.WeakKeyDictionary({o
:364})
965 dict2
= weakref
.WeakKeyDictionary(dict)
966 self
.assertTrue(dict[o
] == 364)
968 def make_weak_keyed_dict(self
):
969 dict = weakref
.WeakKeyDictionary()
970 objects
= map(Object
, range(self
.COUNT
))
975 def make_weak_valued_dict(self
):
976 dict = weakref
.WeakValueDictionary()
977 objects
= map(Object
, range(self
.COUNT
))
982 def check_popitem(self
, klass
, key1
, value1
, key2
, value2
):
984 weakdict
[key1
] = value1
985 weakdict
[key2
] = value2
986 self
.assertTrue(len(weakdict
) == 2)
987 k
, v
= weakdict
.popitem()
988 self
.assertTrue(len(weakdict
) == 1)
990 self
.assertTrue(v
is value1
)
992 self
.assertTrue(v
is value2
)
993 k
, v
= weakdict
.popitem()
994 self
.assertTrue(len(weakdict
) == 0)
996 self
.assertTrue(v
is value1
)
998 self
.assertTrue(v
is value2
)
1000 def test_weak_valued_dict_popitem(self
):
1001 self
.check_popitem(weakref
.WeakValueDictionary
,
1002 "key1", C(), "key2", C())
1004 def test_weak_keyed_dict_popitem(self
):
1005 self
.check_popitem(weakref
.WeakKeyDictionary
,
1006 C(), "value 1", C(), "value 2")
1008 def check_setdefault(self
, klass
, key
, value1
, value2
):
1009 self
.assertTrue(value1
is not value2
,
1011 " -- value parameters must be distinct objects")
1013 o
= weakdict
.setdefault(key
, value1
)
1014 self
.assertIs(o
, value1
)
1015 self
.assertIn(key
, weakdict
)
1016 self
.assertIs(weakdict
.get(key
), value1
)
1017 self
.assertIs(weakdict
[key
], value1
)
1019 o
= weakdict
.setdefault(key
, value2
)
1020 self
.assertIs(o
, value1
)
1021 self
.assertIn(key
, weakdict
)
1022 self
.assertIs(weakdict
.get(key
), value1
)
1023 self
.assertIs(weakdict
[key
], value1
)
1025 def test_weak_valued_dict_setdefault(self
):
1026 self
.check_setdefault(weakref
.WeakValueDictionary
,
1029 def test_weak_keyed_dict_setdefault(self
):
1030 self
.check_setdefault(weakref
.WeakKeyDictionary
,
1031 C(), "value 1", "value 2")
1033 def check_update(self
, klass
, dict):
1035 # This exercises d.update(), len(d), d.keys(), in d,
1039 weakdict
.update(dict)
1040 self
.assertEqual(len(weakdict
), len(dict))
1041 for k
in weakdict
.keys():
1042 self
.assertIn(k
, dict,
1043 "mysterious new key appeared in weak dict")
1045 self
.assertIs(v
, weakdict
[k
])
1046 self
.assertIs(v
, weakdict
.get(k
))
1047 for k
in dict.keys():
1048 self
.assertIn(k
, weakdict
,
1049 "original key disappeared in weak dict")
1051 self
.assertIs(v
, weakdict
[k
])
1052 self
.assertIs(v
, weakdict
.get(k
))
1054 def test_weak_valued_dict_update(self
):
1055 self
.check_update(weakref
.WeakValueDictionary
,
1056 {1: C(), 'a': C(), C(): C()})
1058 def test_weak_keyed_dict_update(self
):
1059 self
.check_update(weakref
.WeakKeyDictionary
,
1060 {C(): 1, C(): 2, C(): 3})
1062 def test_weak_keyed_delitem(self
):
1063 d
= weakref
.WeakKeyDictionary()
1068 self
.assertTrue(len(d
) == 2)
1070 self
.assertTrue(len(d
) == 1)
1071 self
.assertTrue(d
.keys() == [o2
])
1073 def test_weak_valued_delitem(self
):
1074 d
= weakref
.WeakValueDictionary()
1078 d
['something else'] = o2
1079 self
.assertTrue(len(d
) == 2)
1081 self
.assertTrue(len(d
) == 1)
1082 self
.assertTrue(d
.items() == [('something else', o2
)])
1084 def test_weak_keyed_bad_delitem(self
):
1085 d
= weakref
.WeakKeyDictionary()
1087 # An attempt to delete an object that isn't there should raise
1088 # KeyError. It didn't before 2.3.
1089 self
.assertRaises(KeyError, d
.__delitem
__, o
)
1090 self
.assertRaises(KeyError, d
.__getitem
__, o
)
1092 # If a key isn't of a weakly referencable type, __getitem__ and
1093 # __setitem__ raise TypeError. __delitem__ should too.
1094 self
.assertRaises(TypeError, d
.__delitem
__, 13)
1095 self
.assertRaises(TypeError, d
.__getitem
__, 13)
1096 self
.assertRaises(TypeError, d
.__setitem
__, 13, 13)
1098 def test_weak_keyed_cascading_deletes(self
):
1099 # SF bug 742860. For some reason, before 2.3 __delitem__ iterated
1100 # over the keys via self.data.iterkeys(). If things vanished from
1101 # the dict during this (or got added), that caused a RuntimeError.
1103 d
= weakref
.WeakKeyDictionary()
1107 def __init__(self
, i
):
1110 return hash(self
.value
)
1111 def __eq__(self
, other
):
1113 # Side effect that mutates the dict, by removing the
1114 # last strong reference to a key.
1116 return self
.value
== other
.value
1118 objs
= [C(i
) for i
in range(4)]
1121 del o
# now the only strong references to keys are in objs
1122 # Find the order in which iterkeys sees the keys.
1124 # Reverse it, so that the iteration implementation of __delitem__
1125 # has to keep looping to find the first object we delete.
1128 # Turn on mutation in C.__eq__. The first time thru the loop,
1129 # under the iterkeys() business the first comparison will delete
1130 # the last item iterkeys() would see, and that causes a
1131 # RuntimeError: dictionary changed size during iteration
1132 # when the iterkeys() loop goes around to try comparing the next
1133 # key. After this was fixed, it just deletes the last object *our*
1134 # "for o in obj" loop would have gotten to.
1140 self
.assertEqual(len(d
), 0)
1141 self
.assertEqual(count
, 2)
1143 from test
import mapping_tests
1145 class WeakValueDictionaryTestCase(mapping_tests
.BasicTestMappingProtocol
):
1146 """Check that WeakValueDictionary conforms to the mapping protocol"""
1147 __ref
= {"key1":Object(1), "key2":Object(2), "key3":Object(3)}
1148 type2test
= weakref
.WeakValueDictionary
1149 def _reference(self
):
1150 return self
.__ref
.copy()
1152 class WeakKeyDictionaryTestCase(mapping_tests
.BasicTestMappingProtocol
):
1153 """Check that WeakKeyDictionary conforms to the mapping protocol"""
1154 __ref
= {Object("key1"):1, Object("key2"):2, Object("key3"):3}
1155 type2test
= weakref
.WeakKeyDictionary
1156 def _reference(self
):
1157 return self
.__ref
.copy()
1159 libreftest
= """ Doctest for examples in the library reference: weakref.rst
1162 >>> class Dict(dict):
1165 >>> obj = Dict(red=1, green=2, blue=3) # this object is weak referencable
1166 >>> r = weakref.ref(obj)
1167 >>> print r() is obj
1175 >>> r = weakref.ref(o)
1184 >>> class ExtendedRef(weakref.ref):
1185 ... def __init__(self, ob, callback=None, **annotations):
1186 ... super(ExtendedRef, self).__init__(ob, callback)
1187 ... self.__counter = 0
1188 ... for k, v in annotations.iteritems():
1189 ... setattr(self, k, v)
1190 ... def __call__(self):
1191 ... '''Return a pair containing the referent and the number of
1192 ... times the reference has been called.
1194 ... ob = super(ExtendedRef, self).__call__()
1195 ... if ob is not None:
1196 ... self.__counter += 1
1197 ... ob = (ob, self.__counter)
1200 >>> class A: # not in docs from here, just testing the ExtendedRef
1204 >>> r = ExtendedRef(a, foo=1, bar="baz")
1218 >>> _id2obj_dict = weakref.WeakValueDictionary()
1219 >>> def remember(obj):
1221 ... _id2obj_dict[oid] = obj
1224 >>> def id2obj(oid):
1225 ... return _id2obj_dict[oid]
1227 >>> a = A() # from here, just testing
1228 >>> a_id = remember(a)
1229 >>> id2obj(a_id) is a
1234 ... except KeyError:
1237 ... print 'WeakValueDictionary error'
1242 __test__
= {'libreftest' : libreftest
}
1245 test_support
.run_unittest(
1248 WeakValueDictionaryTestCase
,
1249 WeakKeyDictionaryTestCase
,
1250 SubclassableWeakrefTestCase
,
1252 test_support
.run_doctest(sys
.modules
[__name__
])
1255 if __name__
== "__main__":