blob: f49cb7e591fac28522beac32b66c61e12f28c301 [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
Berker Peksagce643912015-05-06 06:33:17 +030010from test import support
11from test.support import script_helper
Fred Drake41deb1e2001-02-01 05:27:45 +000012
Thomas Woutersb2137042007-02-01 18:02:27 +000013# Used in ReferencesTestCase.test_ref_created_during_del() .
14ref_from_del = None
Fred Drake41deb1e2001-02-01 05:27:45 +000015
Richard Oudkerk7a3dae02013-05-05 23:05:00 +010016# Used by FinalizeTestCase as a global that may be replaced by None
17# when the interpreter shuts down.
18_global_var = 'foobar'
19
Fred Drake41deb1e2001-02-01 05:27:45 +000020class C:
Fred Drakeb0fefc52001-03-23 04:22:45 +000021 def method(self):
22 pass
Fred Drake41deb1e2001-02-01 05:27:45 +000023
24
Fred Drakeb0fefc52001-03-23 04:22:45 +000025class Callable:
26 bar = None
Fred Drake41deb1e2001-02-01 05:27:45 +000027
Fred Drakeb0fefc52001-03-23 04:22:45 +000028 def __call__(self, x):
29 self.bar = x
Fred Drake41deb1e2001-02-01 05:27:45 +000030
31
Fred Drakeb0fefc52001-03-23 04:22:45 +000032def create_function():
33 def f(): pass
34 return f
35
36def create_bound_method():
37 return C().method
38
Fred Drake41deb1e2001-02-01 05:27:45 +000039
Antoine Pitroue11fecb2012-11-11 19:36:51 +010040class Object:
41 def __init__(self, arg):
42 self.arg = arg
43 def __repr__(self):
44 return "<Object %r>" % self.arg
45 def __eq__(self, other):
46 if isinstance(other, Object):
47 return self.arg == other.arg
48 return NotImplemented
49 def __lt__(self, other):
50 if isinstance(other, Object):
51 return self.arg < other.arg
52 return NotImplemented
53 def __hash__(self):
54 return hash(self.arg)
Antoine Pitrouc3afba12012-11-17 18:57:38 +010055 def some_method(self):
56 return 4
57 def other_method(self):
58 return 5
59
Antoine Pitroue11fecb2012-11-11 19:36:51 +010060
61class RefCycle:
62 def __init__(self):
63 self.cycle = self
64
65
Fred Drakeb0fefc52001-03-23 04:22:45 +000066class TestBase(unittest.TestCase):
67
68 def setUp(self):
69 self.cbcalled = 0
70
71 def callback(self, ref):
72 self.cbcalled += 1
Fred Drake41deb1e2001-02-01 05:27:45 +000073
74
Fred Drakeb0fefc52001-03-23 04:22:45 +000075class ReferencesTestCase(TestBase):
Fred Drake41deb1e2001-02-01 05:27:45 +000076
Fred Drakeb0fefc52001-03-23 04:22:45 +000077 def test_basic_ref(self):
78 self.check_basic_ref(C)
79 self.check_basic_ref(create_function)
80 self.check_basic_ref(create_bound_method)
Fred Drake41deb1e2001-02-01 05:27:45 +000081
Fred Drake43735da2002-04-11 03:59:42 +000082 # Just make sure the tp_repr handler doesn't raise an exception.
83 # Live reference:
84 o = C()
85 wr = weakref.ref(o)
Brett Cannon0b70cca2006-08-25 02:59:59 +000086 repr(wr)
Fred Drake43735da2002-04-11 03:59:42 +000087 # Dead reference:
88 del o
Brett Cannon0b70cca2006-08-25 02:59:59 +000089 repr(wr)
Fred Drake43735da2002-04-11 03:59:42 +000090
Fred Drakeb0fefc52001-03-23 04:22:45 +000091 def test_basic_callback(self):
92 self.check_basic_callback(C)
93 self.check_basic_callback(create_function)
94 self.check_basic_callback(create_bound_method)
Fred Drake41deb1e2001-02-01 05:27:45 +000095
Antoine Pitroub349e4c2014-08-06 19:31:40 -040096 @support.cpython_only
97 def test_cfunction(self):
98 import _testcapi
99 create_cfunction = _testcapi.create_cfunction
100 f = create_cfunction()
101 wr = weakref.ref(f)
102 self.assertIs(wr(), f)
103 del f
104 self.assertIsNone(wr())
105 self.check_basic_ref(create_cfunction)
106 self.check_basic_callback(create_cfunction)
107
Fred Drakeb0fefc52001-03-23 04:22:45 +0000108 def test_multiple_callbacks(self):
109 o = C()
110 ref1 = weakref.ref(o, self.callback)
111 ref2 = weakref.ref(o, self.callback)
112 del o
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200113 self.assertIsNone(ref1(), "expected reference to be invalidated")
114 self.assertIsNone(ref2(), "expected reference to be invalidated")
115 self.assertEqual(self.cbcalled, 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000116 "callback not called the right number of times")
Fred Drake41deb1e2001-02-01 05:27:45 +0000117
Fred Drake705088e2001-04-13 17:18:15 +0000118 def test_multiple_selfref_callbacks(self):
Guido van Rossum9eee5542002-08-22 20:21:30 +0000119 # Make sure all references are invalidated before callbacks are called
Fred Drake705088e2001-04-13 17:18:15 +0000120 #
121 # What's important here is that we're using the first
122 # reference in the callback invoked on the second reference
123 # (the most recently created ref is cleaned up first). This
124 # tests that all references to the object are invalidated
125 # before any of the callbacks are invoked, so that we only
126 # have one invocation of _weakref.c:cleanup_helper() active
127 # for a particular object at a time.
128 #
129 def callback(object, self=self):
130 self.ref()
131 c = C()
132 self.ref = weakref.ref(c, callback)
133 ref1 = weakref.ref(c, callback)
134 del c
135
Serhiy Storchaka21eb4872016-05-07 15:41:09 +0300136 def test_constructor_kwargs(self):
137 c = C()
138 self.assertRaises(TypeError, weakref.ref, c, callback=None)
139
Fred Drakeb0fefc52001-03-23 04:22:45 +0000140 def test_proxy_ref(self):
141 o = C()
142 o.bar = 1
143 ref1 = weakref.proxy(o, self.callback)
144 ref2 = weakref.proxy(o, self.callback)
145 del o
Fred Drake41deb1e2001-02-01 05:27:45 +0000146
Fred Drakeb0fefc52001-03-23 04:22:45 +0000147 def check(proxy):
148 proxy.bar
Fred Drake41deb1e2001-02-01 05:27:45 +0000149
Neal Norwitz2633c692007-02-26 22:22:47 +0000150 self.assertRaises(ReferenceError, check, ref1)
151 self.assertRaises(ReferenceError, check, ref2)
152 self.assertRaises(ReferenceError, bool, weakref.proxy(C()))
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000153 self.assertEqual(self.cbcalled, 2)
Fred Drake41deb1e2001-02-01 05:27:45 +0000154
Fred Drakeb0fefc52001-03-23 04:22:45 +0000155 def check_basic_ref(self, factory):
156 o = factory()
157 ref = weakref.ref(o)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200158 self.assertIsNotNone(ref(),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000159 "weak reference to live object should be live")
160 o2 = ref()
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200161 self.assertIs(o, o2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000162 "<ref>() should return original object if live")
Fred Drake41deb1e2001-02-01 05:27:45 +0000163
Fred Drakeb0fefc52001-03-23 04:22:45 +0000164 def check_basic_callback(self, factory):
165 self.cbcalled = 0
166 o = factory()
167 ref = weakref.ref(o, self.callback)
168 del o
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200169 self.assertEqual(self.cbcalled, 1,
Fred Drake705088e2001-04-13 17:18:15 +0000170 "callback did not properly set 'cbcalled'")
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200171 self.assertIsNone(ref(),
Fred Drake705088e2001-04-13 17:18:15 +0000172 "ref2 should be dead after deleting object reference")
Fred Drake41deb1e2001-02-01 05:27:45 +0000173
Fred Drakeb0fefc52001-03-23 04:22:45 +0000174 def test_ref_reuse(self):
175 o = C()
176 ref1 = weakref.ref(o)
177 # create a proxy to make sure that there's an intervening creation
178 # between these two; it should make no difference
179 proxy = weakref.proxy(o)
180 ref2 = weakref.ref(o)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200181 self.assertIs(ref1, ref2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000182 "reference object w/out callback should be re-used")
Fred Drake41deb1e2001-02-01 05:27:45 +0000183
Fred Drakeb0fefc52001-03-23 04:22:45 +0000184 o = C()
185 proxy = weakref.proxy(o)
186 ref1 = weakref.ref(o)
187 ref2 = weakref.ref(o)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200188 self.assertIs(ref1, ref2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000189 "reference object w/out callback should be re-used")
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200190 self.assertEqual(weakref.getweakrefcount(o), 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000191 "wrong weak ref count for object")
192 del proxy
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200193 self.assertEqual(weakref.getweakrefcount(o), 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000194 "wrong weak ref count for object after deleting proxy")
Fred Drake41deb1e2001-02-01 05:27:45 +0000195
Fred Drakeb0fefc52001-03-23 04:22:45 +0000196 def test_proxy_reuse(self):
197 o = C()
198 proxy1 = weakref.proxy(o)
199 ref = weakref.ref(o)
200 proxy2 = weakref.proxy(o)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200201 self.assertIs(proxy1, proxy2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000202 "proxy object w/out callback should have been re-used")
203
204 def test_basic_proxy(self):
205 o = C()
206 self.check_proxy(o, weakref.proxy(o))
207
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000208 L = collections.UserList()
Fred Drake5935ff02001-12-19 16:54:23 +0000209 p = weakref.proxy(L)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000210 self.assertFalse(p, "proxy for empty UserList should be false")
Fred Drake5935ff02001-12-19 16:54:23 +0000211 p.append(12)
212 self.assertEqual(len(L), 1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000213 self.assertTrue(p, "proxy for non-empty UserList should be true")
Fred Drake5935ff02001-12-19 16:54:23 +0000214 p[:] = [2, 3]
215 self.assertEqual(len(L), 2)
216 self.assertEqual(len(p), 2)
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000217 self.assertIn(3, p, "proxy didn't support __contains__() properly")
Fred Drake5935ff02001-12-19 16:54:23 +0000218 p[1] = 5
219 self.assertEqual(L[1], 5)
220 self.assertEqual(p[1], 5)
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000221 L2 = collections.UserList(L)
Fred Drake5935ff02001-12-19 16:54:23 +0000222 p2 = weakref.proxy(L2)
223 self.assertEqual(p, p2)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000224 ## self.assertEqual(repr(L2), repr(p2))
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000225 L3 = collections.UserList(range(10))
Fred Drake43735da2002-04-11 03:59:42 +0000226 p3 = weakref.proxy(L3)
227 self.assertEqual(L3[:], p3[:])
228 self.assertEqual(L3[5:], p3[5:])
229 self.assertEqual(L3[:5], p3[:5])
230 self.assertEqual(L3[2:5], p3[2:5])
Fred Drake5935ff02001-12-19 16:54:23 +0000231
Benjamin Peterson32019772009-11-19 03:08:32 +0000232 def test_proxy_unicode(self):
233 # See bug 5037
234 class C(object):
235 def __str__(self):
236 return "string"
237 def __bytes__(self):
238 return b"bytes"
239 instance = C()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000240 self.assertIn("__bytes__", dir(weakref.proxy(instance)))
Benjamin Peterson32019772009-11-19 03:08:32 +0000241 self.assertEqual(bytes(weakref.proxy(instance)), b"bytes")
242
Georg Brandlb533e262008-05-25 18:19:30 +0000243 def test_proxy_index(self):
244 class C:
245 def __index__(self):
246 return 10
247 o = C()
248 p = weakref.proxy(o)
249 self.assertEqual(operator.index(p), 10)
250
251 def test_proxy_div(self):
252 class C:
253 def __floordiv__(self, other):
254 return 42
255 def __ifloordiv__(self, other):
256 return 21
257 o = C()
258 p = weakref.proxy(o)
259 self.assertEqual(p // 5, 42)
260 p //= 5
261 self.assertEqual(p, 21)
262
Fred Drakeea2adc92004-02-03 19:56:46 +0000263 # The PyWeakref_* C API is documented as allowing either NULL or
264 # None as the value for the callback, where either means "no
265 # callback". The "no callback" ref and proxy objects are supposed
266 # to be shared so long as they exist by all callers so long as
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000267 # they are active. In Python 2.3.3 and earlier, this guarantee
Fred Drakeea2adc92004-02-03 19:56:46 +0000268 # was not honored, and was broken in different ways for
269 # PyWeakref_NewRef() and PyWeakref_NewProxy(). (Two tests.)
270
271 def test_shared_ref_without_callback(self):
272 self.check_shared_without_callback(weakref.ref)
273
274 def test_shared_proxy_without_callback(self):
275 self.check_shared_without_callback(weakref.proxy)
276
277 def check_shared_without_callback(self, makeref):
278 o = Object(1)
279 p1 = makeref(o, None)
280 p2 = makeref(o, None)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200281 self.assertIs(p1, p2, "both callbacks were None in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000282 del p1, p2
283 p1 = makeref(o)
284 p2 = makeref(o, None)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200285 self.assertIs(p1, p2, "callbacks were NULL, None in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000286 del p1, p2
287 p1 = makeref(o)
288 p2 = makeref(o)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200289 self.assertIs(p1, p2, "both callbacks were NULL in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000290 del p1, p2
291 p1 = makeref(o, None)
292 p2 = makeref(o)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200293 self.assertIs(p1, p2, "callbacks were None, NULL in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000294
Fred Drakeb0fefc52001-03-23 04:22:45 +0000295 def test_callable_proxy(self):
296 o = Callable()
297 ref1 = weakref.proxy(o)
298
299 self.check_proxy(o, ref1)
300
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200301 self.assertIs(type(ref1), weakref.CallableProxyType,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000302 "proxy is not of callable type")
303 ref1('twinkies!')
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200304 self.assertEqual(o.bar, 'twinkies!',
Fred Drakeb0fefc52001-03-23 04:22:45 +0000305 "call through proxy not passed through to original")
Fred Drake3bb4d212001-10-18 19:28:29 +0000306 ref1(x='Splat.')
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200307 self.assertEqual(o.bar, 'Splat.',
Fred Drake3bb4d212001-10-18 19:28:29 +0000308 "call through proxy not passed through to original")
Fred Drakeb0fefc52001-03-23 04:22:45 +0000309
310 # expect due to too few args
311 self.assertRaises(TypeError, ref1)
312
313 # expect due to too many args
314 self.assertRaises(TypeError, ref1, 1, 2, 3)
315
316 def check_proxy(self, o, proxy):
317 o.foo = 1
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200318 self.assertEqual(proxy.foo, 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000319 "proxy does not reflect attribute addition")
320 o.foo = 2
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200321 self.assertEqual(proxy.foo, 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000322 "proxy does not reflect attribute modification")
323 del o.foo
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200324 self.assertFalse(hasattr(proxy, 'foo'),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000325 "proxy does not reflect attribute removal")
326
327 proxy.foo = 1
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200328 self.assertEqual(o.foo, 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000329 "object does not reflect attribute addition via proxy")
330 proxy.foo = 2
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200331 self.assertEqual(o.foo, 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000332 "object does not reflect attribute modification via proxy")
333 del proxy.foo
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200334 self.assertFalse(hasattr(o, 'foo'),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000335 "object does not reflect attribute removal via proxy")
336
Raymond Hettingerd693a812003-06-30 04:18:48 +0000337 def test_proxy_deletion(self):
338 # Test clearing of SF bug #762891
339 class Foo:
340 result = None
341 def __delitem__(self, accessor):
342 self.result = accessor
343 g = Foo()
344 f = weakref.proxy(g)
345 del f[0]
346 self.assertEqual(f.result, 0)
347
Raymond Hettingere6c470f2005-03-27 03:04:54 +0000348 def test_proxy_bool(self):
349 # Test clearing of SF bug #1170766
350 class List(list): pass
351 lyst = List()
352 self.assertEqual(bool(weakref.proxy(lyst)), bool(lyst))
353
Fred Drakeb0fefc52001-03-23 04:22:45 +0000354 def test_getweakrefcount(self):
355 o = C()
356 ref1 = weakref.ref(o)
357 ref2 = weakref.ref(o, self.callback)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200358 self.assertEqual(weakref.getweakrefcount(o), 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000359 "got wrong number of weak reference objects")
360
361 proxy1 = weakref.proxy(o)
362 proxy2 = weakref.proxy(o, self.callback)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200363 self.assertEqual(weakref.getweakrefcount(o), 4,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000364 "got wrong number of weak reference objects")
365
Fred Drakeea2adc92004-02-03 19:56:46 +0000366 del ref1, ref2, proxy1, proxy2
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200367 self.assertEqual(weakref.getweakrefcount(o), 0,
Fred Drakeea2adc92004-02-03 19:56:46 +0000368 "weak reference objects not unlinked from"
369 " referent when discarded.")
370
Walter Dörwaldb167b042003-12-11 12:34:05 +0000371 # assumes ints do not support weakrefs
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200372 self.assertEqual(weakref.getweakrefcount(1), 0,
Walter Dörwaldb167b042003-12-11 12:34:05 +0000373 "got wrong number of weak reference objects for int")
374
Fred Drakeb0fefc52001-03-23 04:22:45 +0000375 def test_getweakrefs(self):
376 o = C()
377 ref1 = weakref.ref(o, self.callback)
378 ref2 = weakref.ref(o, self.callback)
379 del ref1
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200380 self.assertEqual(weakref.getweakrefs(o), [ref2],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000381 "list of refs does not match")
382
383 o = C()
384 ref1 = weakref.ref(o, self.callback)
385 ref2 = weakref.ref(o, self.callback)
386 del ref2
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200387 self.assertEqual(weakref.getweakrefs(o), [ref1],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000388 "list of refs does not match")
389
Fred Drakeea2adc92004-02-03 19:56:46 +0000390 del ref1
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200391 self.assertEqual(weakref.getweakrefs(o), [],
Fred Drakeea2adc92004-02-03 19:56:46 +0000392 "list of refs not cleared")
393
Walter Dörwaldb167b042003-12-11 12:34:05 +0000394 # assumes ints do not support weakrefs
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200395 self.assertEqual(weakref.getweakrefs(1), [],
Walter Dörwaldb167b042003-12-11 12:34:05 +0000396 "list of refs does not match for int")
397
Fred Drake39c27f12001-10-18 18:06:05 +0000398 def test_newstyle_number_ops(self):
399 class F(float):
400 pass
401 f = F(2.0)
402 p = weakref.proxy(f)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200403 self.assertEqual(p + 1.0, 3.0)
404 self.assertEqual(1.0 + p, 3.0) # this used to SEGV
Fred Drake39c27f12001-10-18 18:06:05 +0000405
Fred Drake2a64f462001-12-10 23:46:02 +0000406 def test_callbacks_protected(self):
Guido van Rossum9eee5542002-08-22 20:21:30 +0000407 # Callbacks protected from already-set exceptions?
Fred Drake2a64f462001-12-10 23:46:02 +0000408 # Regression test for SF bug #478534.
409 class BogusError(Exception):
410 pass
411 data = {}
412 def remove(k):
413 del data[k]
414 def encapsulate():
415 f = lambda : ()
416 data[weakref.ref(f, remove)] = None
417 raise BogusError
418 try:
419 encapsulate()
420 except BogusError:
421 pass
422 else:
423 self.fail("exception not properly restored")
424 try:
425 encapsulate()
426 except BogusError:
427 pass
428 else:
429 self.fail("exception not properly restored")
430
Tim Petersadd09b42003-11-12 20:43:28 +0000431 def test_sf_bug_840829(self):
432 # "weakref callbacks and gc corrupt memory"
433 # subtype_dealloc erroneously exposed a new-style instance
434 # already in the process of getting deallocated to gc,
435 # causing double-deallocation if the instance had a weakref
436 # callback that triggered gc.
437 # If the bug exists, there probably won't be an obvious symptom
438 # in a release build. In a debug build, a segfault will occur
439 # when the second attempt to remove the instance from the "list
440 # of all objects" occurs.
441
442 import gc
443
444 class C(object):
445 pass
446
447 c = C()
448 wr = weakref.ref(c, lambda ignore: gc.collect())
449 del c
450
Tim Petersf7f9e992003-11-13 21:59:32 +0000451 # There endeth the first part. It gets worse.
452 del wr
453
454 c1 = C()
455 c1.i = C()
456 wr = weakref.ref(c1.i, lambda ignore: gc.collect())
457
458 c2 = C()
459 c2.c1 = c1
460 del c1 # still alive because c2 points to it
461
462 # Now when subtype_dealloc gets called on c2, it's not enough just
463 # that c2 is immune from gc while the weakref callbacks associated
464 # with c2 execute (there are none in this 2nd half of the test, btw).
465 # subtype_dealloc goes on to call the base classes' deallocs too,
466 # so any gc triggered by weakref callbacks associated with anything
467 # torn down by a base class dealloc can also trigger double
468 # deallocation of c2.
469 del c2
Fred Drake41deb1e2001-02-01 05:27:45 +0000470
Tim Peters403a2032003-11-20 21:21:46 +0000471 def test_callback_in_cycle_1(self):
472 import gc
473
474 class J(object):
475 pass
476
477 class II(object):
478 def acallback(self, ignore):
479 self.J
480
481 I = II()
482 I.J = J
483 I.wr = weakref.ref(J, I.acallback)
484
485 # Now J and II are each in a self-cycle (as all new-style class
486 # objects are, since their __mro__ points back to them). I holds
487 # both a weak reference (I.wr) and a strong reference (I.J) to class
488 # J. I is also in a cycle (I.wr points to a weakref that references
489 # I.acallback). When we del these three, they all become trash, but
490 # the cycles prevent any of them from getting cleaned up immediately.
491 # Instead they have to wait for cyclic gc to deduce that they're
492 # trash.
493 #
494 # gc used to call tp_clear on all of them, and the order in which
495 # it does that is pretty accidental. The exact order in which we
496 # built up these things manages to provoke gc into running tp_clear
497 # in just the right order (I last). Calling tp_clear on II leaves
498 # behind an insane class object (its __mro__ becomes NULL). Calling
499 # tp_clear on J breaks its self-cycle, but J doesn't get deleted
500 # just then because of the strong reference from I.J. Calling
501 # tp_clear on I starts to clear I's __dict__, and just happens to
502 # clear I.J first -- I.wr is still intact. That removes the last
503 # reference to J, which triggers the weakref callback. The callback
504 # tries to do "self.J", and instances of new-style classes look up
505 # attributes ("J") in the class dict first. The class (II) wants to
506 # search II.__mro__, but that's NULL. The result was a segfault in
507 # a release build, and an assert failure in a debug build.
508 del I, J, II
509 gc.collect()
510
511 def test_callback_in_cycle_2(self):
512 import gc
513
514 # This is just like test_callback_in_cycle_1, except that II is an
515 # old-style class. The symptom is different then: an instance of an
516 # old-style class looks in its own __dict__ first. 'J' happens to
517 # get cleared from I.__dict__ before 'wr', and 'J' was never in II's
518 # __dict__, so the attribute isn't found. The difference is that
519 # the old-style II doesn't have a NULL __mro__ (it doesn't have any
520 # __mro__), so no segfault occurs. Instead it got:
521 # test_callback_in_cycle_2 (__main__.ReferencesTestCase) ...
522 # Exception exceptions.AttributeError:
523 # "II instance has no attribute 'J'" in <bound method II.acallback
524 # of <?.II instance at 0x00B9B4B8>> ignored
525
526 class J(object):
527 pass
528
529 class II:
530 def acallback(self, ignore):
531 self.J
532
533 I = II()
534 I.J = J
535 I.wr = weakref.ref(J, I.acallback)
536
537 del I, J, II
538 gc.collect()
539
540 def test_callback_in_cycle_3(self):
541 import gc
542
543 # This one broke the first patch that fixed the last two. In this
544 # case, the objects reachable from the callback aren't also reachable
545 # from the object (c1) *triggering* the callback: you can get to
546 # c1 from c2, but not vice-versa. The result was that c2's __dict__
547 # got tp_clear'ed by the time the c2.cb callback got invoked.
548
549 class C:
550 def cb(self, ignore):
551 self.me
552 self.c1
553 self.wr
554
555 c1, c2 = C(), C()
556
557 c2.me = c2
558 c2.c1 = c1
559 c2.wr = weakref.ref(c1, c2.cb)
560
561 del c1, c2
562 gc.collect()
563
564 def test_callback_in_cycle_4(self):
565 import gc
566
567 # Like test_callback_in_cycle_3, except c2 and c1 have different
568 # classes. c2's class (C) isn't reachable from c1 then, so protecting
569 # objects reachable from the dying object (c1) isn't enough to stop
570 # c2's class (C) from getting tp_clear'ed before c2.cb is invoked.
571 # The result was a segfault (C.__mro__ was NULL when the callback
572 # tried to look up self.me).
573
574 class C(object):
575 def cb(self, ignore):
576 self.me
577 self.c1
578 self.wr
579
580 class D:
581 pass
582
583 c1, c2 = D(), C()
584
585 c2.me = c2
586 c2.c1 = c1
587 c2.wr = weakref.ref(c1, c2.cb)
588
589 del c1, c2, C, D
590 gc.collect()
591
592 def test_callback_in_cycle_resurrection(self):
593 import gc
594
595 # Do something nasty in a weakref callback: resurrect objects
596 # from dead cycles. For this to be attempted, the weakref and
597 # its callback must also be part of the cyclic trash (else the
598 # objects reachable via the callback couldn't be in cyclic trash
599 # to begin with -- the callback would act like an external root).
600 # But gc clears trash weakrefs with callbacks early now, which
601 # disables the callbacks, so the callbacks shouldn't get called
602 # at all (and so nothing actually gets resurrected).
603
604 alist = []
605 class C(object):
606 def __init__(self, value):
607 self.attribute = value
608
609 def acallback(self, ignore):
610 alist.append(self.c)
611
612 c1, c2 = C(1), C(2)
613 c1.c = c2
614 c2.c = c1
615 c1.wr = weakref.ref(c2, c1.acallback)
616 c2.wr = weakref.ref(c1, c2.acallback)
617
618 def C_went_away(ignore):
619 alist.append("C went away")
620 wr = weakref.ref(C, C_went_away)
621
622 del c1, c2, C # make them all trash
623 self.assertEqual(alist, []) # del isn't enough to reclaim anything
624
625 gc.collect()
626 # c1.wr and c2.wr were part of the cyclic trash, so should have
627 # been cleared without their callbacks executing. OTOH, the weakref
628 # to C is bound to a function local (wr), and wasn't trash, so that
629 # callback should have been invoked when C went away.
630 self.assertEqual(alist, ["C went away"])
631 # The remaining weakref should be dead now (its callback ran).
632 self.assertEqual(wr(), None)
633
634 del alist[:]
635 gc.collect()
636 self.assertEqual(alist, [])
637
638 def test_callbacks_on_callback(self):
639 import gc
640
641 # Set up weakref callbacks *on* weakref callbacks.
642 alist = []
643 def safe_callback(ignore):
644 alist.append("safe_callback called")
645
646 class C(object):
647 def cb(self, ignore):
648 alist.append("cb called")
649
650 c, d = C(), C()
651 c.other = d
652 d.other = c
653 callback = c.cb
654 c.wr = weakref.ref(d, callback) # this won't trigger
655 d.wr = weakref.ref(callback, d.cb) # ditto
656 external_wr = weakref.ref(callback, safe_callback) # but this will
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200657 self.assertIs(external_wr(), callback)
Tim Peters403a2032003-11-20 21:21:46 +0000658
659 # The weakrefs attached to c and d should get cleared, so that
660 # C.cb is never called. But external_wr isn't part of the cyclic
661 # trash, and no cyclic trash is reachable from it, so safe_callback
662 # should get invoked when the bound method object callback (c.cb)
663 # -- which is itself a callback, and also part of the cyclic trash --
664 # gets reclaimed at the end of gc.
665
666 del callback, c, d, C
667 self.assertEqual(alist, []) # del isn't enough to clean up cycles
668 gc.collect()
669 self.assertEqual(alist, ["safe_callback called"])
670 self.assertEqual(external_wr(), None)
671
672 del alist[:]
673 gc.collect()
674 self.assertEqual(alist, [])
675
Fred Drakebc875f52004-02-04 23:14:14 +0000676 def test_gc_during_ref_creation(self):
677 self.check_gc_during_creation(weakref.ref)
678
679 def test_gc_during_proxy_creation(self):
680 self.check_gc_during_creation(weakref.proxy)
681
682 def check_gc_during_creation(self, makeref):
683 thresholds = gc.get_threshold()
684 gc.set_threshold(1, 1, 1)
685 gc.collect()
Fred Drake55cf4342004-02-13 19:21:57 +0000686 class A:
687 pass
Fred Drakebc875f52004-02-04 23:14:14 +0000688
689 def callback(*args):
690 pass
691
Fred Drake55cf4342004-02-13 19:21:57 +0000692 referenced = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000693
Fred Drake55cf4342004-02-13 19:21:57 +0000694 a = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000695 a.a = a
696 a.wr = makeref(referenced)
697
698 try:
699 # now make sure the object and the ref get labeled as
700 # cyclic trash:
Fred Drake55cf4342004-02-13 19:21:57 +0000701 a = A()
702 weakref.ref(referenced, callback)
Fred Drakebc875f52004-02-04 23:14:14 +0000703
704 finally:
705 gc.set_threshold(*thresholds)
706
Thomas Woutersb2137042007-02-01 18:02:27 +0000707 def test_ref_created_during_del(self):
708 # Bug #1377858
709 # A weakref created in an object's __del__() would crash the
710 # interpreter when the weakref was cleaned up since it would refer to
711 # non-existent memory. This test should not segfault the interpreter.
712 class Target(object):
713 def __del__(self):
714 global ref_from_del
715 ref_from_del = weakref.ref(self)
716
717 w = Target()
718
Benjamin Peterson9aa42992008-09-10 21:57:34 +0000719 def test_init(self):
720 # Issue 3634
721 # <weakref to class>.__init__() doesn't check errors correctly
722 r = weakref.ref(Exception)
723 self.assertRaises(TypeError, r.__init__, 0, 0, 0, 0, 0)
724 # No exception should be raised here
725 gc.collect()
726
Antoine Pitrou3af01a12010-03-31 21:40:47 +0000727 def test_classes(self):
728 # Check that classes are weakrefable.
729 class A(object):
730 pass
731 l = []
732 weakref.ref(int)
733 a = weakref.ref(A, l.append)
734 A = None
735 gc.collect()
736 self.assertEqual(a(), None)
737 self.assertEqual(l, [a])
738
Antoine Pitroue11fecb2012-11-11 19:36:51 +0100739 def test_equality(self):
740 # Alive weakrefs defer equality testing to their underlying object.
741 x = Object(1)
742 y = Object(1)
743 z = Object(2)
744 a = weakref.ref(x)
745 b = weakref.ref(y)
746 c = weakref.ref(z)
747 d = weakref.ref(x)
748 # Note how we directly test the operators here, to stress both
749 # __eq__ and __ne__.
750 self.assertTrue(a == b)
751 self.assertFalse(a != b)
752 self.assertFalse(a == c)
753 self.assertTrue(a != c)
754 self.assertTrue(a == d)
755 self.assertFalse(a != d)
756 del x, y, z
757 gc.collect()
758 for r in a, b, c:
759 # Sanity check
760 self.assertIs(r(), None)
761 # Dead weakrefs compare by identity: whether `a` and `d` are the
762 # same weakref object is an implementation detail, since they pointed
763 # to the same original object and didn't have a callback.
764 # (see issue #16453).
765 self.assertFalse(a == b)
766 self.assertTrue(a != b)
767 self.assertFalse(a == c)
768 self.assertTrue(a != c)
769 self.assertEqual(a == d, a is d)
770 self.assertEqual(a != d, a is not d)
771
772 def test_ordering(self):
773 # weakrefs cannot be ordered, even if the underlying objects can.
774 ops = [operator.lt, operator.gt, operator.le, operator.ge]
775 x = Object(1)
776 y = Object(1)
777 a = weakref.ref(x)
778 b = weakref.ref(y)
779 for op in ops:
780 self.assertRaises(TypeError, op, a, b)
781 # Same when dead.
782 del x, y
783 gc.collect()
784 for op in ops:
785 self.assertRaises(TypeError, op, a, b)
786
787 def test_hashing(self):
788 # Alive weakrefs hash the same as the underlying object
789 x = Object(42)
790 y = Object(42)
791 a = weakref.ref(x)
792 b = weakref.ref(y)
793 self.assertEqual(hash(a), hash(42))
794 del x, y
795 gc.collect()
796 # Dead weakrefs:
797 # - retain their hash is they were hashed when alive;
798 # - otherwise, cannot be hashed.
799 self.assertEqual(hash(a), hash(42))
800 self.assertRaises(TypeError, hash, b)
801
Antoine Pitrou62a0d6e2012-12-08 21:15:26 +0100802 def test_trashcan_16602(self):
803 # Issue #16602: when a weakref's target was part of a long
804 # deallocation chain, the trashcan mechanism could delay clearing
805 # of the weakref and make the target object visible from outside
806 # code even though its refcount had dropped to 0. A crash ensued.
807 class C:
808 def __init__(self, parent):
809 if not parent:
810 return
811 wself = weakref.ref(self)
812 def cb(wparent):
813 o = wself()
814 self.wparent = weakref.ref(parent, cb)
815
816 d = weakref.WeakKeyDictionary()
817 root = c = C(None)
818 for n in range(100):
819 d[c] = c = C(c)
820 del root
821 gc.collect()
822
Mark Dickinson556e94b2013-04-13 15:45:44 +0100823 def test_callback_attribute(self):
824 x = Object(1)
825 callback = lambda ref: None
826 ref1 = weakref.ref(x, callback)
827 self.assertIs(ref1.__callback__, callback)
828
829 ref2 = weakref.ref(x)
830 self.assertIsNone(ref2.__callback__)
831
832 def test_callback_attribute_after_deletion(self):
833 x = Object(1)
834 ref = weakref.ref(x, self.callback)
835 self.assertIsNotNone(ref.__callback__)
836 del x
837 support.gc_collect()
838 self.assertIsNone(ref.__callback__)
839
840 def test_set_callback_attribute(self):
841 x = Object(1)
842 callback = lambda ref: None
843 ref1 = weakref.ref(x, callback)
844 with self.assertRaises(AttributeError):
845 ref1.__callback__ = lambda ref: None
846
Fred Drake0a4dd392004-07-02 18:57:45 +0000847
Amaury Forgeot d'Arcc856c7a2008-06-16 19:50:09 +0000848class SubclassableWeakrefTestCase(TestBase):
Fred Drake0a4dd392004-07-02 18:57:45 +0000849
850 def test_subclass_refs(self):
851 class MyRef(weakref.ref):
852 def __init__(self, ob, callback=None, value=42):
853 self.value = value
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000854 super().__init__(ob, callback)
Fred Drake0a4dd392004-07-02 18:57:45 +0000855 def __call__(self):
856 self.called = True
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000857 return super().__call__()
Fred Drake0a4dd392004-07-02 18:57:45 +0000858 o = Object("foo")
859 mr = MyRef(o, value=24)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200860 self.assertIs(mr(), o)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000861 self.assertTrue(mr.called)
Fred Drake0a4dd392004-07-02 18:57:45 +0000862 self.assertEqual(mr.value, 24)
863 del o
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200864 self.assertIsNone(mr())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000865 self.assertTrue(mr.called)
Fred Drake0a4dd392004-07-02 18:57:45 +0000866
867 def test_subclass_refs_dont_replace_standard_refs(self):
868 class MyRef(weakref.ref):
869 pass
870 o = Object(42)
871 r1 = MyRef(o)
872 r2 = weakref.ref(o)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200873 self.assertIsNot(r1, r2)
Fred Drake0a4dd392004-07-02 18:57:45 +0000874 self.assertEqual(weakref.getweakrefs(o), [r2, r1])
875 self.assertEqual(weakref.getweakrefcount(o), 2)
876 r3 = MyRef(o)
877 self.assertEqual(weakref.getweakrefcount(o), 3)
878 refs = weakref.getweakrefs(o)
879 self.assertEqual(len(refs), 3)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200880 self.assertIs(r2, refs[0])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000881 self.assertIn(r1, refs[1:])
882 self.assertIn(r3, refs[1:])
Fred Drake0a4dd392004-07-02 18:57:45 +0000883
884 def test_subclass_refs_dont_conflate_callbacks(self):
885 class MyRef(weakref.ref):
886 pass
887 o = Object(42)
888 r1 = MyRef(o, id)
889 r2 = MyRef(o, str)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200890 self.assertIsNot(r1, r2)
Fred Drake0a4dd392004-07-02 18:57:45 +0000891 refs = weakref.getweakrefs(o)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000892 self.assertIn(r1, refs)
893 self.assertIn(r2, refs)
Fred Drake0a4dd392004-07-02 18:57:45 +0000894
895 def test_subclass_refs_with_slots(self):
896 class MyRef(weakref.ref):
897 __slots__ = "slot1", "slot2"
898 def __new__(type, ob, callback, slot1, slot2):
899 return weakref.ref.__new__(type, ob, callback)
900 def __init__(self, ob, callback, slot1, slot2):
901 self.slot1 = slot1
902 self.slot2 = slot2
903 def meth(self):
904 return self.slot1 + self.slot2
905 o = Object(42)
906 r = MyRef(o, None, "abc", "def")
907 self.assertEqual(r.slot1, "abc")
908 self.assertEqual(r.slot2, "def")
909 self.assertEqual(r.meth(), "abcdef")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000910 self.assertFalse(hasattr(r, "__dict__"))
Fred Drake0a4dd392004-07-02 18:57:45 +0000911
Amaury Forgeot d'Arcc856c7a2008-06-16 19:50:09 +0000912 def test_subclass_refs_with_cycle(self):
913 # Bug #3110
914 # An instance of a weakref subclass can have attributes.
915 # If such a weakref holds the only strong reference to the object,
916 # deleting the weakref will delete the object. In this case,
917 # the callback must not be called, because the ref object is
918 # being deleted.
919 class MyRef(weakref.ref):
920 pass
921
922 # Use a local callback, for "regrtest -R::"
923 # to detect refcounting problems
924 def callback(w):
925 self.cbcalled += 1
926
927 o = C()
928 r1 = MyRef(o, callback)
929 r1.o = o
930 del o
931
932 del r1 # Used to crash here
933
934 self.assertEqual(self.cbcalled, 0)
935
936 # Same test, with two weakrefs to the same object
937 # (since code paths are different)
938 o = C()
939 r1 = MyRef(o, callback)
940 r2 = MyRef(o, callback)
941 r1.r = r2
942 r2.o = o
943 del o
944 del r2
945
946 del r1 # Used to crash here
947
948 self.assertEqual(self.cbcalled, 0)
949
Fred Drake0a4dd392004-07-02 18:57:45 +0000950
Antoine Pitrouc3afba12012-11-17 18:57:38 +0100951class WeakMethodTestCase(unittest.TestCase):
952
953 def _subclass(self):
Martin Panter7462b6492015-11-02 03:37:02 +0000954 """Return an Object subclass overriding `some_method`."""
Antoine Pitrouc3afba12012-11-17 18:57:38 +0100955 class C(Object):
956 def some_method(self):
957 return 6
958 return C
959
960 def test_alive(self):
961 o = Object(1)
962 r = weakref.WeakMethod(o.some_method)
963 self.assertIsInstance(r, weakref.ReferenceType)
964 self.assertIsInstance(r(), type(o.some_method))
965 self.assertIs(r().__self__, o)
966 self.assertIs(r().__func__, o.some_method.__func__)
967 self.assertEqual(r()(), 4)
968
969 def test_object_dead(self):
970 o = Object(1)
971 r = weakref.WeakMethod(o.some_method)
972 del o
973 gc.collect()
974 self.assertIs(r(), None)
975
976 def test_method_dead(self):
977 C = self._subclass()
978 o = C(1)
979 r = weakref.WeakMethod(o.some_method)
980 del C.some_method
981 gc.collect()
982 self.assertIs(r(), None)
983
984 def test_callback_when_object_dead(self):
985 # Test callback behaviour when object dies first.
986 C = self._subclass()
987 calls = []
988 def cb(arg):
989 calls.append(arg)
990 o = C(1)
991 r = weakref.WeakMethod(o.some_method, cb)
992 del o
993 gc.collect()
994 self.assertEqual(calls, [r])
995 # Callback is only called once.
996 C.some_method = Object.some_method
997 gc.collect()
998 self.assertEqual(calls, [r])
999
1000 def test_callback_when_method_dead(self):
1001 # Test callback behaviour when method dies first.
1002 C = self._subclass()
1003 calls = []
1004 def cb(arg):
1005 calls.append(arg)
1006 o = C(1)
1007 r = weakref.WeakMethod(o.some_method, cb)
1008 del C.some_method
1009 gc.collect()
1010 self.assertEqual(calls, [r])
1011 # Callback is only called once.
1012 del o
1013 gc.collect()
1014 self.assertEqual(calls, [r])
1015
1016 @support.cpython_only
1017 def test_no_cycles(self):
1018 # A WeakMethod doesn't create any reference cycle to itself.
1019 o = Object(1)
1020 def cb(_):
1021 pass
1022 r = weakref.WeakMethod(o.some_method, cb)
1023 wr = weakref.ref(r)
1024 del r
1025 self.assertIs(wr(), None)
1026
1027 def test_equality(self):
1028 def _eq(a, b):
1029 self.assertTrue(a == b)
1030 self.assertFalse(a != b)
1031 def _ne(a, b):
1032 self.assertTrue(a != b)
1033 self.assertFalse(a == b)
1034 x = Object(1)
1035 y = Object(1)
1036 a = weakref.WeakMethod(x.some_method)
1037 b = weakref.WeakMethod(y.some_method)
1038 c = weakref.WeakMethod(x.other_method)
1039 d = weakref.WeakMethod(y.other_method)
1040 # Objects equal, same method
1041 _eq(a, b)
1042 _eq(c, d)
1043 # Objects equal, different method
1044 _ne(a, c)
1045 _ne(a, d)
1046 _ne(b, c)
1047 _ne(b, d)
1048 # Objects unequal, same or different method
1049 z = Object(2)
1050 e = weakref.WeakMethod(z.some_method)
1051 f = weakref.WeakMethod(z.other_method)
1052 _ne(a, e)
1053 _ne(a, f)
1054 _ne(b, e)
1055 _ne(b, f)
1056 del x, y, z
1057 gc.collect()
1058 # Dead WeakMethods compare by identity
1059 refs = a, b, c, d, e, f
1060 for q in refs:
1061 for r in refs:
1062 self.assertEqual(q == r, q is r)
1063 self.assertEqual(q != r, q is not r)
1064
1065 def test_hashing(self):
1066 # Alive WeakMethods are hashable if the underlying object is
1067 # hashable.
1068 x = Object(1)
1069 y = Object(1)
1070 a = weakref.WeakMethod(x.some_method)
1071 b = weakref.WeakMethod(y.some_method)
1072 c = weakref.WeakMethod(y.other_method)
1073 # Since WeakMethod objects are equal, the hashes should be equal.
1074 self.assertEqual(hash(a), hash(b))
1075 ha = hash(a)
1076 # Dead WeakMethods retain their old hash value
1077 del x, y
1078 gc.collect()
1079 self.assertEqual(hash(a), ha)
1080 self.assertEqual(hash(b), ha)
1081 # If it wasn't hashed when alive, a dead WeakMethod cannot be hashed.
1082 self.assertRaises(TypeError, hash, c)
1083
1084
Fred Drakeb0fefc52001-03-23 04:22:45 +00001085class MappingTestCase(TestBase):
Martin v. Löwis5e163332001-02-27 18:36:56 +00001086
Fred Drakeb0fefc52001-03-23 04:22:45 +00001087 COUNT = 10
1088
Antoine Pitroubbe2f602012-03-01 16:26:35 +01001089 def check_len_cycles(self, dict_type, cons):
1090 N = 20
1091 items = [RefCycle() for i in range(N)]
1092 dct = dict_type(cons(o) for o in items)
1093 # Keep an iterator alive
1094 it = dct.items()
1095 try:
1096 next(it)
1097 except StopIteration:
1098 pass
1099 del items
1100 gc.collect()
1101 n1 = len(dct)
1102 del it
1103 gc.collect()
1104 n2 = len(dct)
1105 # one item may be kept alive inside the iterator
1106 self.assertIn(n1, (0, 1))
1107 self.assertEqual(n2, 0)
1108
1109 def test_weak_keyed_len_cycles(self):
1110 self.check_len_cycles(weakref.WeakKeyDictionary, lambda k: (k, 1))
1111
1112 def test_weak_valued_len_cycles(self):
1113 self.check_len_cycles(weakref.WeakValueDictionary, lambda k: (1, k))
1114
1115 def check_len_race(self, dict_type, cons):
1116 # Extended sanity checks for len() in the face of cyclic collection
1117 self.addCleanup(gc.set_threshold, *gc.get_threshold())
1118 for th in range(1, 100):
1119 N = 20
1120 gc.collect(0)
1121 gc.set_threshold(th, th, th)
1122 items = [RefCycle() for i in range(N)]
1123 dct = dict_type(cons(o) for o in items)
1124 del items
1125 # All items will be collected at next garbage collection pass
1126 it = dct.items()
1127 try:
1128 next(it)
1129 except StopIteration:
1130 pass
1131 n1 = len(dct)
1132 del it
1133 n2 = len(dct)
1134 self.assertGreaterEqual(n1, 0)
1135 self.assertLessEqual(n1, N)
1136 self.assertGreaterEqual(n2, 0)
1137 self.assertLessEqual(n2, n1)
1138
1139 def test_weak_keyed_len_race(self):
1140 self.check_len_race(weakref.WeakKeyDictionary, lambda k: (k, 1))
1141
1142 def test_weak_valued_len_race(self):
1143 self.check_len_race(weakref.WeakValueDictionary, lambda k: (1, k))
1144
Fred Drakeb0fefc52001-03-23 04:22:45 +00001145 def test_weak_values(self):
Fred Drake0e540c32001-05-02 05:44:22 +00001146 #
1147 # This exercises d.copy(), d.items(), d[], del d[], len(d).
1148 #
1149 dict, objects = self.make_weak_valued_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +00001150 for o in objects:
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001151 self.assertEqual(weakref.getweakrefcount(o), 1)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001152 self.assertIs(o, dict[o.arg],
Fred Drakeb0fefc52001-03-23 04:22:45 +00001153 "wrong object returned by weak dict!")
Barry Warsawecaab832008-09-04 01:42:51 +00001154 items1 = list(dict.items())
1155 items2 = list(dict.copy().items())
Fred Drakeb0fefc52001-03-23 04:22:45 +00001156 items1.sort()
1157 items2.sort()
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001158 self.assertEqual(items1, items2,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001159 "cloning of weak-valued dictionary did not work!")
1160 del items1, items2
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001161 self.assertEqual(len(dict), self.COUNT)
Fred Drakeb0fefc52001-03-23 04:22:45 +00001162 del objects[0]
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001163 self.assertEqual(len(dict), self.COUNT - 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001164 "deleting object did not cause dictionary update")
1165 del objects, o
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001166 self.assertEqual(len(dict), 0,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001167 "deleting the values did not clear the dictionary")
Fred Drake4fd06e02001-08-03 04:11:27 +00001168 # regression on SF bug #447152:
1169 dict = weakref.WeakValueDictionary()
1170 self.assertRaises(KeyError, dict.__getitem__, 1)
1171 dict[2] = C()
1172 self.assertRaises(KeyError, dict.__getitem__, 2)
Fred Drakeb0fefc52001-03-23 04:22:45 +00001173
1174 def test_weak_keys(self):
Fred Drake0e540c32001-05-02 05:44:22 +00001175 #
1176 # This exercises d.copy(), d.items(), d[] = v, d[], del d[],
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001177 # len(d), k in d.
Fred Drake0e540c32001-05-02 05:44:22 +00001178 #
1179 dict, objects = self.make_weak_keyed_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +00001180 for o in objects:
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001181 self.assertEqual(weakref.getweakrefcount(o), 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001182 "wrong number of weak references to %r!" % o)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001183 self.assertIs(o.arg, dict[o],
Fred Drakeb0fefc52001-03-23 04:22:45 +00001184 "wrong object returned by weak dict!")
1185 items1 = dict.items()
1186 items2 = dict.copy().items()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001187 self.assertEqual(set(items1), set(items2),
Fred Drakeb0fefc52001-03-23 04:22:45 +00001188 "cloning of weak-keyed dictionary did not work!")
1189 del items1, items2
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001190 self.assertEqual(len(dict), self.COUNT)
Fred Drakeb0fefc52001-03-23 04:22:45 +00001191 del objects[0]
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001192 self.assertEqual(len(dict), (self.COUNT - 1),
Fred Drakeb0fefc52001-03-23 04:22:45 +00001193 "deleting object did not cause dictionary update")
1194 del objects, o
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001195 self.assertEqual(len(dict), 0,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001196 "deleting the keys did not clear the dictionary")
Fred Drake752eda42001-11-06 16:38:34 +00001197 o = Object(42)
1198 dict[o] = "What is the meaning of the universe?"
Benjamin Peterson577473f2010-01-19 00:09:57 +00001199 self.assertIn(o, dict)
1200 self.assertNotIn(34, dict)
Martin v. Löwis5e163332001-02-27 18:36:56 +00001201
Fred Drake0e540c32001-05-02 05:44:22 +00001202 def test_weak_keyed_iters(self):
1203 dict, objects = self.make_weak_keyed_dict()
1204 self.check_iters(dict)
1205
Thomas Wouters477c8d52006-05-27 19:21:47 +00001206 # Test keyrefs()
1207 refs = dict.keyrefs()
1208 self.assertEqual(len(refs), len(objects))
1209 objects2 = list(objects)
1210 for wr in refs:
1211 ob = wr()
Benjamin Peterson577473f2010-01-19 00:09:57 +00001212 self.assertIn(ob, dict)
1213 self.assertIn(ob, dict)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001214 self.assertEqual(ob.arg, dict[ob])
1215 objects2.remove(ob)
1216 self.assertEqual(len(objects2), 0)
1217
1218 # Test iterkeyrefs()
1219 objects2 = list(objects)
Barry Warsawecaab832008-09-04 01:42:51 +00001220 self.assertEqual(len(list(dict.keyrefs())), len(objects))
1221 for wr in dict.keyrefs():
Thomas Wouters477c8d52006-05-27 19:21:47 +00001222 ob = wr()
Benjamin Peterson577473f2010-01-19 00:09:57 +00001223 self.assertIn(ob, dict)
1224 self.assertIn(ob, dict)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001225 self.assertEqual(ob.arg, dict[ob])
1226 objects2.remove(ob)
1227 self.assertEqual(len(objects2), 0)
1228
Fred Drake0e540c32001-05-02 05:44:22 +00001229 def test_weak_valued_iters(self):
1230 dict, objects = self.make_weak_valued_dict()
1231 self.check_iters(dict)
1232
Thomas Wouters477c8d52006-05-27 19:21:47 +00001233 # Test valuerefs()
1234 refs = dict.valuerefs()
1235 self.assertEqual(len(refs), len(objects))
1236 objects2 = list(objects)
1237 for wr in refs:
1238 ob = wr()
1239 self.assertEqual(ob, dict[ob.arg])
1240 self.assertEqual(ob.arg, dict[ob.arg].arg)
1241 objects2.remove(ob)
1242 self.assertEqual(len(objects2), 0)
1243
1244 # Test itervaluerefs()
1245 objects2 = list(objects)
1246 self.assertEqual(len(list(dict.itervaluerefs())), len(objects))
1247 for wr in dict.itervaluerefs():
1248 ob = wr()
1249 self.assertEqual(ob, dict[ob.arg])
1250 self.assertEqual(ob.arg, dict[ob.arg].arg)
1251 objects2.remove(ob)
1252 self.assertEqual(len(objects2), 0)
1253
Fred Drake0e540c32001-05-02 05:44:22 +00001254 def check_iters(self, dict):
1255 # item iterator:
Barry Warsawecaab832008-09-04 01:42:51 +00001256 items = list(dict.items())
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001257 for item in dict.items():
Fred Drake0e540c32001-05-02 05:44:22 +00001258 items.remove(item)
Barry Warsawecaab832008-09-04 01:42:51 +00001259 self.assertFalse(items, "items() did not touch all items")
Fred Drake0e540c32001-05-02 05:44:22 +00001260
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001261 # key iterator, via __iter__():
Guido van Rossum07f24362007-02-11 22:59:48 +00001262 keys = list(dict.keys())
Fred Drake0e540c32001-05-02 05:44:22 +00001263 for k in dict:
1264 keys.remove(k)
Barry Warsawecaab832008-09-04 01:42:51 +00001265 self.assertFalse(keys, "__iter__() did not touch all keys")
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001266
1267 # key iterator, via iterkeys():
Guido van Rossum07f24362007-02-11 22:59:48 +00001268 keys = list(dict.keys())
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001269 for k in dict.keys():
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001270 keys.remove(k)
Barry Warsawecaab832008-09-04 01:42:51 +00001271 self.assertFalse(keys, "iterkeys() did not touch all keys")
Fred Drake0e540c32001-05-02 05:44:22 +00001272
1273 # value iterator:
Guido van Rossum07f24362007-02-11 22:59:48 +00001274 values = list(dict.values())
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001275 for v in dict.values():
Fred Drake0e540c32001-05-02 05:44:22 +00001276 values.remove(v)
Barry Warsawecaab832008-09-04 01:42:51 +00001277 self.assertFalse(values,
Fred Drakef425b1e2003-07-14 21:37:17 +00001278 "itervalues() did not touch all values")
Fred Drake0e540c32001-05-02 05:44:22 +00001279
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001280 def check_weak_destroy_while_iterating(self, dict, objects, iter_name):
1281 n = len(dict)
1282 it = iter(getattr(dict, iter_name)())
1283 next(it) # Trigger internal iteration
1284 # Destroy an object
1285 del objects[-1]
1286 gc.collect() # just in case
1287 # We have removed either the first consumed object, or another one
1288 self.assertIn(len(list(it)), [len(objects), len(objects) - 1])
1289 del it
1290 # The removal has been committed
1291 self.assertEqual(len(dict), n - 1)
1292
1293 def check_weak_destroy_and_mutate_while_iterating(self, dict, testcontext):
1294 # Check that we can explicitly mutate the weak dict without
1295 # interfering with delayed removal.
1296 # `testcontext` should create an iterator, destroy one of the
1297 # weakref'ed objects and then return a new key/value pair corresponding
1298 # to the destroyed object.
1299 with testcontext() as (k, v):
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001300 self.assertNotIn(k, dict)
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001301 with testcontext() as (k, v):
1302 self.assertRaises(KeyError, dict.__delitem__, k)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001303 self.assertNotIn(k, dict)
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001304 with testcontext() as (k, v):
1305 self.assertRaises(KeyError, dict.pop, k)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001306 self.assertNotIn(k, dict)
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001307 with testcontext() as (k, v):
1308 dict[k] = v
1309 self.assertEqual(dict[k], v)
1310 ddict = copy.copy(dict)
1311 with testcontext() as (k, v):
1312 dict.update(ddict)
1313 self.assertEqual(dict, ddict)
1314 with testcontext() as (k, v):
1315 dict.clear()
1316 self.assertEqual(len(dict), 0)
1317
Antoine Pitrou1bf974d2014-10-05 20:02:28 +02001318 def check_weak_del_and_len_while_iterating(self, dict, testcontext):
1319 # Check that len() works when both iterating and removing keys
1320 # explicitly through various means (.pop(), .clear()...), while
1321 # implicit mutation is deferred because an iterator is alive.
1322 # (each call to testcontext() should schedule one item for removal
1323 # for this test to work properly)
1324 o = Object(123456)
1325 with testcontext():
1326 n = len(dict)
1327 dict.popitem()
1328 self.assertEqual(len(dict), n - 1)
1329 dict[o] = o
1330 self.assertEqual(len(dict), n)
1331 with testcontext():
1332 self.assertEqual(len(dict), n - 1)
1333 dict.pop(next(dict.keys()))
1334 self.assertEqual(len(dict), n - 2)
1335 with testcontext():
1336 self.assertEqual(len(dict), n - 3)
1337 del dict[next(dict.keys())]
1338 self.assertEqual(len(dict), n - 4)
1339 with testcontext():
1340 self.assertEqual(len(dict), n - 5)
1341 dict.popitem()
1342 self.assertEqual(len(dict), n - 6)
1343 with testcontext():
1344 dict.clear()
1345 self.assertEqual(len(dict), 0)
1346 self.assertEqual(len(dict), 0)
1347
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001348 def test_weak_keys_destroy_while_iterating(self):
1349 # Issue #7105: iterators shouldn't crash when a key is implicitly removed
1350 dict, objects = self.make_weak_keyed_dict()
1351 self.check_weak_destroy_while_iterating(dict, objects, 'keys')
1352 self.check_weak_destroy_while_iterating(dict, objects, 'items')
1353 self.check_weak_destroy_while_iterating(dict, objects, 'values')
1354 self.check_weak_destroy_while_iterating(dict, objects, 'keyrefs')
1355 dict, objects = self.make_weak_keyed_dict()
1356 @contextlib.contextmanager
1357 def testcontext():
1358 try:
1359 it = iter(dict.items())
1360 next(it)
1361 # Schedule a key/value for removal and recreate it
1362 v = objects.pop().arg
1363 gc.collect() # just in case
1364 yield Object(v), v
1365 finally:
1366 it = None # should commit all removals
Benjamin Peterson18bb7022014-08-24 18:02:15 -05001367 gc.collect()
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001368 self.check_weak_destroy_and_mutate_while_iterating(dict, testcontext)
Antoine Pitrou1bf974d2014-10-05 20:02:28 +02001369 # Issue #21173: len() fragile when keys are both implicitly and
1370 # explicitly removed.
1371 dict, objects = self.make_weak_keyed_dict()
1372 self.check_weak_del_and_len_while_iterating(dict, testcontext)
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001373
1374 def test_weak_values_destroy_while_iterating(self):
1375 # Issue #7105: iterators shouldn't crash when a key is implicitly removed
1376 dict, objects = self.make_weak_valued_dict()
1377 self.check_weak_destroy_while_iterating(dict, objects, 'keys')
1378 self.check_weak_destroy_while_iterating(dict, objects, 'items')
1379 self.check_weak_destroy_while_iterating(dict, objects, 'values')
1380 self.check_weak_destroy_while_iterating(dict, objects, 'itervaluerefs')
1381 self.check_weak_destroy_while_iterating(dict, objects, 'valuerefs')
1382 dict, objects = self.make_weak_valued_dict()
1383 @contextlib.contextmanager
1384 def testcontext():
1385 try:
1386 it = iter(dict.items())
1387 next(it)
1388 # Schedule a key/value for removal and recreate it
1389 k = objects.pop().arg
1390 gc.collect() # just in case
1391 yield k, Object(k)
1392 finally:
1393 it = None # should commit all removals
Benjamin Peterson18bb7022014-08-24 18:02:15 -05001394 gc.collect()
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001395 self.check_weak_destroy_and_mutate_while_iterating(dict, testcontext)
Antoine Pitrou1bf974d2014-10-05 20:02:28 +02001396 dict, objects = self.make_weak_valued_dict()
1397 self.check_weak_del_and_len_while_iterating(dict, testcontext)
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001398
Guido van Rossum009afb72002-06-10 20:00:52 +00001399 def test_make_weak_keyed_dict_from_dict(self):
1400 o = Object(3)
1401 dict = weakref.WeakKeyDictionary({o:364})
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001402 self.assertEqual(dict[o], 364)
Guido van Rossum009afb72002-06-10 20:00:52 +00001403
1404 def test_make_weak_keyed_dict_from_weak_keyed_dict(self):
1405 o = Object(3)
1406 dict = weakref.WeakKeyDictionary({o:364})
1407 dict2 = weakref.WeakKeyDictionary(dict)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001408 self.assertEqual(dict[o], 364)
Guido van Rossum009afb72002-06-10 20:00:52 +00001409
Fred Drake0e540c32001-05-02 05:44:22 +00001410 def make_weak_keyed_dict(self):
1411 dict = weakref.WeakKeyDictionary()
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001412 objects = list(map(Object, range(self.COUNT)))
Fred Drake0e540c32001-05-02 05:44:22 +00001413 for o in objects:
1414 dict[o] = o.arg
1415 return dict, objects
1416
Antoine Pitrouc06de472009-05-30 21:04:26 +00001417 def test_make_weak_valued_dict_from_dict(self):
1418 o = Object(3)
1419 dict = weakref.WeakValueDictionary({364:o})
1420 self.assertEqual(dict[364], o)
1421
1422 def test_make_weak_valued_dict_from_weak_valued_dict(self):
1423 o = Object(3)
1424 dict = weakref.WeakValueDictionary({364:o})
1425 dict2 = weakref.WeakValueDictionary(dict)
1426 self.assertEqual(dict[364], o)
1427
Serhiy Storchakab5102e32015-09-29 23:52:09 +03001428 def test_make_weak_valued_dict_misc(self):
1429 # errors
1430 self.assertRaises(TypeError, weakref.WeakValueDictionary.__init__)
1431 self.assertRaises(TypeError, weakref.WeakValueDictionary, {}, {})
1432 self.assertRaises(TypeError, weakref.WeakValueDictionary, (), ())
1433 # special keyword arguments
1434 o = Object(3)
1435 for kw in 'self', 'dict', 'other', 'iterable':
1436 d = weakref.WeakValueDictionary(**{kw: o})
1437 self.assertEqual(list(d.keys()), [kw])
1438 self.assertEqual(d[kw], o)
1439
Fred Drake0e540c32001-05-02 05:44:22 +00001440 def make_weak_valued_dict(self):
1441 dict = weakref.WeakValueDictionary()
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001442 objects = list(map(Object, range(self.COUNT)))
Fred Drake0e540c32001-05-02 05:44:22 +00001443 for o in objects:
1444 dict[o.arg] = o
1445 return dict, objects
1446
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001447 def check_popitem(self, klass, key1, value1, key2, value2):
1448 weakdict = klass()
1449 weakdict[key1] = value1
1450 weakdict[key2] = value2
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001451 self.assertEqual(len(weakdict), 2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001452 k, v = weakdict.popitem()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001453 self.assertEqual(len(weakdict), 1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001454 if k is key1:
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001455 self.assertIs(v, value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001456 else:
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001457 self.assertIs(v, value2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001458 k, v = weakdict.popitem()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001459 self.assertEqual(len(weakdict), 0)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001460 if k is key1:
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001461 self.assertIs(v, value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001462 else:
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001463 self.assertIs(v, value2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001464
1465 def test_weak_valued_dict_popitem(self):
1466 self.check_popitem(weakref.WeakValueDictionary,
1467 "key1", C(), "key2", C())
1468
1469 def test_weak_keyed_dict_popitem(self):
1470 self.check_popitem(weakref.WeakKeyDictionary,
1471 C(), "value 1", C(), "value 2")
1472
1473 def check_setdefault(self, klass, key, value1, value2):
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001474 self.assertIsNot(value1, value2,
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001475 "invalid test"
1476 " -- value parameters must be distinct objects")
1477 weakdict = klass()
1478 o = weakdict.setdefault(key, value1)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001479 self.assertIs(o, value1)
Benjamin Peterson577473f2010-01-19 00:09:57 +00001480 self.assertIn(key, weakdict)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001481 self.assertIs(weakdict.get(key), value1)
1482 self.assertIs(weakdict[key], value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001483
1484 o = weakdict.setdefault(key, value2)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001485 self.assertIs(o, value1)
Benjamin Peterson577473f2010-01-19 00:09:57 +00001486 self.assertIn(key, weakdict)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001487 self.assertIs(weakdict.get(key), value1)
1488 self.assertIs(weakdict[key], value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001489
1490 def test_weak_valued_dict_setdefault(self):
1491 self.check_setdefault(weakref.WeakValueDictionary,
1492 "key", C(), C())
1493
1494 def test_weak_keyed_dict_setdefault(self):
1495 self.check_setdefault(weakref.WeakKeyDictionary,
1496 C(), "value 1", "value 2")
1497
Fred Drakea0a4ab12001-04-16 17:37:27 +00001498 def check_update(self, klass, dict):
Fred Drake0e540c32001-05-02 05:44:22 +00001499 #
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001500 # This exercises d.update(), len(d), d.keys(), k in d,
Fred Drake0e540c32001-05-02 05:44:22 +00001501 # d.get(), d[].
1502 #
Fred Drakea0a4ab12001-04-16 17:37:27 +00001503 weakdict = klass()
1504 weakdict.update(dict)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001505 self.assertEqual(len(weakdict), len(dict))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001506 for k in weakdict.keys():
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001507 self.assertIn(k, dict, "mysterious new key appeared in weak dict")
Fred Drakea0a4ab12001-04-16 17:37:27 +00001508 v = dict.get(k)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001509 self.assertIs(v, weakdict[k])
1510 self.assertIs(v, weakdict.get(k))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001511 for k in dict.keys():
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001512 self.assertIn(k, weakdict, "original key disappeared in weak dict")
Fred Drakea0a4ab12001-04-16 17:37:27 +00001513 v = dict[k]
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001514 self.assertIs(v, weakdict[k])
1515 self.assertIs(v, weakdict.get(k))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001516
1517 def test_weak_valued_dict_update(self):
1518 self.check_update(weakref.WeakValueDictionary,
1519 {1: C(), 'a': C(), C(): C()})
Serhiy Storchakab5102e32015-09-29 23:52:09 +03001520 # errors
1521 self.assertRaises(TypeError, weakref.WeakValueDictionary.update)
1522 d = weakref.WeakValueDictionary()
1523 self.assertRaises(TypeError, d.update, {}, {})
1524 self.assertRaises(TypeError, d.update, (), ())
1525 self.assertEqual(list(d.keys()), [])
1526 # special keyword arguments
1527 o = Object(3)
1528 for kw in 'self', 'dict', 'other', 'iterable':
1529 d = weakref.WeakValueDictionary()
1530 d.update(**{kw: o})
1531 self.assertEqual(list(d.keys()), [kw])
1532 self.assertEqual(d[kw], o)
Fred Drakea0a4ab12001-04-16 17:37:27 +00001533
1534 def test_weak_keyed_dict_update(self):
1535 self.check_update(weakref.WeakKeyDictionary,
1536 {C(): 1, C(): 2, C(): 3})
1537
Fred Drakeccc75622001-09-06 14:52:39 +00001538 def test_weak_keyed_delitem(self):
1539 d = weakref.WeakKeyDictionary()
1540 o1 = Object('1')
1541 o2 = Object('2')
1542 d[o1] = 'something'
1543 d[o2] = 'something'
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001544 self.assertEqual(len(d), 2)
Fred Drakeccc75622001-09-06 14:52:39 +00001545 del d[o1]
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001546 self.assertEqual(len(d), 1)
Barry Warsawecaab832008-09-04 01:42:51 +00001547 self.assertEqual(list(d.keys()), [o2])
Fred Drakeccc75622001-09-06 14:52:39 +00001548
1549 def test_weak_valued_delitem(self):
1550 d = weakref.WeakValueDictionary()
1551 o1 = Object('1')
1552 o2 = Object('2')
1553 d['something'] = o1
1554 d['something else'] = o2
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001555 self.assertEqual(len(d), 2)
Fred Drakeccc75622001-09-06 14:52:39 +00001556 del d['something']
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001557 self.assertEqual(len(d), 1)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001558 self.assertEqual(list(d.items()), [('something else', o2)])
Fred Drakeccc75622001-09-06 14:52:39 +00001559
Tim Peters886128f2003-05-25 01:45:11 +00001560 def test_weak_keyed_bad_delitem(self):
1561 d = weakref.WeakKeyDictionary()
1562 o = Object('1')
1563 # An attempt to delete an object that isn't there should raise
Tim Peters50d8b8b2003-05-25 17:44:31 +00001564 # KeyError. It didn't before 2.3.
Tim Peters886128f2003-05-25 01:45:11 +00001565 self.assertRaises(KeyError, d.__delitem__, o)
Tim Peters50d8b8b2003-05-25 17:44:31 +00001566 self.assertRaises(KeyError, d.__getitem__, o)
1567
1568 # If a key isn't of a weakly referencable type, __getitem__ and
1569 # __setitem__ raise TypeError. __delitem__ should too.
1570 self.assertRaises(TypeError, d.__delitem__, 13)
1571 self.assertRaises(TypeError, d.__getitem__, 13)
1572 self.assertRaises(TypeError, d.__setitem__, 13, 13)
Tim Peters886128f2003-05-25 01:45:11 +00001573
1574 def test_weak_keyed_cascading_deletes(self):
1575 # SF bug 742860. For some reason, before 2.3 __delitem__ iterated
1576 # over the keys via self.data.iterkeys(). If things vanished from
1577 # the dict during this (or got added), that caused a RuntimeError.
1578
1579 d = weakref.WeakKeyDictionary()
1580 mutate = False
1581
1582 class C(object):
1583 def __init__(self, i):
1584 self.value = i
1585 def __hash__(self):
1586 return hash(self.value)
1587 def __eq__(self, other):
1588 if mutate:
1589 # Side effect that mutates the dict, by removing the
1590 # last strong reference to a key.
1591 del objs[-1]
1592 return self.value == other.value
1593
1594 objs = [C(i) for i in range(4)]
1595 for o in objs:
1596 d[o] = o.value
1597 del o # now the only strong references to keys are in objs
1598 # Find the order in which iterkeys sees the keys.
Barry Warsawecaab832008-09-04 01:42:51 +00001599 objs = list(d.keys())
Tim Peters886128f2003-05-25 01:45:11 +00001600 # Reverse it, so that the iteration implementation of __delitem__
1601 # has to keep looping to find the first object we delete.
1602 objs.reverse()
Tim Peters50d8b8b2003-05-25 17:44:31 +00001603
Tim Peters886128f2003-05-25 01:45:11 +00001604 # Turn on mutation in C.__eq__. The first time thru the loop,
1605 # under the iterkeys() business the first comparison will delete
1606 # the last item iterkeys() would see, and that causes a
1607 # RuntimeError: dictionary changed size during iteration
1608 # when the iterkeys() loop goes around to try comparing the next
Tim Peters50d8b8b2003-05-25 17:44:31 +00001609 # key. After this was fixed, it just deletes the last object *our*
Tim Peters886128f2003-05-25 01:45:11 +00001610 # "for o in obj" loop would have gotten to.
1611 mutate = True
1612 count = 0
1613 for o in objs:
1614 count += 1
1615 del d[o]
1616 self.assertEqual(len(d), 0)
1617 self.assertEqual(count, 2)
1618
Serhiy Storchaka0c937b32014-07-22 12:14:52 +03001619 def test_make_weak_valued_dict_repr(self):
1620 dict = weakref.WeakValueDictionary()
1621 self.assertRegex(repr(dict), '<WeakValueDictionary at 0x.*>')
1622
1623 def test_make_weak_keyed_dict_repr(self):
1624 dict = weakref.WeakKeyDictionary()
1625 self.assertRegex(repr(dict), '<WeakKeyDictionary at 0x.*>')
1626
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001627from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001628
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001629class WeakValueDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +00001630 """Check that WeakValueDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001631 __ref = {"key1":Object(1), "key2":Object(2), "key3":Object(3)}
Walter Dörwald118f9312004-06-02 18:42:25 +00001632 type2test = weakref.WeakValueDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001633 def _reference(self):
1634 return self.__ref.copy()
1635
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001636class WeakKeyDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +00001637 """Check that WeakKeyDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001638 __ref = {Object("key1"):1, Object("key2"):2, Object("key3"):3}
Walter Dörwald118f9312004-06-02 18:42:25 +00001639 type2test = weakref.WeakKeyDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001640 def _reference(self):
1641 return self.__ref.copy()
Martin v. Löwis5e163332001-02-27 18:36:56 +00001642
Richard Oudkerk7a3dae02013-05-05 23:05:00 +01001643
1644class FinalizeTestCase(unittest.TestCase):
1645
1646 class A:
1647 pass
1648
1649 def _collect_if_necessary(self):
1650 # we create no ref-cycles so in CPython no gc should be needed
1651 if sys.implementation.name != 'cpython':
1652 support.gc_collect()
1653
1654 def test_finalize(self):
1655 def add(x,y,z):
1656 res.append(x + y + z)
1657 return x + y + z
1658
1659 a = self.A()
1660
1661 res = []
1662 f = weakref.finalize(a, add, 67, 43, z=89)
1663 self.assertEqual(f.alive, True)
1664 self.assertEqual(f.peek(), (a, add, (67,43), {'z':89}))
1665 self.assertEqual(f(), 199)
1666 self.assertEqual(f(), None)
1667 self.assertEqual(f(), None)
1668 self.assertEqual(f.peek(), None)
1669 self.assertEqual(f.detach(), None)
1670 self.assertEqual(f.alive, False)
1671 self.assertEqual(res, [199])
1672
1673 res = []
1674 f = weakref.finalize(a, add, 67, 43, 89)
1675 self.assertEqual(f.peek(), (a, add, (67,43,89), {}))
1676 self.assertEqual(f.detach(), (a, add, (67,43,89), {}))
1677 self.assertEqual(f(), None)
1678 self.assertEqual(f(), None)
1679 self.assertEqual(f.peek(), None)
1680 self.assertEqual(f.detach(), None)
1681 self.assertEqual(f.alive, False)
1682 self.assertEqual(res, [])
1683
1684 res = []
1685 f = weakref.finalize(a, add, x=67, y=43, z=89)
1686 del a
1687 self._collect_if_necessary()
1688 self.assertEqual(f(), None)
1689 self.assertEqual(f(), None)
1690 self.assertEqual(f.peek(), None)
1691 self.assertEqual(f.detach(), None)
1692 self.assertEqual(f.alive, False)
1693 self.assertEqual(res, [199])
1694
1695 def test_order(self):
1696 a = self.A()
1697 res = []
1698
1699 f1 = weakref.finalize(a, res.append, 'f1')
1700 f2 = weakref.finalize(a, res.append, 'f2')
1701 f3 = weakref.finalize(a, res.append, 'f3')
1702 f4 = weakref.finalize(a, res.append, 'f4')
1703 f5 = weakref.finalize(a, res.append, 'f5')
1704
1705 # make sure finalizers can keep themselves alive
1706 del f1, f4
1707
1708 self.assertTrue(f2.alive)
1709 self.assertTrue(f3.alive)
1710 self.assertTrue(f5.alive)
1711
1712 self.assertTrue(f5.detach())
1713 self.assertFalse(f5.alive)
1714
1715 f5() # nothing because previously unregistered
1716 res.append('A')
1717 f3() # => res.append('f3')
1718 self.assertFalse(f3.alive)
1719 res.append('B')
1720 f3() # nothing because previously called
1721 res.append('C')
1722 del a
1723 self._collect_if_necessary()
1724 # => res.append('f4')
1725 # => res.append('f2')
1726 # => res.append('f1')
1727 self.assertFalse(f2.alive)
1728 res.append('D')
1729 f2() # nothing because previously called by gc
1730
1731 expected = ['A', 'f3', 'B', 'C', 'f4', 'f2', 'f1', 'D']
1732 self.assertEqual(res, expected)
1733
1734 def test_all_freed(self):
1735 # we want a weakrefable subclass of weakref.finalize
1736 class MyFinalizer(weakref.finalize):
1737 pass
1738
1739 a = self.A()
1740 res = []
1741 def callback():
1742 res.append(123)
1743 f = MyFinalizer(a, callback)
1744
1745 wr_callback = weakref.ref(callback)
1746 wr_f = weakref.ref(f)
1747 del callback, f
1748
1749 self.assertIsNotNone(wr_callback())
1750 self.assertIsNotNone(wr_f())
1751
1752 del a
1753 self._collect_if_necessary()
1754
1755 self.assertIsNone(wr_callback())
1756 self.assertIsNone(wr_f())
1757 self.assertEqual(res, [123])
1758
1759 @classmethod
1760 def run_in_child(cls):
1761 def error():
1762 # Create an atexit finalizer from inside a finalizer called
1763 # at exit. This should be the next to be run.
1764 g1 = weakref.finalize(cls, print, 'g1')
1765 print('f3 error')
1766 1/0
1767
1768 # cls should stay alive till atexit callbacks run
1769 f1 = weakref.finalize(cls, print, 'f1', _global_var)
1770 f2 = weakref.finalize(cls, print, 'f2', _global_var)
1771 f3 = weakref.finalize(cls, error)
1772 f4 = weakref.finalize(cls, print, 'f4', _global_var)
1773
1774 assert f1.atexit == True
1775 f2.atexit = False
1776 assert f3.atexit == True
1777 assert f4.atexit == True
1778
1779 def test_atexit(self):
1780 prog = ('from test.test_weakref import FinalizeTestCase;'+
1781 'FinalizeTestCase.run_in_child()')
1782 rc, out, err = script_helper.assert_python_ok('-c', prog)
1783 out = out.decode('ascii').splitlines()
1784 self.assertEqual(out, ['f4 foobar', 'f3 error', 'g1', 'f1 foobar'])
1785 self.assertTrue(b'ZeroDivisionError' in err)
1786
1787
Georg Brandlb533e262008-05-25 18:19:30 +00001788libreftest = """ Doctest for examples in the library reference: weakref.rst
Georg Brandl9a65d582005-07-02 19:07:30 +00001789
1790>>> import weakref
1791>>> class Dict(dict):
1792... pass
1793...
1794>>> obj = Dict(red=1, green=2, blue=3) # this object is weak referencable
1795>>> r = weakref.ref(obj)
Guido van Rossum7131f842007-02-09 20:13:25 +00001796>>> print(r() is obj)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001797True
Georg Brandl9a65d582005-07-02 19:07:30 +00001798
1799>>> import weakref
1800>>> class Object:
1801... pass
1802...
1803>>> o = Object()
1804>>> r = weakref.ref(o)
1805>>> o2 = r()
1806>>> o is o2
1807True
1808>>> del o, o2
Guido van Rossum7131f842007-02-09 20:13:25 +00001809>>> print(r())
Georg Brandl9a65d582005-07-02 19:07:30 +00001810None
1811
1812>>> import weakref
1813>>> class ExtendedRef(weakref.ref):
1814... def __init__(self, ob, callback=None, **annotations):
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001815... super().__init__(ob, callback)
Georg Brandl9a65d582005-07-02 19:07:30 +00001816... self.__counter = 0
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001817... for k, v in annotations.items():
Georg Brandl9a65d582005-07-02 19:07:30 +00001818... setattr(self, k, v)
1819... def __call__(self):
1820... '''Return a pair containing the referent and the number of
1821... times the reference has been called.
1822... '''
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001823... ob = super().__call__()
Georg Brandl9a65d582005-07-02 19:07:30 +00001824... if ob is not None:
1825... self.__counter += 1
1826... ob = (ob, self.__counter)
1827... return ob
Guido van Rossumd8faa362007-04-27 19:54:29 +00001828...
Georg Brandl9a65d582005-07-02 19:07:30 +00001829>>> class A: # not in docs from here, just testing the ExtendedRef
1830... pass
1831...
1832>>> a = A()
1833>>> r = ExtendedRef(a, foo=1, bar="baz")
1834>>> r.foo
18351
1836>>> r.bar
1837'baz'
1838>>> r()[1]
18391
1840>>> r()[1]
18412
1842>>> r()[0] is a
1843True
1844
1845
1846>>> import weakref
1847>>> _id2obj_dict = weakref.WeakValueDictionary()
1848>>> def remember(obj):
1849... oid = id(obj)
1850... _id2obj_dict[oid] = obj
1851... return oid
1852...
1853>>> def id2obj(oid):
1854... return _id2obj_dict[oid]
1855...
1856>>> a = A() # from here, just testing
1857>>> a_id = remember(a)
1858>>> id2obj(a_id) is a
1859True
1860>>> del a
1861>>> try:
1862... id2obj(a_id)
1863... except KeyError:
Guido van Rossum7131f842007-02-09 20:13:25 +00001864... print('OK')
Georg Brandl9a65d582005-07-02 19:07:30 +00001865... else:
Guido van Rossum7131f842007-02-09 20:13:25 +00001866... print('WeakValueDictionary error')
Georg Brandl9a65d582005-07-02 19:07:30 +00001867OK
1868
1869"""
1870
1871__test__ = {'libreftest' : libreftest}
1872
Fred Drake2e2be372001-09-20 21:33:42 +00001873def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001874 support.run_unittest(
Walter Dörwald21d3a322003-05-01 17:45:56 +00001875 ReferencesTestCase,
Antoine Pitrouc3afba12012-11-17 18:57:38 +01001876 WeakMethodTestCase,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001877 MappingTestCase,
1878 WeakValueDictionaryTestCase,
Fred Drakef425b1e2003-07-14 21:37:17 +00001879 WeakKeyDictionaryTestCase,
Amaury Forgeot d'Arcc856c7a2008-06-16 19:50:09 +00001880 SubclassableWeakrefTestCase,
Richard Oudkerk7a3dae02013-05-05 23:05:00 +01001881 FinalizeTestCase,
Fred Drakef425b1e2003-07-14 21:37:17 +00001882 )
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001883 support.run_doctest(sys.modules[__name__])
Fred Drake2e2be372001-09-20 21:33:42 +00001884
1885
1886if __name__ == "__main__":
1887 test_main()