blob: 9bcb090613137ab6cef9d0d5326d8ea40e3f1ac0 [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
Georg Brandl88659b02008-05-20 08:40:43 +00006import operator
Fred Drake41deb1e2001-02-01 05:27:45 +00007
Barry Warsaw04f357c2002-07-23 19:04:11 +00008from test import test_support
Fred Drake41deb1e2001-02-01 05:27:45 +00009
Brett Cannonf5bee302007-01-23 23:21:22 +000010# Used in ReferencesTestCase.test_ref_created_during_del() .
11ref_from_del = None
Fred Drake41deb1e2001-02-01 05:27:45 +000012
13class C:
Fred Drakeb0fefc52001-03-23 04:22:45 +000014 def method(self):
15 pass
Fred Drake41deb1e2001-02-01 05:27:45 +000016
17
Fred Drakeb0fefc52001-03-23 04:22:45 +000018class Callable:
19 bar = None
Fred Drake41deb1e2001-02-01 05:27:45 +000020
Fred Drakeb0fefc52001-03-23 04:22:45 +000021 def __call__(self, x):
22 self.bar = x
Fred Drake41deb1e2001-02-01 05:27:45 +000023
24
Fred Drakeb0fefc52001-03-23 04:22:45 +000025def create_function():
26 def f(): pass
27 return f
28
29def create_bound_method():
30 return C().method
31
32def create_unbound_method():
33 return C.method
Fred Drake41deb1e2001-02-01 05:27:45 +000034
35
Fred Drakeb0fefc52001-03-23 04:22:45 +000036class TestBase(unittest.TestCase):
37
38 def setUp(self):
39 self.cbcalled = 0
40
41 def callback(self, ref):
42 self.cbcalled += 1
Fred Drake41deb1e2001-02-01 05:27:45 +000043
44
Fred Drakeb0fefc52001-03-23 04:22:45 +000045class ReferencesTestCase(TestBase):
Fred Drake41deb1e2001-02-01 05:27:45 +000046
Fred Drakeb0fefc52001-03-23 04:22:45 +000047 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)
Fred Drake41deb1e2001-02-01 05:27:45 +000052
Fred Drake43735da2002-04-11 03:59:42 +000053 # Just make sure the tp_repr handler doesn't raise an exception.
54 # Live reference:
55 o = C()
56 wr = weakref.ref(o)
Ezio Melottia65e2af2010-08-02 19:56:05 +000057 repr(wr)
Fred Drake43735da2002-04-11 03:59:42 +000058 # Dead reference:
59 del o
Ezio Melottia65e2af2010-08-02 19:56:05 +000060 repr(wr)
Fred Drake43735da2002-04-11 03:59:42 +000061
Fred Drakeb0fefc52001-03-23 04:22:45 +000062 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)
Fred Drake41deb1e2001-02-01 05:27:45 +000067
Fred Drakeb0fefc52001-03-23 04:22:45 +000068 def test_multiple_callbacks(self):
69 o = C()
70 ref1 = weakref.ref(o, self.callback)
71 ref2 = weakref.ref(o, self.callback)
72 del o
73 self.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")
Fred Drake41deb1e2001-02-01 05:27:45 +000079
Fred Drake705088e2001-04-13 17:18:15 +000080 def test_multiple_selfref_callbacks(self):
Guido van Rossum9eee5542002-08-22 20:21:30 +000081 # Make sure all references are invalidated before callbacks are called
Fred Drake705088e2001-04-13 17:18:15 +000082 #
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.
90 #
91 def callback(object, self=self):
92 self.ref()
93 c = C()
94 self.ref = weakref.ref(c, callback)
95 ref1 = weakref.ref(c, callback)
96 del c
97
Fred Drakeb0fefc52001-03-23 04:22:45 +000098 def test_proxy_ref(self):
99 o = C()
100 o.bar = 1
101 ref1 = weakref.proxy(o, self.callback)
102 ref2 = weakref.proxy(o, self.callback)
103 del o
Fred Drake41deb1e2001-02-01 05:27:45 +0000104
Fred Drakeb0fefc52001-03-23 04:22:45 +0000105 def check(proxy):
106 proxy.bar
Fred Drake41deb1e2001-02-01 05:27:45 +0000107
Fred Drakeb0fefc52001-03-23 04:22:45 +0000108 self.assertRaises(weakref.ReferenceError, check, ref1)
109 self.assertRaises(weakref.ReferenceError, check, ref2)
Neal Norwitzbdcb9412004-07-08 01:22:31 +0000110 self.assertRaises(weakref.ReferenceError, bool, weakref.proxy(C()))
Fred Drakeb0fefc52001-03-23 04:22:45 +0000111 self.assert_(self.cbcalled == 2)
Fred Drake41deb1e2001-02-01 05:27:45 +0000112
Fred Drakeb0fefc52001-03-23 04:22:45 +0000113 def check_basic_ref(self, factory):
114 o = factory()
115 ref = weakref.ref(o)
116 self.assert_(ref() is not None,
117 "weak reference to live object should be live")
118 o2 = ref()
119 self.assert_(o is o2,
120 "<ref>() should return original object if live")
Fred Drake41deb1e2001-02-01 05:27:45 +0000121
Fred Drakeb0fefc52001-03-23 04:22:45 +0000122 def check_basic_callback(self, factory):
123 self.cbcalled = 0
124 o = factory()
125 ref = weakref.ref(o, self.callback)
126 del o
Fred Drake705088e2001-04-13 17:18:15 +0000127 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")
Fred Drake41deb1e2001-02-01 05:27:45 +0000131
Fred Drakeb0fefc52001-03-23 04:22:45 +0000132 def test_ref_reuse(self):
133 o = C()
134 ref1 = weakref.ref(o)
135 # create a proxy to make sure that there's an intervening creation
136 # between these two; it should make no difference
137 proxy = weakref.proxy(o)
138 ref2 = weakref.ref(o)
139 self.assert_(ref1 is ref2,
140 "reference object w/out callback should be re-used")
Fred Drake41deb1e2001-02-01 05:27:45 +0000141
Fred Drakeb0fefc52001-03-23 04:22:45 +0000142 o = C()
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")
150 del proxy
151 self.assert_(weakref.getweakrefcount(o) == 1,
152 "wrong weak ref count for object after deleting proxy")
Fred Drake41deb1e2001-02-01 05:27:45 +0000153
Fred Drakeb0fefc52001-03-23 04:22:45 +0000154 def test_proxy_reuse(self):
155 o = C()
156 proxy1 = weakref.proxy(o)
157 ref = weakref.ref(o)
158 proxy2 = weakref.proxy(o)
159 self.assert_(proxy1 is proxy2,
160 "proxy object w/out callback should have been re-used")
161
162 def test_basic_proxy(self):
163 o = C()
164 self.check_proxy(o, weakref.proxy(o))
165
Fred Drake5935ff02001-12-19 16:54:23 +0000166 L = UserList.UserList()
167 p = weakref.proxy(L)
168 self.failIf(p, "proxy for empty UserList should be false")
169 p.append(12)
170 self.assertEqual(len(L), 1)
171 self.failUnless(p, "proxy for non-empty UserList should be true")
Ezio Melottia65e2af2010-08-02 19:56:05 +0000172 with test_support._check_py3k_warnings():
173 p[:] = [2, 3]
Fred Drake5935ff02001-12-19 16:54:23 +0000174 self.assertEqual(len(L), 2)
175 self.assertEqual(len(p), 2)
Fred Drakef425b1e2003-07-14 21:37:17 +0000176 self.failUnless(3 in p,
177 "proxy didn't support __contains__() properly")
Fred Drake5935ff02001-12-19 16:54:23 +0000178 p[1] = 5
179 self.assertEqual(L[1], 5)
180 self.assertEqual(p[1], 5)
181 L2 = UserList.UserList(L)
182 p2 = weakref.proxy(L2)
183 self.assertEqual(p, p2)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000184 ## self.assertEqual(repr(L2), repr(p2))
Fred Drake43735da2002-04-11 03:59:42 +0000185 L3 = UserList.UserList(range(10))
186 p3 = weakref.proxy(L3)
Ezio Melottia65e2af2010-08-02 19:56:05 +0000187 with test_support._check_py3k_warnings():
188 self.assertEqual(L3[:], p3[:])
189 self.assertEqual(L3[5:], p3[5:])
190 self.assertEqual(L3[:5], p3[:5])
191 self.assertEqual(L3[2:5], p3[2:5])
Fred Drake5935ff02001-12-19 16:54:23 +0000192
Benjamin Peterson6481e092009-11-19 03:11:09 +0000193 def test_proxy_unicode(self):
194 # See bug 5037
195 class C(object):
196 def __str__(self):
197 return "string"
198 def __unicode__(self):
199 return u"unicode"
200 instance = C()
201 self.assertTrue("__unicode__" in dir(weakref.proxy(instance)))
202 self.assertEqual(unicode(weakref.proxy(instance)), u"unicode")
203
Georg Brandl88659b02008-05-20 08:40:43 +0000204 def test_proxy_index(self):
205 class C:
206 def __index__(self):
207 return 10
208 o = C()
209 p = weakref.proxy(o)
210 self.assertEqual(operator.index(p), 10)
211
212 def test_proxy_div(self):
213 class C:
214 def __floordiv__(self, other):
215 return 42
216 def __ifloordiv__(self, other):
217 return 21
218 o = C()
219 p = weakref.proxy(o)
220 self.assertEqual(p // 5, 42)
221 p //= 5
222 self.assertEqual(p, 21)
223
Fred Drakeea2adc92004-02-03 19:56:46 +0000224 # The PyWeakref_* C API is documented as allowing either NULL or
225 # None as the value for the callback, where either means "no
226 # callback". The "no callback" ref and proxy objects are supposed
227 # to be shared so long as they exist by all callers so long as
Walter Dörwaldda1ad322006-12-12 21:55:31 +0000228 # they are active. In Python 2.3.3 and earlier, this guarantee
Fred Drakeea2adc92004-02-03 19:56:46 +0000229 # was not honored, and was broken in different ways for
230 # PyWeakref_NewRef() and PyWeakref_NewProxy(). (Two tests.)
231
232 def test_shared_ref_without_callback(self):
233 self.check_shared_without_callback(weakref.ref)
234
235 def test_shared_proxy_without_callback(self):
236 self.check_shared_without_callback(weakref.proxy)
237
238 def check_shared_without_callback(self, makeref):
239 o = Object(1)
240 p1 = makeref(o, None)
241 p2 = makeref(o, None)
242 self.assert_(p1 is p2, "both callbacks were None in the C API")
243 del p1, p2
244 p1 = makeref(o)
245 p2 = makeref(o, None)
246 self.assert_(p1 is p2, "callbacks were NULL, None in the C API")
247 del p1, p2
248 p1 = makeref(o)
249 p2 = makeref(o)
250 self.assert_(p1 is p2, "both callbacks were NULL in the C API")
251 del p1, p2
252 p1 = makeref(o, None)
253 p2 = makeref(o)
254 self.assert_(p1 is p2, "callbacks were None, NULL in the C API")
255
Fred Drakeb0fefc52001-03-23 04:22:45 +0000256 def test_callable_proxy(self):
257 o = Callable()
258 ref1 = weakref.proxy(o)
259
260 self.check_proxy(o, ref1)
261
262 self.assert_(type(ref1) is weakref.CallableProxyType,
263 "proxy is not of callable type")
264 ref1('twinkies!')
265 self.assert_(o.bar == 'twinkies!',
266 "call through proxy not passed through to original")
Fred Drake3bb4d212001-10-18 19:28:29 +0000267 ref1(x='Splat.')
268 self.assert_(o.bar == 'Splat.',
269 "call through proxy not passed through to original")
Fred Drakeb0fefc52001-03-23 04:22:45 +0000270
271 # expect due to too few args
272 self.assertRaises(TypeError, ref1)
273
274 # expect due to too many args
275 self.assertRaises(TypeError, ref1, 1, 2, 3)
276
277 def check_proxy(self, o, proxy):
278 o.foo = 1
279 self.assert_(proxy.foo == 1,
280 "proxy does not reflect attribute addition")
281 o.foo = 2
282 self.assert_(proxy.foo == 2,
283 "proxy does not reflect attribute modification")
284 del o.foo
285 self.assert_(not hasattr(proxy, 'foo'),
286 "proxy does not reflect attribute removal")
287
288 proxy.foo = 1
289 self.assert_(o.foo == 1,
290 "object does not reflect attribute addition via proxy")
291 proxy.foo = 2
292 self.assert_(
293 o.foo == 2,
294 "object does not reflect attribute modification via proxy")
295 del proxy.foo
296 self.assert_(not hasattr(o, 'foo'),
297 "object does not reflect attribute removal via proxy")
298
Raymond Hettingerd693a812003-06-30 04:18:48 +0000299 def test_proxy_deletion(self):
300 # Test clearing of SF bug #762891
301 class Foo:
302 result = None
303 def __delitem__(self, accessor):
304 self.result = accessor
305 g = Foo()
306 f = weakref.proxy(g)
307 del f[0]
308 self.assertEqual(f.result, 0)
309
Raymond Hettingere6c470f2005-03-27 03:04:54 +0000310 def test_proxy_bool(self):
311 # Test clearing of SF bug #1170766
312 class List(list): pass
313 lyst = List()
314 self.assertEqual(bool(weakref.proxy(lyst)), bool(lyst))
315
Fred Drakeb0fefc52001-03-23 04:22:45 +0000316 def test_getweakrefcount(self):
317 o = C()
318 ref1 = weakref.ref(o)
319 ref2 = weakref.ref(o, self.callback)
320 self.assert_(weakref.getweakrefcount(o) == 2,
321 "got wrong number of weak reference objects")
322
323 proxy1 = weakref.proxy(o)
324 proxy2 = weakref.proxy(o, self.callback)
325 self.assert_(weakref.getweakrefcount(o) == 4,
326 "got wrong number of weak reference objects")
327
Fred Drakeea2adc92004-02-03 19:56:46 +0000328 del ref1, ref2, proxy1, proxy2
329 self.assert_(weakref.getweakrefcount(o) == 0,
330 "weak reference objects not unlinked from"
331 " referent when discarded.")
332
Walter Dörwaldb167b042003-12-11 12:34:05 +0000333 # assumes ints do not support weakrefs
334 self.assert_(weakref.getweakrefcount(1) == 0,
335 "got wrong number of weak reference objects for int")
336
Fred Drakeb0fefc52001-03-23 04:22:45 +0000337 def test_getweakrefs(self):
338 o = C()
339 ref1 = weakref.ref(o, self.callback)
340 ref2 = weakref.ref(o, self.callback)
341 del ref1
342 self.assert_(weakref.getweakrefs(o) == [ref2],
343 "list of refs does not match")
344
345 o = C()
346 ref1 = weakref.ref(o, self.callback)
347 ref2 = weakref.ref(o, self.callback)
348 del ref2
349 self.assert_(weakref.getweakrefs(o) == [ref1],
350 "list of refs does not match")
351
Fred Drakeea2adc92004-02-03 19:56:46 +0000352 del ref1
353 self.assert_(weakref.getweakrefs(o) == [],
354 "list of refs not cleared")
355
Walter Dörwaldb167b042003-12-11 12:34:05 +0000356 # assumes ints do not support weakrefs
357 self.assert_(weakref.getweakrefs(1) == [],
358 "list of refs does not match for int")
359
Fred Drake39c27f12001-10-18 18:06:05 +0000360 def test_newstyle_number_ops(self):
361 class F(float):
362 pass
363 f = F(2.0)
364 p = weakref.proxy(f)
365 self.assert_(p + 1.0 == 3.0)
366 self.assert_(1.0 + p == 3.0) # this used to SEGV
367
Fred Drake2a64f462001-12-10 23:46:02 +0000368 def test_callbacks_protected(self):
Guido van Rossum9eee5542002-08-22 20:21:30 +0000369 # Callbacks protected from already-set exceptions?
Fred Drake2a64f462001-12-10 23:46:02 +0000370 # Regression test for SF bug #478534.
371 class BogusError(Exception):
372 pass
373 data = {}
374 def remove(k):
375 del data[k]
376 def encapsulate():
377 f = lambda : ()
378 data[weakref.ref(f, remove)] = None
379 raise BogusError
380 try:
381 encapsulate()
382 except BogusError:
383 pass
384 else:
385 self.fail("exception not properly restored")
386 try:
387 encapsulate()
388 except BogusError:
389 pass
390 else:
391 self.fail("exception not properly restored")
392
Tim Petersadd09b42003-11-12 20:43:28 +0000393 def test_sf_bug_840829(self):
394 # "weakref callbacks and gc corrupt memory"
395 # subtype_dealloc erroneously exposed a new-style instance
396 # already in the process of getting deallocated to gc,
397 # causing double-deallocation if the instance had a weakref
398 # callback that triggered gc.
399 # If the bug exists, there probably won't be an obvious symptom
400 # in a release build. In a debug build, a segfault will occur
401 # when the second attempt to remove the instance from the "list
402 # of all objects" occurs.
403
404 import gc
405
406 class C(object):
407 pass
408
409 c = C()
410 wr = weakref.ref(c, lambda ignore: gc.collect())
411 del c
412
Tim Petersf7f9e992003-11-13 21:59:32 +0000413 # There endeth the first part. It gets worse.
414 del wr
415
416 c1 = C()
417 c1.i = C()
418 wr = weakref.ref(c1.i, lambda ignore: gc.collect())
419
420 c2 = C()
421 c2.c1 = c1
422 del c1 # still alive because c2 points to it
423
424 # Now when subtype_dealloc gets called on c2, it's not enough just
425 # that c2 is immune from gc while the weakref callbacks associated
426 # with c2 execute (there are none in this 2nd half of the test, btw).
427 # subtype_dealloc goes on to call the base classes' deallocs too,
428 # so any gc triggered by weakref callbacks associated with anything
429 # torn down by a base class dealloc can also trigger double
430 # deallocation of c2.
431 del c2
Fred Drake41deb1e2001-02-01 05:27:45 +0000432
Tim Peters403a2032003-11-20 21:21:46 +0000433 def test_callback_in_cycle_1(self):
434 import gc
435
436 class J(object):
437 pass
438
439 class II(object):
440 def acallback(self, ignore):
441 self.J
442
443 I = II()
444 I.J = J
445 I.wr = weakref.ref(J, I.acallback)
446
447 # Now J and II are each in a self-cycle (as all new-style class
448 # objects are, since their __mro__ points back to them). I holds
449 # both a weak reference (I.wr) and a strong reference (I.J) to class
450 # J. I is also in a cycle (I.wr points to a weakref that references
451 # I.acallback). When we del these three, they all become trash, but
452 # the cycles prevent any of them from getting cleaned up immediately.
453 # Instead they have to wait for cyclic gc to deduce that they're
454 # trash.
455 #
456 # gc used to call tp_clear on all of them, and the order in which
457 # it does that is pretty accidental. The exact order in which we
458 # built up these things manages to provoke gc into running tp_clear
459 # in just the right order (I last). Calling tp_clear on II leaves
460 # behind an insane class object (its __mro__ becomes NULL). Calling
461 # tp_clear on J breaks its self-cycle, but J doesn't get deleted
462 # just then because of the strong reference from I.J. Calling
463 # tp_clear on I starts to clear I's __dict__, and just happens to
464 # clear I.J first -- I.wr is still intact. That removes the last
465 # reference to J, which triggers the weakref callback. The callback
466 # tries to do "self.J", and instances of new-style classes look up
467 # attributes ("J") in the class dict first. The class (II) wants to
468 # search II.__mro__, but that's NULL. The result was a segfault in
469 # a release build, and an assert failure in a debug build.
470 del I, J, II
471 gc.collect()
472
473 def test_callback_in_cycle_2(self):
474 import gc
475
476 # This is just like test_callback_in_cycle_1, except that II is an
477 # old-style class. The symptom is different then: an instance of an
478 # old-style class looks in its own __dict__ first. 'J' happens to
479 # get cleared from I.__dict__ before 'wr', and 'J' was never in II's
480 # __dict__, so the attribute isn't found. The difference is that
481 # the old-style II doesn't have a NULL __mro__ (it doesn't have any
482 # __mro__), so no segfault occurs. Instead it got:
483 # test_callback_in_cycle_2 (__main__.ReferencesTestCase) ...
484 # Exception exceptions.AttributeError:
485 # "II instance has no attribute 'J'" in <bound method II.acallback
486 # of <?.II instance at 0x00B9B4B8>> ignored
487
488 class J(object):
489 pass
490
491 class II:
492 def acallback(self, ignore):
493 self.J
494
495 I = II()
496 I.J = J
497 I.wr = weakref.ref(J, I.acallback)
498
499 del I, J, II
500 gc.collect()
501
502 def test_callback_in_cycle_3(self):
503 import gc
504
505 # This one broke the first patch that fixed the last two. In this
506 # case, the objects reachable from the callback aren't also reachable
507 # from the object (c1) *triggering* the callback: you can get to
508 # c1 from c2, but not vice-versa. The result was that c2's __dict__
509 # got tp_clear'ed by the time the c2.cb callback got invoked.
510
511 class C:
512 def cb(self, ignore):
513 self.me
514 self.c1
515 self.wr
516
517 c1, c2 = C(), C()
518
519 c2.me = c2
520 c2.c1 = c1
521 c2.wr = weakref.ref(c1, c2.cb)
522
523 del c1, c2
524 gc.collect()
525
526 def test_callback_in_cycle_4(self):
527 import gc
528
529 # Like test_callback_in_cycle_3, except c2 and c1 have different
530 # classes. c2's class (C) isn't reachable from c1 then, so protecting
531 # objects reachable from the dying object (c1) isn't enough to stop
532 # c2's class (C) from getting tp_clear'ed before c2.cb is invoked.
533 # The result was a segfault (C.__mro__ was NULL when the callback
534 # tried to look up self.me).
535
536 class C(object):
537 def cb(self, ignore):
538 self.me
539 self.c1
540 self.wr
541
542 class D:
543 pass
544
545 c1, c2 = D(), C()
546
547 c2.me = c2
548 c2.c1 = c1
549 c2.wr = weakref.ref(c1, c2.cb)
550
551 del c1, c2, C, D
552 gc.collect()
553
554 def test_callback_in_cycle_resurrection(self):
555 import gc
556
557 # Do something nasty in a weakref callback: resurrect objects
558 # from dead cycles. For this to be attempted, the weakref and
559 # its callback must also be part of the cyclic trash (else the
560 # objects reachable via the callback couldn't be in cyclic trash
561 # to begin with -- the callback would act like an external root).
562 # But gc clears trash weakrefs with callbacks early now, which
563 # disables the callbacks, so the callbacks shouldn't get called
564 # at all (and so nothing actually gets resurrected).
565
566 alist = []
567 class C(object):
568 def __init__(self, value):
569 self.attribute = value
570
571 def acallback(self, ignore):
572 alist.append(self.c)
573
574 c1, c2 = C(1), C(2)
575 c1.c = c2
576 c2.c = c1
577 c1.wr = weakref.ref(c2, c1.acallback)
578 c2.wr = weakref.ref(c1, c2.acallback)
579
580 def C_went_away(ignore):
581 alist.append("C went away")
582 wr = weakref.ref(C, C_went_away)
583
584 del c1, c2, C # make them all trash
585 self.assertEqual(alist, []) # del isn't enough to reclaim anything
586
587 gc.collect()
588 # c1.wr and c2.wr were part of the cyclic trash, so should have
589 # been cleared without their callbacks executing. OTOH, the weakref
590 # to C is bound to a function local (wr), and wasn't trash, so that
591 # callback should have been invoked when C went away.
592 self.assertEqual(alist, ["C went away"])
593 # The remaining weakref should be dead now (its callback ran).
594 self.assertEqual(wr(), None)
595
596 del alist[:]
597 gc.collect()
598 self.assertEqual(alist, [])
599
600 def test_callbacks_on_callback(self):
601 import gc
602
603 # Set up weakref callbacks *on* weakref callbacks.
604 alist = []
605 def safe_callback(ignore):
606 alist.append("safe_callback called")
607
608 class C(object):
609 def cb(self, ignore):
610 alist.append("cb called")
611
612 c, d = C(), C()
613 c.other = d
614 d.other = c
615 callback = c.cb
616 c.wr = weakref.ref(d, callback) # this won't trigger
617 d.wr = weakref.ref(callback, d.cb) # ditto
618 external_wr = weakref.ref(callback, safe_callback) # but this will
619 self.assert_(external_wr() is callback)
620
621 # The weakrefs attached to c and d should get cleared, so that
622 # C.cb is never called. But external_wr isn't part of the cyclic
623 # trash, and no cyclic trash is reachable from it, so safe_callback
624 # should get invoked when the bound method object callback (c.cb)
625 # -- which is itself a callback, and also part of the cyclic trash --
626 # gets reclaimed at the end of gc.
627
628 del callback, c, d, C
629 self.assertEqual(alist, []) # del isn't enough to clean up cycles
630 gc.collect()
631 self.assertEqual(alist, ["safe_callback called"])
632 self.assertEqual(external_wr(), None)
633
634 del alist[:]
635 gc.collect()
636 self.assertEqual(alist, [])
637
Fred Drakebc875f52004-02-04 23:14:14 +0000638 def test_gc_during_ref_creation(self):
639 self.check_gc_during_creation(weakref.ref)
640
641 def test_gc_during_proxy_creation(self):
642 self.check_gc_during_creation(weakref.proxy)
643
644 def check_gc_during_creation(self, makeref):
645 thresholds = gc.get_threshold()
646 gc.set_threshold(1, 1, 1)
647 gc.collect()
Fred Drake55cf4342004-02-13 19:21:57 +0000648 class A:
649 pass
Fred Drakebc875f52004-02-04 23:14:14 +0000650
651 def callback(*args):
652 pass
653
Fred Drake55cf4342004-02-13 19:21:57 +0000654 referenced = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000655
Fred Drake55cf4342004-02-13 19:21:57 +0000656 a = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000657 a.a = a
658 a.wr = makeref(referenced)
659
660 try:
661 # now make sure the object and the ref get labeled as
662 # cyclic trash:
Fred Drake55cf4342004-02-13 19:21:57 +0000663 a = A()
664 weakref.ref(referenced, callback)
Fred Drakebc875f52004-02-04 23:14:14 +0000665
666 finally:
667 gc.set_threshold(*thresholds)
668
Brett Cannonf5bee302007-01-23 23:21:22 +0000669 def test_ref_created_during_del(self):
670 # Bug #1377858
671 # A weakref created in an object's __del__() would crash the
672 # interpreter when the weakref was cleaned up since it would refer to
673 # non-existent memory. This test should not segfault the interpreter.
674 class Target(object):
675 def __del__(self):
676 global ref_from_del
677 ref_from_del = weakref.ref(self)
678
679 w = Target()
680
Benjamin Peterson97179b02008-09-09 20:55:01 +0000681 def test_init(self):
682 # Issue 3634
683 # <weakref to class>.__init__() doesn't check errors correctly
684 r = weakref.ref(Exception)
685 self.assertRaises(TypeError, r.__init__, 0, 0, 0, 0, 0)
686 # No exception should be raised here
687 gc.collect()
688
Fred Drake0a4dd392004-07-02 18:57:45 +0000689
Amaury Forgeot d'Arca8919fe2008-06-16 19:12:42 +0000690class SubclassableWeakrefTestCase(TestBase):
Fred Drake0a4dd392004-07-02 18:57:45 +0000691
692 def test_subclass_refs(self):
693 class MyRef(weakref.ref):
694 def __init__(self, ob, callback=None, value=42):
695 self.value = value
696 super(MyRef, self).__init__(ob, callback)
697 def __call__(self):
698 self.called = True
699 return super(MyRef, self).__call__()
700 o = Object("foo")
701 mr = MyRef(o, value=24)
702 self.assert_(mr() is o)
703 self.assert_(mr.called)
704 self.assertEqual(mr.value, 24)
705 del o
706 self.assert_(mr() is None)
707 self.assert_(mr.called)
708
709 def test_subclass_refs_dont_replace_standard_refs(self):
710 class MyRef(weakref.ref):
711 pass
712 o = Object(42)
713 r1 = MyRef(o)
714 r2 = weakref.ref(o)
715 self.assert_(r1 is not r2)
716 self.assertEqual(weakref.getweakrefs(o), [r2, r1])
717 self.assertEqual(weakref.getweakrefcount(o), 2)
718 r3 = MyRef(o)
719 self.assertEqual(weakref.getweakrefcount(o), 3)
720 refs = weakref.getweakrefs(o)
721 self.assertEqual(len(refs), 3)
722 self.assert_(r2 is refs[0])
723 self.assert_(r1 in refs[1:])
724 self.assert_(r3 in refs[1:])
725
726 def test_subclass_refs_dont_conflate_callbacks(self):
727 class MyRef(weakref.ref):
728 pass
729 o = Object(42)
730 r1 = MyRef(o, id)
731 r2 = MyRef(o, str)
732 self.assert_(r1 is not r2)
733 refs = weakref.getweakrefs(o)
734 self.assert_(r1 in refs)
735 self.assert_(r2 in refs)
736
737 def test_subclass_refs_with_slots(self):
738 class MyRef(weakref.ref):
739 __slots__ = "slot1", "slot2"
740 def __new__(type, ob, callback, slot1, slot2):
741 return weakref.ref.__new__(type, ob, callback)
742 def __init__(self, ob, callback, slot1, slot2):
743 self.slot1 = slot1
744 self.slot2 = slot2
745 def meth(self):
746 return self.slot1 + self.slot2
747 o = Object(42)
748 r = MyRef(o, None, "abc", "def")
749 self.assertEqual(r.slot1, "abc")
750 self.assertEqual(r.slot2, "def")
751 self.assertEqual(r.meth(), "abcdef")
752 self.failIf(hasattr(r, "__dict__"))
753
Amaury Forgeot d'Arca8919fe2008-06-16 19:12:42 +0000754 def test_subclass_refs_with_cycle(self):
755 # Bug #3110
756 # An instance of a weakref subclass can have attributes.
757 # If such a weakref holds the only strong reference to the object,
758 # deleting the weakref will delete the object. In this case,
759 # the callback must not be called, because the ref object is
760 # being deleted.
761 class MyRef(weakref.ref):
762 pass
763
764 # Use a local callback, for "regrtest -R::"
765 # to detect refcounting problems
766 def callback(w):
767 self.cbcalled += 1
768
769 o = C()
770 r1 = MyRef(o, callback)
771 r1.o = o
772 del o
773
774 del r1 # Used to crash here
775
776 self.assertEqual(self.cbcalled, 0)
777
778 # Same test, with two weakrefs to the same object
779 # (since code paths are different)
780 o = C()
781 r1 = MyRef(o, callback)
782 r2 = MyRef(o, callback)
783 r1.r = r2
784 r2.o = o
785 del o
786 del r2
787
788 del r1 # Used to crash here
789
790 self.assertEqual(self.cbcalled, 0)
791
Fred Drake0a4dd392004-07-02 18:57:45 +0000792
Fred Drake41deb1e2001-02-01 05:27:45 +0000793class Object:
794 def __init__(self, arg):
795 self.arg = arg
796 def __repr__(self):
797 return "<Object %r>" % self.arg
798
Fred Drake41deb1e2001-02-01 05:27:45 +0000799
Fred Drakeb0fefc52001-03-23 04:22:45 +0000800class MappingTestCase(TestBase):
Martin v. Löwis5e163332001-02-27 18:36:56 +0000801
Fred Drakeb0fefc52001-03-23 04:22:45 +0000802 COUNT = 10
803
804 def test_weak_values(self):
Fred Drake0e540c32001-05-02 05:44:22 +0000805 #
806 # This exercises d.copy(), d.items(), d[], del d[], len(d).
807 #
808 dict, objects = self.make_weak_valued_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +0000809 for o in objects:
810 self.assert_(weakref.getweakrefcount(o) == 1,
811 "wrong number of weak references to %r!" % o)
812 self.assert_(o is dict[o.arg],
813 "wrong object returned by weak dict!")
814 items1 = dict.items()
815 items2 = dict.copy().items()
816 items1.sort()
817 items2.sort()
818 self.assert_(items1 == items2,
819 "cloning of weak-valued dictionary did not work!")
820 del items1, items2
821 self.assert_(len(dict) == self.COUNT)
822 del objects[0]
823 self.assert_(len(dict) == (self.COUNT - 1),
824 "deleting object did not cause dictionary update")
825 del objects, o
826 self.assert_(len(dict) == 0,
827 "deleting the values did not clear the dictionary")
Fred Drake4fd06e02001-08-03 04:11:27 +0000828 # regression on SF bug #447152:
829 dict = weakref.WeakValueDictionary()
830 self.assertRaises(KeyError, dict.__getitem__, 1)
831 dict[2] = C()
832 self.assertRaises(KeyError, dict.__getitem__, 2)
Fred Drakeb0fefc52001-03-23 04:22:45 +0000833
834 def test_weak_keys(self):
Fred Drake0e540c32001-05-02 05:44:22 +0000835 #
836 # This exercises d.copy(), d.items(), d[] = v, d[], del d[],
Ezio Melottia65e2af2010-08-02 19:56:05 +0000837 # len(d), in d.
Fred Drake0e540c32001-05-02 05:44:22 +0000838 #
839 dict, objects = self.make_weak_keyed_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +0000840 for o in objects:
841 self.assert_(weakref.getweakrefcount(o) == 1,
842 "wrong number of weak references to %r!" % o)
843 self.assert_(o.arg is dict[o],
844 "wrong object returned by weak dict!")
845 items1 = dict.items()
846 items2 = dict.copy().items()
Raymond Hettingera690a992003-11-16 16:17:49 +0000847 self.assert_(set(items1) == set(items2),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000848 "cloning of weak-keyed dictionary did not work!")
849 del items1, items2
850 self.assert_(len(dict) == self.COUNT)
851 del objects[0]
852 self.assert_(len(dict) == (self.COUNT - 1),
853 "deleting object did not cause dictionary update")
854 del objects, o
855 self.assert_(len(dict) == 0,
856 "deleting the keys did not clear the dictionary")
Fred Drake752eda42001-11-06 16:38:34 +0000857 o = Object(42)
858 dict[o] = "What is the meaning of the universe?"
Ezio Melottia65e2af2010-08-02 19:56:05 +0000859 self.assertTrue(o in dict)
860 self.assertTrue(34 not in dict)
Martin v. Löwis5e163332001-02-27 18:36:56 +0000861
Fred Drake0e540c32001-05-02 05:44:22 +0000862 def test_weak_keyed_iters(self):
863 dict, objects = self.make_weak_keyed_dict()
864 self.check_iters(dict)
865
Fred Drake017e68c2006-05-02 06:53:59 +0000866 # Test keyrefs()
867 refs = dict.keyrefs()
868 self.assertEqual(len(refs), len(objects))
869 objects2 = list(objects)
870 for wr in refs:
871 ob = wr()
Ezio Melottia65e2af2010-08-02 19:56:05 +0000872 self.assertTrue(ob in dict)
Fred Drake017e68c2006-05-02 06:53:59 +0000873 self.assertEqual(ob.arg, dict[ob])
874 objects2.remove(ob)
875 self.assertEqual(len(objects2), 0)
876
877 # Test iterkeyrefs()
878 objects2 = list(objects)
879 self.assertEqual(len(list(dict.iterkeyrefs())), len(objects))
880 for wr in dict.iterkeyrefs():
881 ob = wr()
Ezio Melottia65e2af2010-08-02 19:56:05 +0000882 self.assertTrue(ob in dict)
Fred Drake017e68c2006-05-02 06:53:59 +0000883 self.assertEqual(ob.arg, dict[ob])
884 objects2.remove(ob)
885 self.assertEqual(len(objects2), 0)
886
Fred Drake0e540c32001-05-02 05:44:22 +0000887 def test_weak_valued_iters(self):
888 dict, objects = self.make_weak_valued_dict()
889 self.check_iters(dict)
890
Fred Drake017e68c2006-05-02 06:53:59 +0000891 # Test valuerefs()
892 refs = dict.valuerefs()
893 self.assertEqual(len(refs), len(objects))
894 objects2 = list(objects)
895 for wr in refs:
896 ob = wr()
897 self.assertEqual(ob, dict[ob.arg])
898 self.assertEqual(ob.arg, dict[ob.arg].arg)
899 objects2.remove(ob)
900 self.assertEqual(len(objects2), 0)
901
902 # Test itervaluerefs()
903 objects2 = list(objects)
904 self.assertEqual(len(list(dict.itervaluerefs())), len(objects))
905 for wr in dict.itervaluerefs():
906 ob = wr()
907 self.assertEqual(ob, dict[ob.arg])
908 self.assertEqual(ob.arg, dict[ob.arg].arg)
909 objects2.remove(ob)
910 self.assertEqual(len(objects2), 0)
911
Fred Drake0e540c32001-05-02 05:44:22 +0000912 def check_iters(self, dict):
913 # item iterator:
914 items = dict.items()
915 for item in dict.iteritems():
916 items.remove(item)
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000917 self.assert_(len(items) == 0, "iteritems() did not touch all items")
Fred Drake0e540c32001-05-02 05:44:22 +0000918
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000919 # key iterator, via __iter__():
Fred Drake0e540c32001-05-02 05:44:22 +0000920 keys = dict.keys()
921 for k in dict:
922 keys.remove(k)
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000923 self.assert_(len(keys) == 0, "__iter__() did not touch all keys")
924
925 # key iterator, via iterkeys():
926 keys = dict.keys()
927 for k in dict.iterkeys():
928 keys.remove(k)
929 self.assert_(len(keys) == 0, "iterkeys() did not touch all keys")
Fred Drake0e540c32001-05-02 05:44:22 +0000930
931 # value iterator:
932 values = dict.values()
933 for v in dict.itervalues():
934 values.remove(v)
Fred Drakef425b1e2003-07-14 21:37:17 +0000935 self.assert_(len(values) == 0,
936 "itervalues() did not touch all values")
Fred Drake0e540c32001-05-02 05:44:22 +0000937
Guido van Rossum009afb72002-06-10 20:00:52 +0000938 def test_make_weak_keyed_dict_from_dict(self):
939 o = Object(3)
940 dict = weakref.WeakKeyDictionary({o:364})
941 self.assert_(dict[o] == 364)
942
943 def test_make_weak_keyed_dict_from_weak_keyed_dict(self):
944 o = Object(3)
945 dict = weakref.WeakKeyDictionary({o:364})
946 dict2 = weakref.WeakKeyDictionary(dict)
947 self.assert_(dict[o] == 364)
948
Fred Drake0e540c32001-05-02 05:44:22 +0000949 def make_weak_keyed_dict(self):
950 dict = weakref.WeakKeyDictionary()
951 objects = map(Object, range(self.COUNT))
952 for o in objects:
953 dict[o] = o.arg
954 return dict, objects
955
956 def make_weak_valued_dict(self):
957 dict = weakref.WeakValueDictionary()
958 objects = map(Object, range(self.COUNT))
959 for o in objects:
960 dict[o.arg] = o
961 return dict, objects
962
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000963 def check_popitem(self, klass, key1, value1, key2, value2):
964 weakdict = klass()
965 weakdict[key1] = value1
966 weakdict[key2] = value2
967 self.assert_(len(weakdict) == 2)
968 k, v = weakdict.popitem()
969 self.assert_(len(weakdict) == 1)
970 if k is key1:
971 self.assert_(v is value1)
972 else:
973 self.assert_(v is value2)
974 k, v = weakdict.popitem()
975 self.assert_(len(weakdict) == 0)
976 if k is key1:
977 self.assert_(v is value1)
978 else:
979 self.assert_(v is value2)
980
981 def test_weak_valued_dict_popitem(self):
982 self.check_popitem(weakref.WeakValueDictionary,
983 "key1", C(), "key2", C())
984
985 def test_weak_keyed_dict_popitem(self):
986 self.check_popitem(weakref.WeakKeyDictionary,
987 C(), "value 1", C(), "value 2")
988
989 def check_setdefault(self, klass, key, value1, value2):
990 self.assert_(value1 is not value2,
991 "invalid test"
992 " -- value parameters must be distinct objects")
993 weakdict = klass()
994 o = weakdict.setdefault(key, value1)
Ezio Melottia65e2af2010-08-02 19:56:05 +0000995 self.assertTrue(o is value1)
996 self.assertTrue(key in weakdict)
997 self.assertTrue(weakdict.get(key) is value1)
998 self.assertTrue(weakdict[key] is value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000999
1000 o = weakdict.setdefault(key, value2)
Ezio Melottia65e2af2010-08-02 19:56:05 +00001001 self.assertTrue(o is value1)
1002 self.assertTrue(key in weakdict)
1003 self.assertTrue(weakdict.get(key) is value1)
1004 self.assertTrue(weakdict[key] is value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001005
1006 def test_weak_valued_dict_setdefault(self):
1007 self.check_setdefault(weakref.WeakValueDictionary,
1008 "key", C(), C())
1009
1010 def test_weak_keyed_dict_setdefault(self):
1011 self.check_setdefault(weakref.WeakKeyDictionary,
1012 C(), "value 1", "value 2")
1013
Fred Drakea0a4ab12001-04-16 17:37:27 +00001014 def check_update(self, klass, dict):
Fred Drake0e540c32001-05-02 05:44:22 +00001015 #
Ezio Melottia65e2af2010-08-02 19:56:05 +00001016 # This exercises d.update(), len(d), d.keys(), in d,
Fred Drake0e540c32001-05-02 05:44:22 +00001017 # d.get(), d[].
1018 #
Fred Drakea0a4ab12001-04-16 17:37:27 +00001019 weakdict = klass()
1020 weakdict.update(dict)
Ezio Melottia65e2af2010-08-02 19:56:05 +00001021 self.assertEqual(len(weakdict), len(dict))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001022 for k in weakdict.keys():
Ezio Melottia65e2af2010-08-02 19:56:05 +00001023 self.assertTrue(k in dict,
Fred Drakea0a4ab12001-04-16 17:37:27 +00001024 "mysterious new key appeared in weak dict")
1025 v = dict.get(k)
Ezio Melottia65e2af2010-08-02 19:56:05 +00001026 self.assertTrue(v is weakdict[k])
1027 self.assertTrue(v is weakdict.get(k))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001028 for k in dict.keys():
Ezio Melottia65e2af2010-08-02 19:56:05 +00001029 self.assertTrue(k in weakdict,
Fred Drakea0a4ab12001-04-16 17:37:27 +00001030 "original key disappeared in weak dict")
1031 v = dict[k]
Ezio Melottia65e2af2010-08-02 19:56:05 +00001032 self.assertTrue(v is weakdict[k])
1033 self.assertTrue(v is weakdict.get(k))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001034
1035 def test_weak_valued_dict_update(self):
1036 self.check_update(weakref.WeakValueDictionary,
1037 {1: C(), 'a': C(), C(): C()})
1038
1039 def test_weak_keyed_dict_update(self):
1040 self.check_update(weakref.WeakKeyDictionary,
1041 {C(): 1, C(): 2, C(): 3})
1042
Fred Drakeccc75622001-09-06 14:52:39 +00001043 def test_weak_keyed_delitem(self):
1044 d = weakref.WeakKeyDictionary()
1045 o1 = Object('1')
1046 o2 = Object('2')
1047 d[o1] = 'something'
1048 d[o2] = 'something'
1049 self.assert_(len(d) == 2)
1050 del d[o1]
1051 self.assert_(len(d) == 1)
1052 self.assert_(d.keys() == [o2])
1053
1054 def test_weak_valued_delitem(self):
1055 d = weakref.WeakValueDictionary()
1056 o1 = Object('1')
1057 o2 = Object('2')
1058 d['something'] = o1
1059 d['something else'] = o2
1060 self.assert_(len(d) == 2)
1061 del d['something']
1062 self.assert_(len(d) == 1)
1063 self.assert_(d.items() == [('something else', o2)])
1064
Tim Peters886128f2003-05-25 01:45:11 +00001065 def test_weak_keyed_bad_delitem(self):
1066 d = weakref.WeakKeyDictionary()
1067 o = Object('1')
1068 # An attempt to delete an object that isn't there should raise
Tim Peters50d8b8b2003-05-25 17:44:31 +00001069 # KeyError. It didn't before 2.3.
Tim Peters886128f2003-05-25 01:45:11 +00001070 self.assertRaises(KeyError, d.__delitem__, o)
Tim Peters50d8b8b2003-05-25 17:44:31 +00001071 self.assertRaises(KeyError, d.__getitem__, o)
1072
1073 # If a key isn't of a weakly referencable type, __getitem__ and
1074 # __setitem__ raise TypeError. __delitem__ should too.
1075 self.assertRaises(TypeError, d.__delitem__, 13)
1076 self.assertRaises(TypeError, d.__getitem__, 13)
1077 self.assertRaises(TypeError, d.__setitem__, 13, 13)
Tim Peters886128f2003-05-25 01:45:11 +00001078
1079 def test_weak_keyed_cascading_deletes(self):
1080 # SF bug 742860. For some reason, before 2.3 __delitem__ iterated
1081 # over the keys via self.data.iterkeys(). If things vanished from
1082 # the dict during this (or got added), that caused a RuntimeError.
1083
1084 d = weakref.WeakKeyDictionary()
1085 mutate = False
1086
1087 class C(object):
1088 def __init__(self, i):
1089 self.value = i
1090 def __hash__(self):
1091 return hash(self.value)
1092 def __eq__(self, other):
1093 if mutate:
1094 # Side effect that mutates the dict, by removing the
1095 # last strong reference to a key.
1096 del objs[-1]
1097 return self.value == other.value
1098
1099 objs = [C(i) for i in range(4)]
1100 for o in objs:
1101 d[o] = o.value
1102 del o # now the only strong references to keys are in objs
1103 # Find the order in which iterkeys sees the keys.
1104 objs = d.keys()
1105 # Reverse it, so that the iteration implementation of __delitem__
1106 # has to keep looping to find the first object we delete.
1107 objs.reverse()
Tim Peters50d8b8b2003-05-25 17:44:31 +00001108
Tim Peters886128f2003-05-25 01:45:11 +00001109 # Turn on mutation in C.__eq__. The first time thru the loop,
1110 # under the iterkeys() business the first comparison will delete
1111 # the last item iterkeys() would see, and that causes a
1112 # RuntimeError: dictionary changed size during iteration
1113 # when the iterkeys() loop goes around to try comparing the next
Tim Peters50d8b8b2003-05-25 17:44:31 +00001114 # key. After this was fixed, it just deletes the last object *our*
Tim Peters886128f2003-05-25 01:45:11 +00001115 # "for o in obj" loop would have gotten to.
1116 mutate = True
1117 count = 0
1118 for o in objs:
1119 count += 1
1120 del d[o]
1121 self.assertEqual(len(d), 0)
1122 self.assertEqual(count, 2)
1123
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001124from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001125
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001126class WeakValueDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +00001127 """Check that WeakValueDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001128 __ref = {"key1":Object(1), "key2":Object(2), "key3":Object(3)}
Walter Dörwald118f9312004-06-02 18:42:25 +00001129 type2test = weakref.WeakValueDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001130 def _reference(self):
1131 return self.__ref.copy()
1132
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001133class WeakKeyDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +00001134 """Check that WeakKeyDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001135 __ref = {Object("key1"):1, Object("key2"):2, Object("key3"):3}
Walter Dörwald118f9312004-06-02 18:42:25 +00001136 type2test = weakref.WeakKeyDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001137 def _reference(self):
1138 return self.__ref.copy()
Martin v. Löwis5e163332001-02-27 18:36:56 +00001139
Georg Brandl88659b02008-05-20 08:40:43 +00001140libreftest = """ Doctest for examples in the library reference: weakref.rst
Georg Brandl9a65d582005-07-02 19:07:30 +00001141
1142>>> import weakref
1143>>> class Dict(dict):
1144... pass
1145...
1146>>> obj = Dict(red=1, green=2, blue=3) # this object is weak referencable
1147>>> r = weakref.ref(obj)
Armin Rigoa3f09272006-05-28 19:13:17 +00001148>>> print r() is obj
1149True
Georg Brandl9a65d582005-07-02 19:07:30 +00001150
1151>>> import weakref
1152>>> class Object:
1153... pass
1154...
1155>>> o = Object()
1156>>> r = weakref.ref(o)
1157>>> o2 = r()
1158>>> o is o2
1159True
1160>>> del o, o2
1161>>> print r()
1162None
1163
1164>>> import weakref
1165>>> class ExtendedRef(weakref.ref):
1166... def __init__(self, ob, callback=None, **annotations):
1167... super(ExtendedRef, self).__init__(ob, callback)
1168... self.__counter = 0
1169... for k, v in annotations.iteritems():
1170... setattr(self, k, v)
1171... def __call__(self):
1172... '''Return a pair containing the referent and the number of
1173... times the reference has been called.
1174... '''
1175... ob = super(ExtendedRef, self).__call__()
1176... if ob is not None:
1177... self.__counter += 1
1178... ob = (ob, self.__counter)
1179... return ob
1180...
1181>>> class A: # not in docs from here, just testing the ExtendedRef
1182... pass
1183...
1184>>> a = A()
1185>>> r = ExtendedRef(a, foo=1, bar="baz")
1186>>> r.foo
11871
1188>>> r.bar
1189'baz'
1190>>> r()[1]
11911
1192>>> r()[1]
11932
1194>>> r()[0] is a
1195True
1196
1197
1198>>> import weakref
1199>>> _id2obj_dict = weakref.WeakValueDictionary()
1200>>> def remember(obj):
1201... oid = id(obj)
1202... _id2obj_dict[oid] = obj
1203... return oid
1204...
1205>>> def id2obj(oid):
1206... return _id2obj_dict[oid]
1207...
1208>>> a = A() # from here, just testing
1209>>> a_id = remember(a)
1210>>> id2obj(a_id) is a
1211True
1212>>> del a
1213>>> try:
1214... id2obj(a_id)
1215... except KeyError:
1216... print 'OK'
1217... else:
1218... print 'WeakValueDictionary error'
1219OK
1220
1221"""
1222
1223__test__ = {'libreftest' : libreftest}
1224
Fred Drake2e2be372001-09-20 21:33:42 +00001225def test_main():
Walter Dörwald21d3a322003-05-01 17:45:56 +00001226 test_support.run_unittest(
1227 ReferencesTestCase,
1228 MappingTestCase,
1229 WeakValueDictionaryTestCase,
Fred Drakef425b1e2003-07-14 21:37:17 +00001230 WeakKeyDictionaryTestCase,
Amaury Forgeot d'Arca8919fe2008-06-16 19:12:42 +00001231 SubclassableWeakrefTestCase,
Fred Drakef425b1e2003-07-14 21:37:17 +00001232 )
Georg Brandl9a65d582005-07-02 19:07:30 +00001233 test_support.run_doctest(sys.modules[__name__])
Fred Drake2e2be372001-09-20 21:33:42 +00001234
1235
1236if __name__ == "__main__":
1237 test_main()