blob: 6d50a66d7ba2752a9d10644c10a53c712fd195b4 [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
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
Fred Drake0a4dd392004-07-02 18:57:45 +0000848
Amaury Forgeot d'Arcc856c7a2008-06-16 19:50:09 +0000849class SubclassableWeakrefTestCase(TestBase):
Fred Drake0a4dd392004-07-02 18:57:45 +0000850
851 def test_subclass_refs(self):
852 class MyRef(weakref.ref):
853 def __init__(self, ob, callback=None, value=42):
854 self.value = value
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000855 super().__init__(ob, callback)
Fred Drake0a4dd392004-07-02 18:57:45 +0000856 def __call__(self):
857 self.called = True
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000858 return super().__call__()
Fred Drake0a4dd392004-07-02 18:57:45 +0000859 o = Object("foo")
860 mr = MyRef(o, value=24)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200861 self.assertIs(mr(), o)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000862 self.assertTrue(mr.called)
Fred Drake0a4dd392004-07-02 18:57:45 +0000863 self.assertEqual(mr.value, 24)
864 del o
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200865 self.assertIsNone(mr())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000866 self.assertTrue(mr.called)
Fred Drake0a4dd392004-07-02 18:57:45 +0000867
868 def test_subclass_refs_dont_replace_standard_refs(self):
869 class MyRef(weakref.ref):
870 pass
871 o = Object(42)
872 r1 = MyRef(o)
873 r2 = weakref.ref(o)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200874 self.assertIsNot(r1, r2)
Fred Drake0a4dd392004-07-02 18:57:45 +0000875 self.assertEqual(weakref.getweakrefs(o), [r2, r1])
876 self.assertEqual(weakref.getweakrefcount(o), 2)
877 r3 = MyRef(o)
878 self.assertEqual(weakref.getweakrefcount(o), 3)
879 refs = weakref.getweakrefs(o)
880 self.assertEqual(len(refs), 3)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200881 self.assertIs(r2, refs[0])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000882 self.assertIn(r1, refs[1:])
883 self.assertIn(r3, refs[1:])
Fred Drake0a4dd392004-07-02 18:57:45 +0000884
885 def test_subclass_refs_dont_conflate_callbacks(self):
886 class MyRef(weakref.ref):
887 pass
888 o = Object(42)
889 r1 = MyRef(o, id)
890 r2 = MyRef(o, str)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200891 self.assertIsNot(r1, r2)
Fred Drake0a4dd392004-07-02 18:57:45 +0000892 refs = weakref.getweakrefs(o)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000893 self.assertIn(r1, refs)
894 self.assertIn(r2, refs)
Fred Drake0a4dd392004-07-02 18:57:45 +0000895
896 def test_subclass_refs_with_slots(self):
897 class MyRef(weakref.ref):
898 __slots__ = "slot1", "slot2"
899 def __new__(type, ob, callback, slot1, slot2):
900 return weakref.ref.__new__(type, ob, callback)
901 def __init__(self, ob, callback, slot1, slot2):
902 self.slot1 = slot1
903 self.slot2 = slot2
904 def meth(self):
905 return self.slot1 + self.slot2
906 o = Object(42)
907 r = MyRef(o, None, "abc", "def")
908 self.assertEqual(r.slot1, "abc")
909 self.assertEqual(r.slot2, "def")
910 self.assertEqual(r.meth(), "abcdef")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000911 self.assertFalse(hasattr(r, "__dict__"))
Fred Drake0a4dd392004-07-02 18:57:45 +0000912
Amaury Forgeot d'Arcc856c7a2008-06-16 19:50:09 +0000913 def test_subclass_refs_with_cycle(self):
914 # Bug #3110
915 # An instance of a weakref subclass can have attributes.
916 # If such a weakref holds the only strong reference to the object,
917 # deleting the weakref will delete the object. In this case,
918 # the callback must not be called, because the ref object is
919 # being deleted.
920 class MyRef(weakref.ref):
921 pass
922
923 # Use a local callback, for "regrtest -R::"
924 # to detect refcounting problems
925 def callback(w):
926 self.cbcalled += 1
927
928 o = C()
929 r1 = MyRef(o, callback)
930 r1.o = o
931 del o
932
933 del r1 # Used to crash here
934
935 self.assertEqual(self.cbcalled, 0)
936
937 # Same test, with two weakrefs to the same object
938 # (since code paths are different)
939 o = C()
940 r1 = MyRef(o, callback)
941 r2 = MyRef(o, callback)
942 r1.r = r2
943 r2.o = o
944 del o
945 del r2
946
947 del r1 # Used to crash here
948
949 self.assertEqual(self.cbcalled, 0)
950
Fred Drake0a4dd392004-07-02 18:57:45 +0000951
Antoine Pitrouc3afba12012-11-17 18:57:38 +0100952class WeakMethodTestCase(unittest.TestCase):
953
954 def _subclass(self):
Martin Panter7462b6492015-11-02 03:37:02 +0000955 """Return an Object subclass overriding `some_method`."""
Antoine Pitrouc3afba12012-11-17 18:57:38 +0100956 class C(Object):
957 def some_method(self):
958 return 6
959 return C
960
961 def test_alive(self):
962 o = Object(1)
963 r = weakref.WeakMethod(o.some_method)
964 self.assertIsInstance(r, weakref.ReferenceType)
965 self.assertIsInstance(r(), type(o.some_method))
966 self.assertIs(r().__self__, o)
967 self.assertIs(r().__func__, o.some_method.__func__)
968 self.assertEqual(r()(), 4)
969
970 def test_object_dead(self):
971 o = Object(1)
972 r = weakref.WeakMethod(o.some_method)
973 del o
974 gc.collect()
975 self.assertIs(r(), None)
976
977 def test_method_dead(self):
978 C = self._subclass()
979 o = C(1)
980 r = weakref.WeakMethod(o.some_method)
981 del C.some_method
982 gc.collect()
983 self.assertIs(r(), None)
984
985 def test_callback_when_object_dead(self):
986 # Test callback behaviour when object dies first.
987 C = self._subclass()
988 calls = []
989 def cb(arg):
990 calls.append(arg)
991 o = C(1)
992 r = weakref.WeakMethod(o.some_method, cb)
993 del o
994 gc.collect()
995 self.assertEqual(calls, [r])
996 # Callback is only called once.
997 C.some_method = Object.some_method
998 gc.collect()
999 self.assertEqual(calls, [r])
1000
1001 def test_callback_when_method_dead(self):
1002 # Test callback behaviour when method dies first.
1003 C = self._subclass()
1004 calls = []
1005 def cb(arg):
1006 calls.append(arg)
1007 o = C(1)
1008 r = weakref.WeakMethod(o.some_method, cb)
1009 del C.some_method
1010 gc.collect()
1011 self.assertEqual(calls, [r])
1012 # Callback is only called once.
1013 del o
1014 gc.collect()
1015 self.assertEqual(calls, [r])
1016
1017 @support.cpython_only
1018 def test_no_cycles(self):
1019 # A WeakMethod doesn't create any reference cycle to itself.
1020 o = Object(1)
1021 def cb(_):
1022 pass
1023 r = weakref.WeakMethod(o.some_method, cb)
1024 wr = weakref.ref(r)
1025 del r
1026 self.assertIs(wr(), None)
1027
1028 def test_equality(self):
1029 def _eq(a, b):
1030 self.assertTrue(a == b)
1031 self.assertFalse(a != b)
1032 def _ne(a, b):
1033 self.assertTrue(a != b)
1034 self.assertFalse(a == b)
1035 x = Object(1)
1036 y = Object(1)
1037 a = weakref.WeakMethod(x.some_method)
1038 b = weakref.WeakMethod(y.some_method)
1039 c = weakref.WeakMethod(x.other_method)
1040 d = weakref.WeakMethod(y.other_method)
1041 # Objects equal, same method
1042 _eq(a, b)
1043 _eq(c, d)
1044 # Objects equal, different method
1045 _ne(a, c)
1046 _ne(a, d)
1047 _ne(b, c)
1048 _ne(b, d)
1049 # Objects unequal, same or different method
1050 z = Object(2)
1051 e = weakref.WeakMethod(z.some_method)
1052 f = weakref.WeakMethod(z.other_method)
1053 _ne(a, e)
1054 _ne(a, f)
1055 _ne(b, e)
1056 _ne(b, f)
1057 del x, y, z
1058 gc.collect()
1059 # Dead WeakMethods compare by identity
1060 refs = a, b, c, d, e, f
1061 for q in refs:
1062 for r in refs:
1063 self.assertEqual(q == r, q is r)
1064 self.assertEqual(q != r, q is not r)
1065
1066 def test_hashing(self):
1067 # Alive WeakMethods are hashable if the underlying object is
1068 # hashable.
1069 x = Object(1)
1070 y = Object(1)
1071 a = weakref.WeakMethod(x.some_method)
1072 b = weakref.WeakMethod(y.some_method)
1073 c = weakref.WeakMethod(y.other_method)
1074 # Since WeakMethod objects are equal, the hashes should be equal.
1075 self.assertEqual(hash(a), hash(b))
1076 ha = hash(a)
1077 # Dead WeakMethods retain their old hash value
1078 del x, y
1079 gc.collect()
1080 self.assertEqual(hash(a), ha)
1081 self.assertEqual(hash(b), ha)
1082 # If it wasn't hashed when alive, a dead WeakMethod cannot be hashed.
1083 self.assertRaises(TypeError, hash, c)
1084
1085
Fred Drakeb0fefc52001-03-23 04:22:45 +00001086class MappingTestCase(TestBase):
Martin v. Löwis5e163332001-02-27 18:36:56 +00001087
Fred Drakeb0fefc52001-03-23 04:22:45 +00001088 COUNT = 10
1089
Antoine Pitroubbe2f602012-03-01 16:26:35 +01001090 def check_len_cycles(self, dict_type, cons):
1091 N = 20
1092 items = [RefCycle() for i in range(N)]
1093 dct = dict_type(cons(o) for o in items)
1094 # Keep an iterator alive
1095 it = dct.items()
1096 try:
1097 next(it)
1098 except StopIteration:
1099 pass
1100 del items
1101 gc.collect()
1102 n1 = len(dct)
1103 del it
1104 gc.collect()
1105 n2 = len(dct)
1106 # one item may be kept alive inside the iterator
1107 self.assertIn(n1, (0, 1))
1108 self.assertEqual(n2, 0)
1109
1110 def test_weak_keyed_len_cycles(self):
1111 self.check_len_cycles(weakref.WeakKeyDictionary, lambda k: (k, 1))
1112
1113 def test_weak_valued_len_cycles(self):
1114 self.check_len_cycles(weakref.WeakValueDictionary, lambda k: (1, k))
1115
1116 def check_len_race(self, dict_type, cons):
1117 # Extended sanity checks for len() in the face of cyclic collection
1118 self.addCleanup(gc.set_threshold, *gc.get_threshold())
1119 for th in range(1, 100):
1120 N = 20
1121 gc.collect(0)
1122 gc.set_threshold(th, th, th)
1123 items = [RefCycle() for i in range(N)]
1124 dct = dict_type(cons(o) for o in items)
1125 del items
1126 # All items will be collected at next garbage collection pass
1127 it = dct.items()
1128 try:
1129 next(it)
1130 except StopIteration:
1131 pass
1132 n1 = len(dct)
1133 del it
1134 n2 = len(dct)
1135 self.assertGreaterEqual(n1, 0)
1136 self.assertLessEqual(n1, N)
1137 self.assertGreaterEqual(n2, 0)
1138 self.assertLessEqual(n2, n1)
1139
1140 def test_weak_keyed_len_race(self):
1141 self.check_len_race(weakref.WeakKeyDictionary, lambda k: (k, 1))
1142
1143 def test_weak_valued_len_race(self):
1144 self.check_len_race(weakref.WeakValueDictionary, lambda k: (1, k))
1145
Fred Drakeb0fefc52001-03-23 04:22:45 +00001146 def test_weak_values(self):
Fred Drake0e540c32001-05-02 05:44:22 +00001147 #
1148 # This exercises d.copy(), d.items(), d[], del d[], len(d).
1149 #
1150 dict, objects = self.make_weak_valued_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +00001151 for o in objects:
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001152 self.assertEqual(weakref.getweakrefcount(o), 1)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001153 self.assertIs(o, dict[o.arg],
Fred Drakeb0fefc52001-03-23 04:22:45 +00001154 "wrong object returned by weak dict!")
Barry Warsawecaab832008-09-04 01:42:51 +00001155 items1 = list(dict.items())
1156 items2 = list(dict.copy().items())
Fred Drakeb0fefc52001-03-23 04:22:45 +00001157 items1.sort()
1158 items2.sort()
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001159 self.assertEqual(items1, items2,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001160 "cloning of weak-valued dictionary did not work!")
1161 del items1, items2
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001162 self.assertEqual(len(dict), self.COUNT)
Fred Drakeb0fefc52001-03-23 04:22:45 +00001163 del objects[0]
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001164 self.assertEqual(len(dict), self.COUNT - 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001165 "deleting object did not cause dictionary update")
1166 del objects, o
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001167 self.assertEqual(len(dict), 0,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001168 "deleting the values did not clear the dictionary")
Fred Drake4fd06e02001-08-03 04:11:27 +00001169 # regression on SF bug #447152:
1170 dict = weakref.WeakValueDictionary()
1171 self.assertRaises(KeyError, dict.__getitem__, 1)
1172 dict[2] = C()
1173 self.assertRaises(KeyError, dict.__getitem__, 2)
Fred Drakeb0fefc52001-03-23 04:22:45 +00001174
1175 def test_weak_keys(self):
Fred Drake0e540c32001-05-02 05:44:22 +00001176 #
1177 # This exercises d.copy(), d.items(), d[] = v, d[], del d[],
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001178 # len(d), k in d.
Fred Drake0e540c32001-05-02 05:44:22 +00001179 #
1180 dict, objects = self.make_weak_keyed_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +00001181 for o in objects:
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001182 self.assertEqual(weakref.getweakrefcount(o), 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001183 "wrong number of weak references to %r!" % o)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001184 self.assertIs(o.arg, dict[o],
Fred Drakeb0fefc52001-03-23 04:22:45 +00001185 "wrong object returned by weak dict!")
1186 items1 = dict.items()
1187 items2 = dict.copy().items()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001188 self.assertEqual(set(items1), set(items2),
Fred Drakeb0fefc52001-03-23 04:22:45 +00001189 "cloning of weak-keyed dictionary did not work!")
1190 del items1, items2
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001191 self.assertEqual(len(dict), self.COUNT)
Fred Drakeb0fefc52001-03-23 04:22:45 +00001192 del objects[0]
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001193 self.assertEqual(len(dict), (self.COUNT - 1),
Fred Drakeb0fefc52001-03-23 04:22:45 +00001194 "deleting object did not cause dictionary update")
1195 del objects, o
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001196 self.assertEqual(len(dict), 0,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001197 "deleting the keys did not clear the dictionary")
Fred Drake752eda42001-11-06 16:38:34 +00001198 o = Object(42)
1199 dict[o] = "What is the meaning of the universe?"
Benjamin Peterson577473f2010-01-19 00:09:57 +00001200 self.assertIn(o, dict)
1201 self.assertNotIn(34, dict)
Martin v. Löwis5e163332001-02-27 18:36:56 +00001202
Fred Drake0e540c32001-05-02 05:44:22 +00001203 def test_weak_keyed_iters(self):
1204 dict, objects = self.make_weak_keyed_dict()
1205 self.check_iters(dict)
1206
Thomas Wouters477c8d52006-05-27 19:21:47 +00001207 # Test keyrefs()
1208 refs = dict.keyrefs()
1209 self.assertEqual(len(refs), len(objects))
1210 objects2 = list(objects)
1211 for wr in refs:
1212 ob = wr()
Benjamin Peterson577473f2010-01-19 00:09:57 +00001213 self.assertIn(ob, dict)
1214 self.assertIn(ob, dict)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001215 self.assertEqual(ob.arg, dict[ob])
1216 objects2.remove(ob)
1217 self.assertEqual(len(objects2), 0)
1218
1219 # Test iterkeyrefs()
1220 objects2 = list(objects)
Barry Warsawecaab832008-09-04 01:42:51 +00001221 self.assertEqual(len(list(dict.keyrefs())), len(objects))
1222 for wr in dict.keyrefs():
Thomas Wouters477c8d52006-05-27 19:21:47 +00001223 ob = wr()
Benjamin Peterson577473f2010-01-19 00:09:57 +00001224 self.assertIn(ob, dict)
1225 self.assertIn(ob, dict)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001226 self.assertEqual(ob.arg, dict[ob])
1227 objects2.remove(ob)
1228 self.assertEqual(len(objects2), 0)
1229
Fred Drake0e540c32001-05-02 05:44:22 +00001230 def test_weak_valued_iters(self):
1231 dict, objects = self.make_weak_valued_dict()
1232 self.check_iters(dict)
1233
Thomas Wouters477c8d52006-05-27 19:21:47 +00001234 # Test valuerefs()
1235 refs = dict.valuerefs()
1236 self.assertEqual(len(refs), len(objects))
1237 objects2 = list(objects)
1238 for wr in refs:
1239 ob = wr()
1240 self.assertEqual(ob, dict[ob.arg])
1241 self.assertEqual(ob.arg, dict[ob.arg].arg)
1242 objects2.remove(ob)
1243 self.assertEqual(len(objects2), 0)
1244
1245 # Test itervaluerefs()
1246 objects2 = list(objects)
1247 self.assertEqual(len(list(dict.itervaluerefs())), len(objects))
1248 for wr in dict.itervaluerefs():
1249 ob = wr()
1250 self.assertEqual(ob, dict[ob.arg])
1251 self.assertEqual(ob.arg, dict[ob.arg].arg)
1252 objects2.remove(ob)
1253 self.assertEqual(len(objects2), 0)
1254
Fred Drake0e540c32001-05-02 05:44:22 +00001255 def check_iters(self, dict):
1256 # item iterator:
Barry Warsawecaab832008-09-04 01:42:51 +00001257 items = list(dict.items())
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001258 for item in dict.items():
Fred Drake0e540c32001-05-02 05:44:22 +00001259 items.remove(item)
Barry Warsawecaab832008-09-04 01:42:51 +00001260 self.assertFalse(items, "items() did not touch all items")
Fred Drake0e540c32001-05-02 05:44:22 +00001261
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001262 # key iterator, via __iter__():
Guido van Rossum07f24362007-02-11 22:59:48 +00001263 keys = list(dict.keys())
Fred Drake0e540c32001-05-02 05:44:22 +00001264 for k in dict:
1265 keys.remove(k)
Barry Warsawecaab832008-09-04 01:42:51 +00001266 self.assertFalse(keys, "__iter__() did not touch all keys")
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001267
1268 # key iterator, via iterkeys():
Guido van Rossum07f24362007-02-11 22:59:48 +00001269 keys = list(dict.keys())
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001270 for k in dict.keys():
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001271 keys.remove(k)
Barry Warsawecaab832008-09-04 01:42:51 +00001272 self.assertFalse(keys, "iterkeys() did not touch all keys")
Fred Drake0e540c32001-05-02 05:44:22 +00001273
1274 # value iterator:
Guido van Rossum07f24362007-02-11 22:59:48 +00001275 values = list(dict.values())
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001276 for v in dict.values():
Fred Drake0e540c32001-05-02 05:44:22 +00001277 values.remove(v)
Barry Warsawecaab832008-09-04 01:42:51 +00001278 self.assertFalse(values,
Fred Drakef425b1e2003-07-14 21:37:17 +00001279 "itervalues() did not touch all values")
Fred Drake0e540c32001-05-02 05:44:22 +00001280
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001281 def check_weak_destroy_while_iterating(self, dict, objects, iter_name):
1282 n = len(dict)
1283 it = iter(getattr(dict, iter_name)())
1284 next(it) # Trigger internal iteration
1285 # Destroy an object
1286 del objects[-1]
1287 gc.collect() # just in case
1288 # We have removed either the first consumed object, or another one
1289 self.assertIn(len(list(it)), [len(objects), len(objects) - 1])
1290 del it
1291 # The removal has been committed
1292 self.assertEqual(len(dict), n - 1)
1293
1294 def check_weak_destroy_and_mutate_while_iterating(self, dict, testcontext):
1295 # Check that we can explicitly mutate the weak dict without
1296 # interfering with delayed removal.
1297 # `testcontext` should create an iterator, destroy one of the
1298 # weakref'ed objects and then return a new key/value pair corresponding
1299 # to the destroyed object.
1300 with testcontext() as (k, v):
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001301 self.assertNotIn(k, dict)
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001302 with testcontext() as (k, v):
1303 self.assertRaises(KeyError, dict.__delitem__, k)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001304 self.assertNotIn(k, dict)
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001305 with testcontext() as (k, v):
1306 self.assertRaises(KeyError, dict.pop, k)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001307 self.assertNotIn(k, dict)
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001308 with testcontext() as (k, v):
1309 dict[k] = v
1310 self.assertEqual(dict[k], v)
1311 ddict = copy.copy(dict)
1312 with testcontext() as (k, v):
1313 dict.update(ddict)
1314 self.assertEqual(dict, ddict)
1315 with testcontext() as (k, v):
1316 dict.clear()
1317 self.assertEqual(len(dict), 0)
1318
Antoine Pitrou1bf974d2014-10-05 20:02:28 +02001319 def check_weak_del_and_len_while_iterating(self, dict, testcontext):
1320 # Check that len() works when both iterating and removing keys
1321 # explicitly through various means (.pop(), .clear()...), while
1322 # implicit mutation is deferred because an iterator is alive.
1323 # (each call to testcontext() should schedule one item for removal
1324 # for this test to work properly)
1325 o = Object(123456)
1326 with testcontext():
1327 n = len(dict)
1328 dict.popitem()
1329 self.assertEqual(len(dict), n - 1)
1330 dict[o] = o
1331 self.assertEqual(len(dict), n)
1332 with testcontext():
1333 self.assertEqual(len(dict), n - 1)
1334 dict.pop(next(dict.keys()))
1335 self.assertEqual(len(dict), n - 2)
1336 with testcontext():
1337 self.assertEqual(len(dict), n - 3)
1338 del dict[next(dict.keys())]
1339 self.assertEqual(len(dict), n - 4)
1340 with testcontext():
1341 self.assertEqual(len(dict), n - 5)
1342 dict.popitem()
1343 self.assertEqual(len(dict), n - 6)
1344 with testcontext():
1345 dict.clear()
1346 self.assertEqual(len(dict), 0)
1347 self.assertEqual(len(dict), 0)
1348
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001349 def test_weak_keys_destroy_while_iterating(self):
1350 # Issue #7105: iterators shouldn't crash when a key is implicitly removed
1351 dict, objects = self.make_weak_keyed_dict()
1352 self.check_weak_destroy_while_iterating(dict, objects, 'keys')
1353 self.check_weak_destroy_while_iterating(dict, objects, 'items')
1354 self.check_weak_destroy_while_iterating(dict, objects, 'values')
1355 self.check_weak_destroy_while_iterating(dict, objects, 'keyrefs')
1356 dict, objects = self.make_weak_keyed_dict()
1357 @contextlib.contextmanager
1358 def testcontext():
1359 try:
1360 it = iter(dict.items())
1361 next(it)
1362 # Schedule a key/value for removal and recreate it
1363 v = objects.pop().arg
1364 gc.collect() # just in case
1365 yield Object(v), v
1366 finally:
1367 it = None # should commit all removals
Benjamin Peterson18bb7022014-08-24 18:02:15 -05001368 gc.collect()
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001369 self.check_weak_destroy_and_mutate_while_iterating(dict, testcontext)
Antoine Pitrou1bf974d2014-10-05 20:02:28 +02001370 # Issue #21173: len() fragile when keys are both implicitly and
1371 # explicitly removed.
1372 dict, objects = self.make_weak_keyed_dict()
1373 self.check_weak_del_and_len_while_iterating(dict, testcontext)
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001374
1375 def test_weak_values_destroy_while_iterating(self):
1376 # Issue #7105: iterators shouldn't crash when a key is implicitly removed
1377 dict, objects = self.make_weak_valued_dict()
1378 self.check_weak_destroy_while_iterating(dict, objects, 'keys')
1379 self.check_weak_destroy_while_iterating(dict, objects, 'items')
1380 self.check_weak_destroy_while_iterating(dict, objects, 'values')
1381 self.check_weak_destroy_while_iterating(dict, objects, 'itervaluerefs')
1382 self.check_weak_destroy_while_iterating(dict, objects, 'valuerefs')
1383 dict, objects = self.make_weak_valued_dict()
1384 @contextlib.contextmanager
1385 def testcontext():
1386 try:
1387 it = iter(dict.items())
1388 next(it)
1389 # Schedule a key/value for removal and recreate it
1390 k = objects.pop().arg
1391 gc.collect() # just in case
1392 yield k, Object(k)
1393 finally:
1394 it = None # should commit all removals
Benjamin Peterson18bb7022014-08-24 18:02:15 -05001395 gc.collect()
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001396 self.check_weak_destroy_and_mutate_while_iterating(dict, testcontext)
Antoine Pitrou1bf974d2014-10-05 20:02:28 +02001397 dict, objects = self.make_weak_valued_dict()
1398 self.check_weak_del_and_len_while_iterating(dict, testcontext)
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001399
Guido van Rossum009afb72002-06-10 20:00:52 +00001400 def test_make_weak_keyed_dict_from_dict(self):
1401 o = Object(3)
1402 dict = weakref.WeakKeyDictionary({o:364})
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001403 self.assertEqual(dict[o], 364)
Guido van Rossum009afb72002-06-10 20:00:52 +00001404
1405 def test_make_weak_keyed_dict_from_weak_keyed_dict(self):
1406 o = Object(3)
1407 dict = weakref.WeakKeyDictionary({o:364})
1408 dict2 = weakref.WeakKeyDictionary(dict)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001409 self.assertEqual(dict[o], 364)
Guido van Rossum009afb72002-06-10 20:00:52 +00001410
Fred Drake0e540c32001-05-02 05:44:22 +00001411 def make_weak_keyed_dict(self):
1412 dict = weakref.WeakKeyDictionary()
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001413 objects = list(map(Object, range(self.COUNT)))
Fred Drake0e540c32001-05-02 05:44:22 +00001414 for o in objects:
1415 dict[o] = o.arg
1416 return dict, objects
1417
Antoine Pitrouc06de472009-05-30 21:04:26 +00001418 def test_make_weak_valued_dict_from_dict(self):
1419 o = Object(3)
1420 dict = weakref.WeakValueDictionary({364:o})
1421 self.assertEqual(dict[364], o)
1422
1423 def test_make_weak_valued_dict_from_weak_valued_dict(self):
1424 o = Object(3)
1425 dict = weakref.WeakValueDictionary({364:o})
1426 dict2 = weakref.WeakValueDictionary(dict)
1427 self.assertEqual(dict[364], o)
1428
Serhiy Storchakab5102e32015-09-29 23:52:09 +03001429 def test_make_weak_valued_dict_misc(self):
1430 # errors
1431 self.assertRaises(TypeError, weakref.WeakValueDictionary.__init__)
1432 self.assertRaises(TypeError, weakref.WeakValueDictionary, {}, {})
1433 self.assertRaises(TypeError, weakref.WeakValueDictionary, (), ())
1434 # special keyword arguments
1435 o = Object(3)
1436 for kw in 'self', 'dict', 'other', 'iterable':
1437 d = weakref.WeakValueDictionary(**{kw: o})
1438 self.assertEqual(list(d.keys()), [kw])
1439 self.assertEqual(d[kw], o)
1440
Fred Drake0e540c32001-05-02 05:44:22 +00001441 def make_weak_valued_dict(self):
1442 dict = weakref.WeakValueDictionary()
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001443 objects = list(map(Object, range(self.COUNT)))
Fred Drake0e540c32001-05-02 05:44:22 +00001444 for o in objects:
1445 dict[o.arg] = o
1446 return dict, objects
1447
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001448 def check_popitem(self, klass, key1, value1, key2, value2):
1449 weakdict = klass()
1450 weakdict[key1] = value1
1451 weakdict[key2] = value2
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001452 self.assertEqual(len(weakdict), 2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001453 k, v = weakdict.popitem()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001454 self.assertEqual(len(weakdict), 1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001455 if k is key1:
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001456 self.assertIs(v, value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001457 else:
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001458 self.assertIs(v, value2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001459 k, v = weakdict.popitem()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001460 self.assertEqual(len(weakdict), 0)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001461 if k is key1:
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001462 self.assertIs(v, value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001463 else:
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001464 self.assertIs(v, value2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001465
1466 def test_weak_valued_dict_popitem(self):
1467 self.check_popitem(weakref.WeakValueDictionary,
1468 "key1", C(), "key2", C())
1469
1470 def test_weak_keyed_dict_popitem(self):
1471 self.check_popitem(weakref.WeakKeyDictionary,
1472 C(), "value 1", C(), "value 2")
1473
1474 def check_setdefault(self, klass, key, value1, value2):
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001475 self.assertIsNot(value1, value2,
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001476 "invalid test"
1477 " -- value parameters must be distinct objects")
1478 weakdict = klass()
1479 o = weakdict.setdefault(key, value1)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001480 self.assertIs(o, value1)
Benjamin Peterson577473f2010-01-19 00:09:57 +00001481 self.assertIn(key, weakdict)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001482 self.assertIs(weakdict.get(key), value1)
1483 self.assertIs(weakdict[key], value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001484
1485 o = weakdict.setdefault(key, value2)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001486 self.assertIs(o, value1)
Benjamin Peterson577473f2010-01-19 00:09:57 +00001487 self.assertIn(key, weakdict)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001488 self.assertIs(weakdict.get(key), value1)
1489 self.assertIs(weakdict[key], value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001490
1491 def test_weak_valued_dict_setdefault(self):
1492 self.check_setdefault(weakref.WeakValueDictionary,
1493 "key", C(), C())
1494
1495 def test_weak_keyed_dict_setdefault(self):
1496 self.check_setdefault(weakref.WeakKeyDictionary,
1497 C(), "value 1", "value 2")
1498
Fred Drakea0a4ab12001-04-16 17:37:27 +00001499 def check_update(self, klass, dict):
Fred Drake0e540c32001-05-02 05:44:22 +00001500 #
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001501 # This exercises d.update(), len(d), d.keys(), k in d,
Fred Drake0e540c32001-05-02 05:44:22 +00001502 # d.get(), d[].
1503 #
Fred Drakea0a4ab12001-04-16 17:37:27 +00001504 weakdict = klass()
1505 weakdict.update(dict)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001506 self.assertEqual(len(weakdict), len(dict))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001507 for k in weakdict.keys():
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001508 self.assertIn(k, dict, "mysterious new key appeared in weak dict")
Fred Drakea0a4ab12001-04-16 17:37:27 +00001509 v = dict.get(k)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001510 self.assertIs(v, weakdict[k])
1511 self.assertIs(v, weakdict.get(k))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001512 for k in dict.keys():
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001513 self.assertIn(k, weakdict, "original key disappeared in weak dict")
Fred Drakea0a4ab12001-04-16 17:37:27 +00001514 v = dict[k]
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001515 self.assertIs(v, weakdict[k])
1516 self.assertIs(v, weakdict.get(k))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001517
1518 def test_weak_valued_dict_update(self):
1519 self.check_update(weakref.WeakValueDictionary,
1520 {1: C(), 'a': C(), C(): C()})
Serhiy Storchakab5102e32015-09-29 23:52:09 +03001521 # errors
1522 self.assertRaises(TypeError, weakref.WeakValueDictionary.update)
1523 d = weakref.WeakValueDictionary()
1524 self.assertRaises(TypeError, d.update, {}, {})
1525 self.assertRaises(TypeError, d.update, (), ())
1526 self.assertEqual(list(d.keys()), [])
1527 # special keyword arguments
1528 o = Object(3)
1529 for kw in 'self', 'dict', 'other', 'iterable':
1530 d = weakref.WeakValueDictionary()
1531 d.update(**{kw: o})
1532 self.assertEqual(list(d.keys()), [kw])
1533 self.assertEqual(d[kw], o)
Fred Drakea0a4ab12001-04-16 17:37:27 +00001534
1535 def test_weak_keyed_dict_update(self):
1536 self.check_update(weakref.WeakKeyDictionary,
1537 {C(): 1, C(): 2, C(): 3})
1538
Fred Drakeccc75622001-09-06 14:52:39 +00001539 def test_weak_keyed_delitem(self):
1540 d = weakref.WeakKeyDictionary()
1541 o1 = Object('1')
1542 o2 = Object('2')
1543 d[o1] = 'something'
1544 d[o2] = 'something'
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001545 self.assertEqual(len(d), 2)
Fred Drakeccc75622001-09-06 14:52:39 +00001546 del d[o1]
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001547 self.assertEqual(len(d), 1)
Barry Warsawecaab832008-09-04 01:42:51 +00001548 self.assertEqual(list(d.keys()), [o2])
Fred Drakeccc75622001-09-06 14:52:39 +00001549
1550 def test_weak_valued_delitem(self):
1551 d = weakref.WeakValueDictionary()
1552 o1 = Object('1')
1553 o2 = Object('2')
1554 d['something'] = o1
1555 d['something else'] = o2
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001556 self.assertEqual(len(d), 2)
Fred Drakeccc75622001-09-06 14:52:39 +00001557 del d['something']
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001558 self.assertEqual(len(d), 1)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001559 self.assertEqual(list(d.items()), [('something else', o2)])
Fred Drakeccc75622001-09-06 14:52:39 +00001560
Tim Peters886128f2003-05-25 01:45:11 +00001561 def test_weak_keyed_bad_delitem(self):
1562 d = weakref.WeakKeyDictionary()
1563 o = Object('1')
1564 # An attempt to delete an object that isn't there should raise
Tim Peters50d8b8b2003-05-25 17:44:31 +00001565 # KeyError. It didn't before 2.3.
Tim Peters886128f2003-05-25 01:45:11 +00001566 self.assertRaises(KeyError, d.__delitem__, o)
Tim Peters50d8b8b2003-05-25 17:44:31 +00001567 self.assertRaises(KeyError, d.__getitem__, o)
1568
1569 # If a key isn't of a weakly referencable type, __getitem__ and
1570 # __setitem__ raise TypeError. __delitem__ should too.
1571 self.assertRaises(TypeError, d.__delitem__, 13)
1572 self.assertRaises(TypeError, d.__getitem__, 13)
1573 self.assertRaises(TypeError, d.__setitem__, 13, 13)
Tim Peters886128f2003-05-25 01:45:11 +00001574
1575 def test_weak_keyed_cascading_deletes(self):
1576 # SF bug 742860. For some reason, before 2.3 __delitem__ iterated
1577 # over the keys via self.data.iterkeys(). If things vanished from
1578 # the dict during this (or got added), that caused a RuntimeError.
1579
1580 d = weakref.WeakKeyDictionary()
1581 mutate = False
1582
1583 class C(object):
1584 def __init__(self, i):
1585 self.value = i
1586 def __hash__(self):
1587 return hash(self.value)
1588 def __eq__(self, other):
1589 if mutate:
1590 # Side effect that mutates the dict, by removing the
1591 # last strong reference to a key.
1592 del objs[-1]
1593 return self.value == other.value
1594
1595 objs = [C(i) for i in range(4)]
1596 for o in objs:
1597 d[o] = o.value
1598 del o # now the only strong references to keys are in objs
1599 # Find the order in which iterkeys sees the keys.
Barry Warsawecaab832008-09-04 01:42:51 +00001600 objs = list(d.keys())
Tim Peters886128f2003-05-25 01:45:11 +00001601 # Reverse it, so that the iteration implementation of __delitem__
1602 # has to keep looping to find the first object we delete.
1603 objs.reverse()
Tim Peters50d8b8b2003-05-25 17:44:31 +00001604
Tim Peters886128f2003-05-25 01:45:11 +00001605 # Turn on mutation in C.__eq__. The first time thru the loop,
1606 # under the iterkeys() business the first comparison will delete
1607 # the last item iterkeys() would see, and that causes a
1608 # RuntimeError: dictionary changed size during iteration
1609 # when the iterkeys() loop goes around to try comparing the next
Tim Peters50d8b8b2003-05-25 17:44:31 +00001610 # key. After this was fixed, it just deletes the last object *our*
Tim Peters886128f2003-05-25 01:45:11 +00001611 # "for o in obj" loop would have gotten to.
1612 mutate = True
1613 count = 0
1614 for o in objs:
1615 count += 1
1616 del d[o]
1617 self.assertEqual(len(d), 0)
1618 self.assertEqual(count, 2)
1619
Serhiy Storchaka0c937b32014-07-22 12:14:52 +03001620 def test_make_weak_valued_dict_repr(self):
1621 dict = weakref.WeakValueDictionary()
1622 self.assertRegex(repr(dict), '<WeakValueDictionary at 0x.*>')
1623
1624 def test_make_weak_keyed_dict_repr(self):
1625 dict = weakref.WeakKeyDictionary()
1626 self.assertRegex(repr(dict), '<WeakKeyDictionary at 0x.*>')
1627
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001628from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001629
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001630class WeakValueDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +00001631 """Check that WeakValueDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001632 __ref = {"key1":Object(1), "key2":Object(2), "key3":Object(3)}
Walter Dörwald118f9312004-06-02 18:42:25 +00001633 type2test = weakref.WeakValueDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001634 def _reference(self):
1635 return self.__ref.copy()
1636
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001637class WeakKeyDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +00001638 """Check that WeakKeyDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001639 __ref = {Object("key1"):1, Object("key2"):2, Object("key3"):3}
Walter Dörwald118f9312004-06-02 18:42:25 +00001640 type2test = weakref.WeakKeyDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001641 def _reference(self):
1642 return self.__ref.copy()
Martin v. Löwis5e163332001-02-27 18:36:56 +00001643
Richard Oudkerk7a3dae02013-05-05 23:05:00 +01001644
1645class FinalizeTestCase(unittest.TestCase):
1646
1647 class A:
1648 pass
1649
1650 def _collect_if_necessary(self):
1651 # we create no ref-cycles so in CPython no gc should be needed
1652 if sys.implementation.name != 'cpython':
1653 support.gc_collect()
1654
1655 def test_finalize(self):
1656 def add(x,y,z):
1657 res.append(x + y + z)
1658 return x + y + z
1659
1660 a = self.A()
1661
1662 res = []
1663 f = weakref.finalize(a, add, 67, 43, z=89)
1664 self.assertEqual(f.alive, True)
1665 self.assertEqual(f.peek(), (a, add, (67,43), {'z':89}))
1666 self.assertEqual(f(), 199)
1667 self.assertEqual(f(), None)
1668 self.assertEqual(f(), None)
1669 self.assertEqual(f.peek(), None)
1670 self.assertEqual(f.detach(), None)
1671 self.assertEqual(f.alive, False)
1672 self.assertEqual(res, [199])
1673
1674 res = []
1675 f = weakref.finalize(a, add, 67, 43, 89)
1676 self.assertEqual(f.peek(), (a, add, (67,43,89), {}))
1677 self.assertEqual(f.detach(), (a, add, (67,43,89), {}))
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, [])
1684
1685 res = []
1686 f = weakref.finalize(a, add, x=67, y=43, z=89)
1687 del a
1688 self._collect_if_necessary()
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, [199])
1695
1696 def test_order(self):
1697 a = self.A()
1698 res = []
1699
1700 f1 = weakref.finalize(a, res.append, 'f1')
1701 f2 = weakref.finalize(a, res.append, 'f2')
1702 f3 = weakref.finalize(a, res.append, 'f3')
1703 f4 = weakref.finalize(a, res.append, 'f4')
1704 f5 = weakref.finalize(a, res.append, 'f5')
1705
1706 # make sure finalizers can keep themselves alive
1707 del f1, f4
1708
1709 self.assertTrue(f2.alive)
1710 self.assertTrue(f3.alive)
1711 self.assertTrue(f5.alive)
1712
1713 self.assertTrue(f5.detach())
1714 self.assertFalse(f5.alive)
1715
1716 f5() # nothing because previously unregistered
1717 res.append('A')
1718 f3() # => res.append('f3')
1719 self.assertFalse(f3.alive)
1720 res.append('B')
1721 f3() # nothing because previously called
1722 res.append('C')
1723 del a
1724 self._collect_if_necessary()
1725 # => res.append('f4')
1726 # => res.append('f2')
1727 # => res.append('f1')
1728 self.assertFalse(f2.alive)
1729 res.append('D')
1730 f2() # nothing because previously called by gc
1731
1732 expected = ['A', 'f3', 'B', 'C', 'f4', 'f2', 'f1', 'D']
1733 self.assertEqual(res, expected)
1734
1735 def test_all_freed(self):
1736 # we want a weakrefable subclass of weakref.finalize
1737 class MyFinalizer(weakref.finalize):
1738 pass
1739
1740 a = self.A()
1741 res = []
1742 def callback():
1743 res.append(123)
1744 f = MyFinalizer(a, callback)
1745
1746 wr_callback = weakref.ref(callback)
1747 wr_f = weakref.ref(f)
1748 del callback, f
1749
1750 self.assertIsNotNone(wr_callback())
1751 self.assertIsNotNone(wr_f())
1752
1753 del a
1754 self._collect_if_necessary()
1755
1756 self.assertIsNone(wr_callback())
1757 self.assertIsNone(wr_f())
1758 self.assertEqual(res, [123])
1759
1760 @classmethod
1761 def run_in_child(cls):
1762 def error():
1763 # Create an atexit finalizer from inside a finalizer called
1764 # at exit. This should be the next to be run.
1765 g1 = weakref.finalize(cls, print, 'g1')
1766 print('f3 error')
1767 1/0
1768
1769 # cls should stay alive till atexit callbacks run
1770 f1 = weakref.finalize(cls, print, 'f1', _global_var)
1771 f2 = weakref.finalize(cls, print, 'f2', _global_var)
1772 f3 = weakref.finalize(cls, error)
1773 f4 = weakref.finalize(cls, print, 'f4', _global_var)
1774
1775 assert f1.atexit == True
1776 f2.atexit = False
1777 assert f3.atexit == True
1778 assert f4.atexit == True
1779
1780 def test_atexit(self):
1781 prog = ('from test.test_weakref import FinalizeTestCase;'+
1782 'FinalizeTestCase.run_in_child()')
1783 rc, out, err = script_helper.assert_python_ok('-c', prog)
1784 out = out.decode('ascii').splitlines()
1785 self.assertEqual(out, ['f4 foobar', 'f3 error', 'g1', 'f1 foobar'])
1786 self.assertTrue(b'ZeroDivisionError' in err)
1787
1788
Georg Brandlb533e262008-05-25 18:19:30 +00001789libreftest = """ Doctest for examples in the library reference: weakref.rst
Georg Brandl9a65d582005-07-02 19:07:30 +00001790
1791>>> import weakref
1792>>> class Dict(dict):
1793... pass
1794...
1795>>> obj = Dict(red=1, green=2, blue=3) # this object is weak referencable
1796>>> r = weakref.ref(obj)
Guido van Rossum7131f842007-02-09 20:13:25 +00001797>>> print(r() is obj)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001798True
Georg Brandl9a65d582005-07-02 19:07:30 +00001799
1800>>> import weakref
1801>>> class Object:
1802... pass
1803...
1804>>> o = Object()
1805>>> r = weakref.ref(o)
1806>>> o2 = r()
1807>>> o is o2
1808True
1809>>> del o, o2
Guido van Rossum7131f842007-02-09 20:13:25 +00001810>>> print(r())
Georg Brandl9a65d582005-07-02 19:07:30 +00001811None
1812
1813>>> import weakref
1814>>> class ExtendedRef(weakref.ref):
1815... def __init__(self, ob, callback=None, **annotations):
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001816... super().__init__(ob, callback)
Georg Brandl9a65d582005-07-02 19:07:30 +00001817... self.__counter = 0
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001818... for k, v in annotations.items():
Georg Brandl9a65d582005-07-02 19:07:30 +00001819... setattr(self, k, v)
1820... def __call__(self):
1821... '''Return a pair containing the referent and the number of
1822... times the reference has been called.
1823... '''
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001824... ob = super().__call__()
Georg Brandl9a65d582005-07-02 19:07:30 +00001825... if ob is not None:
1826... self.__counter += 1
1827... ob = (ob, self.__counter)
1828... return ob
Guido van Rossumd8faa362007-04-27 19:54:29 +00001829...
Georg Brandl9a65d582005-07-02 19:07:30 +00001830>>> class A: # not in docs from here, just testing the ExtendedRef
1831... pass
1832...
1833>>> a = A()
1834>>> r = ExtendedRef(a, foo=1, bar="baz")
1835>>> r.foo
18361
1837>>> r.bar
1838'baz'
1839>>> r()[1]
18401
1841>>> r()[1]
18422
1843>>> r()[0] is a
1844True
1845
1846
1847>>> import weakref
1848>>> _id2obj_dict = weakref.WeakValueDictionary()
1849>>> def remember(obj):
1850... oid = id(obj)
1851... _id2obj_dict[oid] = obj
1852... return oid
1853...
1854>>> def id2obj(oid):
1855... return _id2obj_dict[oid]
1856...
1857>>> a = A() # from here, just testing
1858>>> a_id = remember(a)
1859>>> id2obj(a_id) is a
1860True
1861>>> del a
1862>>> try:
1863... id2obj(a_id)
1864... except KeyError:
Guido van Rossum7131f842007-02-09 20:13:25 +00001865... print('OK')
Georg Brandl9a65d582005-07-02 19:07:30 +00001866... else:
Guido van Rossum7131f842007-02-09 20:13:25 +00001867... print('WeakValueDictionary error')
Georg Brandl9a65d582005-07-02 19:07:30 +00001868OK
1869
1870"""
1871
1872__test__ = {'libreftest' : libreftest}
1873
Fred Drake2e2be372001-09-20 21:33:42 +00001874def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001875 support.run_unittest(
Walter Dörwald21d3a322003-05-01 17:45:56 +00001876 ReferencesTestCase,
Antoine Pitrouc3afba12012-11-17 18:57:38 +01001877 WeakMethodTestCase,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001878 MappingTestCase,
1879 WeakValueDictionaryTestCase,
Fred Drakef425b1e2003-07-14 21:37:17 +00001880 WeakKeyDictionaryTestCase,
Amaury Forgeot d'Arcc856c7a2008-06-16 19:50:09 +00001881 SubclassableWeakrefTestCase,
Richard Oudkerk7a3dae02013-05-05 23:05:00 +01001882 FinalizeTestCase,
Fred Drakef425b1e2003-07-14 21:37:17 +00001883 )
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001884 support.run_doctest(sys.modules[__name__])
Fred Drake2e2be372001-09-20 21:33:42 +00001885
1886
1887if __name__ == "__main__":
1888 test_main()