blob: 9821e1ba759864ab692fe04c2db039db3e55a1be [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
Raymond Hettinger53dbe392008-02-12 20:03:09 +00004import collections
Fred Drake41deb1e2001-02-01 05:27:45 +00005import weakref
Georg Brandlb533e262008-05-25 18:19:30 +00006import operator
Fred Drake41deb1e2001-02-01 05:27:45 +00007
Benjamin Petersonee8712c2008-05-20 21:35:26 +00008from test import support
Fred Drake41deb1e2001-02-01 05:27:45 +00009
Thomas Woutersb2137042007-02-01 18:02:27 +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
Fred Drake41deb1e2001-02-01 05:27:45 +000032
Fred Drakeb0fefc52001-03-23 04:22:45 +000033class TestBase(unittest.TestCase):
34
35 def setUp(self):
36 self.cbcalled = 0
37
38 def callback(self, ref):
39 self.cbcalled += 1
Fred Drake41deb1e2001-02-01 05:27:45 +000040
41
Fred Drakeb0fefc52001-03-23 04:22:45 +000042class ReferencesTestCase(TestBase):
Fred Drake41deb1e2001-02-01 05:27:45 +000043
Fred Drakeb0fefc52001-03-23 04:22:45 +000044 def test_basic_ref(self):
45 self.check_basic_ref(C)
46 self.check_basic_ref(create_function)
47 self.check_basic_ref(create_bound_method)
Fred Drake41deb1e2001-02-01 05:27:45 +000048
Fred Drake43735da2002-04-11 03:59:42 +000049 # Just make sure the tp_repr handler doesn't raise an exception.
50 # Live reference:
51 o = C()
52 wr = weakref.ref(o)
Brett Cannon0b70cca2006-08-25 02:59:59 +000053 repr(wr)
Fred Drake43735da2002-04-11 03:59:42 +000054 # Dead reference:
55 del o
Brett Cannon0b70cca2006-08-25 02:59:59 +000056 repr(wr)
Fred Drake43735da2002-04-11 03:59:42 +000057
Fred Drakeb0fefc52001-03-23 04:22:45 +000058 def test_basic_callback(self):
59 self.check_basic_callback(C)
60 self.check_basic_callback(create_function)
61 self.check_basic_callback(create_bound_method)
Fred Drake41deb1e2001-02-01 05:27:45 +000062
Fred Drakeb0fefc52001-03-23 04:22:45 +000063 def test_multiple_callbacks(self):
64 o = C()
65 ref1 = weakref.ref(o, self.callback)
66 ref2 = weakref.ref(o, self.callback)
67 del o
68 self.assert_(ref1() is None,
69 "expected reference to be invalidated")
70 self.assert_(ref2() is None,
71 "expected reference to be invalidated")
72 self.assert_(self.cbcalled == 2,
73 "callback not called the right number of times")
Fred Drake41deb1e2001-02-01 05:27:45 +000074
Fred Drake705088e2001-04-13 17:18:15 +000075 def test_multiple_selfref_callbacks(self):
Guido van Rossum9eee5542002-08-22 20:21:30 +000076 # Make sure all references are invalidated before callbacks are called
Fred Drake705088e2001-04-13 17:18:15 +000077 #
78 # What's important here is that we're using the first
79 # reference in the callback invoked on the second reference
80 # (the most recently created ref is cleaned up first). This
81 # tests that all references to the object are invalidated
82 # before any of the callbacks are invoked, so that we only
83 # have one invocation of _weakref.c:cleanup_helper() active
84 # for a particular object at a time.
85 #
86 def callback(object, self=self):
87 self.ref()
88 c = C()
89 self.ref = weakref.ref(c, callback)
90 ref1 = weakref.ref(c, callback)
91 del c
92
Fred Drakeb0fefc52001-03-23 04:22:45 +000093 def test_proxy_ref(self):
94 o = C()
95 o.bar = 1
96 ref1 = weakref.proxy(o, self.callback)
97 ref2 = weakref.proxy(o, self.callback)
98 del o
Fred Drake41deb1e2001-02-01 05:27:45 +000099
Fred Drakeb0fefc52001-03-23 04:22:45 +0000100 def check(proxy):
101 proxy.bar
Fred Drake41deb1e2001-02-01 05:27:45 +0000102
Neal Norwitz2633c692007-02-26 22:22:47 +0000103 self.assertRaises(ReferenceError, check, ref1)
104 self.assertRaises(ReferenceError, check, ref2)
105 self.assertRaises(ReferenceError, bool, weakref.proxy(C()))
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000106 self.assertEqual(self.cbcalled, 2)
Fred Drake41deb1e2001-02-01 05:27:45 +0000107
Fred Drakeb0fefc52001-03-23 04:22:45 +0000108 def check_basic_ref(self, factory):
109 o = factory()
110 ref = weakref.ref(o)
111 self.assert_(ref() is not None,
112 "weak reference to live object should be live")
113 o2 = ref()
114 self.assert_(o is o2,
115 "<ref>() should return original object if live")
Fred Drake41deb1e2001-02-01 05:27:45 +0000116
Fred Drakeb0fefc52001-03-23 04:22:45 +0000117 def check_basic_callback(self, factory):
118 self.cbcalled = 0
119 o = factory()
120 ref = weakref.ref(o, self.callback)
121 del o
Fred Drake705088e2001-04-13 17:18:15 +0000122 self.assert_(self.cbcalled == 1,
123 "callback did not properly set 'cbcalled'")
124 self.assert_(ref() is None,
125 "ref2 should be dead after deleting object reference")
Fred Drake41deb1e2001-02-01 05:27:45 +0000126
Fred Drakeb0fefc52001-03-23 04:22:45 +0000127 def test_ref_reuse(self):
128 o = C()
129 ref1 = weakref.ref(o)
130 # create a proxy to make sure that there's an intervening creation
131 # between these two; it should make no difference
132 proxy = weakref.proxy(o)
133 ref2 = weakref.ref(o)
134 self.assert_(ref1 is ref2,
135 "reference object w/out callback should be re-used")
Fred Drake41deb1e2001-02-01 05:27:45 +0000136
Fred Drakeb0fefc52001-03-23 04:22:45 +0000137 o = C()
138 proxy = weakref.proxy(o)
139 ref1 = weakref.ref(o)
140 ref2 = weakref.ref(o)
141 self.assert_(ref1 is ref2,
142 "reference object w/out callback should be re-used")
143 self.assert_(weakref.getweakrefcount(o) == 2,
144 "wrong weak ref count for object")
145 del proxy
146 self.assert_(weakref.getweakrefcount(o) == 1,
147 "wrong weak ref count for object after deleting proxy")
Fred Drake41deb1e2001-02-01 05:27:45 +0000148
Fred Drakeb0fefc52001-03-23 04:22:45 +0000149 def test_proxy_reuse(self):
150 o = C()
151 proxy1 = weakref.proxy(o)
152 ref = weakref.ref(o)
153 proxy2 = weakref.proxy(o)
154 self.assert_(proxy1 is proxy2,
155 "proxy object w/out callback should have been re-used")
156
157 def test_basic_proxy(self):
158 o = C()
159 self.check_proxy(o, weakref.proxy(o))
160
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000161 L = collections.UserList()
Fred Drake5935ff02001-12-19 16:54:23 +0000162 p = weakref.proxy(L)
163 self.failIf(p, "proxy for empty UserList should be false")
164 p.append(12)
165 self.assertEqual(len(L), 1)
166 self.failUnless(p, "proxy for non-empty UserList should be true")
167 p[:] = [2, 3]
168 self.assertEqual(len(L), 2)
169 self.assertEqual(len(p), 2)
Fred Drakef425b1e2003-07-14 21:37:17 +0000170 self.failUnless(3 in p,
171 "proxy didn't support __contains__() properly")
Fred Drake5935ff02001-12-19 16:54:23 +0000172 p[1] = 5
173 self.assertEqual(L[1], 5)
174 self.assertEqual(p[1], 5)
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000175 L2 = collections.UserList(L)
Fred Drake5935ff02001-12-19 16:54:23 +0000176 p2 = weakref.proxy(L2)
177 self.assertEqual(p, p2)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000178 ## self.assertEqual(repr(L2), repr(p2))
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000179 L3 = collections.UserList(range(10))
Fred Drake43735da2002-04-11 03:59:42 +0000180 p3 = weakref.proxy(L3)
181 self.assertEqual(L3[:], p3[:])
182 self.assertEqual(L3[5:], p3[5:])
183 self.assertEqual(L3[:5], p3[:5])
184 self.assertEqual(L3[2:5], p3[2:5])
Fred Drake5935ff02001-12-19 16:54:23 +0000185
Georg Brandlb533e262008-05-25 18:19:30 +0000186 def test_proxy_index(self):
187 class C:
188 def __index__(self):
189 return 10
190 o = C()
191 p = weakref.proxy(o)
192 self.assertEqual(operator.index(p), 10)
193
194 def test_proxy_div(self):
195 class C:
196 def __floordiv__(self, other):
197 return 42
198 def __ifloordiv__(self, other):
199 return 21
200 o = C()
201 p = weakref.proxy(o)
202 self.assertEqual(p // 5, 42)
203 p //= 5
204 self.assertEqual(p, 21)
205
Fred Drakeea2adc92004-02-03 19:56:46 +0000206 # The PyWeakref_* C API is documented as allowing either NULL or
207 # None as the value for the callback, where either means "no
208 # callback". The "no callback" ref and proxy objects are supposed
209 # to be shared so long as they exist by all callers so long as
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000210 # they are active. In Python 2.3.3 and earlier, this guarantee
Fred Drakeea2adc92004-02-03 19:56:46 +0000211 # was not honored, and was broken in different ways for
212 # PyWeakref_NewRef() and PyWeakref_NewProxy(). (Two tests.)
213
214 def test_shared_ref_without_callback(self):
215 self.check_shared_without_callback(weakref.ref)
216
217 def test_shared_proxy_without_callback(self):
218 self.check_shared_without_callback(weakref.proxy)
219
220 def check_shared_without_callback(self, makeref):
221 o = Object(1)
222 p1 = makeref(o, None)
223 p2 = makeref(o, None)
224 self.assert_(p1 is p2, "both callbacks were None in the C API")
225 del p1, p2
226 p1 = makeref(o)
227 p2 = makeref(o, None)
228 self.assert_(p1 is p2, "callbacks were NULL, None in the C API")
229 del p1, p2
230 p1 = makeref(o)
231 p2 = makeref(o)
232 self.assert_(p1 is p2, "both callbacks were NULL in the C API")
233 del p1, p2
234 p1 = makeref(o, None)
235 p2 = makeref(o)
236 self.assert_(p1 is p2, "callbacks were None, NULL in the C API")
237
Fred Drakeb0fefc52001-03-23 04:22:45 +0000238 def test_callable_proxy(self):
239 o = Callable()
240 ref1 = weakref.proxy(o)
241
242 self.check_proxy(o, ref1)
243
244 self.assert_(type(ref1) is weakref.CallableProxyType,
245 "proxy is not of callable type")
246 ref1('twinkies!')
247 self.assert_(o.bar == 'twinkies!',
248 "call through proxy not passed through to original")
Fred Drake3bb4d212001-10-18 19:28:29 +0000249 ref1(x='Splat.')
250 self.assert_(o.bar == 'Splat.',
251 "call through proxy not passed through to original")
Fred Drakeb0fefc52001-03-23 04:22:45 +0000252
253 # expect due to too few args
254 self.assertRaises(TypeError, ref1)
255
256 # expect due to too many args
257 self.assertRaises(TypeError, ref1, 1, 2, 3)
258
259 def check_proxy(self, o, proxy):
260 o.foo = 1
261 self.assert_(proxy.foo == 1,
262 "proxy does not reflect attribute addition")
263 o.foo = 2
264 self.assert_(proxy.foo == 2,
265 "proxy does not reflect attribute modification")
266 del o.foo
267 self.assert_(not hasattr(proxy, 'foo'),
268 "proxy does not reflect attribute removal")
269
270 proxy.foo = 1
271 self.assert_(o.foo == 1,
272 "object does not reflect attribute addition via proxy")
273 proxy.foo = 2
274 self.assert_(
275 o.foo == 2,
276 "object does not reflect attribute modification via proxy")
277 del proxy.foo
278 self.assert_(not hasattr(o, 'foo'),
279 "object does not reflect attribute removal via proxy")
280
Raymond Hettingerd693a812003-06-30 04:18:48 +0000281 def test_proxy_deletion(self):
282 # Test clearing of SF bug #762891
283 class Foo:
284 result = None
285 def __delitem__(self, accessor):
286 self.result = accessor
287 g = Foo()
288 f = weakref.proxy(g)
289 del f[0]
290 self.assertEqual(f.result, 0)
291
Raymond Hettingere6c470f2005-03-27 03:04:54 +0000292 def test_proxy_bool(self):
293 # Test clearing of SF bug #1170766
294 class List(list): pass
295 lyst = List()
296 self.assertEqual(bool(weakref.proxy(lyst)), bool(lyst))
297
Fred Drakeb0fefc52001-03-23 04:22:45 +0000298 def test_getweakrefcount(self):
299 o = C()
300 ref1 = weakref.ref(o)
301 ref2 = weakref.ref(o, self.callback)
302 self.assert_(weakref.getweakrefcount(o) == 2,
303 "got wrong number of weak reference objects")
304
305 proxy1 = weakref.proxy(o)
306 proxy2 = weakref.proxy(o, self.callback)
307 self.assert_(weakref.getweakrefcount(o) == 4,
308 "got wrong number of weak reference objects")
309
Fred Drakeea2adc92004-02-03 19:56:46 +0000310 del ref1, ref2, proxy1, proxy2
311 self.assert_(weakref.getweakrefcount(o) == 0,
312 "weak reference objects not unlinked from"
313 " referent when discarded.")
314
Walter Dörwaldb167b042003-12-11 12:34:05 +0000315 # assumes ints do not support weakrefs
316 self.assert_(weakref.getweakrefcount(1) == 0,
317 "got wrong number of weak reference objects for int")
318
Fred Drakeb0fefc52001-03-23 04:22:45 +0000319 def test_getweakrefs(self):
320 o = C()
321 ref1 = weakref.ref(o, self.callback)
322 ref2 = weakref.ref(o, self.callback)
323 del ref1
324 self.assert_(weakref.getweakrefs(o) == [ref2],
325 "list of refs does not match")
326
327 o = C()
328 ref1 = weakref.ref(o, self.callback)
329 ref2 = weakref.ref(o, self.callback)
330 del ref2
331 self.assert_(weakref.getweakrefs(o) == [ref1],
332 "list of refs does not match")
333
Fred Drakeea2adc92004-02-03 19:56:46 +0000334 del ref1
335 self.assert_(weakref.getweakrefs(o) == [],
336 "list of refs not cleared")
337
Walter Dörwaldb167b042003-12-11 12:34:05 +0000338 # assumes ints do not support weakrefs
339 self.assert_(weakref.getweakrefs(1) == [],
340 "list of refs does not match for int")
341
Fred Drake39c27f12001-10-18 18:06:05 +0000342 def test_newstyle_number_ops(self):
343 class F(float):
344 pass
345 f = F(2.0)
346 p = weakref.proxy(f)
347 self.assert_(p + 1.0 == 3.0)
348 self.assert_(1.0 + p == 3.0) # this used to SEGV
349
Fred Drake2a64f462001-12-10 23:46:02 +0000350 def test_callbacks_protected(self):
Guido van Rossum9eee5542002-08-22 20:21:30 +0000351 # Callbacks protected from already-set exceptions?
Fred Drake2a64f462001-12-10 23:46:02 +0000352 # Regression test for SF bug #478534.
353 class BogusError(Exception):
354 pass
355 data = {}
356 def remove(k):
357 del data[k]
358 def encapsulate():
359 f = lambda : ()
360 data[weakref.ref(f, remove)] = None
361 raise BogusError
362 try:
363 encapsulate()
364 except BogusError:
365 pass
366 else:
367 self.fail("exception not properly restored")
368 try:
369 encapsulate()
370 except BogusError:
371 pass
372 else:
373 self.fail("exception not properly restored")
374
Tim Petersadd09b42003-11-12 20:43:28 +0000375 def test_sf_bug_840829(self):
376 # "weakref callbacks and gc corrupt memory"
377 # subtype_dealloc erroneously exposed a new-style instance
378 # already in the process of getting deallocated to gc,
379 # causing double-deallocation if the instance had a weakref
380 # callback that triggered gc.
381 # If the bug exists, there probably won't be an obvious symptom
382 # in a release build. In a debug build, a segfault will occur
383 # when the second attempt to remove the instance from the "list
384 # of all objects" occurs.
385
386 import gc
387
388 class C(object):
389 pass
390
391 c = C()
392 wr = weakref.ref(c, lambda ignore: gc.collect())
393 del c
394
Tim Petersf7f9e992003-11-13 21:59:32 +0000395 # There endeth the first part. It gets worse.
396 del wr
397
398 c1 = C()
399 c1.i = C()
400 wr = weakref.ref(c1.i, lambda ignore: gc.collect())
401
402 c2 = C()
403 c2.c1 = c1
404 del c1 # still alive because c2 points to it
405
406 # Now when subtype_dealloc gets called on c2, it's not enough just
407 # that c2 is immune from gc while the weakref callbacks associated
408 # with c2 execute (there are none in this 2nd half of the test, btw).
409 # subtype_dealloc goes on to call the base classes' deallocs too,
410 # so any gc triggered by weakref callbacks associated with anything
411 # torn down by a base class dealloc can also trigger double
412 # deallocation of c2.
413 del c2
Fred Drake41deb1e2001-02-01 05:27:45 +0000414
Tim Peters403a2032003-11-20 21:21:46 +0000415 def test_callback_in_cycle_1(self):
416 import gc
417
418 class J(object):
419 pass
420
421 class II(object):
422 def acallback(self, ignore):
423 self.J
424
425 I = II()
426 I.J = J
427 I.wr = weakref.ref(J, I.acallback)
428
429 # Now J and II are each in a self-cycle (as all new-style class
430 # objects are, since their __mro__ points back to them). I holds
431 # both a weak reference (I.wr) and a strong reference (I.J) to class
432 # J. I is also in a cycle (I.wr points to a weakref that references
433 # I.acallback). When we del these three, they all become trash, but
434 # the cycles prevent any of them from getting cleaned up immediately.
435 # Instead they have to wait for cyclic gc to deduce that they're
436 # trash.
437 #
438 # gc used to call tp_clear on all of them, and the order in which
439 # it does that is pretty accidental. The exact order in which we
440 # built up these things manages to provoke gc into running tp_clear
441 # in just the right order (I last). Calling tp_clear on II leaves
442 # behind an insane class object (its __mro__ becomes NULL). Calling
443 # tp_clear on J breaks its self-cycle, but J doesn't get deleted
444 # just then because of the strong reference from I.J. Calling
445 # tp_clear on I starts to clear I's __dict__, and just happens to
446 # clear I.J first -- I.wr is still intact. That removes the last
447 # reference to J, which triggers the weakref callback. The callback
448 # tries to do "self.J", and instances of new-style classes look up
449 # attributes ("J") in the class dict first. The class (II) wants to
450 # search II.__mro__, but that's NULL. The result was a segfault in
451 # a release build, and an assert failure in a debug build.
452 del I, J, II
453 gc.collect()
454
455 def test_callback_in_cycle_2(self):
456 import gc
457
458 # This is just like test_callback_in_cycle_1, except that II is an
459 # old-style class. The symptom is different then: an instance of an
460 # old-style class looks in its own __dict__ first. 'J' happens to
461 # get cleared from I.__dict__ before 'wr', and 'J' was never in II's
462 # __dict__, so the attribute isn't found. The difference is that
463 # the old-style II doesn't have a NULL __mro__ (it doesn't have any
464 # __mro__), so no segfault occurs. Instead it got:
465 # test_callback_in_cycle_2 (__main__.ReferencesTestCase) ...
466 # Exception exceptions.AttributeError:
467 # "II instance has no attribute 'J'" in <bound method II.acallback
468 # of <?.II instance at 0x00B9B4B8>> ignored
469
470 class J(object):
471 pass
472
473 class II:
474 def acallback(self, ignore):
475 self.J
476
477 I = II()
478 I.J = J
479 I.wr = weakref.ref(J, I.acallback)
480
481 del I, J, II
482 gc.collect()
483
484 def test_callback_in_cycle_3(self):
485 import gc
486
487 # This one broke the first patch that fixed the last two. In this
488 # case, the objects reachable from the callback aren't also reachable
489 # from the object (c1) *triggering* the callback: you can get to
490 # c1 from c2, but not vice-versa. The result was that c2's __dict__
491 # got tp_clear'ed by the time the c2.cb callback got invoked.
492
493 class C:
494 def cb(self, ignore):
495 self.me
496 self.c1
497 self.wr
498
499 c1, c2 = C(), C()
500
501 c2.me = c2
502 c2.c1 = c1
503 c2.wr = weakref.ref(c1, c2.cb)
504
505 del c1, c2
506 gc.collect()
507
508 def test_callback_in_cycle_4(self):
509 import gc
510
511 # Like test_callback_in_cycle_3, except c2 and c1 have different
512 # classes. c2's class (C) isn't reachable from c1 then, so protecting
513 # objects reachable from the dying object (c1) isn't enough to stop
514 # c2's class (C) from getting tp_clear'ed before c2.cb is invoked.
515 # The result was a segfault (C.__mro__ was NULL when the callback
516 # tried to look up self.me).
517
518 class C(object):
519 def cb(self, ignore):
520 self.me
521 self.c1
522 self.wr
523
524 class D:
525 pass
526
527 c1, c2 = D(), C()
528
529 c2.me = c2
530 c2.c1 = c1
531 c2.wr = weakref.ref(c1, c2.cb)
532
533 del c1, c2, C, D
534 gc.collect()
535
536 def test_callback_in_cycle_resurrection(self):
537 import gc
538
539 # Do something nasty in a weakref callback: resurrect objects
540 # from dead cycles. For this to be attempted, the weakref and
541 # its callback must also be part of the cyclic trash (else the
542 # objects reachable via the callback couldn't be in cyclic trash
543 # to begin with -- the callback would act like an external root).
544 # But gc clears trash weakrefs with callbacks early now, which
545 # disables the callbacks, so the callbacks shouldn't get called
546 # at all (and so nothing actually gets resurrected).
547
548 alist = []
549 class C(object):
550 def __init__(self, value):
551 self.attribute = value
552
553 def acallback(self, ignore):
554 alist.append(self.c)
555
556 c1, c2 = C(1), C(2)
557 c1.c = c2
558 c2.c = c1
559 c1.wr = weakref.ref(c2, c1.acallback)
560 c2.wr = weakref.ref(c1, c2.acallback)
561
562 def C_went_away(ignore):
563 alist.append("C went away")
564 wr = weakref.ref(C, C_went_away)
565
566 del c1, c2, C # make them all trash
567 self.assertEqual(alist, []) # del isn't enough to reclaim anything
568
569 gc.collect()
570 # c1.wr and c2.wr were part of the cyclic trash, so should have
571 # been cleared without their callbacks executing. OTOH, the weakref
572 # to C is bound to a function local (wr), and wasn't trash, so that
573 # callback should have been invoked when C went away.
574 self.assertEqual(alist, ["C went away"])
575 # The remaining weakref should be dead now (its callback ran).
576 self.assertEqual(wr(), None)
577
578 del alist[:]
579 gc.collect()
580 self.assertEqual(alist, [])
581
582 def test_callbacks_on_callback(self):
583 import gc
584
585 # Set up weakref callbacks *on* weakref callbacks.
586 alist = []
587 def safe_callback(ignore):
588 alist.append("safe_callback called")
589
590 class C(object):
591 def cb(self, ignore):
592 alist.append("cb called")
593
594 c, d = C(), C()
595 c.other = d
596 d.other = c
597 callback = c.cb
598 c.wr = weakref.ref(d, callback) # this won't trigger
599 d.wr = weakref.ref(callback, d.cb) # ditto
600 external_wr = weakref.ref(callback, safe_callback) # but this will
601 self.assert_(external_wr() is callback)
602
603 # The weakrefs attached to c and d should get cleared, so that
604 # C.cb is never called. But external_wr isn't part of the cyclic
605 # trash, and no cyclic trash is reachable from it, so safe_callback
606 # should get invoked when the bound method object callback (c.cb)
607 # -- which is itself a callback, and also part of the cyclic trash --
608 # gets reclaimed at the end of gc.
609
610 del callback, c, d, C
611 self.assertEqual(alist, []) # del isn't enough to clean up cycles
612 gc.collect()
613 self.assertEqual(alist, ["safe_callback called"])
614 self.assertEqual(external_wr(), None)
615
616 del alist[:]
617 gc.collect()
618 self.assertEqual(alist, [])
619
Fred Drakebc875f52004-02-04 23:14:14 +0000620 def test_gc_during_ref_creation(self):
621 self.check_gc_during_creation(weakref.ref)
622
623 def test_gc_during_proxy_creation(self):
624 self.check_gc_during_creation(weakref.proxy)
625
626 def check_gc_during_creation(self, makeref):
627 thresholds = gc.get_threshold()
628 gc.set_threshold(1, 1, 1)
629 gc.collect()
Fred Drake55cf4342004-02-13 19:21:57 +0000630 class A:
631 pass
Fred Drakebc875f52004-02-04 23:14:14 +0000632
633 def callback(*args):
634 pass
635
Fred Drake55cf4342004-02-13 19:21:57 +0000636 referenced = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000637
Fred Drake55cf4342004-02-13 19:21:57 +0000638 a = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000639 a.a = a
640 a.wr = makeref(referenced)
641
642 try:
643 # now make sure the object and the ref get labeled as
644 # cyclic trash:
Fred Drake55cf4342004-02-13 19:21:57 +0000645 a = A()
646 weakref.ref(referenced, callback)
Fred Drakebc875f52004-02-04 23:14:14 +0000647
648 finally:
649 gc.set_threshold(*thresholds)
650
Thomas Woutersb2137042007-02-01 18:02:27 +0000651 def test_ref_created_during_del(self):
652 # Bug #1377858
653 # A weakref created in an object's __del__() would crash the
654 # interpreter when the weakref was cleaned up since it would refer to
655 # non-existent memory. This test should not segfault the interpreter.
656 class Target(object):
657 def __del__(self):
658 global ref_from_del
659 ref_from_del = weakref.ref(self)
660
661 w = Target()
662
Benjamin Peterson9aa42992008-09-10 21:57:34 +0000663 def test_init(self):
664 # Issue 3634
665 # <weakref to class>.__init__() doesn't check errors correctly
666 r = weakref.ref(Exception)
667 self.assertRaises(TypeError, r.__init__, 0, 0, 0, 0, 0)
668 # No exception should be raised here
669 gc.collect()
670
Fred Drake0a4dd392004-07-02 18:57:45 +0000671
Amaury Forgeot d'Arcc856c7a2008-06-16 19:50:09 +0000672class SubclassableWeakrefTestCase(TestBase):
Fred Drake0a4dd392004-07-02 18:57:45 +0000673
674 def test_subclass_refs(self):
675 class MyRef(weakref.ref):
676 def __init__(self, ob, callback=None, value=42):
677 self.value = value
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000678 super().__init__(ob, callback)
Fred Drake0a4dd392004-07-02 18:57:45 +0000679 def __call__(self):
680 self.called = True
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000681 return super().__call__()
Fred Drake0a4dd392004-07-02 18:57:45 +0000682 o = Object("foo")
683 mr = MyRef(o, value=24)
684 self.assert_(mr() is o)
685 self.assert_(mr.called)
686 self.assertEqual(mr.value, 24)
687 del o
688 self.assert_(mr() is None)
689 self.assert_(mr.called)
690
691 def test_subclass_refs_dont_replace_standard_refs(self):
692 class MyRef(weakref.ref):
693 pass
694 o = Object(42)
695 r1 = MyRef(o)
696 r2 = weakref.ref(o)
697 self.assert_(r1 is not r2)
698 self.assertEqual(weakref.getweakrefs(o), [r2, r1])
699 self.assertEqual(weakref.getweakrefcount(o), 2)
700 r3 = MyRef(o)
701 self.assertEqual(weakref.getweakrefcount(o), 3)
702 refs = weakref.getweakrefs(o)
703 self.assertEqual(len(refs), 3)
704 self.assert_(r2 is refs[0])
705 self.assert_(r1 in refs[1:])
706 self.assert_(r3 in refs[1:])
707
708 def test_subclass_refs_dont_conflate_callbacks(self):
709 class MyRef(weakref.ref):
710 pass
711 o = Object(42)
712 r1 = MyRef(o, id)
713 r2 = MyRef(o, str)
714 self.assert_(r1 is not r2)
715 refs = weakref.getweakrefs(o)
716 self.assert_(r1 in refs)
717 self.assert_(r2 in refs)
718
719 def test_subclass_refs_with_slots(self):
720 class MyRef(weakref.ref):
721 __slots__ = "slot1", "slot2"
722 def __new__(type, ob, callback, slot1, slot2):
723 return weakref.ref.__new__(type, ob, callback)
724 def __init__(self, ob, callback, slot1, slot2):
725 self.slot1 = slot1
726 self.slot2 = slot2
727 def meth(self):
728 return self.slot1 + self.slot2
729 o = Object(42)
730 r = MyRef(o, None, "abc", "def")
731 self.assertEqual(r.slot1, "abc")
732 self.assertEqual(r.slot2, "def")
733 self.assertEqual(r.meth(), "abcdef")
734 self.failIf(hasattr(r, "__dict__"))
735
Amaury Forgeot d'Arcc856c7a2008-06-16 19:50:09 +0000736 def test_subclass_refs_with_cycle(self):
737 # Bug #3110
738 # An instance of a weakref subclass can have attributes.
739 # If such a weakref holds the only strong reference to the object,
740 # deleting the weakref will delete the object. In this case,
741 # the callback must not be called, because the ref object is
742 # being deleted.
743 class MyRef(weakref.ref):
744 pass
745
746 # Use a local callback, for "regrtest -R::"
747 # to detect refcounting problems
748 def callback(w):
749 self.cbcalled += 1
750
751 o = C()
752 r1 = MyRef(o, callback)
753 r1.o = o
754 del o
755
756 del r1 # Used to crash here
757
758 self.assertEqual(self.cbcalled, 0)
759
760 # Same test, with two weakrefs to the same object
761 # (since code paths are different)
762 o = C()
763 r1 = MyRef(o, callback)
764 r2 = MyRef(o, callback)
765 r1.r = r2
766 r2.o = o
767 del o
768 del r2
769
770 del r1 # Used to crash here
771
772 self.assertEqual(self.cbcalled, 0)
773
Fred Drake0a4dd392004-07-02 18:57:45 +0000774
Fred Drake41deb1e2001-02-01 05:27:45 +0000775class Object:
776 def __init__(self, arg):
777 self.arg = arg
778 def __repr__(self):
779 return "<Object %r>" % self.arg
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000780 def __lt__(self, other):
781 if isinstance(other, Object):
782 return self.arg < other.arg
783 return NotImplemented
784 def __hash__(self):
785 return hash(self.arg)
Fred Drake41deb1e2001-02-01 05:27:45 +0000786
Fred Drake41deb1e2001-02-01 05:27:45 +0000787
Fred Drakeb0fefc52001-03-23 04:22:45 +0000788class MappingTestCase(TestBase):
Martin v. Löwis5e163332001-02-27 18:36:56 +0000789
Fred Drakeb0fefc52001-03-23 04:22:45 +0000790 COUNT = 10
791
792 def test_weak_values(self):
Fred Drake0e540c32001-05-02 05:44:22 +0000793 #
794 # This exercises d.copy(), d.items(), d[], del d[], len(d).
795 #
796 dict, objects = self.make_weak_valued_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +0000797 for o in objects:
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000798 self.assertEqual(weakref.getweakrefcount(o), 1)
Fred Drakeb0fefc52001-03-23 04:22:45 +0000799 self.assert_(o is dict[o.arg],
800 "wrong object returned by weak dict!")
Barry Warsawecaab832008-09-04 01:42:51 +0000801 items1 = list(dict.items())
802 items2 = list(dict.copy().items())
Fred Drakeb0fefc52001-03-23 04:22:45 +0000803 items1.sort()
804 items2.sort()
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000805 self.assertEqual(items1, items2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000806 "cloning of weak-valued dictionary did not work!")
807 del items1, items2
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000808 self.assertEqual(len(dict), self.COUNT)
Fred Drakeb0fefc52001-03-23 04:22:45 +0000809 del objects[0]
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000810 self.assertEqual(len(dict), self.COUNT - 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000811 "deleting object did not cause dictionary update")
812 del objects, o
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000813 self.assertEqual(len(dict), 0,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000814 "deleting the values did not clear the dictionary")
Fred Drake4fd06e02001-08-03 04:11:27 +0000815 # regression on SF bug #447152:
816 dict = weakref.WeakValueDictionary()
817 self.assertRaises(KeyError, dict.__getitem__, 1)
818 dict[2] = C()
819 self.assertRaises(KeyError, dict.__getitem__, 2)
Fred Drakeb0fefc52001-03-23 04:22:45 +0000820
821 def test_weak_keys(self):
Fred Drake0e540c32001-05-02 05:44:22 +0000822 #
823 # This exercises d.copy(), d.items(), d[] = v, d[], del d[],
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000824 # len(d), k in d.
Fred Drake0e540c32001-05-02 05:44:22 +0000825 #
826 dict, objects = self.make_weak_keyed_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +0000827 for o in objects:
828 self.assert_(weakref.getweakrefcount(o) == 1,
829 "wrong number of weak references to %r!" % o)
830 self.assert_(o.arg is dict[o],
831 "wrong object returned by weak dict!")
832 items1 = dict.items()
833 items2 = dict.copy().items()
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000834 self.assertEqual(set(items1), set(items2),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000835 "cloning of weak-keyed dictionary did not work!")
836 del items1, items2
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000837 self.assertEqual(len(dict), self.COUNT)
Fred Drakeb0fefc52001-03-23 04:22:45 +0000838 del objects[0]
839 self.assert_(len(dict) == (self.COUNT - 1),
840 "deleting object did not cause dictionary update")
841 del objects, o
842 self.assert_(len(dict) == 0,
843 "deleting the keys did not clear the dictionary")
Fred Drake752eda42001-11-06 16:38:34 +0000844 o = Object(42)
845 dict[o] = "What is the meaning of the universe?"
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000846 self.assert_(o in dict)
847 self.assert_(34 not in dict)
Martin v. Löwis5e163332001-02-27 18:36:56 +0000848
Fred Drake0e540c32001-05-02 05:44:22 +0000849 def test_weak_keyed_iters(self):
850 dict, objects = self.make_weak_keyed_dict()
851 self.check_iters(dict)
852
Thomas Wouters477c8d52006-05-27 19:21:47 +0000853 # Test keyrefs()
854 refs = dict.keyrefs()
855 self.assertEqual(len(refs), len(objects))
856 objects2 = list(objects)
857 for wr in refs:
858 ob = wr()
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000859 self.assert_(ob in dict)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000860 self.assert_(ob in dict)
861 self.assertEqual(ob.arg, dict[ob])
862 objects2.remove(ob)
863 self.assertEqual(len(objects2), 0)
864
865 # Test iterkeyrefs()
866 objects2 = list(objects)
Barry Warsawecaab832008-09-04 01:42:51 +0000867 self.assertEqual(len(list(dict.keyrefs())), len(objects))
868 for wr in dict.keyrefs():
Thomas Wouters477c8d52006-05-27 19:21:47 +0000869 ob = wr()
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000870 self.assert_(ob in dict)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000871 self.assert_(ob in dict)
872 self.assertEqual(ob.arg, dict[ob])
873 objects2.remove(ob)
874 self.assertEqual(len(objects2), 0)
875
Fred Drake0e540c32001-05-02 05:44:22 +0000876 def test_weak_valued_iters(self):
877 dict, objects = self.make_weak_valued_dict()
878 self.check_iters(dict)
879
Thomas Wouters477c8d52006-05-27 19:21:47 +0000880 # Test valuerefs()
881 refs = dict.valuerefs()
882 self.assertEqual(len(refs), len(objects))
883 objects2 = list(objects)
884 for wr in refs:
885 ob = wr()
886 self.assertEqual(ob, dict[ob.arg])
887 self.assertEqual(ob.arg, dict[ob.arg].arg)
888 objects2.remove(ob)
889 self.assertEqual(len(objects2), 0)
890
891 # Test itervaluerefs()
892 objects2 = list(objects)
893 self.assertEqual(len(list(dict.itervaluerefs())), len(objects))
894 for wr in dict.itervaluerefs():
895 ob = wr()
896 self.assertEqual(ob, dict[ob.arg])
897 self.assertEqual(ob.arg, dict[ob.arg].arg)
898 objects2.remove(ob)
899 self.assertEqual(len(objects2), 0)
900
Fred Drake0e540c32001-05-02 05:44:22 +0000901 def check_iters(self, dict):
902 # item iterator:
Barry Warsawecaab832008-09-04 01:42:51 +0000903 items = list(dict.items())
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000904 for item in dict.items():
Fred Drake0e540c32001-05-02 05:44:22 +0000905 items.remove(item)
Barry Warsawecaab832008-09-04 01:42:51 +0000906 self.assertFalse(items, "items() did not touch all items")
Fred Drake0e540c32001-05-02 05:44:22 +0000907
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000908 # key iterator, via __iter__():
Guido van Rossum07f24362007-02-11 22:59:48 +0000909 keys = list(dict.keys())
Fred Drake0e540c32001-05-02 05:44:22 +0000910 for k in dict:
911 keys.remove(k)
Barry Warsawecaab832008-09-04 01:42:51 +0000912 self.assertFalse(keys, "__iter__() did not touch all keys")
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000913
914 # key iterator, via iterkeys():
Guido van Rossum07f24362007-02-11 22:59:48 +0000915 keys = list(dict.keys())
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000916 for k in dict.keys():
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000917 keys.remove(k)
Barry Warsawecaab832008-09-04 01:42:51 +0000918 self.assertFalse(keys, "iterkeys() did not touch all keys")
Fred Drake0e540c32001-05-02 05:44:22 +0000919
920 # value iterator:
Guido van Rossum07f24362007-02-11 22:59:48 +0000921 values = list(dict.values())
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000922 for v in dict.values():
Fred Drake0e540c32001-05-02 05:44:22 +0000923 values.remove(v)
Barry Warsawecaab832008-09-04 01:42:51 +0000924 self.assertFalse(values,
Fred Drakef425b1e2003-07-14 21:37:17 +0000925 "itervalues() did not touch all values")
Fred Drake0e540c32001-05-02 05:44:22 +0000926
Guido van Rossum009afb72002-06-10 20:00:52 +0000927 def test_make_weak_keyed_dict_from_dict(self):
928 o = Object(3)
929 dict = weakref.WeakKeyDictionary({o:364})
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000930 self.assertEqual(dict[o], 364)
Guido van Rossum009afb72002-06-10 20:00:52 +0000931
932 def test_make_weak_keyed_dict_from_weak_keyed_dict(self):
933 o = Object(3)
934 dict = weakref.WeakKeyDictionary({o:364})
935 dict2 = weakref.WeakKeyDictionary(dict)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000936 self.assertEqual(dict[o], 364)
Guido van Rossum009afb72002-06-10 20:00:52 +0000937
Fred Drake0e540c32001-05-02 05:44:22 +0000938 def make_weak_keyed_dict(self):
939 dict = weakref.WeakKeyDictionary()
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000940 objects = list(map(Object, range(self.COUNT)))
Fred Drake0e540c32001-05-02 05:44:22 +0000941 for o in objects:
942 dict[o] = o.arg
943 return dict, objects
944
945 def make_weak_valued_dict(self):
946 dict = weakref.WeakValueDictionary()
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000947 objects = list(map(Object, range(self.COUNT)))
Fred Drake0e540c32001-05-02 05:44:22 +0000948 for o in objects:
949 dict[o.arg] = o
950 return dict, objects
951
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000952 def check_popitem(self, klass, key1, value1, key2, value2):
953 weakdict = klass()
954 weakdict[key1] = value1
955 weakdict[key2] = value2
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000956 self.assertEqual(len(weakdict), 2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000957 k, v = weakdict.popitem()
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000958 self.assertEqual(len(weakdict), 1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000959 if k is key1:
960 self.assert_(v is value1)
961 else:
962 self.assert_(v is value2)
963 k, v = weakdict.popitem()
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000964 self.assertEqual(len(weakdict), 0)
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000965 if k is key1:
966 self.assert_(v is value1)
967 else:
968 self.assert_(v is value2)
969
970 def test_weak_valued_dict_popitem(self):
971 self.check_popitem(weakref.WeakValueDictionary,
972 "key1", C(), "key2", C())
973
974 def test_weak_keyed_dict_popitem(self):
975 self.check_popitem(weakref.WeakKeyDictionary,
976 C(), "value 1", C(), "value 2")
977
978 def check_setdefault(self, klass, key, value1, value2):
979 self.assert_(value1 is not value2,
980 "invalid test"
981 " -- value parameters must be distinct objects")
982 weakdict = klass()
983 o = weakdict.setdefault(key, value1)
984 self.assert_(o is value1)
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000985 self.assert_(key in weakdict)
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000986 self.assert_(weakdict.get(key) is value1)
987 self.assert_(weakdict[key] is value1)
988
989 o = weakdict.setdefault(key, value2)
990 self.assert_(o is value1)
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000991 self.assert_(key in weakdict)
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000992 self.assert_(weakdict.get(key) is value1)
993 self.assert_(weakdict[key] is value1)
994
995 def test_weak_valued_dict_setdefault(self):
996 self.check_setdefault(weakref.WeakValueDictionary,
997 "key", C(), C())
998
999 def test_weak_keyed_dict_setdefault(self):
1000 self.check_setdefault(weakref.WeakKeyDictionary,
1001 C(), "value 1", "value 2")
1002
Fred Drakea0a4ab12001-04-16 17:37:27 +00001003 def check_update(self, klass, dict):
Fred Drake0e540c32001-05-02 05:44:22 +00001004 #
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001005 # This exercises d.update(), len(d), d.keys(), k in d,
Fred Drake0e540c32001-05-02 05:44:22 +00001006 # d.get(), d[].
1007 #
Fred Drakea0a4ab12001-04-16 17:37:27 +00001008 weakdict = klass()
1009 weakdict.update(dict)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001010 self.assertEqual(len(weakdict), len(dict))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001011 for k in weakdict.keys():
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001012 self.assert_(k in dict,
Fred Drakea0a4ab12001-04-16 17:37:27 +00001013 "mysterious new key appeared in weak dict")
1014 v = dict.get(k)
1015 self.assert_(v is weakdict[k])
1016 self.assert_(v is weakdict.get(k))
1017 for k in dict.keys():
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001018 self.assert_(k in weakdict,
Fred Drakea0a4ab12001-04-16 17:37:27 +00001019 "original key disappeared in weak dict")
1020 v = dict[k]
1021 self.assert_(v is weakdict[k])
1022 self.assert_(v is weakdict.get(k))
1023
1024 def test_weak_valued_dict_update(self):
1025 self.check_update(weakref.WeakValueDictionary,
1026 {1: C(), 'a': C(), C(): C()})
1027
1028 def test_weak_keyed_dict_update(self):
1029 self.check_update(weakref.WeakKeyDictionary,
1030 {C(): 1, C(): 2, C(): 3})
1031
Fred Drakeccc75622001-09-06 14:52:39 +00001032 def test_weak_keyed_delitem(self):
1033 d = weakref.WeakKeyDictionary()
1034 o1 = Object('1')
1035 o2 = Object('2')
1036 d[o1] = 'something'
1037 d[o2] = 'something'
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001038 self.assertEqual(len(d), 2)
Fred Drakeccc75622001-09-06 14:52:39 +00001039 del d[o1]
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001040 self.assertEqual(len(d), 1)
Barry Warsawecaab832008-09-04 01:42:51 +00001041 self.assertEqual(list(d.keys()), [o2])
Fred Drakeccc75622001-09-06 14:52:39 +00001042
1043 def test_weak_valued_delitem(self):
1044 d = weakref.WeakValueDictionary()
1045 o1 = Object('1')
1046 o2 = Object('2')
1047 d['something'] = o1
1048 d['something else'] = o2
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001049 self.assertEqual(len(d), 2)
Fred Drakeccc75622001-09-06 14:52:39 +00001050 del d['something']
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001051 self.assertEqual(len(d), 1)
Barry Warsawecaab832008-09-04 01:42:51 +00001052 self.assert_(list(d.items()) == [('something else', o2)])
Fred Drakeccc75622001-09-06 14:52:39 +00001053
Tim Peters886128f2003-05-25 01:45:11 +00001054 def test_weak_keyed_bad_delitem(self):
1055 d = weakref.WeakKeyDictionary()
1056 o = Object('1')
1057 # An attempt to delete an object that isn't there should raise
Tim Peters50d8b8b2003-05-25 17:44:31 +00001058 # KeyError. It didn't before 2.3.
Tim Peters886128f2003-05-25 01:45:11 +00001059 self.assertRaises(KeyError, d.__delitem__, o)
Tim Peters50d8b8b2003-05-25 17:44:31 +00001060 self.assertRaises(KeyError, d.__getitem__, o)
1061
1062 # If a key isn't of a weakly referencable type, __getitem__ and
1063 # __setitem__ raise TypeError. __delitem__ should too.
1064 self.assertRaises(TypeError, d.__delitem__, 13)
1065 self.assertRaises(TypeError, d.__getitem__, 13)
1066 self.assertRaises(TypeError, d.__setitem__, 13, 13)
Tim Peters886128f2003-05-25 01:45:11 +00001067
1068 def test_weak_keyed_cascading_deletes(self):
1069 # SF bug 742860. For some reason, before 2.3 __delitem__ iterated
1070 # over the keys via self.data.iterkeys(). If things vanished from
1071 # the dict during this (or got added), that caused a RuntimeError.
1072
1073 d = weakref.WeakKeyDictionary()
1074 mutate = False
1075
1076 class C(object):
1077 def __init__(self, i):
1078 self.value = i
1079 def __hash__(self):
1080 return hash(self.value)
1081 def __eq__(self, other):
1082 if mutate:
1083 # Side effect that mutates the dict, by removing the
1084 # last strong reference to a key.
1085 del objs[-1]
1086 return self.value == other.value
1087
1088 objs = [C(i) for i in range(4)]
1089 for o in objs:
1090 d[o] = o.value
1091 del o # now the only strong references to keys are in objs
1092 # Find the order in which iterkeys sees the keys.
Barry Warsawecaab832008-09-04 01:42:51 +00001093 objs = list(d.keys())
Tim Peters886128f2003-05-25 01:45:11 +00001094 # Reverse it, so that the iteration implementation of __delitem__
1095 # has to keep looping to find the first object we delete.
1096 objs.reverse()
Tim Peters50d8b8b2003-05-25 17:44:31 +00001097
Tim Peters886128f2003-05-25 01:45:11 +00001098 # Turn on mutation in C.__eq__. The first time thru the loop,
1099 # under the iterkeys() business the first comparison will delete
1100 # the last item iterkeys() would see, and that causes a
1101 # RuntimeError: dictionary changed size during iteration
1102 # when the iterkeys() loop goes around to try comparing the next
Tim Peters50d8b8b2003-05-25 17:44:31 +00001103 # key. After this was fixed, it just deletes the last object *our*
Tim Peters886128f2003-05-25 01:45:11 +00001104 # "for o in obj" loop would have gotten to.
1105 mutate = True
1106 count = 0
1107 for o in objs:
1108 count += 1
1109 del d[o]
1110 self.assertEqual(len(d), 0)
1111 self.assertEqual(count, 2)
1112
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001113from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001114
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001115class WeakValueDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +00001116 """Check that WeakValueDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001117 __ref = {"key1":Object(1), "key2":Object(2), "key3":Object(3)}
Walter Dörwald118f9312004-06-02 18:42:25 +00001118 type2test = weakref.WeakValueDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001119 def _reference(self):
1120 return self.__ref.copy()
1121
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001122class WeakKeyDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +00001123 """Check that WeakKeyDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001124 __ref = {Object("key1"):1, Object("key2"):2, Object("key3"):3}
Walter Dörwald118f9312004-06-02 18:42:25 +00001125 type2test = weakref.WeakKeyDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001126 def _reference(self):
1127 return self.__ref.copy()
Martin v. Löwis5e163332001-02-27 18:36:56 +00001128
Georg Brandlb533e262008-05-25 18:19:30 +00001129libreftest = """ Doctest for examples in the library reference: weakref.rst
Georg Brandl9a65d582005-07-02 19:07:30 +00001130
1131>>> import weakref
1132>>> class Dict(dict):
1133... pass
1134...
1135>>> obj = Dict(red=1, green=2, blue=3) # this object is weak referencable
1136>>> r = weakref.ref(obj)
Guido van Rossum7131f842007-02-09 20:13:25 +00001137>>> print(r() is obj)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001138True
Georg Brandl9a65d582005-07-02 19:07:30 +00001139
1140>>> import weakref
1141>>> class Object:
1142... pass
1143...
1144>>> o = Object()
1145>>> r = weakref.ref(o)
1146>>> o2 = r()
1147>>> o is o2
1148True
1149>>> del o, o2
Guido van Rossum7131f842007-02-09 20:13:25 +00001150>>> print(r())
Georg Brandl9a65d582005-07-02 19:07:30 +00001151None
1152
1153>>> import weakref
1154>>> class ExtendedRef(weakref.ref):
1155... def __init__(self, ob, callback=None, **annotations):
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001156... super().__init__(ob, callback)
Georg Brandl9a65d582005-07-02 19:07:30 +00001157... self.__counter = 0
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001158... for k, v in annotations.items():
Georg Brandl9a65d582005-07-02 19:07:30 +00001159... setattr(self, k, v)
1160... def __call__(self):
1161... '''Return a pair containing the referent and the number of
1162... times the reference has been called.
1163... '''
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001164... ob = super().__call__()
Georg Brandl9a65d582005-07-02 19:07:30 +00001165... if ob is not None:
1166... self.__counter += 1
1167... ob = (ob, self.__counter)
1168... return ob
Guido van Rossumd8faa362007-04-27 19:54:29 +00001169...
Georg Brandl9a65d582005-07-02 19:07:30 +00001170>>> class A: # not in docs from here, just testing the ExtendedRef
1171... pass
1172...
1173>>> a = A()
1174>>> r = ExtendedRef(a, foo=1, bar="baz")
1175>>> r.foo
11761
1177>>> r.bar
1178'baz'
1179>>> r()[1]
11801
1181>>> r()[1]
11822
1183>>> r()[0] is a
1184True
1185
1186
1187>>> import weakref
1188>>> _id2obj_dict = weakref.WeakValueDictionary()
1189>>> def remember(obj):
1190... oid = id(obj)
1191... _id2obj_dict[oid] = obj
1192... return oid
1193...
1194>>> def id2obj(oid):
1195... return _id2obj_dict[oid]
1196...
1197>>> a = A() # from here, just testing
1198>>> a_id = remember(a)
1199>>> id2obj(a_id) is a
1200True
1201>>> del a
1202>>> try:
1203... id2obj(a_id)
1204... except KeyError:
Guido van Rossum7131f842007-02-09 20:13:25 +00001205... print('OK')
Georg Brandl9a65d582005-07-02 19:07:30 +00001206... else:
Guido van Rossum7131f842007-02-09 20:13:25 +00001207... print('WeakValueDictionary error')
Georg Brandl9a65d582005-07-02 19:07:30 +00001208OK
1209
1210"""
1211
1212__test__ = {'libreftest' : libreftest}
1213
Fred Drake2e2be372001-09-20 21:33:42 +00001214def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001215 support.run_unittest(
Walter Dörwald21d3a322003-05-01 17:45:56 +00001216 ReferencesTestCase,
1217 MappingTestCase,
1218 WeakValueDictionaryTestCase,
Fred Drakef425b1e2003-07-14 21:37:17 +00001219 WeakKeyDictionaryTestCase,
Amaury Forgeot d'Arcc856c7a2008-06-16 19:50:09 +00001220 SubclassableWeakrefTestCase,
Fred Drakef425b1e2003-07-14 21:37:17 +00001221 )
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001222 support.run_doctest(sys.modules[__name__])
Fred Drake2e2be372001-09-20 21:33:42 +00001223
1224
1225if __name__ == "__main__":
1226 test_main()