blob: 57a098d754bb5c700feda812b98d56c4c181fe3a [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)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000172 self.assertTrue(3 in p,
Fred Drakef425b1e2003-07-14 21:37:17 +0000173 "proxy didn't support __contains__() properly")
Fred Drake5935ff02001-12-19 16:54:23 +0000174 p[1] = 5
175 self.assertEqual(L[1], 5)
176 self.assertEqual(p[1], 5)
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000177 L2 = collections.UserList(L)
Fred Drake5935ff02001-12-19 16:54:23 +0000178 p2 = weakref.proxy(L2)
179 self.assertEqual(p, p2)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000180 ## self.assertEqual(repr(L2), repr(p2))
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000181 L3 = collections.UserList(range(10))
Fred Drake43735da2002-04-11 03:59:42 +0000182 p3 = weakref.proxy(L3)
183 self.assertEqual(L3[:], p3[:])
184 self.assertEqual(L3[5:], p3[5:])
185 self.assertEqual(L3[:5], p3[:5])
186 self.assertEqual(L3[2:5], p3[2:5])
Fred Drake5935ff02001-12-19 16:54:23 +0000187
Benjamin Peterson32019772009-11-19 03:08:32 +0000188 def test_proxy_unicode(self):
189 # See bug 5037
190 class C(object):
191 def __str__(self):
192 return "string"
193 def __bytes__(self):
194 return b"bytes"
195 instance = C()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000196 self.assertIn("__bytes__", dir(weakref.proxy(instance)))
Benjamin Peterson32019772009-11-19 03:08:32 +0000197 self.assertEqual(bytes(weakref.proxy(instance)), b"bytes")
198
Georg Brandlb533e262008-05-25 18:19:30 +0000199 def test_proxy_index(self):
200 class C:
201 def __index__(self):
202 return 10
203 o = C()
204 p = weakref.proxy(o)
205 self.assertEqual(operator.index(p), 10)
206
207 def test_proxy_div(self):
208 class C:
209 def __floordiv__(self, other):
210 return 42
211 def __ifloordiv__(self, other):
212 return 21
213 o = C()
214 p = weakref.proxy(o)
215 self.assertEqual(p // 5, 42)
216 p //= 5
217 self.assertEqual(p, 21)
218
Fred Drakeea2adc92004-02-03 19:56:46 +0000219 # The PyWeakref_* C API is documented as allowing either NULL or
220 # None as the value for the callback, where either means "no
221 # callback". The "no callback" ref and proxy objects are supposed
222 # to be shared so long as they exist by all callers so long as
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000223 # they are active. In Python 2.3.3 and earlier, this guarantee
Fred Drakeea2adc92004-02-03 19:56:46 +0000224 # was not honored, and was broken in different ways for
225 # PyWeakref_NewRef() and PyWeakref_NewProxy(). (Two tests.)
226
227 def test_shared_ref_without_callback(self):
228 self.check_shared_without_callback(weakref.ref)
229
230 def test_shared_proxy_without_callback(self):
231 self.check_shared_without_callback(weakref.proxy)
232
233 def check_shared_without_callback(self, makeref):
234 o = Object(1)
235 p1 = makeref(o, None)
236 p2 = makeref(o, None)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000237 self.assertTrue(p1 is p2, "both callbacks were None in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000238 del p1, p2
239 p1 = makeref(o)
240 p2 = makeref(o, None)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000241 self.assertTrue(p1 is p2, "callbacks were NULL, None in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000242 del p1, p2
243 p1 = makeref(o)
244 p2 = makeref(o)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000245 self.assertTrue(p1 is p2, "both callbacks were NULL in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000246 del p1, p2
247 p1 = makeref(o, None)
248 p2 = makeref(o)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000249 self.assertTrue(p1 is p2, "callbacks were None, NULL in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000250
Fred Drakeb0fefc52001-03-23 04:22:45 +0000251 def test_callable_proxy(self):
252 o = Callable()
253 ref1 = weakref.proxy(o)
254
255 self.check_proxy(o, ref1)
256
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000257 self.assertTrue(type(ref1) is weakref.CallableProxyType,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000258 "proxy is not of callable type")
259 ref1('twinkies!')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000260 self.assertTrue(o.bar == 'twinkies!',
Fred Drakeb0fefc52001-03-23 04:22:45 +0000261 "call through proxy not passed through to original")
Fred Drake3bb4d212001-10-18 19:28:29 +0000262 ref1(x='Splat.')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000263 self.assertTrue(o.bar == 'Splat.',
Fred Drake3bb4d212001-10-18 19:28:29 +0000264 "call through proxy not passed through to original")
Fred Drakeb0fefc52001-03-23 04:22:45 +0000265
266 # expect due to too few args
267 self.assertRaises(TypeError, ref1)
268
269 # expect due to too many args
270 self.assertRaises(TypeError, ref1, 1, 2, 3)
271
272 def check_proxy(self, o, proxy):
273 o.foo = 1
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000274 self.assertTrue(proxy.foo == 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000275 "proxy does not reflect attribute addition")
276 o.foo = 2
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000277 self.assertTrue(proxy.foo == 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000278 "proxy does not reflect attribute modification")
279 del o.foo
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000280 self.assertTrue(not hasattr(proxy, 'foo'),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000281 "proxy does not reflect attribute removal")
282
283 proxy.foo = 1
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000284 self.assertTrue(o.foo == 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000285 "object does not reflect attribute addition via proxy")
286 proxy.foo = 2
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000287 self.assertTrue(
Fred Drakeb0fefc52001-03-23 04:22:45 +0000288 o.foo == 2,
289 "object does not reflect attribute modification via proxy")
290 del proxy.foo
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000291 self.assertTrue(not hasattr(o, 'foo'),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000292 "object does not reflect attribute removal via proxy")
293
Raymond Hettingerd693a812003-06-30 04:18:48 +0000294 def test_proxy_deletion(self):
295 # Test clearing of SF bug #762891
296 class Foo:
297 result = None
298 def __delitem__(self, accessor):
299 self.result = accessor
300 g = Foo()
301 f = weakref.proxy(g)
302 del f[0]
303 self.assertEqual(f.result, 0)
304
Raymond Hettingere6c470f2005-03-27 03:04:54 +0000305 def test_proxy_bool(self):
306 # Test clearing of SF bug #1170766
307 class List(list): pass
308 lyst = List()
309 self.assertEqual(bool(weakref.proxy(lyst)), bool(lyst))
310
Fred Drakeb0fefc52001-03-23 04:22:45 +0000311 def test_getweakrefcount(self):
312 o = C()
313 ref1 = weakref.ref(o)
314 ref2 = weakref.ref(o, self.callback)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000315 self.assertTrue(weakref.getweakrefcount(o) == 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000316 "got wrong number of weak reference objects")
317
318 proxy1 = weakref.proxy(o)
319 proxy2 = weakref.proxy(o, self.callback)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000320 self.assertTrue(weakref.getweakrefcount(o) == 4,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000321 "got wrong number of weak reference objects")
322
Fred Drakeea2adc92004-02-03 19:56:46 +0000323 del ref1, ref2, proxy1, proxy2
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000324 self.assertTrue(weakref.getweakrefcount(o) == 0,
Fred Drakeea2adc92004-02-03 19:56:46 +0000325 "weak reference objects not unlinked from"
326 " referent when discarded.")
327
Walter Dörwaldb167b042003-12-11 12:34:05 +0000328 # assumes ints do not support weakrefs
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000329 self.assertTrue(weakref.getweakrefcount(1) == 0,
Walter Dörwaldb167b042003-12-11 12:34:05 +0000330 "got wrong number of weak reference objects for int")
331
Fred Drakeb0fefc52001-03-23 04:22:45 +0000332 def test_getweakrefs(self):
333 o = C()
334 ref1 = weakref.ref(o, self.callback)
335 ref2 = weakref.ref(o, self.callback)
336 del ref1
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000337 self.assertTrue(weakref.getweakrefs(o) == [ref2],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000338 "list of refs does not match")
339
340 o = C()
341 ref1 = weakref.ref(o, self.callback)
342 ref2 = weakref.ref(o, self.callback)
343 del ref2
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000344 self.assertTrue(weakref.getweakrefs(o) == [ref1],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000345 "list of refs does not match")
346
Fred Drakeea2adc92004-02-03 19:56:46 +0000347 del ref1
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000348 self.assertTrue(weakref.getweakrefs(o) == [],
Fred Drakeea2adc92004-02-03 19:56:46 +0000349 "list of refs not cleared")
350
Walter Dörwaldb167b042003-12-11 12:34:05 +0000351 # assumes ints do not support weakrefs
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000352 self.assertTrue(weakref.getweakrefs(1) == [],
Walter Dörwaldb167b042003-12-11 12:34:05 +0000353 "list of refs does not match for int")
354
Fred Drake39c27f12001-10-18 18:06:05 +0000355 def test_newstyle_number_ops(self):
356 class F(float):
357 pass
358 f = F(2.0)
359 p = weakref.proxy(f)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000360 self.assertTrue(p + 1.0 == 3.0)
361 self.assertTrue(1.0 + p == 3.0) # this used to SEGV
Fred Drake39c27f12001-10-18 18:06:05 +0000362
Fred Drake2a64f462001-12-10 23:46:02 +0000363 def test_callbacks_protected(self):
Guido van Rossum9eee5542002-08-22 20:21:30 +0000364 # Callbacks protected from already-set exceptions?
Fred Drake2a64f462001-12-10 23:46:02 +0000365 # Regression test for SF bug #478534.
366 class BogusError(Exception):
367 pass
368 data = {}
369 def remove(k):
370 del data[k]
371 def encapsulate():
372 f = lambda : ()
373 data[weakref.ref(f, remove)] = None
374 raise BogusError
375 try:
376 encapsulate()
377 except BogusError:
378 pass
379 else:
380 self.fail("exception not properly restored")
381 try:
382 encapsulate()
383 except BogusError:
384 pass
385 else:
386 self.fail("exception not properly restored")
387
Tim Petersadd09b42003-11-12 20:43:28 +0000388 def test_sf_bug_840829(self):
389 # "weakref callbacks and gc corrupt memory"
390 # subtype_dealloc erroneously exposed a new-style instance
391 # already in the process of getting deallocated to gc,
392 # causing double-deallocation if the instance had a weakref
393 # callback that triggered gc.
394 # If the bug exists, there probably won't be an obvious symptom
395 # in a release build. In a debug build, a segfault will occur
396 # when the second attempt to remove the instance from the "list
397 # of all objects" occurs.
398
399 import gc
400
401 class C(object):
402 pass
403
404 c = C()
405 wr = weakref.ref(c, lambda ignore: gc.collect())
406 del c
407
Tim Petersf7f9e992003-11-13 21:59:32 +0000408 # There endeth the first part. It gets worse.
409 del wr
410
411 c1 = C()
412 c1.i = C()
413 wr = weakref.ref(c1.i, lambda ignore: gc.collect())
414
415 c2 = C()
416 c2.c1 = c1
417 del c1 # still alive because c2 points to it
418
419 # Now when subtype_dealloc gets called on c2, it's not enough just
420 # that c2 is immune from gc while the weakref callbacks associated
421 # with c2 execute (there are none in this 2nd half of the test, btw).
422 # subtype_dealloc goes on to call the base classes' deallocs too,
423 # so any gc triggered by weakref callbacks associated with anything
424 # torn down by a base class dealloc can also trigger double
425 # deallocation of c2.
426 del c2
Fred Drake41deb1e2001-02-01 05:27:45 +0000427
Tim Peters403a2032003-11-20 21:21:46 +0000428 def test_callback_in_cycle_1(self):
429 import gc
430
431 class J(object):
432 pass
433
434 class II(object):
435 def acallback(self, ignore):
436 self.J
437
438 I = II()
439 I.J = J
440 I.wr = weakref.ref(J, I.acallback)
441
442 # Now J and II are each in a self-cycle (as all new-style class
443 # objects are, since their __mro__ points back to them). I holds
444 # both a weak reference (I.wr) and a strong reference (I.J) to class
445 # J. I is also in a cycle (I.wr points to a weakref that references
446 # I.acallback). When we del these three, they all become trash, but
447 # the cycles prevent any of them from getting cleaned up immediately.
448 # Instead they have to wait for cyclic gc to deduce that they're
449 # trash.
450 #
451 # gc used to call tp_clear on all of them, and the order in which
452 # it does that is pretty accidental. The exact order in which we
453 # built up these things manages to provoke gc into running tp_clear
454 # in just the right order (I last). Calling tp_clear on II leaves
455 # behind an insane class object (its __mro__ becomes NULL). Calling
456 # tp_clear on J breaks its self-cycle, but J doesn't get deleted
457 # just then because of the strong reference from I.J. Calling
458 # tp_clear on I starts to clear I's __dict__, and just happens to
459 # clear I.J first -- I.wr is still intact. That removes the last
460 # reference to J, which triggers the weakref callback. The callback
461 # tries to do "self.J", and instances of new-style classes look up
462 # attributes ("J") in the class dict first. The class (II) wants to
463 # search II.__mro__, but that's NULL. The result was a segfault in
464 # a release build, and an assert failure in a debug build.
465 del I, J, II
466 gc.collect()
467
468 def test_callback_in_cycle_2(self):
469 import gc
470
471 # This is just like test_callback_in_cycle_1, except that II is an
472 # old-style class. The symptom is different then: an instance of an
473 # old-style class looks in its own __dict__ first. 'J' happens to
474 # get cleared from I.__dict__ before 'wr', and 'J' was never in II's
475 # __dict__, so the attribute isn't found. The difference is that
476 # the old-style II doesn't have a NULL __mro__ (it doesn't have any
477 # __mro__), so no segfault occurs. Instead it got:
478 # test_callback_in_cycle_2 (__main__.ReferencesTestCase) ...
479 # Exception exceptions.AttributeError:
480 # "II instance has no attribute 'J'" in <bound method II.acallback
481 # of <?.II instance at 0x00B9B4B8>> ignored
482
483 class J(object):
484 pass
485
486 class II:
487 def acallback(self, ignore):
488 self.J
489
490 I = II()
491 I.J = J
492 I.wr = weakref.ref(J, I.acallback)
493
494 del I, J, II
495 gc.collect()
496
497 def test_callback_in_cycle_3(self):
498 import gc
499
500 # This one broke the first patch that fixed the last two. In this
501 # case, the objects reachable from the callback aren't also reachable
502 # from the object (c1) *triggering* the callback: you can get to
503 # c1 from c2, but not vice-versa. The result was that c2's __dict__
504 # got tp_clear'ed by the time the c2.cb callback got invoked.
505
506 class C:
507 def cb(self, ignore):
508 self.me
509 self.c1
510 self.wr
511
512 c1, c2 = C(), C()
513
514 c2.me = c2
515 c2.c1 = c1
516 c2.wr = weakref.ref(c1, c2.cb)
517
518 del c1, c2
519 gc.collect()
520
521 def test_callback_in_cycle_4(self):
522 import gc
523
524 # Like test_callback_in_cycle_3, except c2 and c1 have different
525 # classes. c2's class (C) isn't reachable from c1 then, so protecting
526 # objects reachable from the dying object (c1) isn't enough to stop
527 # c2's class (C) from getting tp_clear'ed before c2.cb is invoked.
528 # The result was a segfault (C.__mro__ was NULL when the callback
529 # tried to look up self.me).
530
531 class C(object):
532 def cb(self, ignore):
533 self.me
534 self.c1
535 self.wr
536
537 class D:
538 pass
539
540 c1, c2 = D(), C()
541
542 c2.me = c2
543 c2.c1 = c1
544 c2.wr = weakref.ref(c1, c2.cb)
545
546 del c1, c2, C, D
547 gc.collect()
548
549 def test_callback_in_cycle_resurrection(self):
550 import gc
551
552 # Do something nasty in a weakref callback: resurrect objects
553 # from dead cycles. For this to be attempted, the weakref and
554 # its callback must also be part of the cyclic trash (else the
555 # objects reachable via the callback couldn't be in cyclic trash
556 # to begin with -- the callback would act like an external root).
557 # But gc clears trash weakrefs with callbacks early now, which
558 # disables the callbacks, so the callbacks shouldn't get called
559 # at all (and so nothing actually gets resurrected).
560
561 alist = []
562 class C(object):
563 def __init__(self, value):
564 self.attribute = value
565
566 def acallback(self, ignore):
567 alist.append(self.c)
568
569 c1, c2 = C(1), C(2)
570 c1.c = c2
571 c2.c = c1
572 c1.wr = weakref.ref(c2, c1.acallback)
573 c2.wr = weakref.ref(c1, c2.acallback)
574
575 def C_went_away(ignore):
576 alist.append("C went away")
577 wr = weakref.ref(C, C_went_away)
578
579 del c1, c2, C # make them all trash
580 self.assertEqual(alist, []) # del isn't enough to reclaim anything
581
582 gc.collect()
583 # c1.wr and c2.wr were part of the cyclic trash, so should have
584 # been cleared without their callbacks executing. OTOH, the weakref
585 # to C is bound to a function local (wr), and wasn't trash, so that
586 # callback should have been invoked when C went away.
587 self.assertEqual(alist, ["C went away"])
588 # The remaining weakref should be dead now (its callback ran).
589 self.assertEqual(wr(), None)
590
591 del alist[:]
592 gc.collect()
593 self.assertEqual(alist, [])
594
595 def test_callbacks_on_callback(self):
596 import gc
597
598 # Set up weakref callbacks *on* weakref callbacks.
599 alist = []
600 def safe_callback(ignore):
601 alist.append("safe_callback called")
602
603 class C(object):
604 def cb(self, ignore):
605 alist.append("cb called")
606
607 c, d = C(), C()
608 c.other = d
609 d.other = c
610 callback = c.cb
611 c.wr = weakref.ref(d, callback) # this won't trigger
612 d.wr = weakref.ref(callback, d.cb) # ditto
613 external_wr = weakref.ref(callback, safe_callback) # but this will
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000614 self.assertTrue(external_wr() is callback)
Tim Peters403a2032003-11-20 21:21:46 +0000615
616 # The weakrefs attached to c and d should get cleared, so that
617 # C.cb is never called. But external_wr isn't part of the cyclic
618 # trash, and no cyclic trash is reachable from it, so safe_callback
619 # should get invoked when the bound method object callback (c.cb)
620 # -- which is itself a callback, and also part of the cyclic trash --
621 # gets reclaimed at the end of gc.
622
623 del callback, c, d, C
624 self.assertEqual(alist, []) # del isn't enough to clean up cycles
625 gc.collect()
626 self.assertEqual(alist, ["safe_callback called"])
627 self.assertEqual(external_wr(), None)
628
629 del alist[:]
630 gc.collect()
631 self.assertEqual(alist, [])
632
Fred Drakebc875f52004-02-04 23:14:14 +0000633 def test_gc_during_ref_creation(self):
634 self.check_gc_during_creation(weakref.ref)
635
636 def test_gc_during_proxy_creation(self):
637 self.check_gc_during_creation(weakref.proxy)
638
639 def check_gc_during_creation(self, makeref):
640 thresholds = gc.get_threshold()
641 gc.set_threshold(1, 1, 1)
642 gc.collect()
Fred Drake55cf4342004-02-13 19:21:57 +0000643 class A:
644 pass
Fred Drakebc875f52004-02-04 23:14:14 +0000645
646 def callback(*args):
647 pass
648
Fred Drake55cf4342004-02-13 19:21:57 +0000649 referenced = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000650
Fred Drake55cf4342004-02-13 19:21:57 +0000651 a = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000652 a.a = a
653 a.wr = makeref(referenced)
654
655 try:
656 # now make sure the object and the ref get labeled as
657 # cyclic trash:
Fred Drake55cf4342004-02-13 19:21:57 +0000658 a = A()
659 weakref.ref(referenced, callback)
Fred Drakebc875f52004-02-04 23:14:14 +0000660
661 finally:
662 gc.set_threshold(*thresholds)
663
Thomas Woutersb2137042007-02-01 18:02:27 +0000664 def test_ref_created_during_del(self):
665 # Bug #1377858
666 # A weakref created in an object's __del__() would crash the
667 # interpreter when the weakref was cleaned up since it would refer to
668 # non-existent memory. This test should not segfault the interpreter.
669 class Target(object):
670 def __del__(self):
671 global ref_from_del
672 ref_from_del = weakref.ref(self)
673
674 w = Target()
675
Benjamin Peterson9aa42992008-09-10 21:57:34 +0000676 def test_init(self):
677 # Issue 3634
678 # <weakref to class>.__init__() doesn't check errors correctly
679 r = weakref.ref(Exception)
680 self.assertRaises(TypeError, r.__init__, 0, 0, 0, 0, 0)
681 # No exception should be raised here
682 gc.collect()
683
Fred Drake0a4dd392004-07-02 18:57:45 +0000684
Amaury Forgeot d'Arcc856c7a2008-06-16 19:50:09 +0000685class SubclassableWeakrefTestCase(TestBase):
Fred Drake0a4dd392004-07-02 18:57:45 +0000686
687 def test_subclass_refs(self):
688 class MyRef(weakref.ref):
689 def __init__(self, ob, callback=None, value=42):
690 self.value = value
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000691 super().__init__(ob, callback)
Fred Drake0a4dd392004-07-02 18:57:45 +0000692 def __call__(self):
693 self.called = True
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000694 return super().__call__()
Fred Drake0a4dd392004-07-02 18:57:45 +0000695 o = Object("foo")
696 mr = MyRef(o, value=24)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000697 self.assertTrue(mr() is o)
698 self.assertTrue(mr.called)
Fred Drake0a4dd392004-07-02 18:57:45 +0000699 self.assertEqual(mr.value, 24)
700 del o
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000701 self.assertTrue(mr() is None)
702 self.assertTrue(mr.called)
Fred Drake0a4dd392004-07-02 18:57:45 +0000703
704 def test_subclass_refs_dont_replace_standard_refs(self):
705 class MyRef(weakref.ref):
706 pass
707 o = Object(42)
708 r1 = MyRef(o)
709 r2 = weakref.ref(o)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000710 self.assertTrue(r1 is not r2)
Fred Drake0a4dd392004-07-02 18:57:45 +0000711 self.assertEqual(weakref.getweakrefs(o), [r2, r1])
712 self.assertEqual(weakref.getweakrefcount(o), 2)
713 r3 = MyRef(o)
714 self.assertEqual(weakref.getweakrefcount(o), 3)
715 refs = weakref.getweakrefs(o)
716 self.assertEqual(len(refs), 3)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000717 self.assertTrue(r2 is refs[0])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000718 self.assertIn(r1, refs[1:])
719 self.assertIn(r3, refs[1:])
Fred Drake0a4dd392004-07-02 18:57:45 +0000720
721 def test_subclass_refs_dont_conflate_callbacks(self):
722 class MyRef(weakref.ref):
723 pass
724 o = Object(42)
725 r1 = MyRef(o, id)
726 r2 = MyRef(o, str)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000727 self.assertTrue(r1 is not r2)
Fred Drake0a4dd392004-07-02 18:57:45 +0000728 refs = weakref.getweakrefs(o)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000729 self.assertIn(r1, refs)
730 self.assertIn(r2, refs)
Fred Drake0a4dd392004-07-02 18:57:45 +0000731
732 def test_subclass_refs_with_slots(self):
733 class MyRef(weakref.ref):
734 __slots__ = "slot1", "slot2"
735 def __new__(type, ob, callback, slot1, slot2):
736 return weakref.ref.__new__(type, ob, callback)
737 def __init__(self, ob, callback, slot1, slot2):
738 self.slot1 = slot1
739 self.slot2 = slot2
740 def meth(self):
741 return self.slot1 + self.slot2
742 o = Object(42)
743 r = MyRef(o, None, "abc", "def")
744 self.assertEqual(r.slot1, "abc")
745 self.assertEqual(r.slot2, "def")
746 self.assertEqual(r.meth(), "abcdef")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000747 self.assertFalse(hasattr(r, "__dict__"))
Fred Drake0a4dd392004-07-02 18:57:45 +0000748
Amaury Forgeot d'Arcc856c7a2008-06-16 19:50:09 +0000749 def test_subclass_refs_with_cycle(self):
750 # Bug #3110
751 # An instance of a weakref subclass can have attributes.
752 # If such a weakref holds the only strong reference to the object,
753 # deleting the weakref will delete the object. In this case,
754 # the callback must not be called, because the ref object is
755 # being deleted.
756 class MyRef(weakref.ref):
757 pass
758
759 # Use a local callback, for "regrtest -R::"
760 # to detect refcounting problems
761 def callback(w):
762 self.cbcalled += 1
763
764 o = C()
765 r1 = MyRef(o, callback)
766 r1.o = o
767 del o
768
769 del r1 # Used to crash here
770
771 self.assertEqual(self.cbcalled, 0)
772
773 # Same test, with two weakrefs to the same object
774 # (since code paths are different)
775 o = C()
776 r1 = MyRef(o, callback)
777 r2 = MyRef(o, callback)
778 r1.r = r2
779 r2.o = o
780 del o
781 del r2
782
783 del r1 # Used to crash here
784
785 self.assertEqual(self.cbcalled, 0)
786
Fred Drake0a4dd392004-07-02 18:57:45 +0000787
Fred Drake41deb1e2001-02-01 05:27:45 +0000788class Object:
789 def __init__(self, arg):
790 self.arg = arg
791 def __repr__(self):
792 return "<Object %r>" % self.arg
Antoine Pitrouc1baa602010-01-08 17:54:23 +0000793 def __eq__(self, other):
794 if isinstance(other, Object):
795 return self.arg == other.arg
796 return NotImplemented
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000797 def __lt__(self, other):
798 if isinstance(other, Object):
799 return self.arg < other.arg
800 return NotImplemented
801 def __hash__(self):
802 return hash(self.arg)
Fred Drake41deb1e2001-02-01 05:27:45 +0000803
Fred Drake41deb1e2001-02-01 05:27:45 +0000804
Fred Drakeb0fefc52001-03-23 04:22:45 +0000805class MappingTestCase(TestBase):
Martin v. Löwis5e163332001-02-27 18:36:56 +0000806
Fred Drakeb0fefc52001-03-23 04:22:45 +0000807 COUNT = 10
808
809 def test_weak_values(self):
Fred Drake0e540c32001-05-02 05:44:22 +0000810 #
811 # This exercises d.copy(), d.items(), d[], del d[], len(d).
812 #
813 dict, objects = self.make_weak_valued_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +0000814 for o in objects:
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000815 self.assertEqual(weakref.getweakrefcount(o), 1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000816 self.assertTrue(o is dict[o.arg],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000817 "wrong object returned by weak dict!")
Barry Warsawecaab832008-09-04 01:42:51 +0000818 items1 = list(dict.items())
819 items2 = list(dict.copy().items())
Fred Drakeb0fefc52001-03-23 04:22:45 +0000820 items1.sort()
821 items2.sort()
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000822 self.assertEqual(items1, items2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000823 "cloning of weak-valued dictionary did not work!")
824 del items1, items2
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000825 self.assertEqual(len(dict), self.COUNT)
Fred Drakeb0fefc52001-03-23 04:22:45 +0000826 del objects[0]
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000827 self.assertEqual(len(dict), self.COUNT - 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000828 "deleting object did not cause dictionary update")
829 del objects, o
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000830 self.assertEqual(len(dict), 0,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000831 "deleting the values did not clear the dictionary")
Fred Drake4fd06e02001-08-03 04:11:27 +0000832 # regression on SF bug #447152:
833 dict = weakref.WeakValueDictionary()
834 self.assertRaises(KeyError, dict.__getitem__, 1)
835 dict[2] = C()
836 self.assertRaises(KeyError, dict.__getitem__, 2)
Fred Drakeb0fefc52001-03-23 04:22:45 +0000837
838 def test_weak_keys(self):
Fred Drake0e540c32001-05-02 05:44:22 +0000839 #
840 # This exercises d.copy(), d.items(), d[] = v, d[], del d[],
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000841 # len(d), k in d.
Fred Drake0e540c32001-05-02 05:44:22 +0000842 #
843 dict, objects = self.make_weak_keyed_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +0000844 for o in objects:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000845 self.assertTrue(weakref.getweakrefcount(o) == 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000846 "wrong number of weak references to %r!" % o)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000847 self.assertTrue(o.arg is dict[o],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000848 "wrong object returned by weak dict!")
849 items1 = dict.items()
850 items2 = dict.copy().items()
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000851 self.assertEqual(set(items1), set(items2),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000852 "cloning of weak-keyed dictionary did not work!")
853 del items1, items2
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000854 self.assertEqual(len(dict), self.COUNT)
Fred Drakeb0fefc52001-03-23 04:22:45 +0000855 del objects[0]
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000856 self.assertTrue(len(dict) == (self.COUNT - 1),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000857 "deleting object did not cause dictionary update")
858 del objects, o
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000859 self.assertTrue(len(dict) == 0,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000860 "deleting the keys did not clear the dictionary")
Fred Drake752eda42001-11-06 16:38:34 +0000861 o = Object(42)
862 dict[o] = "What is the meaning of the universe?"
Benjamin Peterson577473f2010-01-19 00:09:57 +0000863 self.assertIn(o, dict)
864 self.assertNotIn(34, dict)
Martin v. Löwis5e163332001-02-27 18:36:56 +0000865
Fred Drake0e540c32001-05-02 05:44:22 +0000866 def test_weak_keyed_iters(self):
867 dict, objects = self.make_weak_keyed_dict()
868 self.check_iters(dict)
869
Thomas Wouters477c8d52006-05-27 19:21:47 +0000870 # Test keyrefs()
871 refs = dict.keyrefs()
872 self.assertEqual(len(refs), len(objects))
873 objects2 = list(objects)
874 for wr in refs:
875 ob = wr()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000876 self.assertIn(ob, dict)
877 self.assertIn(ob, dict)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000878 self.assertEqual(ob.arg, dict[ob])
879 objects2.remove(ob)
880 self.assertEqual(len(objects2), 0)
881
882 # Test iterkeyrefs()
883 objects2 = list(objects)
Barry Warsawecaab832008-09-04 01:42:51 +0000884 self.assertEqual(len(list(dict.keyrefs())), len(objects))
885 for wr in dict.keyrefs():
Thomas Wouters477c8d52006-05-27 19:21:47 +0000886 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
Fred Drake0e540c32001-05-02 05:44:22 +0000893 def test_weak_valued_iters(self):
894 dict, objects = self.make_weak_valued_dict()
895 self.check_iters(dict)
896
Thomas Wouters477c8d52006-05-27 19:21:47 +0000897 # Test valuerefs()
898 refs = dict.valuerefs()
899 self.assertEqual(len(refs), len(objects))
900 objects2 = list(objects)
901 for wr in refs:
902 ob = wr()
903 self.assertEqual(ob, dict[ob.arg])
904 self.assertEqual(ob.arg, dict[ob.arg].arg)
905 objects2.remove(ob)
906 self.assertEqual(len(objects2), 0)
907
908 # Test itervaluerefs()
909 objects2 = list(objects)
910 self.assertEqual(len(list(dict.itervaluerefs())), len(objects))
911 for wr in dict.itervaluerefs():
912 ob = wr()
913 self.assertEqual(ob, dict[ob.arg])
914 self.assertEqual(ob.arg, dict[ob.arg].arg)
915 objects2.remove(ob)
916 self.assertEqual(len(objects2), 0)
917
Fred Drake0e540c32001-05-02 05:44:22 +0000918 def check_iters(self, dict):
919 # item iterator:
Barry Warsawecaab832008-09-04 01:42:51 +0000920 items = list(dict.items())
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000921 for item in dict.items():
Fred Drake0e540c32001-05-02 05:44:22 +0000922 items.remove(item)
Barry Warsawecaab832008-09-04 01:42:51 +0000923 self.assertFalse(items, "items() did not touch all items")
Fred Drake0e540c32001-05-02 05:44:22 +0000924
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000925 # key iterator, via __iter__():
Guido van Rossum07f24362007-02-11 22:59:48 +0000926 keys = list(dict.keys())
Fred Drake0e540c32001-05-02 05:44:22 +0000927 for k in dict:
928 keys.remove(k)
Barry Warsawecaab832008-09-04 01:42:51 +0000929 self.assertFalse(keys, "__iter__() did not touch all keys")
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000930
931 # key iterator, via iterkeys():
Guido van Rossum07f24362007-02-11 22:59:48 +0000932 keys = list(dict.keys())
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000933 for k in dict.keys():
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000934 keys.remove(k)
Barry Warsawecaab832008-09-04 01:42:51 +0000935 self.assertFalse(keys, "iterkeys() did not touch all keys")
Fred Drake0e540c32001-05-02 05:44:22 +0000936
937 # value iterator:
Guido van Rossum07f24362007-02-11 22:59:48 +0000938 values = list(dict.values())
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000939 for v in dict.values():
Fred Drake0e540c32001-05-02 05:44:22 +0000940 values.remove(v)
Barry Warsawecaab832008-09-04 01:42:51 +0000941 self.assertFalse(values,
Fred Drakef425b1e2003-07-14 21:37:17 +0000942 "itervalues() did not touch all values")
Fred Drake0e540c32001-05-02 05:44:22 +0000943
Antoine Pitrouc1baa602010-01-08 17:54:23 +0000944 def check_weak_destroy_while_iterating(self, dict, objects, iter_name):
945 n = len(dict)
946 it = iter(getattr(dict, iter_name)())
947 next(it) # Trigger internal iteration
948 # Destroy an object
949 del objects[-1]
950 gc.collect() # just in case
951 # We have removed either the first consumed object, or another one
952 self.assertIn(len(list(it)), [len(objects), len(objects) - 1])
953 del it
954 # The removal has been committed
955 self.assertEqual(len(dict), n - 1)
956
957 def check_weak_destroy_and_mutate_while_iterating(self, dict, testcontext):
958 # Check that we can explicitly mutate the weak dict without
959 # interfering with delayed removal.
960 # `testcontext` should create an iterator, destroy one of the
961 # weakref'ed objects and then return a new key/value pair corresponding
962 # to the destroyed object.
963 with testcontext() as (k, v):
964 self.assertFalse(k in dict)
965 with testcontext() as (k, v):
966 self.assertRaises(KeyError, dict.__delitem__, k)
967 self.assertFalse(k in dict)
968 with testcontext() as (k, v):
969 self.assertRaises(KeyError, dict.pop, k)
970 self.assertFalse(k in dict)
971 with testcontext() as (k, v):
972 dict[k] = v
973 self.assertEqual(dict[k], v)
974 ddict = copy.copy(dict)
975 with testcontext() as (k, v):
976 dict.update(ddict)
977 self.assertEqual(dict, ddict)
978 with testcontext() as (k, v):
979 dict.clear()
980 self.assertEqual(len(dict), 0)
981
982 def test_weak_keys_destroy_while_iterating(self):
983 # Issue #7105: iterators shouldn't crash when a key is implicitly removed
984 dict, objects = self.make_weak_keyed_dict()
985 self.check_weak_destroy_while_iterating(dict, objects, 'keys')
986 self.check_weak_destroy_while_iterating(dict, objects, 'items')
987 self.check_weak_destroy_while_iterating(dict, objects, 'values')
988 self.check_weak_destroy_while_iterating(dict, objects, 'keyrefs')
989 dict, objects = self.make_weak_keyed_dict()
990 @contextlib.contextmanager
991 def testcontext():
992 try:
993 it = iter(dict.items())
994 next(it)
995 # Schedule a key/value for removal and recreate it
996 v = objects.pop().arg
997 gc.collect() # just in case
998 yield Object(v), v
999 finally:
1000 it = None # should commit all removals
1001 self.check_weak_destroy_and_mutate_while_iterating(dict, testcontext)
1002
1003 def test_weak_values_destroy_while_iterating(self):
1004 # Issue #7105: iterators shouldn't crash when a key is implicitly removed
1005 dict, objects = self.make_weak_valued_dict()
1006 self.check_weak_destroy_while_iterating(dict, objects, 'keys')
1007 self.check_weak_destroy_while_iterating(dict, objects, 'items')
1008 self.check_weak_destroy_while_iterating(dict, objects, 'values')
1009 self.check_weak_destroy_while_iterating(dict, objects, 'itervaluerefs')
1010 self.check_weak_destroy_while_iterating(dict, objects, 'valuerefs')
1011 dict, objects = self.make_weak_valued_dict()
1012 @contextlib.contextmanager
1013 def testcontext():
1014 try:
1015 it = iter(dict.items())
1016 next(it)
1017 # Schedule a key/value for removal and recreate it
1018 k = objects.pop().arg
1019 gc.collect() # just in case
1020 yield k, Object(k)
1021 finally:
1022 it = None # should commit all removals
1023 self.check_weak_destroy_and_mutate_while_iterating(dict, testcontext)
1024
Guido van Rossum009afb72002-06-10 20:00:52 +00001025 def test_make_weak_keyed_dict_from_dict(self):
1026 o = Object(3)
1027 dict = weakref.WeakKeyDictionary({o:364})
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001028 self.assertEqual(dict[o], 364)
Guido van Rossum009afb72002-06-10 20:00:52 +00001029
1030 def test_make_weak_keyed_dict_from_weak_keyed_dict(self):
1031 o = Object(3)
1032 dict = weakref.WeakKeyDictionary({o:364})
1033 dict2 = weakref.WeakKeyDictionary(dict)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001034 self.assertEqual(dict[o], 364)
Guido van Rossum009afb72002-06-10 20:00:52 +00001035
Fred Drake0e540c32001-05-02 05:44:22 +00001036 def make_weak_keyed_dict(self):
1037 dict = weakref.WeakKeyDictionary()
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001038 objects = list(map(Object, range(self.COUNT)))
Fred Drake0e540c32001-05-02 05:44:22 +00001039 for o in objects:
1040 dict[o] = o.arg
1041 return dict, objects
1042
Antoine Pitrouc06de472009-05-30 21:04:26 +00001043 def test_make_weak_valued_dict_from_dict(self):
1044 o = Object(3)
1045 dict = weakref.WeakValueDictionary({364:o})
1046 self.assertEqual(dict[364], o)
1047
1048 def test_make_weak_valued_dict_from_weak_valued_dict(self):
1049 o = Object(3)
1050 dict = weakref.WeakValueDictionary({364:o})
1051 dict2 = weakref.WeakValueDictionary(dict)
1052 self.assertEqual(dict[364], o)
1053
Fred Drake0e540c32001-05-02 05:44:22 +00001054 def make_weak_valued_dict(self):
1055 dict = weakref.WeakValueDictionary()
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001056 objects = list(map(Object, range(self.COUNT)))
Fred Drake0e540c32001-05-02 05:44:22 +00001057 for o in objects:
1058 dict[o.arg] = o
1059 return dict, objects
1060
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001061 def check_popitem(self, klass, key1, value1, key2, value2):
1062 weakdict = klass()
1063 weakdict[key1] = value1
1064 weakdict[key2] = value2
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001065 self.assertEqual(len(weakdict), 2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001066 k, v = weakdict.popitem()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001067 self.assertEqual(len(weakdict), 1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001068 if k is key1:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001069 self.assertTrue(v is value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001070 else:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001071 self.assertTrue(v is value2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001072 k, v = weakdict.popitem()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001073 self.assertEqual(len(weakdict), 0)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001074 if k is key1:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001075 self.assertTrue(v is value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001076 else:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001077 self.assertTrue(v is value2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001078
1079 def test_weak_valued_dict_popitem(self):
1080 self.check_popitem(weakref.WeakValueDictionary,
1081 "key1", C(), "key2", C())
1082
1083 def test_weak_keyed_dict_popitem(self):
1084 self.check_popitem(weakref.WeakKeyDictionary,
1085 C(), "value 1", C(), "value 2")
1086
1087 def check_setdefault(self, klass, key, value1, value2):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001088 self.assertTrue(value1 is not value2,
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001089 "invalid test"
1090 " -- value parameters must be distinct objects")
1091 weakdict = klass()
1092 o = weakdict.setdefault(key, value1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001093 self.assertTrue(o is value1)
Benjamin Peterson577473f2010-01-19 00:09:57 +00001094 self.assertIn(key, weakdict)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001095 self.assertTrue(weakdict.get(key) is value1)
1096 self.assertTrue(weakdict[key] is value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001097
1098 o = weakdict.setdefault(key, value2)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001099 self.assertTrue(o is value1)
Benjamin Peterson577473f2010-01-19 00:09:57 +00001100 self.assertIn(key, weakdict)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001101 self.assertTrue(weakdict.get(key) is value1)
1102 self.assertTrue(weakdict[key] is value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001103
1104 def test_weak_valued_dict_setdefault(self):
1105 self.check_setdefault(weakref.WeakValueDictionary,
1106 "key", C(), C())
1107
1108 def test_weak_keyed_dict_setdefault(self):
1109 self.check_setdefault(weakref.WeakKeyDictionary,
1110 C(), "value 1", "value 2")
1111
Fred Drakea0a4ab12001-04-16 17:37:27 +00001112 def check_update(self, klass, dict):
Fred Drake0e540c32001-05-02 05:44:22 +00001113 #
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001114 # This exercises d.update(), len(d), d.keys(), k in d,
Fred Drake0e540c32001-05-02 05:44:22 +00001115 # d.get(), d[].
1116 #
Fred Drakea0a4ab12001-04-16 17:37:27 +00001117 weakdict = klass()
1118 weakdict.update(dict)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001119 self.assertEqual(len(weakdict), len(dict))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001120 for k in weakdict.keys():
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001121 self.assertTrue(k in dict,
Fred Drakea0a4ab12001-04-16 17:37:27 +00001122 "mysterious new key appeared in weak dict")
1123 v = dict.get(k)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001124 self.assertTrue(v is weakdict[k])
1125 self.assertTrue(v is weakdict.get(k))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001126 for k in dict.keys():
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001127 self.assertTrue(k in weakdict,
Fred Drakea0a4ab12001-04-16 17:37:27 +00001128 "original key disappeared in weak dict")
1129 v = dict[k]
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001130 self.assertTrue(v is weakdict[k])
1131 self.assertTrue(v is weakdict.get(k))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001132
1133 def test_weak_valued_dict_update(self):
1134 self.check_update(weakref.WeakValueDictionary,
1135 {1: C(), 'a': C(), C(): C()})
1136
1137 def test_weak_keyed_dict_update(self):
1138 self.check_update(weakref.WeakKeyDictionary,
1139 {C(): 1, C(): 2, C(): 3})
1140
Fred Drakeccc75622001-09-06 14:52:39 +00001141 def test_weak_keyed_delitem(self):
1142 d = weakref.WeakKeyDictionary()
1143 o1 = Object('1')
1144 o2 = Object('2')
1145 d[o1] = 'something'
1146 d[o2] = 'something'
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001147 self.assertEqual(len(d), 2)
Fred Drakeccc75622001-09-06 14:52:39 +00001148 del d[o1]
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001149 self.assertEqual(len(d), 1)
Barry Warsawecaab832008-09-04 01:42:51 +00001150 self.assertEqual(list(d.keys()), [o2])
Fred Drakeccc75622001-09-06 14:52:39 +00001151
1152 def test_weak_valued_delitem(self):
1153 d = weakref.WeakValueDictionary()
1154 o1 = Object('1')
1155 o2 = Object('2')
1156 d['something'] = o1
1157 d['something else'] = o2
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001158 self.assertEqual(len(d), 2)
Fred Drakeccc75622001-09-06 14:52:39 +00001159 del d['something']
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001160 self.assertEqual(len(d), 1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001161 self.assertTrue(list(d.items()) == [('something else', o2)])
Fred Drakeccc75622001-09-06 14:52:39 +00001162
Tim Peters886128f2003-05-25 01:45:11 +00001163 def test_weak_keyed_bad_delitem(self):
1164 d = weakref.WeakKeyDictionary()
1165 o = Object('1')
1166 # An attempt to delete an object that isn't there should raise
Tim Peters50d8b8b2003-05-25 17:44:31 +00001167 # KeyError. It didn't before 2.3.
Tim Peters886128f2003-05-25 01:45:11 +00001168 self.assertRaises(KeyError, d.__delitem__, o)
Tim Peters50d8b8b2003-05-25 17:44:31 +00001169 self.assertRaises(KeyError, d.__getitem__, o)
1170
1171 # If a key isn't of a weakly referencable type, __getitem__ and
1172 # __setitem__ raise TypeError. __delitem__ should too.
1173 self.assertRaises(TypeError, d.__delitem__, 13)
1174 self.assertRaises(TypeError, d.__getitem__, 13)
1175 self.assertRaises(TypeError, d.__setitem__, 13, 13)
Tim Peters886128f2003-05-25 01:45:11 +00001176
1177 def test_weak_keyed_cascading_deletes(self):
1178 # SF bug 742860. For some reason, before 2.3 __delitem__ iterated
1179 # over the keys via self.data.iterkeys(). If things vanished from
1180 # the dict during this (or got added), that caused a RuntimeError.
1181
1182 d = weakref.WeakKeyDictionary()
1183 mutate = False
1184
1185 class C(object):
1186 def __init__(self, i):
1187 self.value = i
1188 def __hash__(self):
1189 return hash(self.value)
1190 def __eq__(self, other):
1191 if mutate:
1192 # Side effect that mutates the dict, by removing the
1193 # last strong reference to a key.
1194 del objs[-1]
1195 return self.value == other.value
1196
1197 objs = [C(i) for i in range(4)]
1198 for o in objs:
1199 d[o] = o.value
1200 del o # now the only strong references to keys are in objs
1201 # Find the order in which iterkeys sees the keys.
Barry Warsawecaab832008-09-04 01:42:51 +00001202 objs = list(d.keys())
Tim Peters886128f2003-05-25 01:45:11 +00001203 # Reverse it, so that the iteration implementation of __delitem__
1204 # has to keep looping to find the first object we delete.
1205 objs.reverse()
Tim Peters50d8b8b2003-05-25 17:44:31 +00001206
Tim Peters886128f2003-05-25 01:45:11 +00001207 # Turn on mutation in C.__eq__. The first time thru the loop,
1208 # under the iterkeys() business the first comparison will delete
1209 # the last item iterkeys() would see, and that causes a
1210 # RuntimeError: dictionary changed size during iteration
1211 # when the iterkeys() loop goes around to try comparing the next
Tim Peters50d8b8b2003-05-25 17:44:31 +00001212 # key. After this was fixed, it just deletes the last object *our*
Tim Peters886128f2003-05-25 01:45:11 +00001213 # "for o in obj" loop would have gotten to.
1214 mutate = True
1215 count = 0
1216 for o in objs:
1217 count += 1
1218 del d[o]
1219 self.assertEqual(len(d), 0)
1220 self.assertEqual(count, 2)
1221
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001222from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001223
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001224class WeakValueDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +00001225 """Check that WeakValueDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001226 __ref = {"key1":Object(1), "key2":Object(2), "key3":Object(3)}
Walter Dörwald118f9312004-06-02 18:42:25 +00001227 type2test = weakref.WeakValueDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001228 def _reference(self):
1229 return self.__ref.copy()
1230
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001231class WeakKeyDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +00001232 """Check that WeakKeyDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001233 __ref = {Object("key1"):1, Object("key2"):2, Object("key3"):3}
Walter Dörwald118f9312004-06-02 18:42:25 +00001234 type2test = weakref.WeakKeyDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001235 def _reference(self):
1236 return self.__ref.copy()
Martin v. Löwis5e163332001-02-27 18:36:56 +00001237
Georg Brandlb533e262008-05-25 18:19:30 +00001238libreftest = """ Doctest for examples in the library reference: weakref.rst
Georg Brandl9a65d582005-07-02 19:07:30 +00001239
1240>>> import weakref
1241>>> class Dict(dict):
1242... pass
1243...
1244>>> obj = Dict(red=1, green=2, blue=3) # this object is weak referencable
1245>>> r = weakref.ref(obj)
Guido van Rossum7131f842007-02-09 20:13:25 +00001246>>> print(r() is obj)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001247True
Georg Brandl9a65d582005-07-02 19:07:30 +00001248
1249>>> import weakref
1250>>> class Object:
1251... pass
1252...
1253>>> o = Object()
1254>>> r = weakref.ref(o)
1255>>> o2 = r()
1256>>> o is o2
1257True
1258>>> del o, o2
Guido van Rossum7131f842007-02-09 20:13:25 +00001259>>> print(r())
Georg Brandl9a65d582005-07-02 19:07:30 +00001260None
1261
1262>>> import weakref
1263>>> class ExtendedRef(weakref.ref):
1264... def __init__(self, ob, callback=None, **annotations):
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001265... super().__init__(ob, callback)
Georg Brandl9a65d582005-07-02 19:07:30 +00001266... self.__counter = 0
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001267... for k, v in annotations.items():
Georg Brandl9a65d582005-07-02 19:07:30 +00001268... setattr(self, k, v)
1269... def __call__(self):
1270... '''Return a pair containing the referent and the number of
1271... times the reference has been called.
1272... '''
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001273... ob = super().__call__()
Georg Brandl9a65d582005-07-02 19:07:30 +00001274... if ob is not None:
1275... self.__counter += 1
1276... ob = (ob, self.__counter)
1277... return ob
Guido van Rossumd8faa362007-04-27 19:54:29 +00001278...
Georg Brandl9a65d582005-07-02 19:07:30 +00001279>>> class A: # not in docs from here, just testing the ExtendedRef
1280... pass
1281...
1282>>> a = A()
1283>>> r = ExtendedRef(a, foo=1, bar="baz")
1284>>> r.foo
12851
1286>>> r.bar
1287'baz'
1288>>> r()[1]
12891
1290>>> r()[1]
12912
1292>>> r()[0] is a
1293True
1294
1295
1296>>> import weakref
1297>>> _id2obj_dict = weakref.WeakValueDictionary()
1298>>> def remember(obj):
1299... oid = id(obj)
1300... _id2obj_dict[oid] = obj
1301... return oid
1302...
1303>>> def id2obj(oid):
1304... return _id2obj_dict[oid]
1305...
1306>>> a = A() # from here, just testing
1307>>> a_id = remember(a)
1308>>> id2obj(a_id) is a
1309True
1310>>> del a
1311>>> try:
1312... id2obj(a_id)
1313... except KeyError:
Guido van Rossum7131f842007-02-09 20:13:25 +00001314... print('OK')
Georg Brandl9a65d582005-07-02 19:07:30 +00001315... else:
Guido van Rossum7131f842007-02-09 20:13:25 +00001316... print('WeakValueDictionary error')
Georg Brandl9a65d582005-07-02 19:07:30 +00001317OK
1318
1319"""
1320
1321__test__ = {'libreftest' : libreftest}
1322
Fred Drake2e2be372001-09-20 21:33:42 +00001323def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001324 support.run_unittest(
Walter Dörwald21d3a322003-05-01 17:45:56 +00001325 ReferencesTestCase,
1326 MappingTestCase,
1327 WeakValueDictionaryTestCase,
Fred Drakef425b1e2003-07-14 21:37:17 +00001328 WeakKeyDictionaryTestCase,
Amaury Forgeot d'Arcc856c7a2008-06-16 19:50:09 +00001329 SubclassableWeakrefTestCase,
Fred Drakef425b1e2003-07-14 21:37:17 +00001330 )
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001331 support.run_doctest(sys.modules[__name__])
Fred Drake2e2be372001-09-20 21:33:42 +00001332
1333
1334if __name__ == "__main__":
1335 test_main()