blob: 536a987fe4f2b6579b157aa5ce9446bd32c9ac46 [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)
Florent Xicluna07627882010-03-21 01:14:24 +000057 repr(wr)
Fred Drake43735da2002-04-11 03:59:42 +000058 # Dead reference:
59 del o
Florent Xicluna07627882010-03-21 01:14:24 +000060 repr(wr)
Fred Drake43735da2002-04-11 03:59:42 +000061
Fred Drakeb0fefc52001-03-23 04:22:45 +000062 def test_basic_callback(self):
63 self.check_basic_callback(C)
64 self.check_basic_callback(create_function)
65 self.check_basic_callback(create_bound_method)
66 self.check_basic_callback(create_unbound_method)
Fred Drake41deb1e2001-02-01 05:27:45 +000067
Fred Drakeb0fefc52001-03-23 04:22:45 +000068 def test_multiple_callbacks(self):
69 o = C()
70 ref1 = weakref.ref(o, self.callback)
71 ref2 = weakref.ref(o, self.callback)
72 del o
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")
Florent Xicluna07627882010-03-21 01:14:24 +0000172 with test_support.check_py3k_warnings():
173 p[:] = [2, 3]
Fred Drake5935ff02001-12-19 16:54:23 +0000174 self.assertEqual(len(L), 2)
175 self.assertEqual(len(p), 2)
Ezio Melottiaa980582010-01-23 23:04:36 +0000176 self.assertIn(3, p, "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)
Florent Xicluna07627882010-03-21 01:14:24 +0000186 with test_support.check_py3k_warnings():
187 self.assertEqual(L3[:], p3[:])
188 self.assertEqual(L3[5:], p3[5:])
189 self.assertEqual(L3[:5], p3[:5])
190 self.assertEqual(L3[2:5], p3[2:5])
Fred Drake5935ff02001-12-19 16:54:23 +0000191
Benjamin Petersondc3c2392009-11-19 03:00:02 +0000192 def test_proxy_unicode(self):
193 # See bug 5037
194 class C(object):
195 def __str__(self):
196 return "string"
197 def __unicode__(self):
198 return u"unicode"
199 instance = C()
Ezio Melottiaa980582010-01-23 23:04:36 +0000200 self.assertIn("__unicode__", dir(weakref.proxy(instance)))
Benjamin Petersondc3c2392009-11-19 03:00:02 +0000201 self.assertEqual(unicode(weakref.proxy(instance)), u"unicode")
202
Georg Brandl88659b02008-05-20 08:40:43 +0000203 def test_proxy_index(self):
204 class C:
205 def __index__(self):
206 return 10
207 o = C()
208 p = weakref.proxy(o)
209 self.assertEqual(operator.index(p), 10)
210
211 def test_proxy_div(self):
212 class C:
213 def __floordiv__(self, other):
214 return 42
215 def __ifloordiv__(self, other):
216 return 21
217 o = C()
218 p = weakref.proxy(o)
219 self.assertEqual(p // 5, 42)
220 p //= 5
221 self.assertEqual(p, 21)
222
Fred Drakeea2adc92004-02-03 19:56:46 +0000223 # The PyWeakref_* C API is documented as allowing either NULL or
224 # None as the value for the callback, where either means "no
225 # callback". The "no callback" ref and proxy objects are supposed
226 # to be shared so long as they exist by all callers so long as
Walter Dörwaldda1ad322006-12-12 21:55:31 +0000227 # they are active. In Python 2.3.3 and earlier, this guarantee
Fred Drakeea2adc92004-02-03 19:56:46 +0000228 # was not honored, and was broken in different ways for
229 # PyWeakref_NewRef() and PyWeakref_NewProxy(). (Two tests.)
230
231 def test_shared_ref_without_callback(self):
232 self.check_shared_without_callback(weakref.ref)
233
234 def test_shared_proxy_without_callback(self):
235 self.check_shared_without_callback(weakref.proxy)
236
237 def check_shared_without_callback(self, makeref):
238 o = Object(1)
239 p1 = makeref(o, None)
240 p2 = makeref(o, None)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000241 self.assertTrue(p1 is p2, "both callbacks were None in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000242 del p1, p2
243 p1 = makeref(o)
244 p2 = makeref(o, None)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000245 self.assertTrue(p1 is p2, "callbacks were NULL, None in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000246 del p1, p2
247 p1 = makeref(o)
248 p2 = makeref(o)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000249 self.assertTrue(p1 is p2, "both callbacks were NULL in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000250 del p1, p2
251 p1 = makeref(o, None)
252 p2 = makeref(o)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000253 self.assertTrue(p1 is p2, "callbacks were None, NULL in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000254
Fred Drakeb0fefc52001-03-23 04:22:45 +0000255 def test_callable_proxy(self):
256 o = Callable()
257 ref1 = weakref.proxy(o)
258
259 self.check_proxy(o, ref1)
260
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000261 self.assertTrue(type(ref1) is weakref.CallableProxyType,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000262 "proxy is not of callable type")
263 ref1('twinkies!')
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000264 self.assertTrue(o.bar == 'twinkies!',
Fred Drakeb0fefc52001-03-23 04:22:45 +0000265 "call through proxy not passed through to original")
Fred Drake3bb4d212001-10-18 19:28:29 +0000266 ref1(x='Splat.')
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000267 self.assertTrue(o.bar == 'Splat.',
Fred Drake3bb4d212001-10-18 19:28:29 +0000268 "call through proxy not passed through to original")
Fred Drakeb0fefc52001-03-23 04:22:45 +0000269
270 # expect due to too few args
271 self.assertRaises(TypeError, ref1)
272
273 # expect due to too many args
274 self.assertRaises(TypeError, ref1, 1, 2, 3)
275
276 def check_proxy(self, o, proxy):
277 o.foo = 1
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000278 self.assertTrue(proxy.foo == 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000279 "proxy does not reflect attribute addition")
280 o.foo = 2
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000281 self.assertTrue(proxy.foo == 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000282 "proxy does not reflect attribute modification")
283 del o.foo
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000284 self.assertTrue(not hasattr(proxy, 'foo'),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000285 "proxy does not reflect attribute removal")
286
287 proxy.foo = 1
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000288 self.assertTrue(o.foo == 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000289 "object does not reflect attribute addition via proxy")
290 proxy.foo = 2
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000291 self.assertTrue(
Fred Drakeb0fefc52001-03-23 04:22:45 +0000292 o.foo == 2,
293 "object does not reflect attribute modification via proxy")
294 del proxy.foo
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000295 self.assertTrue(not hasattr(o, 'foo'),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000296 "object does not reflect attribute removal via proxy")
297
Raymond Hettingerd693a812003-06-30 04:18:48 +0000298 def test_proxy_deletion(self):
299 # Test clearing of SF bug #762891
300 class Foo:
301 result = None
302 def __delitem__(self, accessor):
303 self.result = accessor
304 g = Foo()
305 f = weakref.proxy(g)
306 del f[0]
307 self.assertEqual(f.result, 0)
308
Raymond Hettingere6c470f2005-03-27 03:04:54 +0000309 def test_proxy_bool(self):
310 # Test clearing of SF bug #1170766
311 class List(list): pass
312 lyst = List()
313 self.assertEqual(bool(weakref.proxy(lyst)), bool(lyst))
314
Fred Drakeb0fefc52001-03-23 04:22:45 +0000315 def test_getweakrefcount(self):
316 o = C()
317 ref1 = weakref.ref(o)
318 ref2 = weakref.ref(o, self.callback)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000319 self.assertTrue(weakref.getweakrefcount(o) == 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000320 "got wrong number of weak reference objects")
321
322 proxy1 = weakref.proxy(o)
323 proxy2 = weakref.proxy(o, self.callback)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000324 self.assertTrue(weakref.getweakrefcount(o) == 4,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000325 "got wrong number of weak reference objects")
326
Fred Drakeea2adc92004-02-03 19:56:46 +0000327 del ref1, ref2, proxy1, proxy2
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000328 self.assertTrue(weakref.getweakrefcount(o) == 0,
Fred Drakeea2adc92004-02-03 19:56:46 +0000329 "weak reference objects not unlinked from"
330 " referent when discarded.")
331
Walter Dörwaldb167b042003-12-11 12:34:05 +0000332 # assumes ints do not support weakrefs
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000333 self.assertTrue(weakref.getweakrefcount(1) == 0,
Walter Dörwaldb167b042003-12-11 12:34:05 +0000334 "got wrong number of weak reference objects for int")
335
Fred Drakeb0fefc52001-03-23 04:22:45 +0000336 def test_getweakrefs(self):
337 o = C()
338 ref1 = weakref.ref(o, self.callback)
339 ref2 = weakref.ref(o, self.callback)
340 del ref1
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000341 self.assertTrue(weakref.getweakrefs(o) == [ref2],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000342 "list of refs does not match")
343
344 o = C()
345 ref1 = weakref.ref(o, self.callback)
346 ref2 = weakref.ref(o, self.callback)
347 del ref2
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000348 self.assertTrue(weakref.getweakrefs(o) == [ref1],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000349 "list of refs does not match")
350
Fred Drakeea2adc92004-02-03 19:56:46 +0000351 del ref1
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000352 self.assertTrue(weakref.getweakrefs(o) == [],
Fred Drakeea2adc92004-02-03 19:56:46 +0000353 "list of refs not cleared")
354
Walter Dörwaldb167b042003-12-11 12:34:05 +0000355 # assumes ints do not support weakrefs
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000356 self.assertTrue(weakref.getweakrefs(1) == [],
Walter Dörwaldb167b042003-12-11 12:34:05 +0000357 "list of refs does not match for int")
358
Fred Drake39c27f12001-10-18 18:06:05 +0000359 def test_newstyle_number_ops(self):
360 class F(float):
361 pass
362 f = F(2.0)
363 p = weakref.proxy(f)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000364 self.assertTrue(p + 1.0 == 3.0)
365 self.assertTrue(1.0 + p == 3.0) # this used to SEGV
Fred Drake39c27f12001-10-18 18:06:05 +0000366
Fred Drake2a64f462001-12-10 23:46:02 +0000367 def test_callbacks_protected(self):
Guido van Rossum9eee5542002-08-22 20:21:30 +0000368 # Callbacks protected from already-set exceptions?
Fred Drake2a64f462001-12-10 23:46:02 +0000369 # Regression test for SF bug #478534.
370 class BogusError(Exception):
371 pass
372 data = {}
373 def remove(k):
374 del data[k]
375 def encapsulate():
376 f = lambda : ()
377 data[weakref.ref(f, remove)] = None
378 raise BogusError
379 try:
380 encapsulate()
381 except BogusError:
382 pass
383 else:
384 self.fail("exception not properly restored")
385 try:
386 encapsulate()
387 except BogusError:
388 pass
389 else:
390 self.fail("exception not properly restored")
391
Tim Petersadd09b42003-11-12 20:43:28 +0000392 def test_sf_bug_840829(self):
393 # "weakref callbacks and gc corrupt memory"
394 # subtype_dealloc erroneously exposed a new-style instance
395 # already in the process of getting deallocated to gc,
396 # causing double-deallocation if the instance had a weakref
397 # callback that triggered gc.
398 # If the bug exists, there probably won't be an obvious symptom
399 # in a release build. In a debug build, a segfault will occur
400 # when the second attempt to remove the instance from the "list
401 # of all objects" occurs.
402
403 import gc
404
405 class C(object):
406 pass
407
408 c = C()
409 wr = weakref.ref(c, lambda ignore: gc.collect())
410 del c
411
Tim Petersf7f9e992003-11-13 21:59:32 +0000412 # There endeth the first part. It gets worse.
413 del wr
414
415 c1 = C()
416 c1.i = C()
417 wr = weakref.ref(c1.i, lambda ignore: gc.collect())
418
419 c2 = C()
420 c2.c1 = c1
421 del c1 # still alive because c2 points to it
422
423 # Now when subtype_dealloc gets called on c2, it's not enough just
424 # that c2 is immune from gc while the weakref callbacks associated
425 # with c2 execute (there are none in this 2nd half of the test, btw).
426 # subtype_dealloc goes on to call the base classes' deallocs too,
427 # so any gc triggered by weakref callbacks associated with anything
428 # torn down by a base class dealloc can also trigger double
429 # deallocation of c2.
430 del c2
Fred Drake41deb1e2001-02-01 05:27:45 +0000431
Tim Peters403a2032003-11-20 21:21:46 +0000432 def test_callback_in_cycle_1(self):
433 import gc
434
435 class J(object):
436 pass
437
438 class II(object):
439 def acallback(self, ignore):
440 self.J
441
442 I = II()
443 I.J = J
444 I.wr = weakref.ref(J, I.acallback)
445
446 # Now J and II are each in a self-cycle (as all new-style class
447 # objects are, since their __mro__ points back to them). I holds
448 # both a weak reference (I.wr) and a strong reference (I.J) to class
449 # J. I is also in a cycle (I.wr points to a weakref that references
450 # I.acallback). When we del these three, they all become trash, but
451 # the cycles prevent any of them from getting cleaned up immediately.
452 # Instead they have to wait for cyclic gc to deduce that they're
453 # trash.
454 #
455 # gc used to call tp_clear on all of them, and the order in which
456 # it does that is pretty accidental. The exact order in which we
457 # built up these things manages to provoke gc into running tp_clear
458 # in just the right order (I last). Calling tp_clear on II leaves
459 # behind an insane class object (its __mro__ becomes NULL). Calling
460 # tp_clear on J breaks its self-cycle, but J doesn't get deleted
461 # just then because of the strong reference from I.J. Calling
462 # tp_clear on I starts to clear I's __dict__, and just happens to
463 # clear I.J first -- I.wr is still intact. That removes the last
464 # reference to J, which triggers the weakref callback. The callback
465 # tries to do "self.J", and instances of new-style classes look up
466 # attributes ("J") in the class dict first. The class (II) wants to
467 # search II.__mro__, but that's NULL. The result was a segfault in
468 # a release build, and an assert failure in a debug build.
469 del I, J, II
470 gc.collect()
471
472 def test_callback_in_cycle_2(self):
473 import gc
474
475 # This is just like test_callback_in_cycle_1, except that II is an
476 # old-style class. The symptom is different then: an instance of an
477 # old-style class looks in its own __dict__ first. 'J' happens to
478 # get cleared from I.__dict__ before 'wr', and 'J' was never in II's
479 # __dict__, so the attribute isn't found. The difference is that
480 # the old-style II doesn't have a NULL __mro__ (it doesn't have any
481 # __mro__), so no segfault occurs. Instead it got:
482 # test_callback_in_cycle_2 (__main__.ReferencesTestCase) ...
483 # Exception exceptions.AttributeError:
484 # "II instance has no attribute 'J'" in <bound method II.acallback
485 # of <?.II instance at 0x00B9B4B8>> ignored
486
487 class J(object):
488 pass
489
490 class II:
491 def acallback(self, ignore):
492 self.J
493
494 I = II()
495 I.J = J
496 I.wr = weakref.ref(J, I.acallback)
497
498 del I, J, II
499 gc.collect()
500
501 def test_callback_in_cycle_3(self):
502 import gc
503
504 # This one broke the first patch that fixed the last two. In this
505 # case, the objects reachable from the callback aren't also reachable
506 # from the object (c1) *triggering* the callback: you can get to
507 # c1 from c2, but not vice-versa. The result was that c2's __dict__
508 # got tp_clear'ed by the time the c2.cb callback got invoked.
509
510 class C:
511 def cb(self, ignore):
512 self.me
513 self.c1
514 self.wr
515
516 c1, c2 = C(), C()
517
518 c2.me = c2
519 c2.c1 = c1
520 c2.wr = weakref.ref(c1, c2.cb)
521
522 del c1, c2
523 gc.collect()
524
525 def test_callback_in_cycle_4(self):
526 import gc
527
528 # Like test_callback_in_cycle_3, except c2 and c1 have different
529 # classes. c2's class (C) isn't reachable from c1 then, so protecting
530 # objects reachable from the dying object (c1) isn't enough to stop
531 # c2's class (C) from getting tp_clear'ed before c2.cb is invoked.
532 # The result was a segfault (C.__mro__ was NULL when the callback
533 # tried to look up self.me).
534
535 class C(object):
536 def cb(self, ignore):
537 self.me
538 self.c1
539 self.wr
540
541 class D:
542 pass
543
544 c1, c2 = D(), C()
545
546 c2.me = c2
547 c2.c1 = c1
548 c2.wr = weakref.ref(c1, c2.cb)
549
550 del c1, c2, C, D
551 gc.collect()
552
553 def test_callback_in_cycle_resurrection(self):
554 import gc
555
556 # Do something nasty in a weakref callback: resurrect objects
557 # from dead cycles. For this to be attempted, the weakref and
558 # its callback must also be part of the cyclic trash (else the
559 # objects reachable via the callback couldn't be in cyclic trash
560 # to begin with -- the callback would act like an external root).
561 # But gc clears trash weakrefs with callbacks early now, which
562 # disables the callbacks, so the callbacks shouldn't get called
563 # at all (and so nothing actually gets resurrected).
564
565 alist = []
566 class C(object):
567 def __init__(self, value):
568 self.attribute = value
569
570 def acallback(self, ignore):
571 alist.append(self.c)
572
573 c1, c2 = C(1), C(2)
574 c1.c = c2
575 c2.c = c1
576 c1.wr = weakref.ref(c2, c1.acallback)
577 c2.wr = weakref.ref(c1, c2.acallback)
578
579 def C_went_away(ignore):
580 alist.append("C went away")
581 wr = weakref.ref(C, C_went_away)
582
583 del c1, c2, C # make them all trash
584 self.assertEqual(alist, []) # del isn't enough to reclaim anything
585
586 gc.collect()
587 # c1.wr and c2.wr were part of the cyclic trash, so should have
588 # been cleared without their callbacks executing. OTOH, the weakref
589 # to C is bound to a function local (wr), and wasn't trash, so that
590 # callback should have been invoked when C went away.
591 self.assertEqual(alist, ["C went away"])
592 # The remaining weakref should be dead now (its callback ran).
593 self.assertEqual(wr(), None)
594
595 del alist[:]
596 gc.collect()
597 self.assertEqual(alist, [])
598
599 def test_callbacks_on_callback(self):
600 import gc
601
602 # Set up weakref callbacks *on* weakref callbacks.
603 alist = []
604 def safe_callback(ignore):
605 alist.append("safe_callback called")
606
607 class C(object):
608 def cb(self, ignore):
609 alist.append("cb called")
610
611 c, d = C(), C()
612 c.other = d
613 d.other = c
614 callback = c.cb
615 c.wr = weakref.ref(d, callback) # this won't trigger
616 d.wr = weakref.ref(callback, d.cb) # ditto
617 external_wr = weakref.ref(callback, safe_callback) # but this will
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000618 self.assertTrue(external_wr() is callback)
Tim Peters403a2032003-11-20 21:21:46 +0000619
620 # The weakrefs attached to c and d should get cleared, so that
621 # C.cb is never called. But external_wr isn't part of the cyclic
622 # trash, and no cyclic trash is reachable from it, so safe_callback
623 # should get invoked when the bound method object callback (c.cb)
624 # -- which is itself a callback, and also part of the cyclic trash --
625 # gets reclaimed at the end of gc.
626
627 del callback, c, d, C
628 self.assertEqual(alist, []) # del isn't enough to clean up cycles
629 gc.collect()
630 self.assertEqual(alist, ["safe_callback called"])
631 self.assertEqual(external_wr(), None)
632
633 del alist[:]
634 gc.collect()
635 self.assertEqual(alist, [])
636
Fred Drakebc875f52004-02-04 23:14:14 +0000637 def test_gc_during_ref_creation(self):
638 self.check_gc_during_creation(weakref.ref)
639
640 def test_gc_during_proxy_creation(self):
641 self.check_gc_during_creation(weakref.proxy)
642
643 def check_gc_during_creation(self, makeref):
644 thresholds = gc.get_threshold()
645 gc.set_threshold(1, 1, 1)
646 gc.collect()
Fred Drake55cf4342004-02-13 19:21:57 +0000647 class A:
648 pass
Fred Drakebc875f52004-02-04 23:14:14 +0000649
650 def callback(*args):
651 pass
652
Fred Drake55cf4342004-02-13 19:21:57 +0000653 referenced = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000654
Fred Drake55cf4342004-02-13 19:21:57 +0000655 a = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000656 a.a = a
657 a.wr = makeref(referenced)
658
659 try:
660 # now make sure the object and the ref get labeled as
661 # cyclic trash:
Fred Drake55cf4342004-02-13 19:21:57 +0000662 a = A()
663 weakref.ref(referenced, callback)
Fred Drakebc875f52004-02-04 23:14:14 +0000664
665 finally:
666 gc.set_threshold(*thresholds)
667
Brett Cannonf5bee302007-01-23 23:21:22 +0000668 def test_ref_created_during_del(self):
669 # Bug #1377858
670 # A weakref created in an object's __del__() would crash the
671 # interpreter when the weakref was cleaned up since it would refer to
672 # non-existent memory. This test should not segfault the interpreter.
673 class Target(object):
674 def __del__(self):
675 global ref_from_del
676 ref_from_del = weakref.ref(self)
677
678 w = Target()
679
Benjamin Peterson97179b02008-09-09 20:55:01 +0000680 def test_init(self):
681 # Issue 3634
682 # <weakref to class>.__init__() doesn't check errors correctly
683 r = weakref.ref(Exception)
684 self.assertRaises(TypeError, r.__init__, 0, 0, 0, 0, 0)
685 # No exception should be raised here
686 gc.collect()
687
Fred Drake0a4dd392004-07-02 18:57:45 +0000688
Amaury Forgeot d'Arca8919fe2008-06-16 19:12:42 +0000689class SubclassableWeakrefTestCase(TestBase):
Fred Drake0a4dd392004-07-02 18:57:45 +0000690
691 def test_subclass_refs(self):
692 class MyRef(weakref.ref):
693 def __init__(self, ob, callback=None, value=42):
694 self.value = value
695 super(MyRef, self).__init__(ob, callback)
696 def __call__(self):
697 self.called = True
698 return super(MyRef, self).__call__()
699 o = Object("foo")
700 mr = MyRef(o, value=24)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000701 self.assertTrue(mr() is o)
702 self.assertTrue(mr.called)
Fred Drake0a4dd392004-07-02 18:57:45 +0000703 self.assertEqual(mr.value, 24)
704 del o
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000705 self.assertTrue(mr() is None)
706 self.assertTrue(mr.called)
Fred Drake0a4dd392004-07-02 18:57:45 +0000707
708 def test_subclass_refs_dont_replace_standard_refs(self):
709 class MyRef(weakref.ref):
710 pass
711 o = Object(42)
712 r1 = MyRef(o)
713 r2 = weakref.ref(o)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000714 self.assertTrue(r1 is not r2)
Fred Drake0a4dd392004-07-02 18:57:45 +0000715 self.assertEqual(weakref.getweakrefs(o), [r2, r1])
716 self.assertEqual(weakref.getweakrefcount(o), 2)
717 r3 = MyRef(o)
718 self.assertEqual(weakref.getweakrefcount(o), 3)
719 refs = weakref.getweakrefs(o)
720 self.assertEqual(len(refs), 3)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000721 self.assertTrue(r2 is refs[0])
Ezio Melottiaa980582010-01-23 23:04:36 +0000722 self.assertIn(r1, refs[1:])
723 self.assertIn(r3, refs[1:])
Fred Drake0a4dd392004-07-02 18:57:45 +0000724
725 def test_subclass_refs_dont_conflate_callbacks(self):
726 class MyRef(weakref.ref):
727 pass
728 o = Object(42)
729 r1 = MyRef(o, id)
730 r2 = MyRef(o, str)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000731 self.assertTrue(r1 is not r2)
Fred Drake0a4dd392004-07-02 18:57:45 +0000732 refs = weakref.getweakrefs(o)
Ezio Melottiaa980582010-01-23 23:04:36 +0000733 self.assertIn(r1, refs)
734 self.assertIn(r2, refs)
Fred Drake0a4dd392004-07-02 18:57:45 +0000735
736 def test_subclass_refs_with_slots(self):
737 class MyRef(weakref.ref):
738 __slots__ = "slot1", "slot2"
739 def __new__(type, ob, callback, slot1, slot2):
740 return weakref.ref.__new__(type, ob, callback)
741 def __init__(self, ob, callback, slot1, slot2):
742 self.slot1 = slot1
743 self.slot2 = slot2
744 def meth(self):
745 return self.slot1 + self.slot2
746 o = Object(42)
747 r = MyRef(o, None, "abc", "def")
748 self.assertEqual(r.slot1, "abc")
749 self.assertEqual(r.slot2, "def")
750 self.assertEqual(r.meth(), "abcdef")
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000751 self.assertFalse(hasattr(r, "__dict__"))
Fred Drake0a4dd392004-07-02 18:57:45 +0000752
Amaury Forgeot d'Arca8919fe2008-06-16 19:12:42 +0000753 def test_subclass_refs_with_cycle(self):
754 # Bug #3110
755 # An instance of a weakref subclass can have attributes.
756 # If such a weakref holds the only strong reference to the object,
757 # deleting the weakref will delete the object. In this case,
758 # the callback must not be called, because the ref object is
759 # being deleted.
760 class MyRef(weakref.ref):
761 pass
762
763 # Use a local callback, for "regrtest -R::"
764 # to detect refcounting problems
765 def callback(w):
766 self.cbcalled += 1
767
768 o = C()
769 r1 = MyRef(o, callback)
770 r1.o = o
771 del o
772
773 del r1 # Used to crash here
774
775 self.assertEqual(self.cbcalled, 0)
776
777 # Same test, with two weakrefs to the same object
778 # (since code paths are different)
779 o = C()
780 r1 = MyRef(o, callback)
781 r2 = MyRef(o, callback)
782 r1.r = r2
783 r2.o = o
784 del o
785 del r2
786
787 del r1 # Used to crash here
788
789 self.assertEqual(self.cbcalled, 0)
790
Fred Drake0a4dd392004-07-02 18:57:45 +0000791
Fred Drake41deb1e2001-02-01 05:27:45 +0000792class Object:
793 def __init__(self, arg):
794 self.arg = arg
795 def __repr__(self):
796 return "<Object %r>" % self.arg
797
Fred Drake41deb1e2001-02-01 05:27:45 +0000798
Fred Drakeb0fefc52001-03-23 04:22:45 +0000799class MappingTestCase(TestBase):
Martin v. Löwis5e163332001-02-27 18:36:56 +0000800
Fred Drakeb0fefc52001-03-23 04:22:45 +0000801 COUNT = 10
802
803 def test_weak_values(self):
Fred Drake0e540c32001-05-02 05:44:22 +0000804 #
805 # This exercises d.copy(), d.items(), d[], del d[], len(d).
806 #
807 dict, objects = self.make_weak_valued_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +0000808 for o in objects:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000809 self.assertTrue(weakref.getweakrefcount(o) == 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000810 "wrong number of weak references to %r!" % o)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000811 self.assertTrue(o is dict[o.arg],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000812 "wrong object returned by weak dict!")
813 items1 = dict.items()
814 items2 = dict.copy().items()
815 items1.sort()
816 items2.sort()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000817 self.assertTrue(items1 == items2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000818 "cloning of weak-valued dictionary did not work!")
819 del items1, items2
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000820 self.assertTrue(len(dict) == self.COUNT)
Fred Drakeb0fefc52001-03-23 04:22:45 +0000821 del objects[0]
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000822 self.assertTrue(len(dict) == (self.COUNT - 1),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000823 "deleting object did not cause dictionary update")
824 del objects, o
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000825 self.assertTrue(len(dict) == 0,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000826 "deleting the values did not clear the dictionary")
Fred Drake4fd06e02001-08-03 04:11:27 +0000827 # regression on SF bug #447152:
828 dict = weakref.WeakValueDictionary()
829 self.assertRaises(KeyError, dict.__getitem__, 1)
830 dict[2] = C()
831 self.assertRaises(KeyError, dict.__getitem__, 2)
Fred Drakeb0fefc52001-03-23 04:22:45 +0000832
833 def test_weak_keys(self):
Fred Drake0e540c32001-05-02 05:44:22 +0000834 #
835 # This exercises d.copy(), d.items(), d[] = v, d[], del d[],
Florent Xicluna07627882010-03-21 01:14:24 +0000836 # len(d), in d.
Fred Drake0e540c32001-05-02 05:44:22 +0000837 #
838 dict, objects = self.make_weak_keyed_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +0000839 for o in objects:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000840 self.assertTrue(weakref.getweakrefcount(o) == 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000841 "wrong number of weak references to %r!" % o)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000842 self.assertTrue(o.arg is dict[o],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000843 "wrong object returned by weak dict!")
844 items1 = dict.items()
845 items2 = dict.copy().items()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000846 self.assertTrue(set(items1) == set(items2),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000847 "cloning of weak-keyed dictionary did not work!")
848 del items1, items2
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000849 self.assertTrue(len(dict) == self.COUNT)
Fred Drakeb0fefc52001-03-23 04:22:45 +0000850 del objects[0]
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000851 self.assertTrue(len(dict) == (self.COUNT - 1),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000852 "deleting object did not cause dictionary update")
853 del objects, o
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000854 self.assertTrue(len(dict) == 0,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000855 "deleting the keys did not clear the dictionary")
Fred Drake752eda42001-11-06 16:38:34 +0000856 o = Object(42)
857 dict[o] = "What is the meaning of the universe?"
Florent Xicluna07627882010-03-21 01:14:24 +0000858 self.assertIn(o, dict)
859 self.assertNotIn(34, dict)
Martin v. Löwis5e163332001-02-27 18:36:56 +0000860
Fred Drake0e540c32001-05-02 05:44:22 +0000861 def test_weak_keyed_iters(self):
862 dict, objects = self.make_weak_keyed_dict()
863 self.check_iters(dict)
864
Fred Drake017e68c2006-05-02 06:53:59 +0000865 # Test keyrefs()
866 refs = dict.keyrefs()
867 self.assertEqual(len(refs), len(objects))
868 objects2 = list(objects)
869 for wr in refs:
870 ob = wr()
Ezio Melottiaa980582010-01-23 23:04:36 +0000871 self.assertIn(ob, 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()
Ezio Melottiaa980582010-01-23 23:04:36 +0000881 self.assertIn(ob, dict)
Fred Drake017e68c2006-05-02 06:53:59 +0000882 self.assertEqual(ob.arg, dict[ob])
883 objects2.remove(ob)
884 self.assertEqual(len(objects2), 0)
885
Fred Drake0e540c32001-05-02 05:44:22 +0000886 def test_weak_valued_iters(self):
887 dict, objects = self.make_weak_valued_dict()
888 self.check_iters(dict)
889
Fred Drake017e68c2006-05-02 06:53:59 +0000890 # Test valuerefs()
891 refs = dict.valuerefs()
892 self.assertEqual(len(refs), len(objects))
893 objects2 = list(objects)
894 for wr in refs:
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
901 # Test itervaluerefs()
902 objects2 = list(objects)
903 self.assertEqual(len(list(dict.itervaluerefs())), len(objects))
904 for wr in dict.itervaluerefs():
905 ob = wr()
906 self.assertEqual(ob, dict[ob.arg])
907 self.assertEqual(ob.arg, dict[ob.arg].arg)
908 objects2.remove(ob)
909 self.assertEqual(len(objects2), 0)
910
Fred Drake0e540c32001-05-02 05:44:22 +0000911 def check_iters(self, dict):
912 # item iterator:
913 items = dict.items()
914 for item in dict.iteritems():
915 items.remove(item)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000916 self.assertTrue(len(items) == 0, "iteritems() did not touch all items")
Fred Drake0e540c32001-05-02 05:44:22 +0000917
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000918 # key iterator, via __iter__():
Fred Drake0e540c32001-05-02 05:44:22 +0000919 keys = dict.keys()
920 for k in dict:
921 keys.remove(k)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000922 self.assertTrue(len(keys) == 0, "__iter__() did not touch all keys")
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000923
924 # key iterator, via iterkeys():
925 keys = dict.keys()
926 for k in dict.iterkeys():
927 keys.remove(k)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000928 self.assertTrue(len(keys) == 0, "iterkeys() did not touch all keys")
Fred Drake0e540c32001-05-02 05:44:22 +0000929
930 # value iterator:
931 values = dict.values()
932 for v in dict.itervalues():
933 values.remove(v)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000934 self.assertTrue(len(values) == 0,
Fred Drakef425b1e2003-07-14 21:37:17 +0000935 "itervalues() did not touch all values")
Fred Drake0e540c32001-05-02 05:44:22 +0000936
Guido van Rossum009afb72002-06-10 20:00:52 +0000937 def test_make_weak_keyed_dict_from_dict(self):
938 o = Object(3)
939 dict = weakref.WeakKeyDictionary({o:364})
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000940 self.assertTrue(dict[o] == 364)
Guido van Rossum009afb72002-06-10 20:00:52 +0000941
942 def test_make_weak_keyed_dict_from_weak_keyed_dict(self):
943 o = Object(3)
944 dict = weakref.WeakKeyDictionary({o:364})
945 dict2 = weakref.WeakKeyDictionary(dict)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000946 self.assertTrue(dict[o] == 364)
Guido van Rossum009afb72002-06-10 20:00:52 +0000947
Fred Drake0e540c32001-05-02 05:44:22 +0000948 def make_weak_keyed_dict(self):
949 dict = weakref.WeakKeyDictionary()
950 objects = map(Object, range(self.COUNT))
951 for o in objects:
952 dict[o] = o.arg
953 return dict, objects
954
955 def make_weak_valued_dict(self):
956 dict = weakref.WeakValueDictionary()
957 objects = map(Object, range(self.COUNT))
958 for o in objects:
959 dict[o.arg] = o
960 return dict, objects
961
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000962 def check_popitem(self, klass, key1, value1, key2, value2):
963 weakdict = klass()
964 weakdict[key1] = value1
965 weakdict[key2] = value2
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000966 self.assertTrue(len(weakdict) == 2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000967 k, v = weakdict.popitem()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000968 self.assertTrue(len(weakdict) == 1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000969 if k is key1:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000970 self.assertTrue(v is value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000971 else:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000972 self.assertTrue(v is value2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000973 k, v = weakdict.popitem()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000974 self.assertTrue(len(weakdict) == 0)
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000975 if k is key1:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000976 self.assertTrue(v is value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000977 else:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000978 self.assertTrue(v is value2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000979
980 def test_weak_valued_dict_popitem(self):
981 self.check_popitem(weakref.WeakValueDictionary,
982 "key1", C(), "key2", C())
983
984 def test_weak_keyed_dict_popitem(self):
985 self.check_popitem(weakref.WeakKeyDictionary,
986 C(), "value 1", C(), "value 2")
987
988 def check_setdefault(self, klass, key, value1, value2):
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000989 self.assertTrue(value1 is not value2,
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000990 "invalid test"
991 " -- value parameters must be distinct objects")
992 weakdict = klass()
993 o = weakdict.setdefault(key, value1)
Florent Xicluna07627882010-03-21 01:14:24 +0000994 self.assertIs(o, value1)
995 self.assertIn(key, weakdict)
996 self.assertIs(weakdict.get(key), value1)
997 self.assertIs(weakdict[key], value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000998
999 o = weakdict.setdefault(key, value2)
Florent Xicluna07627882010-03-21 01:14:24 +00001000 self.assertIs(o, value1)
1001 self.assertIn(key, weakdict)
1002 self.assertIs(weakdict.get(key), value1)
1003 self.assertIs(weakdict[key], value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001004
1005 def test_weak_valued_dict_setdefault(self):
1006 self.check_setdefault(weakref.WeakValueDictionary,
1007 "key", C(), C())
1008
1009 def test_weak_keyed_dict_setdefault(self):
1010 self.check_setdefault(weakref.WeakKeyDictionary,
1011 C(), "value 1", "value 2")
1012
Fred Drakea0a4ab12001-04-16 17:37:27 +00001013 def check_update(self, klass, dict):
Fred Drake0e540c32001-05-02 05:44:22 +00001014 #
Florent Xicluna07627882010-03-21 01:14:24 +00001015 # This exercises d.update(), len(d), d.keys(), in d,
Fred Drake0e540c32001-05-02 05:44:22 +00001016 # d.get(), d[].
1017 #
Fred Drakea0a4ab12001-04-16 17:37:27 +00001018 weakdict = klass()
1019 weakdict.update(dict)
Florent Xicluna07627882010-03-21 01:14:24 +00001020 self.assertEqual(len(weakdict), len(dict))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001021 for k in weakdict.keys():
Florent Xicluna07627882010-03-21 01:14:24 +00001022 self.assertIn(k, dict,
Fred Drakea0a4ab12001-04-16 17:37:27 +00001023 "mysterious new key appeared in weak dict")
1024 v = dict.get(k)
Florent Xicluna07627882010-03-21 01:14:24 +00001025 self.assertIs(v, weakdict[k])
1026 self.assertIs(v, weakdict.get(k))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001027 for k in dict.keys():
Florent Xicluna07627882010-03-21 01:14:24 +00001028 self.assertIn(k, weakdict,
Fred Drakea0a4ab12001-04-16 17:37:27 +00001029 "original key disappeared in weak dict")
1030 v = dict[k]
Florent Xicluna07627882010-03-21 01:14:24 +00001031 self.assertIs(v, weakdict[k])
1032 self.assertIs(v, weakdict.get(k))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001033
1034 def test_weak_valued_dict_update(self):
1035 self.check_update(weakref.WeakValueDictionary,
1036 {1: C(), 'a': C(), C(): C()})
1037
1038 def test_weak_keyed_dict_update(self):
1039 self.check_update(weakref.WeakKeyDictionary,
1040 {C(): 1, C(): 2, C(): 3})
1041
Fred Drakeccc75622001-09-06 14:52:39 +00001042 def test_weak_keyed_delitem(self):
1043 d = weakref.WeakKeyDictionary()
1044 o1 = Object('1')
1045 o2 = Object('2')
1046 d[o1] = 'something'
1047 d[o2] = 'something'
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001048 self.assertTrue(len(d) == 2)
Fred Drakeccc75622001-09-06 14:52:39 +00001049 del d[o1]
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001050 self.assertTrue(len(d) == 1)
1051 self.assertTrue(d.keys() == [o2])
Fred Drakeccc75622001-09-06 14:52:39 +00001052
1053 def test_weak_valued_delitem(self):
1054 d = weakref.WeakValueDictionary()
1055 o1 = Object('1')
1056 o2 = Object('2')
1057 d['something'] = o1
1058 d['something else'] = o2
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001059 self.assertTrue(len(d) == 2)
Fred Drakeccc75622001-09-06 14:52:39 +00001060 del d['something']
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001061 self.assertTrue(len(d) == 1)
1062 self.assertTrue(d.items() == [('something else', o2)])
Fred Drakeccc75622001-09-06 14:52:39 +00001063
Tim Peters886128f2003-05-25 01:45:11 +00001064 def test_weak_keyed_bad_delitem(self):
1065 d = weakref.WeakKeyDictionary()
1066 o = Object('1')
1067 # An attempt to delete an object that isn't there should raise
Tim Peters50d8b8b2003-05-25 17:44:31 +00001068 # KeyError. It didn't before 2.3.
Tim Peters886128f2003-05-25 01:45:11 +00001069 self.assertRaises(KeyError, d.__delitem__, o)
Tim Peters50d8b8b2003-05-25 17:44:31 +00001070 self.assertRaises(KeyError, d.__getitem__, o)
1071
1072 # If a key isn't of a weakly referencable type, __getitem__ and
1073 # __setitem__ raise TypeError. __delitem__ should too.
1074 self.assertRaises(TypeError, d.__delitem__, 13)
1075 self.assertRaises(TypeError, d.__getitem__, 13)
1076 self.assertRaises(TypeError, d.__setitem__, 13, 13)
Tim Peters886128f2003-05-25 01:45:11 +00001077
1078 def test_weak_keyed_cascading_deletes(self):
1079 # SF bug 742860. For some reason, before 2.3 __delitem__ iterated
1080 # over the keys via self.data.iterkeys(). If things vanished from
1081 # the dict during this (or got added), that caused a RuntimeError.
1082
1083 d = weakref.WeakKeyDictionary()
1084 mutate = False
1085
1086 class C(object):
1087 def __init__(self, i):
1088 self.value = i
1089 def __hash__(self):
1090 return hash(self.value)
1091 def __eq__(self, other):
1092 if mutate:
1093 # Side effect that mutates the dict, by removing the
1094 # last strong reference to a key.
1095 del objs[-1]
1096 return self.value == other.value
1097
1098 objs = [C(i) for i in range(4)]
1099 for o in objs:
1100 d[o] = o.value
1101 del o # now the only strong references to keys are in objs
1102 # Find the order in which iterkeys sees the keys.
1103 objs = d.keys()
1104 # Reverse it, so that the iteration implementation of __delitem__
1105 # has to keep looping to find the first object we delete.
1106 objs.reverse()
Tim Peters50d8b8b2003-05-25 17:44:31 +00001107
Tim Peters886128f2003-05-25 01:45:11 +00001108 # Turn on mutation in C.__eq__. The first time thru the loop,
1109 # under the iterkeys() business the first comparison will delete
1110 # the last item iterkeys() would see, and that causes a
1111 # RuntimeError: dictionary changed size during iteration
1112 # when the iterkeys() loop goes around to try comparing the next
Tim Peters50d8b8b2003-05-25 17:44:31 +00001113 # key. After this was fixed, it just deletes the last object *our*
Tim Peters886128f2003-05-25 01:45:11 +00001114 # "for o in obj" loop would have gotten to.
1115 mutate = True
1116 count = 0
1117 for o in objs:
1118 count += 1
1119 del d[o]
1120 self.assertEqual(len(d), 0)
1121 self.assertEqual(count, 2)
1122
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001123from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001124
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001125class WeakValueDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +00001126 """Check that WeakValueDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001127 __ref = {"key1":Object(1), "key2":Object(2), "key3":Object(3)}
Walter Dörwald118f9312004-06-02 18:42:25 +00001128 type2test = weakref.WeakValueDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001129 def _reference(self):
1130 return self.__ref.copy()
1131
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001132class WeakKeyDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +00001133 """Check that WeakKeyDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001134 __ref = {Object("key1"):1, Object("key2"):2, Object("key3"):3}
Walter Dörwald118f9312004-06-02 18:42:25 +00001135 type2test = weakref.WeakKeyDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001136 def _reference(self):
1137 return self.__ref.copy()
Martin v. Löwis5e163332001-02-27 18:36:56 +00001138
Georg Brandl88659b02008-05-20 08:40:43 +00001139libreftest = """ Doctest for examples in the library reference: weakref.rst
Georg Brandl9a65d582005-07-02 19:07:30 +00001140
1141>>> import weakref
1142>>> class Dict(dict):
1143... pass
1144...
1145>>> obj = Dict(red=1, green=2, blue=3) # this object is weak referencable
1146>>> r = weakref.ref(obj)
Armin Rigoa3f09272006-05-28 19:13:17 +00001147>>> print r() is obj
1148True
Georg Brandl9a65d582005-07-02 19:07:30 +00001149
1150>>> import weakref
1151>>> class Object:
1152... pass
1153...
1154>>> o = Object()
1155>>> r = weakref.ref(o)
1156>>> o2 = r()
1157>>> o is o2
1158True
1159>>> del o, o2
1160>>> print r()
1161None
1162
1163>>> import weakref
1164>>> class ExtendedRef(weakref.ref):
1165... def __init__(self, ob, callback=None, **annotations):
1166... super(ExtendedRef, self).__init__(ob, callback)
1167... self.__counter = 0
1168... for k, v in annotations.iteritems():
1169... setattr(self, k, v)
1170... def __call__(self):
1171... '''Return a pair containing the referent and the number of
1172... times the reference has been called.
1173... '''
1174... ob = super(ExtendedRef, self).__call__()
1175... if ob is not None:
1176... self.__counter += 1
1177... ob = (ob, self.__counter)
1178... return ob
1179...
1180>>> class A: # not in docs from here, just testing the ExtendedRef
1181... pass
1182...
1183>>> a = A()
1184>>> r = ExtendedRef(a, foo=1, bar="baz")
1185>>> r.foo
11861
1187>>> r.bar
1188'baz'
1189>>> r()[1]
11901
1191>>> r()[1]
11922
1193>>> r()[0] is a
1194True
1195
1196
1197>>> import weakref
1198>>> _id2obj_dict = weakref.WeakValueDictionary()
1199>>> def remember(obj):
1200... oid = id(obj)
1201... _id2obj_dict[oid] = obj
1202... return oid
1203...
1204>>> def id2obj(oid):
1205... return _id2obj_dict[oid]
1206...
1207>>> a = A() # from here, just testing
1208>>> a_id = remember(a)
1209>>> id2obj(a_id) is a
1210True
1211>>> del a
1212>>> try:
1213... id2obj(a_id)
1214... except KeyError:
1215... print 'OK'
1216... else:
1217... print 'WeakValueDictionary error'
1218OK
1219
1220"""
1221
1222__test__ = {'libreftest' : libreftest}
1223
Fred Drake2e2be372001-09-20 21:33:42 +00001224def test_main():
Walter Dörwald21d3a322003-05-01 17:45:56 +00001225 test_support.run_unittest(
1226 ReferencesTestCase,
1227 MappingTestCase,
1228 WeakValueDictionaryTestCase,
Fred Drakef425b1e2003-07-14 21:37:17 +00001229 WeakKeyDictionaryTestCase,
Amaury Forgeot d'Arca8919fe2008-06-16 19:12:42 +00001230 SubclassableWeakrefTestCase,
Fred Drakef425b1e2003-07-14 21:37:17 +00001231 )
Georg Brandl9a65d582005-07-02 19:07:30 +00001232 test_support.run_doctest(sys.modules[__name__])
Fred Drake2e2be372001-09-20 21:33:42 +00001233
1234
1235if __name__ == "__main__":
1236 test_main()