blob: 75869a758a65ecd4675b86ff4b66fca772d0499e [file] [log] [blame]
Fred Drakebc875f52004-02-04 23:14:14 +00001import gc
Fred Drake41deb1e2001-02-01 05:27:45 +00002import sys
Fred Drakeb0fefc52001-03-23 04:22:45 +00003import unittest
Fred Drake5935ff02001-12-19 16:54:23 +00004import UserList
Fred Drake41deb1e2001-02-01 05:27:45 +00005import weakref
6
Barry Warsaw04f357c2002-07-23 19:04:11 +00007from test import test_support
Fred Drake41deb1e2001-02-01 05:27:45 +00008
9
10class C:
Fred Drakeb0fefc52001-03-23 04:22:45 +000011 def method(self):
12 pass
Fred Drake41deb1e2001-02-01 05:27:45 +000013
14
Fred Drakeb0fefc52001-03-23 04:22:45 +000015class Callable:
16 bar = None
Fred Drake41deb1e2001-02-01 05:27:45 +000017
Fred Drakeb0fefc52001-03-23 04:22:45 +000018 def __call__(self, x):
19 self.bar = x
Fred Drake41deb1e2001-02-01 05:27:45 +000020
21
Fred Drakeb0fefc52001-03-23 04:22:45 +000022def create_function():
23 def f(): pass
24 return f
25
26def create_bound_method():
27 return C().method
28
29def create_unbound_method():
30 return C.method
Fred Drake41deb1e2001-02-01 05:27:45 +000031
32
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)
48 self.check_basic_ref(create_unbound_method)
Fred Drake41deb1e2001-02-01 05:27:45 +000049
Fred Drake43735da2002-04-11 03:59:42 +000050 # Just make sure the tp_repr handler doesn't raise an exception.
51 # Live reference:
52 o = C()
53 wr = weakref.ref(o)
54 `wr`
55 # Dead reference:
56 del o
57 `wr`
58
Fred Drakeb0fefc52001-03-23 04:22:45 +000059 def test_basic_callback(self):
60 self.check_basic_callback(C)
61 self.check_basic_callback(create_function)
62 self.check_basic_callback(create_bound_method)
63 self.check_basic_callback(create_unbound_method)
Fred Drake41deb1e2001-02-01 05:27:45 +000064
Fred Drakeb0fefc52001-03-23 04:22:45 +000065 def test_multiple_callbacks(self):
66 o = C()
67 ref1 = weakref.ref(o, self.callback)
68 ref2 = weakref.ref(o, self.callback)
69 del o
70 self.assert_(ref1() is None,
71 "expected reference to be invalidated")
72 self.assert_(ref2() is None,
73 "expected reference to be invalidated")
74 self.assert_(self.cbcalled == 2,
75 "callback not called the right number of times")
Fred Drake41deb1e2001-02-01 05:27:45 +000076
Fred Drake705088e2001-04-13 17:18:15 +000077 def test_multiple_selfref_callbacks(self):
Guido van Rossum9eee5542002-08-22 20:21:30 +000078 # Make sure all references are invalidated before callbacks are called
Fred Drake705088e2001-04-13 17:18:15 +000079 #
80 # What's important here is that we're using the first
81 # reference in the callback invoked on the second reference
82 # (the most recently created ref is cleaned up first). This
83 # tests that all references to the object are invalidated
84 # before any of the callbacks are invoked, so that we only
85 # have one invocation of _weakref.c:cleanup_helper() active
86 # for a particular object at a time.
87 #
88 def callback(object, self=self):
89 self.ref()
90 c = C()
91 self.ref = weakref.ref(c, callback)
92 ref1 = weakref.ref(c, callback)
93 del c
94
Fred Drakeb0fefc52001-03-23 04:22:45 +000095 def test_proxy_ref(self):
96 o = C()
97 o.bar = 1
98 ref1 = weakref.proxy(o, self.callback)
99 ref2 = weakref.proxy(o, self.callback)
100 del o
Fred Drake41deb1e2001-02-01 05:27:45 +0000101
Fred Drakeb0fefc52001-03-23 04:22:45 +0000102 def check(proxy):
103 proxy.bar
Fred Drake41deb1e2001-02-01 05:27:45 +0000104
Fred Drakeb0fefc52001-03-23 04:22:45 +0000105 self.assertRaises(weakref.ReferenceError, check, ref1)
106 self.assertRaises(weakref.ReferenceError, check, ref2)
Neal Norwitzbdcb9412004-07-08 01:22:31 +0000107 self.assertRaises(weakref.ReferenceError, bool, weakref.proxy(C()))
Fred Drakeb0fefc52001-03-23 04:22:45 +0000108 self.assert_(self.cbcalled == 2)
Fred Drake41deb1e2001-02-01 05:27:45 +0000109
Fred Drakeb0fefc52001-03-23 04:22:45 +0000110 def check_basic_ref(self, factory):
111 o = factory()
112 ref = weakref.ref(o)
113 self.assert_(ref() is not None,
114 "weak reference to live object should be live")
115 o2 = ref()
116 self.assert_(o is o2,
117 "<ref>() should return original object if live")
Fred Drake41deb1e2001-02-01 05:27:45 +0000118
Fred Drakeb0fefc52001-03-23 04:22:45 +0000119 def check_basic_callback(self, factory):
120 self.cbcalled = 0
121 o = factory()
122 ref = weakref.ref(o, self.callback)
123 del o
Fred Drake705088e2001-04-13 17:18:15 +0000124 self.assert_(self.cbcalled == 1,
125 "callback did not properly set 'cbcalled'")
126 self.assert_(ref() is None,
127 "ref2 should be dead after deleting object reference")
Fred Drake41deb1e2001-02-01 05:27:45 +0000128
Fred Drakeb0fefc52001-03-23 04:22:45 +0000129 def test_ref_reuse(self):
130 o = C()
131 ref1 = weakref.ref(o)
132 # create a proxy to make sure that there's an intervening creation
133 # between these two; it should make no difference
134 proxy = weakref.proxy(o)
135 ref2 = weakref.ref(o)
136 self.assert_(ref1 is ref2,
137 "reference object w/out callback should be re-used")
Fred Drake41deb1e2001-02-01 05:27:45 +0000138
Fred Drakeb0fefc52001-03-23 04:22:45 +0000139 o = C()
140 proxy = weakref.proxy(o)
141 ref1 = weakref.ref(o)
142 ref2 = weakref.ref(o)
143 self.assert_(ref1 is ref2,
144 "reference object w/out callback should be re-used")
145 self.assert_(weakref.getweakrefcount(o) == 2,
146 "wrong weak ref count for object")
147 del proxy
148 self.assert_(weakref.getweakrefcount(o) == 1,
149 "wrong weak ref count for object after deleting proxy")
Fred Drake41deb1e2001-02-01 05:27:45 +0000150
Fred Drakeb0fefc52001-03-23 04:22:45 +0000151 def test_proxy_reuse(self):
152 o = C()
153 proxy1 = weakref.proxy(o)
154 ref = weakref.ref(o)
155 proxy2 = weakref.proxy(o)
156 self.assert_(proxy1 is proxy2,
157 "proxy object w/out callback should have been re-used")
158
159 def test_basic_proxy(self):
160 o = C()
161 self.check_proxy(o, weakref.proxy(o))
162
Fred Drake5935ff02001-12-19 16:54:23 +0000163 L = UserList.UserList()
164 p = weakref.proxy(L)
165 self.failIf(p, "proxy for empty UserList should be false")
166 p.append(12)
167 self.assertEqual(len(L), 1)
168 self.failUnless(p, "proxy for non-empty UserList should be true")
169 p[:] = [2, 3]
170 self.assertEqual(len(L), 2)
171 self.assertEqual(len(p), 2)
Fred Drakef425b1e2003-07-14 21:37:17 +0000172 self.failUnless(3 in p,
173 "proxy didn't support __contains__() properly")
Fred Drake5935ff02001-12-19 16:54:23 +0000174 p[1] = 5
175 self.assertEqual(L[1], 5)
176 self.assertEqual(p[1], 5)
177 L2 = UserList.UserList(L)
178 p2 = weakref.proxy(L2)
179 self.assertEqual(p, p2)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000180 ## self.assertEqual(repr(L2), repr(p2))
Fred Drake43735da2002-04-11 03:59:42 +0000181 L3 = UserList.UserList(range(10))
182 p3 = weakref.proxy(L3)
183 self.assertEqual(L3[:], p3[:])
184 self.assertEqual(L3[5:], p3[5:])
185 self.assertEqual(L3[:5], p3[:5])
186 self.assertEqual(L3[2:5], p3[2:5])
Fred Drake5935ff02001-12-19 16:54:23 +0000187
Fred Drakeea2adc92004-02-03 19:56:46 +0000188 # The PyWeakref_* C API is documented as allowing either NULL or
189 # None as the value for the callback, where either means "no
190 # callback". The "no callback" ref and proxy objects are supposed
191 # to be shared so long as they exist by all callers so long as
192 # they are active. In Python 2.3.3 and earlier, this guaranttee
193 # was not honored, and was broken in different ways for
194 # PyWeakref_NewRef() and PyWeakref_NewProxy(). (Two tests.)
195
196 def test_shared_ref_without_callback(self):
197 self.check_shared_without_callback(weakref.ref)
198
199 def test_shared_proxy_without_callback(self):
200 self.check_shared_without_callback(weakref.proxy)
201
202 def check_shared_without_callback(self, makeref):
203 o = Object(1)
204 p1 = makeref(o, None)
205 p2 = makeref(o, None)
206 self.assert_(p1 is p2, "both callbacks were None in the C API")
207 del p1, p2
208 p1 = makeref(o)
209 p2 = makeref(o, None)
210 self.assert_(p1 is p2, "callbacks were NULL, None in the C API")
211 del p1, p2
212 p1 = makeref(o)
213 p2 = makeref(o)
214 self.assert_(p1 is p2, "both callbacks were NULL in the C API")
215 del p1, p2
216 p1 = makeref(o, None)
217 p2 = makeref(o)
218 self.assert_(p1 is p2, "callbacks were None, NULL in the C API")
219
Fred Drakeb0fefc52001-03-23 04:22:45 +0000220 def test_callable_proxy(self):
221 o = Callable()
222 ref1 = weakref.proxy(o)
223
224 self.check_proxy(o, ref1)
225
226 self.assert_(type(ref1) is weakref.CallableProxyType,
227 "proxy is not of callable type")
228 ref1('twinkies!')
229 self.assert_(o.bar == 'twinkies!',
230 "call through proxy not passed through to original")
Fred Drake3bb4d212001-10-18 19:28:29 +0000231 ref1(x='Splat.')
232 self.assert_(o.bar == 'Splat.',
233 "call through proxy not passed through to original")
Fred Drakeb0fefc52001-03-23 04:22:45 +0000234
235 # expect due to too few args
236 self.assertRaises(TypeError, ref1)
237
238 # expect due to too many args
239 self.assertRaises(TypeError, ref1, 1, 2, 3)
240
241 def check_proxy(self, o, proxy):
242 o.foo = 1
243 self.assert_(proxy.foo == 1,
244 "proxy does not reflect attribute addition")
245 o.foo = 2
246 self.assert_(proxy.foo == 2,
247 "proxy does not reflect attribute modification")
248 del o.foo
249 self.assert_(not hasattr(proxy, 'foo'),
250 "proxy does not reflect attribute removal")
251
252 proxy.foo = 1
253 self.assert_(o.foo == 1,
254 "object does not reflect attribute addition via proxy")
255 proxy.foo = 2
256 self.assert_(
257 o.foo == 2,
258 "object does not reflect attribute modification via proxy")
259 del proxy.foo
260 self.assert_(not hasattr(o, 'foo'),
261 "object does not reflect attribute removal via proxy")
262
Raymond Hettingerd693a812003-06-30 04:18:48 +0000263 def test_proxy_deletion(self):
264 # Test clearing of SF bug #762891
265 class Foo:
266 result = None
267 def __delitem__(self, accessor):
268 self.result = accessor
269 g = Foo()
270 f = weakref.proxy(g)
271 del f[0]
272 self.assertEqual(f.result, 0)
273
Fred Drakeb0fefc52001-03-23 04:22:45 +0000274 def test_getweakrefcount(self):
275 o = C()
276 ref1 = weakref.ref(o)
277 ref2 = weakref.ref(o, self.callback)
278 self.assert_(weakref.getweakrefcount(o) == 2,
279 "got wrong number of weak reference objects")
280
281 proxy1 = weakref.proxy(o)
282 proxy2 = weakref.proxy(o, self.callback)
283 self.assert_(weakref.getweakrefcount(o) == 4,
284 "got wrong number of weak reference objects")
285
Fred Drakeea2adc92004-02-03 19:56:46 +0000286 del ref1, ref2, proxy1, proxy2
287 self.assert_(weakref.getweakrefcount(o) == 0,
288 "weak reference objects not unlinked from"
289 " referent when discarded.")
290
Walter Dörwaldb167b042003-12-11 12:34:05 +0000291 # assumes ints do not support weakrefs
292 self.assert_(weakref.getweakrefcount(1) == 0,
293 "got wrong number of weak reference objects for int")
294
Fred Drakeb0fefc52001-03-23 04:22:45 +0000295 def test_getweakrefs(self):
296 o = C()
297 ref1 = weakref.ref(o, self.callback)
298 ref2 = weakref.ref(o, self.callback)
299 del ref1
300 self.assert_(weakref.getweakrefs(o) == [ref2],
301 "list of refs does not match")
302
303 o = C()
304 ref1 = weakref.ref(o, self.callback)
305 ref2 = weakref.ref(o, self.callback)
306 del ref2
307 self.assert_(weakref.getweakrefs(o) == [ref1],
308 "list of refs does not match")
309
Fred Drakeea2adc92004-02-03 19:56:46 +0000310 del ref1
311 self.assert_(weakref.getweakrefs(o) == [],
312 "list of refs not cleared")
313
Walter Dörwaldb167b042003-12-11 12:34:05 +0000314 # assumes ints do not support weakrefs
315 self.assert_(weakref.getweakrefs(1) == [],
316 "list of refs does not match for int")
317
Fred Drake39c27f12001-10-18 18:06:05 +0000318 def test_newstyle_number_ops(self):
319 class F(float):
320 pass
321 f = F(2.0)
322 p = weakref.proxy(f)
323 self.assert_(p + 1.0 == 3.0)
324 self.assert_(1.0 + p == 3.0) # this used to SEGV
325
Fred Drake2a64f462001-12-10 23:46:02 +0000326 def test_callbacks_protected(self):
Guido van Rossum9eee5542002-08-22 20:21:30 +0000327 # Callbacks protected from already-set exceptions?
Fred Drake2a64f462001-12-10 23:46:02 +0000328 # Regression test for SF bug #478534.
329 class BogusError(Exception):
330 pass
331 data = {}
332 def remove(k):
333 del data[k]
334 def encapsulate():
335 f = lambda : ()
336 data[weakref.ref(f, remove)] = None
337 raise BogusError
338 try:
339 encapsulate()
340 except BogusError:
341 pass
342 else:
343 self.fail("exception not properly restored")
344 try:
345 encapsulate()
346 except BogusError:
347 pass
348 else:
349 self.fail("exception not properly restored")
350
Tim Petersadd09b42003-11-12 20:43:28 +0000351 def test_sf_bug_840829(self):
352 # "weakref callbacks and gc corrupt memory"
353 # subtype_dealloc erroneously exposed a new-style instance
354 # already in the process of getting deallocated to gc,
355 # causing double-deallocation if the instance had a weakref
356 # callback that triggered gc.
357 # If the bug exists, there probably won't be an obvious symptom
358 # in a release build. In a debug build, a segfault will occur
359 # when the second attempt to remove the instance from the "list
360 # of all objects" occurs.
361
362 import gc
363
364 class C(object):
365 pass
366
367 c = C()
368 wr = weakref.ref(c, lambda ignore: gc.collect())
369 del c
370
Tim Petersf7f9e992003-11-13 21:59:32 +0000371 # There endeth the first part. It gets worse.
372 del wr
373
374 c1 = C()
375 c1.i = C()
376 wr = weakref.ref(c1.i, lambda ignore: gc.collect())
377
378 c2 = C()
379 c2.c1 = c1
380 del c1 # still alive because c2 points to it
381
382 # Now when subtype_dealloc gets called on c2, it's not enough just
383 # that c2 is immune from gc while the weakref callbacks associated
384 # with c2 execute (there are none in this 2nd half of the test, btw).
385 # subtype_dealloc goes on to call the base classes' deallocs too,
386 # so any gc triggered by weakref callbacks associated with anything
387 # torn down by a base class dealloc can also trigger double
388 # deallocation of c2.
389 del c2
Fred Drake41deb1e2001-02-01 05:27:45 +0000390
Tim Peters403a2032003-11-20 21:21:46 +0000391 def test_callback_in_cycle_1(self):
392 import gc
393
394 class J(object):
395 pass
396
397 class II(object):
398 def acallback(self, ignore):
399 self.J
400
401 I = II()
402 I.J = J
403 I.wr = weakref.ref(J, I.acallback)
404
405 # Now J and II are each in a self-cycle (as all new-style class
406 # objects are, since their __mro__ points back to them). I holds
407 # both a weak reference (I.wr) and a strong reference (I.J) to class
408 # J. I is also in a cycle (I.wr points to a weakref that references
409 # I.acallback). When we del these three, they all become trash, but
410 # the cycles prevent any of them from getting cleaned up immediately.
411 # Instead they have to wait for cyclic gc to deduce that they're
412 # trash.
413 #
414 # gc used to call tp_clear on all of them, and the order in which
415 # it does that is pretty accidental. The exact order in which we
416 # built up these things manages to provoke gc into running tp_clear
417 # in just the right order (I last). Calling tp_clear on II leaves
418 # behind an insane class object (its __mro__ becomes NULL). Calling
419 # tp_clear on J breaks its self-cycle, but J doesn't get deleted
420 # just then because of the strong reference from I.J. Calling
421 # tp_clear on I starts to clear I's __dict__, and just happens to
422 # clear I.J first -- I.wr is still intact. That removes the last
423 # reference to J, which triggers the weakref callback. The callback
424 # tries to do "self.J", and instances of new-style classes look up
425 # attributes ("J") in the class dict first. The class (II) wants to
426 # search II.__mro__, but that's NULL. The result was a segfault in
427 # a release build, and an assert failure in a debug build.
428 del I, J, II
429 gc.collect()
430
431 def test_callback_in_cycle_2(self):
432 import gc
433
434 # This is just like test_callback_in_cycle_1, except that II is an
435 # old-style class. The symptom is different then: an instance of an
436 # old-style class looks in its own __dict__ first. 'J' happens to
437 # get cleared from I.__dict__ before 'wr', and 'J' was never in II's
438 # __dict__, so the attribute isn't found. The difference is that
439 # the old-style II doesn't have a NULL __mro__ (it doesn't have any
440 # __mro__), so no segfault occurs. Instead it got:
441 # test_callback_in_cycle_2 (__main__.ReferencesTestCase) ...
442 # Exception exceptions.AttributeError:
443 # "II instance has no attribute 'J'" in <bound method II.acallback
444 # of <?.II instance at 0x00B9B4B8>> ignored
445
446 class J(object):
447 pass
448
449 class II:
450 def acallback(self, ignore):
451 self.J
452
453 I = II()
454 I.J = J
455 I.wr = weakref.ref(J, I.acallback)
456
457 del I, J, II
458 gc.collect()
459
460 def test_callback_in_cycle_3(self):
461 import gc
462
463 # This one broke the first patch that fixed the last two. In this
464 # case, the objects reachable from the callback aren't also reachable
465 # from the object (c1) *triggering* the callback: you can get to
466 # c1 from c2, but not vice-versa. The result was that c2's __dict__
467 # got tp_clear'ed by the time the c2.cb callback got invoked.
468
469 class C:
470 def cb(self, ignore):
471 self.me
472 self.c1
473 self.wr
474
475 c1, c2 = C(), C()
476
477 c2.me = c2
478 c2.c1 = c1
479 c2.wr = weakref.ref(c1, c2.cb)
480
481 del c1, c2
482 gc.collect()
483
484 def test_callback_in_cycle_4(self):
485 import gc
486
487 # Like test_callback_in_cycle_3, except c2 and c1 have different
488 # classes. c2's class (C) isn't reachable from c1 then, so protecting
489 # objects reachable from the dying object (c1) isn't enough to stop
490 # c2's class (C) from getting tp_clear'ed before c2.cb is invoked.
491 # The result was a segfault (C.__mro__ was NULL when the callback
492 # tried to look up self.me).
493
494 class C(object):
495 def cb(self, ignore):
496 self.me
497 self.c1
498 self.wr
499
500 class D:
501 pass
502
503 c1, c2 = D(), C()
504
505 c2.me = c2
506 c2.c1 = c1
507 c2.wr = weakref.ref(c1, c2.cb)
508
509 del c1, c2, C, D
510 gc.collect()
511
512 def test_callback_in_cycle_resurrection(self):
513 import gc
514
515 # Do something nasty in a weakref callback: resurrect objects
516 # from dead cycles. For this to be attempted, the weakref and
517 # its callback must also be part of the cyclic trash (else the
518 # objects reachable via the callback couldn't be in cyclic trash
519 # to begin with -- the callback would act like an external root).
520 # But gc clears trash weakrefs with callbacks early now, which
521 # disables the callbacks, so the callbacks shouldn't get called
522 # at all (and so nothing actually gets resurrected).
523
524 alist = []
525 class C(object):
526 def __init__(self, value):
527 self.attribute = value
528
529 def acallback(self, ignore):
530 alist.append(self.c)
531
532 c1, c2 = C(1), C(2)
533 c1.c = c2
534 c2.c = c1
535 c1.wr = weakref.ref(c2, c1.acallback)
536 c2.wr = weakref.ref(c1, c2.acallback)
537
538 def C_went_away(ignore):
539 alist.append("C went away")
540 wr = weakref.ref(C, C_went_away)
541
542 del c1, c2, C # make them all trash
543 self.assertEqual(alist, []) # del isn't enough to reclaim anything
544
545 gc.collect()
546 # c1.wr and c2.wr were part of the cyclic trash, so should have
547 # been cleared without their callbacks executing. OTOH, the weakref
548 # to C is bound to a function local (wr), and wasn't trash, so that
549 # callback should have been invoked when C went away.
550 self.assertEqual(alist, ["C went away"])
551 # The remaining weakref should be dead now (its callback ran).
552 self.assertEqual(wr(), None)
553
554 del alist[:]
555 gc.collect()
556 self.assertEqual(alist, [])
557
558 def test_callbacks_on_callback(self):
559 import gc
560
561 # Set up weakref callbacks *on* weakref callbacks.
562 alist = []
563 def safe_callback(ignore):
564 alist.append("safe_callback called")
565
566 class C(object):
567 def cb(self, ignore):
568 alist.append("cb called")
569
570 c, d = C(), C()
571 c.other = d
572 d.other = c
573 callback = c.cb
574 c.wr = weakref.ref(d, callback) # this won't trigger
575 d.wr = weakref.ref(callback, d.cb) # ditto
576 external_wr = weakref.ref(callback, safe_callback) # but this will
577 self.assert_(external_wr() is callback)
578
579 # The weakrefs attached to c and d should get cleared, so that
580 # C.cb is never called. But external_wr isn't part of the cyclic
581 # trash, and no cyclic trash is reachable from it, so safe_callback
582 # should get invoked when the bound method object callback (c.cb)
583 # -- which is itself a callback, and also part of the cyclic trash --
584 # gets reclaimed at the end of gc.
585
586 del callback, c, d, C
587 self.assertEqual(alist, []) # del isn't enough to clean up cycles
588 gc.collect()
589 self.assertEqual(alist, ["safe_callback called"])
590 self.assertEqual(external_wr(), None)
591
592 del alist[:]
593 gc.collect()
594 self.assertEqual(alist, [])
595
Fred Drakebc875f52004-02-04 23:14:14 +0000596 def test_gc_during_ref_creation(self):
597 self.check_gc_during_creation(weakref.ref)
598
599 def test_gc_during_proxy_creation(self):
600 self.check_gc_during_creation(weakref.proxy)
601
602 def check_gc_during_creation(self, makeref):
603 thresholds = gc.get_threshold()
604 gc.set_threshold(1, 1, 1)
605 gc.collect()
Fred Drake55cf4342004-02-13 19:21:57 +0000606 class A:
607 pass
Fred Drakebc875f52004-02-04 23:14:14 +0000608
609 def callback(*args):
610 pass
611
Fred Drake55cf4342004-02-13 19:21:57 +0000612 referenced = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000613
Fred Drake55cf4342004-02-13 19:21:57 +0000614 a = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000615 a.a = a
616 a.wr = makeref(referenced)
617
618 try:
619 # now make sure the object and the ref get labeled as
620 # cyclic trash:
Fred Drake55cf4342004-02-13 19:21:57 +0000621 a = A()
622 weakref.ref(referenced, callback)
Fred Drakebc875f52004-02-04 23:14:14 +0000623
624 finally:
625 gc.set_threshold(*thresholds)
626
Fred Drake0a4dd392004-07-02 18:57:45 +0000627
628class SubclassableWeakrefTestCase(unittest.TestCase):
629
630 def test_subclass_refs(self):
631 class MyRef(weakref.ref):
632 def __init__(self, ob, callback=None, value=42):
633 self.value = value
634 super(MyRef, self).__init__(ob, callback)
635 def __call__(self):
636 self.called = True
637 return super(MyRef, self).__call__()
638 o = Object("foo")
639 mr = MyRef(o, value=24)
640 self.assert_(mr() is o)
641 self.assert_(mr.called)
642 self.assertEqual(mr.value, 24)
643 del o
644 self.assert_(mr() is None)
645 self.assert_(mr.called)
646
647 def test_subclass_refs_dont_replace_standard_refs(self):
648 class MyRef(weakref.ref):
649 pass
650 o = Object(42)
651 r1 = MyRef(o)
652 r2 = weakref.ref(o)
653 self.assert_(r1 is not r2)
654 self.assertEqual(weakref.getweakrefs(o), [r2, r1])
655 self.assertEqual(weakref.getweakrefcount(o), 2)
656 r3 = MyRef(o)
657 self.assertEqual(weakref.getweakrefcount(o), 3)
658 refs = weakref.getweakrefs(o)
659 self.assertEqual(len(refs), 3)
660 self.assert_(r2 is refs[0])
661 self.assert_(r1 in refs[1:])
662 self.assert_(r3 in refs[1:])
663
664 def test_subclass_refs_dont_conflate_callbacks(self):
665 class MyRef(weakref.ref):
666 pass
667 o = Object(42)
668 r1 = MyRef(o, id)
669 r2 = MyRef(o, str)
670 self.assert_(r1 is not r2)
671 refs = weakref.getweakrefs(o)
672 self.assert_(r1 in refs)
673 self.assert_(r2 in refs)
674
675 def test_subclass_refs_with_slots(self):
676 class MyRef(weakref.ref):
677 __slots__ = "slot1", "slot2"
678 def __new__(type, ob, callback, slot1, slot2):
679 return weakref.ref.__new__(type, ob, callback)
680 def __init__(self, ob, callback, slot1, slot2):
681 self.slot1 = slot1
682 self.slot2 = slot2
683 def meth(self):
684 return self.slot1 + self.slot2
685 o = Object(42)
686 r = MyRef(o, None, "abc", "def")
687 self.assertEqual(r.slot1, "abc")
688 self.assertEqual(r.slot2, "def")
689 self.assertEqual(r.meth(), "abcdef")
690 self.failIf(hasattr(r, "__dict__"))
691
692
Fred Drake41deb1e2001-02-01 05:27:45 +0000693class Object:
694 def __init__(self, arg):
695 self.arg = arg
696 def __repr__(self):
697 return "<Object %r>" % self.arg
698
Fred Drake41deb1e2001-02-01 05:27:45 +0000699
Fred Drakeb0fefc52001-03-23 04:22:45 +0000700class MappingTestCase(TestBase):
Martin v. Löwis5e163332001-02-27 18:36:56 +0000701
Fred Drakeb0fefc52001-03-23 04:22:45 +0000702 COUNT = 10
703
704 def test_weak_values(self):
Fred Drake0e540c32001-05-02 05:44:22 +0000705 #
706 # This exercises d.copy(), d.items(), d[], del d[], len(d).
707 #
708 dict, objects = self.make_weak_valued_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +0000709 for o in objects:
710 self.assert_(weakref.getweakrefcount(o) == 1,
711 "wrong number of weak references to %r!" % o)
712 self.assert_(o is dict[o.arg],
713 "wrong object returned by weak dict!")
714 items1 = dict.items()
715 items2 = dict.copy().items()
716 items1.sort()
717 items2.sort()
718 self.assert_(items1 == items2,
719 "cloning of weak-valued dictionary did not work!")
720 del items1, items2
721 self.assert_(len(dict) == self.COUNT)
722 del objects[0]
723 self.assert_(len(dict) == (self.COUNT - 1),
724 "deleting object did not cause dictionary update")
725 del objects, o
726 self.assert_(len(dict) == 0,
727 "deleting the values did not clear the dictionary")
Fred Drake4fd06e02001-08-03 04:11:27 +0000728 # regression on SF bug #447152:
729 dict = weakref.WeakValueDictionary()
730 self.assertRaises(KeyError, dict.__getitem__, 1)
731 dict[2] = C()
732 self.assertRaises(KeyError, dict.__getitem__, 2)
Fred Drakeb0fefc52001-03-23 04:22:45 +0000733
734 def test_weak_keys(self):
Fred Drake0e540c32001-05-02 05:44:22 +0000735 #
736 # This exercises d.copy(), d.items(), d[] = v, d[], del d[],
Fred Drake752eda42001-11-06 16:38:34 +0000737 # len(d), d.has_key().
Fred Drake0e540c32001-05-02 05:44:22 +0000738 #
739 dict, objects = self.make_weak_keyed_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +0000740 for o in objects:
741 self.assert_(weakref.getweakrefcount(o) == 1,
742 "wrong number of weak references to %r!" % o)
743 self.assert_(o.arg is dict[o],
744 "wrong object returned by weak dict!")
745 items1 = dict.items()
746 items2 = dict.copy().items()
Raymond Hettingera690a992003-11-16 16:17:49 +0000747 self.assert_(set(items1) == set(items2),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000748 "cloning of weak-keyed dictionary did not work!")
749 del items1, items2
750 self.assert_(len(dict) == self.COUNT)
751 del objects[0]
752 self.assert_(len(dict) == (self.COUNT - 1),
753 "deleting object did not cause dictionary update")
754 del objects, o
755 self.assert_(len(dict) == 0,
756 "deleting the keys did not clear the dictionary")
Fred Drake752eda42001-11-06 16:38:34 +0000757 o = Object(42)
758 dict[o] = "What is the meaning of the universe?"
759 self.assert_(dict.has_key(o))
760 self.assert_(not dict.has_key(34))
Martin v. Löwis5e163332001-02-27 18:36:56 +0000761
Fred Drake0e540c32001-05-02 05:44:22 +0000762 def test_weak_keyed_iters(self):
763 dict, objects = self.make_weak_keyed_dict()
764 self.check_iters(dict)
765
766 def test_weak_valued_iters(self):
767 dict, objects = self.make_weak_valued_dict()
768 self.check_iters(dict)
769
770 def check_iters(self, dict):
771 # item iterator:
772 items = dict.items()
773 for item in dict.iteritems():
774 items.remove(item)
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000775 self.assert_(len(items) == 0, "iteritems() did not touch all items")
Fred Drake0e540c32001-05-02 05:44:22 +0000776
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000777 # key iterator, via __iter__():
Fred Drake0e540c32001-05-02 05:44:22 +0000778 keys = dict.keys()
779 for k in dict:
780 keys.remove(k)
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000781 self.assert_(len(keys) == 0, "__iter__() did not touch all keys")
782
783 # key iterator, via iterkeys():
784 keys = dict.keys()
785 for k in dict.iterkeys():
786 keys.remove(k)
787 self.assert_(len(keys) == 0, "iterkeys() did not touch all keys")
Fred Drake0e540c32001-05-02 05:44:22 +0000788
789 # value iterator:
790 values = dict.values()
791 for v in dict.itervalues():
792 values.remove(v)
Fred Drakef425b1e2003-07-14 21:37:17 +0000793 self.assert_(len(values) == 0,
794 "itervalues() did not touch all values")
Fred Drake0e540c32001-05-02 05:44:22 +0000795
Guido van Rossum009afb72002-06-10 20:00:52 +0000796 def test_make_weak_keyed_dict_from_dict(self):
797 o = Object(3)
798 dict = weakref.WeakKeyDictionary({o:364})
799 self.assert_(dict[o] == 364)
800
801 def test_make_weak_keyed_dict_from_weak_keyed_dict(self):
802 o = Object(3)
803 dict = weakref.WeakKeyDictionary({o:364})
804 dict2 = weakref.WeakKeyDictionary(dict)
805 self.assert_(dict[o] == 364)
806
Fred Drake0e540c32001-05-02 05:44:22 +0000807 def make_weak_keyed_dict(self):
808 dict = weakref.WeakKeyDictionary()
809 objects = map(Object, range(self.COUNT))
810 for o in objects:
811 dict[o] = o.arg
812 return dict, objects
813
814 def make_weak_valued_dict(self):
815 dict = weakref.WeakValueDictionary()
816 objects = map(Object, range(self.COUNT))
817 for o in objects:
818 dict[o.arg] = o
819 return dict, objects
820
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000821 def check_popitem(self, klass, key1, value1, key2, value2):
822 weakdict = klass()
823 weakdict[key1] = value1
824 weakdict[key2] = value2
825 self.assert_(len(weakdict) == 2)
826 k, v = weakdict.popitem()
827 self.assert_(len(weakdict) == 1)
828 if k is key1:
829 self.assert_(v is value1)
830 else:
831 self.assert_(v is value2)
832 k, v = weakdict.popitem()
833 self.assert_(len(weakdict) == 0)
834 if k is key1:
835 self.assert_(v is value1)
836 else:
837 self.assert_(v is value2)
838
839 def test_weak_valued_dict_popitem(self):
840 self.check_popitem(weakref.WeakValueDictionary,
841 "key1", C(), "key2", C())
842
843 def test_weak_keyed_dict_popitem(self):
844 self.check_popitem(weakref.WeakKeyDictionary,
845 C(), "value 1", C(), "value 2")
846
847 def check_setdefault(self, klass, key, value1, value2):
848 self.assert_(value1 is not value2,
849 "invalid test"
850 " -- value parameters must be distinct objects")
851 weakdict = klass()
852 o = weakdict.setdefault(key, value1)
853 self.assert_(o is value1)
854 self.assert_(weakdict.has_key(key))
855 self.assert_(weakdict.get(key) is value1)
856 self.assert_(weakdict[key] is value1)
857
858 o = weakdict.setdefault(key, value2)
859 self.assert_(o is value1)
860 self.assert_(weakdict.has_key(key))
861 self.assert_(weakdict.get(key) is value1)
862 self.assert_(weakdict[key] is value1)
863
864 def test_weak_valued_dict_setdefault(self):
865 self.check_setdefault(weakref.WeakValueDictionary,
866 "key", C(), C())
867
868 def test_weak_keyed_dict_setdefault(self):
869 self.check_setdefault(weakref.WeakKeyDictionary,
870 C(), "value 1", "value 2")
871
Fred Drakea0a4ab12001-04-16 17:37:27 +0000872 def check_update(self, klass, dict):
Fred Drake0e540c32001-05-02 05:44:22 +0000873 #
874 # This exercises d.update(), len(d), d.keys(), d.has_key(),
875 # d.get(), d[].
876 #
Fred Drakea0a4ab12001-04-16 17:37:27 +0000877 weakdict = klass()
878 weakdict.update(dict)
879 self.assert_(len(weakdict) == len(dict))
880 for k in weakdict.keys():
881 self.assert_(dict.has_key(k),
882 "mysterious new key appeared in weak dict")
883 v = dict.get(k)
884 self.assert_(v is weakdict[k])
885 self.assert_(v is weakdict.get(k))
886 for k in dict.keys():
887 self.assert_(weakdict.has_key(k),
888 "original key disappeared in weak dict")
889 v = dict[k]
890 self.assert_(v is weakdict[k])
891 self.assert_(v is weakdict.get(k))
892
893 def test_weak_valued_dict_update(self):
894 self.check_update(weakref.WeakValueDictionary,
895 {1: C(), 'a': C(), C(): C()})
896
897 def test_weak_keyed_dict_update(self):
898 self.check_update(weakref.WeakKeyDictionary,
899 {C(): 1, C(): 2, C(): 3})
900
Fred Drakeccc75622001-09-06 14:52:39 +0000901 def test_weak_keyed_delitem(self):
902 d = weakref.WeakKeyDictionary()
903 o1 = Object('1')
904 o2 = Object('2')
905 d[o1] = 'something'
906 d[o2] = 'something'
907 self.assert_(len(d) == 2)
908 del d[o1]
909 self.assert_(len(d) == 1)
910 self.assert_(d.keys() == [o2])
911
912 def test_weak_valued_delitem(self):
913 d = weakref.WeakValueDictionary()
914 o1 = Object('1')
915 o2 = Object('2')
916 d['something'] = o1
917 d['something else'] = o2
918 self.assert_(len(d) == 2)
919 del d['something']
920 self.assert_(len(d) == 1)
921 self.assert_(d.items() == [('something else', o2)])
922
Tim Peters886128f2003-05-25 01:45:11 +0000923 def test_weak_keyed_bad_delitem(self):
924 d = weakref.WeakKeyDictionary()
925 o = Object('1')
926 # An attempt to delete an object that isn't there should raise
Tim Peters50d8b8b2003-05-25 17:44:31 +0000927 # KeyError. It didn't before 2.3.
Tim Peters886128f2003-05-25 01:45:11 +0000928 self.assertRaises(KeyError, d.__delitem__, o)
Tim Peters50d8b8b2003-05-25 17:44:31 +0000929 self.assertRaises(KeyError, d.__getitem__, o)
930
931 # If a key isn't of a weakly referencable type, __getitem__ and
932 # __setitem__ raise TypeError. __delitem__ should too.
933 self.assertRaises(TypeError, d.__delitem__, 13)
934 self.assertRaises(TypeError, d.__getitem__, 13)
935 self.assertRaises(TypeError, d.__setitem__, 13, 13)
Tim Peters886128f2003-05-25 01:45:11 +0000936
937 def test_weak_keyed_cascading_deletes(self):
938 # SF bug 742860. For some reason, before 2.3 __delitem__ iterated
939 # over the keys via self.data.iterkeys(). If things vanished from
940 # the dict during this (or got added), that caused a RuntimeError.
941
942 d = weakref.WeakKeyDictionary()
943 mutate = False
944
945 class C(object):
946 def __init__(self, i):
947 self.value = i
948 def __hash__(self):
949 return hash(self.value)
950 def __eq__(self, other):
951 if mutate:
952 # Side effect that mutates the dict, by removing the
953 # last strong reference to a key.
954 del objs[-1]
955 return self.value == other.value
956
957 objs = [C(i) for i in range(4)]
958 for o in objs:
959 d[o] = o.value
960 del o # now the only strong references to keys are in objs
961 # Find the order in which iterkeys sees the keys.
962 objs = d.keys()
963 # Reverse it, so that the iteration implementation of __delitem__
964 # has to keep looping to find the first object we delete.
965 objs.reverse()
Tim Peters50d8b8b2003-05-25 17:44:31 +0000966
Tim Peters886128f2003-05-25 01:45:11 +0000967 # Turn on mutation in C.__eq__. The first time thru the loop,
968 # under the iterkeys() business the first comparison will delete
969 # the last item iterkeys() would see, and that causes a
970 # RuntimeError: dictionary changed size during iteration
971 # when the iterkeys() loop goes around to try comparing the next
Tim Peters50d8b8b2003-05-25 17:44:31 +0000972 # key. After this was fixed, it just deletes the last object *our*
Tim Peters886128f2003-05-25 01:45:11 +0000973 # "for o in obj" loop would have gotten to.
974 mutate = True
975 count = 0
976 for o in objs:
977 count += 1
978 del d[o]
979 self.assertEqual(len(d), 0)
980 self.assertEqual(count, 2)
981
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000982from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000983
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000984class WeakValueDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +0000985 """Check that WeakValueDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000986 __ref = {"key1":Object(1), "key2":Object(2), "key3":Object(3)}
Walter Dörwald118f9312004-06-02 18:42:25 +0000987 type2test = weakref.WeakValueDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000988 def _reference(self):
989 return self.__ref.copy()
990
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000991class WeakKeyDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +0000992 """Check that WeakKeyDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000993 __ref = {Object("key1"):1, Object("key2"):2, Object("key3"):3}
Walter Dörwald118f9312004-06-02 18:42:25 +0000994 type2test = weakref.WeakKeyDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000995 def _reference(self):
996 return self.__ref.copy()
Martin v. Löwis5e163332001-02-27 18:36:56 +0000997
Fred Drake2e2be372001-09-20 21:33:42 +0000998def test_main():
Walter Dörwald21d3a322003-05-01 17:45:56 +0000999 test_support.run_unittest(
1000 ReferencesTestCase,
1001 MappingTestCase,
1002 WeakValueDictionaryTestCase,
Fred Drakef425b1e2003-07-14 21:37:17 +00001003 WeakKeyDictionaryTestCase,
1004 )
Fred Drake2e2be372001-09-20 21:33:42 +00001005
1006
1007if __name__ == "__main__":
1008 test_main()