blob: b70230f1b40a6a4ff0be3b91ea2c8020a3cad323 [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
Antoine Pitroub704eab2012-11-11 19:36:51 +010036class Object:
37 def __init__(self, arg):
38 self.arg = arg
39 def __repr__(self):
40 return "<Object %r>" % self.arg
41 def __eq__(self, other):
42 if isinstance(other, Object):
43 return self.arg == other.arg
44 return NotImplemented
45 def __ne__(self, other):
46 if isinstance(other, Object):
47 return self.arg != other.arg
48 return NotImplemented
49 def __hash__(self):
50 return hash(self.arg)
51
52class RefCycle:
53 def __init__(self):
54 self.cycle = self
55
56
Fred Drakeb0fefc52001-03-23 04:22:45 +000057class TestBase(unittest.TestCase):
58
59 def setUp(self):
60 self.cbcalled = 0
61
62 def callback(self, ref):
63 self.cbcalled += 1
Fred Drake41deb1e2001-02-01 05:27:45 +000064
65
Fred Drakeb0fefc52001-03-23 04:22:45 +000066class ReferencesTestCase(TestBase):
Fred Drake41deb1e2001-02-01 05:27:45 +000067
Fred Drakeb0fefc52001-03-23 04:22:45 +000068 def test_basic_ref(self):
69 self.check_basic_ref(C)
70 self.check_basic_ref(create_function)
71 self.check_basic_ref(create_bound_method)
72 self.check_basic_ref(create_unbound_method)
Fred Drake41deb1e2001-02-01 05:27:45 +000073
Fred Drake43735da2002-04-11 03:59:42 +000074 # Just make sure the tp_repr handler doesn't raise an exception.
75 # Live reference:
76 o = C()
77 wr = weakref.ref(o)
Florent Xicluna07627882010-03-21 01:14:24 +000078 repr(wr)
Fred Drake43735da2002-04-11 03:59:42 +000079 # Dead reference:
80 del o
Florent Xicluna07627882010-03-21 01:14:24 +000081 repr(wr)
Fred Drake43735da2002-04-11 03:59:42 +000082
Fred Drakeb0fefc52001-03-23 04:22:45 +000083 def test_basic_callback(self):
84 self.check_basic_callback(C)
85 self.check_basic_callback(create_function)
86 self.check_basic_callback(create_bound_method)
87 self.check_basic_callback(create_unbound_method)
Fred Drake41deb1e2001-02-01 05:27:45 +000088
Fred Drakeb0fefc52001-03-23 04:22:45 +000089 def test_multiple_callbacks(self):
90 o = C()
91 ref1 = weakref.ref(o, self.callback)
92 ref2 = weakref.ref(o, self.callback)
93 del o
Serhiy Storchakaca626b12013-11-17 13:20:50 +020094 self.assertIsNone(ref1(), "expected reference to be invalidated")
95 self.assertIsNone(ref2(), "expected reference to be invalidated")
96 self.assertEqual(self.cbcalled, 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +000097 "callback not called the right number of times")
Fred Drake41deb1e2001-02-01 05:27:45 +000098
Fred Drake705088e2001-04-13 17:18:15 +000099 def test_multiple_selfref_callbacks(self):
Guido van Rossum9eee5542002-08-22 20:21:30 +0000100 # Make sure all references are invalidated before callbacks are called
Fred Drake705088e2001-04-13 17:18:15 +0000101 #
102 # What's important here is that we're using the first
103 # reference in the callback invoked on the second reference
104 # (the most recently created ref is cleaned up first). This
105 # tests that all references to the object are invalidated
106 # before any of the callbacks are invoked, so that we only
107 # have one invocation of _weakref.c:cleanup_helper() active
108 # for a particular object at a time.
109 #
110 def callback(object, self=self):
111 self.ref()
112 c = C()
113 self.ref = weakref.ref(c, callback)
114 ref1 = weakref.ref(c, callback)
115 del c
116
Fred Drakeb0fefc52001-03-23 04:22:45 +0000117 def test_proxy_ref(self):
118 o = C()
119 o.bar = 1
120 ref1 = weakref.proxy(o, self.callback)
121 ref2 = weakref.proxy(o, self.callback)
122 del o
Fred Drake41deb1e2001-02-01 05:27:45 +0000123
Fred Drakeb0fefc52001-03-23 04:22:45 +0000124 def check(proxy):
125 proxy.bar
Fred Drake41deb1e2001-02-01 05:27:45 +0000126
Fred Drakeb0fefc52001-03-23 04:22:45 +0000127 self.assertRaises(weakref.ReferenceError, check, ref1)
128 self.assertRaises(weakref.ReferenceError, check, ref2)
Neal Norwitzbdcb9412004-07-08 01:22:31 +0000129 self.assertRaises(weakref.ReferenceError, bool, weakref.proxy(C()))
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200130 self.assertEqual(self.cbcalled, 2)
Fred Drake41deb1e2001-02-01 05:27:45 +0000131
Fred Drakeb0fefc52001-03-23 04:22:45 +0000132 def check_basic_ref(self, factory):
133 o = factory()
134 ref = weakref.ref(o)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200135 self.assertIsNotNone(ref(),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000136 "weak reference to live object should be live")
137 o2 = ref()
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200138 self.assertIs(o, o2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000139 "<ref>() should return original object if live")
Fred Drake41deb1e2001-02-01 05:27:45 +0000140
Fred Drakeb0fefc52001-03-23 04:22:45 +0000141 def check_basic_callback(self, factory):
142 self.cbcalled = 0
143 o = factory()
144 ref = weakref.ref(o, self.callback)
145 del o
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200146 self.assertEqual(self.cbcalled, 1,
Fred Drake705088e2001-04-13 17:18:15 +0000147 "callback did not properly set 'cbcalled'")
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200148 self.assertIsNone(ref(),
Fred Drake705088e2001-04-13 17:18:15 +0000149 "ref2 should be dead after deleting object reference")
Fred Drake41deb1e2001-02-01 05:27:45 +0000150
Fred Drakeb0fefc52001-03-23 04:22:45 +0000151 def test_ref_reuse(self):
152 o = C()
153 ref1 = weakref.ref(o)
154 # create a proxy to make sure that there's an intervening creation
155 # between these two; it should make no difference
156 proxy = weakref.proxy(o)
157 ref2 = weakref.ref(o)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200158 self.assertIs(ref1, ref2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000159 "reference object w/out callback should be re-used")
Fred Drake41deb1e2001-02-01 05:27:45 +0000160
Fred Drakeb0fefc52001-03-23 04:22:45 +0000161 o = C()
162 proxy = weakref.proxy(o)
163 ref1 = weakref.ref(o)
164 ref2 = weakref.ref(o)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200165 self.assertIs(ref1, ref2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000166 "reference object w/out callback should be re-used")
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200167 self.assertEqual(weakref.getweakrefcount(o), 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000168 "wrong weak ref count for object")
169 del proxy
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200170 self.assertEqual(weakref.getweakrefcount(o), 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000171 "wrong weak ref count for object after deleting proxy")
Fred Drake41deb1e2001-02-01 05:27:45 +0000172
Fred Drakeb0fefc52001-03-23 04:22:45 +0000173 def test_proxy_reuse(self):
174 o = C()
175 proxy1 = weakref.proxy(o)
176 ref = weakref.ref(o)
177 proxy2 = weakref.proxy(o)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200178 self.assertIs(proxy1, proxy2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000179 "proxy object w/out callback should have been re-used")
180
181 def test_basic_proxy(self):
182 o = C()
183 self.check_proxy(o, weakref.proxy(o))
184
Fred Drake5935ff02001-12-19 16:54:23 +0000185 L = UserList.UserList()
186 p = weakref.proxy(L)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000187 self.assertFalse(p, "proxy for empty UserList should be false")
Fred Drake5935ff02001-12-19 16:54:23 +0000188 p.append(12)
189 self.assertEqual(len(L), 1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000190 self.assertTrue(p, "proxy for non-empty UserList should be true")
Florent Xicluna07627882010-03-21 01:14:24 +0000191 with test_support.check_py3k_warnings():
192 p[:] = [2, 3]
Fred Drake5935ff02001-12-19 16:54:23 +0000193 self.assertEqual(len(L), 2)
194 self.assertEqual(len(p), 2)
Ezio Melottiaa980582010-01-23 23:04:36 +0000195 self.assertIn(3, p, "proxy didn't support __contains__() properly")
Fred Drake5935ff02001-12-19 16:54:23 +0000196 p[1] = 5
197 self.assertEqual(L[1], 5)
198 self.assertEqual(p[1], 5)
199 L2 = UserList.UserList(L)
200 p2 = weakref.proxy(L2)
201 self.assertEqual(p, p2)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000202 ## self.assertEqual(repr(L2), repr(p2))
Fred Drake43735da2002-04-11 03:59:42 +0000203 L3 = UserList.UserList(range(10))
204 p3 = weakref.proxy(L3)
Florent Xicluna07627882010-03-21 01:14:24 +0000205 with test_support.check_py3k_warnings():
206 self.assertEqual(L3[:], p3[:])
207 self.assertEqual(L3[5:], p3[5:])
208 self.assertEqual(L3[:5], p3[:5])
209 self.assertEqual(L3[2:5], p3[2:5])
Fred Drake5935ff02001-12-19 16:54:23 +0000210
Benjamin Petersondc3c2392009-11-19 03:00:02 +0000211 def test_proxy_unicode(self):
212 # See bug 5037
213 class C(object):
214 def __str__(self):
215 return "string"
216 def __unicode__(self):
217 return u"unicode"
218 instance = C()
Ezio Melottiaa980582010-01-23 23:04:36 +0000219 self.assertIn("__unicode__", dir(weakref.proxy(instance)))
Benjamin Petersondc3c2392009-11-19 03:00:02 +0000220 self.assertEqual(unicode(weakref.proxy(instance)), u"unicode")
221
Georg Brandl88659b02008-05-20 08:40:43 +0000222 def test_proxy_index(self):
223 class C:
224 def __index__(self):
225 return 10
226 o = C()
227 p = weakref.proxy(o)
228 self.assertEqual(operator.index(p), 10)
229
230 def test_proxy_div(self):
231 class C:
232 def __floordiv__(self, other):
233 return 42
234 def __ifloordiv__(self, other):
235 return 21
236 o = C()
237 p = weakref.proxy(o)
238 self.assertEqual(p // 5, 42)
239 p //= 5
240 self.assertEqual(p, 21)
241
Fred Drakeea2adc92004-02-03 19:56:46 +0000242 # The PyWeakref_* C API is documented as allowing either NULL or
243 # None as the value for the callback, where either means "no
244 # callback". The "no callback" ref and proxy objects are supposed
245 # to be shared so long as they exist by all callers so long as
Walter Dörwaldda1ad322006-12-12 21:55:31 +0000246 # they are active. In Python 2.3.3 and earlier, this guarantee
Fred Drakeea2adc92004-02-03 19:56:46 +0000247 # was not honored, and was broken in different ways for
248 # PyWeakref_NewRef() and PyWeakref_NewProxy(). (Two tests.)
249
250 def test_shared_ref_without_callback(self):
251 self.check_shared_without_callback(weakref.ref)
252
253 def test_shared_proxy_without_callback(self):
254 self.check_shared_without_callback(weakref.proxy)
255
256 def check_shared_without_callback(self, makeref):
257 o = Object(1)
258 p1 = makeref(o, None)
259 p2 = makeref(o, None)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200260 self.assertIs(p1, p2, "both callbacks were None in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000261 del p1, p2
262 p1 = makeref(o)
263 p2 = makeref(o, None)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200264 self.assertIs(p1, p2, "callbacks were NULL, None in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000265 del p1, p2
266 p1 = makeref(o)
267 p2 = makeref(o)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200268 self.assertIs(p1, p2, "both callbacks were NULL in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000269 del p1, p2
270 p1 = makeref(o, None)
271 p2 = makeref(o)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200272 self.assertIs(p1, p2, "callbacks were None, NULL in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000273
Fred Drakeb0fefc52001-03-23 04:22:45 +0000274 def test_callable_proxy(self):
275 o = Callable()
276 ref1 = weakref.proxy(o)
277
278 self.check_proxy(o, ref1)
279
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200280 self.assertIs(type(ref1), weakref.CallableProxyType,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000281 "proxy is not of callable type")
282 ref1('twinkies!')
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200283 self.assertEqual(o.bar, 'twinkies!',
Fred Drakeb0fefc52001-03-23 04:22:45 +0000284 "call through proxy not passed through to original")
Fred Drake3bb4d212001-10-18 19:28:29 +0000285 ref1(x='Splat.')
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200286 self.assertEqual(o.bar, 'Splat.',
Fred Drake3bb4d212001-10-18 19:28:29 +0000287 "call through proxy not passed through to original")
Fred Drakeb0fefc52001-03-23 04:22:45 +0000288
289 # expect due to too few args
290 self.assertRaises(TypeError, ref1)
291
292 # expect due to too many args
293 self.assertRaises(TypeError, ref1, 1, 2, 3)
294
295 def check_proxy(self, o, proxy):
296 o.foo = 1
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200297 self.assertEqual(proxy.foo, 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000298 "proxy does not reflect attribute addition")
299 o.foo = 2
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200300 self.assertEqual(proxy.foo, 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000301 "proxy does not reflect attribute modification")
302 del o.foo
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200303 self.assertFalse(hasattr(proxy, 'foo'),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000304 "proxy does not reflect attribute removal")
305
306 proxy.foo = 1
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200307 self.assertEqual(o.foo, 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000308 "object does not reflect attribute addition via proxy")
309 proxy.foo = 2
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200310 self.assertEqual(o.foo, 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000311 "object does not reflect attribute modification via proxy")
312 del proxy.foo
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200313 self.assertFalse(hasattr(o, 'foo'),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000314 "object does not reflect attribute removal via proxy")
315
Raymond Hettingerd693a812003-06-30 04:18:48 +0000316 def test_proxy_deletion(self):
317 # Test clearing of SF bug #762891
318 class Foo:
319 result = None
320 def __delitem__(self, accessor):
321 self.result = accessor
322 g = Foo()
323 f = weakref.proxy(g)
324 del f[0]
325 self.assertEqual(f.result, 0)
326
Raymond Hettingere6c470f2005-03-27 03:04:54 +0000327 def test_proxy_bool(self):
328 # Test clearing of SF bug #1170766
329 class List(list): pass
330 lyst = List()
331 self.assertEqual(bool(weakref.proxy(lyst)), bool(lyst))
332
Fred Drakeb0fefc52001-03-23 04:22:45 +0000333 def test_getweakrefcount(self):
334 o = C()
335 ref1 = weakref.ref(o)
336 ref2 = weakref.ref(o, self.callback)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200337 self.assertEqual(weakref.getweakrefcount(o), 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000338 "got wrong number of weak reference objects")
339
340 proxy1 = weakref.proxy(o)
341 proxy2 = weakref.proxy(o, self.callback)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200342 self.assertEqual(weakref.getweakrefcount(o), 4,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000343 "got wrong number of weak reference objects")
344
Fred Drakeea2adc92004-02-03 19:56:46 +0000345 del ref1, ref2, proxy1, proxy2
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200346 self.assertEqual(weakref.getweakrefcount(o), 0,
Fred Drakeea2adc92004-02-03 19:56:46 +0000347 "weak reference objects not unlinked from"
348 " referent when discarded.")
349
Walter Dörwaldb167b042003-12-11 12:34:05 +0000350 # assumes ints do not support weakrefs
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200351 self.assertEqual(weakref.getweakrefcount(1), 0,
Walter Dörwaldb167b042003-12-11 12:34:05 +0000352 "got wrong number of weak reference objects for int")
353
Fred Drakeb0fefc52001-03-23 04:22:45 +0000354 def test_getweakrefs(self):
355 o = C()
356 ref1 = weakref.ref(o, self.callback)
357 ref2 = weakref.ref(o, self.callback)
358 del ref1
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200359 self.assertEqual(weakref.getweakrefs(o), [ref2],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000360 "list of refs does not match")
361
362 o = C()
363 ref1 = weakref.ref(o, self.callback)
364 ref2 = weakref.ref(o, self.callback)
365 del ref2
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200366 self.assertEqual(weakref.getweakrefs(o), [ref1],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000367 "list of refs does not match")
368
Fred Drakeea2adc92004-02-03 19:56:46 +0000369 del ref1
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200370 self.assertEqual(weakref.getweakrefs(o), [],
Fred Drakeea2adc92004-02-03 19:56:46 +0000371 "list of refs not cleared")
372
Walter Dörwaldb167b042003-12-11 12:34:05 +0000373 # assumes ints do not support weakrefs
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200374 self.assertEqual(weakref.getweakrefs(1), [],
Walter Dörwaldb167b042003-12-11 12:34:05 +0000375 "list of refs does not match for int")
376
Fred Drake39c27f12001-10-18 18:06:05 +0000377 def test_newstyle_number_ops(self):
378 class F(float):
379 pass
380 f = F(2.0)
381 p = weakref.proxy(f)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200382 self.assertEqual(p + 1.0, 3.0)
383 self.assertEqual(1.0 + p, 3.0) # this used to SEGV
Fred Drake39c27f12001-10-18 18:06:05 +0000384
Fred Drake2a64f462001-12-10 23:46:02 +0000385 def test_callbacks_protected(self):
Guido van Rossum9eee5542002-08-22 20:21:30 +0000386 # Callbacks protected from already-set exceptions?
Fred Drake2a64f462001-12-10 23:46:02 +0000387 # Regression test for SF bug #478534.
388 class BogusError(Exception):
389 pass
390 data = {}
391 def remove(k):
392 del data[k]
393 def encapsulate():
394 f = lambda : ()
395 data[weakref.ref(f, remove)] = None
396 raise BogusError
397 try:
398 encapsulate()
399 except BogusError:
400 pass
401 else:
402 self.fail("exception not properly restored")
403 try:
404 encapsulate()
405 except BogusError:
406 pass
407 else:
408 self.fail("exception not properly restored")
409
Tim Petersadd09b42003-11-12 20:43:28 +0000410 def test_sf_bug_840829(self):
411 # "weakref callbacks and gc corrupt memory"
412 # subtype_dealloc erroneously exposed a new-style instance
413 # already in the process of getting deallocated to gc,
414 # causing double-deallocation if the instance had a weakref
415 # callback that triggered gc.
416 # If the bug exists, there probably won't be an obvious symptom
417 # in a release build. In a debug build, a segfault will occur
418 # when the second attempt to remove the instance from the "list
419 # of all objects" occurs.
420
421 import gc
422
423 class C(object):
424 pass
425
426 c = C()
427 wr = weakref.ref(c, lambda ignore: gc.collect())
428 del c
429
Tim Petersf7f9e992003-11-13 21:59:32 +0000430 # There endeth the first part. It gets worse.
431 del wr
432
433 c1 = C()
434 c1.i = C()
435 wr = weakref.ref(c1.i, lambda ignore: gc.collect())
436
437 c2 = C()
438 c2.c1 = c1
439 del c1 # still alive because c2 points to it
440
441 # Now when subtype_dealloc gets called on c2, it's not enough just
442 # that c2 is immune from gc while the weakref callbacks associated
443 # with c2 execute (there are none in this 2nd half of the test, btw).
444 # subtype_dealloc goes on to call the base classes' deallocs too,
445 # so any gc triggered by weakref callbacks associated with anything
446 # torn down by a base class dealloc can also trigger double
447 # deallocation of c2.
448 del c2
Fred Drake41deb1e2001-02-01 05:27:45 +0000449
Tim Peters403a2032003-11-20 21:21:46 +0000450 def test_callback_in_cycle_1(self):
451 import gc
452
453 class J(object):
454 pass
455
456 class II(object):
457 def acallback(self, ignore):
458 self.J
459
460 I = II()
461 I.J = J
462 I.wr = weakref.ref(J, I.acallback)
463
464 # Now J and II are each in a self-cycle (as all new-style class
465 # objects are, since their __mro__ points back to them). I holds
466 # both a weak reference (I.wr) and a strong reference (I.J) to class
467 # J. I is also in a cycle (I.wr points to a weakref that references
468 # I.acallback). When we del these three, they all become trash, but
469 # the cycles prevent any of them from getting cleaned up immediately.
470 # Instead they have to wait for cyclic gc to deduce that they're
471 # trash.
472 #
473 # gc used to call tp_clear on all of them, and the order in which
474 # it does that is pretty accidental. The exact order in which we
475 # built up these things manages to provoke gc into running tp_clear
476 # in just the right order (I last). Calling tp_clear on II leaves
477 # behind an insane class object (its __mro__ becomes NULL). Calling
478 # tp_clear on J breaks its self-cycle, but J doesn't get deleted
479 # just then because of the strong reference from I.J. Calling
480 # tp_clear on I starts to clear I's __dict__, and just happens to
481 # clear I.J first -- I.wr is still intact. That removes the last
482 # reference to J, which triggers the weakref callback. The callback
483 # tries to do "self.J", and instances of new-style classes look up
484 # attributes ("J") in the class dict first. The class (II) wants to
485 # search II.__mro__, but that's NULL. The result was a segfault in
486 # a release build, and an assert failure in a debug build.
487 del I, J, II
488 gc.collect()
489
490 def test_callback_in_cycle_2(self):
491 import gc
492
493 # This is just like test_callback_in_cycle_1, except that II is an
494 # old-style class. The symptom is different then: an instance of an
495 # old-style class looks in its own __dict__ first. 'J' happens to
496 # get cleared from I.__dict__ before 'wr', and 'J' was never in II's
497 # __dict__, so the attribute isn't found. The difference is that
498 # the old-style II doesn't have a NULL __mro__ (it doesn't have any
499 # __mro__), so no segfault occurs. Instead it got:
500 # test_callback_in_cycle_2 (__main__.ReferencesTestCase) ...
501 # Exception exceptions.AttributeError:
502 # "II instance has no attribute 'J'" in <bound method II.acallback
503 # of <?.II instance at 0x00B9B4B8>> ignored
504
505 class J(object):
506 pass
507
508 class II:
509 def acallback(self, ignore):
510 self.J
511
512 I = II()
513 I.J = J
514 I.wr = weakref.ref(J, I.acallback)
515
516 del I, J, II
517 gc.collect()
518
519 def test_callback_in_cycle_3(self):
520 import gc
521
522 # This one broke the first patch that fixed the last two. In this
523 # case, the objects reachable from the callback aren't also reachable
524 # from the object (c1) *triggering* the callback: you can get to
525 # c1 from c2, but not vice-versa. The result was that c2's __dict__
526 # got tp_clear'ed by the time the c2.cb callback got invoked.
527
528 class C:
529 def cb(self, ignore):
530 self.me
531 self.c1
532 self.wr
533
534 c1, c2 = C(), C()
535
536 c2.me = c2
537 c2.c1 = c1
538 c2.wr = weakref.ref(c1, c2.cb)
539
540 del c1, c2
541 gc.collect()
542
543 def test_callback_in_cycle_4(self):
544 import gc
545
546 # Like test_callback_in_cycle_3, except c2 and c1 have different
547 # classes. c2's class (C) isn't reachable from c1 then, so protecting
548 # objects reachable from the dying object (c1) isn't enough to stop
549 # c2's class (C) from getting tp_clear'ed before c2.cb is invoked.
550 # The result was a segfault (C.__mro__ was NULL when the callback
551 # tried to look up self.me).
552
553 class C(object):
554 def cb(self, ignore):
555 self.me
556 self.c1
557 self.wr
558
559 class D:
560 pass
561
562 c1, c2 = D(), C()
563
564 c2.me = c2
565 c2.c1 = c1
566 c2.wr = weakref.ref(c1, c2.cb)
567
568 del c1, c2, C, D
569 gc.collect()
570
571 def test_callback_in_cycle_resurrection(self):
572 import gc
573
574 # Do something nasty in a weakref callback: resurrect objects
575 # from dead cycles. For this to be attempted, the weakref and
576 # its callback must also be part of the cyclic trash (else the
577 # objects reachable via the callback couldn't be in cyclic trash
578 # to begin with -- the callback would act like an external root).
579 # But gc clears trash weakrefs with callbacks early now, which
580 # disables the callbacks, so the callbacks shouldn't get called
581 # at all (and so nothing actually gets resurrected).
582
583 alist = []
584 class C(object):
585 def __init__(self, value):
586 self.attribute = value
587
588 def acallback(self, ignore):
589 alist.append(self.c)
590
591 c1, c2 = C(1), C(2)
592 c1.c = c2
593 c2.c = c1
594 c1.wr = weakref.ref(c2, c1.acallback)
595 c2.wr = weakref.ref(c1, c2.acallback)
596
597 def C_went_away(ignore):
598 alist.append("C went away")
599 wr = weakref.ref(C, C_went_away)
600
601 del c1, c2, C # make them all trash
602 self.assertEqual(alist, []) # del isn't enough to reclaim anything
603
604 gc.collect()
605 # c1.wr and c2.wr were part of the cyclic trash, so should have
606 # been cleared without their callbacks executing. OTOH, the weakref
607 # to C is bound to a function local (wr), and wasn't trash, so that
608 # callback should have been invoked when C went away.
609 self.assertEqual(alist, ["C went away"])
610 # The remaining weakref should be dead now (its callback ran).
611 self.assertEqual(wr(), None)
612
613 del alist[:]
614 gc.collect()
615 self.assertEqual(alist, [])
616
617 def test_callbacks_on_callback(self):
618 import gc
619
620 # Set up weakref callbacks *on* weakref callbacks.
621 alist = []
622 def safe_callback(ignore):
623 alist.append("safe_callback called")
624
625 class C(object):
626 def cb(self, ignore):
627 alist.append("cb called")
628
629 c, d = C(), C()
630 c.other = d
631 d.other = c
632 callback = c.cb
633 c.wr = weakref.ref(d, callback) # this won't trigger
634 d.wr = weakref.ref(callback, d.cb) # ditto
635 external_wr = weakref.ref(callback, safe_callback) # but this will
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200636 self.assertIs(external_wr(), callback)
Tim Peters403a2032003-11-20 21:21:46 +0000637
638 # The weakrefs attached to c and d should get cleared, so that
639 # C.cb is never called. But external_wr isn't part of the cyclic
640 # trash, and no cyclic trash is reachable from it, so safe_callback
641 # should get invoked when the bound method object callback (c.cb)
642 # -- which is itself a callback, and also part of the cyclic trash --
643 # gets reclaimed at the end of gc.
644
645 del callback, c, d, C
646 self.assertEqual(alist, []) # del isn't enough to clean up cycles
647 gc.collect()
648 self.assertEqual(alist, ["safe_callback called"])
649 self.assertEqual(external_wr(), None)
650
651 del alist[:]
652 gc.collect()
653 self.assertEqual(alist, [])
654
Fred Drakebc875f52004-02-04 23:14:14 +0000655 def test_gc_during_ref_creation(self):
656 self.check_gc_during_creation(weakref.ref)
657
658 def test_gc_during_proxy_creation(self):
659 self.check_gc_during_creation(weakref.proxy)
660
661 def check_gc_during_creation(self, makeref):
662 thresholds = gc.get_threshold()
663 gc.set_threshold(1, 1, 1)
664 gc.collect()
Fred Drake55cf4342004-02-13 19:21:57 +0000665 class A:
666 pass
Fred Drakebc875f52004-02-04 23:14:14 +0000667
668 def callback(*args):
669 pass
670
Fred Drake55cf4342004-02-13 19:21:57 +0000671 referenced = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000672
Fred Drake55cf4342004-02-13 19:21:57 +0000673 a = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000674 a.a = a
675 a.wr = makeref(referenced)
676
677 try:
678 # now make sure the object and the ref get labeled as
679 # cyclic trash:
Fred Drake55cf4342004-02-13 19:21:57 +0000680 a = A()
681 weakref.ref(referenced, callback)
Fred Drakebc875f52004-02-04 23:14:14 +0000682
683 finally:
684 gc.set_threshold(*thresholds)
685
Brett Cannonf5bee302007-01-23 23:21:22 +0000686 def test_ref_created_during_del(self):
687 # Bug #1377858
688 # A weakref created in an object's __del__() would crash the
689 # interpreter when the weakref was cleaned up since it would refer to
690 # non-existent memory. This test should not segfault the interpreter.
691 class Target(object):
692 def __del__(self):
693 global ref_from_del
694 ref_from_del = weakref.ref(self)
695
696 w = Target()
697
Benjamin Peterson97179b02008-09-09 20:55:01 +0000698 def test_init(self):
699 # Issue 3634
700 # <weakref to class>.__init__() doesn't check errors correctly
701 r = weakref.ref(Exception)
702 self.assertRaises(TypeError, r.__init__, 0, 0, 0, 0, 0)
703 # No exception should be raised here
704 gc.collect()
705
Antoine Pitroua57df2c2010-03-31 21:32:15 +0000706 def test_classes(self):
707 # Check that both old-style classes and new-style classes
708 # are weakrefable.
709 class A(object):
710 pass
711 class B:
712 pass
713 l = []
714 weakref.ref(int)
715 a = weakref.ref(A, l.append)
716 A = None
717 gc.collect()
718 self.assertEqual(a(), None)
719 self.assertEqual(l, [a])
720 b = weakref.ref(B, l.append)
721 B = None
722 gc.collect()
723 self.assertEqual(b(), None)
724 self.assertEqual(l, [a, b])
725
Antoine Pitroub704eab2012-11-11 19:36:51 +0100726 def test_equality(self):
727 # Alive weakrefs defer equality testing to their underlying object.
728 x = Object(1)
729 y = Object(1)
730 z = Object(2)
731 a = weakref.ref(x)
732 b = weakref.ref(y)
733 c = weakref.ref(z)
734 d = weakref.ref(x)
735 # Note how we directly test the operators here, to stress both
736 # __eq__ and __ne__.
737 self.assertTrue(a == b)
738 self.assertFalse(a != b)
739 self.assertFalse(a == c)
740 self.assertTrue(a != c)
741 self.assertTrue(a == d)
742 self.assertFalse(a != d)
743 del x, y, z
744 gc.collect()
745 for r in a, b, c:
746 # Sanity check
747 self.assertIs(r(), None)
748 # Dead weakrefs compare by identity: whether `a` and `d` are the
749 # same weakref object is an implementation detail, since they pointed
750 # to the same original object and didn't have a callback.
751 # (see issue #16453).
752 self.assertFalse(a == b)
753 self.assertTrue(a != b)
754 self.assertFalse(a == c)
755 self.assertTrue(a != c)
756 self.assertEqual(a == d, a is d)
757 self.assertEqual(a != d, a is not d)
758
759 def test_hashing(self):
760 # Alive weakrefs hash the same as the underlying object
761 x = Object(42)
762 y = Object(42)
763 a = weakref.ref(x)
764 b = weakref.ref(y)
765 self.assertEqual(hash(a), hash(42))
766 del x, y
767 gc.collect()
768 # Dead weakrefs:
769 # - retain their hash is they were hashed when alive;
770 # - otherwise, cannot be hashed.
771 self.assertEqual(hash(a), hash(42))
772 self.assertRaises(TypeError, hash, b)
773
Antoine Pitroud38c9902012-12-08 21:15:26 +0100774 def test_trashcan_16602(self):
775 # Issue #16602: when a weakref's target was part of a long
776 # deallocation chain, the trashcan mechanism could delay clearing
777 # of the weakref and make the target object visible from outside
778 # code even though its refcount had dropped to 0. A crash ensued.
779 class C(object):
780 def __init__(self, parent):
781 if not parent:
782 return
783 wself = weakref.ref(self)
784 def cb(wparent):
785 o = wself()
786 self.wparent = weakref.ref(parent, cb)
787
788 d = weakref.WeakKeyDictionary()
789 root = c = C(None)
790 for n in range(100):
791 d[c] = c = C(c)
792 del root
793 gc.collect()
794
Fred Drake0a4dd392004-07-02 18:57:45 +0000795
Amaury Forgeot d'Arca8919fe2008-06-16 19:12:42 +0000796class SubclassableWeakrefTestCase(TestBase):
Fred Drake0a4dd392004-07-02 18:57:45 +0000797
798 def test_subclass_refs(self):
799 class MyRef(weakref.ref):
800 def __init__(self, ob, callback=None, value=42):
801 self.value = value
802 super(MyRef, self).__init__(ob, callback)
803 def __call__(self):
804 self.called = True
805 return super(MyRef, self).__call__()
806 o = Object("foo")
807 mr = MyRef(o, value=24)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200808 self.assertIs(mr(), o)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000809 self.assertTrue(mr.called)
Fred Drake0a4dd392004-07-02 18:57:45 +0000810 self.assertEqual(mr.value, 24)
811 del o
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200812 self.assertIsNone(mr())
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000813 self.assertTrue(mr.called)
Fred Drake0a4dd392004-07-02 18:57:45 +0000814
815 def test_subclass_refs_dont_replace_standard_refs(self):
816 class MyRef(weakref.ref):
817 pass
818 o = Object(42)
819 r1 = MyRef(o)
820 r2 = weakref.ref(o)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200821 self.assertIsNot(r1, r2)
Fred Drake0a4dd392004-07-02 18:57:45 +0000822 self.assertEqual(weakref.getweakrefs(o), [r2, r1])
823 self.assertEqual(weakref.getweakrefcount(o), 2)
824 r3 = MyRef(o)
825 self.assertEqual(weakref.getweakrefcount(o), 3)
826 refs = weakref.getweakrefs(o)
827 self.assertEqual(len(refs), 3)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200828 self.assertIs(r2, refs[0])
Ezio Melottiaa980582010-01-23 23:04:36 +0000829 self.assertIn(r1, refs[1:])
830 self.assertIn(r3, refs[1:])
Fred Drake0a4dd392004-07-02 18:57:45 +0000831
832 def test_subclass_refs_dont_conflate_callbacks(self):
833 class MyRef(weakref.ref):
834 pass
835 o = Object(42)
836 r1 = MyRef(o, id)
837 r2 = MyRef(o, str)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200838 self.assertIsNot(r1, r2)
Fred Drake0a4dd392004-07-02 18:57:45 +0000839 refs = weakref.getweakrefs(o)
Ezio Melottiaa980582010-01-23 23:04:36 +0000840 self.assertIn(r1, refs)
841 self.assertIn(r2, refs)
Fred Drake0a4dd392004-07-02 18:57:45 +0000842
843 def test_subclass_refs_with_slots(self):
844 class MyRef(weakref.ref):
845 __slots__ = "slot1", "slot2"
846 def __new__(type, ob, callback, slot1, slot2):
847 return weakref.ref.__new__(type, ob, callback)
848 def __init__(self, ob, callback, slot1, slot2):
849 self.slot1 = slot1
850 self.slot2 = slot2
851 def meth(self):
852 return self.slot1 + self.slot2
853 o = Object(42)
854 r = MyRef(o, None, "abc", "def")
855 self.assertEqual(r.slot1, "abc")
856 self.assertEqual(r.slot2, "def")
857 self.assertEqual(r.meth(), "abcdef")
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000858 self.assertFalse(hasattr(r, "__dict__"))
Fred Drake0a4dd392004-07-02 18:57:45 +0000859
Amaury Forgeot d'Arca8919fe2008-06-16 19:12:42 +0000860 def test_subclass_refs_with_cycle(self):
861 # Bug #3110
862 # An instance of a weakref subclass can have attributes.
863 # If such a weakref holds the only strong reference to the object,
864 # deleting the weakref will delete the object. In this case,
865 # the callback must not be called, because the ref object is
866 # being deleted.
867 class MyRef(weakref.ref):
868 pass
869
870 # Use a local callback, for "regrtest -R::"
871 # to detect refcounting problems
872 def callback(w):
873 self.cbcalled += 1
874
875 o = C()
876 r1 = MyRef(o, callback)
877 r1.o = o
878 del o
879
880 del r1 # Used to crash here
881
882 self.assertEqual(self.cbcalled, 0)
883
884 # Same test, with two weakrefs to the same object
885 # (since code paths are different)
886 o = C()
887 r1 = MyRef(o, callback)
888 r2 = MyRef(o, callback)
889 r1.r = r2
890 r2.o = o
891 del o
892 del r2
893
894 del r1 # Used to crash here
895
896 self.assertEqual(self.cbcalled, 0)
897
Fred Drake0a4dd392004-07-02 18:57:45 +0000898
Fred Drakeb0fefc52001-03-23 04:22:45 +0000899class MappingTestCase(TestBase):
Martin v. Löwis5e163332001-02-27 18:36:56 +0000900
Fred Drakeb0fefc52001-03-23 04:22:45 +0000901 COUNT = 10
902
Antoine Pitrouc56bca32012-03-01 16:26:35 +0100903 def check_len_cycles(self, dict_type, cons):
904 N = 20
905 items = [RefCycle() for i in range(N)]
906 dct = dict_type(cons(o) for o in items)
907 # Keep an iterator alive
908 it = dct.iteritems()
909 try:
910 next(it)
911 except StopIteration:
912 pass
913 del items
914 gc.collect()
915 n1 = len(dct)
916 del it
917 gc.collect()
918 n2 = len(dct)
919 # one item may be kept alive inside the iterator
920 self.assertIn(n1, (0, 1))
921 self.assertEqual(n2, 0)
922
923 def test_weak_keyed_len_cycles(self):
924 self.check_len_cycles(weakref.WeakKeyDictionary, lambda k: (k, 1))
925
926 def test_weak_valued_len_cycles(self):
927 self.check_len_cycles(weakref.WeakValueDictionary, lambda k: (1, k))
928
929 def check_len_race(self, dict_type, cons):
930 # Extended sanity checks for len() in the face of cyclic collection
931 self.addCleanup(gc.set_threshold, *gc.get_threshold())
932 for th in range(1, 100):
933 N = 20
934 gc.collect(0)
935 gc.set_threshold(th, th, th)
936 items = [RefCycle() for i in range(N)]
937 dct = dict_type(cons(o) for o in items)
938 del items
939 # All items will be collected at next garbage collection pass
940 it = dct.iteritems()
941 try:
942 next(it)
943 except StopIteration:
944 pass
945 n1 = len(dct)
946 del it
947 n2 = len(dct)
948 self.assertGreaterEqual(n1, 0)
949 self.assertLessEqual(n1, N)
950 self.assertGreaterEqual(n2, 0)
951 self.assertLessEqual(n2, n1)
952
953 def test_weak_keyed_len_race(self):
954 self.check_len_race(weakref.WeakKeyDictionary, lambda k: (k, 1))
955
956 def test_weak_valued_len_race(self):
957 self.check_len_race(weakref.WeakValueDictionary, lambda k: (1, k))
958
Fred Drakeb0fefc52001-03-23 04:22:45 +0000959 def test_weak_values(self):
Fred Drake0e540c32001-05-02 05:44:22 +0000960 #
961 # This exercises d.copy(), d.items(), d[], del d[], len(d).
962 #
963 dict, objects = self.make_weak_valued_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +0000964 for o in objects:
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200965 self.assertEqual(weakref.getweakrefcount(o), 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000966 "wrong number of weak references to %r!" % o)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200967 self.assertIs(o, dict[o.arg],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000968 "wrong object returned by weak dict!")
969 items1 = dict.items()
970 items2 = dict.copy().items()
971 items1.sort()
972 items2.sort()
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200973 self.assertEqual(items1, items2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000974 "cloning of weak-valued dictionary did not work!")
975 del items1, items2
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200976 self.assertEqual(len(dict), self.COUNT)
Fred Drakeb0fefc52001-03-23 04:22:45 +0000977 del objects[0]
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200978 self.assertEqual(len(dict), (self.COUNT - 1),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000979 "deleting object did not cause dictionary update")
980 del objects, o
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200981 self.assertEqual(len(dict), 0,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000982 "deleting the values did not clear the dictionary")
Fred Drake4fd06e02001-08-03 04:11:27 +0000983 # regression on SF bug #447152:
984 dict = weakref.WeakValueDictionary()
985 self.assertRaises(KeyError, dict.__getitem__, 1)
986 dict[2] = C()
987 self.assertRaises(KeyError, dict.__getitem__, 2)
Fred Drakeb0fefc52001-03-23 04:22:45 +0000988
989 def test_weak_keys(self):
Fred Drake0e540c32001-05-02 05:44:22 +0000990 #
991 # This exercises d.copy(), d.items(), d[] = v, d[], del d[],
Florent Xicluna07627882010-03-21 01:14:24 +0000992 # len(d), in d.
Fred Drake0e540c32001-05-02 05:44:22 +0000993 #
994 dict, objects = self.make_weak_keyed_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +0000995 for o in objects:
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200996 self.assertEqual(weakref.getweakrefcount(o), 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000997 "wrong number of weak references to %r!" % o)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200998 self.assertIs(o.arg, dict[o],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000999 "wrong object returned by weak dict!")
1000 items1 = dict.items()
1001 items2 = dict.copy().items()
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001002 self.assertEqual(set(items1), set(items2),
Fred Drakeb0fefc52001-03-23 04:22:45 +00001003 "cloning of weak-keyed dictionary did not work!")
1004 del items1, items2
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001005 self.assertEqual(len(dict), self.COUNT)
Fred Drakeb0fefc52001-03-23 04:22:45 +00001006 del objects[0]
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001007 self.assertEqual(len(dict), (self.COUNT - 1),
Fred Drakeb0fefc52001-03-23 04:22:45 +00001008 "deleting object did not cause dictionary update")
1009 del objects, o
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001010 self.assertEqual(len(dict), 0,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001011 "deleting the keys did not clear the dictionary")
Fred Drake752eda42001-11-06 16:38:34 +00001012 o = Object(42)
1013 dict[o] = "What is the meaning of the universe?"
Florent Xicluna07627882010-03-21 01:14:24 +00001014 self.assertIn(o, dict)
1015 self.assertNotIn(34, dict)
Martin v. Löwis5e163332001-02-27 18:36:56 +00001016
Fred Drake0e540c32001-05-02 05:44:22 +00001017 def test_weak_keyed_iters(self):
1018 dict, objects = self.make_weak_keyed_dict()
1019 self.check_iters(dict)
1020
Fred Drake017e68c2006-05-02 06:53:59 +00001021 # Test keyrefs()
1022 refs = dict.keyrefs()
1023 self.assertEqual(len(refs), len(objects))
1024 objects2 = list(objects)
1025 for wr in refs:
1026 ob = wr()
Ezio Melottiaa980582010-01-23 23:04:36 +00001027 self.assertIn(ob, dict)
Fred Drake017e68c2006-05-02 06:53:59 +00001028 self.assertEqual(ob.arg, dict[ob])
1029 objects2.remove(ob)
1030 self.assertEqual(len(objects2), 0)
1031
1032 # Test iterkeyrefs()
1033 objects2 = list(objects)
1034 self.assertEqual(len(list(dict.iterkeyrefs())), len(objects))
1035 for wr in dict.iterkeyrefs():
1036 ob = wr()
Ezio Melottiaa980582010-01-23 23:04:36 +00001037 self.assertIn(ob, dict)
Fred Drake017e68c2006-05-02 06:53:59 +00001038 self.assertEqual(ob.arg, dict[ob])
1039 objects2.remove(ob)
1040 self.assertEqual(len(objects2), 0)
1041
Fred Drake0e540c32001-05-02 05:44:22 +00001042 def test_weak_valued_iters(self):
1043 dict, objects = self.make_weak_valued_dict()
1044 self.check_iters(dict)
1045
Fred Drake017e68c2006-05-02 06:53:59 +00001046 # Test valuerefs()
1047 refs = dict.valuerefs()
1048 self.assertEqual(len(refs), len(objects))
1049 objects2 = list(objects)
1050 for wr in refs:
1051 ob = wr()
1052 self.assertEqual(ob, dict[ob.arg])
1053 self.assertEqual(ob.arg, dict[ob.arg].arg)
1054 objects2.remove(ob)
1055 self.assertEqual(len(objects2), 0)
1056
1057 # Test itervaluerefs()
1058 objects2 = list(objects)
1059 self.assertEqual(len(list(dict.itervaluerefs())), len(objects))
1060 for wr in dict.itervaluerefs():
1061 ob = wr()
1062 self.assertEqual(ob, dict[ob.arg])
1063 self.assertEqual(ob.arg, dict[ob.arg].arg)
1064 objects2.remove(ob)
1065 self.assertEqual(len(objects2), 0)
1066
Fred Drake0e540c32001-05-02 05:44:22 +00001067 def check_iters(self, dict):
1068 # item iterator:
1069 items = dict.items()
1070 for item in dict.iteritems():
1071 items.remove(item)
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001072 self.assertEqual(len(items), 0, "iteritems() did not touch all items")
Fred Drake0e540c32001-05-02 05:44:22 +00001073
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001074 # key iterator, via __iter__():
Fred Drake0e540c32001-05-02 05:44:22 +00001075 keys = dict.keys()
1076 for k in dict:
1077 keys.remove(k)
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001078 self.assertEqual(len(keys), 0, "__iter__() did not touch all keys")
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001079
1080 # key iterator, via iterkeys():
1081 keys = dict.keys()
1082 for k in dict.iterkeys():
1083 keys.remove(k)
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001084 self.assertEqual(len(keys), 0, "iterkeys() did not touch all keys")
Fred Drake0e540c32001-05-02 05:44:22 +00001085
1086 # value iterator:
1087 values = dict.values()
1088 for v in dict.itervalues():
1089 values.remove(v)
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001090 self.assertEqual(len(values), 0,
Fred Drakef425b1e2003-07-14 21:37:17 +00001091 "itervalues() did not touch all values")
Fred Drake0e540c32001-05-02 05:44:22 +00001092
Guido van Rossum009afb72002-06-10 20:00:52 +00001093 def test_make_weak_keyed_dict_from_dict(self):
1094 o = Object(3)
1095 dict = weakref.WeakKeyDictionary({o:364})
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001096 self.assertEqual(dict[o], 364)
Guido van Rossum009afb72002-06-10 20:00:52 +00001097
1098 def test_make_weak_keyed_dict_from_weak_keyed_dict(self):
1099 o = Object(3)
1100 dict = weakref.WeakKeyDictionary({o:364})
1101 dict2 = weakref.WeakKeyDictionary(dict)
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001102 self.assertEqual(dict[o], 364)
Guido van Rossum009afb72002-06-10 20:00:52 +00001103
Fred Drake0e540c32001-05-02 05:44:22 +00001104 def make_weak_keyed_dict(self):
1105 dict = weakref.WeakKeyDictionary()
1106 objects = map(Object, range(self.COUNT))
1107 for o in objects:
1108 dict[o] = o.arg
1109 return dict, objects
1110
1111 def make_weak_valued_dict(self):
1112 dict = weakref.WeakValueDictionary()
1113 objects = map(Object, range(self.COUNT))
1114 for o in objects:
1115 dict[o.arg] = o
1116 return dict, objects
1117
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001118 def check_popitem(self, klass, key1, value1, key2, value2):
1119 weakdict = klass()
1120 weakdict[key1] = value1
1121 weakdict[key2] = value2
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001122 self.assertEqual(len(weakdict), 2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001123 k, v = weakdict.popitem()
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001124 self.assertEqual(len(weakdict), 1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001125 if k is key1:
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001126 self.assertIs(v, value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001127 else:
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001128 self.assertIs(v, value2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001129 k, v = weakdict.popitem()
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001130 self.assertEqual(len(weakdict), 0)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001131 if k is key1:
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001132 self.assertIs(v, value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001133 else:
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001134 self.assertIs(v, value2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001135
1136 def test_weak_valued_dict_popitem(self):
1137 self.check_popitem(weakref.WeakValueDictionary,
1138 "key1", C(), "key2", C())
1139
1140 def test_weak_keyed_dict_popitem(self):
1141 self.check_popitem(weakref.WeakKeyDictionary,
1142 C(), "value 1", C(), "value 2")
1143
1144 def check_setdefault(self, klass, key, value1, value2):
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001145 self.assertIsNot(value1, value2,
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001146 "invalid test"
1147 " -- value parameters must be distinct objects")
1148 weakdict = klass()
1149 o = weakdict.setdefault(key, value1)
Florent Xicluna07627882010-03-21 01:14:24 +00001150 self.assertIs(o, value1)
1151 self.assertIn(key, weakdict)
1152 self.assertIs(weakdict.get(key), value1)
1153 self.assertIs(weakdict[key], value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001154
1155 o = weakdict.setdefault(key, value2)
Florent Xicluna07627882010-03-21 01:14:24 +00001156 self.assertIs(o, value1)
1157 self.assertIn(key, weakdict)
1158 self.assertIs(weakdict.get(key), value1)
1159 self.assertIs(weakdict[key], value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001160
1161 def test_weak_valued_dict_setdefault(self):
1162 self.check_setdefault(weakref.WeakValueDictionary,
1163 "key", C(), C())
1164
1165 def test_weak_keyed_dict_setdefault(self):
1166 self.check_setdefault(weakref.WeakKeyDictionary,
1167 C(), "value 1", "value 2")
1168
Fred Drakea0a4ab12001-04-16 17:37:27 +00001169 def check_update(self, klass, dict):
Fred Drake0e540c32001-05-02 05:44:22 +00001170 #
Florent Xicluna07627882010-03-21 01:14:24 +00001171 # This exercises d.update(), len(d), d.keys(), in d,
Fred Drake0e540c32001-05-02 05:44:22 +00001172 # d.get(), d[].
1173 #
Fred Drakea0a4ab12001-04-16 17:37:27 +00001174 weakdict = klass()
1175 weakdict.update(dict)
Florent Xicluna07627882010-03-21 01:14:24 +00001176 self.assertEqual(len(weakdict), len(dict))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001177 for k in weakdict.keys():
Florent Xicluna07627882010-03-21 01:14:24 +00001178 self.assertIn(k, dict,
Fred Drakea0a4ab12001-04-16 17:37:27 +00001179 "mysterious new key appeared in weak dict")
1180 v = dict.get(k)
Florent Xicluna07627882010-03-21 01:14:24 +00001181 self.assertIs(v, weakdict[k])
1182 self.assertIs(v, weakdict.get(k))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001183 for k in dict.keys():
Florent Xicluna07627882010-03-21 01:14:24 +00001184 self.assertIn(k, weakdict,
Fred Drakea0a4ab12001-04-16 17:37:27 +00001185 "original key disappeared in weak dict")
1186 v = dict[k]
Florent Xicluna07627882010-03-21 01:14:24 +00001187 self.assertIs(v, weakdict[k])
1188 self.assertIs(v, weakdict.get(k))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001189
1190 def test_weak_valued_dict_update(self):
1191 self.check_update(weakref.WeakValueDictionary,
1192 {1: C(), 'a': C(), C(): C()})
1193
1194 def test_weak_keyed_dict_update(self):
1195 self.check_update(weakref.WeakKeyDictionary,
1196 {C(): 1, C(): 2, C(): 3})
1197
Fred Drakeccc75622001-09-06 14:52:39 +00001198 def test_weak_keyed_delitem(self):
1199 d = weakref.WeakKeyDictionary()
1200 o1 = Object('1')
1201 o2 = Object('2')
1202 d[o1] = 'something'
1203 d[o2] = 'something'
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001204 self.assertEqual(len(d), 2)
Fred Drakeccc75622001-09-06 14:52:39 +00001205 del d[o1]
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001206 self.assertEqual(len(d), 1)
1207 self.assertEqual(d.keys(), [o2])
Fred Drakeccc75622001-09-06 14:52:39 +00001208
1209 def test_weak_valued_delitem(self):
1210 d = weakref.WeakValueDictionary()
1211 o1 = Object('1')
1212 o2 = Object('2')
1213 d['something'] = o1
1214 d['something else'] = o2
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001215 self.assertEqual(len(d), 2)
Fred Drakeccc75622001-09-06 14:52:39 +00001216 del d['something']
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001217 self.assertEqual(len(d), 1)
1218 self.assertEqual(d.items(), [('something else', o2)])
Fred Drakeccc75622001-09-06 14:52:39 +00001219
Tim Peters886128f2003-05-25 01:45:11 +00001220 def test_weak_keyed_bad_delitem(self):
1221 d = weakref.WeakKeyDictionary()
1222 o = Object('1')
1223 # An attempt to delete an object that isn't there should raise
Tim Peters50d8b8b2003-05-25 17:44:31 +00001224 # KeyError. It didn't before 2.3.
Tim Peters886128f2003-05-25 01:45:11 +00001225 self.assertRaises(KeyError, d.__delitem__, o)
Tim Peters50d8b8b2003-05-25 17:44:31 +00001226 self.assertRaises(KeyError, d.__getitem__, o)
1227
1228 # If a key isn't of a weakly referencable type, __getitem__ and
1229 # __setitem__ raise TypeError. __delitem__ should too.
1230 self.assertRaises(TypeError, d.__delitem__, 13)
1231 self.assertRaises(TypeError, d.__getitem__, 13)
1232 self.assertRaises(TypeError, d.__setitem__, 13, 13)
Tim Peters886128f2003-05-25 01:45:11 +00001233
1234 def test_weak_keyed_cascading_deletes(self):
1235 # SF bug 742860. For some reason, before 2.3 __delitem__ iterated
1236 # over the keys via self.data.iterkeys(). If things vanished from
1237 # the dict during this (or got added), that caused a RuntimeError.
1238
1239 d = weakref.WeakKeyDictionary()
1240 mutate = False
1241
1242 class C(object):
1243 def __init__(self, i):
1244 self.value = i
1245 def __hash__(self):
1246 return hash(self.value)
1247 def __eq__(self, other):
1248 if mutate:
1249 # Side effect that mutates the dict, by removing the
1250 # last strong reference to a key.
1251 del objs[-1]
1252 return self.value == other.value
1253
1254 objs = [C(i) for i in range(4)]
1255 for o in objs:
1256 d[o] = o.value
1257 del o # now the only strong references to keys are in objs
1258 # Find the order in which iterkeys sees the keys.
1259 objs = d.keys()
1260 # Reverse it, so that the iteration implementation of __delitem__
1261 # has to keep looping to find the first object we delete.
1262 objs.reverse()
Tim Peters50d8b8b2003-05-25 17:44:31 +00001263
Tim Peters886128f2003-05-25 01:45:11 +00001264 # Turn on mutation in C.__eq__. The first time thru the loop,
1265 # under the iterkeys() business the first comparison will delete
1266 # the last item iterkeys() would see, and that causes a
1267 # RuntimeError: dictionary changed size during iteration
1268 # when the iterkeys() loop goes around to try comparing the next
Tim Peters50d8b8b2003-05-25 17:44:31 +00001269 # key. After this was fixed, it just deletes the last object *our*
Tim Peters886128f2003-05-25 01:45:11 +00001270 # "for o in obj" loop would have gotten to.
1271 mutate = True
1272 count = 0
1273 for o in objs:
1274 count += 1
1275 del d[o]
1276 self.assertEqual(len(d), 0)
1277 self.assertEqual(count, 2)
1278
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001279from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001280
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001281class WeakValueDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +00001282 """Check that WeakValueDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001283 __ref = {"key1":Object(1), "key2":Object(2), "key3":Object(3)}
Walter Dörwald118f9312004-06-02 18:42:25 +00001284 type2test = weakref.WeakValueDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001285 def _reference(self):
1286 return self.__ref.copy()
1287
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001288class WeakKeyDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +00001289 """Check that WeakKeyDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001290 __ref = {Object("key1"):1, Object("key2"):2, Object("key3"):3}
Walter Dörwald118f9312004-06-02 18:42:25 +00001291 type2test = weakref.WeakKeyDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001292 def _reference(self):
1293 return self.__ref.copy()
Martin v. Löwis5e163332001-02-27 18:36:56 +00001294
Georg Brandl88659b02008-05-20 08:40:43 +00001295libreftest = """ Doctest for examples in the library reference: weakref.rst
Georg Brandl9a65d582005-07-02 19:07:30 +00001296
1297>>> import weakref
1298>>> class Dict(dict):
1299... pass
1300...
1301>>> obj = Dict(red=1, green=2, blue=3) # this object is weak referencable
1302>>> r = weakref.ref(obj)
Armin Rigoa3f09272006-05-28 19:13:17 +00001303>>> print r() is obj
1304True
Georg Brandl9a65d582005-07-02 19:07:30 +00001305
1306>>> import weakref
1307>>> class Object:
1308... pass
1309...
1310>>> o = Object()
1311>>> r = weakref.ref(o)
1312>>> o2 = r()
1313>>> o is o2
1314True
1315>>> del o, o2
1316>>> print r()
1317None
1318
1319>>> import weakref
1320>>> class ExtendedRef(weakref.ref):
1321... def __init__(self, ob, callback=None, **annotations):
1322... super(ExtendedRef, self).__init__(ob, callback)
1323... self.__counter = 0
1324... for k, v in annotations.iteritems():
1325... setattr(self, k, v)
1326... def __call__(self):
1327... '''Return a pair containing the referent and the number of
1328... times the reference has been called.
1329... '''
1330... ob = super(ExtendedRef, self).__call__()
1331... if ob is not None:
1332... self.__counter += 1
1333... ob = (ob, self.__counter)
1334... return ob
1335...
1336>>> class A: # not in docs from here, just testing the ExtendedRef
1337... pass
1338...
1339>>> a = A()
1340>>> r = ExtendedRef(a, foo=1, bar="baz")
1341>>> r.foo
13421
1343>>> r.bar
1344'baz'
1345>>> r()[1]
13461
1347>>> r()[1]
13482
1349>>> r()[0] is a
1350True
1351
1352
1353>>> import weakref
1354>>> _id2obj_dict = weakref.WeakValueDictionary()
1355>>> def remember(obj):
1356... oid = id(obj)
1357... _id2obj_dict[oid] = obj
1358... return oid
1359...
1360>>> def id2obj(oid):
1361... return _id2obj_dict[oid]
1362...
1363>>> a = A() # from here, just testing
1364>>> a_id = remember(a)
1365>>> id2obj(a_id) is a
1366True
1367>>> del a
1368>>> try:
1369... id2obj(a_id)
1370... except KeyError:
1371... print 'OK'
1372... else:
1373... print 'WeakValueDictionary error'
1374OK
1375
1376"""
1377
1378__test__ = {'libreftest' : libreftest}
1379
Fred Drake2e2be372001-09-20 21:33:42 +00001380def test_main():
Walter Dörwald21d3a322003-05-01 17:45:56 +00001381 test_support.run_unittest(
1382 ReferencesTestCase,
1383 MappingTestCase,
1384 WeakValueDictionaryTestCase,
Fred Drakef425b1e2003-07-14 21:37:17 +00001385 WeakKeyDictionaryTestCase,
Amaury Forgeot d'Arca8919fe2008-06-16 19:12:42 +00001386 SubclassableWeakrefTestCase,
Fred Drakef425b1e2003-07-14 21:37:17 +00001387 )
Georg Brandl9a65d582005-07-02 19:07:30 +00001388 test_support.run_doctest(sys.modules[__name__])
Fred Drake2e2be372001-09-20 21:33:42 +00001389
1390
1391if __name__ == "__main__":
1392 test_main()