blob: 8b5bbc3d360133013b2dedba76bd5658cf01e7b7 [file] [log] [blame]
Fred Drakebc875f52004-02-04 23:14:14 +00001import gc
Fred Drake41deb1e2001-02-01 05:27:45 +00002import sys
Fred Drakeb0fefc52001-03-23 04:22:45 +00003import unittest
Raymond Hettinger53dbe392008-02-12 20:03:09 +00004import collections
Fred Drake41deb1e2001-02-01 05:27:45 +00005import weakref
Georg Brandlb533e262008-05-25 18:19:30 +00006import operator
Antoine Pitrouc1baa602010-01-08 17:54:23 +00007import contextlib
8import copy
Fred Drake41deb1e2001-02-01 05:27:45 +00009
Benjamin Petersonee8712c2008-05-20 21:35:26 +000010from test import support
Fred Drake41deb1e2001-02-01 05:27:45 +000011
Thomas Woutersb2137042007-02-01 18:02:27 +000012# Used in ReferencesTestCase.test_ref_created_during_del() .
13ref_from_del = None
Fred Drake41deb1e2001-02-01 05:27:45 +000014
15class C:
Fred Drakeb0fefc52001-03-23 04:22:45 +000016 def method(self):
17 pass
Fred Drake41deb1e2001-02-01 05:27:45 +000018
19
Fred Drakeb0fefc52001-03-23 04:22:45 +000020class Callable:
21 bar = None
Fred Drake41deb1e2001-02-01 05:27:45 +000022
Fred Drakeb0fefc52001-03-23 04:22:45 +000023 def __call__(self, x):
24 self.bar = x
Fred Drake41deb1e2001-02-01 05:27:45 +000025
26
Fred Drakeb0fefc52001-03-23 04:22:45 +000027def create_function():
28 def f(): pass
29 return f
30
31def create_bound_method():
32 return C().method
33
Fred Drake41deb1e2001-02-01 05:27:45 +000034
Fred Drakeb0fefc52001-03-23 04:22:45 +000035class TestBase(unittest.TestCase):
36
37 def setUp(self):
38 self.cbcalled = 0
39
40 def callback(self, ref):
41 self.cbcalled += 1
Fred Drake41deb1e2001-02-01 05:27:45 +000042
43
Fred Drakeb0fefc52001-03-23 04:22:45 +000044class ReferencesTestCase(TestBase):
Fred Drake41deb1e2001-02-01 05:27:45 +000045
Fred Drakeb0fefc52001-03-23 04:22:45 +000046 def test_basic_ref(self):
47 self.check_basic_ref(C)
48 self.check_basic_ref(create_function)
49 self.check_basic_ref(create_bound_method)
Fred Drake41deb1e2001-02-01 05:27:45 +000050
Fred Drake43735da2002-04-11 03:59:42 +000051 # Just make sure the tp_repr handler doesn't raise an exception.
52 # Live reference:
53 o = C()
54 wr = weakref.ref(o)
Brett Cannon0b70cca2006-08-25 02:59:59 +000055 repr(wr)
Fred Drake43735da2002-04-11 03:59:42 +000056 # Dead reference:
57 del o
Brett Cannon0b70cca2006-08-25 02:59:59 +000058 repr(wr)
Fred Drake43735da2002-04-11 03:59:42 +000059
Fred Drakeb0fefc52001-03-23 04:22:45 +000060 def test_basic_callback(self):
61 self.check_basic_callback(C)
62 self.check_basic_callback(create_function)
63 self.check_basic_callback(create_bound_method)
Fred Drake41deb1e2001-02-01 05:27:45 +000064
Fred Drakeb0fefc52001-03-23 04:22:45 +000065 def test_multiple_callbacks(self):
66 o = C()
67 ref1 = weakref.ref(o, self.callback)
68 ref2 = weakref.ref(o, self.callback)
69 del o
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000070 self.assertTrue(ref1() is None,
Fred Drakeb0fefc52001-03-23 04:22:45 +000071 "expected reference to be invalidated")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000072 self.assertTrue(ref2() is None,
Fred Drakeb0fefc52001-03-23 04:22:45 +000073 "expected reference to be invalidated")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000074 self.assertTrue(self.cbcalled == 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +000075 "callback not called the right number of times")
Fred Drake41deb1e2001-02-01 05:27:45 +000076
Fred Drake705088e2001-04-13 17:18:15 +000077 def test_multiple_selfref_callbacks(self):
Guido van Rossum9eee5542002-08-22 20:21:30 +000078 # Make sure all references are invalidated before callbacks are called
Fred Drake705088e2001-04-13 17:18:15 +000079 #
80 # What's important here is that we're using the first
81 # reference in the callback invoked on the second reference
82 # (the most recently created ref is cleaned up first). This
83 # tests that all references to the object are invalidated
84 # before any of the callbacks are invoked, so that we only
85 # have one invocation of _weakref.c:cleanup_helper() active
86 # for a particular object at a time.
87 #
88 def callback(object, self=self):
89 self.ref()
90 c = C()
91 self.ref = weakref.ref(c, callback)
92 ref1 = weakref.ref(c, callback)
93 del c
94
Fred Drakeb0fefc52001-03-23 04:22:45 +000095 def test_proxy_ref(self):
96 o = C()
97 o.bar = 1
98 ref1 = weakref.proxy(o, self.callback)
99 ref2 = weakref.proxy(o, self.callback)
100 del o
Fred Drake41deb1e2001-02-01 05:27:45 +0000101
Fred Drakeb0fefc52001-03-23 04:22:45 +0000102 def check(proxy):
103 proxy.bar
Fred Drake41deb1e2001-02-01 05:27:45 +0000104
Neal Norwitz2633c692007-02-26 22:22:47 +0000105 self.assertRaises(ReferenceError, check, ref1)
106 self.assertRaises(ReferenceError, check, ref2)
107 self.assertRaises(ReferenceError, bool, weakref.proxy(C()))
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000108 self.assertEqual(self.cbcalled, 2)
Fred Drake41deb1e2001-02-01 05:27:45 +0000109
Fred Drakeb0fefc52001-03-23 04:22:45 +0000110 def check_basic_ref(self, factory):
111 o = factory()
112 ref = weakref.ref(o)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000113 self.assertTrue(ref() is not None,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000114 "weak reference to live object should be live")
115 o2 = ref()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000116 self.assertTrue(o is o2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000117 "<ref>() should return original object if live")
Fred Drake41deb1e2001-02-01 05:27:45 +0000118
Fred Drakeb0fefc52001-03-23 04:22:45 +0000119 def check_basic_callback(self, factory):
120 self.cbcalled = 0
121 o = factory()
122 ref = weakref.ref(o, self.callback)
123 del o
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000124 self.assertTrue(self.cbcalled == 1,
Fred Drake705088e2001-04-13 17:18:15 +0000125 "callback did not properly set 'cbcalled'")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000126 self.assertTrue(ref() is None,
Fred Drake705088e2001-04-13 17:18:15 +0000127 "ref2 should be dead after deleting object reference")
Fred Drake41deb1e2001-02-01 05:27:45 +0000128
Fred Drakeb0fefc52001-03-23 04:22:45 +0000129 def test_ref_reuse(self):
130 o = C()
131 ref1 = weakref.ref(o)
132 # create a proxy to make sure that there's an intervening creation
133 # between these two; it should make no difference
134 proxy = weakref.proxy(o)
135 ref2 = weakref.ref(o)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000136 self.assertTrue(ref1 is ref2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000137 "reference object w/out callback should be re-used")
Fred Drake41deb1e2001-02-01 05:27:45 +0000138
Fred Drakeb0fefc52001-03-23 04:22:45 +0000139 o = C()
140 proxy = weakref.proxy(o)
141 ref1 = weakref.ref(o)
142 ref2 = weakref.ref(o)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000143 self.assertTrue(ref1 is ref2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000144 "reference object w/out callback should be re-used")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000145 self.assertTrue(weakref.getweakrefcount(o) == 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000146 "wrong weak ref count for object")
147 del proxy
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000148 self.assertTrue(weakref.getweakrefcount(o) == 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000149 "wrong weak ref count for object after deleting proxy")
Fred Drake41deb1e2001-02-01 05:27:45 +0000150
Fred Drakeb0fefc52001-03-23 04:22:45 +0000151 def test_proxy_reuse(self):
152 o = C()
153 proxy1 = weakref.proxy(o)
154 ref = weakref.ref(o)
155 proxy2 = weakref.proxy(o)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000156 self.assertTrue(proxy1 is proxy2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000157 "proxy object w/out callback should have been re-used")
158
159 def test_basic_proxy(self):
160 o = C()
161 self.check_proxy(o, weakref.proxy(o))
162
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000163 L = collections.UserList()
Fred Drake5935ff02001-12-19 16:54:23 +0000164 p = weakref.proxy(L)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000165 self.assertFalse(p, "proxy for empty UserList should be false")
Fred Drake5935ff02001-12-19 16:54:23 +0000166 p.append(12)
167 self.assertEqual(len(L), 1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000168 self.assertTrue(p, "proxy for non-empty UserList should be true")
Fred Drake5935ff02001-12-19 16:54:23 +0000169 p[:] = [2, 3]
170 self.assertEqual(len(L), 2)
171 self.assertEqual(len(p), 2)
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000172 self.assertIn(3, p, "proxy didn't support __contains__() properly")
Fred Drake5935ff02001-12-19 16:54:23 +0000173 p[1] = 5
174 self.assertEqual(L[1], 5)
175 self.assertEqual(p[1], 5)
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000176 L2 = collections.UserList(L)
Fred Drake5935ff02001-12-19 16:54:23 +0000177 p2 = weakref.proxy(L2)
178 self.assertEqual(p, p2)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000179 ## self.assertEqual(repr(L2), repr(p2))
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000180 L3 = collections.UserList(range(10))
Fred Drake43735da2002-04-11 03:59:42 +0000181 p3 = weakref.proxy(L3)
182 self.assertEqual(L3[:], p3[:])
183 self.assertEqual(L3[5:], p3[5:])
184 self.assertEqual(L3[:5], p3[:5])
185 self.assertEqual(L3[2:5], p3[2:5])
Fred Drake5935ff02001-12-19 16:54:23 +0000186
Benjamin Peterson32019772009-11-19 03:08:32 +0000187 def test_proxy_unicode(self):
188 # See bug 5037
189 class C(object):
190 def __str__(self):
191 return "string"
192 def __bytes__(self):
193 return b"bytes"
194 instance = C()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000195 self.assertIn("__bytes__", dir(weakref.proxy(instance)))
Benjamin Peterson32019772009-11-19 03:08:32 +0000196 self.assertEqual(bytes(weakref.proxy(instance)), b"bytes")
197
Georg Brandlb533e262008-05-25 18:19:30 +0000198 def test_proxy_index(self):
199 class C:
200 def __index__(self):
201 return 10
202 o = C()
203 p = weakref.proxy(o)
204 self.assertEqual(operator.index(p), 10)
205
206 def test_proxy_div(self):
207 class C:
208 def __floordiv__(self, other):
209 return 42
210 def __ifloordiv__(self, other):
211 return 21
212 o = C()
213 p = weakref.proxy(o)
214 self.assertEqual(p // 5, 42)
215 p //= 5
216 self.assertEqual(p, 21)
217
Fred Drakeea2adc92004-02-03 19:56:46 +0000218 # The PyWeakref_* C API is documented as allowing either NULL or
219 # None as the value for the callback, where either means "no
220 # callback". The "no callback" ref and proxy objects are supposed
221 # to be shared so long as they exist by all callers so long as
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000222 # they are active. In Python 2.3.3 and earlier, this guarantee
Fred Drakeea2adc92004-02-03 19:56:46 +0000223 # was not honored, and was broken in different ways for
224 # PyWeakref_NewRef() and PyWeakref_NewProxy(). (Two tests.)
225
226 def test_shared_ref_without_callback(self):
227 self.check_shared_without_callback(weakref.ref)
228
229 def test_shared_proxy_without_callback(self):
230 self.check_shared_without_callback(weakref.proxy)
231
232 def check_shared_without_callback(self, makeref):
233 o = Object(1)
234 p1 = makeref(o, None)
235 p2 = makeref(o, None)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000236 self.assertTrue(p1 is p2, "both callbacks were None in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000237 del p1, p2
238 p1 = makeref(o)
239 p2 = makeref(o, None)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000240 self.assertTrue(p1 is p2, "callbacks were NULL, None in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000241 del p1, p2
242 p1 = makeref(o)
243 p2 = makeref(o)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000244 self.assertTrue(p1 is p2, "both callbacks were NULL in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000245 del p1, p2
246 p1 = makeref(o, None)
247 p2 = makeref(o)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000248 self.assertTrue(p1 is p2, "callbacks were None, NULL in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000249
Fred Drakeb0fefc52001-03-23 04:22:45 +0000250 def test_callable_proxy(self):
251 o = Callable()
252 ref1 = weakref.proxy(o)
253
254 self.check_proxy(o, ref1)
255
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000256 self.assertTrue(type(ref1) is weakref.CallableProxyType,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000257 "proxy is not of callable type")
258 ref1('twinkies!')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000259 self.assertTrue(o.bar == 'twinkies!',
Fred Drakeb0fefc52001-03-23 04:22:45 +0000260 "call through proxy not passed through to original")
Fred Drake3bb4d212001-10-18 19:28:29 +0000261 ref1(x='Splat.')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000262 self.assertTrue(o.bar == 'Splat.',
Fred Drake3bb4d212001-10-18 19:28:29 +0000263 "call through proxy not passed through to original")
Fred Drakeb0fefc52001-03-23 04:22:45 +0000264
265 # expect due to too few args
266 self.assertRaises(TypeError, ref1)
267
268 # expect due to too many args
269 self.assertRaises(TypeError, ref1, 1, 2, 3)
270
271 def check_proxy(self, o, proxy):
272 o.foo = 1
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000273 self.assertTrue(proxy.foo == 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000274 "proxy does not reflect attribute addition")
275 o.foo = 2
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000276 self.assertTrue(proxy.foo == 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000277 "proxy does not reflect attribute modification")
278 del o.foo
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000279 self.assertTrue(not hasattr(proxy, 'foo'),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000280 "proxy does not reflect attribute removal")
281
282 proxy.foo = 1
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000283 self.assertTrue(o.foo == 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000284 "object does not reflect attribute addition via proxy")
285 proxy.foo = 2
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000286 self.assertTrue(
Fred Drakeb0fefc52001-03-23 04:22:45 +0000287 o.foo == 2,
288 "object does not reflect attribute modification via proxy")
289 del proxy.foo
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000290 self.assertTrue(not hasattr(o, 'foo'),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000291 "object does not reflect attribute removal via proxy")
292
Raymond Hettingerd693a812003-06-30 04:18:48 +0000293 def test_proxy_deletion(self):
294 # Test clearing of SF bug #762891
295 class Foo:
296 result = None
297 def __delitem__(self, accessor):
298 self.result = accessor
299 g = Foo()
300 f = weakref.proxy(g)
301 del f[0]
302 self.assertEqual(f.result, 0)
303
Raymond Hettingere6c470f2005-03-27 03:04:54 +0000304 def test_proxy_bool(self):
305 # Test clearing of SF bug #1170766
306 class List(list): pass
307 lyst = List()
308 self.assertEqual(bool(weakref.proxy(lyst)), bool(lyst))
309
Fred Drakeb0fefc52001-03-23 04:22:45 +0000310 def test_getweakrefcount(self):
311 o = C()
312 ref1 = weakref.ref(o)
313 ref2 = weakref.ref(o, self.callback)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000314 self.assertTrue(weakref.getweakrefcount(o) == 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000315 "got wrong number of weak reference objects")
316
317 proxy1 = weakref.proxy(o)
318 proxy2 = weakref.proxy(o, self.callback)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000319 self.assertTrue(weakref.getweakrefcount(o) == 4,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000320 "got wrong number of weak reference objects")
321
Fred Drakeea2adc92004-02-03 19:56:46 +0000322 del ref1, ref2, proxy1, proxy2
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000323 self.assertTrue(weakref.getweakrefcount(o) == 0,
Fred Drakeea2adc92004-02-03 19:56:46 +0000324 "weak reference objects not unlinked from"
325 " referent when discarded.")
326
Walter Dörwaldb167b042003-12-11 12:34:05 +0000327 # assumes ints do not support weakrefs
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000328 self.assertTrue(weakref.getweakrefcount(1) == 0,
Walter Dörwaldb167b042003-12-11 12:34:05 +0000329 "got wrong number of weak reference objects for int")
330
Fred Drakeb0fefc52001-03-23 04:22:45 +0000331 def test_getweakrefs(self):
332 o = C()
333 ref1 = weakref.ref(o, self.callback)
334 ref2 = weakref.ref(o, self.callback)
335 del ref1
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000336 self.assertTrue(weakref.getweakrefs(o) == [ref2],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000337 "list of refs does not match")
338
339 o = C()
340 ref1 = weakref.ref(o, self.callback)
341 ref2 = weakref.ref(o, self.callback)
342 del ref2
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000343 self.assertTrue(weakref.getweakrefs(o) == [ref1],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000344 "list of refs does not match")
345
Fred Drakeea2adc92004-02-03 19:56:46 +0000346 del ref1
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000347 self.assertTrue(weakref.getweakrefs(o) == [],
Fred Drakeea2adc92004-02-03 19:56:46 +0000348 "list of refs not cleared")
349
Walter Dörwaldb167b042003-12-11 12:34:05 +0000350 # assumes ints do not support weakrefs
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000351 self.assertTrue(weakref.getweakrefs(1) == [],
Walter Dörwaldb167b042003-12-11 12:34:05 +0000352 "list of refs does not match for int")
353
Fred Drake39c27f12001-10-18 18:06:05 +0000354 def test_newstyle_number_ops(self):
355 class F(float):
356 pass
357 f = F(2.0)
358 p = weakref.proxy(f)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000359 self.assertTrue(p + 1.0 == 3.0)
360 self.assertTrue(1.0 + p == 3.0) # this used to SEGV
Fred Drake39c27f12001-10-18 18:06:05 +0000361
Fred Drake2a64f462001-12-10 23:46:02 +0000362 def test_callbacks_protected(self):
Guido van Rossum9eee5542002-08-22 20:21:30 +0000363 # Callbacks protected from already-set exceptions?
Fred Drake2a64f462001-12-10 23:46:02 +0000364 # Regression test for SF bug #478534.
365 class BogusError(Exception):
366 pass
367 data = {}
368 def remove(k):
369 del data[k]
370 def encapsulate():
371 f = lambda : ()
372 data[weakref.ref(f, remove)] = None
373 raise BogusError
374 try:
375 encapsulate()
376 except BogusError:
377 pass
378 else:
379 self.fail("exception not properly restored")
380 try:
381 encapsulate()
382 except BogusError:
383 pass
384 else:
385 self.fail("exception not properly restored")
386
Tim Petersadd09b42003-11-12 20:43:28 +0000387 def test_sf_bug_840829(self):
388 # "weakref callbacks and gc corrupt memory"
389 # subtype_dealloc erroneously exposed a new-style instance
390 # already in the process of getting deallocated to gc,
391 # causing double-deallocation if the instance had a weakref
392 # callback that triggered gc.
393 # If the bug exists, there probably won't be an obvious symptom
394 # in a release build. In a debug build, a segfault will occur
395 # when the second attempt to remove the instance from the "list
396 # of all objects" occurs.
397
398 import gc
399
400 class C(object):
401 pass
402
403 c = C()
404 wr = weakref.ref(c, lambda ignore: gc.collect())
405 del c
406
Tim Petersf7f9e992003-11-13 21:59:32 +0000407 # There endeth the first part. It gets worse.
408 del wr
409
410 c1 = C()
411 c1.i = C()
412 wr = weakref.ref(c1.i, lambda ignore: gc.collect())
413
414 c2 = C()
415 c2.c1 = c1
416 del c1 # still alive because c2 points to it
417
418 # Now when subtype_dealloc gets called on c2, it's not enough just
419 # that c2 is immune from gc while the weakref callbacks associated
420 # with c2 execute (there are none in this 2nd half of the test, btw).
421 # subtype_dealloc goes on to call the base classes' deallocs too,
422 # so any gc triggered by weakref callbacks associated with anything
423 # torn down by a base class dealloc can also trigger double
424 # deallocation of c2.
425 del c2
Fred Drake41deb1e2001-02-01 05:27:45 +0000426
Tim Peters403a2032003-11-20 21:21:46 +0000427 def test_callback_in_cycle_1(self):
428 import gc
429
430 class J(object):
431 pass
432
433 class II(object):
434 def acallback(self, ignore):
435 self.J
436
437 I = II()
438 I.J = J
439 I.wr = weakref.ref(J, I.acallback)
440
441 # Now J and II are each in a self-cycle (as all new-style class
442 # objects are, since their __mro__ points back to them). I holds
443 # both a weak reference (I.wr) and a strong reference (I.J) to class
444 # J. I is also in a cycle (I.wr points to a weakref that references
445 # I.acallback). When we del these three, they all become trash, but
446 # the cycles prevent any of them from getting cleaned up immediately.
447 # Instead they have to wait for cyclic gc to deduce that they're
448 # trash.
449 #
450 # gc used to call tp_clear on all of them, and the order in which
451 # it does that is pretty accidental. The exact order in which we
452 # built up these things manages to provoke gc into running tp_clear
453 # in just the right order (I last). Calling tp_clear on II leaves
454 # behind an insane class object (its __mro__ becomes NULL). Calling
455 # tp_clear on J breaks its self-cycle, but J doesn't get deleted
456 # just then because of the strong reference from I.J. Calling
457 # tp_clear on I starts to clear I's __dict__, and just happens to
458 # clear I.J first -- I.wr is still intact. That removes the last
459 # reference to J, which triggers the weakref callback. The callback
460 # tries to do "self.J", and instances of new-style classes look up
461 # attributes ("J") in the class dict first. The class (II) wants to
462 # search II.__mro__, but that's NULL. The result was a segfault in
463 # a release build, and an assert failure in a debug build.
464 del I, J, II
465 gc.collect()
466
467 def test_callback_in_cycle_2(self):
468 import gc
469
470 # This is just like test_callback_in_cycle_1, except that II is an
471 # old-style class. The symptom is different then: an instance of an
472 # old-style class looks in its own __dict__ first. 'J' happens to
473 # get cleared from I.__dict__ before 'wr', and 'J' was never in II's
474 # __dict__, so the attribute isn't found. The difference is that
475 # the old-style II doesn't have a NULL __mro__ (it doesn't have any
476 # __mro__), so no segfault occurs. Instead it got:
477 # test_callback_in_cycle_2 (__main__.ReferencesTestCase) ...
478 # Exception exceptions.AttributeError:
479 # "II instance has no attribute 'J'" in <bound method II.acallback
480 # of <?.II instance at 0x00B9B4B8>> ignored
481
482 class J(object):
483 pass
484
485 class II:
486 def acallback(self, ignore):
487 self.J
488
489 I = II()
490 I.J = J
491 I.wr = weakref.ref(J, I.acallback)
492
493 del I, J, II
494 gc.collect()
495
496 def test_callback_in_cycle_3(self):
497 import gc
498
499 # This one broke the first patch that fixed the last two. In this
500 # case, the objects reachable from the callback aren't also reachable
501 # from the object (c1) *triggering* the callback: you can get to
502 # c1 from c2, but not vice-versa. The result was that c2's __dict__
503 # got tp_clear'ed by the time the c2.cb callback got invoked.
504
505 class C:
506 def cb(self, ignore):
507 self.me
508 self.c1
509 self.wr
510
511 c1, c2 = C(), C()
512
513 c2.me = c2
514 c2.c1 = c1
515 c2.wr = weakref.ref(c1, c2.cb)
516
517 del c1, c2
518 gc.collect()
519
520 def test_callback_in_cycle_4(self):
521 import gc
522
523 # Like test_callback_in_cycle_3, except c2 and c1 have different
524 # classes. c2's class (C) isn't reachable from c1 then, so protecting
525 # objects reachable from the dying object (c1) isn't enough to stop
526 # c2's class (C) from getting tp_clear'ed before c2.cb is invoked.
527 # The result was a segfault (C.__mro__ was NULL when the callback
528 # tried to look up self.me).
529
530 class C(object):
531 def cb(self, ignore):
532 self.me
533 self.c1
534 self.wr
535
536 class D:
537 pass
538
539 c1, c2 = D(), C()
540
541 c2.me = c2
542 c2.c1 = c1
543 c2.wr = weakref.ref(c1, c2.cb)
544
545 del c1, c2, C, D
546 gc.collect()
547
548 def test_callback_in_cycle_resurrection(self):
549 import gc
550
551 # Do something nasty in a weakref callback: resurrect objects
552 # from dead cycles. For this to be attempted, the weakref and
553 # its callback must also be part of the cyclic trash (else the
554 # objects reachable via the callback couldn't be in cyclic trash
555 # to begin with -- the callback would act like an external root).
556 # But gc clears trash weakrefs with callbacks early now, which
557 # disables the callbacks, so the callbacks shouldn't get called
558 # at all (and so nothing actually gets resurrected).
559
560 alist = []
561 class C(object):
562 def __init__(self, value):
563 self.attribute = value
564
565 def acallback(self, ignore):
566 alist.append(self.c)
567
568 c1, c2 = C(1), C(2)
569 c1.c = c2
570 c2.c = c1
571 c1.wr = weakref.ref(c2, c1.acallback)
572 c2.wr = weakref.ref(c1, c2.acallback)
573
574 def C_went_away(ignore):
575 alist.append("C went away")
576 wr = weakref.ref(C, C_went_away)
577
578 del c1, c2, C # make them all trash
579 self.assertEqual(alist, []) # del isn't enough to reclaim anything
580
581 gc.collect()
582 # c1.wr and c2.wr were part of the cyclic trash, so should have
583 # been cleared without their callbacks executing. OTOH, the weakref
584 # to C is bound to a function local (wr), and wasn't trash, so that
585 # callback should have been invoked when C went away.
586 self.assertEqual(alist, ["C went away"])
587 # The remaining weakref should be dead now (its callback ran).
588 self.assertEqual(wr(), None)
589
590 del alist[:]
591 gc.collect()
592 self.assertEqual(alist, [])
593
594 def test_callbacks_on_callback(self):
595 import gc
596
597 # Set up weakref callbacks *on* weakref callbacks.
598 alist = []
599 def safe_callback(ignore):
600 alist.append("safe_callback called")
601
602 class C(object):
603 def cb(self, ignore):
604 alist.append("cb called")
605
606 c, d = C(), C()
607 c.other = d
608 d.other = c
609 callback = c.cb
610 c.wr = weakref.ref(d, callback) # this won't trigger
611 d.wr = weakref.ref(callback, d.cb) # ditto
612 external_wr = weakref.ref(callback, safe_callback) # but this will
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000613 self.assertTrue(external_wr() is callback)
Tim Peters403a2032003-11-20 21:21:46 +0000614
615 # The weakrefs attached to c and d should get cleared, so that
616 # C.cb is never called. But external_wr isn't part of the cyclic
617 # trash, and no cyclic trash is reachable from it, so safe_callback
618 # should get invoked when the bound method object callback (c.cb)
619 # -- which is itself a callback, and also part of the cyclic trash --
620 # gets reclaimed at the end of gc.
621
622 del callback, c, d, C
623 self.assertEqual(alist, []) # del isn't enough to clean up cycles
624 gc.collect()
625 self.assertEqual(alist, ["safe_callback called"])
626 self.assertEqual(external_wr(), None)
627
628 del alist[:]
629 gc.collect()
630 self.assertEqual(alist, [])
631
Fred Drakebc875f52004-02-04 23:14:14 +0000632 def test_gc_during_ref_creation(self):
633 self.check_gc_during_creation(weakref.ref)
634
635 def test_gc_during_proxy_creation(self):
636 self.check_gc_during_creation(weakref.proxy)
637
638 def check_gc_during_creation(self, makeref):
639 thresholds = gc.get_threshold()
640 gc.set_threshold(1, 1, 1)
641 gc.collect()
Fred Drake55cf4342004-02-13 19:21:57 +0000642 class A:
643 pass
Fred Drakebc875f52004-02-04 23:14:14 +0000644
645 def callback(*args):
646 pass
647
Fred Drake55cf4342004-02-13 19:21:57 +0000648 referenced = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000649
Fred Drake55cf4342004-02-13 19:21:57 +0000650 a = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000651 a.a = a
652 a.wr = makeref(referenced)
653
654 try:
655 # now make sure the object and the ref get labeled as
656 # cyclic trash:
Fred Drake55cf4342004-02-13 19:21:57 +0000657 a = A()
658 weakref.ref(referenced, callback)
Fred Drakebc875f52004-02-04 23:14:14 +0000659
660 finally:
661 gc.set_threshold(*thresholds)
662
Thomas Woutersb2137042007-02-01 18:02:27 +0000663 def test_ref_created_during_del(self):
664 # Bug #1377858
665 # A weakref created in an object's __del__() would crash the
666 # interpreter when the weakref was cleaned up since it would refer to
667 # non-existent memory. This test should not segfault the interpreter.
668 class Target(object):
669 def __del__(self):
670 global ref_from_del
671 ref_from_del = weakref.ref(self)
672
673 w = Target()
674
Benjamin Peterson9aa42992008-09-10 21:57:34 +0000675 def test_init(self):
676 # Issue 3634
677 # <weakref to class>.__init__() doesn't check errors correctly
678 r = weakref.ref(Exception)
679 self.assertRaises(TypeError, r.__init__, 0, 0, 0, 0, 0)
680 # No exception should be raised here
681 gc.collect()
682
Antoine Pitrou3af01a12010-03-31 21:40:47 +0000683 def test_classes(self):
684 # Check that classes are weakrefable.
685 class A(object):
686 pass
687 l = []
688 weakref.ref(int)
689 a = weakref.ref(A, l.append)
690 A = None
691 gc.collect()
692 self.assertEqual(a(), None)
693 self.assertEqual(l, [a])
694
Fred Drake0a4dd392004-07-02 18:57:45 +0000695
Amaury Forgeot d'Arcc856c7a2008-06-16 19:50:09 +0000696class SubclassableWeakrefTestCase(TestBase):
Fred Drake0a4dd392004-07-02 18:57:45 +0000697
698 def test_subclass_refs(self):
699 class MyRef(weakref.ref):
700 def __init__(self, ob, callback=None, value=42):
701 self.value = value
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000702 super().__init__(ob, callback)
Fred Drake0a4dd392004-07-02 18:57:45 +0000703 def __call__(self):
704 self.called = True
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000705 return super().__call__()
Fred Drake0a4dd392004-07-02 18:57:45 +0000706 o = Object("foo")
707 mr = MyRef(o, value=24)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000708 self.assertTrue(mr() is o)
709 self.assertTrue(mr.called)
Fred Drake0a4dd392004-07-02 18:57:45 +0000710 self.assertEqual(mr.value, 24)
711 del o
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000712 self.assertTrue(mr() is None)
713 self.assertTrue(mr.called)
Fred Drake0a4dd392004-07-02 18:57:45 +0000714
715 def test_subclass_refs_dont_replace_standard_refs(self):
716 class MyRef(weakref.ref):
717 pass
718 o = Object(42)
719 r1 = MyRef(o)
720 r2 = weakref.ref(o)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000721 self.assertTrue(r1 is not r2)
Fred Drake0a4dd392004-07-02 18:57:45 +0000722 self.assertEqual(weakref.getweakrefs(o), [r2, r1])
723 self.assertEqual(weakref.getweakrefcount(o), 2)
724 r3 = MyRef(o)
725 self.assertEqual(weakref.getweakrefcount(o), 3)
726 refs = weakref.getweakrefs(o)
727 self.assertEqual(len(refs), 3)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000728 self.assertTrue(r2 is refs[0])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000729 self.assertIn(r1, refs[1:])
730 self.assertIn(r3, refs[1:])
Fred Drake0a4dd392004-07-02 18:57:45 +0000731
732 def test_subclass_refs_dont_conflate_callbacks(self):
733 class MyRef(weakref.ref):
734 pass
735 o = Object(42)
736 r1 = MyRef(o, id)
737 r2 = MyRef(o, str)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000738 self.assertTrue(r1 is not r2)
Fred Drake0a4dd392004-07-02 18:57:45 +0000739 refs = weakref.getweakrefs(o)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000740 self.assertIn(r1, refs)
741 self.assertIn(r2, refs)
Fred Drake0a4dd392004-07-02 18:57:45 +0000742
743 def test_subclass_refs_with_slots(self):
744 class MyRef(weakref.ref):
745 __slots__ = "slot1", "slot2"
746 def __new__(type, ob, callback, slot1, slot2):
747 return weakref.ref.__new__(type, ob, callback)
748 def __init__(self, ob, callback, slot1, slot2):
749 self.slot1 = slot1
750 self.slot2 = slot2
751 def meth(self):
752 return self.slot1 + self.slot2
753 o = Object(42)
754 r = MyRef(o, None, "abc", "def")
755 self.assertEqual(r.slot1, "abc")
756 self.assertEqual(r.slot2, "def")
757 self.assertEqual(r.meth(), "abcdef")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000758 self.assertFalse(hasattr(r, "__dict__"))
Fred Drake0a4dd392004-07-02 18:57:45 +0000759
Amaury Forgeot d'Arcc856c7a2008-06-16 19:50:09 +0000760 def test_subclass_refs_with_cycle(self):
761 # Bug #3110
762 # An instance of a weakref subclass can have attributes.
763 # If such a weakref holds the only strong reference to the object,
764 # deleting the weakref will delete the object. In this case,
765 # the callback must not be called, because the ref object is
766 # being deleted.
767 class MyRef(weakref.ref):
768 pass
769
770 # Use a local callback, for "regrtest -R::"
771 # to detect refcounting problems
772 def callback(w):
773 self.cbcalled += 1
774
775 o = C()
776 r1 = MyRef(o, callback)
777 r1.o = o
778 del o
779
780 del r1 # Used to crash here
781
782 self.assertEqual(self.cbcalled, 0)
783
784 # Same test, with two weakrefs to the same object
785 # (since code paths are different)
786 o = C()
787 r1 = MyRef(o, callback)
788 r2 = MyRef(o, callback)
789 r1.r = r2
790 r2.o = o
791 del o
792 del r2
793
794 del r1 # Used to crash here
795
796 self.assertEqual(self.cbcalled, 0)
797
Fred Drake0a4dd392004-07-02 18:57:45 +0000798
Fred Drake41deb1e2001-02-01 05:27:45 +0000799class Object:
800 def __init__(self, arg):
801 self.arg = arg
802 def __repr__(self):
803 return "<Object %r>" % self.arg
Antoine Pitrouc1baa602010-01-08 17:54:23 +0000804 def __eq__(self, other):
805 if isinstance(other, Object):
806 return self.arg == other.arg
807 return NotImplemented
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000808 def __lt__(self, other):
809 if isinstance(other, Object):
810 return self.arg < other.arg
811 return NotImplemented
812 def __hash__(self):
813 return hash(self.arg)
Fred Drake41deb1e2001-02-01 05:27:45 +0000814
Fred Drake41deb1e2001-02-01 05:27:45 +0000815
Fred Drakeb0fefc52001-03-23 04:22:45 +0000816class MappingTestCase(TestBase):
Martin v. Löwis5e163332001-02-27 18:36:56 +0000817
Fred Drakeb0fefc52001-03-23 04:22:45 +0000818 COUNT = 10
819
820 def test_weak_values(self):
Fred Drake0e540c32001-05-02 05:44:22 +0000821 #
822 # This exercises d.copy(), d.items(), d[], del d[], len(d).
823 #
824 dict, objects = self.make_weak_valued_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +0000825 for o in objects:
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000826 self.assertEqual(weakref.getweakrefcount(o), 1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000827 self.assertTrue(o is dict[o.arg],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000828 "wrong object returned by weak dict!")
Barry Warsawecaab832008-09-04 01:42:51 +0000829 items1 = list(dict.items())
830 items2 = list(dict.copy().items())
Fred Drakeb0fefc52001-03-23 04:22:45 +0000831 items1.sort()
832 items2.sort()
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000833 self.assertEqual(items1, items2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000834 "cloning of weak-valued dictionary did not work!")
835 del items1, items2
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000836 self.assertEqual(len(dict), self.COUNT)
Fred Drakeb0fefc52001-03-23 04:22:45 +0000837 del objects[0]
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000838 self.assertEqual(len(dict), self.COUNT - 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000839 "deleting object did not cause dictionary update")
840 del objects, o
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000841 self.assertEqual(len(dict), 0,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000842 "deleting the values did not clear the dictionary")
Fred Drake4fd06e02001-08-03 04:11:27 +0000843 # regression on SF bug #447152:
844 dict = weakref.WeakValueDictionary()
845 self.assertRaises(KeyError, dict.__getitem__, 1)
846 dict[2] = C()
847 self.assertRaises(KeyError, dict.__getitem__, 2)
Fred Drakeb0fefc52001-03-23 04:22:45 +0000848
849 def test_weak_keys(self):
Fred Drake0e540c32001-05-02 05:44:22 +0000850 #
851 # This exercises d.copy(), d.items(), d[] = v, d[], del d[],
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000852 # len(d), k in d.
Fred Drake0e540c32001-05-02 05:44:22 +0000853 #
854 dict, objects = self.make_weak_keyed_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +0000855 for o in objects:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000856 self.assertTrue(weakref.getweakrefcount(o) == 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000857 "wrong number of weak references to %r!" % o)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000858 self.assertTrue(o.arg is dict[o],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000859 "wrong object returned by weak dict!")
860 items1 = dict.items()
861 items2 = dict.copy().items()
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000862 self.assertEqual(set(items1), set(items2),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000863 "cloning of weak-keyed dictionary did not work!")
864 del items1, items2
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000865 self.assertEqual(len(dict), self.COUNT)
Fred Drakeb0fefc52001-03-23 04:22:45 +0000866 del objects[0]
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000867 self.assertTrue(len(dict) == (self.COUNT - 1),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000868 "deleting object did not cause dictionary update")
869 del objects, o
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000870 self.assertTrue(len(dict) == 0,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000871 "deleting the keys did not clear the dictionary")
Fred Drake752eda42001-11-06 16:38:34 +0000872 o = Object(42)
873 dict[o] = "What is the meaning of the universe?"
Benjamin Peterson577473f2010-01-19 00:09:57 +0000874 self.assertIn(o, dict)
875 self.assertNotIn(34, dict)
Martin v. Löwis5e163332001-02-27 18:36:56 +0000876
Fred Drake0e540c32001-05-02 05:44:22 +0000877 def test_weak_keyed_iters(self):
878 dict, objects = self.make_weak_keyed_dict()
879 self.check_iters(dict)
880
Thomas Wouters477c8d52006-05-27 19:21:47 +0000881 # Test keyrefs()
882 refs = dict.keyrefs()
883 self.assertEqual(len(refs), len(objects))
884 objects2 = list(objects)
885 for wr in refs:
886 ob = wr()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000887 self.assertIn(ob, dict)
888 self.assertIn(ob, dict)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000889 self.assertEqual(ob.arg, dict[ob])
890 objects2.remove(ob)
891 self.assertEqual(len(objects2), 0)
892
893 # Test iterkeyrefs()
894 objects2 = list(objects)
Barry Warsawecaab832008-09-04 01:42:51 +0000895 self.assertEqual(len(list(dict.keyrefs())), len(objects))
896 for wr in dict.keyrefs():
Thomas Wouters477c8d52006-05-27 19:21:47 +0000897 ob = wr()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000898 self.assertIn(ob, dict)
899 self.assertIn(ob, dict)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000900 self.assertEqual(ob.arg, dict[ob])
901 objects2.remove(ob)
902 self.assertEqual(len(objects2), 0)
903
Fred Drake0e540c32001-05-02 05:44:22 +0000904 def test_weak_valued_iters(self):
905 dict, objects = self.make_weak_valued_dict()
906 self.check_iters(dict)
907
Thomas Wouters477c8d52006-05-27 19:21:47 +0000908 # Test valuerefs()
909 refs = dict.valuerefs()
910 self.assertEqual(len(refs), len(objects))
911 objects2 = list(objects)
912 for wr in refs:
913 ob = wr()
914 self.assertEqual(ob, dict[ob.arg])
915 self.assertEqual(ob.arg, dict[ob.arg].arg)
916 objects2.remove(ob)
917 self.assertEqual(len(objects2), 0)
918
919 # Test itervaluerefs()
920 objects2 = list(objects)
921 self.assertEqual(len(list(dict.itervaluerefs())), len(objects))
922 for wr in dict.itervaluerefs():
923 ob = wr()
924 self.assertEqual(ob, dict[ob.arg])
925 self.assertEqual(ob.arg, dict[ob.arg].arg)
926 objects2.remove(ob)
927 self.assertEqual(len(objects2), 0)
928
Fred Drake0e540c32001-05-02 05:44:22 +0000929 def check_iters(self, dict):
930 # item iterator:
Barry Warsawecaab832008-09-04 01:42:51 +0000931 items = list(dict.items())
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000932 for item in dict.items():
Fred Drake0e540c32001-05-02 05:44:22 +0000933 items.remove(item)
Barry Warsawecaab832008-09-04 01:42:51 +0000934 self.assertFalse(items, "items() did not touch all items")
Fred Drake0e540c32001-05-02 05:44:22 +0000935
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000936 # key iterator, via __iter__():
Guido van Rossum07f24362007-02-11 22:59:48 +0000937 keys = list(dict.keys())
Fred Drake0e540c32001-05-02 05:44:22 +0000938 for k in dict:
939 keys.remove(k)
Barry Warsawecaab832008-09-04 01:42:51 +0000940 self.assertFalse(keys, "__iter__() did not touch all keys")
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000941
942 # key iterator, via iterkeys():
Guido van Rossum07f24362007-02-11 22:59:48 +0000943 keys = list(dict.keys())
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000944 for k in dict.keys():
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000945 keys.remove(k)
Barry Warsawecaab832008-09-04 01:42:51 +0000946 self.assertFalse(keys, "iterkeys() did not touch all keys")
Fred Drake0e540c32001-05-02 05:44:22 +0000947
948 # value iterator:
Guido van Rossum07f24362007-02-11 22:59:48 +0000949 values = list(dict.values())
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000950 for v in dict.values():
Fred Drake0e540c32001-05-02 05:44:22 +0000951 values.remove(v)
Barry Warsawecaab832008-09-04 01:42:51 +0000952 self.assertFalse(values,
Fred Drakef425b1e2003-07-14 21:37:17 +0000953 "itervalues() did not touch all values")
Fred Drake0e540c32001-05-02 05:44:22 +0000954
Antoine Pitrouc1baa602010-01-08 17:54:23 +0000955 def check_weak_destroy_while_iterating(self, dict, objects, iter_name):
956 n = len(dict)
957 it = iter(getattr(dict, iter_name)())
958 next(it) # Trigger internal iteration
959 # Destroy an object
960 del objects[-1]
961 gc.collect() # just in case
962 # We have removed either the first consumed object, or another one
963 self.assertIn(len(list(it)), [len(objects), len(objects) - 1])
964 del it
965 # The removal has been committed
966 self.assertEqual(len(dict), n - 1)
967
968 def check_weak_destroy_and_mutate_while_iterating(self, dict, testcontext):
969 # Check that we can explicitly mutate the weak dict without
970 # interfering with delayed removal.
971 # `testcontext` should create an iterator, destroy one of the
972 # weakref'ed objects and then return a new key/value pair corresponding
973 # to the destroyed object.
974 with testcontext() as (k, v):
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000975 self.assertNotIn(k, dict)
Antoine Pitrouc1baa602010-01-08 17:54:23 +0000976 with testcontext() as (k, v):
977 self.assertRaises(KeyError, dict.__delitem__, k)
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000978 self.assertNotIn(k, dict)
Antoine Pitrouc1baa602010-01-08 17:54:23 +0000979 with testcontext() as (k, v):
980 self.assertRaises(KeyError, dict.pop, k)
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000981 self.assertNotIn(k, dict)
Antoine Pitrouc1baa602010-01-08 17:54:23 +0000982 with testcontext() as (k, v):
983 dict[k] = v
984 self.assertEqual(dict[k], v)
985 ddict = copy.copy(dict)
986 with testcontext() as (k, v):
987 dict.update(ddict)
988 self.assertEqual(dict, ddict)
989 with testcontext() as (k, v):
990 dict.clear()
991 self.assertEqual(len(dict), 0)
992
993 def test_weak_keys_destroy_while_iterating(self):
994 # Issue #7105: iterators shouldn't crash when a key is implicitly removed
995 dict, objects = self.make_weak_keyed_dict()
996 self.check_weak_destroy_while_iterating(dict, objects, 'keys')
997 self.check_weak_destroy_while_iterating(dict, objects, 'items')
998 self.check_weak_destroy_while_iterating(dict, objects, 'values')
999 self.check_weak_destroy_while_iterating(dict, objects, 'keyrefs')
1000 dict, objects = self.make_weak_keyed_dict()
1001 @contextlib.contextmanager
1002 def testcontext():
1003 try:
1004 it = iter(dict.items())
1005 next(it)
1006 # Schedule a key/value for removal and recreate it
1007 v = objects.pop().arg
1008 gc.collect() # just in case
1009 yield Object(v), v
1010 finally:
1011 it = None # should commit all removals
1012 self.check_weak_destroy_and_mutate_while_iterating(dict, testcontext)
1013
1014 def test_weak_values_destroy_while_iterating(self):
1015 # Issue #7105: iterators shouldn't crash when a key is implicitly removed
1016 dict, objects = self.make_weak_valued_dict()
1017 self.check_weak_destroy_while_iterating(dict, objects, 'keys')
1018 self.check_weak_destroy_while_iterating(dict, objects, 'items')
1019 self.check_weak_destroy_while_iterating(dict, objects, 'values')
1020 self.check_weak_destroy_while_iterating(dict, objects, 'itervaluerefs')
1021 self.check_weak_destroy_while_iterating(dict, objects, 'valuerefs')
1022 dict, objects = self.make_weak_valued_dict()
1023 @contextlib.contextmanager
1024 def testcontext():
1025 try:
1026 it = iter(dict.items())
1027 next(it)
1028 # Schedule a key/value for removal and recreate it
1029 k = objects.pop().arg
1030 gc.collect() # just in case
1031 yield k, Object(k)
1032 finally:
1033 it = None # should commit all removals
1034 self.check_weak_destroy_and_mutate_while_iterating(dict, testcontext)
1035
Guido van Rossum009afb72002-06-10 20:00:52 +00001036 def test_make_weak_keyed_dict_from_dict(self):
1037 o = Object(3)
1038 dict = weakref.WeakKeyDictionary({o:364})
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001039 self.assertEqual(dict[o], 364)
Guido van Rossum009afb72002-06-10 20:00:52 +00001040
1041 def test_make_weak_keyed_dict_from_weak_keyed_dict(self):
1042 o = Object(3)
1043 dict = weakref.WeakKeyDictionary({o:364})
1044 dict2 = weakref.WeakKeyDictionary(dict)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001045 self.assertEqual(dict[o], 364)
Guido van Rossum009afb72002-06-10 20:00:52 +00001046
Fred Drake0e540c32001-05-02 05:44:22 +00001047 def make_weak_keyed_dict(self):
1048 dict = weakref.WeakKeyDictionary()
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001049 objects = list(map(Object, range(self.COUNT)))
Fred Drake0e540c32001-05-02 05:44:22 +00001050 for o in objects:
1051 dict[o] = o.arg
1052 return dict, objects
1053
Antoine Pitrouc06de472009-05-30 21:04:26 +00001054 def test_make_weak_valued_dict_from_dict(self):
1055 o = Object(3)
1056 dict = weakref.WeakValueDictionary({364:o})
1057 self.assertEqual(dict[364], o)
1058
1059 def test_make_weak_valued_dict_from_weak_valued_dict(self):
1060 o = Object(3)
1061 dict = weakref.WeakValueDictionary({364:o})
1062 dict2 = weakref.WeakValueDictionary(dict)
1063 self.assertEqual(dict[364], o)
1064
Fred Drake0e540c32001-05-02 05:44:22 +00001065 def make_weak_valued_dict(self):
1066 dict = weakref.WeakValueDictionary()
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001067 objects = list(map(Object, range(self.COUNT)))
Fred Drake0e540c32001-05-02 05:44:22 +00001068 for o in objects:
1069 dict[o.arg] = o
1070 return dict, objects
1071
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001072 def check_popitem(self, klass, key1, value1, key2, value2):
1073 weakdict = klass()
1074 weakdict[key1] = value1
1075 weakdict[key2] = value2
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001076 self.assertEqual(len(weakdict), 2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001077 k, v = weakdict.popitem()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001078 self.assertEqual(len(weakdict), 1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001079 if k is key1:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001080 self.assertTrue(v is value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001081 else:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001082 self.assertTrue(v is value2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001083 k, v = weakdict.popitem()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001084 self.assertEqual(len(weakdict), 0)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001085 if k is key1:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001086 self.assertTrue(v is value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001087 else:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001088 self.assertTrue(v is value2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001089
1090 def test_weak_valued_dict_popitem(self):
1091 self.check_popitem(weakref.WeakValueDictionary,
1092 "key1", C(), "key2", C())
1093
1094 def test_weak_keyed_dict_popitem(self):
1095 self.check_popitem(weakref.WeakKeyDictionary,
1096 C(), "value 1", C(), "value 2")
1097
1098 def check_setdefault(self, klass, key, value1, value2):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001099 self.assertTrue(value1 is not value2,
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001100 "invalid test"
1101 " -- value parameters must be distinct objects")
1102 weakdict = klass()
1103 o = weakdict.setdefault(key, value1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001104 self.assertTrue(o is value1)
Benjamin Peterson577473f2010-01-19 00:09:57 +00001105 self.assertIn(key, weakdict)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001106 self.assertTrue(weakdict.get(key) is value1)
1107 self.assertTrue(weakdict[key] is value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001108
1109 o = weakdict.setdefault(key, value2)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001110 self.assertTrue(o is value1)
Benjamin Peterson577473f2010-01-19 00:09:57 +00001111 self.assertIn(key, weakdict)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001112 self.assertTrue(weakdict.get(key) is value1)
1113 self.assertTrue(weakdict[key] is value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001114
1115 def test_weak_valued_dict_setdefault(self):
1116 self.check_setdefault(weakref.WeakValueDictionary,
1117 "key", C(), C())
1118
1119 def test_weak_keyed_dict_setdefault(self):
1120 self.check_setdefault(weakref.WeakKeyDictionary,
1121 C(), "value 1", "value 2")
1122
Fred Drakea0a4ab12001-04-16 17:37:27 +00001123 def check_update(self, klass, dict):
Fred Drake0e540c32001-05-02 05:44:22 +00001124 #
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001125 # This exercises d.update(), len(d), d.keys(), k in d,
Fred Drake0e540c32001-05-02 05:44:22 +00001126 # d.get(), d[].
1127 #
Fred Drakea0a4ab12001-04-16 17:37:27 +00001128 weakdict = klass()
1129 weakdict.update(dict)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001130 self.assertEqual(len(weakdict), len(dict))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001131 for k in weakdict.keys():
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001132 self.assertIn(k, dict, "mysterious new key appeared in weak dict")
Fred Drakea0a4ab12001-04-16 17:37:27 +00001133 v = dict.get(k)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001134 self.assertTrue(v is weakdict[k])
1135 self.assertTrue(v is weakdict.get(k))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001136 for k in dict.keys():
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001137 self.assertIn(k, weakdict, "original key disappeared in weak dict")
Fred Drakea0a4ab12001-04-16 17:37:27 +00001138 v = dict[k]
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001139 self.assertTrue(v is weakdict[k])
1140 self.assertTrue(v is weakdict.get(k))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001141
1142 def test_weak_valued_dict_update(self):
1143 self.check_update(weakref.WeakValueDictionary,
1144 {1: C(), 'a': C(), C(): C()})
1145
1146 def test_weak_keyed_dict_update(self):
1147 self.check_update(weakref.WeakKeyDictionary,
1148 {C(): 1, C(): 2, C(): 3})
1149
Fred Drakeccc75622001-09-06 14:52:39 +00001150 def test_weak_keyed_delitem(self):
1151 d = weakref.WeakKeyDictionary()
1152 o1 = Object('1')
1153 o2 = Object('2')
1154 d[o1] = 'something'
1155 d[o2] = 'something'
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001156 self.assertEqual(len(d), 2)
Fred Drakeccc75622001-09-06 14:52:39 +00001157 del d[o1]
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001158 self.assertEqual(len(d), 1)
Barry Warsawecaab832008-09-04 01:42:51 +00001159 self.assertEqual(list(d.keys()), [o2])
Fred Drakeccc75622001-09-06 14:52:39 +00001160
1161 def test_weak_valued_delitem(self):
1162 d = weakref.WeakValueDictionary()
1163 o1 = Object('1')
1164 o2 = Object('2')
1165 d['something'] = o1
1166 d['something else'] = o2
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001167 self.assertEqual(len(d), 2)
Fred Drakeccc75622001-09-06 14:52:39 +00001168 del d['something']
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001169 self.assertEqual(len(d), 1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001170 self.assertTrue(list(d.items()) == [('something else', o2)])
Fred Drakeccc75622001-09-06 14:52:39 +00001171
Tim Peters886128f2003-05-25 01:45:11 +00001172 def test_weak_keyed_bad_delitem(self):
1173 d = weakref.WeakKeyDictionary()
1174 o = Object('1')
1175 # An attempt to delete an object that isn't there should raise
Tim Peters50d8b8b2003-05-25 17:44:31 +00001176 # KeyError. It didn't before 2.3.
Tim Peters886128f2003-05-25 01:45:11 +00001177 self.assertRaises(KeyError, d.__delitem__, o)
Tim Peters50d8b8b2003-05-25 17:44:31 +00001178 self.assertRaises(KeyError, d.__getitem__, o)
1179
1180 # If a key isn't of a weakly referencable type, __getitem__ and
1181 # __setitem__ raise TypeError. __delitem__ should too.
1182 self.assertRaises(TypeError, d.__delitem__, 13)
1183 self.assertRaises(TypeError, d.__getitem__, 13)
1184 self.assertRaises(TypeError, d.__setitem__, 13, 13)
Tim Peters886128f2003-05-25 01:45:11 +00001185
1186 def test_weak_keyed_cascading_deletes(self):
1187 # SF bug 742860. For some reason, before 2.3 __delitem__ iterated
1188 # over the keys via self.data.iterkeys(). If things vanished from
1189 # the dict during this (or got added), that caused a RuntimeError.
1190
1191 d = weakref.WeakKeyDictionary()
1192 mutate = False
1193
1194 class C(object):
1195 def __init__(self, i):
1196 self.value = i
1197 def __hash__(self):
1198 return hash(self.value)
1199 def __eq__(self, other):
1200 if mutate:
1201 # Side effect that mutates the dict, by removing the
1202 # last strong reference to a key.
1203 del objs[-1]
1204 return self.value == other.value
1205
1206 objs = [C(i) for i in range(4)]
1207 for o in objs:
1208 d[o] = o.value
1209 del o # now the only strong references to keys are in objs
1210 # Find the order in which iterkeys sees the keys.
Barry Warsawecaab832008-09-04 01:42:51 +00001211 objs = list(d.keys())
Tim Peters886128f2003-05-25 01:45:11 +00001212 # Reverse it, so that the iteration implementation of __delitem__
1213 # has to keep looping to find the first object we delete.
1214 objs.reverse()
Tim Peters50d8b8b2003-05-25 17:44:31 +00001215
Tim Peters886128f2003-05-25 01:45:11 +00001216 # Turn on mutation in C.__eq__. The first time thru the loop,
1217 # under the iterkeys() business the first comparison will delete
1218 # the last item iterkeys() would see, and that causes a
1219 # RuntimeError: dictionary changed size during iteration
1220 # when the iterkeys() loop goes around to try comparing the next
Tim Peters50d8b8b2003-05-25 17:44:31 +00001221 # key. After this was fixed, it just deletes the last object *our*
Tim Peters886128f2003-05-25 01:45:11 +00001222 # "for o in obj" loop would have gotten to.
1223 mutate = True
1224 count = 0
1225 for o in objs:
1226 count += 1
1227 del d[o]
1228 self.assertEqual(len(d), 0)
1229 self.assertEqual(count, 2)
1230
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001231from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001232
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001233class WeakValueDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +00001234 """Check that WeakValueDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001235 __ref = {"key1":Object(1), "key2":Object(2), "key3":Object(3)}
Walter Dörwald118f9312004-06-02 18:42:25 +00001236 type2test = weakref.WeakValueDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001237 def _reference(self):
1238 return self.__ref.copy()
1239
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001240class WeakKeyDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +00001241 """Check that WeakKeyDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001242 __ref = {Object("key1"):1, Object("key2"):2, Object("key3"):3}
Walter Dörwald118f9312004-06-02 18:42:25 +00001243 type2test = weakref.WeakKeyDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001244 def _reference(self):
1245 return self.__ref.copy()
Martin v. Löwis5e163332001-02-27 18:36:56 +00001246
Georg Brandlb533e262008-05-25 18:19:30 +00001247libreftest = """ Doctest for examples in the library reference: weakref.rst
Georg Brandl9a65d582005-07-02 19:07:30 +00001248
1249>>> import weakref
1250>>> class Dict(dict):
1251... pass
1252...
1253>>> obj = Dict(red=1, green=2, blue=3) # this object is weak referencable
1254>>> r = weakref.ref(obj)
Guido van Rossum7131f842007-02-09 20:13:25 +00001255>>> print(r() is obj)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001256True
Georg Brandl9a65d582005-07-02 19:07:30 +00001257
1258>>> import weakref
1259>>> class Object:
1260... pass
1261...
1262>>> o = Object()
1263>>> r = weakref.ref(o)
1264>>> o2 = r()
1265>>> o is o2
1266True
1267>>> del o, o2
Guido van Rossum7131f842007-02-09 20:13:25 +00001268>>> print(r())
Georg Brandl9a65d582005-07-02 19:07:30 +00001269None
1270
1271>>> import weakref
1272>>> class ExtendedRef(weakref.ref):
1273... def __init__(self, ob, callback=None, **annotations):
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001274... super().__init__(ob, callback)
Georg Brandl9a65d582005-07-02 19:07:30 +00001275... self.__counter = 0
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001276... for k, v in annotations.items():
Georg Brandl9a65d582005-07-02 19:07:30 +00001277... setattr(self, k, v)
1278... def __call__(self):
1279... '''Return a pair containing the referent and the number of
1280... times the reference has been called.
1281... '''
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001282... ob = super().__call__()
Georg Brandl9a65d582005-07-02 19:07:30 +00001283... if ob is not None:
1284... self.__counter += 1
1285... ob = (ob, self.__counter)
1286... return ob
Guido van Rossumd8faa362007-04-27 19:54:29 +00001287...
Georg Brandl9a65d582005-07-02 19:07:30 +00001288>>> class A: # not in docs from here, just testing the ExtendedRef
1289... pass
1290...
1291>>> a = A()
1292>>> r = ExtendedRef(a, foo=1, bar="baz")
1293>>> r.foo
12941
1295>>> r.bar
1296'baz'
1297>>> r()[1]
12981
1299>>> r()[1]
13002
1301>>> r()[0] is a
1302True
1303
1304
1305>>> import weakref
1306>>> _id2obj_dict = weakref.WeakValueDictionary()
1307>>> def remember(obj):
1308... oid = id(obj)
1309... _id2obj_dict[oid] = obj
1310... return oid
1311...
1312>>> def id2obj(oid):
1313... return _id2obj_dict[oid]
1314...
1315>>> a = A() # from here, just testing
1316>>> a_id = remember(a)
1317>>> id2obj(a_id) is a
1318True
1319>>> del a
1320>>> try:
1321... id2obj(a_id)
1322... except KeyError:
Guido van Rossum7131f842007-02-09 20:13:25 +00001323... print('OK')
Georg Brandl9a65d582005-07-02 19:07:30 +00001324... else:
Guido van Rossum7131f842007-02-09 20:13:25 +00001325... print('WeakValueDictionary error')
Georg Brandl9a65d582005-07-02 19:07:30 +00001326OK
1327
1328"""
1329
1330__test__ = {'libreftest' : libreftest}
1331
Fred Drake2e2be372001-09-20 21:33:42 +00001332def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001333 support.run_unittest(
Walter Dörwald21d3a322003-05-01 17:45:56 +00001334 ReferencesTestCase,
1335 MappingTestCase,
1336 WeakValueDictionaryTestCase,
Fred Drakef425b1e2003-07-14 21:37:17 +00001337 WeakKeyDictionaryTestCase,
Amaury Forgeot d'Arcc856c7a2008-06-16 19:50:09 +00001338 SubclassableWeakrefTestCase,
Fred Drakef425b1e2003-07-14 21:37:17 +00001339 )
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001340 support.run_doctest(sys.modules[__name__])
Fred Drake2e2be372001-09-20 21:33:42 +00001341
1342
1343if __name__ == "__main__":
1344 test_main()