blob: afd0b62f3b3c10a2ee3b1c290d57fc1e6a7df174 [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
Fred Drakeb0fefc52001-03-23 04:22:45 +0000136 def test_proxy_ref(self):
137 o = C()
138 o.bar = 1
139 ref1 = weakref.proxy(o, self.callback)
140 ref2 = weakref.proxy(o, self.callback)
141 del o
Fred Drake41deb1e2001-02-01 05:27:45 +0000142
Fred Drakeb0fefc52001-03-23 04:22:45 +0000143 def check(proxy):
144 proxy.bar
Fred Drake41deb1e2001-02-01 05:27:45 +0000145
Neal Norwitz2633c692007-02-26 22:22:47 +0000146 self.assertRaises(ReferenceError, check, ref1)
147 self.assertRaises(ReferenceError, check, ref2)
148 self.assertRaises(ReferenceError, bool, weakref.proxy(C()))
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000149 self.assertEqual(self.cbcalled, 2)
Fred Drake41deb1e2001-02-01 05:27:45 +0000150
Fred Drakeb0fefc52001-03-23 04:22:45 +0000151 def check_basic_ref(self, factory):
152 o = factory()
153 ref = weakref.ref(o)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200154 self.assertIsNotNone(ref(),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000155 "weak reference to live object should be live")
156 o2 = ref()
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200157 self.assertIs(o, o2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000158 "<ref>() should return original object if live")
Fred Drake41deb1e2001-02-01 05:27:45 +0000159
Fred Drakeb0fefc52001-03-23 04:22:45 +0000160 def check_basic_callback(self, factory):
161 self.cbcalled = 0
162 o = factory()
163 ref = weakref.ref(o, self.callback)
164 del o
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200165 self.assertEqual(self.cbcalled, 1,
Fred Drake705088e2001-04-13 17:18:15 +0000166 "callback did not properly set 'cbcalled'")
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200167 self.assertIsNone(ref(),
Fred Drake705088e2001-04-13 17:18:15 +0000168 "ref2 should be dead after deleting object reference")
Fred Drake41deb1e2001-02-01 05:27:45 +0000169
Fred Drakeb0fefc52001-03-23 04:22:45 +0000170 def test_ref_reuse(self):
171 o = C()
172 ref1 = weakref.ref(o)
173 # create a proxy to make sure that there's an intervening creation
174 # between these two; it should make no difference
175 proxy = weakref.proxy(o)
176 ref2 = weakref.ref(o)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200177 self.assertIs(ref1, ref2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000178 "reference object w/out callback should be re-used")
Fred Drake41deb1e2001-02-01 05:27:45 +0000179
Fred Drakeb0fefc52001-03-23 04:22:45 +0000180 o = C()
181 proxy = weakref.proxy(o)
182 ref1 = weakref.ref(o)
183 ref2 = weakref.ref(o)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200184 self.assertIs(ref1, ref2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000185 "reference object w/out callback should be re-used")
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200186 self.assertEqual(weakref.getweakrefcount(o), 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000187 "wrong weak ref count for object")
188 del proxy
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200189 self.assertEqual(weakref.getweakrefcount(o), 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000190 "wrong weak ref count for object after deleting proxy")
Fred Drake41deb1e2001-02-01 05:27:45 +0000191
Fred Drakeb0fefc52001-03-23 04:22:45 +0000192 def test_proxy_reuse(self):
193 o = C()
194 proxy1 = weakref.proxy(o)
195 ref = weakref.ref(o)
196 proxy2 = weakref.proxy(o)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200197 self.assertIs(proxy1, proxy2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000198 "proxy object w/out callback should have been re-used")
199
200 def test_basic_proxy(self):
201 o = C()
202 self.check_proxy(o, weakref.proxy(o))
203
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000204 L = collections.UserList()
Fred Drake5935ff02001-12-19 16:54:23 +0000205 p = weakref.proxy(L)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000206 self.assertFalse(p, "proxy for empty UserList should be false")
Fred Drake5935ff02001-12-19 16:54:23 +0000207 p.append(12)
208 self.assertEqual(len(L), 1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000209 self.assertTrue(p, "proxy for non-empty UserList should be true")
Fred Drake5935ff02001-12-19 16:54:23 +0000210 p[:] = [2, 3]
211 self.assertEqual(len(L), 2)
212 self.assertEqual(len(p), 2)
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000213 self.assertIn(3, p, "proxy didn't support __contains__() properly")
Fred Drake5935ff02001-12-19 16:54:23 +0000214 p[1] = 5
215 self.assertEqual(L[1], 5)
216 self.assertEqual(p[1], 5)
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000217 L2 = collections.UserList(L)
Fred Drake5935ff02001-12-19 16:54:23 +0000218 p2 = weakref.proxy(L2)
219 self.assertEqual(p, p2)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000220 ## self.assertEqual(repr(L2), repr(p2))
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000221 L3 = collections.UserList(range(10))
Fred Drake43735da2002-04-11 03:59:42 +0000222 p3 = weakref.proxy(L3)
223 self.assertEqual(L3[:], p3[:])
224 self.assertEqual(L3[5:], p3[5:])
225 self.assertEqual(L3[:5], p3[:5])
226 self.assertEqual(L3[2:5], p3[2:5])
Fred Drake5935ff02001-12-19 16:54:23 +0000227
Benjamin Peterson32019772009-11-19 03:08:32 +0000228 def test_proxy_unicode(self):
229 # See bug 5037
230 class C(object):
231 def __str__(self):
232 return "string"
233 def __bytes__(self):
234 return b"bytes"
235 instance = C()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000236 self.assertIn("__bytes__", dir(weakref.proxy(instance)))
Benjamin Peterson32019772009-11-19 03:08:32 +0000237 self.assertEqual(bytes(weakref.proxy(instance)), b"bytes")
238
Georg Brandlb533e262008-05-25 18:19:30 +0000239 def test_proxy_index(self):
240 class C:
241 def __index__(self):
242 return 10
243 o = C()
244 p = weakref.proxy(o)
245 self.assertEqual(operator.index(p), 10)
246
247 def test_proxy_div(self):
248 class C:
249 def __floordiv__(self, other):
250 return 42
251 def __ifloordiv__(self, other):
252 return 21
253 o = C()
254 p = weakref.proxy(o)
255 self.assertEqual(p // 5, 42)
256 p //= 5
257 self.assertEqual(p, 21)
258
Fred Drakeea2adc92004-02-03 19:56:46 +0000259 # The PyWeakref_* C API is documented as allowing either NULL or
260 # None as the value for the callback, where either means "no
261 # callback". The "no callback" ref and proxy objects are supposed
262 # to be shared so long as they exist by all callers so long as
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000263 # they are active. In Python 2.3.3 and earlier, this guarantee
Fred Drakeea2adc92004-02-03 19:56:46 +0000264 # was not honored, and was broken in different ways for
265 # PyWeakref_NewRef() and PyWeakref_NewProxy(). (Two tests.)
266
267 def test_shared_ref_without_callback(self):
268 self.check_shared_without_callback(weakref.ref)
269
270 def test_shared_proxy_without_callback(self):
271 self.check_shared_without_callback(weakref.proxy)
272
273 def check_shared_without_callback(self, makeref):
274 o = Object(1)
275 p1 = makeref(o, None)
276 p2 = makeref(o, None)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200277 self.assertIs(p1, p2, "both callbacks were None in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000278 del p1, p2
279 p1 = makeref(o)
280 p2 = makeref(o, None)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200281 self.assertIs(p1, p2, "callbacks were NULL, None in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000282 del p1, p2
283 p1 = makeref(o)
284 p2 = makeref(o)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200285 self.assertIs(p1, p2, "both callbacks were NULL in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000286 del p1, p2
287 p1 = makeref(o, None)
288 p2 = makeref(o)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200289 self.assertIs(p1, p2, "callbacks were None, NULL in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000290
Fred Drakeb0fefc52001-03-23 04:22:45 +0000291 def test_callable_proxy(self):
292 o = Callable()
293 ref1 = weakref.proxy(o)
294
295 self.check_proxy(o, ref1)
296
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200297 self.assertIs(type(ref1), weakref.CallableProxyType,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000298 "proxy is not of callable type")
299 ref1('twinkies!')
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200300 self.assertEqual(o.bar, 'twinkies!',
Fred Drakeb0fefc52001-03-23 04:22:45 +0000301 "call through proxy not passed through to original")
Fred Drake3bb4d212001-10-18 19:28:29 +0000302 ref1(x='Splat.')
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200303 self.assertEqual(o.bar, 'Splat.',
Fred Drake3bb4d212001-10-18 19:28:29 +0000304 "call through proxy not passed through to original")
Fred Drakeb0fefc52001-03-23 04:22:45 +0000305
306 # expect due to too few args
307 self.assertRaises(TypeError, ref1)
308
309 # expect due to too many args
310 self.assertRaises(TypeError, ref1, 1, 2, 3)
311
312 def check_proxy(self, o, proxy):
313 o.foo = 1
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200314 self.assertEqual(proxy.foo, 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000315 "proxy does not reflect attribute addition")
316 o.foo = 2
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200317 self.assertEqual(proxy.foo, 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000318 "proxy does not reflect attribute modification")
319 del o.foo
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200320 self.assertFalse(hasattr(proxy, 'foo'),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000321 "proxy does not reflect attribute removal")
322
323 proxy.foo = 1
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200324 self.assertEqual(o.foo, 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000325 "object does not reflect attribute addition via proxy")
326 proxy.foo = 2
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200327 self.assertEqual(o.foo, 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000328 "object does not reflect attribute modification via proxy")
329 del proxy.foo
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200330 self.assertFalse(hasattr(o, 'foo'),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000331 "object does not reflect attribute removal via proxy")
332
Raymond Hettingerd693a812003-06-30 04:18:48 +0000333 def test_proxy_deletion(self):
334 # Test clearing of SF bug #762891
335 class Foo:
336 result = None
337 def __delitem__(self, accessor):
338 self.result = accessor
339 g = Foo()
340 f = weakref.proxy(g)
341 del f[0]
342 self.assertEqual(f.result, 0)
343
Raymond Hettingere6c470f2005-03-27 03:04:54 +0000344 def test_proxy_bool(self):
345 # Test clearing of SF bug #1170766
346 class List(list): pass
347 lyst = List()
348 self.assertEqual(bool(weakref.proxy(lyst)), bool(lyst))
349
Fred Drakeb0fefc52001-03-23 04:22:45 +0000350 def test_getweakrefcount(self):
351 o = C()
352 ref1 = weakref.ref(o)
353 ref2 = weakref.ref(o, self.callback)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200354 self.assertEqual(weakref.getweakrefcount(o), 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000355 "got wrong number of weak reference objects")
356
357 proxy1 = weakref.proxy(o)
358 proxy2 = weakref.proxy(o, self.callback)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200359 self.assertEqual(weakref.getweakrefcount(o), 4,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000360 "got wrong number of weak reference objects")
361
Fred Drakeea2adc92004-02-03 19:56:46 +0000362 del ref1, ref2, proxy1, proxy2
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200363 self.assertEqual(weakref.getweakrefcount(o), 0,
Fred Drakeea2adc92004-02-03 19:56:46 +0000364 "weak reference objects not unlinked from"
365 " referent when discarded.")
366
Walter Dörwaldb167b042003-12-11 12:34:05 +0000367 # assumes ints do not support weakrefs
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200368 self.assertEqual(weakref.getweakrefcount(1), 0,
Walter Dörwaldb167b042003-12-11 12:34:05 +0000369 "got wrong number of weak reference objects for int")
370
Fred Drakeb0fefc52001-03-23 04:22:45 +0000371 def test_getweakrefs(self):
372 o = C()
373 ref1 = weakref.ref(o, self.callback)
374 ref2 = weakref.ref(o, self.callback)
375 del ref1
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200376 self.assertEqual(weakref.getweakrefs(o), [ref2],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000377 "list of refs does not match")
378
379 o = C()
380 ref1 = weakref.ref(o, self.callback)
381 ref2 = weakref.ref(o, self.callback)
382 del ref2
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200383 self.assertEqual(weakref.getweakrefs(o), [ref1],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000384 "list of refs does not match")
385
Fred Drakeea2adc92004-02-03 19:56:46 +0000386 del ref1
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200387 self.assertEqual(weakref.getweakrefs(o), [],
Fred Drakeea2adc92004-02-03 19:56:46 +0000388 "list of refs not cleared")
389
Walter Dörwaldb167b042003-12-11 12:34:05 +0000390 # assumes ints do not support weakrefs
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200391 self.assertEqual(weakref.getweakrefs(1), [],
Walter Dörwaldb167b042003-12-11 12:34:05 +0000392 "list of refs does not match for int")
393
Fred Drake39c27f12001-10-18 18:06:05 +0000394 def test_newstyle_number_ops(self):
395 class F(float):
396 pass
397 f = F(2.0)
398 p = weakref.proxy(f)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200399 self.assertEqual(p + 1.0, 3.0)
400 self.assertEqual(1.0 + p, 3.0) # this used to SEGV
Fred Drake39c27f12001-10-18 18:06:05 +0000401
Fred Drake2a64f462001-12-10 23:46:02 +0000402 def test_callbacks_protected(self):
Guido van Rossum9eee5542002-08-22 20:21:30 +0000403 # Callbacks protected from already-set exceptions?
Fred Drake2a64f462001-12-10 23:46:02 +0000404 # Regression test for SF bug #478534.
405 class BogusError(Exception):
406 pass
407 data = {}
408 def remove(k):
409 del data[k]
410 def encapsulate():
411 f = lambda : ()
412 data[weakref.ref(f, remove)] = None
413 raise BogusError
414 try:
415 encapsulate()
416 except BogusError:
417 pass
418 else:
419 self.fail("exception not properly restored")
420 try:
421 encapsulate()
422 except BogusError:
423 pass
424 else:
425 self.fail("exception not properly restored")
426
Tim Petersadd09b42003-11-12 20:43:28 +0000427 def test_sf_bug_840829(self):
428 # "weakref callbacks and gc corrupt memory"
429 # subtype_dealloc erroneously exposed a new-style instance
430 # already in the process of getting deallocated to gc,
431 # causing double-deallocation if the instance had a weakref
432 # callback that triggered gc.
433 # If the bug exists, there probably won't be an obvious symptom
434 # in a release build. In a debug build, a segfault will occur
435 # when the second attempt to remove the instance from the "list
436 # of all objects" occurs.
437
438 import gc
439
440 class C(object):
441 pass
442
443 c = C()
444 wr = weakref.ref(c, lambda ignore: gc.collect())
445 del c
446
Tim Petersf7f9e992003-11-13 21:59:32 +0000447 # There endeth the first part. It gets worse.
448 del wr
449
450 c1 = C()
451 c1.i = C()
452 wr = weakref.ref(c1.i, lambda ignore: gc.collect())
453
454 c2 = C()
455 c2.c1 = c1
456 del c1 # still alive because c2 points to it
457
458 # Now when subtype_dealloc gets called on c2, it's not enough just
459 # that c2 is immune from gc while the weakref callbacks associated
460 # with c2 execute (there are none in this 2nd half of the test, btw).
461 # subtype_dealloc goes on to call the base classes' deallocs too,
462 # so any gc triggered by weakref callbacks associated with anything
463 # torn down by a base class dealloc can also trigger double
464 # deallocation of c2.
465 del c2
Fred Drake41deb1e2001-02-01 05:27:45 +0000466
Tim Peters403a2032003-11-20 21:21:46 +0000467 def test_callback_in_cycle_1(self):
468 import gc
469
470 class J(object):
471 pass
472
473 class II(object):
474 def acallback(self, ignore):
475 self.J
476
477 I = II()
478 I.J = J
479 I.wr = weakref.ref(J, I.acallback)
480
481 # Now J and II are each in a self-cycle (as all new-style class
482 # objects are, since their __mro__ points back to them). I holds
483 # both a weak reference (I.wr) and a strong reference (I.J) to class
484 # J. I is also in a cycle (I.wr points to a weakref that references
485 # I.acallback). When we del these three, they all become trash, but
486 # the cycles prevent any of them from getting cleaned up immediately.
487 # Instead they have to wait for cyclic gc to deduce that they're
488 # trash.
489 #
490 # gc used to call tp_clear on all of them, and the order in which
491 # it does that is pretty accidental. The exact order in which we
492 # built up these things manages to provoke gc into running tp_clear
493 # in just the right order (I last). Calling tp_clear on II leaves
494 # behind an insane class object (its __mro__ becomes NULL). Calling
495 # tp_clear on J breaks its self-cycle, but J doesn't get deleted
496 # just then because of the strong reference from I.J. Calling
497 # tp_clear on I starts to clear I's __dict__, and just happens to
498 # clear I.J first -- I.wr is still intact. That removes the last
499 # reference to J, which triggers the weakref callback. The callback
500 # tries to do "self.J", and instances of new-style classes look up
501 # attributes ("J") in the class dict first. The class (II) wants to
502 # search II.__mro__, but that's NULL. The result was a segfault in
503 # a release build, and an assert failure in a debug build.
504 del I, J, II
505 gc.collect()
506
507 def test_callback_in_cycle_2(self):
508 import gc
509
510 # This is just like test_callback_in_cycle_1, except that II is an
511 # old-style class. The symptom is different then: an instance of an
512 # old-style class looks in its own __dict__ first. 'J' happens to
513 # get cleared from I.__dict__ before 'wr', and 'J' was never in II's
514 # __dict__, so the attribute isn't found. The difference is that
515 # the old-style II doesn't have a NULL __mro__ (it doesn't have any
516 # __mro__), so no segfault occurs. Instead it got:
517 # test_callback_in_cycle_2 (__main__.ReferencesTestCase) ...
518 # Exception exceptions.AttributeError:
519 # "II instance has no attribute 'J'" in <bound method II.acallback
520 # of <?.II instance at 0x00B9B4B8>> ignored
521
522 class J(object):
523 pass
524
525 class II:
526 def acallback(self, ignore):
527 self.J
528
529 I = II()
530 I.J = J
531 I.wr = weakref.ref(J, I.acallback)
532
533 del I, J, II
534 gc.collect()
535
536 def test_callback_in_cycle_3(self):
537 import gc
538
539 # This one broke the first patch that fixed the last two. In this
540 # case, the objects reachable from the callback aren't also reachable
541 # from the object (c1) *triggering* the callback: you can get to
542 # c1 from c2, but not vice-versa. The result was that c2's __dict__
543 # got tp_clear'ed by the time the c2.cb callback got invoked.
544
545 class C:
546 def cb(self, ignore):
547 self.me
548 self.c1
549 self.wr
550
551 c1, c2 = C(), C()
552
553 c2.me = c2
554 c2.c1 = c1
555 c2.wr = weakref.ref(c1, c2.cb)
556
557 del c1, c2
558 gc.collect()
559
560 def test_callback_in_cycle_4(self):
561 import gc
562
563 # Like test_callback_in_cycle_3, except c2 and c1 have different
564 # classes. c2's class (C) isn't reachable from c1 then, so protecting
565 # objects reachable from the dying object (c1) isn't enough to stop
566 # c2's class (C) from getting tp_clear'ed before c2.cb is invoked.
567 # The result was a segfault (C.__mro__ was NULL when the callback
568 # tried to look up self.me).
569
570 class C(object):
571 def cb(self, ignore):
572 self.me
573 self.c1
574 self.wr
575
576 class D:
577 pass
578
579 c1, c2 = D(), C()
580
581 c2.me = c2
582 c2.c1 = c1
583 c2.wr = weakref.ref(c1, c2.cb)
584
585 del c1, c2, C, D
586 gc.collect()
587
588 def test_callback_in_cycle_resurrection(self):
589 import gc
590
591 # Do something nasty in a weakref callback: resurrect objects
592 # from dead cycles. For this to be attempted, the weakref and
593 # its callback must also be part of the cyclic trash (else the
594 # objects reachable via the callback couldn't be in cyclic trash
595 # to begin with -- the callback would act like an external root).
596 # But gc clears trash weakrefs with callbacks early now, which
597 # disables the callbacks, so the callbacks shouldn't get called
598 # at all (and so nothing actually gets resurrected).
599
600 alist = []
601 class C(object):
602 def __init__(self, value):
603 self.attribute = value
604
605 def acallback(self, ignore):
606 alist.append(self.c)
607
608 c1, c2 = C(1), C(2)
609 c1.c = c2
610 c2.c = c1
611 c1.wr = weakref.ref(c2, c1.acallback)
612 c2.wr = weakref.ref(c1, c2.acallback)
613
614 def C_went_away(ignore):
615 alist.append("C went away")
616 wr = weakref.ref(C, C_went_away)
617
618 del c1, c2, C # make them all trash
619 self.assertEqual(alist, []) # del isn't enough to reclaim anything
620
621 gc.collect()
622 # c1.wr and c2.wr were part of the cyclic trash, so should have
623 # been cleared without their callbacks executing. OTOH, the weakref
624 # to C is bound to a function local (wr), and wasn't trash, so that
625 # callback should have been invoked when C went away.
626 self.assertEqual(alist, ["C went away"])
627 # The remaining weakref should be dead now (its callback ran).
628 self.assertEqual(wr(), None)
629
630 del alist[:]
631 gc.collect()
632 self.assertEqual(alist, [])
633
634 def test_callbacks_on_callback(self):
635 import gc
636
637 # Set up weakref callbacks *on* weakref callbacks.
638 alist = []
639 def safe_callback(ignore):
640 alist.append("safe_callback called")
641
642 class C(object):
643 def cb(self, ignore):
644 alist.append("cb called")
645
646 c, d = C(), C()
647 c.other = d
648 d.other = c
649 callback = c.cb
650 c.wr = weakref.ref(d, callback) # this won't trigger
651 d.wr = weakref.ref(callback, d.cb) # ditto
652 external_wr = weakref.ref(callback, safe_callback) # but this will
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200653 self.assertIs(external_wr(), callback)
Tim Peters403a2032003-11-20 21:21:46 +0000654
655 # The weakrefs attached to c and d should get cleared, so that
656 # C.cb is never called. But external_wr isn't part of the cyclic
657 # trash, and no cyclic trash is reachable from it, so safe_callback
658 # should get invoked when the bound method object callback (c.cb)
659 # -- which is itself a callback, and also part of the cyclic trash --
660 # gets reclaimed at the end of gc.
661
662 del callback, c, d, C
663 self.assertEqual(alist, []) # del isn't enough to clean up cycles
664 gc.collect()
665 self.assertEqual(alist, ["safe_callback called"])
666 self.assertEqual(external_wr(), None)
667
668 del alist[:]
669 gc.collect()
670 self.assertEqual(alist, [])
671
Fred Drakebc875f52004-02-04 23:14:14 +0000672 def test_gc_during_ref_creation(self):
673 self.check_gc_during_creation(weakref.ref)
674
675 def test_gc_during_proxy_creation(self):
676 self.check_gc_during_creation(weakref.proxy)
677
678 def check_gc_during_creation(self, makeref):
679 thresholds = gc.get_threshold()
680 gc.set_threshold(1, 1, 1)
681 gc.collect()
Fred Drake55cf4342004-02-13 19:21:57 +0000682 class A:
683 pass
Fred Drakebc875f52004-02-04 23:14:14 +0000684
685 def callback(*args):
686 pass
687
Fred Drake55cf4342004-02-13 19:21:57 +0000688 referenced = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000689
Fred Drake55cf4342004-02-13 19:21:57 +0000690 a = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000691 a.a = a
692 a.wr = makeref(referenced)
693
694 try:
695 # now make sure the object and the ref get labeled as
696 # cyclic trash:
Fred Drake55cf4342004-02-13 19:21:57 +0000697 a = A()
698 weakref.ref(referenced, callback)
Fred Drakebc875f52004-02-04 23:14:14 +0000699
700 finally:
701 gc.set_threshold(*thresholds)
702
Thomas Woutersb2137042007-02-01 18:02:27 +0000703 def test_ref_created_during_del(self):
704 # Bug #1377858
705 # A weakref created in an object's __del__() would crash the
706 # interpreter when the weakref was cleaned up since it would refer to
707 # non-existent memory. This test should not segfault the interpreter.
708 class Target(object):
709 def __del__(self):
710 global ref_from_del
711 ref_from_del = weakref.ref(self)
712
713 w = Target()
714
Benjamin Peterson9aa42992008-09-10 21:57:34 +0000715 def test_init(self):
716 # Issue 3634
717 # <weakref to class>.__init__() doesn't check errors correctly
718 r = weakref.ref(Exception)
719 self.assertRaises(TypeError, r.__init__, 0, 0, 0, 0, 0)
720 # No exception should be raised here
721 gc.collect()
722
Antoine Pitrou3af01a12010-03-31 21:40:47 +0000723 def test_classes(self):
724 # Check that classes are weakrefable.
725 class A(object):
726 pass
727 l = []
728 weakref.ref(int)
729 a = weakref.ref(A, l.append)
730 A = None
731 gc.collect()
732 self.assertEqual(a(), None)
733 self.assertEqual(l, [a])
734
Antoine Pitroue11fecb2012-11-11 19:36:51 +0100735 def test_equality(self):
736 # Alive weakrefs defer equality testing to their underlying object.
737 x = Object(1)
738 y = Object(1)
739 z = Object(2)
740 a = weakref.ref(x)
741 b = weakref.ref(y)
742 c = weakref.ref(z)
743 d = weakref.ref(x)
744 # Note how we directly test the operators here, to stress both
745 # __eq__ and __ne__.
746 self.assertTrue(a == b)
747 self.assertFalse(a != b)
748 self.assertFalse(a == c)
749 self.assertTrue(a != c)
750 self.assertTrue(a == d)
751 self.assertFalse(a != d)
752 del x, y, z
753 gc.collect()
754 for r in a, b, c:
755 # Sanity check
756 self.assertIs(r(), None)
757 # Dead weakrefs compare by identity: whether `a` and `d` are the
758 # same weakref object is an implementation detail, since they pointed
759 # to the same original object and didn't have a callback.
760 # (see issue #16453).
761 self.assertFalse(a == b)
762 self.assertTrue(a != b)
763 self.assertFalse(a == c)
764 self.assertTrue(a != c)
765 self.assertEqual(a == d, a is d)
766 self.assertEqual(a != d, a is not d)
767
768 def test_ordering(self):
769 # weakrefs cannot be ordered, even if the underlying objects can.
770 ops = [operator.lt, operator.gt, operator.le, operator.ge]
771 x = Object(1)
772 y = Object(1)
773 a = weakref.ref(x)
774 b = weakref.ref(y)
775 for op in ops:
776 self.assertRaises(TypeError, op, a, b)
777 # Same when dead.
778 del x, y
779 gc.collect()
780 for op in ops:
781 self.assertRaises(TypeError, op, a, b)
782
783 def test_hashing(self):
784 # Alive weakrefs hash the same as the underlying object
785 x = Object(42)
786 y = Object(42)
787 a = weakref.ref(x)
788 b = weakref.ref(y)
789 self.assertEqual(hash(a), hash(42))
790 del x, y
791 gc.collect()
792 # Dead weakrefs:
793 # - retain their hash is they were hashed when alive;
794 # - otherwise, cannot be hashed.
795 self.assertEqual(hash(a), hash(42))
796 self.assertRaises(TypeError, hash, b)
797
Antoine Pitrou62a0d6e2012-12-08 21:15:26 +0100798 def test_trashcan_16602(self):
799 # Issue #16602: when a weakref's target was part of a long
800 # deallocation chain, the trashcan mechanism could delay clearing
801 # of the weakref and make the target object visible from outside
802 # code even though its refcount had dropped to 0. A crash ensued.
803 class C:
804 def __init__(self, parent):
805 if not parent:
806 return
807 wself = weakref.ref(self)
808 def cb(wparent):
809 o = wself()
810 self.wparent = weakref.ref(parent, cb)
811
812 d = weakref.WeakKeyDictionary()
813 root = c = C(None)
814 for n in range(100):
815 d[c] = c = C(c)
816 del root
817 gc.collect()
818
Mark Dickinson556e94b2013-04-13 15:45:44 +0100819 def test_callback_attribute(self):
820 x = Object(1)
821 callback = lambda ref: None
822 ref1 = weakref.ref(x, callback)
823 self.assertIs(ref1.__callback__, callback)
824
825 ref2 = weakref.ref(x)
826 self.assertIsNone(ref2.__callback__)
827
828 def test_callback_attribute_after_deletion(self):
829 x = Object(1)
830 ref = weakref.ref(x, self.callback)
831 self.assertIsNotNone(ref.__callback__)
832 del x
833 support.gc_collect()
834 self.assertIsNone(ref.__callback__)
835
836 def test_set_callback_attribute(self):
837 x = Object(1)
838 callback = lambda ref: None
839 ref1 = weakref.ref(x, callback)
840 with self.assertRaises(AttributeError):
841 ref1.__callback__ = lambda ref: None
842
Fred Drake0a4dd392004-07-02 18:57:45 +0000843
Amaury Forgeot d'Arcc856c7a2008-06-16 19:50:09 +0000844class SubclassableWeakrefTestCase(TestBase):
Fred Drake0a4dd392004-07-02 18:57:45 +0000845
846 def test_subclass_refs(self):
847 class MyRef(weakref.ref):
848 def __init__(self, ob, callback=None, value=42):
849 self.value = value
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000850 super().__init__(ob, callback)
Fred Drake0a4dd392004-07-02 18:57:45 +0000851 def __call__(self):
852 self.called = True
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000853 return super().__call__()
Fred Drake0a4dd392004-07-02 18:57:45 +0000854 o = Object("foo")
855 mr = MyRef(o, value=24)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200856 self.assertIs(mr(), o)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000857 self.assertTrue(mr.called)
Fred Drake0a4dd392004-07-02 18:57:45 +0000858 self.assertEqual(mr.value, 24)
859 del o
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200860 self.assertIsNone(mr())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000861 self.assertTrue(mr.called)
Fred Drake0a4dd392004-07-02 18:57:45 +0000862
863 def test_subclass_refs_dont_replace_standard_refs(self):
864 class MyRef(weakref.ref):
865 pass
866 o = Object(42)
867 r1 = MyRef(o)
868 r2 = weakref.ref(o)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200869 self.assertIsNot(r1, r2)
Fred Drake0a4dd392004-07-02 18:57:45 +0000870 self.assertEqual(weakref.getweakrefs(o), [r2, r1])
871 self.assertEqual(weakref.getweakrefcount(o), 2)
872 r3 = MyRef(o)
873 self.assertEqual(weakref.getweakrefcount(o), 3)
874 refs = weakref.getweakrefs(o)
875 self.assertEqual(len(refs), 3)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200876 self.assertIs(r2, refs[0])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000877 self.assertIn(r1, refs[1:])
878 self.assertIn(r3, refs[1:])
Fred Drake0a4dd392004-07-02 18:57:45 +0000879
880 def test_subclass_refs_dont_conflate_callbacks(self):
881 class MyRef(weakref.ref):
882 pass
883 o = Object(42)
884 r1 = MyRef(o, id)
885 r2 = MyRef(o, str)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200886 self.assertIsNot(r1, r2)
Fred Drake0a4dd392004-07-02 18:57:45 +0000887 refs = weakref.getweakrefs(o)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000888 self.assertIn(r1, refs)
889 self.assertIn(r2, refs)
Fred Drake0a4dd392004-07-02 18:57:45 +0000890
891 def test_subclass_refs_with_slots(self):
892 class MyRef(weakref.ref):
893 __slots__ = "slot1", "slot2"
894 def __new__(type, ob, callback, slot1, slot2):
895 return weakref.ref.__new__(type, ob, callback)
896 def __init__(self, ob, callback, slot1, slot2):
897 self.slot1 = slot1
898 self.slot2 = slot2
899 def meth(self):
900 return self.slot1 + self.slot2
901 o = Object(42)
902 r = MyRef(o, None, "abc", "def")
903 self.assertEqual(r.slot1, "abc")
904 self.assertEqual(r.slot2, "def")
905 self.assertEqual(r.meth(), "abcdef")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000906 self.assertFalse(hasattr(r, "__dict__"))
Fred Drake0a4dd392004-07-02 18:57:45 +0000907
Amaury Forgeot d'Arcc856c7a2008-06-16 19:50:09 +0000908 def test_subclass_refs_with_cycle(self):
909 # Bug #3110
910 # An instance of a weakref subclass can have attributes.
911 # If such a weakref holds the only strong reference to the object,
912 # deleting the weakref will delete the object. In this case,
913 # the callback must not be called, because the ref object is
914 # being deleted.
915 class MyRef(weakref.ref):
916 pass
917
918 # Use a local callback, for "regrtest -R::"
919 # to detect refcounting problems
920 def callback(w):
921 self.cbcalled += 1
922
923 o = C()
924 r1 = MyRef(o, callback)
925 r1.o = o
926 del o
927
928 del r1 # Used to crash here
929
930 self.assertEqual(self.cbcalled, 0)
931
932 # Same test, with two weakrefs to the same object
933 # (since code paths are different)
934 o = C()
935 r1 = MyRef(o, callback)
936 r2 = MyRef(o, callback)
937 r1.r = r2
938 r2.o = o
939 del o
940 del r2
941
942 del r1 # Used to crash here
943
944 self.assertEqual(self.cbcalled, 0)
945
Fred Drake0a4dd392004-07-02 18:57:45 +0000946
Antoine Pitrouc3afba12012-11-17 18:57:38 +0100947class WeakMethodTestCase(unittest.TestCase):
948
949 def _subclass(self):
950 """Return a Object subclass overriding `some_method`."""
951 class C(Object):
952 def some_method(self):
953 return 6
954 return C
955
956 def test_alive(self):
957 o = Object(1)
958 r = weakref.WeakMethod(o.some_method)
959 self.assertIsInstance(r, weakref.ReferenceType)
960 self.assertIsInstance(r(), type(o.some_method))
961 self.assertIs(r().__self__, o)
962 self.assertIs(r().__func__, o.some_method.__func__)
963 self.assertEqual(r()(), 4)
964
965 def test_object_dead(self):
966 o = Object(1)
967 r = weakref.WeakMethod(o.some_method)
968 del o
969 gc.collect()
970 self.assertIs(r(), None)
971
972 def test_method_dead(self):
973 C = self._subclass()
974 o = C(1)
975 r = weakref.WeakMethod(o.some_method)
976 del C.some_method
977 gc.collect()
978 self.assertIs(r(), None)
979
980 def test_callback_when_object_dead(self):
981 # Test callback behaviour when object dies first.
982 C = self._subclass()
983 calls = []
984 def cb(arg):
985 calls.append(arg)
986 o = C(1)
987 r = weakref.WeakMethod(o.some_method, cb)
988 del o
989 gc.collect()
990 self.assertEqual(calls, [r])
991 # Callback is only called once.
992 C.some_method = Object.some_method
993 gc.collect()
994 self.assertEqual(calls, [r])
995
996 def test_callback_when_method_dead(self):
997 # Test callback behaviour when method dies first.
998 C = self._subclass()
999 calls = []
1000 def cb(arg):
1001 calls.append(arg)
1002 o = C(1)
1003 r = weakref.WeakMethod(o.some_method, cb)
1004 del C.some_method
1005 gc.collect()
1006 self.assertEqual(calls, [r])
1007 # Callback is only called once.
1008 del o
1009 gc.collect()
1010 self.assertEqual(calls, [r])
1011
1012 @support.cpython_only
1013 def test_no_cycles(self):
1014 # A WeakMethod doesn't create any reference cycle to itself.
1015 o = Object(1)
1016 def cb(_):
1017 pass
1018 r = weakref.WeakMethod(o.some_method, cb)
1019 wr = weakref.ref(r)
1020 del r
1021 self.assertIs(wr(), None)
1022
1023 def test_equality(self):
1024 def _eq(a, b):
1025 self.assertTrue(a == b)
1026 self.assertFalse(a != b)
1027 def _ne(a, b):
1028 self.assertTrue(a != b)
1029 self.assertFalse(a == b)
1030 x = Object(1)
1031 y = Object(1)
1032 a = weakref.WeakMethod(x.some_method)
1033 b = weakref.WeakMethod(y.some_method)
1034 c = weakref.WeakMethod(x.other_method)
1035 d = weakref.WeakMethod(y.other_method)
1036 # Objects equal, same method
1037 _eq(a, b)
1038 _eq(c, d)
1039 # Objects equal, different method
1040 _ne(a, c)
1041 _ne(a, d)
1042 _ne(b, c)
1043 _ne(b, d)
1044 # Objects unequal, same or different method
1045 z = Object(2)
1046 e = weakref.WeakMethod(z.some_method)
1047 f = weakref.WeakMethod(z.other_method)
1048 _ne(a, e)
1049 _ne(a, f)
1050 _ne(b, e)
1051 _ne(b, f)
1052 del x, y, z
1053 gc.collect()
1054 # Dead WeakMethods compare by identity
1055 refs = a, b, c, d, e, f
1056 for q in refs:
1057 for r in refs:
1058 self.assertEqual(q == r, q is r)
1059 self.assertEqual(q != r, q is not r)
1060
1061 def test_hashing(self):
1062 # Alive WeakMethods are hashable if the underlying object is
1063 # hashable.
1064 x = Object(1)
1065 y = Object(1)
1066 a = weakref.WeakMethod(x.some_method)
1067 b = weakref.WeakMethod(y.some_method)
1068 c = weakref.WeakMethod(y.other_method)
1069 # Since WeakMethod objects are equal, the hashes should be equal.
1070 self.assertEqual(hash(a), hash(b))
1071 ha = hash(a)
1072 # Dead WeakMethods retain their old hash value
1073 del x, y
1074 gc.collect()
1075 self.assertEqual(hash(a), ha)
1076 self.assertEqual(hash(b), ha)
1077 # If it wasn't hashed when alive, a dead WeakMethod cannot be hashed.
1078 self.assertRaises(TypeError, hash, c)
1079
1080
Fred Drakeb0fefc52001-03-23 04:22:45 +00001081class MappingTestCase(TestBase):
Martin v. Löwis5e163332001-02-27 18:36:56 +00001082
Fred Drakeb0fefc52001-03-23 04:22:45 +00001083 COUNT = 10
1084
Antoine Pitroubbe2f602012-03-01 16:26:35 +01001085 def check_len_cycles(self, dict_type, cons):
1086 N = 20
1087 items = [RefCycle() for i in range(N)]
1088 dct = dict_type(cons(o) for o in items)
1089 # Keep an iterator alive
1090 it = dct.items()
1091 try:
1092 next(it)
1093 except StopIteration:
1094 pass
1095 del items
1096 gc.collect()
1097 n1 = len(dct)
1098 del it
1099 gc.collect()
1100 n2 = len(dct)
1101 # one item may be kept alive inside the iterator
1102 self.assertIn(n1, (0, 1))
1103 self.assertEqual(n2, 0)
1104
1105 def test_weak_keyed_len_cycles(self):
1106 self.check_len_cycles(weakref.WeakKeyDictionary, lambda k: (k, 1))
1107
1108 def test_weak_valued_len_cycles(self):
1109 self.check_len_cycles(weakref.WeakValueDictionary, lambda k: (1, k))
1110
1111 def check_len_race(self, dict_type, cons):
1112 # Extended sanity checks for len() in the face of cyclic collection
1113 self.addCleanup(gc.set_threshold, *gc.get_threshold())
1114 for th in range(1, 100):
1115 N = 20
1116 gc.collect(0)
1117 gc.set_threshold(th, th, th)
1118 items = [RefCycle() for i in range(N)]
1119 dct = dict_type(cons(o) for o in items)
1120 del items
1121 # All items will be collected at next garbage collection pass
1122 it = dct.items()
1123 try:
1124 next(it)
1125 except StopIteration:
1126 pass
1127 n1 = len(dct)
1128 del it
1129 n2 = len(dct)
1130 self.assertGreaterEqual(n1, 0)
1131 self.assertLessEqual(n1, N)
1132 self.assertGreaterEqual(n2, 0)
1133 self.assertLessEqual(n2, n1)
1134
1135 def test_weak_keyed_len_race(self):
1136 self.check_len_race(weakref.WeakKeyDictionary, lambda k: (k, 1))
1137
1138 def test_weak_valued_len_race(self):
1139 self.check_len_race(weakref.WeakValueDictionary, lambda k: (1, k))
1140
Fred Drakeb0fefc52001-03-23 04:22:45 +00001141 def test_weak_values(self):
Fred Drake0e540c32001-05-02 05:44:22 +00001142 #
1143 # This exercises d.copy(), d.items(), d[], del d[], len(d).
1144 #
1145 dict, objects = self.make_weak_valued_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +00001146 for o in objects:
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001147 self.assertEqual(weakref.getweakrefcount(o), 1)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001148 self.assertIs(o, dict[o.arg],
Fred Drakeb0fefc52001-03-23 04:22:45 +00001149 "wrong object returned by weak dict!")
Barry Warsawecaab832008-09-04 01:42:51 +00001150 items1 = list(dict.items())
1151 items2 = list(dict.copy().items())
Fred Drakeb0fefc52001-03-23 04:22:45 +00001152 items1.sort()
1153 items2.sort()
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001154 self.assertEqual(items1, items2,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001155 "cloning of weak-valued dictionary did not work!")
1156 del items1, items2
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001157 self.assertEqual(len(dict), self.COUNT)
Fred Drakeb0fefc52001-03-23 04:22:45 +00001158 del objects[0]
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001159 self.assertEqual(len(dict), self.COUNT - 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001160 "deleting object did not cause dictionary update")
1161 del objects, o
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001162 self.assertEqual(len(dict), 0,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001163 "deleting the values did not clear the dictionary")
Fred Drake4fd06e02001-08-03 04:11:27 +00001164 # regression on SF bug #447152:
1165 dict = weakref.WeakValueDictionary()
1166 self.assertRaises(KeyError, dict.__getitem__, 1)
1167 dict[2] = C()
1168 self.assertRaises(KeyError, dict.__getitem__, 2)
Fred Drakeb0fefc52001-03-23 04:22:45 +00001169
1170 def test_weak_keys(self):
Fred Drake0e540c32001-05-02 05:44:22 +00001171 #
1172 # This exercises d.copy(), d.items(), d[] = v, d[], del d[],
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001173 # len(d), k in d.
Fred Drake0e540c32001-05-02 05:44:22 +00001174 #
1175 dict, objects = self.make_weak_keyed_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +00001176 for o in objects:
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001177 self.assertEqual(weakref.getweakrefcount(o), 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001178 "wrong number of weak references to %r!" % o)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001179 self.assertIs(o.arg, dict[o],
Fred Drakeb0fefc52001-03-23 04:22:45 +00001180 "wrong object returned by weak dict!")
1181 items1 = dict.items()
1182 items2 = dict.copy().items()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001183 self.assertEqual(set(items1), set(items2),
Fred Drakeb0fefc52001-03-23 04:22:45 +00001184 "cloning of weak-keyed dictionary did not work!")
1185 del items1, items2
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001186 self.assertEqual(len(dict), self.COUNT)
Fred Drakeb0fefc52001-03-23 04:22:45 +00001187 del objects[0]
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001188 self.assertEqual(len(dict), (self.COUNT - 1),
Fred Drakeb0fefc52001-03-23 04:22:45 +00001189 "deleting object did not cause dictionary update")
1190 del objects, o
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001191 self.assertEqual(len(dict), 0,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001192 "deleting the keys did not clear the dictionary")
Fred Drake752eda42001-11-06 16:38:34 +00001193 o = Object(42)
1194 dict[o] = "What is the meaning of the universe?"
Benjamin Peterson577473f2010-01-19 00:09:57 +00001195 self.assertIn(o, dict)
1196 self.assertNotIn(34, dict)
Martin v. Löwis5e163332001-02-27 18:36:56 +00001197
Fred Drake0e540c32001-05-02 05:44:22 +00001198 def test_weak_keyed_iters(self):
1199 dict, objects = self.make_weak_keyed_dict()
1200 self.check_iters(dict)
1201
Thomas Wouters477c8d52006-05-27 19:21:47 +00001202 # Test keyrefs()
1203 refs = dict.keyrefs()
1204 self.assertEqual(len(refs), len(objects))
1205 objects2 = list(objects)
1206 for wr in refs:
1207 ob = wr()
Benjamin Peterson577473f2010-01-19 00:09:57 +00001208 self.assertIn(ob, dict)
1209 self.assertIn(ob, dict)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001210 self.assertEqual(ob.arg, dict[ob])
1211 objects2.remove(ob)
1212 self.assertEqual(len(objects2), 0)
1213
1214 # Test iterkeyrefs()
1215 objects2 = list(objects)
Barry Warsawecaab832008-09-04 01:42:51 +00001216 self.assertEqual(len(list(dict.keyrefs())), len(objects))
1217 for wr in dict.keyrefs():
Thomas Wouters477c8d52006-05-27 19:21:47 +00001218 ob = wr()
Benjamin Peterson577473f2010-01-19 00:09:57 +00001219 self.assertIn(ob, dict)
1220 self.assertIn(ob, dict)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001221 self.assertEqual(ob.arg, dict[ob])
1222 objects2.remove(ob)
1223 self.assertEqual(len(objects2), 0)
1224
Fred Drake0e540c32001-05-02 05:44:22 +00001225 def test_weak_valued_iters(self):
1226 dict, objects = self.make_weak_valued_dict()
1227 self.check_iters(dict)
1228
Thomas Wouters477c8d52006-05-27 19:21:47 +00001229 # Test valuerefs()
1230 refs = dict.valuerefs()
1231 self.assertEqual(len(refs), len(objects))
1232 objects2 = list(objects)
1233 for wr in refs:
1234 ob = wr()
1235 self.assertEqual(ob, dict[ob.arg])
1236 self.assertEqual(ob.arg, dict[ob.arg].arg)
1237 objects2.remove(ob)
1238 self.assertEqual(len(objects2), 0)
1239
1240 # Test itervaluerefs()
1241 objects2 = list(objects)
1242 self.assertEqual(len(list(dict.itervaluerefs())), len(objects))
1243 for wr in dict.itervaluerefs():
1244 ob = wr()
1245 self.assertEqual(ob, dict[ob.arg])
1246 self.assertEqual(ob.arg, dict[ob.arg].arg)
1247 objects2.remove(ob)
1248 self.assertEqual(len(objects2), 0)
1249
Fred Drake0e540c32001-05-02 05:44:22 +00001250 def check_iters(self, dict):
1251 # item iterator:
Barry Warsawecaab832008-09-04 01:42:51 +00001252 items = list(dict.items())
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001253 for item in dict.items():
Fred Drake0e540c32001-05-02 05:44:22 +00001254 items.remove(item)
Barry Warsawecaab832008-09-04 01:42:51 +00001255 self.assertFalse(items, "items() did not touch all items")
Fred Drake0e540c32001-05-02 05:44:22 +00001256
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001257 # key iterator, via __iter__():
Guido van Rossum07f24362007-02-11 22:59:48 +00001258 keys = list(dict.keys())
Fred Drake0e540c32001-05-02 05:44:22 +00001259 for k in dict:
1260 keys.remove(k)
Barry Warsawecaab832008-09-04 01:42:51 +00001261 self.assertFalse(keys, "__iter__() did not touch all keys")
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001262
1263 # key iterator, via iterkeys():
Guido van Rossum07f24362007-02-11 22:59:48 +00001264 keys = list(dict.keys())
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001265 for k in dict.keys():
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001266 keys.remove(k)
Barry Warsawecaab832008-09-04 01:42:51 +00001267 self.assertFalse(keys, "iterkeys() did not touch all keys")
Fred Drake0e540c32001-05-02 05:44:22 +00001268
1269 # value iterator:
Guido van Rossum07f24362007-02-11 22:59:48 +00001270 values = list(dict.values())
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001271 for v in dict.values():
Fred Drake0e540c32001-05-02 05:44:22 +00001272 values.remove(v)
Barry Warsawecaab832008-09-04 01:42:51 +00001273 self.assertFalse(values,
Fred Drakef425b1e2003-07-14 21:37:17 +00001274 "itervalues() did not touch all values")
Fred Drake0e540c32001-05-02 05:44:22 +00001275
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001276 def check_weak_destroy_while_iterating(self, dict, objects, iter_name):
1277 n = len(dict)
1278 it = iter(getattr(dict, iter_name)())
1279 next(it) # Trigger internal iteration
1280 # Destroy an object
1281 del objects[-1]
1282 gc.collect() # just in case
1283 # We have removed either the first consumed object, or another one
1284 self.assertIn(len(list(it)), [len(objects), len(objects) - 1])
1285 del it
1286 # The removal has been committed
1287 self.assertEqual(len(dict), n - 1)
1288
1289 def check_weak_destroy_and_mutate_while_iterating(self, dict, testcontext):
1290 # Check that we can explicitly mutate the weak dict without
1291 # interfering with delayed removal.
1292 # `testcontext` should create an iterator, destroy one of the
1293 # weakref'ed objects and then return a new key/value pair corresponding
1294 # to the destroyed object.
1295 with testcontext() as (k, v):
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001296 self.assertNotIn(k, dict)
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001297 with testcontext() as (k, v):
1298 self.assertRaises(KeyError, dict.__delitem__, k)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001299 self.assertNotIn(k, dict)
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001300 with testcontext() as (k, v):
1301 self.assertRaises(KeyError, dict.pop, k)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001302 self.assertNotIn(k, dict)
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001303 with testcontext() as (k, v):
1304 dict[k] = v
1305 self.assertEqual(dict[k], v)
1306 ddict = copy.copy(dict)
1307 with testcontext() as (k, v):
1308 dict.update(ddict)
1309 self.assertEqual(dict, ddict)
1310 with testcontext() as (k, v):
1311 dict.clear()
1312 self.assertEqual(len(dict), 0)
1313
Antoine Pitrou1bf974d2014-10-05 20:02:28 +02001314 def check_weak_del_and_len_while_iterating(self, dict, testcontext):
1315 # Check that len() works when both iterating and removing keys
1316 # explicitly through various means (.pop(), .clear()...), while
1317 # implicit mutation is deferred because an iterator is alive.
1318 # (each call to testcontext() should schedule one item for removal
1319 # for this test to work properly)
1320 o = Object(123456)
1321 with testcontext():
1322 n = len(dict)
1323 dict.popitem()
1324 self.assertEqual(len(dict), n - 1)
1325 dict[o] = o
1326 self.assertEqual(len(dict), n)
1327 with testcontext():
1328 self.assertEqual(len(dict), n - 1)
1329 dict.pop(next(dict.keys()))
1330 self.assertEqual(len(dict), n - 2)
1331 with testcontext():
1332 self.assertEqual(len(dict), n - 3)
1333 del dict[next(dict.keys())]
1334 self.assertEqual(len(dict), n - 4)
1335 with testcontext():
1336 self.assertEqual(len(dict), n - 5)
1337 dict.popitem()
1338 self.assertEqual(len(dict), n - 6)
1339 with testcontext():
1340 dict.clear()
1341 self.assertEqual(len(dict), 0)
1342 self.assertEqual(len(dict), 0)
1343
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001344 def test_weak_keys_destroy_while_iterating(self):
1345 # Issue #7105: iterators shouldn't crash when a key is implicitly removed
1346 dict, objects = self.make_weak_keyed_dict()
1347 self.check_weak_destroy_while_iterating(dict, objects, 'keys')
1348 self.check_weak_destroy_while_iterating(dict, objects, 'items')
1349 self.check_weak_destroy_while_iterating(dict, objects, 'values')
1350 self.check_weak_destroy_while_iterating(dict, objects, 'keyrefs')
1351 dict, objects = self.make_weak_keyed_dict()
1352 @contextlib.contextmanager
1353 def testcontext():
1354 try:
1355 it = iter(dict.items())
1356 next(it)
1357 # Schedule a key/value for removal and recreate it
1358 v = objects.pop().arg
1359 gc.collect() # just in case
1360 yield Object(v), v
1361 finally:
1362 it = None # should commit all removals
Benjamin Peterson18bb7022014-08-24 18:02:15 -05001363 gc.collect()
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001364 self.check_weak_destroy_and_mutate_while_iterating(dict, testcontext)
Antoine Pitrou1bf974d2014-10-05 20:02:28 +02001365 # Issue #21173: len() fragile when keys are both implicitly and
1366 # explicitly removed.
1367 dict, objects = self.make_weak_keyed_dict()
1368 self.check_weak_del_and_len_while_iterating(dict, testcontext)
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001369
1370 def test_weak_values_destroy_while_iterating(self):
1371 # Issue #7105: iterators shouldn't crash when a key is implicitly removed
1372 dict, objects = self.make_weak_valued_dict()
1373 self.check_weak_destroy_while_iterating(dict, objects, 'keys')
1374 self.check_weak_destroy_while_iterating(dict, objects, 'items')
1375 self.check_weak_destroy_while_iterating(dict, objects, 'values')
1376 self.check_weak_destroy_while_iterating(dict, objects, 'itervaluerefs')
1377 self.check_weak_destroy_while_iterating(dict, objects, 'valuerefs')
1378 dict, objects = self.make_weak_valued_dict()
1379 @contextlib.contextmanager
1380 def testcontext():
1381 try:
1382 it = iter(dict.items())
1383 next(it)
1384 # Schedule a key/value for removal and recreate it
1385 k = objects.pop().arg
1386 gc.collect() # just in case
1387 yield k, Object(k)
1388 finally:
1389 it = None # should commit all removals
Benjamin Peterson18bb7022014-08-24 18:02:15 -05001390 gc.collect()
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001391 self.check_weak_destroy_and_mutate_while_iterating(dict, testcontext)
Antoine Pitrou1bf974d2014-10-05 20:02:28 +02001392 dict, objects = self.make_weak_valued_dict()
1393 self.check_weak_del_and_len_while_iterating(dict, testcontext)
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001394
Guido van Rossum009afb72002-06-10 20:00:52 +00001395 def test_make_weak_keyed_dict_from_dict(self):
1396 o = Object(3)
1397 dict = weakref.WeakKeyDictionary({o:364})
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001398 self.assertEqual(dict[o], 364)
Guido van Rossum009afb72002-06-10 20:00:52 +00001399
1400 def test_make_weak_keyed_dict_from_weak_keyed_dict(self):
1401 o = Object(3)
1402 dict = weakref.WeakKeyDictionary({o:364})
1403 dict2 = weakref.WeakKeyDictionary(dict)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001404 self.assertEqual(dict[o], 364)
Guido van Rossum009afb72002-06-10 20:00:52 +00001405
Fred Drake0e540c32001-05-02 05:44:22 +00001406 def make_weak_keyed_dict(self):
1407 dict = weakref.WeakKeyDictionary()
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001408 objects = list(map(Object, range(self.COUNT)))
Fred Drake0e540c32001-05-02 05:44:22 +00001409 for o in objects:
1410 dict[o] = o.arg
1411 return dict, objects
1412
Antoine Pitrouc06de472009-05-30 21:04:26 +00001413 def test_make_weak_valued_dict_from_dict(self):
1414 o = Object(3)
1415 dict = weakref.WeakValueDictionary({364:o})
1416 self.assertEqual(dict[364], o)
1417
1418 def test_make_weak_valued_dict_from_weak_valued_dict(self):
1419 o = Object(3)
1420 dict = weakref.WeakValueDictionary({364:o})
1421 dict2 = weakref.WeakValueDictionary(dict)
1422 self.assertEqual(dict[364], o)
1423
Fred Drake0e540c32001-05-02 05:44:22 +00001424 def make_weak_valued_dict(self):
1425 dict = weakref.WeakValueDictionary()
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001426 objects = list(map(Object, range(self.COUNT)))
Fred Drake0e540c32001-05-02 05:44:22 +00001427 for o in objects:
1428 dict[o.arg] = o
1429 return dict, objects
1430
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001431 def check_popitem(self, klass, key1, value1, key2, value2):
1432 weakdict = klass()
1433 weakdict[key1] = value1
1434 weakdict[key2] = value2
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001435 self.assertEqual(len(weakdict), 2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001436 k, v = weakdict.popitem()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001437 self.assertEqual(len(weakdict), 1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001438 if k is key1:
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001439 self.assertIs(v, value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001440 else:
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001441 self.assertIs(v, value2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001442 k, v = weakdict.popitem()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001443 self.assertEqual(len(weakdict), 0)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001444 if k is key1:
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001445 self.assertIs(v, value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001446 else:
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001447 self.assertIs(v, value2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001448
1449 def test_weak_valued_dict_popitem(self):
1450 self.check_popitem(weakref.WeakValueDictionary,
1451 "key1", C(), "key2", C())
1452
1453 def test_weak_keyed_dict_popitem(self):
1454 self.check_popitem(weakref.WeakKeyDictionary,
1455 C(), "value 1", C(), "value 2")
1456
1457 def check_setdefault(self, klass, key, value1, value2):
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001458 self.assertIsNot(value1, value2,
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001459 "invalid test"
1460 " -- value parameters must be distinct objects")
1461 weakdict = klass()
1462 o = weakdict.setdefault(key, value1)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001463 self.assertIs(o, value1)
Benjamin Peterson577473f2010-01-19 00:09:57 +00001464 self.assertIn(key, weakdict)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001465 self.assertIs(weakdict.get(key), value1)
1466 self.assertIs(weakdict[key], value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001467
1468 o = weakdict.setdefault(key, value2)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001469 self.assertIs(o, value1)
Benjamin Peterson577473f2010-01-19 00:09:57 +00001470 self.assertIn(key, weakdict)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001471 self.assertIs(weakdict.get(key), value1)
1472 self.assertIs(weakdict[key], value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001473
1474 def test_weak_valued_dict_setdefault(self):
1475 self.check_setdefault(weakref.WeakValueDictionary,
1476 "key", C(), C())
1477
1478 def test_weak_keyed_dict_setdefault(self):
1479 self.check_setdefault(weakref.WeakKeyDictionary,
1480 C(), "value 1", "value 2")
1481
Fred Drakea0a4ab12001-04-16 17:37:27 +00001482 def check_update(self, klass, dict):
Fred Drake0e540c32001-05-02 05:44:22 +00001483 #
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001484 # This exercises d.update(), len(d), d.keys(), k in d,
Fred Drake0e540c32001-05-02 05:44:22 +00001485 # d.get(), d[].
1486 #
Fred Drakea0a4ab12001-04-16 17:37:27 +00001487 weakdict = klass()
1488 weakdict.update(dict)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001489 self.assertEqual(len(weakdict), len(dict))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001490 for k in weakdict.keys():
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001491 self.assertIn(k, dict, "mysterious new key appeared in weak dict")
Fred Drakea0a4ab12001-04-16 17:37:27 +00001492 v = dict.get(k)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001493 self.assertIs(v, weakdict[k])
1494 self.assertIs(v, weakdict.get(k))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001495 for k in dict.keys():
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001496 self.assertIn(k, weakdict, "original key disappeared in weak dict")
Fred Drakea0a4ab12001-04-16 17:37:27 +00001497 v = dict[k]
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001498 self.assertIs(v, weakdict[k])
1499 self.assertIs(v, weakdict.get(k))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001500
1501 def test_weak_valued_dict_update(self):
1502 self.check_update(weakref.WeakValueDictionary,
1503 {1: C(), 'a': C(), C(): C()})
1504
1505 def test_weak_keyed_dict_update(self):
1506 self.check_update(weakref.WeakKeyDictionary,
1507 {C(): 1, C(): 2, C(): 3})
1508
Fred Drakeccc75622001-09-06 14:52:39 +00001509 def test_weak_keyed_delitem(self):
1510 d = weakref.WeakKeyDictionary()
1511 o1 = Object('1')
1512 o2 = Object('2')
1513 d[o1] = 'something'
1514 d[o2] = 'something'
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001515 self.assertEqual(len(d), 2)
Fred Drakeccc75622001-09-06 14:52:39 +00001516 del d[o1]
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001517 self.assertEqual(len(d), 1)
Barry Warsawecaab832008-09-04 01:42:51 +00001518 self.assertEqual(list(d.keys()), [o2])
Fred Drakeccc75622001-09-06 14:52:39 +00001519
1520 def test_weak_valued_delitem(self):
1521 d = weakref.WeakValueDictionary()
1522 o1 = Object('1')
1523 o2 = Object('2')
1524 d['something'] = o1
1525 d['something else'] = o2
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001526 self.assertEqual(len(d), 2)
Fred Drakeccc75622001-09-06 14:52:39 +00001527 del d['something']
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001528 self.assertEqual(len(d), 1)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001529 self.assertEqual(list(d.items()), [('something else', o2)])
Fred Drakeccc75622001-09-06 14:52:39 +00001530
Tim Peters886128f2003-05-25 01:45:11 +00001531 def test_weak_keyed_bad_delitem(self):
1532 d = weakref.WeakKeyDictionary()
1533 o = Object('1')
1534 # An attempt to delete an object that isn't there should raise
Tim Peters50d8b8b2003-05-25 17:44:31 +00001535 # KeyError. It didn't before 2.3.
Tim Peters886128f2003-05-25 01:45:11 +00001536 self.assertRaises(KeyError, d.__delitem__, o)
Tim Peters50d8b8b2003-05-25 17:44:31 +00001537 self.assertRaises(KeyError, d.__getitem__, o)
1538
1539 # If a key isn't of a weakly referencable type, __getitem__ and
1540 # __setitem__ raise TypeError. __delitem__ should too.
1541 self.assertRaises(TypeError, d.__delitem__, 13)
1542 self.assertRaises(TypeError, d.__getitem__, 13)
1543 self.assertRaises(TypeError, d.__setitem__, 13, 13)
Tim Peters886128f2003-05-25 01:45:11 +00001544
1545 def test_weak_keyed_cascading_deletes(self):
1546 # SF bug 742860. For some reason, before 2.3 __delitem__ iterated
1547 # over the keys via self.data.iterkeys(). If things vanished from
1548 # the dict during this (or got added), that caused a RuntimeError.
1549
1550 d = weakref.WeakKeyDictionary()
1551 mutate = False
1552
1553 class C(object):
1554 def __init__(self, i):
1555 self.value = i
1556 def __hash__(self):
1557 return hash(self.value)
1558 def __eq__(self, other):
1559 if mutate:
1560 # Side effect that mutates the dict, by removing the
1561 # last strong reference to a key.
1562 del objs[-1]
1563 return self.value == other.value
1564
1565 objs = [C(i) for i in range(4)]
1566 for o in objs:
1567 d[o] = o.value
1568 del o # now the only strong references to keys are in objs
1569 # Find the order in which iterkeys sees the keys.
Barry Warsawecaab832008-09-04 01:42:51 +00001570 objs = list(d.keys())
Tim Peters886128f2003-05-25 01:45:11 +00001571 # Reverse it, so that the iteration implementation of __delitem__
1572 # has to keep looping to find the first object we delete.
1573 objs.reverse()
Tim Peters50d8b8b2003-05-25 17:44:31 +00001574
Tim Peters886128f2003-05-25 01:45:11 +00001575 # Turn on mutation in C.__eq__. The first time thru the loop,
1576 # under the iterkeys() business the first comparison will delete
1577 # the last item iterkeys() would see, and that causes a
1578 # RuntimeError: dictionary changed size during iteration
1579 # when the iterkeys() loop goes around to try comparing the next
Tim Peters50d8b8b2003-05-25 17:44:31 +00001580 # key. After this was fixed, it just deletes the last object *our*
Tim Peters886128f2003-05-25 01:45:11 +00001581 # "for o in obj" loop would have gotten to.
1582 mutate = True
1583 count = 0
1584 for o in objs:
1585 count += 1
1586 del d[o]
1587 self.assertEqual(len(d), 0)
1588 self.assertEqual(count, 2)
1589
Serhiy Storchaka0c937b32014-07-22 12:14:52 +03001590 def test_make_weak_valued_dict_repr(self):
1591 dict = weakref.WeakValueDictionary()
1592 self.assertRegex(repr(dict), '<WeakValueDictionary at 0x.*>')
1593
1594 def test_make_weak_keyed_dict_repr(self):
1595 dict = weakref.WeakKeyDictionary()
1596 self.assertRegex(repr(dict), '<WeakKeyDictionary at 0x.*>')
1597
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001598from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001599
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001600class WeakValueDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +00001601 """Check that WeakValueDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001602 __ref = {"key1":Object(1), "key2":Object(2), "key3":Object(3)}
Walter Dörwald118f9312004-06-02 18:42:25 +00001603 type2test = weakref.WeakValueDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001604 def _reference(self):
1605 return self.__ref.copy()
1606
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001607class WeakKeyDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +00001608 """Check that WeakKeyDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001609 __ref = {Object("key1"):1, Object("key2"):2, Object("key3"):3}
Walter Dörwald118f9312004-06-02 18:42:25 +00001610 type2test = weakref.WeakKeyDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001611 def _reference(self):
1612 return self.__ref.copy()
Martin v. Löwis5e163332001-02-27 18:36:56 +00001613
Richard Oudkerk7a3dae02013-05-05 23:05:00 +01001614
1615class FinalizeTestCase(unittest.TestCase):
1616
1617 class A:
1618 pass
1619
1620 def _collect_if_necessary(self):
1621 # we create no ref-cycles so in CPython no gc should be needed
1622 if sys.implementation.name != 'cpython':
1623 support.gc_collect()
1624
1625 def test_finalize(self):
1626 def add(x,y,z):
1627 res.append(x + y + z)
1628 return x + y + z
1629
1630 a = self.A()
1631
1632 res = []
1633 f = weakref.finalize(a, add, 67, 43, z=89)
1634 self.assertEqual(f.alive, True)
1635 self.assertEqual(f.peek(), (a, add, (67,43), {'z':89}))
1636 self.assertEqual(f(), 199)
1637 self.assertEqual(f(), None)
1638 self.assertEqual(f(), None)
1639 self.assertEqual(f.peek(), None)
1640 self.assertEqual(f.detach(), None)
1641 self.assertEqual(f.alive, False)
1642 self.assertEqual(res, [199])
1643
1644 res = []
1645 f = weakref.finalize(a, add, 67, 43, 89)
1646 self.assertEqual(f.peek(), (a, add, (67,43,89), {}))
1647 self.assertEqual(f.detach(), (a, add, (67,43,89), {}))
1648 self.assertEqual(f(), None)
1649 self.assertEqual(f(), None)
1650 self.assertEqual(f.peek(), None)
1651 self.assertEqual(f.detach(), None)
1652 self.assertEqual(f.alive, False)
1653 self.assertEqual(res, [])
1654
1655 res = []
1656 f = weakref.finalize(a, add, x=67, y=43, z=89)
1657 del a
1658 self._collect_if_necessary()
1659 self.assertEqual(f(), None)
1660 self.assertEqual(f(), None)
1661 self.assertEqual(f.peek(), None)
1662 self.assertEqual(f.detach(), None)
1663 self.assertEqual(f.alive, False)
1664 self.assertEqual(res, [199])
1665
1666 def test_order(self):
1667 a = self.A()
1668 res = []
1669
1670 f1 = weakref.finalize(a, res.append, 'f1')
1671 f2 = weakref.finalize(a, res.append, 'f2')
1672 f3 = weakref.finalize(a, res.append, 'f3')
1673 f4 = weakref.finalize(a, res.append, 'f4')
1674 f5 = weakref.finalize(a, res.append, 'f5')
1675
1676 # make sure finalizers can keep themselves alive
1677 del f1, f4
1678
1679 self.assertTrue(f2.alive)
1680 self.assertTrue(f3.alive)
1681 self.assertTrue(f5.alive)
1682
1683 self.assertTrue(f5.detach())
1684 self.assertFalse(f5.alive)
1685
1686 f5() # nothing because previously unregistered
1687 res.append('A')
1688 f3() # => res.append('f3')
1689 self.assertFalse(f3.alive)
1690 res.append('B')
1691 f3() # nothing because previously called
1692 res.append('C')
1693 del a
1694 self._collect_if_necessary()
1695 # => res.append('f4')
1696 # => res.append('f2')
1697 # => res.append('f1')
1698 self.assertFalse(f2.alive)
1699 res.append('D')
1700 f2() # nothing because previously called by gc
1701
1702 expected = ['A', 'f3', 'B', 'C', 'f4', 'f2', 'f1', 'D']
1703 self.assertEqual(res, expected)
1704
1705 def test_all_freed(self):
1706 # we want a weakrefable subclass of weakref.finalize
1707 class MyFinalizer(weakref.finalize):
1708 pass
1709
1710 a = self.A()
1711 res = []
1712 def callback():
1713 res.append(123)
1714 f = MyFinalizer(a, callback)
1715
1716 wr_callback = weakref.ref(callback)
1717 wr_f = weakref.ref(f)
1718 del callback, f
1719
1720 self.assertIsNotNone(wr_callback())
1721 self.assertIsNotNone(wr_f())
1722
1723 del a
1724 self._collect_if_necessary()
1725
1726 self.assertIsNone(wr_callback())
1727 self.assertIsNone(wr_f())
1728 self.assertEqual(res, [123])
1729
1730 @classmethod
1731 def run_in_child(cls):
1732 def error():
1733 # Create an atexit finalizer from inside a finalizer called
1734 # at exit. This should be the next to be run.
1735 g1 = weakref.finalize(cls, print, 'g1')
1736 print('f3 error')
1737 1/0
1738
1739 # cls should stay alive till atexit callbacks run
1740 f1 = weakref.finalize(cls, print, 'f1', _global_var)
1741 f2 = weakref.finalize(cls, print, 'f2', _global_var)
1742 f3 = weakref.finalize(cls, error)
1743 f4 = weakref.finalize(cls, print, 'f4', _global_var)
1744
1745 assert f1.atexit == True
1746 f2.atexit = False
1747 assert f3.atexit == True
1748 assert f4.atexit == True
1749
1750 def test_atexit(self):
1751 prog = ('from test.test_weakref import FinalizeTestCase;'+
1752 'FinalizeTestCase.run_in_child()')
1753 rc, out, err = script_helper.assert_python_ok('-c', prog)
1754 out = out.decode('ascii').splitlines()
1755 self.assertEqual(out, ['f4 foobar', 'f3 error', 'g1', 'f1 foobar'])
1756 self.assertTrue(b'ZeroDivisionError' in err)
1757
1758
Georg Brandlb533e262008-05-25 18:19:30 +00001759libreftest = """ Doctest for examples in the library reference: weakref.rst
Georg Brandl9a65d582005-07-02 19:07:30 +00001760
1761>>> import weakref
1762>>> class Dict(dict):
1763... pass
1764...
1765>>> obj = Dict(red=1, green=2, blue=3) # this object is weak referencable
1766>>> r = weakref.ref(obj)
Guido van Rossum7131f842007-02-09 20:13:25 +00001767>>> print(r() is obj)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001768True
Georg Brandl9a65d582005-07-02 19:07:30 +00001769
1770>>> import weakref
1771>>> class Object:
1772... pass
1773...
1774>>> o = Object()
1775>>> r = weakref.ref(o)
1776>>> o2 = r()
1777>>> o is o2
1778True
1779>>> del o, o2
Guido van Rossum7131f842007-02-09 20:13:25 +00001780>>> print(r())
Georg Brandl9a65d582005-07-02 19:07:30 +00001781None
1782
1783>>> import weakref
1784>>> class ExtendedRef(weakref.ref):
1785... def __init__(self, ob, callback=None, **annotations):
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001786... super().__init__(ob, callback)
Georg Brandl9a65d582005-07-02 19:07:30 +00001787... self.__counter = 0
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001788... for k, v in annotations.items():
Georg Brandl9a65d582005-07-02 19:07:30 +00001789... setattr(self, k, v)
1790... def __call__(self):
1791... '''Return a pair containing the referent and the number of
1792... times the reference has been called.
1793... '''
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001794... ob = super().__call__()
Georg Brandl9a65d582005-07-02 19:07:30 +00001795... if ob is not None:
1796... self.__counter += 1
1797... ob = (ob, self.__counter)
1798... return ob
Guido van Rossumd8faa362007-04-27 19:54:29 +00001799...
Georg Brandl9a65d582005-07-02 19:07:30 +00001800>>> class A: # not in docs from here, just testing the ExtendedRef
1801... pass
1802...
1803>>> a = A()
1804>>> r = ExtendedRef(a, foo=1, bar="baz")
1805>>> r.foo
18061
1807>>> r.bar
1808'baz'
1809>>> r()[1]
18101
1811>>> r()[1]
18122
1813>>> r()[0] is a
1814True
1815
1816
1817>>> import weakref
1818>>> _id2obj_dict = weakref.WeakValueDictionary()
1819>>> def remember(obj):
1820... oid = id(obj)
1821... _id2obj_dict[oid] = obj
1822... return oid
1823...
1824>>> def id2obj(oid):
1825... return _id2obj_dict[oid]
1826...
1827>>> a = A() # from here, just testing
1828>>> a_id = remember(a)
1829>>> id2obj(a_id) is a
1830True
1831>>> del a
1832>>> try:
1833... id2obj(a_id)
1834... except KeyError:
Guido van Rossum7131f842007-02-09 20:13:25 +00001835... print('OK')
Georg Brandl9a65d582005-07-02 19:07:30 +00001836... else:
Guido van Rossum7131f842007-02-09 20:13:25 +00001837... print('WeakValueDictionary error')
Georg Brandl9a65d582005-07-02 19:07:30 +00001838OK
1839
1840"""
1841
1842__test__ = {'libreftest' : libreftest}
1843
Fred Drake2e2be372001-09-20 21:33:42 +00001844def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001845 support.run_unittest(
Walter Dörwald21d3a322003-05-01 17:45:56 +00001846 ReferencesTestCase,
Antoine Pitrouc3afba12012-11-17 18:57:38 +01001847 WeakMethodTestCase,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001848 MappingTestCase,
1849 WeakValueDictionaryTestCase,
Fred Drakef425b1e2003-07-14 21:37:17 +00001850 WeakKeyDictionaryTestCase,
Amaury Forgeot d'Arcc856c7a2008-06-16 19:50:09 +00001851 SubclassableWeakrefTestCase,
Richard Oudkerk7a3dae02013-05-05 23:05:00 +01001852 FinalizeTestCase,
Fred Drakef425b1e2003-07-14 21:37:17 +00001853 )
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001854 support.run_doctest(sys.modules[__name__])
Fred Drake2e2be372001-09-20 21:33:42 +00001855
1856
1857if __name__ == "__main__":
1858 test_main()