blob: a474a077b76d3600be6e8879b251178a7708c993 [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 Oudkerk7a3dae052013-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
Serhiy Storchakaa7930372016-07-03 22:27:26 +0300592 @support.requires_type_collecting
Tim Peters403a2032003-11-20 21:21:46 +0000593 def test_callback_in_cycle_resurrection(self):
594 import gc
595
596 # Do something nasty in a weakref callback: resurrect objects
597 # from dead cycles. For this to be attempted, the weakref and
598 # its callback must also be part of the cyclic trash (else the
599 # objects reachable via the callback couldn't be in cyclic trash
600 # to begin with -- the callback would act like an external root).
601 # But gc clears trash weakrefs with callbacks early now, which
602 # disables the callbacks, so the callbacks shouldn't get called
603 # at all (and so nothing actually gets resurrected).
604
605 alist = []
606 class C(object):
607 def __init__(self, value):
608 self.attribute = value
609
610 def acallback(self, ignore):
611 alist.append(self.c)
612
613 c1, c2 = C(1), C(2)
614 c1.c = c2
615 c2.c = c1
616 c1.wr = weakref.ref(c2, c1.acallback)
617 c2.wr = weakref.ref(c1, c2.acallback)
618
619 def C_went_away(ignore):
620 alist.append("C went away")
621 wr = weakref.ref(C, C_went_away)
622
623 del c1, c2, C # make them all trash
624 self.assertEqual(alist, []) # del isn't enough to reclaim anything
625
626 gc.collect()
627 # c1.wr and c2.wr were part of the cyclic trash, so should have
628 # been cleared without their callbacks executing. OTOH, the weakref
629 # to C is bound to a function local (wr), and wasn't trash, so that
630 # callback should have been invoked when C went away.
631 self.assertEqual(alist, ["C went away"])
632 # The remaining weakref should be dead now (its callback ran).
633 self.assertEqual(wr(), None)
634
635 del alist[:]
636 gc.collect()
637 self.assertEqual(alist, [])
638
639 def test_callbacks_on_callback(self):
640 import gc
641
642 # Set up weakref callbacks *on* weakref callbacks.
643 alist = []
644 def safe_callback(ignore):
645 alist.append("safe_callback called")
646
647 class C(object):
648 def cb(self, ignore):
649 alist.append("cb called")
650
651 c, d = C(), C()
652 c.other = d
653 d.other = c
654 callback = c.cb
655 c.wr = weakref.ref(d, callback) # this won't trigger
656 d.wr = weakref.ref(callback, d.cb) # ditto
657 external_wr = weakref.ref(callback, safe_callback) # but this will
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200658 self.assertIs(external_wr(), callback)
Tim Peters403a2032003-11-20 21:21:46 +0000659
660 # The weakrefs attached to c and d should get cleared, so that
661 # C.cb is never called. But external_wr isn't part of the cyclic
662 # trash, and no cyclic trash is reachable from it, so safe_callback
663 # should get invoked when the bound method object callback (c.cb)
664 # -- which is itself a callback, and also part of the cyclic trash --
665 # gets reclaimed at the end of gc.
666
667 del callback, c, d, C
668 self.assertEqual(alist, []) # del isn't enough to clean up cycles
669 gc.collect()
670 self.assertEqual(alist, ["safe_callback called"])
671 self.assertEqual(external_wr(), None)
672
673 del alist[:]
674 gc.collect()
675 self.assertEqual(alist, [])
676
Fred Drakebc875f52004-02-04 23:14:14 +0000677 def test_gc_during_ref_creation(self):
678 self.check_gc_during_creation(weakref.ref)
679
680 def test_gc_during_proxy_creation(self):
681 self.check_gc_during_creation(weakref.proxy)
682
683 def check_gc_during_creation(self, makeref):
684 thresholds = gc.get_threshold()
685 gc.set_threshold(1, 1, 1)
686 gc.collect()
Fred Drake55cf4342004-02-13 19:21:57 +0000687 class A:
688 pass
Fred Drakebc875f52004-02-04 23:14:14 +0000689
690 def callback(*args):
691 pass
692
Fred Drake55cf4342004-02-13 19:21:57 +0000693 referenced = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000694
Fred Drake55cf4342004-02-13 19:21:57 +0000695 a = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000696 a.a = a
697 a.wr = makeref(referenced)
698
699 try:
700 # now make sure the object and the ref get labeled as
701 # cyclic trash:
Fred Drake55cf4342004-02-13 19:21:57 +0000702 a = A()
703 weakref.ref(referenced, callback)
Fred Drakebc875f52004-02-04 23:14:14 +0000704
705 finally:
706 gc.set_threshold(*thresholds)
707
Thomas Woutersb2137042007-02-01 18:02:27 +0000708 def test_ref_created_during_del(self):
709 # Bug #1377858
710 # A weakref created in an object's __del__() would crash the
711 # interpreter when the weakref was cleaned up since it would refer to
712 # non-existent memory. This test should not segfault the interpreter.
713 class Target(object):
714 def __del__(self):
715 global ref_from_del
716 ref_from_del = weakref.ref(self)
717
718 w = Target()
719
Benjamin Peterson9aa42992008-09-10 21:57:34 +0000720 def test_init(self):
721 # Issue 3634
722 # <weakref to class>.__init__() doesn't check errors correctly
723 r = weakref.ref(Exception)
724 self.assertRaises(TypeError, r.__init__, 0, 0, 0, 0, 0)
725 # No exception should be raised here
726 gc.collect()
727
Antoine Pitrou3af01a12010-03-31 21:40:47 +0000728 def test_classes(self):
729 # Check that classes are weakrefable.
730 class A(object):
731 pass
732 l = []
733 weakref.ref(int)
734 a = weakref.ref(A, l.append)
735 A = None
736 gc.collect()
737 self.assertEqual(a(), None)
738 self.assertEqual(l, [a])
739
Antoine Pitroue11fecb2012-11-11 19:36:51 +0100740 def test_equality(self):
741 # Alive weakrefs defer equality testing to their underlying object.
742 x = Object(1)
743 y = Object(1)
744 z = Object(2)
745 a = weakref.ref(x)
746 b = weakref.ref(y)
747 c = weakref.ref(z)
748 d = weakref.ref(x)
749 # Note how we directly test the operators here, to stress both
750 # __eq__ and __ne__.
751 self.assertTrue(a == b)
752 self.assertFalse(a != b)
753 self.assertFalse(a == c)
754 self.assertTrue(a != c)
755 self.assertTrue(a == d)
756 self.assertFalse(a != d)
757 del x, y, z
758 gc.collect()
759 for r in a, b, c:
760 # Sanity check
761 self.assertIs(r(), None)
762 # Dead weakrefs compare by identity: whether `a` and `d` are the
763 # same weakref object is an implementation detail, since they pointed
764 # to the same original object and didn't have a callback.
765 # (see issue #16453).
766 self.assertFalse(a == b)
767 self.assertTrue(a != b)
768 self.assertFalse(a == c)
769 self.assertTrue(a != c)
770 self.assertEqual(a == d, a is d)
771 self.assertEqual(a != d, a is not d)
772
773 def test_ordering(self):
774 # weakrefs cannot be ordered, even if the underlying objects can.
775 ops = [operator.lt, operator.gt, operator.le, operator.ge]
776 x = Object(1)
777 y = Object(1)
778 a = weakref.ref(x)
779 b = weakref.ref(y)
780 for op in ops:
781 self.assertRaises(TypeError, op, a, b)
782 # Same when dead.
783 del x, y
784 gc.collect()
785 for op in ops:
786 self.assertRaises(TypeError, op, a, b)
787
788 def test_hashing(self):
789 # Alive weakrefs hash the same as the underlying object
790 x = Object(42)
791 y = Object(42)
792 a = weakref.ref(x)
793 b = weakref.ref(y)
794 self.assertEqual(hash(a), hash(42))
795 del x, y
796 gc.collect()
797 # Dead weakrefs:
798 # - retain their hash is they were hashed when alive;
799 # - otherwise, cannot be hashed.
800 self.assertEqual(hash(a), hash(42))
801 self.assertRaises(TypeError, hash, b)
802
Antoine Pitrou62a0d6e2012-12-08 21:15:26 +0100803 def test_trashcan_16602(self):
804 # Issue #16602: when a weakref's target was part of a long
805 # deallocation chain, the trashcan mechanism could delay clearing
806 # of the weakref and make the target object visible from outside
807 # code even though its refcount had dropped to 0. A crash ensued.
808 class C:
809 def __init__(self, parent):
810 if not parent:
811 return
812 wself = weakref.ref(self)
813 def cb(wparent):
814 o = wself()
815 self.wparent = weakref.ref(parent, cb)
816
817 d = weakref.WeakKeyDictionary()
818 root = c = C(None)
819 for n in range(100):
820 d[c] = c = C(c)
821 del root
822 gc.collect()
823
Mark Dickinson556e94b2013-04-13 15:45:44 +0100824 def test_callback_attribute(self):
825 x = Object(1)
826 callback = lambda ref: None
827 ref1 = weakref.ref(x, callback)
828 self.assertIs(ref1.__callback__, callback)
829
830 ref2 = weakref.ref(x)
831 self.assertIsNone(ref2.__callback__)
832
833 def test_callback_attribute_after_deletion(self):
834 x = Object(1)
835 ref = weakref.ref(x, self.callback)
836 self.assertIsNotNone(ref.__callback__)
837 del x
838 support.gc_collect()
839 self.assertIsNone(ref.__callback__)
840
841 def test_set_callback_attribute(self):
842 x = Object(1)
843 callback = lambda ref: None
844 ref1 = weakref.ref(x, callback)
845 with self.assertRaises(AttributeError):
846 ref1.__callback__ = lambda ref: None
847
Benjamin Peterson8f657c32016-10-04 00:00:02 -0700848 def test_callback_gcs(self):
849 class ObjectWithDel(Object):
850 def __del__(self): pass
851 x = ObjectWithDel(1)
852 ref1 = weakref.ref(x, lambda ref: support.gc_collect())
853 del x
854 support.gc_collect()
855
Fred Drake0a4dd392004-07-02 18:57:45 +0000856
Amaury Forgeot d'Arcc856c7a2008-06-16 19:50:09 +0000857class SubclassableWeakrefTestCase(TestBase):
Fred Drake0a4dd392004-07-02 18:57:45 +0000858
859 def test_subclass_refs(self):
860 class MyRef(weakref.ref):
861 def __init__(self, ob, callback=None, value=42):
862 self.value = value
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000863 super().__init__(ob, callback)
Fred Drake0a4dd392004-07-02 18:57:45 +0000864 def __call__(self):
865 self.called = True
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000866 return super().__call__()
Fred Drake0a4dd392004-07-02 18:57:45 +0000867 o = Object("foo")
868 mr = MyRef(o, value=24)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200869 self.assertIs(mr(), o)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000870 self.assertTrue(mr.called)
Fred Drake0a4dd392004-07-02 18:57:45 +0000871 self.assertEqual(mr.value, 24)
872 del o
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200873 self.assertIsNone(mr())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000874 self.assertTrue(mr.called)
Fred Drake0a4dd392004-07-02 18:57:45 +0000875
876 def test_subclass_refs_dont_replace_standard_refs(self):
877 class MyRef(weakref.ref):
878 pass
879 o = Object(42)
880 r1 = MyRef(o)
881 r2 = weakref.ref(o)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200882 self.assertIsNot(r1, r2)
Fred Drake0a4dd392004-07-02 18:57:45 +0000883 self.assertEqual(weakref.getweakrefs(o), [r2, r1])
884 self.assertEqual(weakref.getweakrefcount(o), 2)
885 r3 = MyRef(o)
886 self.assertEqual(weakref.getweakrefcount(o), 3)
887 refs = weakref.getweakrefs(o)
888 self.assertEqual(len(refs), 3)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200889 self.assertIs(r2, refs[0])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000890 self.assertIn(r1, refs[1:])
891 self.assertIn(r3, refs[1:])
Fred Drake0a4dd392004-07-02 18:57:45 +0000892
893 def test_subclass_refs_dont_conflate_callbacks(self):
894 class MyRef(weakref.ref):
895 pass
896 o = Object(42)
897 r1 = MyRef(o, id)
898 r2 = MyRef(o, str)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200899 self.assertIsNot(r1, r2)
Fred Drake0a4dd392004-07-02 18:57:45 +0000900 refs = weakref.getweakrefs(o)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000901 self.assertIn(r1, refs)
902 self.assertIn(r2, refs)
Fred Drake0a4dd392004-07-02 18:57:45 +0000903
904 def test_subclass_refs_with_slots(self):
905 class MyRef(weakref.ref):
906 __slots__ = "slot1", "slot2"
907 def __new__(type, ob, callback, slot1, slot2):
908 return weakref.ref.__new__(type, ob, callback)
909 def __init__(self, ob, callback, slot1, slot2):
910 self.slot1 = slot1
911 self.slot2 = slot2
912 def meth(self):
913 return self.slot1 + self.slot2
914 o = Object(42)
915 r = MyRef(o, None, "abc", "def")
916 self.assertEqual(r.slot1, "abc")
917 self.assertEqual(r.slot2, "def")
918 self.assertEqual(r.meth(), "abcdef")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000919 self.assertFalse(hasattr(r, "__dict__"))
Fred Drake0a4dd392004-07-02 18:57:45 +0000920
Amaury Forgeot d'Arcc856c7a2008-06-16 19:50:09 +0000921 def test_subclass_refs_with_cycle(self):
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)cd14d5d2016-09-07 00:22:22 +0000922 """Confirm https://bugs.python.org/issue3100 is fixed."""
Amaury Forgeot d'Arcc856c7a2008-06-16 19:50:09 +0000923 # An instance of a weakref subclass can have attributes.
924 # If such a weakref holds the only strong reference to the object,
925 # deleting the weakref will delete the object. In this case,
926 # the callback must not be called, because the ref object is
927 # being deleted.
928 class MyRef(weakref.ref):
929 pass
930
931 # Use a local callback, for "regrtest -R::"
932 # to detect refcounting problems
933 def callback(w):
934 self.cbcalled += 1
935
936 o = C()
937 r1 = MyRef(o, callback)
938 r1.o = o
939 del o
940
941 del r1 # Used to crash here
942
943 self.assertEqual(self.cbcalled, 0)
944
945 # Same test, with two weakrefs to the same object
946 # (since code paths are different)
947 o = C()
948 r1 = MyRef(o, callback)
949 r2 = MyRef(o, callback)
950 r1.r = r2
951 r2.o = o
952 del o
953 del r2
954
955 del r1 # Used to crash here
956
957 self.assertEqual(self.cbcalled, 0)
958
Fred Drake0a4dd392004-07-02 18:57:45 +0000959
Antoine Pitrouc3afba12012-11-17 18:57:38 +0100960class WeakMethodTestCase(unittest.TestCase):
961
962 def _subclass(self):
Martin Panter7462b6492015-11-02 03:37:02 +0000963 """Return an Object subclass overriding `some_method`."""
Antoine Pitrouc3afba12012-11-17 18:57:38 +0100964 class C(Object):
965 def some_method(self):
966 return 6
967 return C
968
969 def test_alive(self):
970 o = Object(1)
971 r = weakref.WeakMethod(o.some_method)
972 self.assertIsInstance(r, weakref.ReferenceType)
973 self.assertIsInstance(r(), type(o.some_method))
974 self.assertIs(r().__self__, o)
975 self.assertIs(r().__func__, o.some_method.__func__)
976 self.assertEqual(r()(), 4)
977
978 def test_object_dead(self):
979 o = Object(1)
980 r = weakref.WeakMethod(o.some_method)
981 del o
982 gc.collect()
983 self.assertIs(r(), None)
984
985 def test_method_dead(self):
986 C = self._subclass()
987 o = C(1)
988 r = weakref.WeakMethod(o.some_method)
989 del C.some_method
990 gc.collect()
991 self.assertIs(r(), None)
992
993 def test_callback_when_object_dead(self):
994 # Test callback behaviour when object dies first.
995 C = self._subclass()
996 calls = []
997 def cb(arg):
998 calls.append(arg)
999 o = C(1)
1000 r = weakref.WeakMethod(o.some_method, cb)
1001 del o
1002 gc.collect()
1003 self.assertEqual(calls, [r])
1004 # Callback is only called once.
1005 C.some_method = Object.some_method
1006 gc.collect()
1007 self.assertEqual(calls, [r])
1008
1009 def test_callback_when_method_dead(self):
1010 # Test callback behaviour when method dies first.
1011 C = self._subclass()
1012 calls = []
1013 def cb(arg):
1014 calls.append(arg)
1015 o = C(1)
1016 r = weakref.WeakMethod(o.some_method, cb)
1017 del C.some_method
1018 gc.collect()
1019 self.assertEqual(calls, [r])
1020 # Callback is only called once.
1021 del o
1022 gc.collect()
1023 self.assertEqual(calls, [r])
1024
1025 @support.cpython_only
1026 def test_no_cycles(self):
1027 # A WeakMethod doesn't create any reference cycle to itself.
1028 o = Object(1)
1029 def cb(_):
1030 pass
1031 r = weakref.WeakMethod(o.some_method, cb)
1032 wr = weakref.ref(r)
1033 del r
1034 self.assertIs(wr(), None)
1035
1036 def test_equality(self):
1037 def _eq(a, b):
1038 self.assertTrue(a == b)
1039 self.assertFalse(a != b)
1040 def _ne(a, b):
1041 self.assertTrue(a != b)
1042 self.assertFalse(a == b)
1043 x = Object(1)
1044 y = Object(1)
1045 a = weakref.WeakMethod(x.some_method)
1046 b = weakref.WeakMethod(y.some_method)
1047 c = weakref.WeakMethod(x.other_method)
1048 d = weakref.WeakMethod(y.other_method)
1049 # Objects equal, same method
1050 _eq(a, b)
1051 _eq(c, d)
1052 # Objects equal, different method
1053 _ne(a, c)
1054 _ne(a, d)
1055 _ne(b, c)
1056 _ne(b, d)
1057 # Objects unequal, same or different method
1058 z = Object(2)
1059 e = weakref.WeakMethod(z.some_method)
1060 f = weakref.WeakMethod(z.other_method)
1061 _ne(a, e)
1062 _ne(a, f)
1063 _ne(b, e)
1064 _ne(b, f)
1065 del x, y, z
1066 gc.collect()
1067 # Dead WeakMethods compare by identity
1068 refs = a, b, c, d, e, f
1069 for q in refs:
1070 for r in refs:
1071 self.assertEqual(q == r, q is r)
1072 self.assertEqual(q != r, q is not r)
1073
1074 def test_hashing(self):
1075 # Alive WeakMethods are hashable if the underlying object is
1076 # hashable.
1077 x = Object(1)
1078 y = Object(1)
1079 a = weakref.WeakMethod(x.some_method)
1080 b = weakref.WeakMethod(y.some_method)
1081 c = weakref.WeakMethod(y.other_method)
1082 # Since WeakMethod objects are equal, the hashes should be equal.
1083 self.assertEqual(hash(a), hash(b))
1084 ha = hash(a)
1085 # Dead WeakMethods retain their old hash value
1086 del x, y
1087 gc.collect()
1088 self.assertEqual(hash(a), ha)
1089 self.assertEqual(hash(b), ha)
1090 # If it wasn't hashed when alive, a dead WeakMethod cannot be hashed.
1091 self.assertRaises(TypeError, hash, c)
1092
1093
Fred Drakeb0fefc52001-03-23 04:22:45 +00001094class MappingTestCase(TestBase):
Martin v. Löwis5e163332001-02-27 18:36:56 +00001095
Fred Drakeb0fefc52001-03-23 04:22:45 +00001096 COUNT = 10
1097
Antoine Pitroubbe2f602012-03-01 16:26:35 +01001098 def check_len_cycles(self, dict_type, cons):
1099 N = 20
1100 items = [RefCycle() for i in range(N)]
1101 dct = dict_type(cons(o) for o in items)
1102 # Keep an iterator alive
1103 it = dct.items()
1104 try:
1105 next(it)
1106 except StopIteration:
1107 pass
1108 del items
1109 gc.collect()
1110 n1 = len(dct)
1111 del it
1112 gc.collect()
1113 n2 = len(dct)
1114 # one item may be kept alive inside the iterator
1115 self.assertIn(n1, (0, 1))
1116 self.assertEqual(n2, 0)
1117
1118 def test_weak_keyed_len_cycles(self):
1119 self.check_len_cycles(weakref.WeakKeyDictionary, lambda k: (k, 1))
1120
1121 def test_weak_valued_len_cycles(self):
1122 self.check_len_cycles(weakref.WeakValueDictionary, lambda k: (1, k))
1123
1124 def check_len_race(self, dict_type, cons):
1125 # Extended sanity checks for len() in the face of cyclic collection
1126 self.addCleanup(gc.set_threshold, *gc.get_threshold())
1127 for th in range(1, 100):
1128 N = 20
1129 gc.collect(0)
1130 gc.set_threshold(th, th, th)
1131 items = [RefCycle() for i in range(N)]
1132 dct = dict_type(cons(o) for o in items)
1133 del items
1134 # All items will be collected at next garbage collection pass
1135 it = dct.items()
1136 try:
1137 next(it)
1138 except StopIteration:
1139 pass
1140 n1 = len(dct)
1141 del it
1142 n2 = len(dct)
1143 self.assertGreaterEqual(n1, 0)
1144 self.assertLessEqual(n1, N)
1145 self.assertGreaterEqual(n2, 0)
1146 self.assertLessEqual(n2, n1)
1147
1148 def test_weak_keyed_len_race(self):
1149 self.check_len_race(weakref.WeakKeyDictionary, lambda k: (k, 1))
1150
1151 def test_weak_valued_len_race(self):
1152 self.check_len_race(weakref.WeakValueDictionary, lambda k: (1, k))
1153
Fred Drakeb0fefc52001-03-23 04:22:45 +00001154 def test_weak_values(self):
Fred Drake0e540c32001-05-02 05:44:22 +00001155 #
1156 # This exercises d.copy(), d.items(), d[], del d[], len(d).
1157 #
1158 dict, objects = self.make_weak_valued_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +00001159 for o in objects:
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001160 self.assertEqual(weakref.getweakrefcount(o), 1)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001161 self.assertIs(o, dict[o.arg],
Fred Drakeb0fefc52001-03-23 04:22:45 +00001162 "wrong object returned by weak dict!")
Barry Warsawecaab832008-09-04 01:42:51 +00001163 items1 = list(dict.items())
1164 items2 = list(dict.copy().items())
Fred Drakeb0fefc52001-03-23 04:22:45 +00001165 items1.sort()
1166 items2.sort()
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001167 self.assertEqual(items1, items2,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001168 "cloning of weak-valued dictionary did not work!")
1169 del items1, items2
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001170 self.assertEqual(len(dict), self.COUNT)
Fred Drakeb0fefc52001-03-23 04:22:45 +00001171 del objects[0]
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001172 self.assertEqual(len(dict), self.COUNT - 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001173 "deleting object did not cause dictionary update")
1174 del objects, o
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001175 self.assertEqual(len(dict), 0,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001176 "deleting the values did not clear the dictionary")
Fred Drake4fd06e02001-08-03 04:11:27 +00001177 # regression on SF bug #447152:
1178 dict = weakref.WeakValueDictionary()
1179 self.assertRaises(KeyError, dict.__getitem__, 1)
1180 dict[2] = C()
1181 self.assertRaises(KeyError, dict.__getitem__, 2)
Fred Drakeb0fefc52001-03-23 04:22:45 +00001182
1183 def test_weak_keys(self):
Fred Drake0e540c32001-05-02 05:44:22 +00001184 #
1185 # This exercises d.copy(), d.items(), d[] = v, d[], del d[],
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001186 # len(d), k in d.
Fred Drake0e540c32001-05-02 05:44:22 +00001187 #
1188 dict, objects = self.make_weak_keyed_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +00001189 for o in objects:
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001190 self.assertEqual(weakref.getweakrefcount(o), 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001191 "wrong number of weak references to %r!" % o)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001192 self.assertIs(o.arg, dict[o],
Fred Drakeb0fefc52001-03-23 04:22:45 +00001193 "wrong object returned by weak dict!")
1194 items1 = dict.items()
1195 items2 = dict.copy().items()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001196 self.assertEqual(set(items1), set(items2),
Fred Drakeb0fefc52001-03-23 04:22:45 +00001197 "cloning of weak-keyed dictionary did not work!")
1198 del items1, items2
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001199 self.assertEqual(len(dict), self.COUNT)
Fred Drakeb0fefc52001-03-23 04:22:45 +00001200 del objects[0]
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001201 self.assertEqual(len(dict), (self.COUNT - 1),
Fred Drakeb0fefc52001-03-23 04:22:45 +00001202 "deleting object did not cause dictionary update")
1203 del objects, o
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001204 self.assertEqual(len(dict), 0,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001205 "deleting the keys did not clear the dictionary")
Fred Drake752eda42001-11-06 16:38:34 +00001206 o = Object(42)
1207 dict[o] = "What is the meaning of the universe?"
Benjamin Peterson577473f2010-01-19 00:09:57 +00001208 self.assertIn(o, dict)
1209 self.assertNotIn(34, dict)
Martin v. Löwis5e163332001-02-27 18:36:56 +00001210
Fred Drake0e540c32001-05-02 05:44:22 +00001211 def test_weak_keyed_iters(self):
1212 dict, objects = self.make_weak_keyed_dict()
1213 self.check_iters(dict)
1214
Thomas Wouters477c8d52006-05-27 19:21:47 +00001215 # Test keyrefs()
1216 refs = dict.keyrefs()
1217 self.assertEqual(len(refs), len(objects))
1218 objects2 = list(objects)
1219 for wr in refs:
1220 ob = wr()
Benjamin Peterson577473f2010-01-19 00:09:57 +00001221 self.assertIn(ob, dict)
1222 self.assertIn(ob, dict)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001223 self.assertEqual(ob.arg, dict[ob])
1224 objects2.remove(ob)
1225 self.assertEqual(len(objects2), 0)
1226
1227 # Test iterkeyrefs()
1228 objects2 = list(objects)
Barry Warsawecaab832008-09-04 01:42:51 +00001229 self.assertEqual(len(list(dict.keyrefs())), len(objects))
1230 for wr in dict.keyrefs():
Thomas Wouters477c8d52006-05-27 19:21:47 +00001231 ob = wr()
Benjamin Peterson577473f2010-01-19 00:09:57 +00001232 self.assertIn(ob, dict)
1233 self.assertIn(ob, dict)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001234 self.assertEqual(ob.arg, dict[ob])
1235 objects2.remove(ob)
1236 self.assertEqual(len(objects2), 0)
1237
Fred Drake0e540c32001-05-02 05:44:22 +00001238 def test_weak_valued_iters(self):
1239 dict, objects = self.make_weak_valued_dict()
1240 self.check_iters(dict)
1241
Thomas Wouters477c8d52006-05-27 19:21:47 +00001242 # Test valuerefs()
1243 refs = dict.valuerefs()
1244 self.assertEqual(len(refs), len(objects))
1245 objects2 = list(objects)
1246 for wr in refs:
1247 ob = wr()
1248 self.assertEqual(ob, dict[ob.arg])
1249 self.assertEqual(ob.arg, dict[ob.arg].arg)
1250 objects2.remove(ob)
1251 self.assertEqual(len(objects2), 0)
1252
1253 # Test itervaluerefs()
1254 objects2 = list(objects)
1255 self.assertEqual(len(list(dict.itervaluerefs())), len(objects))
1256 for wr in dict.itervaluerefs():
1257 ob = wr()
1258 self.assertEqual(ob, dict[ob.arg])
1259 self.assertEqual(ob.arg, dict[ob.arg].arg)
1260 objects2.remove(ob)
1261 self.assertEqual(len(objects2), 0)
1262
Fred Drake0e540c32001-05-02 05:44:22 +00001263 def check_iters(self, dict):
1264 # item iterator:
Barry Warsawecaab832008-09-04 01:42:51 +00001265 items = list(dict.items())
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001266 for item in dict.items():
Fred Drake0e540c32001-05-02 05:44:22 +00001267 items.remove(item)
Barry Warsawecaab832008-09-04 01:42:51 +00001268 self.assertFalse(items, "items() did not touch all items")
Fred Drake0e540c32001-05-02 05:44:22 +00001269
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001270 # key iterator, via __iter__():
Guido van Rossum07f24362007-02-11 22:59:48 +00001271 keys = list(dict.keys())
Fred Drake0e540c32001-05-02 05:44:22 +00001272 for k in dict:
1273 keys.remove(k)
Barry Warsawecaab832008-09-04 01:42:51 +00001274 self.assertFalse(keys, "__iter__() did not touch all keys")
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001275
1276 # key iterator, via iterkeys():
Guido van Rossum07f24362007-02-11 22:59:48 +00001277 keys = list(dict.keys())
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001278 for k in dict.keys():
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001279 keys.remove(k)
Barry Warsawecaab832008-09-04 01:42:51 +00001280 self.assertFalse(keys, "iterkeys() did not touch all keys")
Fred Drake0e540c32001-05-02 05:44:22 +00001281
1282 # value iterator:
Guido van Rossum07f24362007-02-11 22:59:48 +00001283 values = list(dict.values())
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001284 for v in dict.values():
Fred Drake0e540c32001-05-02 05:44:22 +00001285 values.remove(v)
Barry Warsawecaab832008-09-04 01:42:51 +00001286 self.assertFalse(values,
Fred Drakef425b1e2003-07-14 21:37:17 +00001287 "itervalues() did not touch all values")
Fred Drake0e540c32001-05-02 05:44:22 +00001288
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001289 def check_weak_destroy_while_iterating(self, dict, objects, iter_name):
1290 n = len(dict)
1291 it = iter(getattr(dict, iter_name)())
1292 next(it) # Trigger internal iteration
1293 # Destroy an object
1294 del objects[-1]
1295 gc.collect() # just in case
1296 # We have removed either the first consumed object, or another one
1297 self.assertIn(len(list(it)), [len(objects), len(objects) - 1])
1298 del it
1299 # The removal has been committed
1300 self.assertEqual(len(dict), n - 1)
1301
1302 def check_weak_destroy_and_mutate_while_iterating(self, dict, testcontext):
1303 # Check that we can explicitly mutate the weak dict without
1304 # interfering with delayed removal.
1305 # `testcontext` should create an iterator, destroy one of the
1306 # weakref'ed objects and then return a new key/value pair corresponding
1307 # to the destroyed object.
1308 with testcontext() as (k, v):
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001309 self.assertNotIn(k, dict)
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001310 with testcontext() as (k, v):
1311 self.assertRaises(KeyError, dict.__delitem__, k)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001312 self.assertNotIn(k, dict)
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001313 with testcontext() as (k, v):
1314 self.assertRaises(KeyError, dict.pop, k)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001315 self.assertNotIn(k, dict)
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001316 with testcontext() as (k, v):
1317 dict[k] = v
1318 self.assertEqual(dict[k], v)
1319 ddict = copy.copy(dict)
1320 with testcontext() as (k, v):
1321 dict.update(ddict)
1322 self.assertEqual(dict, ddict)
1323 with testcontext() as (k, v):
1324 dict.clear()
1325 self.assertEqual(len(dict), 0)
1326
Antoine Pitrou1bf974d2014-10-05 20:02:28 +02001327 def check_weak_del_and_len_while_iterating(self, dict, testcontext):
1328 # Check that len() works when both iterating and removing keys
1329 # explicitly through various means (.pop(), .clear()...), while
1330 # implicit mutation is deferred because an iterator is alive.
1331 # (each call to testcontext() should schedule one item for removal
1332 # for this test to work properly)
1333 o = Object(123456)
1334 with testcontext():
1335 n = len(dict)
Victor Stinner742da042016-09-07 17:40:12 -07001336 # Since underlaying dict is ordered, first item is popped
1337 dict.pop(next(dict.keys()))
Antoine Pitrou1bf974d2014-10-05 20:02:28 +02001338 self.assertEqual(len(dict), n - 1)
1339 dict[o] = o
1340 self.assertEqual(len(dict), n)
Victor Stinner742da042016-09-07 17:40:12 -07001341 # last item in objects is removed from dict in context shutdown
Antoine Pitrou1bf974d2014-10-05 20:02:28 +02001342 with testcontext():
1343 self.assertEqual(len(dict), n - 1)
Victor Stinner742da042016-09-07 17:40:12 -07001344 # Then, (o, o) is popped
1345 dict.popitem()
Antoine Pitrou1bf974d2014-10-05 20:02:28 +02001346 self.assertEqual(len(dict), n - 2)
1347 with testcontext():
1348 self.assertEqual(len(dict), n - 3)
1349 del dict[next(dict.keys())]
1350 self.assertEqual(len(dict), n - 4)
1351 with testcontext():
1352 self.assertEqual(len(dict), n - 5)
1353 dict.popitem()
1354 self.assertEqual(len(dict), n - 6)
1355 with testcontext():
1356 dict.clear()
1357 self.assertEqual(len(dict), 0)
1358 self.assertEqual(len(dict), 0)
1359
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001360 def test_weak_keys_destroy_while_iterating(self):
1361 # Issue #7105: iterators shouldn't crash when a key is implicitly removed
1362 dict, objects = self.make_weak_keyed_dict()
1363 self.check_weak_destroy_while_iterating(dict, objects, 'keys')
1364 self.check_weak_destroy_while_iterating(dict, objects, 'items')
1365 self.check_weak_destroy_while_iterating(dict, objects, 'values')
1366 self.check_weak_destroy_while_iterating(dict, objects, 'keyrefs')
1367 dict, objects = self.make_weak_keyed_dict()
1368 @contextlib.contextmanager
1369 def testcontext():
1370 try:
1371 it = iter(dict.items())
1372 next(it)
1373 # Schedule a key/value for removal and recreate it
1374 v = objects.pop().arg
1375 gc.collect() # just in case
1376 yield Object(v), v
1377 finally:
1378 it = None # should commit all removals
Benjamin Peterson18bb7022014-08-24 18:02:15 -05001379 gc.collect()
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001380 self.check_weak_destroy_and_mutate_while_iterating(dict, testcontext)
Antoine Pitrou1bf974d2014-10-05 20:02:28 +02001381 # Issue #21173: len() fragile when keys are both implicitly and
1382 # explicitly removed.
1383 dict, objects = self.make_weak_keyed_dict()
1384 self.check_weak_del_and_len_while_iterating(dict, testcontext)
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001385
1386 def test_weak_values_destroy_while_iterating(self):
1387 # Issue #7105: iterators shouldn't crash when a key is implicitly removed
1388 dict, objects = self.make_weak_valued_dict()
1389 self.check_weak_destroy_while_iterating(dict, objects, 'keys')
1390 self.check_weak_destroy_while_iterating(dict, objects, 'items')
1391 self.check_weak_destroy_while_iterating(dict, objects, 'values')
1392 self.check_weak_destroy_while_iterating(dict, objects, 'itervaluerefs')
1393 self.check_weak_destroy_while_iterating(dict, objects, 'valuerefs')
1394 dict, objects = self.make_weak_valued_dict()
1395 @contextlib.contextmanager
1396 def testcontext():
1397 try:
1398 it = iter(dict.items())
1399 next(it)
1400 # Schedule a key/value for removal and recreate it
1401 k = objects.pop().arg
1402 gc.collect() # just in case
1403 yield k, Object(k)
1404 finally:
1405 it = None # should commit all removals
Benjamin Peterson18bb7022014-08-24 18:02:15 -05001406 gc.collect()
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001407 self.check_weak_destroy_and_mutate_while_iterating(dict, testcontext)
Antoine Pitrou1bf974d2014-10-05 20:02:28 +02001408 dict, objects = self.make_weak_valued_dict()
1409 self.check_weak_del_and_len_while_iterating(dict, testcontext)
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001410
Guido van Rossum009afb72002-06-10 20:00:52 +00001411 def test_make_weak_keyed_dict_from_dict(self):
1412 o = Object(3)
1413 dict = weakref.WeakKeyDictionary({o:364})
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001414 self.assertEqual(dict[o], 364)
Guido van Rossum009afb72002-06-10 20:00:52 +00001415
1416 def test_make_weak_keyed_dict_from_weak_keyed_dict(self):
1417 o = Object(3)
1418 dict = weakref.WeakKeyDictionary({o:364})
1419 dict2 = weakref.WeakKeyDictionary(dict)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001420 self.assertEqual(dict[o], 364)
Guido van Rossum009afb72002-06-10 20:00:52 +00001421
Fred Drake0e540c32001-05-02 05:44:22 +00001422 def make_weak_keyed_dict(self):
1423 dict = weakref.WeakKeyDictionary()
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001424 objects = list(map(Object, range(self.COUNT)))
Fred Drake0e540c32001-05-02 05:44:22 +00001425 for o in objects:
1426 dict[o] = o.arg
1427 return dict, objects
1428
Antoine Pitrouc06de472009-05-30 21:04:26 +00001429 def test_make_weak_valued_dict_from_dict(self):
1430 o = Object(3)
1431 dict = weakref.WeakValueDictionary({364:o})
1432 self.assertEqual(dict[364], o)
1433
1434 def test_make_weak_valued_dict_from_weak_valued_dict(self):
1435 o = Object(3)
1436 dict = weakref.WeakValueDictionary({364:o})
1437 dict2 = weakref.WeakValueDictionary(dict)
1438 self.assertEqual(dict[364], o)
1439
Serhiy Storchakab5102e32015-09-29 23:52:09 +03001440 def test_make_weak_valued_dict_misc(self):
1441 # errors
1442 self.assertRaises(TypeError, weakref.WeakValueDictionary.__init__)
1443 self.assertRaises(TypeError, weakref.WeakValueDictionary, {}, {})
1444 self.assertRaises(TypeError, weakref.WeakValueDictionary, (), ())
1445 # special keyword arguments
1446 o = Object(3)
1447 for kw in 'self', 'dict', 'other', 'iterable':
1448 d = weakref.WeakValueDictionary(**{kw: o})
1449 self.assertEqual(list(d.keys()), [kw])
1450 self.assertEqual(d[kw], o)
1451
Fred Drake0e540c32001-05-02 05:44:22 +00001452 def make_weak_valued_dict(self):
1453 dict = weakref.WeakValueDictionary()
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001454 objects = list(map(Object, range(self.COUNT)))
Fred Drake0e540c32001-05-02 05:44:22 +00001455 for o in objects:
1456 dict[o.arg] = o
1457 return dict, objects
1458
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001459 def check_popitem(self, klass, key1, value1, key2, value2):
1460 weakdict = klass()
1461 weakdict[key1] = value1
1462 weakdict[key2] = value2
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001463 self.assertEqual(len(weakdict), 2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001464 k, v = weakdict.popitem()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001465 self.assertEqual(len(weakdict), 1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001466 if k is key1:
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001467 self.assertIs(v, value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001468 else:
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001469 self.assertIs(v, value2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001470 k, v = weakdict.popitem()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001471 self.assertEqual(len(weakdict), 0)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001472 if k is key1:
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001473 self.assertIs(v, value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001474 else:
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001475 self.assertIs(v, value2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001476
1477 def test_weak_valued_dict_popitem(self):
1478 self.check_popitem(weakref.WeakValueDictionary,
1479 "key1", C(), "key2", C())
1480
1481 def test_weak_keyed_dict_popitem(self):
1482 self.check_popitem(weakref.WeakKeyDictionary,
1483 C(), "value 1", C(), "value 2")
1484
1485 def check_setdefault(self, klass, key, value1, value2):
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001486 self.assertIsNot(value1, value2,
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001487 "invalid test"
1488 " -- value parameters must be distinct objects")
1489 weakdict = klass()
1490 o = weakdict.setdefault(key, value1)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001491 self.assertIs(o, value1)
Benjamin Peterson577473f2010-01-19 00:09:57 +00001492 self.assertIn(key, weakdict)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001493 self.assertIs(weakdict.get(key), value1)
1494 self.assertIs(weakdict[key], value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001495
1496 o = weakdict.setdefault(key, value2)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001497 self.assertIs(o, value1)
Benjamin Peterson577473f2010-01-19 00:09:57 +00001498 self.assertIn(key, weakdict)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001499 self.assertIs(weakdict.get(key), value1)
1500 self.assertIs(weakdict[key], value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001501
1502 def test_weak_valued_dict_setdefault(self):
1503 self.check_setdefault(weakref.WeakValueDictionary,
1504 "key", C(), C())
1505
1506 def test_weak_keyed_dict_setdefault(self):
1507 self.check_setdefault(weakref.WeakKeyDictionary,
1508 C(), "value 1", "value 2")
1509
Fred Drakea0a4ab12001-04-16 17:37:27 +00001510 def check_update(self, klass, dict):
Fred Drake0e540c32001-05-02 05:44:22 +00001511 #
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001512 # This exercises d.update(), len(d), d.keys(), k in d,
Fred Drake0e540c32001-05-02 05:44:22 +00001513 # d.get(), d[].
1514 #
Fred Drakea0a4ab12001-04-16 17:37:27 +00001515 weakdict = klass()
1516 weakdict.update(dict)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001517 self.assertEqual(len(weakdict), len(dict))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001518 for k in weakdict.keys():
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001519 self.assertIn(k, dict, "mysterious new key appeared in weak dict")
Fred Drakea0a4ab12001-04-16 17:37:27 +00001520 v = dict.get(k)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001521 self.assertIs(v, weakdict[k])
1522 self.assertIs(v, weakdict.get(k))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001523 for k in dict.keys():
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001524 self.assertIn(k, weakdict, "original key disappeared in weak dict")
Fred Drakea0a4ab12001-04-16 17:37:27 +00001525 v = dict[k]
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001526 self.assertIs(v, weakdict[k])
1527 self.assertIs(v, weakdict.get(k))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001528
1529 def test_weak_valued_dict_update(self):
1530 self.check_update(weakref.WeakValueDictionary,
1531 {1: C(), 'a': C(), C(): C()})
Serhiy Storchakab5102e32015-09-29 23:52:09 +03001532 # errors
1533 self.assertRaises(TypeError, weakref.WeakValueDictionary.update)
1534 d = weakref.WeakValueDictionary()
1535 self.assertRaises(TypeError, d.update, {}, {})
1536 self.assertRaises(TypeError, d.update, (), ())
1537 self.assertEqual(list(d.keys()), [])
1538 # special keyword arguments
1539 o = Object(3)
1540 for kw in 'self', 'dict', 'other', 'iterable':
1541 d = weakref.WeakValueDictionary()
1542 d.update(**{kw: o})
1543 self.assertEqual(list(d.keys()), [kw])
1544 self.assertEqual(d[kw], o)
Fred Drakea0a4ab12001-04-16 17:37:27 +00001545
1546 def test_weak_keyed_dict_update(self):
1547 self.check_update(weakref.WeakKeyDictionary,
1548 {C(): 1, C(): 2, C(): 3})
1549
Fred Drakeccc75622001-09-06 14:52:39 +00001550 def test_weak_keyed_delitem(self):
1551 d = weakref.WeakKeyDictionary()
1552 o1 = Object('1')
1553 o2 = Object('2')
1554 d[o1] = 'something'
1555 d[o2] = 'something'
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001556 self.assertEqual(len(d), 2)
Fred Drakeccc75622001-09-06 14:52:39 +00001557 del d[o1]
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001558 self.assertEqual(len(d), 1)
Barry Warsawecaab832008-09-04 01:42:51 +00001559 self.assertEqual(list(d.keys()), [o2])
Fred Drakeccc75622001-09-06 14:52:39 +00001560
1561 def test_weak_valued_delitem(self):
1562 d = weakref.WeakValueDictionary()
1563 o1 = Object('1')
1564 o2 = Object('2')
1565 d['something'] = o1
1566 d['something else'] = o2
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001567 self.assertEqual(len(d), 2)
Fred Drakeccc75622001-09-06 14:52:39 +00001568 del d['something']
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001569 self.assertEqual(len(d), 1)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001570 self.assertEqual(list(d.items()), [('something else', o2)])
Fred Drakeccc75622001-09-06 14:52:39 +00001571
Tim Peters886128f2003-05-25 01:45:11 +00001572 def test_weak_keyed_bad_delitem(self):
1573 d = weakref.WeakKeyDictionary()
1574 o = Object('1')
1575 # An attempt to delete an object that isn't there should raise
Tim Peters50d8b8b2003-05-25 17:44:31 +00001576 # KeyError. It didn't before 2.3.
Tim Peters886128f2003-05-25 01:45:11 +00001577 self.assertRaises(KeyError, d.__delitem__, o)
Tim Peters50d8b8b2003-05-25 17:44:31 +00001578 self.assertRaises(KeyError, d.__getitem__, o)
1579
1580 # If a key isn't of a weakly referencable type, __getitem__ and
1581 # __setitem__ raise TypeError. __delitem__ should too.
1582 self.assertRaises(TypeError, d.__delitem__, 13)
1583 self.assertRaises(TypeError, d.__getitem__, 13)
1584 self.assertRaises(TypeError, d.__setitem__, 13, 13)
Tim Peters886128f2003-05-25 01:45:11 +00001585
1586 def test_weak_keyed_cascading_deletes(self):
1587 # SF bug 742860. For some reason, before 2.3 __delitem__ iterated
1588 # over the keys via self.data.iterkeys(). If things vanished from
1589 # the dict during this (or got added), that caused a RuntimeError.
1590
1591 d = weakref.WeakKeyDictionary()
1592 mutate = False
1593
1594 class C(object):
1595 def __init__(self, i):
1596 self.value = i
1597 def __hash__(self):
1598 return hash(self.value)
1599 def __eq__(self, other):
1600 if mutate:
1601 # Side effect that mutates the dict, by removing the
1602 # last strong reference to a key.
1603 del objs[-1]
1604 return self.value == other.value
1605
1606 objs = [C(i) for i in range(4)]
1607 for o in objs:
1608 d[o] = o.value
1609 del o # now the only strong references to keys are in objs
1610 # Find the order in which iterkeys sees the keys.
Barry Warsawecaab832008-09-04 01:42:51 +00001611 objs = list(d.keys())
Tim Peters886128f2003-05-25 01:45:11 +00001612 # Reverse it, so that the iteration implementation of __delitem__
1613 # has to keep looping to find the first object we delete.
1614 objs.reverse()
Tim Peters50d8b8b2003-05-25 17:44:31 +00001615
Tim Peters886128f2003-05-25 01:45:11 +00001616 # Turn on mutation in C.__eq__. The first time thru the loop,
1617 # under the iterkeys() business the first comparison will delete
1618 # the last item iterkeys() would see, and that causes a
1619 # RuntimeError: dictionary changed size during iteration
1620 # when the iterkeys() loop goes around to try comparing the next
Tim Peters50d8b8b2003-05-25 17:44:31 +00001621 # key. After this was fixed, it just deletes the last object *our*
Tim Peters886128f2003-05-25 01:45:11 +00001622 # "for o in obj" loop would have gotten to.
1623 mutate = True
1624 count = 0
1625 for o in objs:
1626 count += 1
1627 del d[o]
1628 self.assertEqual(len(d), 0)
1629 self.assertEqual(count, 2)
1630
Serhiy Storchaka0c937b32014-07-22 12:14:52 +03001631 def test_make_weak_valued_dict_repr(self):
1632 dict = weakref.WeakValueDictionary()
1633 self.assertRegex(repr(dict), '<WeakValueDictionary at 0x.*>')
1634
1635 def test_make_weak_keyed_dict_repr(self):
1636 dict = weakref.WeakKeyDictionary()
1637 self.assertRegex(repr(dict), '<WeakKeyDictionary at 0x.*>')
1638
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001639from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001640
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001641class WeakValueDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +00001642 """Check that WeakValueDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001643 __ref = {"key1":Object(1), "key2":Object(2), "key3":Object(3)}
Walter Dörwald118f9312004-06-02 18:42:25 +00001644 type2test = weakref.WeakValueDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001645 def _reference(self):
1646 return self.__ref.copy()
1647
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001648class WeakKeyDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +00001649 """Check that WeakKeyDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001650 __ref = {Object("key1"):1, Object("key2"):2, Object("key3"):3}
Walter Dörwald118f9312004-06-02 18:42:25 +00001651 type2test = weakref.WeakKeyDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001652 def _reference(self):
1653 return self.__ref.copy()
Martin v. Löwis5e163332001-02-27 18:36:56 +00001654
Richard Oudkerk7a3dae052013-05-05 23:05:00 +01001655
1656class FinalizeTestCase(unittest.TestCase):
1657
1658 class A:
1659 pass
1660
1661 def _collect_if_necessary(self):
1662 # we create no ref-cycles so in CPython no gc should be needed
1663 if sys.implementation.name != 'cpython':
1664 support.gc_collect()
1665
1666 def test_finalize(self):
1667 def add(x,y,z):
1668 res.append(x + y + z)
1669 return x + y + z
1670
1671 a = self.A()
1672
1673 res = []
1674 f = weakref.finalize(a, add, 67, 43, z=89)
1675 self.assertEqual(f.alive, True)
1676 self.assertEqual(f.peek(), (a, add, (67,43), {'z':89}))
1677 self.assertEqual(f(), 199)
1678 self.assertEqual(f(), None)
1679 self.assertEqual(f(), None)
1680 self.assertEqual(f.peek(), None)
1681 self.assertEqual(f.detach(), None)
1682 self.assertEqual(f.alive, False)
1683 self.assertEqual(res, [199])
1684
1685 res = []
1686 f = weakref.finalize(a, add, 67, 43, 89)
1687 self.assertEqual(f.peek(), (a, add, (67,43,89), {}))
1688 self.assertEqual(f.detach(), (a, add, (67,43,89), {}))
1689 self.assertEqual(f(), None)
1690 self.assertEqual(f(), None)
1691 self.assertEqual(f.peek(), None)
1692 self.assertEqual(f.detach(), None)
1693 self.assertEqual(f.alive, False)
1694 self.assertEqual(res, [])
1695
1696 res = []
1697 f = weakref.finalize(a, add, x=67, y=43, z=89)
1698 del a
1699 self._collect_if_necessary()
1700 self.assertEqual(f(), None)
1701 self.assertEqual(f(), None)
1702 self.assertEqual(f.peek(), None)
1703 self.assertEqual(f.detach(), None)
1704 self.assertEqual(f.alive, False)
1705 self.assertEqual(res, [199])
1706
1707 def test_order(self):
1708 a = self.A()
1709 res = []
1710
1711 f1 = weakref.finalize(a, res.append, 'f1')
1712 f2 = weakref.finalize(a, res.append, 'f2')
1713 f3 = weakref.finalize(a, res.append, 'f3')
1714 f4 = weakref.finalize(a, res.append, 'f4')
1715 f5 = weakref.finalize(a, res.append, 'f5')
1716
1717 # make sure finalizers can keep themselves alive
1718 del f1, f4
1719
1720 self.assertTrue(f2.alive)
1721 self.assertTrue(f3.alive)
1722 self.assertTrue(f5.alive)
1723
1724 self.assertTrue(f5.detach())
1725 self.assertFalse(f5.alive)
1726
1727 f5() # nothing because previously unregistered
1728 res.append('A')
1729 f3() # => res.append('f3')
1730 self.assertFalse(f3.alive)
1731 res.append('B')
1732 f3() # nothing because previously called
1733 res.append('C')
1734 del a
1735 self._collect_if_necessary()
1736 # => res.append('f4')
1737 # => res.append('f2')
1738 # => res.append('f1')
1739 self.assertFalse(f2.alive)
1740 res.append('D')
1741 f2() # nothing because previously called by gc
1742
1743 expected = ['A', 'f3', 'B', 'C', 'f4', 'f2', 'f1', 'D']
1744 self.assertEqual(res, expected)
1745
1746 def test_all_freed(self):
1747 # we want a weakrefable subclass of weakref.finalize
1748 class MyFinalizer(weakref.finalize):
1749 pass
1750
1751 a = self.A()
1752 res = []
1753 def callback():
1754 res.append(123)
1755 f = MyFinalizer(a, callback)
1756
1757 wr_callback = weakref.ref(callback)
1758 wr_f = weakref.ref(f)
1759 del callback, f
1760
1761 self.assertIsNotNone(wr_callback())
1762 self.assertIsNotNone(wr_f())
1763
1764 del a
1765 self._collect_if_necessary()
1766
1767 self.assertIsNone(wr_callback())
1768 self.assertIsNone(wr_f())
1769 self.assertEqual(res, [123])
1770
1771 @classmethod
1772 def run_in_child(cls):
1773 def error():
1774 # Create an atexit finalizer from inside a finalizer called
1775 # at exit. This should be the next to be run.
1776 g1 = weakref.finalize(cls, print, 'g1')
1777 print('f3 error')
1778 1/0
1779
1780 # cls should stay alive till atexit callbacks run
1781 f1 = weakref.finalize(cls, print, 'f1', _global_var)
1782 f2 = weakref.finalize(cls, print, 'f2', _global_var)
1783 f3 = weakref.finalize(cls, error)
1784 f4 = weakref.finalize(cls, print, 'f4', _global_var)
1785
1786 assert f1.atexit == True
1787 f2.atexit = False
1788 assert f3.atexit == True
1789 assert f4.atexit == True
1790
1791 def test_atexit(self):
1792 prog = ('from test.test_weakref import FinalizeTestCase;'+
1793 'FinalizeTestCase.run_in_child()')
1794 rc, out, err = script_helper.assert_python_ok('-c', prog)
1795 out = out.decode('ascii').splitlines()
1796 self.assertEqual(out, ['f4 foobar', 'f3 error', 'g1', 'f1 foobar'])
1797 self.assertTrue(b'ZeroDivisionError' in err)
1798
1799
Georg Brandlb533e262008-05-25 18:19:30 +00001800libreftest = """ Doctest for examples in the library reference: weakref.rst
Georg Brandl9a65d582005-07-02 19:07:30 +00001801
1802>>> import weakref
1803>>> class Dict(dict):
1804... pass
1805...
1806>>> obj = Dict(red=1, green=2, blue=3) # this object is weak referencable
1807>>> r = weakref.ref(obj)
Guido van Rossum7131f842007-02-09 20:13:25 +00001808>>> print(r() is obj)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001809True
Georg Brandl9a65d582005-07-02 19:07:30 +00001810
1811>>> import weakref
1812>>> class Object:
1813... pass
1814...
1815>>> o = Object()
1816>>> r = weakref.ref(o)
1817>>> o2 = r()
1818>>> o is o2
1819True
1820>>> del o, o2
Guido van Rossum7131f842007-02-09 20:13:25 +00001821>>> print(r())
Georg Brandl9a65d582005-07-02 19:07:30 +00001822None
1823
1824>>> import weakref
1825>>> class ExtendedRef(weakref.ref):
1826... def __init__(self, ob, callback=None, **annotations):
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001827... super().__init__(ob, callback)
Georg Brandl9a65d582005-07-02 19:07:30 +00001828... self.__counter = 0
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001829... for k, v in annotations.items():
Georg Brandl9a65d582005-07-02 19:07:30 +00001830... setattr(self, k, v)
1831... def __call__(self):
1832... '''Return a pair containing the referent and the number of
1833... times the reference has been called.
1834... '''
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001835... ob = super().__call__()
Georg Brandl9a65d582005-07-02 19:07:30 +00001836... if ob is not None:
1837... self.__counter += 1
1838... ob = (ob, self.__counter)
1839... return ob
Guido van Rossumd8faa362007-04-27 19:54:29 +00001840...
Georg Brandl9a65d582005-07-02 19:07:30 +00001841>>> class A: # not in docs from here, just testing the ExtendedRef
1842... pass
1843...
1844>>> a = A()
1845>>> r = ExtendedRef(a, foo=1, bar="baz")
1846>>> r.foo
18471
1848>>> r.bar
1849'baz'
1850>>> r()[1]
18511
1852>>> r()[1]
18532
1854>>> r()[0] is a
1855True
1856
1857
1858>>> import weakref
1859>>> _id2obj_dict = weakref.WeakValueDictionary()
1860>>> def remember(obj):
1861... oid = id(obj)
1862... _id2obj_dict[oid] = obj
1863... return oid
1864...
1865>>> def id2obj(oid):
1866... return _id2obj_dict[oid]
1867...
1868>>> a = A() # from here, just testing
1869>>> a_id = remember(a)
1870>>> id2obj(a_id) is a
1871True
1872>>> del a
1873>>> try:
1874... id2obj(a_id)
1875... except KeyError:
Guido van Rossum7131f842007-02-09 20:13:25 +00001876... print('OK')
Georg Brandl9a65d582005-07-02 19:07:30 +00001877... else:
Guido van Rossum7131f842007-02-09 20:13:25 +00001878... print('WeakValueDictionary error')
Georg Brandl9a65d582005-07-02 19:07:30 +00001879OK
1880
1881"""
1882
1883__test__ = {'libreftest' : libreftest}
1884
Fred Drake2e2be372001-09-20 21:33:42 +00001885def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001886 support.run_unittest(
Walter Dörwald21d3a322003-05-01 17:45:56 +00001887 ReferencesTestCase,
Antoine Pitrouc3afba12012-11-17 18:57:38 +01001888 WeakMethodTestCase,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001889 MappingTestCase,
1890 WeakValueDictionaryTestCase,
Fred Drakef425b1e2003-07-14 21:37:17 +00001891 WeakKeyDictionaryTestCase,
Amaury Forgeot d'Arcc856c7a2008-06-16 19:50:09 +00001892 SubclassableWeakrefTestCase,
Richard Oudkerk7a3dae052013-05-05 23:05:00 +01001893 FinalizeTestCase,
Fred Drakef425b1e2003-07-14 21:37:17 +00001894 )
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001895 support.run_doctest(sys.modules[__name__])
Fred Drake2e2be372001-09-20 21:33:42 +00001896
1897
1898if __name__ == "__main__":
1899 test_main()