blob: e7b6ed23062fdcfbf0a41aae313d97e429ad15f6 [file] [log] [blame]
Fred Drakebc875f52004-02-04 23:14:14 +00001import gc
Fred Drake41deb1e2001-02-01 05:27:45 +00002import sys
Fred Drakeb0fefc52001-03-23 04:22:45 +00003import unittest
Fred Drake5935ff02001-12-19 16:54:23 +00004import UserList
Fred Drake41deb1e2001-02-01 05:27:45 +00005import weakref
6
Barry Warsaw04f357c2002-07-23 19:04:11 +00007from test import test_support
Fred Drake41deb1e2001-02-01 05:27:45 +00008
Brett Cannon75ba0752007-01-23 22:41:20 +00009# Used in ReferencesTestCase.test_ref_created_during_del() .
10ref_from_del = None
Fred Drake41deb1e2001-02-01 05:27:45 +000011
12class C:
Fred Drakeb0fefc52001-03-23 04:22:45 +000013 def method(self):
14 pass
Fred Drake41deb1e2001-02-01 05:27:45 +000015
16
Fred Drakeb0fefc52001-03-23 04:22:45 +000017class Callable:
18 bar = None
Fred Drake41deb1e2001-02-01 05:27:45 +000019
Fred Drakeb0fefc52001-03-23 04:22:45 +000020 def __call__(self, x):
21 self.bar = x
Fred Drake41deb1e2001-02-01 05:27:45 +000022
23
Fred Drakeb0fefc52001-03-23 04:22:45 +000024def create_function():
25 def f(): pass
26 return f
27
28def create_bound_method():
29 return C().method
30
31def create_unbound_method():
32 return C.method
Fred Drake41deb1e2001-02-01 05:27:45 +000033
34
Fred Drakeb0fefc52001-03-23 04:22:45 +000035class TestBase(unittest.TestCase):
36
37 def setUp(self):
38 self.cbcalled = 0
39
40 def callback(self, ref):
41 self.cbcalled += 1
Fred Drake41deb1e2001-02-01 05:27:45 +000042
43
Fred Drakeb0fefc52001-03-23 04:22:45 +000044class ReferencesTestCase(TestBase):
Fred Drake41deb1e2001-02-01 05:27:45 +000045
Fred Drakeb0fefc52001-03-23 04:22:45 +000046 def test_basic_ref(self):
47 self.check_basic_ref(C)
48 self.check_basic_ref(create_function)
49 self.check_basic_ref(create_bound_method)
50 self.check_basic_ref(create_unbound_method)
Fred Drake41deb1e2001-02-01 05:27:45 +000051
Fred Drake43735da2002-04-11 03:59:42 +000052 # Just make sure the tp_repr handler doesn't raise an exception.
53 # Live reference:
54 o = C()
55 wr = weakref.ref(o)
56 `wr`
57 # Dead reference:
58 del o
59 `wr`
60
Fred Drakeb0fefc52001-03-23 04:22:45 +000061 def test_basic_callback(self):
62 self.check_basic_callback(C)
63 self.check_basic_callback(create_function)
64 self.check_basic_callback(create_bound_method)
65 self.check_basic_callback(create_unbound_method)
Fred Drake41deb1e2001-02-01 05:27:45 +000066
Fred Drakeb0fefc52001-03-23 04:22:45 +000067 def test_multiple_callbacks(self):
68 o = C()
69 ref1 = weakref.ref(o, self.callback)
70 ref2 = weakref.ref(o, self.callback)
71 del o
72 self.assert_(ref1() is None,
73 "expected reference to be invalidated")
74 self.assert_(ref2() is None,
75 "expected reference to be invalidated")
76 self.assert_(self.cbcalled == 2,
77 "callback not called the right number of times")
Fred Drake41deb1e2001-02-01 05:27:45 +000078
Fred Drake705088e2001-04-13 17:18:15 +000079 def test_multiple_selfref_callbacks(self):
Guido van Rossum9eee5542002-08-22 20:21:30 +000080 # Make sure all references are invalidated before callbacks are called
Fred Drake705088e2001-04-13 17:18:15 +000081 #
82 # What's important here is that we're using the first
83 # reference in the callback invoked on the second reference
84 # (the most recently created ref is cleaned up first). This
85 # tests that all references to the object are invalidated
86 # before any of the callbacks are invoked, so that we only
87 # have one invocation of _weakref.c:cleanup_helper() active
88 # for a particular object at a time.
89 #
90 def callback(object, self=self):
91 self.ref()
92 c = C()
93 self.ref = weakref.ref(c, callback)
94 ref1 = weakref.ref(c, callback)
95 del c
96
Fred Drakeb0fefc52001-03-23 04:22:45 +000097 def test_proxy_ref(self):
98 o = C()
99 o.bar = 1
100 ref1 = weakref.proxy(o, self.callback)
101 ref2 = weakref.proxy(o, self.callback)
102 del o
Fred Drake41deb1e2001-02-01 05:27:45 +0000103
Fred Drakeb0fefc52001-03-23 04:22:45 +0000104 def check(proxy):
105 proxy.bar
Fred Drake41deb1e2001-02-01 05:27:45 +0000106
Fred Drakeb0fefc52001-03-23 04:22:45 +0000107 self.assertRaises(weakref.ReferenceError, check, ref1)
108 self.assertRaises(weakref.ReferenceError, check, ref2)
Neal Norwitzbdcb9412004-07-08 01:22:31 +0000109 self.assertRaises(weakref.ReferenceError, bool, weakref.proxy(C()))
Fred Drakeb0fefc52001-03-23 04:22:45 +0000110 self.assert_(self.cbcalled == 2)
Fred Drake41deb1e2001-02-01 05:27:45 +0000111
Fred Drakeb0fefc52001-03-23 04:22:45 +0000112 def check_basic_ref(self, factory):
113 o = factory()
114 ref = weakref.ref(o)
115 self.assert_(ref() is not None,
116 "weak reference to live object should be live")
117 o2 = ref()
118 self.assert_(o is o2,
119 "<ref>() should return original object if live")
Fred Drake41deb1e2001-02-01 05:27:45 +0000120
Fred Drakeb0fefc52001-03-23 04:22:45 +0000121 def check_basic_callback(self, factory):
122 self.cbcalled = 0
123 o = factory()
124 ref = weakref.ref(o, self.callback)
125 del o
Fred Drake705088e2001-04-13 17:18:15 +0000126 self.assert_(self.cbcalled == 1,
127 "callback did not properly set 'cbcalled'")
128 self.assert_(ref() is None,
129 "ref2 should be dead after deleting object reference")
Fred Drake41deb1e2001-02-01 05:27:45 +0000130
Fred Drakeb0fefc52001-03-23 04:22:45 +0000131 def test_ref_reuse(self):
132 o = C()
133 ref1 = weakref.ref(o)
134 # create a proxy to make sure that there's an intervening creation
135 # between these two; it should make no difference
136 proxy = weakref.proxy(o)
137 ref2 = weakref.ref(o)
138 self.assert_(ref1 is ref2,
139 "reference object w/out callback should be re-used")
Fred Drake41deb1e2001-02-01 05:27:45 +0000140
Fred Drakeb0fefc52001-03-23 04:22:45 +0000141 o = C()
142 proxy = weakref.proxy(o)
143 ref1 = weakref.ref(o)
144 ref2 = weakref.ref(o)
145 self.assert_(ref1 is ref2,
146 "reference object w/out callback should be re-used")
147 self.assert_(weakref.getweakrefcount(o) == 2,
148 "wrong weak ref count for object")
149 del proxy
150 self.assert_(weakref.getweakrefcount(o) == 1,
151 "wrong weak ref count for object after deleting proxy")
Fred Drake41deb1e2001-02-01 05:27:45 +0000152
Fred Drakeb0fefc52001-03-23 04:22:45 +0000153 def test_proxy_reuse(self):
154 o = C()
155 proxy1 = weakref.proxy(o)
156 ref = weakref.ref(o)
157 proxy2 = weakref.proxy(o)
158 self.assert_(proxy1 is proxy2,
159 "proxy object w/out callback should have been re-used")
160
161 def test_basic_proxy(self):
162 o = C()
163 self.check_proxy(o, weakref.proxy(o))
164
Fred Drake5935ff02001-12-19 16:54:23 +0000165 L = UserList.UserList()
166 p = weakref.proxy(L)
167 self.failIf(p, "proxy for empty UserList should be false")
168 p.append(12)
169 self.assertEqual(len(L), 1)
170 self.failUnless(p, "proxy for non-empty UserList should be true")
171 p[:] = [2, 3]
172 self.assertEqual(len(L), 2)
173 self.assertEqual(len(p), 2)
Fred Drakef425b1e2003-07-14 21:37:17 +0000174 self.failUnless(3 in p,
175 "proxy didn't support __contains__() properly")
Fred Drake5935ff02001-12-19 16:54:23 +0000176 p[1] = 5
177 self.assertEqual(L[1], 5)
178 self.assertEqual(p[1], 5)
179 L2 = UserList.UserList(L)
180 p2 = weakref.proxy(L2)
181 self.assertEqual(p, p2)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000182 ## self.assertEqual(repr(L2), repr(p2))
Fred Drake43735da2002-04-11 03:59:42 +0000183 L3 = UserList.UserList(range(10))
184 p3 = weakref.proxy(L3)
185 self.assertEqual(L3[:], p3[:])
186 self.assertEqual(L3[5:], p3[5:])
187 self.assertEqual(L3[:5], p3[:5])
188 self.assertEqual(L3[2:5], p3[2:5])
Fred Drake5935ff02001-12-19 16:54:23 +0000189
Fred Drakeea2adc92004-02-03 19:56:46 +0000190 # The PyWeakref_* C API is documented as allowing either NULL or
191 # None as the value for the callback, where either means "no
192 # callback". The "no callback" ref and proxy objects are supposed
193 # to be shared so long as they exist by all callers so long as
194 # they are active. In Python 2.3.3 and earlier, this guaranttee
195 # was not honored, and was broken in different ways for
196 # PyWeakref_NewRef() and PyWeakref_NewProxy(). (Two tests.)
197
198 def test_shared_ref_without_callback(self):
199 self.check_shared_without_callback(weakref.ref)
200
201 def test_shared_proxy_without_callback(self):
202 self.check_shared_without_callback(weakref.proxy)
203
204 def check_shared_without_callback(self, makeref):
205 o = Object(1)
206 p1 = makeref(o, None)
207 p2 = makeref(o, None)
208 self.assert_(p1 is p2, "both callbacks were None in the C API")
209 del p1, p2
210 p1 = makeref(o)
211 p2 = makeref(o, None)
212 self.assert_(p1 is p2, "callbacks were NULL, None in the C API")
213 del p1, p2
214 p1 = makeref(o)
215 p2 = makeref(o)
216 self.assert_(p1 is p2, "both callbacks were NULL in the C API")
217 del p1, p2
218 p1 = makeref(o, None)
219 p2 = makeref(o)
220 self.assert_(p1 is p2, "callbacks were None, NULL in the C API")
221
Fred Drakeb0fefc52001-03-23 04:22:45 +0000222 def test_callable_proxy(self):
223 o = Callable()
224 ref1 = weakref.proxy(o)
225
226 self.check_proxy(o, ref1)
227
228 self.assert_(type(ref1) is weakref.CallableProxyType,
229 "proxy is not of callable type")
230 ref1('twinkies!')
231 self.assert_(o.bar == 'twinkies!',
232 "call through proxy not passed through to original")
Fred Drake3bb4d212001-10-18 19:28:29 +0000233 ref1(x='Splat.')
234 self.assert_(o.bar == 'Splat.',
235 "call through proxy not passed through to original")
Fred Drakeb0fefc52001-03-23 04:22:45 +0000236
237 # expect due to too few args
238 self.assertRaises(TypeError, ref1)
239
240 # expect due to too many args
241 self.assertRaises(TypeError, ref1, 1, 2, 3)
242
243 def check_proxy(self, o, proxy):
244 o.foo = 1
245 self.assert_(proxy.foo == 1,
246 "proxy does not reflect attribute addition")
247 o.foo = 2
248 self.assert_(proxy.foo == 2,
249 "proxy does not reflect attribute modification")
250 del o.foo
251 self.assert_(not hasattr(proxy, 'foo'),
252 "proxy does not reflect attribute removal")
253
254 proxy.foo = 1
255 self.assert_(o.foo == 1,
256 "object does not reflect attribute addition via proxy")
257 proxy.foo = 2
258 self.assert_(
259 o.foo == 2,
260 "object does not reflect attribute modification via proxy")
261 del proxy.foo
262 self.assert_(not hasattr(o, 'foo'),
263 "object does not reflect attribute removal via proxy")
264
Raymond Hettingerd693a812003-06-30 04:18:48 +0000265 def test_proxy_deletion(self):
266 # Test clearing of SF bug #762891
267 class Foo:
268 result = None
269 def __delitem__(self, accessor):
270 self.result = accessor
271 g = Foo()
272 f = weakref.proxy(g)
273 del f[0]
274 self.assertEqual(f.result, 0)
275
Raymond Hettingere6c470f2005-03-27 03:04:54 +0000276 def test_proxy_bool(self):
277 # Test clearing of SF bug #1170766
278 class List(list): pass
279 lyst = List()
280 self.assertEqual(bool(weakref.proxy(lyst)), bool(lyst))
281
Fred Drakeb0fefc52001-03-23 04:22:45 +0000282 def test_getweakrefcount(self):
283 o = C()
284 ref1 = weakref.ref(o)
285 ref2 = weakref.ref(o, self.callback)
286 self.assert_(weakref.getweakrefcount(o) == 2,
287 "got wrong number of weak reference objects")
288
289 proxy1 = weakref.proxy(o)
290 proxy2 = weakref.proxy(o, self.callback)
291 self.assert_(weakref.getweakrefcount(o) == 4,
292 "got wrong number of weak reference objects")
293
Fred Drakeea2adc92004-02-03 19:56:46 +0000294 del ref1, ref2, proxy1, proxy2
295 self.assert_(weakref.getweakrefcount(o) == 0,
296 "weak reference objects not unlinked from"
297 " referent when discarded.")
298
Walter Dörwaldb167b042003-12-11 12:34:05 +0000299 # assumes ints do not support weakrefs
300 self.assert_(weakref.getweakrefcount(1) == 0,
301 "got wrong number of weak reference objects for int")
302
Fred Drakeb0fefc52001-03-23 04:22:45 +0000303 def test_getweakrefs(self):
304 o = C()
305 ref1 = weakref.ref(o, self.callback)
306 ref2 = weakref.ref(o, self.callback)
307 del ref1
308 self.assert_(weakref.getweakrefs(o) == [ref2],
309 "list of refs does not match")
310
311 o = C()
312 ref1 = weakref.ref(o, self.callback)
313 ref2 = weakref.ref(o, self.callback)
314 del ref2
315 self.assert_(weakref.getweakrefs(o) == [ref1],
316 "list of refs does not match")
317
Fred Drakeea2adc92004-02-03 19:56:46 +0000318 del ref1
319 self.assert_(weakref.getweakrefs(o) == [],
320 "list of refs not cleared")
321
Walter Dörwaldb167b042003-12-11 12:34:05 +0000322 # assumes ints do not support weakrefs
323 self.assert_(weakref.getweakrefs(1) == [],
324 "list of refs does not match for int")
325
Fred Drake39c27f12001-10-18 18:06:05 +0000326 def test_newstyle_number_ops(self):
327 class F(float):
328 pass
329 f = F(2.0)
330 p = weakref.proxy(f)
331 self.assert_(p + 1.0 == 3.0)
332 self.assert_(1.0 + p == 3.0) # this used to SEGV
333
Fred Drake2a64f462001-12-10 23:46:02 +0000334 def test_callbacks_protected(self):
Guido van Rossum9eee5542002-08-22 20:21:30 +0000335 # Callbacks protected from already-set exceptions?
Fred Drake2a64f462001-12-10 23:46:02 +0000336 # Regression test for SF bug #478534.
337 class BogusError(Exception):
338 pass
339 data = {}
340 def remove(k):
341 del data[k]
342 def encapsulate():
343 f = lambda : ()
344 data[weakref.ref(f, remove)] = None
345 raise BogusError
346 try:
347 encapsulate()
348 except BogusError:
349 pass
350 else:
351 self.fail("exception not properly restored")
352 try:
353 encapsulate()
354 except BogusError:
355 pass
356 else:
357 self.fail("exception not properly restored")
358
Tim Petersadd09b42003-11-12 20:43:28 +0000359 def test_sf_bug_840829(self):
360 # "weakref callbacks and gc corrupt memory"
361 # subtype_dealloc erroneously exposed a new-style instance
362 # already in the process of getting deallocated to gc,
363 # causing double-deallocation if the instance had a weakref
364 # callback that triggered gc.
365 # If the bug exists, there probably won't be an obvious symptom
366 # in a release build. In a debug build, a segfault will occur
367 # when the second attempt to remove the instance from the "list
368 # of all objects" occurs.
369
370 import gc
371
372 class C(object):
373 pass
374
375 c = C()
376 wr = weakref.ref(c, lambda ignore: gc.collect())
377 del c
378
Tim Petersf7f9e992003-11-13 21:59:32 +0000379 # There endeth the first part. It gets worse.
380 del wr
381
382 c1 = C()
383 c1.i = C()
384 wr = weakref.ref(c1.i, lambda ignore: gc.collect())
385
386 c2 = C()
387 c2.c1 = c1
388 del c1 # still alive because c2 points to it
389
390 # Now when subtype_dealloc gets called on c2, it's not enough just
391 # that c2 is immune from gc while the weakref callbacks associated
392 # with c2 execute (there are none in this 2nd half of the test, btw).
393 # subtype_dealloc goes on to call the base classes' deallocs too,
394 # so any gc triggered by weakref callbacks associated with anything
395 # torn down by a base class dealloc can also trigger double
396 # deallocation of c2.
397 del c2
Fred Drake41deb1e2001-02-01 05:27:45 +0000398
Tim Peters403a2032003-11-20 21:21:46 +0000399 def test_callback_in_cycle_1(self):
400 import gc
401
402 class J(object):
403 pass
404
405 class II(object):
406 def acallback(self, ignore):
407 self.J
408
409 I = II()
410 I.J = J
411 I.wr = weakref.ref(J, I.acallback)
412
413 # Now J and II are each in a self-cycle (as all new-style class
414 # objects are, since their __mro__ points back to them). I holds
415 # both a weak reference (I.wr) and a strong reference (I.J) to class
416 # J. I is also in a cycle (I.wr points to a weakref that references
417 # I.acallback). When we del these three, they all become trash, but
418 # the cycles prevent any of them from getting cleaned up immediately.
419 # Instead they have to wait for cyclic gc to deduce that they're
420 # trash.
421 #
422 # gc used to call tp_clear on all of them, and the order in which
423 # it does that is pretty accidental. The exact order in which we
424 # built up these things manages to provoke gc into running tp_clear
425 # in just the right order (I last). Calling tp_clear on II leaves
426 # behind an insane class object (its __mro__ becomes NULL). Calling
427 # tp_clear on J breaks its self-cycle, but J doesn't get deleted
428 # just then because of the strong reference from I.J. Calling
429 # tp_clear on I starts to clear I's __dict__, and just happens to
430 # clear I.J first -- I.wr is still intact. That removes the last
431 # reference to J, which triggers the weakref callback. The callback
432 # tries to do "self.J", and instances of new-style classes look up
433 # attributes ("J") in the class dict first. The class (II) wants to
434 # search II.__mro__, but that's NULL. The result was a segfault in
435 # a release build, and an assert failure in a debug build.
436 del I, J, II
437 gc.collect()
438
439 def test_callback_in_cycle_2(self):
440 import gc
441
442 # This is just like test_callback_in_cycle_1, except that II is an
443 # old-style class. The symptom is different then: an instance of an
444 # old-style class looks in its own __dict__ first. 'J' happens to
445 # get cleared from I.__dict__ before 'wr', and 'J' was never in II's
446 # __dict__, so the attribute isn't found. The difference is that
447 # the old-style II doesn't have a NULL __mro__ (it doesn't have any
448 # __mro__), so no segfault occurs. Instead it got:
449 # test_callback_in_cycle_2 (__main__.ReferencesTestCase) ...
450 # Exception exceptions.AttributeError:
451 # "II instance has no attribute 'J'" in <bound method II.acallback
452 # of <?.II instance at 0x00B9B4B8>> ignored
453
454 class J(object):
455 pass
456
457 class II:
458 def acallback(self, ignore):
459 self.J
460
461 I = II()
462 I.J = J
463 I.wr = weakref.ref(J, I.acallback)
464
465 del I, J, II
466 gc.collect()
467
468 def test_callback_in_cycle_3(self):
469 import gc
470
471 # This one broke the first patch that fixed the last two. In this
472 # case, the objects reachable from the callback aren't also reachable
473 # from the object (c1) *triggering* the callback: you can get to
474 # c1 from c2, but not vice-versa. The result was that c2's __dict__
475 # got tp_clear'ed by the time the c2.cb callback got invoked.
476
477 class C:
478 def cb(self, ignore):
479 self.me
480 self.c1
481 self.wr
482
483 c1, c2 = C(), C()
484
485 c2.me = c2
486 c2.c1 = c1
487 c2.wr = weakref.ref(c1, c2.cb)
488
489 del c1, c2
490 gc.collect()
491
492 def test_callback_in_cycle_4(self):
493 import gc
494
495 # Like test_callback_in_cycle_3, except c2 and c1 have different
496 # classes. c2's class (C) isn't reachable from c1 then, so protecting
497 # objects reachable from the dying object (c1) isn't enough to stop
498 # c2's class (C) from getting tp_clear'ed before c2.cb is invoked.
499 # The result was a segfault (C.__mro__ was NULL when the callback
500 # tried to look up self.me).
501
502 class C(object):
503 def cb(self, ignore):
504 self.me
505 self.c1
506 self.wr
507
508 class D:
509 pass
510
511 c1, c2 = D(), C()
512
513 c2.me = c2
514 c2.c1 = c1
515 c2.wr = weakref.ref(c1, c2.cb)
516
517 del c1, c2, C, D
518 gc.collect()
519
520 def test_callback_in_cycle_resurrection(self):
521 import gc
522
523 # Do something nasty in a weakref callback: resurrect objects
524 # from dead cycles. For this to be attempted, the weakref and
525 # its callback must also be part of the cyclic trash (else the
526 # objects reachable via the callback couldn't be in cyclic trash
527 # to begin with -- the callback would act like an external root).
528 # But gc clears trash weakrefs with callbacks early now, which
529 # disables the callbacks, so the callbacks shouldn't get called
530 # at all (and so nothing actually gets resurrected).
531
532 alist = []
533 class C(object):
534 def __init__(self, value):
535 self.attribute = value
536
537 def acallback(self, ignore):
538 alist.append(self.c)
539
540 c1, c2 = C(1), C(2)
541 c1.c = c2
542 c2.c = c1
543 c1.wr = weakref.ref(c2, c1.acallback)
544 c2.wr = weakref.ref(c1, c2.acallback)
545
546 def C_went_away(ignore):
547 alist.append("C went away")
548 wr = weakref.ref(C, C_went_away)
549
550 del c1, c2, C # make them all trash
551 self.assertEqual(alist, []) # del isn't enough to reclaim anything
552
553 gc.collect()
554 # c1.wr and c2.wr were part of the cyclic trash, so should have
555 # been cleared without their callbacks executing. OTOH, the weakref
556 # to C is bound to a function local (wr), and wasn't trash, so that
557 # callback should have been invoked when C went away.
558 self.assertEqual(alist, ["C went away"])
559 # The remaining weakref should be dead now (its callback ran).
560 self.assertEqual(wr(), None)
561
562 del alist[:]
563 gc.collect()
564 self.assertEqual(alist, [])
565
566 def test_callbacks_on_callback(self):
567 import gc
568
569 # Set up weakref callbacks *on* weakref callbacks.
570 alist = []
571 def safe_callback(ignore):
572 alist.append("safe_callback called")
573
574 class C(object):
575 def cb(self, ignore):
576 alist.append("cb called")
577
578 c, d = C(), C()
579 c.other = d
580 d.other = c
581 callback = c.cb
582 c.wr = weakref.ref(d, callback) # this won't trigger
583 d.wr = weakref.ref(callback, d.cb) # ditto
584 external_wr = weakref.ref(callback, safe_callback) # but this will
585 self.assert_(external_wr() is callback)
586
587 # The weakrefs attached to c and d should get cleared, so that
588 # C.cb is never called. But external_wr isn't part of the cyclic
589 # trash, and no cyclic trash is reachable from it, so safe_callback
590 # should get invoked when the bound method object callback (c.cb)
591 # -- which is itself a callback, and also part of the cyclic trash --
592 # gets reclaimed at the end of gc.
593
594 del callback, c, d, C
595 self.assertEqual(alist, []) # del isn't enough to clean up cycles
596 gc.collect()
597 self.assertEqual(alist, ["safe_callback called"])
598 self.assertEqual(external_wr(), None)
599
600 del alist[:]
601 gc.collect()
602 self.assertEqual(alist, [])
603
Fred Drakebc875f52004-02-04 23:14:14 +0000604 def test_gc_during_ref_creation(self):
605 self.check_gc_during_creation(weakref.ref)
606
607 def test_gc_during_proxy_creation(self):
608 self.check_gc_during_creation(weakref.proxy)
609
610 def check_gc_during_creation(self, makeref):
611 thresholds = gc.get_threshold()
612 gc.set_threshold(1, 1, 1)
613 gc.collect()
Fred Drake55cf4342004-02-13 19:21:57 +0000614 class A:
615 pass
Fred Drakebc875f52004-02-04 23:14:14 +0000616
617 def callback(*args):
618 pass
619
Fred Drake55cf4342004-02-13 19:21:57 +0000620 referenced = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000621
Fred Drake55cf4342004-02-13 19:21:57 +0000622 a = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000623 a.a = a
624 a.wr = makeref(referenced)
625
626 try:
627 # now make sure the object and the ref get labeled as
628 # cyclic trash:
Fred Drake55cf4342004-02-13 19:21:57 +0000629 a = A()
630 weakref.ref(referenced, callback)
Fred Drakebc875f52004-02-04 23:14:14 +0000631
632 finally:
633 gc.set_threshold(*thresholds)
634
Brett Cannon75ba0752007-01-23 22:41:20 +0000635 def test_ref_created_during_del(self):
636 # Bug #1377858
637 # A weakref created in an object's __del__() would crash the
638 # interpreter when the weakref was cleaned up since it would refer to
639 # non-existent memory. This test should not segfault the interpreter.
640 class Target(object):
641 def __del__(self):
642 global ref_from_del
643 ref_from_del = weakref.ref(self)
644
645 w = Target()
646
Fred Drake0a4dd392004-07-02 18:57:45 +0000647
Amaury Forgeot d'Arc3255e132008-06-16 19:22:42 +0000648class SubclassableWeakrefTestCase(TestBase):
Fred Drake0a4dd392004-07-02 18:57:45 +0000649
650 def test_subclass_refs(self):
651 class MyRef(weakref.ref):
652 def __init__(self, ob, callback=None, value=42):
653 self.value = value
654 super(MyRef, self).__init__(ob, callback)
655 def __call__(self):
656 self.called = True
657 return super(MyRef, self).__call__()
658 o = Object("foo")
659 mr = MyRef(o, value=24)
660 self.assert_(mr() is o)
661 self.assert_(mr.called)
662 self.assertEqual(mr.value, 24)
663 del o
664 self.assert_(mr() is None)
665 self.assert_(mr.called)
666
667 def test_subclass_refs_dont_replace_standard_refs(self):
668 class MyRef(weakref.ref):
669 pass
670 o = Object(42)
671 r1 = MyRef(o)
672 r2 = weakref.ref(o)
673 self.assert_(r1 is not r2)
674 self.assertEqual(weakref.getweakrefs(o), [r2, r1])
675 self.assertEqual(weakref.getweakrefcount(o), 2)
676 r3 = MyRef(o)
677 self.assertEqual(weakref.getweakrefcount(o), 3)
678 refs = weakref.getweakrefs(o)
679 self.assertEqual(len(refs), 3)
680 self.assert_(r2 is refs[0])
681 self.assert_(r1 in refs[1:])
682 self.assert_(r3 in refs[1:])
683
684 def test_subclass_refs_dont_conflate_callbacks(self):
685 class MyRef(weakref.ref):
686 pass
687 o = Object(42)
688 r1 = MyRef(o, id)
689 r2 = MyRef(o, str)
690 self.assert_(r1 is not r2)
691 refs = weakref.getweakrefs(o)
692 self.assert_(r1 in refs)
693 self.assert_(r2 in refs)
694
695 def test_subclass_refs_with_slots(self):
696 class MyRef(weakref.ref):
697 __slots__ = "slot1", "slot2"
698 def __new__(type, ob, callback, slot1, slot2):
699 return weakref.ref.__new__(type, ob, callback)
700 def __init__(self, ob, callback, slot1, slot2):
701 self.slot1 = slot1
702 self.slot2 = slot2
703 def meth(self):
704 return self.slot1 + self.slot2
705 o = Object(42)
706 r = MyRef(o, None, "abc", "def")
707 self.assertEqual(r.slot1, "abc")
708 self.assertEqual(r.slot2, "def")
709 self.assertEqual(r.meth(), "abcdef")
710 self.failIf(hasattr(r, "__dict__"))
711
Amaury Forgeot d'Arc3255e132008-06-16 19:22:42 +0000712 def test_subclass_refs_with_cycle(self):
713 # Bug #3110
714 # An instance of a weakref subclass can have attributes.
715 # If such a weakref holds the only strong reference to the object,
716 # deleting the weakref will delete the object. In this case,
717 # the callback must not be called, because the ref object is
718 # being deleted.
719 class MyRef(weakref.ref):
720 pass
721
722 # Use a local callback, for "regrtest -R::"
723 # to detect refcounting problems
724 def callback(w):
725 self.cbcalled += 1
726
727 o = C()
728 r1 = MyRef(o, callback)
729 r1.o = o
730 del o
731
732 del r1 # Used to crash here
733
734 self.assertEqual(self.cbcalled, 0)
735
736 # Same test, with two weakrefs to the same object
737 # (since code paths are different)
738 o = C()
739 r1 = MyRef(o, callback)
740 r2 = MyRef(o, callback)
741 r1.r = r2
742 r2.o = o
743 del o
744 del r2
745
746 del r1 # Used to crash here
747
748 self.assertEqual(self.cbcalled, 0)
749
Fred Drake0a4dd392004-07-02 18:57:45 +0000750
Fred Drake41deb1e2001-02-01 05:27:45 +0000751class Object:
752 def __init__(self, arg):
753 self.arg = arg
754 def __repr__(self):
755 return "<Object %r>" % self.arg
756
Fred Drake41deb1e2001-02-01 05:27:45 +0000757
Fred Drakeb0fefc52001-03-23 04:22:45 +0000758class MappingTestCase(TestBase):
Martin v. Löwis5e163332001-02-27 18:36:56 +0000759
Fred Drakeb0fefc52001-03-23 04:22:45 +0000760 COUNT = 10
761
762 def test_weak_values(self):
Fred Drake0e540c32001-05-02 05:44:22 +0000763 #
764 # This exercises d.copy(), d.items(), d[], del d[], len(d).
765 #
766 dict, objects = self.make_weak_valued_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +0000767 for o in objects:
768 self.assert_(weakref.getweakrefcount(o) == 1,
769 "wrong number of weak references to %r!" % o)
770 self.assert_(o is dict[o.arg],
771 "wrong object returned by weak dict!")
772 items1 = dict.items()
773 items2 = dict.copy().items()
774 items1.sort()
775 items2.sort()
776 self.assert_(items1 == items2,
777 "cloning of weak-valued dictionary did not work!")
778 del items1, items2
779 self.assert_(len(dict) == self.COUNT)
780 del objects[0]
781 self.assert_(len(dict) == (self.COUNT - 1),
782 "deleting object did not cause dictionary update")
783 del objects, o
784 self.assert_(len(dict) == 0,
785 "deleting the values did not clear the dictionary")
Fred Drake4fd06e02001-08-03 04:11:27 +0000786 # regression on SF bug #447152:
787 dict = weakref.WeakValueDictionary()
788 self.assertRaises(KeyError, dict.__getitem__, 1)
789 dict[2] = C()
790 self.assertRaises(KeyError, dict.__getitem__, 2)
Fred Drakeb0fefc52001-03-23 04:22:45 +0000791
792 def test_weak_keys(self):
Fred Drake0e540c32001-05-02 05:44:22 +0000793 #
794 # This exercises d.copy(), d.items(), d[] = v, d[], del d[],
Fred Drake752eda42001-11-06 16:38:34 +0000795 # len(d), d.has_key().
Fred Drake0e540c32001-05-02 05:44:22 +0000796 #
797 dict, objects = self.make_weak_keyed_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +0000798 for o in objects:
799 self.assert_(weakref.getweakrefcount(o) == 1,
800 "wrong number of weak references to %r!" % o)
801 self.assert_(o.arg is dict[o],
802 "wrong object returned by weak dict!")
803 items1 = dict.items()
804 items2 = dict.copy().items()
Raymond Hettingera690a992003-11-16 16:17:49 +0000805 self.assert_(set(items1) == set(items2),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000806 "cloning of weak-keyed dictionary did not work!")
807 del items1, items2
808 self.assert_(len(dict) == self.COUNT)
809 del objects[0]
810 self.assert_(len(dict) == (self.COUNT - 1),
811 "deleting object did not cause dictionary update")
812 del objects, o
813 self.assert_(len(dict) == 0,
814 "deleting the keys did not clear the dictionary")
Fred Drake752eda42001-11-06 16:38:34 +0000815 o = Object(42)
816 dict[o] = "What is the meaning of the universe?"
817 self.assert_(dict.has_key(o))
818 self.assert_(not dict.has_key(34))
Martin v. Löwis5e163332001-02-27 18:36:56 +0000819
Fred Drake0e540c32001-05-02 05:44:22 +0000820 def test_weak_keyed_iters(self):
821 dict, objects = self.make_weak_keyed_dict()
822 self.check_iters(dict)
823
Fred Drake017e68c2006-05-02 06:53:59 +0000824 # Test keyrefs()
825 refs = dict.keyrefs()
826 self.assertEqual(len(refs), len(objects))
827 objects2 = list(objects)
828 for wr in refs:
829 ob = wr()
830 self.assert_(dict.has_key(ob))
831 self.assert_(ob in dict)
832 self.assertEqual(ob.arg, dict[ob])
833 objects2.remove(ob)
834 self.assertEqual(len(objects2), 0)
835
836 # Test iterkeyrefs()
837 objects2 = list(objects)
838 self.assertEqual(len(list(dict.iterkeyrefs())), len(objects))
839 for wr in dict.iterkeyrefs():
840 ob = wr()
841 self.assert_(dict.has_key(ob))
842 self.assert_(ob in dict)
843 self.assertEqual(ob.arg, dict[ob])
844 objects2.remove(ob)
845 self.assertEqual(len(objects2), 0)
846
Fred Drake0e540c32001-05-02 05:44:22 +0000847 def test_weak_valued_iters(self):
848 dict, objects = self.make_weak_valued_dict()
849 self.check_iters(dict)
850
Fred Drake017e68c2006-05-02 06:53:59 +0000851 # Test valuerefs()
852 refs = dict.valuerefs()
853 self.assertEqual(len(refs), len(objects))
854 objects2 = list(objects)
855 for wr in refs:
856 ob = wr()
857 self.assertEqual(ob, dict[ob.arg])
858 self.assertEqual(ob.arg, dict[ob.arg].arg)
859 objects2.remove(ob)
860 self.assertEqual(len(objects2), 0)
861
862 # Test itervaluerefs()
863 objects2 = list(objects)
864 self.assertEqual(len(list(dict.itervaluerefs())), len(objects))
865 for wr in dict.itervaluerefs():
866 ob = wr()
867 self.assertEqual(ob, dict[ob.arg])
868 self.assertEqual(ob.arg, dict[ob.arg].arg)
869 objects2.remove(ob)
870 self.assertEqual(len(objects2), 0)
871
Fred Drake0e540c32001-05-02 05:44:22 +0000872 def check_iters(self, dict):
873 # item iterator:
874 items = dict.items()
875 for item in dict.iteritems():
876 items.remove(item)
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000877 self.assert_(len(items) == 0, "iteritems() did not touch all items")
Fred Drake0e540c32001-05-02 05:44:22 +0000878
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000879 # key iterator, via __iter__():
Fred Drake0e540c32001-05-02 05:44:22 +0000880 keys = dict.keys()
881 for k in dict:
882 keys.remove(k)
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000883 self.assert_(len(keys) == 0, "__iter__() did not touch all keys")
884
885 # key iterator, via iterkeys():
886 keys = dict.keys()
887 for k in dict.iterkeys():
888 keys.remove(k)
889 self.assert_(len(keys) == 0, "iterkeys() did not touch all keys")
Fred Drake0e540c32001-05-02 05:44:22 +0000890
891 # value iterator:
892 values = dict.values()
893 for v in dict.itervalues():
894 values.remove(v)
Fred Drakef425b1e2003-07-14 21:37:17 +0000895 self.assert_(len(values) == 0,
896 "itervalues() did not touch all values")
Fred Drake0e540c32001-05-02 05:44:22 +0000897
Guido van Rossum009afb72002-06-10 20:00:52 +0000898 def test_make_weak_keyed_dict_from_dict(self):
899 o = Object(3)
900 dict = weakref.WeakKeyDictionary({o:364})
901 self.assert_(dict[o] == 364)
902
903 def test_make_weak_keyed_dict_from_weak_keyed_dict(self):
904 o = Object(3)
905 dict = weakref.WeakKeyDictionary({o:364})
906 dict2 = weakref.WeakKeyDictionary(dict)
907 self.assert_(dict[o] == 364)
908
Fred Drake0e540c32001-05-02 05:44:22 +0000909 def make_weak_keyed_dict(self):
910 dict = weakref.WeakKeyDictionary()
911 objects = map(Object, range(self.COUNT))
912 for o in objects:
913 dict[o] = o.arg
914 return dict, objects
915
916 def make_weak_valued_dict(self):
917 dict = weakref.WeakValueDictionary()
918 objects = map(Object, range(self.COUNT))
919 for o in objects:
920 dict[o.arg] = o
921 return dict, objects
922
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000923 def check_popitem(self, klass, key1, value1, key2, value2):
924 weakdict = klass()
925 weakdict[key1] = value1
926 weakdict[key2] = value2
927 self.assert_(len(weakdict) == 2)
928 k, v = weakdict.popitem()
929 self.assert_(len(weakdict) == 1)
930 if k is key1:
931 self.assert_(v is value1)
932 else:
933 self.assert_(v is value2)
934 k, v = weakdict.popitem()
935 self.assert_(len(weakdict) == 0)
936 if k is key1:
937 self.assert_(v is value1)
938 else:
939 self.assert_(v is value2)
940
941 def test_weak_valued_dict_popitem(self):
942 self.check_popitem(weakref.WeakValueDictionary,
943 "key1", C(), "key2", C())
944
945 def test_weak_keyed_dict_popitem(self):
946 self.check_popitem(weakref.WeakKeyDictionary,
947 C(), "value 1", C(), "value 2")
948
949 def check_setdefault(self, klass, key, value1, value2):
950 self.assert_(value1 is not value2,
951 "invalid test"
952 " -- value parameters must be distinct objects")
953 weakdict = klass()
954 o = weakdict.setdefault(key, value1)
955 self.assert_(o is value1)
956 self.assert_(weakdict.has_key(key))
957 self.assert_(weakdict.get(key) is value1)
958 self.assert_(weakdict[key] is value1)
959
960 o = weakdict.setdefault(key, value2)
961 self.assert_(o is value1)
962 self.assert_(weakdict.has_key(key))
963 self.assert_(weakdict.get(key) is value1)
964 self.assert_(weakdict[key] is value1)
965
966 def test_weak_valued_dict_setdefault(self):
967 self.check_setdefault(weakref.WeakValueDictionary,
968 "key", C(), C())
969
970 def test_weak_keyed_dict_setdefault(self):
971 self.check_setdefault(weakref.WeakKeyDictionary,
972 C(), "value 1", "value 2")
973
Fred Drakea0a4ab12001-04-16 17:37:27 +0000974 def check_update(self, klass, dict):
Fred Drake0e540c32001-05-02 05:44:22 +0000975 #
976 # This exercises d.update(), len(d), d.keys(), d.has_key(),
977 # d.get(), d[].
978 #
Fred Drakea0a4ab12001-04-16 17:37:27 +0000979 weakdict = klass()
980 weakdict.update(dict)
981 self.assert_(len(weakdict) == len(dict))
982 for k in weakdict.keys():
983 self.assert_(dict.has_key(k),
984 "mysterious new key appeared in weak dict")
985 v = dict.get(k)
986 self.assert_(v is weakdict[k])
987 self.assert_(v is weakdict.get(k))
988 for k in dict.keys():
989 self.assert_(weakdict.has_key(k),
990 "original key disappeared in weak dict")
991 v = dict[k]
992 self.assert_(v is weakdict[k])
993 self.assert_(v is weakdict.get(k))
994
995 def test_weak_valued_dict_update(self):
996 self.check_update(weakref.WeakValueDictionary,
997 {1: C(), 'a': C(), C(): C()})
998
999 def test_weak_keyed_dict_update(self):
1000 self.check_update(weakref.WeakKeyDictionary,
1001 {C(): 1, C(): 2, C(): 3})
1002
Fred Drakeccc75622001-09-06 14:52:39 +00001003 def test_weak_keyed_delitem(self):
1004 d = weakref.WeakKeyDictionary()
1005 o1 = Object('1')
1006 o2 = Object('2')
1007 d[o1] = 'something'
1008 d[o2] = 'something'
1009 self.assert_(len(d) == 2)
1010 del d[o1]
1011 self.assert_(len(d) == 1)
1012 self.assert_(d.keys() == [o2])
1013
1014 def test_weak_valued_delitem(self):
1015 d = weakref.WeakValueDictionary()
1016 o1 = Object('1')
1017 o2 = Object('2')
1018 d['something'] = o1
1019 d['something else'] = o2
1020 self.assert_(len(d) == 2)
1021 del d['something']
1022 self.assert_(len(d) == 1)
1023 self.assert_(d.items() == [('something else', o2)])
1024
Tim Peters886128f2003-05-25 01:45:11 +00001025 def test_weak_keyed_bad_delitem(self):
1026 d = weakref.WeakKeyDictionary()
1027 o = Object('1')
1028 # An attempt to delete an object that isn't there should raise
Tim Peters50d8b8b2003-05-25 17:44:31 +00001029 # KeyError. It didn't before 2.3.
Tim Peters886128f2003-05-25 01:45:11 +00001030 self.assertRaises(KeyError, d.__delitem__, o)
Tim Peters50d8b8b2003-05-25 17:44:31 +00001031 self.assertRaises(KeyError, d.__getitem__, o)
1032
1033 # If a key isn't of a weakly referencable type, __getitem__ and
1034 # __setitem__ raise TypeError. __delitem__ should too.
1035 self.assertRaises(TypeError, d.__delitem__, 13)
1036 self.assertRaises(TypeError, d.__getitem__, 13)
1037 self.assertRaises(TypeError, d.__setitem__, 13, 13)
Tim Peters886128f2003-05-25 01:45:11 +00001038
1039 def test_weak_keyed_cascading_deletes(self):
1040 # SF bug 742860. For some reason, before 2.3 __delitem__ iterated
1041 # over the keys via self.data.iterkeys(). If things vanished from
1042 # the dict during this (or got added), that caused a RuntimeError.
1043
1044 d = weakref.WeakKeyDictionary()
1045 mutate = False
1046
1047 class C(object):
1048 def __init__(self, i):
1049 self.value = i
1050 def __hash__(self):
1051 return hash(self.value)
1052 def __eq__(self, other):
1053 if mutate:
1054 # Side effect that mutates the dict, by removing the
1055 # last strong reference to a key.
1056 del objs[-1]
1057 return self.value == other.value
1058
1059 objs = [C(i) for i in range(4)]
1060 for o in objs:
1061 d[o] = o.value
1062 del o # now the only strong references to keys are in objs
1063 # Find the order in which iterkeys sees the keys.
1064 objs = d.keys()
1065 # Reverse it, so that the iteration implementation of __delitem__
1066 # has to keep looping to find the first object we delete.
1067 objs.reverse()
Tim Peters50d8b8b2003-05-25 17:44:31 +00001068
Tim Peters886128f2003-05-25 01:45:11 +00001069 # Turn on mutation in C.__eq__. The first time thru the loop,
1070 # under the iterkeys() business the first comparison will delete
1071 # the last item iterkeys() would see, and that causes a
1072 # RuntimeError: dictionary changed size during iteration
1073 # when the iterkeys() loop goes around to try comparing the next
Tim Peters50d8b8b2003-05-25 17:44:31 +00001074 # key. After this was fixed, it just deletes the last object *our*
Tim Peters886128f2003-05-25 01:45:11 +00001075 # "for o in obj" loop would have gotten to.
1076 mutate = True
1077 count = 0
1078 for o in objs:
1079 count += 1
1080 del d[o]
1081 self.assertEqual(len(d), 0)
1082 self.assertEqual(count, 2)
1083
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001084from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001085
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001086class WeakValueDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +00001087 """Check that WeakValueDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001088 __ref = {"key1":Object(1), "key2":Object(2), "key3":Object(3)}
Walter Dörwald118f9312004-06-02 18:42:25 +00001089 type2test = weakref.WeakValueDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001090 def _reference(self):
1091 return self.__ref.copy()
1092
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001093class WeakKeyDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +00001094 """Check that WeakKeyDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001095 __ref = {Object("key1"):1, Object("key2"):2, Object("key3"):3}
Walter Dörwald118f9312004-06-02 18:42:25 +00001096 type2test = weakref.WeakKeyDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001097 def _reference(self):
1098 return self.__ref.copy()
Martin v. Löwis5e163332001-02-27 18:36:56 +00001099
Georg Brandl9a65d582005-07-02 19:07:30 +00001100libreftest = """ Doctest for examples in the library reference: libweakref.tex
1101
1102>>> import weakref
1103>>> class Dict(dict):
1104... pass
1105...
1106>>> obj = Dict(red=1, green=2, blue=3) # this object is weak referencable
1107>>> r = weakref.ref(obj)
Armin Rigoa3f09272006-05-28 19:13:17 +00001108>>> print r() is obj
1109True
Georg Brandl9a65d582005-07-02 19:07:30 +00001110
1111>>> import weakref
1112>>> class Object:
1113... pass
1114...
1115>>> o = Object()
1116>>> r = weakref.ref(o)
1117>>> o2 = r()
1118>>> o is o2
1119True
1120>>> del o, o2
1121>>> print r()
1122None
1123
1124>>> import weakref
1125>>> class ExtendedRef(weakref.ref):
1126... def __init__(self, ob, callback=None, **annotations):
1127... super(ExtendedRef, self).__init__(ob, callback)
1128... self.__counter = 0
1129... for k, v in annotations.iteritems():
1130... setattr(self, k, v)
1131... def __call__(self):
1132... '''Return a pair containing the referent and the number of
1133... times the reference has been called.
1134... '''
1135... ob = super(ExtendedRef, self).__call__()
1136... if ob is not None:
1137... self.__counter += 1
1138... ob = (ob, self.__counter)
1139... return ob
1140...
1141>>> class A: # not in docs from here, just testing the ExtendedRef
1142... pass
1143...
1144>>> a = A()
1145>>> r = ExtendedRef(a, foo=1, bar="baz")
1146>>> r.foo
11471
1148>>> r.bar
1149'baz'
1150>>> r()[1]
11511
1152>>> r()[1]
11532
1154>>> r()[0] is a
1155True
1156
1157
1158>>> import weakref
1159>>> _id2obj_dict = weakref.WeakValueDictionary()
1160>>> def remember(obj):
1161... oid = id(obj)
1162... _id2obj_dict[oid] = obj
1163... return oid
1164...
1165>>> def id2obj(oid):
1166... return _id2obj_dict[oid]
1167...
1168>>> a = A() # from here, just testing
1169>>> a_id = remember(a)
1170>>> id2obj(a_id) is a
1171True
1172>>> del a
1173>>> try:
1174... id2obj(a_id)
1175... except KeyError:
1176... print 'OK'
1177... else:
1178... print 'WeakValueDictionary error'
1179OK
1180
1181"""
1182
1183__test__ = {'libreftest' : libreftest}
1184
Fred Drake2e2be372001-09-20 21:33:42 +00001185def test_main():
Walter Dörwald21d3a322003-05-01 17:45:56 +00001186 test_support.run_unittest(
1187 ReferencesTestCase,
1188 MappingTestCase,
1189 WeakValueDictionaryTestCase,
Fred Drakef425b1e2003-07-14 21:37:17 +00001190 WeakKeyDictionaryTestCase,
Amaury Forgeot d'Arc3255e132008-06-16 19:22:42 +00001191 SubclassableWeakrefTestCase,
Fred Drakef425b1e2003-07-14 21:37:17 +00001192 )
Georg Brandl9a65d582005-07-02 19:07:30 +00001193 test_support.run_doctest(sys.modules[__name__])
Fred Drake2e2be372001-09-20 21:33:42 +00001194
1195
1196if __name__ == "__main__":
1197 test_main()