blob: 2106d8cd9bd50796234b7820fd8066712d60dd9f [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)
Senthil Kumarance8e33a2010-01-08 19:04:16 +000057 `wr`
Fred Drake43735da2002-04-11 03:59:42 +000058 # Dead reference:
59 del o
Senthil Kumarance8e33a2010-01-08 19:04:16 +000060 `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
Benjamin Peterson5c8da862009-06-30 22:57:08 +000073 self.assertTrue(ref1() is None,
Fred Drakeb0fefc52001-03-23 04:22:45 +000074 "expected reference to be invalidated")
Benjamin Peterson5c8da862009-06-30 22:57:08 +000075 self.assertTrue(ref2() is None,
Fred Drakeb0fefc52001-03-23 04:22:45 +000076 "expected reference to be invalidated")
Benjamin Peterson5c8da862009-06-30 22:57:08 +000077 self.assertTrue(self.cbcalled == 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +000078 "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()))
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000111 self.assertTrue(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)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000116 self.assertTrue(ref() is not None,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000117 "weak reference to live object should be live")
118 o2 = ref()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000119 self.assertTrue(o is o2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000120 "<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
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000127 self.assertTrue(self.cbcalled == 1,
Fred Drake705088e2001-04-13 17:18:15 +0000128 "callback did not properly set 'cbcalled'")
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000129 self.assertTrue(ref() is None,
Fred Drake705088e2001-04-13 17:18:15 +0000130 "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)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000139 self.assertTrue(ref1 is ref2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000140 "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)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000146 self.assertTrue(ref1 is ref2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000147 "reference object w/out callback should be re-used")
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000148 self.assertTrue(weakref.getweakrefcount(o) == 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000149 "wrong weak ref count for object")
150 del proxy
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000151 self.assertTrue(weakref.getweakrefcount(o) == 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000152 "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)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000159 self.assertTrue(proxy1 is proxy2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000160 "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)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000168 self.assertFalse(p, "proxy for empty UserList should be false")
Fred Drake5935ff02001-12-19 16:54:23 +0000169 p.append(12)
170 self.assertEqual(len(L), 1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000171 self.assertTrue(p, "proxy for non-empty UserList should be true")
Senthil Kumarance8e33a2010-01-08 19:04:16 +0000172 p[:] = [2, 3]
Fred Drake5935ff02001-12-19 16:54:23 +0000173 self.assertEqual(len(L), 2)
174 self.assertEqual(len(p), 2)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000175 self.assertTrue(3 in p,
Fred Drakef425b1e2003-07-14 21:37:17 +0000176 "proxy didn't support __contains__() properly")
Fred Drake5935ff02001-12-19 16:54:23 +0000177 p[1] = 5
178 self.assertEqual(L[1], 5)
179 self.assertEqual(p[1], 5)
180 L2 = UserList.UserList(L)
181 p2 = weakref.proxy(L2)
182 self.assertEqual(p, p2)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000183 ## self.assertEqual(repr(L2), repr(p2))
Fred Drake43735da2002-04-11 03:59:42 +0000184 L3 = UserList.UserList(range(10))
185 p3 = weakref.proxy(L3)
Senthil Kumarance8e33a2010-01-08 19:04:16 +0000186 self.assertEqual(L3[:], p3[:])
187 self.assertEqual(L3[5:], p3[5:])
188 self.assertEqual(L3[:5], p3[:5])
189 self.assertEqual(L3[2:5], p3[2:5])
Fred Drake5935ff02001-12-19 16:54:23 +0000190
Benjamin Petersondc3c2392009-11-19 03:00:02 +0000191 def test_proxy_unicode(self):
192 # See bug 5037
193 class C(object):
194 def __str__(self):
195 return "string"
196 def __unicode__(self):
197 return u"unicode"
198 instance = C()
199 self.assertTrue("__unicode__" in dir(weakref.proxy(instance)))
200 self.assertEqual(unicode(weakref.proxy(instance)), u"unicode")
201
Georg Brandl88659b02008-05-20 08:40:43 +0000202 def test_proxy_index(self):
203 class C:
204 def __index__(self):
205 return 10
206 o = C()
207 p = weakref.proxy(o)
208 self.assertEqual(operator.index(p), 10)
209
210 def test_proxy_div(self):
211 class C:
212 def __floordiv__(self, other):
213 return 42
214 def __ifloordiv__(self, other):
215 return 21
216 o = C()
217 p = weakref.proxy(o)
218 self.assertEqual(p // 5, 42)
219 p //= 5
220 self.assertEqual(p, 21)
221
Fred Drakeea2adc92004-02-03 19:56:46 +0000222 # The PyWeakref_* C API is documented as allowing either NULL or
223 # None as the value for the callback, where either means "no
224 # callback". The "no callback" ref and proxy objects are supposed
225 # to be shared so long as they exist by all callers so long as
Walter Dörwaldda1ad322006-12-12 21:55:31 +0000226 # they are active. In Python 2.3.3 and earlier, this guarantee
Fred Drakeea2adc92004-02-03 19:56:46 +0000227 # was not honored, and was broken in different ways for
228 # PyWeakref_NewRef() and PyWeakref_NewProxy(). (Two tests.)
229
230 def test_shared_ref_without_callback(self):
231 self.check_shared_without_callback(weakref.ref)
232
233 def test_shared_proxy_without_callback(self):
234 self.check_shared_without_callback(weakref.proxy)
235
236 def check_shared_without_callback(self, makeref):
237 o = Object(1)
238 p1 = makeref(o, None)
239 p2 = makeref(o, None)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000240 self.assertTrue(p1 is p2, "both callbacks were None in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000241 del p1, p2
242 p1 = makeref(o)
243 p2 = makeref(o, None)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000244 self.assertTrue(p1 is p2, "callbacks were NULL, None in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000245 del p1, p2
246 p1 = makeref(o)
247 p2 = makeref(o)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000248 self.assertTrue(p1 is p2, "both callbacks were NULL in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000249 del p1, p2
250 p1 = makeref(o, None)
251 p2 = makeref(o)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000252 self.assertTrue(p1 is p2, "callbacks were None, NULL in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000253
Fred Drakeb0fefc52001-03-23 04:22:45 +0000254 def test_callable_proxy(self):
255 o = Callable()
256 ref1 = weakref.proxy(o)
257
258 self.check_proxy(o, ref1)
259
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000260 self.assertTrue(type(ref1) is weakref.CallableProxyType,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000261 "proxy is not of callable type")
262 ref1('twinkies!')
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000263 self.assertTrue(o.bar == 'twinkies!',
Fred Drakeb0fefc52001-03-23 04:22:45 +0000264 "call through proxy not passed through to original")
Fred Drake3bb4d212001-10-18 19:28:29 +0000265 ref1(x='Splat.')
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000266 self.assertTrue(o.bar == 'Splat.',
Fred Drake3bb4d212001-10-18 19:28:29 +0000267 "call through proxy not passed through to original")
Fred Drakeb0fefc52001-03-23 04:22:45 +0000268
269 # expect due to too few args
270 self.assertRaises(TypeError, ref1)
271
272 # expect due to too many args
273 self.assertRaises(TypeError, ref1, 1, 2, 3)
274
275 def check_proxy(self, o, proxy):
276 o.foo = 1
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000277 self.assertTrue(proxy.foo == 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000278 "proxy does not reflect attribute addition")
279 o.foo = 2
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000280 self.assertTrue(proxy.foo == 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000281 "proxy does not reflect attribute modification")
282 del o.foo
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000283 self.assertTrue(not hasattr(proxy, 'foo'),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000284 "proxy does not reflect attribute removal")
285
286 proxy.foo = 1
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000287 self.assertTrue(o.foo == 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000288 "object does not reflect attribute addition via proxy")
289 proxy.foo = 2
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000290 self.assertTrue(
Fred Drakeb0fefc52001-03-23 04:22:45 +0000291 o.foo == 2,
292 "object does not reflect attribute modification via proxy")
293 del proxy.foo
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000294 self.assertTrue(not hasattr(o, 'foo'),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000295 "object does not reflect attribute removal via proxy")
296
Raymond Hettingerd693a812003-06-30 04:18:48 +0000297 def test_proxy_deletion(self):
298 # Test clearing of SF bug #762891
299 class Foo:
300 result = None
301 def __delitem__(self, accessor):
302 self.result = accessor
303 g = Foo()
304 f = weakref.proxy(g)
305 del f[0]
306 self.assertEqual(f.result, 0)
307
Raymond Hettingere6c470f2005-03-27 03:04:54 +0000308 def test_proxy_bool(self):
309 # Test clearing of SF bug #1170766
310 class List(list): pass
311 lyst = List()
312 self.assertEqual(bool(weakref.proxy(lyst)), bool(lyst))
313
Fred Drakeb0fefc52001-03-23 04:22:45 +0000314 def test_getweakrefcount(self):
315 o = C()
316 ref1 = weakref.ref(o)
317 ref2 = weakref.ref(o, self.callback)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000318 self.assertTrue(weakref.getweakrefcount(o) == 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000319 "got wrong number of weak reference objects")
320
321 proxy1 = weakref.proxy(o)
322 proxy2 = weakref.proxy(o, self.callback)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000323 self.assertTrue(weakref.getweakrefcount(o) == 4,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000324 "got wrong number of weak reference objects")
325
Fred Drakeea2adc92004-02-03 19:56:46 +0000326 del ref1, ref2, proxy1, proxy2
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000327 self.assertTrue(weakref.getweakrefcount(o) == 0,
Fred Drakeea2adc92004-02-03 19:56:46 +0000328 "weak reference objects not unlinked from"
329 " referent when discarded.")
330
Walter Dörwaldb167b042003-12-11 12:34:05 +0000331 # assumes ints do not support weakrefs
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000332 self.assertTrue(weakref.getweakrefcount(1) == 0,
Walter Dörwaldb167b042003-12-11 12:34:05 +0000333 "got wrong number of weak reference objects for int")
334
Fred Drakeb0fefc52001-03-23 04:22:45 +0000335 def test_getweakrefs(self):
336 o = C()
337 ref1 = weakref.ref(o, self.callback)
338 ref2 = weakref.ref(o, self.callback)
339 del ref1
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000340 self.assertTrue(weakref.getweakrefs(o) == [ref2],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000341 "list of refs does not match")
342
343 o = C()
344 ref1 = weakref.ref(o, self.callback)
345 ref2 = weakref.ref(o, self.callback)
346 del ref2
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000347 self.assertTrue(weakref.getweakrefs(o) == [ref1],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000348 "list of refs does not match")
349
Fred Drakeea2adc92004-02-03 19:56:46 +0000350 del ref1
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000351 self.assertTrue(weakref.getweakrefs(o) == [],
Fred Drakeea2adc92004-02-03 19:56:46 +0000352 "list of refs not cleared")
353
Walter Dörwaldb167b042003-12-11 12:34:05 +0000354 # assumes ints do not support weakrefs
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000355 self.assertTrue(weakref.getweakrefs(1) == [],
Walter Dörwaldb167b042003-12-11 12:34:05 +0000356 "list of refs does not match for int")
357
Fred Drake39c27f12001-10-18 18:06:05 +0000358 def test_newstyle_number_ops(self):
359 class F(float):
360 pass
361 f = F(2.0)
362 p = weakref.proxy(f)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000363 self.assertTrue(p + 1.0 == 3.0)
364 self.assertTrue(1.0 + p == 3.0) # this used to SEGV
Fred Drake39c27f12001-10-18 18:06:05 +0000365
Fred Drake2a64f462001-12-10 23:46:02 +0000366 def test_callbacks_protected(self):
Guido van Rossum9eee5542002-08-22 20:21:30 +0000367 # Callbacks protected from already-set exceptions?
Fred Drake2a64f462001-12-10 23:46:02 +0000368 # Regression test for SF bug #478534.
369 class BogusError(Exception):
370 pass
371 data = {}
372 def remove(k):
373 del data[k]
374 def encapsulate():
375 f = lambda : ()
376 data[weakref.ref(f, remove)] = None
377 raise BogusError
378 try:
379 encapsulate()
380 except BogusError:
381 pass
382 else:
383 self.fail("exception not properly restored")
384 try:
385 encapsulate()
386 except BogusError:
387 pass
388 else:
389 self.fail("exception not properly restored")
390
Tim Petersadd09b42003-11-12 20:43:28 +0000391 def test_sf_bug_840829(self):
392 # "weakref callbacks and gc corrupt memory"
393 # subtype_dealloc erroneously exposed a new-style instance
394 # already in the process of getting deallocated to gc,
395 # causing double-deallocation if the instance had a weakref
396 # callback that triggered gc.
397 # If the bug exists, there probably won't be an obvious symptom
398 # in a release build. In a debug build, a segfault will occur
399 # when the second attempt to remove the instance from the "list
400 # of all objects" occurs.
401
402 import gc
403
404 class C(object):
405 pass
406
407 c = C()
408 wr = weakref.ref(c, lambda ignore: gc.collect())
409 del c
410
Tim Petersf7f9e992003-11-13 21:59:32 +0000411 # There endeth the first part. It gets worse.
412 del wr
413
414 c1 = C()
415 c1.i = C()
416 wr = weakref.ref(c1.i, lambda ignore: gc.collect())
417
418 c2 = C()
419 c2.c1 = c1
420 del c1 # still alive because c2 points to it
421
422 # Now when subtype_dealloc gets called on c2, it's not enough just
423 # that c2 is immune from gc while the weakref callbacks associated
424 # with c2 execute (there are none in this 2nd half of the test, btw).
425 # subtype_dealloc goes on to call the base classes' deallocs too,
426 # so any gc triggered by weakref callbacks associated with anything
427 # torn down by a base class dealloc can also trigger double
428 # deallocation of c2.
429 del c2
Fred Drake41deb1e2001-02-01 05:27:45 +0000430
Tim Peters403a2032003-11-20 21:21:46 +0000431 def test_callback_in_cycle_1(self):
432 import gc
433
434 class J(object):
435 pass
436
437 class II(object):
438 def acallback(self, ignore):
439 self.J
440
441 I = II()
442 I.J = J
443 I.wr = weakref.ref(J, I.acallback)
444
445 # Now J and II are each in a self-cycle (as all new-style class
446 # objects are, since their __mro__ points back to them). I holds
447 # both a weak reference (I.wr) and a strong reference (I.J) to class
448 # J. I is also in a cycle (I.wr points to a weakref that references
449 # I.acallback). When we del these three, they all become trash, but
450 # the cycles prevent any of them from getting cleaned up immediately.
451 # Instead they have to wait for cyclic gc to deduce that they're
452 # trash.
453 #
454 # gc used to call tp_clear on all of them, and the order in which
455 # it does that is pretty accidental. The exact order in which we
456 # built up these things manages to provoke gc into running tp_clear
457 # in just the right order (I last). Calling tp_clear on II leaves
458 # behind an insane class object (its __mro__ becomes NULL). Calling
459 # tp_clear on J breaks its self-cycle, but J doesn't get deleted
460 # just then because of the strong reference from I.J. Calling
461 # tp_clear on I starts to clear I's __dict__, and just happens to
462 # clear I.J first -- I.wr is still intact. That removes the last
463 # reference to J, which triggers the weakref callback. The callback
464 # tries to do "self.J", and instances of new-style classes look up
465 # attributes ("J") in the class dict first. The class (II) wants to
466 # search II.__mro__, but that's NULL. The result was a segfault in
467 # a release build, and an assert failure in a debug build.
468 del I, J, II
469 gc.collect()
470
471 def test_callback_in_cycle_2(self):
472 import gc
473
474 # This is just like test_callback_in_cycle_1, except that II is an
475 # old-style class. The symptom is different then: an instance of an
476 # old-style class looks in its own __dict__ first. 'J' happens to
477 # get cleared from I.__dict__ before 'wr', and 'J' was never in II's
478 # __dict__, so the attribute isn't found. The difference is that
479 # the old-style II doesn't have a NULL __mro__ (it doesn't have any
480 # __mro__), so no segfault occurs. Instead it got:
481 # test_callback_in_cycle_2 (__main__.ReferencesTestCase) ...
482 # Exception exceptions.AttributeError:
483 # "II instance has no attribute 'J'" in <bound method II.acallback
484 # of <?.II instance at 0x00B9B4B8>> ignored
485
486 class J(object):
487 pass
488
489 class II:
490 def acallback(self, ignore):
491 self.J
492
493 I = II()
494 I.J = J
495 I.wr = weakref.ref(J, I.acallback)
496
497 del I, J, II
498 gc.collect()
499
500 def test_callback_in_cycle_3(self):
501 import gc
502
503 # This one broke the first patch that fixed the last two. In this
504 # case, the objects reachable from the callback aren't also reachable
505 # from the object (c1) *triggering* the callback: you can get to
506 # c1 from c2, but not vice-versa. The result was that c2's __dict__
507 # got tp_clear'ed by the time the c2.cb callback got invoked.
508
509 class C:
510 def cb(self, ignore):
511 self.me
512 self.c1
513 self.wr
514
515 c1, c2 = C(), C()
516
517 c2.me = c2
518 c2.c1 = c1
519 c2.wr = weakref.ref(c1, c2.cb)
520
521 del c1, c2
522 gc.collect()
523
524 def test_callback_in_cycle_4(self):
525 import gc
526
527 # Like test_callback_in_cycle_3, except c2 and c1 have different
528 # classes. c2's class (C) isn't reachable from c1 then, so protecting
529 # objects reachable from the dying object (c1) isn't enough to stop
530 # c2's class (C) from getting tp_clear'ed before c2.cb is invoked.
531 # The result was a segfault (C.__mro__ was NULL when the callback
532 # tried to look up self.me).
533
534 class C(object):
535 def cb(self, ignore):
536 self.me
537 self.c1
538 self.wr
539
540 class D:
541 pass
542
543 c1, c2 = D(), C()
544
545 c2.me = c2
546 c2.c1 = c1
547 c2.wr = weakref.ref(c1, c2.cb)
548
549 del c1, c2, C, D
550 gc.collect()
551
552 def test_callback_in_cycle_resurrection(self):
553 import gc
554
555 # Do something nasty in a weakref callback: resurrect objects
556 # from dead cycles. For this to be attempted, the weakref and
557 # its callback must also be part of the cyclic trash (else the
558 # objects reachable via the callback couldn't be in cyclic trash
559 # to begin with -- the callback would act like an external root).
560 # But gc clears trash weakrefs with callbacks early now, which
561 # disables the callbacks, so the callbacks shouldn't get called
562 # at all (and so nothing actually gets resurrected).
563
564 alist = []
565 class C(object):
566 def __init__(self, value):
567 self.attribute = value
568
569 def acallback(self, ignore):
570 alist.append(self.c)
571
572 c1, c2 = C(1), C(2)
573 c1.c = c2
574 c2.c = c1
575 c1.wr = weakref.ref(c2, c1.acallback)
576 c2.wr = weakref.ref(c1, c2.acallback)
577
578 def C_went_away(ignore):
579 alist.append("C went away")
580 wr = weakref.ref(C, C_went_away)
581
582 del c1, c2, C # make them all trash
583 self.assertEqual(alist, []) # del isn't enough to reclaim anything
584
585 gc.collect()
586 # c1.wr and c2.wr were part of the cyclic trash, so should have
587 # been cleared without their callbacks executing. OTOH, the weakref
588 # to C is bound to a function local (wr), and wasn't trash, so that
589 # callback should have been invoked when C went away.
590 self.assertEqual(alist, ["C went away"])
591 # The remaining weakref should be dead now (its callback ran).
592 self.assertEqual(wr(), None)
593
594 del alist[:]
595 gc.collect()
596 self.assertEqual(alist, [])
597
598 def test_callbacks_on_callback(self):
599 import gc
600
601 # Set up weakref callbacks *on* weakref callbacks.
602 alist = []
603 def safe_callback(ignore):
604 alist.append("safe_callback called")
605
606 class C(object):
607 def cb(self, ignore):
608 alist.append("cb called")
609
610 c, d = C(), C()
611 c.other = d
612 d.other = c
613 callback = c.cb
614 c.wr = weakref.ref(d, callback) # this won't trigger
615 d.wr = weakref.ref(callback, d.cb) # ditto
616 external_wr = weakref.ref(callback, safe_callback) # but this will
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000617 self.assertTrue(external_wr() is callback)
Tim Peters403a2032003-11-20 21:21:46 +0000618
619 # The weakrefs attached to c and d should get cleared, so that
620 # C.cb is never called. But external_wr isn't part of the cyclic
621 # trash, and no cyclic trash is reachable from it, so safe_callback
622 # should get invoked when the bound method object callback (c.cb)
623 # -- which is itself a callback, and also part of the cyclic trash --
624 # gets reclaimed at the end of gc.
625
626 del callback, c, d, C
627 self.assertEqual(alist, []) # del isn't enough to clean up cycles
628 gc.collect()
629 self.assertEqual(alist, ["safe_callback called"])
630 self.assertEqual(external_wr(), None)
631
632 del alist[:]
633 gc.collect()
634 self.assertEqual(alist, [])
635
Fred Drakebc875f52004-02-04 23:14:14 +0000636 def test_gc_during_ref_creation(self):
637 self.check_gc_during_creation(weakref.ref)
638
639 def test_gc_during_proxy_creation(self):
640 self.check_gc_during_creation(weakref.proxy)
641
642 def check_gc_during_creation(self, makeref):
643 thresholds = gc.get_threshold()
644 gc.set_threshold(1, 1, 1)
645 gc.collect()
Fred Drake55cf4342004-02-13 19:21:57 +0000646 class A:
647 pass
Fred Drakebc875f52004-02-04 23:14:14 +0000648
649 def callback(*args):
650 pass
651
Fred Drake55cf4342004-02-13 19:21:57 +0000652 referenced = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000653
Fred Drake55cf4342004-02-13 19:21:57 +0000654 a = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000655 a.a = a
656 a.wr = makeref(referenced)
657
658 try:
659 # now make sure the object and the ref get labeled as
660 # cyclic trash:
Fred Drake55cf4342004-02-13 19:21:57 +0000661 a = A()
662 weakref.ref(referenced, callback)
Fred Drakebc875f52004-02-04 23:14:14 +0000663
664 finally:
665 gc.set_threshold(*thresholds)
666
Brett Cannonf5bee302007-01-23 23:21:22 +0000667 def test_ref_created_during_del(self):
668 # Bug #1377858
669 # A weakref created in an object's __del__() would crash the
670 # interpreter when the weakref was cleaned up since it would refer to
671 # non-existent memory. This test should not segfault the interpreter.
672 class Target(object):
673 def __del__(self):
674 global ref_from_del
675 ref_from_del = weakref.ref(self)
676
677 w = Target()
678
Benjamin Peterson97179b02008-09-09 20:55:01 +0000679 def test_init(self):
680 # Issue 3634
681 # <weakref to class>.__init__() doesn't check errors correctly
682 r = weakref.ref(Exception)
683 self.assertRaises(TypeError, r.__init__, 0, 0, 0, 0, 0)
684 # No exception should be raised here
685 gc.collect()
686
Fred Drake0a4dd392004-07-02 18:57:45 +0000687
Amaury Forgeot d'Arca8919fe2008-06-16 19:12:42 +0000688class SubclassableWeakrefTestCase(TestBase):
Fred Drake0a4dd392004-07-02 18:57:45 +0000689
690 def test_subclass_refs(self):
691 class MyRef(weakref.ref):
692 def __init__(self, ob, callback=None, value=42):
693 self.value = value
694 super(MyRef, self).__init__(ob, callback)
695 def __call__(self):
696 self.called = True
697 return super(MyRef, self).__call__()
698 o = Object("foo")
699 mr = MyRef(o, value=24)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000700 self.assertTrue(mr() is o)
701 self.assertTrue(mr.called)
Fred Drake0a4dd392004-07-02 18:57:45 +0000702 self.assertEqual(mr.value, 24)
703 del o
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000704 self.assertTrue(mr() is None)
705 self.assertTrue(mr.called)
Fred Drake0a4dd392004-07-02 18:57:45 +0000706
707 def test_subclass_refs_dont_replace_standard_refs(self):
708 class MyRef(weakref.ref):
709 pass
710 o = Object(42)
711 r1 = MyRef(o)
712 r2 = weakref.ref(o)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000713 self.assertTrue(r1 is not r2)
Fred Drake0a4dd392004-07-02 18:57:45 +0000714 self.assertEqual(weakref.getweakrefs(o), [r2, r1])
715 self.assertEqual(weakref.getweakrefcount(o), 2)
716 r3 = MyRef(o)
717 self.assertEqual(weakref.getweakrefcount(o), 3)
718 refs = weakref.getweakrefs(o)
719 self.assertEqual(len(refs), 3)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000720 self.assertTrue(r2 is refs[0])
721 self.assertTrue(r1 in refs[1:])
722 self.assertTrue(r3 in refs[1:])
Fred Drake0a4dd392004-07-02 18:57:45 +0000723
724 def test_subclass_refs_dont_conflate_callbacks(self):
725 class MyRef(weakref.ref):
726 pass
727 o = Object(42)
728 r1 = MyRef(o, id)
729 r2 = MyRef(o, str)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000730 self.assertTrue(r1 is not r2)
Fred Drake0a4dd392004-07-02 18:57:45 +0000731 refs = weakref.getweakrefs(o)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000732 self.assertTrue(r1 in refs)
733 self.assertTrue(r2 in refs)
Fred Drake0a4dd392004-07-02 18:57:45 +0000734
735 def test_subclass_refs_with_slots(self):
736 class MyRef(weakref.ref):
737 __slots__ = "slot1", "slot2"
738 def __new__(type, ob, callback, slot1, slot2):
739 return weakref.ref.__new__(type, ob, callback)
740 def __init__(self, ob, callback, slot1, slot2):
741 self.slot1 = slot1
742 self.slot2 = slot2
743 def meth(self):
744 return self.slot1 + self.slot2
745 o = Object(42)
746 r = MyRef(o, None, "abc", "def")
747 self.assertEqual(r.slot1, "abc")
748 self.assertEqual(r.slot2, "def")
749 self.assertEqual(r.meth(), "abcdef")
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000750 self.assertFalse(hasattr(r, "__dict__"))
Fred Drake0a4dd392004-07-02 18:57:45 +0000751
Amaury Forgeot d'Arca8919fe2008-06-16 19:12:42 +0000752 def test_subclass_refs_with_cycle(self):
753 # Bug #3110
754 # An instance of a weakref subclass can have attributes.
755 # If such a weakref holds the only strong reference to the object,
756 # deleting the weakref will delete the object. In this case,
757 # the callback must not be called, because the ref object is
758 # being deleted.
759 class MyRef(weakref.ref):
760 pass
761
762 # Use a local callback, for "regrtest -R::"
763 # to detect refcounting problems
764 def callback(w):
765 self.cbcalled += 1
766
767 o = C()
768 r1 = MyRef(o, callback)
769 r1.o = o
770 del o
771
772 del r1 # Used to crash here
773
774 self.assertEqual(self.cbcalled, 0)
775
776 # Same test, with two weakrefs to the same object
777 # (since code paths are different)
778 o = C()
779 r1 = MyRef(o, callback)
780 r2 = MyRef(o, callback)
781 r1.r = r2
782 r2.o = o
783 del o
784 del r2
785
786 del r1 # Used to crash here
787
788 self.assertEqual(self.cbcalled, 0)
789
Fred Drake0a4dd392004-07-02 18:57:45 +0000790
Fred Drake41deb1e2001-02-01 05:27:45 +0000791class Object:
792 def __init__(self, arg):
793 self.arg = arg
794 def __repr__(self):
795 return "<Object %r>" % self.arg
796
Fred Drake41deb1e2001-02-01 05:27:45 +0000797
Fred Drakeb0fefc52001-03-23 04:22:45 +0000798class MappingTestCase(TestBase):
Martin v. Löwis5e163332001-02-27 18:36:56 +0000799
Fred Drakeb0fefc52001-03-23 04:22:45 +0000800 COUNT = 10
801
802 def test_weak_values(self):
Fred Drake0e540c32001-05-02 05:44:22 +0000803 #
804 # This exercises d.copy(), d.items(), d[], del d[], len(d).
805 #
806 dict, objects = self.make_weak_valued_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +0000807 for o in objects:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000808 self.assertTrue(weakref.getweakrefcount(o) == 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000809 "wrong number of weak references to %r!" % o)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000810 self.assertTrue(o is dict[o.arg],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000811 "wrong object returned by weak dict!")
812 items1 = dict.items()
813 items2 = dict.copy().items()
814 items1.sort()
815 items2.sort()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000816 self.assertTrue(items1 == items2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000817 "cloning of weak-valued dictionary did not work!")
818 del items1, items2
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000819 self.assertTrue(len(dict) == self.COUNT)
Fred Drakeb0fefc52001-03-23 04:22:45 +0000820 del objects[0]
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000821 self.assertTrue(len(dict) == (self.COUNT - 1),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000822 "deleting object did not cause dictionary update")
823 del objects, o
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000824 self.assertTrue(len(dict) == 0,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000825 "deleting the values did not clear the dictionary")
Fred Drake4fd06e02001-08-03 04:11:27 +0000826 # regression on SF bug #447152:
827 dict = weakref.WeakValueDictionary()
828 self.assertRaises(KeyError, dict.__getitem__, 1)
829 dict[2] = C()
830 self.assertRaises(KeyError, dict.__getitem__, 2)
Fred Drakeb0fefc52001-03-23 04:22:45 +0000831
832 def test_weak_keys(self):
Fred Drake0e540c32001-05-02 05:44:22 +0000833 #
834 # This exercises d.copy(), d.items(), d[] = v, d[], del d[],
Senthil Kumarance8e33a2010-01-08 19:04:16 +0000835 # len(d), d.has_key().
Fred Drake0e540c32001-05-02 05:44:22 +0000836 #
837 dict, objects = self.make_weak_keyed_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +0000838 for o in objects:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000839 self.assertTrue(weakref.getweakrefcount(o) == 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000840 "wrong number of weak references to %r!" % o)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000841 self.assertTrue(o.arg is dict[o],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000842 "wrong object returned by weak dict!")
843 items1 = dict.items()
844 items2 = dict.copy().items()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000845 self.assertTrue(set(items1) == set(items2),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000846 "cloning of weak-keyed dictionary did not work!")
847 del items1, items2
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000848 self.assertTrue(len(dict) == self.COUNT)
Fred Drakeb0fefc52001-03-23 04:22:45 +0000849 del objects[0]
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000850 self.assertTrue(len(dict) == (self.COUNT - 1),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000851 "deleting object did not cause dictionary update")
852 del objects, o
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000853 self.assertTrue(len(dict) == 0,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000854 "deleting the keys did not clear the dictionary")
Fred Drake752eda42001-11-06 16:38:34 +0000855 o = Object(42)
856 dict[o] = "What is the meaning of the universe?"
Senthil Kumarance8e33a2010-01-08 19:04:16 +0000857 self.assertTrue(dict.has_key(o))
858 self.assertTrue(not dict.has_key(34))
Martin v. Löwis5e163332001-02-27 18:36:56 +0000859
Fred Drake0e540c32001-05-02 05:44:22 +0000860 def test_weak_keyed_iters(self):
861 dict, objects = self.make_weak_keyed_dict()
862 self.check_iters(dict)
863
Fred Drake017e68c2006-05-02 06:53:59 +0000864 # Test keyrefs()
865 refs = dict.keyrefs()
866 self.assertEqual(len(refs), len(objects))
867 objects2 = list(objects)
868 for wr in refs:
869 ob = wr()
Senthil Kumarance8e33a2010-01-08 19:04:16 +0000870 self.assertTrue(dict.has_key(ob))
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000871 self.assertTrue(ob in dict)
Fred Drake017e68c2006-05-02 06:53:59 +0000872 self.assertEqual(ob.arg, dict[ob])
873 objects2.remove(ob)
874 self.assertEqual(len(objects2), 0)
875
876 # Test iterkeyrefs()
877 objects2 = list(objects)
878 self.assertEqual(len(list(dict.iterkeyrefs())), len(objects))
879 for wr in dict.iterkeyrefs():
880 ob = wr()
Senthil Kumarance8e33a2010-01-08 19:04:16 +0000881 self.assertTrue(dict.has_key(ob))
Benjamin Peterson5c8da862009-06-30 22:57:08 +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)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000917 self.assertTrue(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)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000923 self.assertTrue(len(keys) == 0, "__iter__() did not touch all keys")
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000924
925 # key iterator, via iterkeys():
926 keys = dict.keys()
927 for k in dict.iterkeys():
928 keys.remove(k)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000929 self.assertTrue(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)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000935 self.assertTrue(len(values) == 0,
Fred Drakef425b1e2003-07-14 21:37:17 +0000936 "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})
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000941 self.assertTrue(dict[o] == 364)
Guido van Rossum009afb72002-06-10 20:00:52 +0000942
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)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000947 self.assertTrue(dict[o] == 364)
Guido van Rossum009afb72002-06-10 20:00:52 +0000948
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
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000967 self.assertTrue(len(weakdict) == 2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000968 k, v = weakdict.popitem()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000969 self.assertTrue(len(weakdict) == 1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000970 if k is key1:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000971 self.assertTrue(v is value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000972 else:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000973 self.assertTrue(v is value2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000974 k, v = weakdict.popitem()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000975 self.assertTrue(len(weakdict) == 0)
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000976 if k is key1:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000977 self.assertTrue(v is value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000978 else:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000979 self.assertTrue(v is value2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000980
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):
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000990 self.assertTrue(value1 is not value2,
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000991 "invalid test"
992 " -- value parameters must be distinct objects")
993 weakdict = klass()
994 o = weakdict.setdefault(key, value1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000995 self.assertTrue(o is value1)
Senthil Kumarance8e33a2010-01-08 19:04:16 +0000996 self.assertTrue(weakdict.has_key(key))
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000997 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)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001001 self.assertTrue(o is value1)
Senthil Kumarance8e33a2010-01-08 19:04:16 +00001002 self.assertTrue(weakdict.has_key(key))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001003 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 #
Senthil Kumarance8e33a2010-01-08 19:04:16 +00001016 # This exercises d.update(), len(d), d.keys(), d.has_key(),
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)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001021 self.assertTrue(len(weakdict) == len(dict))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001022 for k in weakdict.keys():
Senthil Kumarance8e33a2010-01-08 19:04:16 +00001023 self.assertTrue(dict.has_key(k),
Fred Drakea0a4ab12001-04-16 17:37:27 +00001024 "mysterious new key appeared in weak dict")
1025 v = dict.get(k)
Benjamin Peterson5c8da862009-06-30 22:57:08 +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():
Senthil Kumarance8e33a2010-01-08 19:04:16 +00001029 self.assertTrue(weakdict.has_key(k),
Fred Drakea0a4ab12001-04-16 17:37:27 +00001030 "original key disappeared in weak dict")
1031 v = dict[k]
Benjamin Peterson5c8da862009-06-30 22:57:08 +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'
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001049 self.assertTrue(len(d) == 2)
Fred Drakeccc75622001-09-06 14:52:39 +00001050 del d[o1]
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001051 self.assertTrue(len(d) == 1)
1052 self.assertTrue(d.keys() == [o2])
Fred Drakeccc75622001-09-06 14:52:39 +00001053
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
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001060 self.assertTrue(len(d) == 2)
Fred Drakeccc75622001-09-06 14:52:39 +00001061 del d['something']
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001062 self.assertTrue(len(d) == 1)
1063 self.assertTrue(d.items() == [('something else', o2)])
Fred Drakeccc75622001-09-06 14:52:39 +00001064
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()