blob: dd5a781ed59d8ba87939b50232d0b2af011c3188 [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
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02009import threading
Antoine Pitrouc1ee4882016-12-19 10:56:40 +010010import time
Fish96d37db2019-02-07 14:51:59 -050011import random
Fred Drake41deb1e2001-02-01 05:27:45 +000012
Berker Peksagce643912015-05-06 06:33:17 +030013from test import support
Serhiy Storchaka662db122019-08-08 08:42:54 +030014from test.support import script_helper, ALWAYS_EQ
Fred Drake41deb1e2001-02-01 05:27:45 +000015
Thomas Woutersb2137042007-02-01 18:02:27 +000016# Used in ReferencesTestCase.test_ref_created_during_del() .
17ref_from_del = None
Fred Drake41deb1e2001-02-01 05:27:45 +000018
Richard Oudkerk7a3dae052013-05-05 23:05:00 +010019# Used by FinalizeTestCase as a global that may be replaced by None
20# when the interpreter shuts down.
21_global_var = 'foobar'
22
Fred Drake41deb1e2001-02-01 05:27:45 +000023class C:
Fred Drakeb0fefc52001-03-23 04:22:45 +000024 def method(self):
25 pass
Fred Drake41deb1e2001-02-01 05:27:45 +000026
27
Fred Drakeb0fefc52001-03-23 04:22:45 +000028class Callable:
29 bar = None
Fred Drake41deb1e2001-02-01 05:27:45 +000030
Fred Drakeb0fefc52001-03-23 04:22:45 +000031 def __call__(self, x):
32 self.bar = x
Fred Drake41deb1e2001-02-01 05:27:45 +000033
34
Fred Drakeb0fefc52001-03-23 04:22:45 +000035def create_function():
36 def f(): pass
37 return f
38
39def create_bound_method():
40 return C().method
41
Fred Drake41deb1e2001-02-01 05:27:45 +000042
Antoine Pitroue11fecb2012-11-11 19:36:51 +010043class Object:
44 def __init__(self, arg):
45 self.arg = arg
46 def __repr__(self):
47 return "<Object %r>" % self.arg
48 def __eq__(self, other):
49 if isinstance(other, Object):
50 return self.arg == other.arg
51 return NotImplemented
52 def __lt__(self, other):
53 if isinstance(other, Object):
54 return self.arg < other.arg
55 return NotImplemented
56 def __hash__(self):
57 return hash(self.arg)
Antoine Pitrouc3afba12012-11-17 18:57:38 +010058 def some_method(self):
59 return 4
60 def other_method(self):
61 return 5
62
Antoine Pitroue11fecb2012-11-11 19:36:51 +010063
64class RefCycle:
65 def __init__(self):
66 self.cycle = self
67
68
Fred Drakeb0fefc52001-03-23 04:22:45 +000069class TestBase(unittest.TestCase):
70
71 def setUp(self):
72 self.cbcalled = 0
73
74 def callback(self, ref):
75 self.cbcalled += 1
Fred Drake41deb1e2001-02-01 05:27:45 +000076
77
Antoine Pitrouc1ee4882016-12-19 10:56:40 +010078@contextlib.contextmanager
79def collect_in_thread(period=0.0001):
80 """
81 Ensure GC collections happen in a different thread, at a high frequency.
82 """
Antoine Pitrouc1ee4882016-12-19 10:56:40 +010083 please_stop = False
84
85 def collect():
86 while not please_stop:
87 time.sleep(period)
88 gc.collect()
89
90 with support.disable_gc():
91 t = threading.Thread(target=collect)
92 t.start()
93 try:
94 yield
95 finally:
96 please_stop = True
97 t.join()
98
99
Fred Drakeb0fefc52001-03-23 04:22:45 +0000100class ReferencesTestCase(TestBase):
Fred Drake41deb1e2001-02-01 05:27:45 +0000101
Fred Drakeb0fefc52001-03-23 04:22:45 +0000102 def test_basic_ref(self):
103 self.check_basic_ref(C)
104 self.check_basic_ref(create_function)
105 self.check_basic_ref(create_bound_method)
Fred Drake41deb1e2001-02-01 05:27:45 +0000106
Fred Drake43735da2002-04-11 03:59:42 +0000107 # Just make sure the tp_repr handler doesn't raise an exception.
108 # Live reference:
109 o = C()
110 wr = weakref.ref(o)
Brett Cannon0b70cca2006-08-25 02:59:59 +0000111 repr(wr)
Fred Drake43735da2002-04-11 03:59:42 +0000112 # Dead reference:
113 del o
Brett Cannon0b70cca2006-08-25 02:59:59 +0000114 repr(wr)
Fred Drake43735da2002-04-11 03:59:42 +0000115
Fred Drakeb0fefc52001-03-23 04:22:45 +0000116 def test_basic_callback(self):
117 self.check_basic_callback(C)
118 self.check_basic_callback(create_function)
119 self.check_basic_callback(create_bound_method)
Fred Drake41deb1e2001-02-01 05:27:45 +0000120
Antoine Pitroub349e4c2014-08-06 19:31:40 -0400121 @support.cpython_only
122 def test_cfunction(self):
123 import _testcapi
124 create_cfunction = _testcapi.create_cfunction
125 f = create_cfunction()
126 wr = weakref.ref(f)
127 self.assertIs(wr(), f)
128 del f
129 self.assertIsNone(wr())
130 self.check_basic_ref(create_cfunction)
131 self.check_basic_callback(create_cfunction)
132
Fred Drakeb0fefc52001-03-23 04:22:45 +0000133 def test_multiple_callbacks(self):
134 o = C()
135 ref1 = weakref.ref(o, self.callback)
136 ref2 = weakref.ref(o, self.callback)
137 del o
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200138 self.assertIsNone(ref1(), "expected reference to be invalidated")
139 self.assertIsNone(ref2(), "expected reference to be invalidated")
140 self.assertEqual(self.cbcalled, 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000141 "callback not called the right number of times")
Fred Drake41deb1e2001-02-01 05:27:45 +0000142
Fred Drake705088e2001-04-13 17:18:15 +0000143 def test_multiple_selfref_callbacks(self):
Guido van Rossum9eee5542002-08-22 20:21:30 +0000144 # Make sure all references are invalidated before callbacks are called
Fred Drake705088e2001-04-13 17:18:15 +0000145 #
146 # What's important here is that we're using the first
147 # reference in the callback invoked on the second reference
148 # (the most recently created ref is cleaned up first). This
149 # tests that all references to the object are invalidated
150 # before any of the callbacks are invoked, so that we only
151 # have one invocation of _weakref.c:cleanup_helper() active
152 # for a particular object at a time.
153 #
154 def callback(object, self=self):
155 self.ref()
156 c = C()
157 self.ref = weakref.ref(c, callback)
158 ref1 = weakref.ref(c, callback)
159 del c
160
Serhiy Storchaka21eb4872016-05-07 15:41:09 +0300161 def test_constructor_kwargs(self):
162 c = C()
163 self.assertRaises(TypeError, weakref.ref, c, callback=None)
164
Fred Drakeb0fefc52001-03-23 04:22:45 +0000165 def test_proxy_ref(self):
166 o = C()
167 o.bar = 1
168 ref1 = weakref.proxy(o, self.callback)
169 ref2 = weakref.proxy(o, self.callback)
170 del o
Fred Drake41deb1e2001-02-01 05:27:45 +0000171
Fred Drakeb0fefc52001-03-23 04:22:45 +0000172 def check(proxy):
173 proxy.bar
Fred Drake41deb1e2001-02-01 05:27:45 +0000174
Neal Norwitz2633c692007-02-26 22:22:47 +0000175 self.assertRaises(ReferenceError, check, ref1)
176 self.assertRaises(ReferenceError, check, ref2)
177 self.assertRaises(ReferenceError, bool, weakref.proxy(C()))
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000178 self.assertEqual(self.cbcalled, 2)
Fred Drake41deb1e2001-02-01 05:27:45 +0000179
Fred Drakeb0fefc52001-03-23 04:22:45 +0000180 def check_basic_ref(self, factory):
181 o = factory()
182 ref = weakref.ref(o)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200183 self.assertIsNotNone(ref(),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000184 "weak reference to live object should be live")
185 o2 = ref()
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200186 self.assertIs(o, o2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000187 "<ref>() should return original object if live")
Fred Drake41deb1e2001-02-01 05:27:45 +0000188
Fred Drakeb0fefc52001-03-23 04:22:45 +0000189 def check_basic_callback(self, factory):
190 self.cbcalled = 0
191 o = factory()
192 ref = weakref.ref(o, self.callback)
193 del o
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200194 self.assertEqual(self.cbcalled, 1,
Fred Drake705088e2001-04-13 17:18:15 +0000195 "callback did not properly set 'cbcalled'")
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200196 self.assertIsNone(ref(),
Fred Drake705088e2001-04-13 17:18:15 +0000197 "ref2 should be dead after deleting object reference")
Fred Drake41deb1e2001-02-01 05:27:45 +0000198
Fred Drakeb0fefc52001-03-23 04:22:45 +0000199 def test_ref_reuse(self):
200 o = C()
201 ref1 = weakref.ref(o)
202 # create a proxy to make sure that there's an intervening creation
203 # between these two; it should make no difference
204 proxy = weakref.proxy(o)
205 ref2 = weakref.ref(o)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200206 self.assertIs(ref1, ref2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000207 "reference object w/out callback should be re-used")
Fred Drake41deb1e2001-02-01 05:27:45 +0000208
Fred Drakeb0fefc52001-03-23 04:22:45 +0000209 o = C()
210 proxy = weakref.proxy(o)
211 ref1 = weakref.ref(o)
212 ref2 = weakref.ref(o)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200213 self.assertIs(ref1, ref2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000214 "reference object w/out callback should be re-used")
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200215 self.assertEqual(weakref.getweakrefcount(o), 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000216 "wrong weak ref count for object")
217 del proxy
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200218 self.assertEqual(weakref.getweakrefcount(o), 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000219 "wrong weak ref count for object after deleting proxy")
Fred Drake41deb1e2001-02-01 05:27:45 +0000220
Fred Drakeb0fefc52001-03-23 04:22:45 +0000221 def test_proxy_reuse(self):
222 o = C()
223 proxy1 = weakref.proxy(o)
224 ref = weakref.ref(o)
225 proxy2 = weakref.proxy(o)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200226 self.assertIs(proxy1, proxy2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000227 "proxy object w/out callback should have been re-used")
228
229 def test_basic_proxy(self):
230 o = C()
231 self.check_proxy(o, weakref.proxy(o))
232
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000233 L = collections.UserList()
Fred Drake5935ff02001-12-19 16:54:23 +0000234 p = weakref.proxy(L)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000235 self.assertFalse(p, "proxy for empty UserList should be false")
Fred Drake5935ff02001-12-19 16:54:23 +0000236 p.append(12)
237 self.assertEqual(len(L), 1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000238 self.assertTrue(p, "proxy for non-empty UserList should be true")
Fred Drake5935ff02001-12-19 16:54:23 +0000239 p[:] = [2, 3]
240 self.assertEqual(len(L), 2)
241 self.assertEqual(len(p), 2)
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000242 self.assertIn(3, p, "proxy didn't support __contains__() properly")
Fred Drake5935ff02001-12-19 16:54:23 +0000243 p[1] = 5
244 self.assertEqual(L[1], 5)
245 self.assertEqual(p[1], 5)
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000246 L2 = collections.UserList(L)
Fred Drake5935ff02001-12-19 16:54:23 +0000247 p2 = weakref.proxy(L2)
248 self.assertEqual(p, p2)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000249 ## self.assertEqual(repr(L2), repr(p2))
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000250 L3 = collections.UserList(range(10))
Fred Drake43735da2002-04-11 03:59:42 +0000251 p3 = weakref.proxy(L3)
252 self.assertEqual(L3[:], p3[:])
253 self.assertEqual(L3[5:], p3[5:])
254 self.assertEqual(L3[:5], p3[:5])
255 self.assertEqual(L3[2:5], p3[2:5])
Fred Drake5935ff02001-12-19 16:54:23 +0000256
Benjamin Peterson32019772009-11-19 03:08:32 +0000257 def test_proxy_unicode(self):
258 # See bug 5037
259 class C(object):
260 def __str__(self):
261 return "string"
262 def __bytes__(self):
263 return b"bytes"
264 instance = C()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000265 self.assertIn("__bytes__", dir(weakref.proxy(instance)))
Benjamin Peterson32019772009-11-19 03:08:32 +0000266 self.assertEqual(bytes(weakref.proxy(instance)), b"bytes")
267
Georg Brandlb533e262008-05-25 18:19:30 +0000268 def test_proxy_index(self):
269 class C:
270 def __index__(self):
271 return 10
272 o = C()
273 p = weakref.proxy(o)
274 self.assertEqual(operator.index(p), 10)
275
276 def test_proxy_div(self):
277 class C:
278 def __floordiv__(self, other):
279 return 42
280 def __ifloordiv__(self, other):
281 return 21
282 o = C()
283 p = weakref.proxy(o)
284 self.assertEqual(p // 5, 42)
285 p //= 5
286 self.assertEqual(p, 21)
287
Mark Dickinson7abb6c02019-04-26 15:56:15 +0900288 def test_proxy_matmul(self):
289 class C:
290 def __matmul__(self, other):
291 return 1729
292 def __rmatmul__(self, other):
293 return -163
294 def __imatmul__(self, other):
295 return 561
296 o = C()
297 p = weakref.proxy(o)
298 self.assertEqual(p @ 5, 1729)
299 self.assertEqual(5 @ p, -163)
300 p @= 5
301 self.assertEqual(p, 561)
302
Fred Drakeea2adc92004-02-03 19:56:46 +0000303 # The PyWeakref_* C API is documented as allowing either NULL or
304 # None as the value for the callback, where either means "no
305 # callback". The "no callback" ref and proxy objects are supposed
306 # to be shared so long as they exist by all callers so long as
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000307 # they are active. In Python 2.3.3 and earlier, this guarantee
Fred Drakeea2adc92004-02-03 19:56:46 +0000308 # was not honored, and was broken in different ways for
309 # PyWeakref_NewRef() and PyWeakref_NewProxy(). (Two tests.)
310
311 def test_shared_ref_without_callback(self):
312 self.check_shared_without_callback(weakref.ref)
313
314 def test_shared_proxy_without_callback(self):
315 self.check_shared_without_callback(weakref.proxy)
316
317 def check_shared_without_callback(self, makeref):
318 o = Object(1)
319 p1 = makeref(o, None)
320 p2 = makeref(o, None)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200321 self.assertIs(p1, p2, "both callbacks were None in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000322 del p1, p2
323 p1 = makeref(o)
324 p2 = makeref(o, None)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200325 self.assertIs(p1, p2, "callbacks were NULL, None in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000326 del p1, p2
327 p1 = makeref(o)
328 p2 = makeref(o)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200329 self.assertIs(p1, p2, "both callbacks were NULL in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000330 del p1, p2
331 p1 = makeref(o, None)
332 p2 = makeref(o)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200333 self.assertIs(p1, p2, "callbacks were None, NULL in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000334
Fred Drakeb0fefc52001-03-23 04:22:45 +0000335 def test_callable_proxy(self):
336 o = Callable()
337 ref1 = weakref.proxy(o)
338
339 self.check_proxy(o, ref1)
340
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200341 self.assertIs(type(ref1), weakref.CallableProxyType,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000342 "proxy is not of callable type")
343 ref1('twinkies!')
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200344 self.assertEqual(o.bar, 'twinkies!',
Fred Drakeb0fefc52001-03-23 04:22:45 +0000345 "call through proxy not passed through to original")
Fred Drake3bb4d212001-10-18 19:28:29 +0000346 ref1(x='Splat.')
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200347 self.assertEqual(o.bar, 'Splat.',
Fred Drake3bb4d212001-10-18 19:28:29 +0000348 "call through proxy not passed through to original")
Fred Drakeb0fefc52001-03-23 04:22:45 +0000349
350 # expect due to too few args
351 self.assertRaises(TypeError, ref1)
352
353 # expect due to too many args
354 self.assertRaises(TypeError, ref1, 1, 2, 3)
355
356 def check_proxy(self, o, proxy):
357 o.foo = 1
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200358 self.assertEqual(proxy.foo, 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000359 "proxy does not reflect attribute addition")
360 o.foo = 2
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200361 self.assertEqual(proxy.foo, 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000362 "proxy does not reflect attribute modification")
363 del o.foo
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200364 self.assertFalse(hasattr(proxy, 'foo'),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000365 "proxy does not reflect attribute removal")
366
367 proxy.foo = 1
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200368 self.assertEqual(o.foo, 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000369 "object does not reflect attribute addition via proxy")
370 proxy.foo = 2
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200371 self.assertEqual(o.foo, 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000372 "object does not reflect attribute modification via proxy")
373 del proxy.foo
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200374 self.assertFalse(hasattr(o, 'foo'),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000375 "object does not reflect attribute removal via proxy")
376
Raymond Hettingerd693a812003-06-30 04:18:48 +0000377 def test_proxy_deletion(self):
378 # Test clearing of SF bug #762891
379 class Foo:
380 result = None
381 def __delitem__(self, accessor):
382 self.result = accessor
383 g = Foo()
384 f = weakref.proxy(g)
385 del f[0]
386 self.assertEqual(f.result, 0)
387
Raymond Hettingere6c470f2005-03-27 03:04:54 +0000388 def test_proxy_bool(self):
389 # Test clearing of SF bug #1170766
390 class List(list): pass
391 lyst = List()
392 self.assertEqual(bool(weakref.proxy(lyst)), bool(lyst))
393
Pablo Galindo10cd00a2019-10-08 16:30:50 +0100394 def test_proxy_iter(self):
395 # Test fails with a debug build of the interpreter
396 # (see bpo-38395).
397
398 obj = None
399
400 class MyObj:
401 def __iter__(self):
402 nonlocal obj
403 del obj
404 return NotImplemented
405
406 obj = MyObj()
407 p = weakref.proxy(obj)
408 with self.assertRaises(TypeError):
409 # "blech" in p calls MyObj.__iter__ through the proxy,
410 # without keeping a reference to the real object, so it
411 # can be killed in the middle of the call
412 "blech" in p
413
Pablo Galindo96074de2020-05-05 22:58:19 +0100414 def test_proxy_reversed(self):
415 class MyObj:
416 def __len__(self):
417 return 3
418 def __reversed__(self):
419 return iter('cba')
420
421 obj = MyObj()
422 self.assertEqual("".join(reversed(weakref.proxy(obj))), "cba")
423
424 def test_proxy_hash(self):
Pablo Galindo96074de2020-05-05 22:58:19 +0100425 class MyObj:
426 def __hash__(self):
Miss Islington (bot)2df13e12021-06-29 16:19:06 -0700427 return 42
Pablo Galindo96074de2020-05-05 22:58:19 +0100428
429 obj = MyObj()
Miss Islington (bot)2df13e12021-06-29 16:19:06 -0700430 with self.assertRaises(TypeError):
431 hash(weakref.proxy(obj))
432
433 class MyObj:
434 __hash__ = None
435
436 obj = MyObj()
437 with self.assertRaises(TypeError):
438 hash(weakref.proxy(obj))
Pablo Galindo96074de2020-05-05 22:58:19 +0100439
Fred Drakeb0fefc52001-03-23 04:22:45 +0000440 def test_getweakrefcount(self):
441 o = C()
442 ref1 = weakref.ref(o)
443 ref2 = weakref.ref(o, self.callback)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200444 self.assertEqual(weakref.getweakrefcount(o), 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000445 "got wrong number of weak reference objects")
446
447 proxy1 = weakref.proxy(o)
448 proxy2 = weakref.proxy(o, self.callback)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200449 self.assertEqual(weakref.getweakrefcount(o), 4,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000450 "got wrong number of weak reference objects")
451
Fred Drakeea2adc92004-02-03 19:56:46 +0000452 del ref1, ref2, proxy1, proxy2
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200453 self.assertEqual(weakref.getweakrefcount(o), 0,
Fred Drakeea2adc92004-02-03 19:56:46 +0000454 "weak reference objects not unlinked from"
455 " referent when discarded.")
456
Walter Dörwaldb167b042003-12-11 12:34:05 +0000457 # assumes ints do not support weakrefs
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200458 self.assertEqual(weakref.getweakrefcount(1), 0,
Walter Dörwaldb167b042003-12-11 12:34:05 +0000459 "got wrong number of weak reference objects for int")
460
Fred Drakeb0fefc52001-03-23 04:22:45 +0000461 def test_getweakrefs(self):
462 o = C()
463 ref1 = weakref.ref(o, self.callback)
464 ref2 = weakref.ref(o, self.callback)
465 del ref1
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200466 self.assertEqual(weakref.getweakrefs(o), [ref2],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000467 "list of refs does not match")
468
469 o = C()
470 ref1 = weakref.ref(o, self.callback)
471 ref2 = weakref.ref(o, self.callback)
472 del ref2
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200473 self.assertEqual(weakref.getweakrefs(o), [ref1],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000474 "list of refs does not match")
475
Fred Drakeea2adc92004-02-03 19:56:46 +0000476 del ref1
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200477 self.assertEqual(weakref.getweakrefs(o), [],
Fred Drakeea2adc92004-02-03 19:56:46 +0000478 "list of refs not cleared")
479
Walter Dörwaldb167b042003-12-11 12:34:05 +0000480 # assumes ints do not support weakrefs
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200481 self.assertEqual(weakref.getweakrefs(1), [],
Walter Dörwaldb167b042003-12-11 12:34:05 +0000482 "list of refs does not match for int")
483
Fred Drake39c27f12001-10-18 18:06:05 +0000484 def test_newstyle_number_ops(self):
485 class F(float):
486 pass
487 f = F(2.0)
488 p = weakref.proxy(f)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200489 self.assertEqual(p + 1.0, 3.0)
490 self.assertEqual(1.0 + p, 3.0) # this used to SEGV
Fred Drake39c27f12001-10-18 18:06:05 +0000491
Fred Drake2a64f462001-12-10 23:46:02 +0000492 def test_callbacks_protected(self):
Guido van Rossum9eee5542002-08-22 20:21:30 +0000493 # Callbacks protected from already-set exceptions?
Fred Drake2a64f462001-12-10 23:46:02 +0000494 # Regression test for SF bug #478534.
495 class BogusError(Exception):
496 pass
497 data = {}
498 def remove(k):
499 del data[k]
500 def encapsulate():
501 f = lambda : ()
502 data[weakref.ref(f, remove)] = None
503 raise BogusError
504 try:
505 encapsulate()
506 except BogusError:
507 pass
508 else:
509 self.fail("exception not properly restored")
510 try:
511 encapsulate()
512 except BogusError:
513 pass
514 else:
515 self.fail("exception not properly restored")
516
Tim Petersadd09b42003-11-12 20:43:28 +0000517 def test_sf_bug_840829(self):
518 # "weakref callbacks and gc corrupt memory"
519 # subtype_dealloc erroneously exposed a new-style instance
520 # already in the process of getting deallocated to gc,
521 # causing double-deallocation if the instance had a weakref
522 # callback that triggered gc.
523 # If the bug exists, there probably won't be an obvious symptom
524 # in a release build. In a debug build, a segfault will occur
525 # when the second attempt to remove the instance from the "list
526 # of all objects" occurs.
527
528 import gc
529
530 class C(object):
531 pass
532
533 c = C()
534 wr = weakref.ref(c, lambda ignore: gc.collect())
535 del c
536
Tim Petersf7f9e992003-11-13 21:59:32 +0000537 # There endeth the first part. It gets worse.
538 del wr
539
540 c1 = C()
541 c1.i = C()
542 wr = weakref.ref(c1.i, lambda ignore: gc.collect())
543
544 c2 = C()
545 c2.c1 = c1
546 del c1 # still alive because c2 points to it
547
548 # Now when subtype_dealloc gets called on c2, it's not enough just
549 # that c2 is immune from gc while the weakref callbacks associated
550 # with c2 execute (there are none in this 2nd half of the test, btw).
551 # subtype_dealloc goes on to call the base classes' deallocs too,
552 # so any gc triggered by weakref callbacks associated with anything
553 # torn down by a base class dealloc can also trigger double
554 # deallocation of c2.
555 del c2
Fred Drake41deb1e2001-02-01 05:27:45 +0000556
Tim Peters403a2032003-11-20 21:21:46 +0000557 def test_callback_in_cycle_1(self):
558 import gc
559
560 class J(object):
561 pass
562
563 class II(object):
564 def acallback(self, ignore):
565 self.J
566
567 I = II()
568 I.J = J
569 I.wr = weakref.ref(J, I.acallback)
570
571 # Now J and II are each in a self-cycle (as all new-style class
572 # objects are, since their __mro__ points back to them). I holds
573 # both a weak reference (I.wr) and a strong reference (I.J) to class
574 # J. I is also in a cycle (I.wr points to a weakref that references
575 # I.acallback). When we del these three, they all become trash, but
576 # the cycles prevent any of them from getting cleaned up immediately.
577 # Instead they have to wait for cyclic gc to deduce that they're
578 # trash.
579 #
580 # gc used to call tp_clear on all of them, and the order in which
581 # it does that is pretty accidental. The exact order in which we
582 # built up these things manages to provoke gc into running tp_clear
583 # in just the right order (I last). Calling tp_clear on II leaves
584 # behind an insane class object (its __mro__ becomes NULL). Calling
585 # tp_clear on J breaks its self-cycle, but J doesn't get deleted
586 # just then because of the strong reference from I.J. Calling
587 # tp_clear on I starts to clear I's __dict__, and just happens to
588 # clear I.J first -- I.wr is still intact. That removes the last
589 # reference to J, which triggers the weakref callback. The callback
590 # tries to do "self.J", and instances of new-style classes look up
591 # attributes ("J") in the class dict first. The class (II) wants to
592 # search II.__mro__, but that's NULL. The result was a segfault in
593 # a release build, and an assert failure in a debug build.
594 del I, J, II
595 gc.collect()
596
597 def test_callback_in_cycle_2(self):
598 import gc
599
600 # This is just like test_callback_in_cycle_1, except that II is an
601 # old-style class. The symptom is different then: an instance of an
602 # old-style class looks in its own __dict__ first. 'J' happens to
603 # get cleared from I.__dict__ before 'wr', and 'J' was never in II's
604 # __dict__, so the attribute isn't found. The difference is that
605 # the old-style II doesn't have a NULL __mro__ (it doesn't have any
606 # __mro__), so no segfault occurs. Instead it got:
607 # test_callback_in_cycle_2 (__main__.ReferencesTestCase) ...
608 # Exception exceptions.AttributeError:
609 # "II instance has no attribute 'J'" in <bound method II.acallback
610 # of <?.II instance at 0x00B9B4B8>> ignored
611
612 class J(object):
613 pass
614
615 class II:
616 def acallback(self, ignore):
617 self.J
618
619 I = II()
620 I.J = J
621 I.wr = weakref.ref(J, I.acallback)
622
623 del I, J, II
624 gc.collect()
625
626 def test_callback_in_cycle_3(self):
627 import gc
628
629 # This one broke the first patch that fixed the last two. In this
630 # case, the objects reachable from the callback aren't also reachable
631 # from the object (c1) *triggering* the callback: you can get to
632 # c1 from c2, but not vice-versa. The result was that c2's __dict__
633 # got tp_clear'ed by the time the c2.cb callback got invoked.
634
635 class C:
636 def cb(self, ignore):
637 self.me
638 self.c1
639 self.wr
640
641 c1, c2 = C(), C()
642
643 c2.me = c2
644 c2.c1 = c1
645 c2.wr = weakref.ref(c1, c2.cb)
646
647 del c1, c2
648 gc.collect()
649
650 def test_callback_in_cycle_4(self):
651 import gc
652
653 # Like test_callback_in_cycle_3, except c2 and c1 have different
654 # classes. c2's class (C) isn't reachable from c1 then, so protecting
655 # objects reachable from the dying object (c1) isn't enough to stop
656 # c2's class (C) from getting tp_clear'ed before c2.cb is invoked.
657 # The result was a segfault (C.__mro__ was NULL when the callback
658 # tried to look up self.me).
659
660 class C(object):
661 def cb(self, ignore):
662 self.me
663 self.c1
664 self.wr
665
666 class D:
667 pass
668
669 c1, c2 = D(), C()
670
671 c2.me = c2
672 c2.c1 = c1
673 c2.wr = weakref.ref(c1, c2.cb)
674
675 del c1, c2, C, D
676 gc.collect()
677
678 def test_callback_in_cycle_resurrection(self):
679 import gc
680
681 # Do something nasty in a weakref callback: resurrect objects
682 # from dead cycles. For this to be attempted, the weakref and
683 # its callback must also be part of the cyclic trash (else the
684 # objects reachable via the callback couldn't be in cyclic trash
685 # to begin with -- the callback would act like an external root).
686 # But gc clears trash weakrefs with callbacks early now, which
687 # disables the callbacks, so the callbacks shouldn't get called
688 # at all (and so nothing actually gets resurrected).
689
690 alist = []
691 class C(object):
692 def __init__(self, value):
693 self.attribute = value
694
695 def acallback(self, ignore):
696 alist.append(self.c)
697
698 c1, c2 = C(1), C(2)
699 c1.c = c2
700 c2.c = c1
701 c1.wr = weakref.ref(c2, c1.acallback)
702 c2.wr = weakref.ref(c1, c2.acallback)
703
704 def C_went_away(ignore):
705 alist.append("C went away")
706 wr = weakref.ref(C, C_went_away)
707
708 del c1, c2, C # make them all trash
709 self.assertEqual(alist, []) # del isn't enough to reclaim anything
710
711 gc.collect()
712 # c1.wr and c2.wr were part of the cyclic trash, so should have
713 # been cleared without their callbacks executing. OTOH, the weakref
714 # to C is bound to a function local (wr), and wasn't trash, so that
715 # callback should have been invoked when C went away.
716 self.assertEqual(alist, ["C went away"])
717 # The remaining weakref should be dead now (its callback ran).
718 self.assertEqual(wr(), None)
719
720 del alist[:]
721 gc.collect()
722 self.assertEqual(alist, [])
723
724 def test_callbacks_on_callback(self):
725 import gc
726
727 # Set up weakref callbacks *on* weakref callbacks.
728 alist = []
729 def safe_callback(ignore):
730 alist.append("safe_callback called")
731
732 class C(object):
733 def cb(self, ignore):
734 alist.append("cb called")
735
736 c, d = C(), C()
737 c.other = d
738 d.other = c
739 callback = c.cb
740 c.wr = weakref.ref(d, callback) # this won't trigger
741 d.wr = weakref.ref(callback, d.cb) # ditto
742 external_wr = weakref.ref(callback, safe_callback) # but this will
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200743 self.assertIs(external_wr(), callback)
Tim Peters403a2032003-11-20 21:21:46 +0000744
745 # The weakrefs attached to c and d should get cleared, so that
746 # C.cb is never called. But external_wr isn't part of the cyclic
747 # trash, and no cyclic trash is reachable from it, so safe_callback
748 # should get invoked when the bound method object callback (c.cb)
749 # -- which is itself a callback, and also part of the cyclic trash --
750 # gets reclaimed at the end of gc.
751
752 del callback, c, d, C
753 self.assertEqual(alist, []) # del isn't enough to clean up cycles
754 gc.collect()
755 self.assertEqual(alist, ["safe_callback called"])
756 self.assertEqual(external_wr(), None)
757
758 del alist[:]
759 gc.collect()
760 self.assertEqual(alist, [])
761
Fred Drakebc875f52004-02-04 23:14:14 +0000762 def test_gc_during_ref_creation(self):
763 self.check_gc_during_creation(weakref.ref)
764
765 def test_gc_during_proxy_creation(self):
766 self.check_gc_during_creation(weakref.proxy)
767
768 def check_gc_during_creation(self, makeref):
769 thresholds = gc.get_threshold()
770 gc.set_threshold(1, 1, 1)
771 gc.collect()
Fred Drake55cf4342004-02-13 19:21:57 +0000772 class A:
773 pass
Fred Drakebc875f52004-02-04 23:14:14 +0000774
775 def callback(*args):
776 pass
777
Fred Drake55cf4342004-02-13 19:21:57 +0000778 referenced = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000779
Fred Drake55cf4342004-02-13 19:21:57 +0000780 a = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000781 a.a = a
782 a.wr = makeref(referenced)
783
784 try:
785 # now make sure the object and the ref get labeled as
786 # cyclic trash:
Fred Drake55cf4342004-02-13 19:21:57 +0000787 a = A()
788 weakref.ref(referenced, callback)
Fred Drakebc875f52004-02-04 23:14:14 +0000789
790 finally:
791 gc.set_threshold(*thresholds)
792
Thomas Woutersb2137042007-02-01 18:02:27 +0000793 def test_ref_created_during_del(self):
794 # Bug #1377858
795 # A weakref created in an object's __del__() would crash the
796 # interpreter when the weakref was cleaned up since it would refer to
797 # non-existent memory. This test should not segfault the interpreter.
798 class Target(object):
799 def __del__(self):
800 global ref_from_del
801 ref_from_del = weakref.ref(self)
802
803 w = Target()
804
Benjamin Peterson9aa42992008-09-10 21:57:34 +0000805 def test_init(self):
806 # Issue 3634
807 # <weakref to class>.__init__() doesn't check errors correctly
808 r = weakref.ref(Exception)
809 self.assertRaises(TypeError, r.__init__, 0, 0, 0, 0, 0)
810 # No exception should be raised here
811 gc.collect()
812
Antoine Pitrou3af01a12010-03-31 21:40:47 +0000813 def test_classes(self):
814 # Check that classes are weakrefable.
815 class A(object):
816 pass
817 l = []
818 weakref.ref(int)
819 a = weakref.ref(A, l.append)
820 A = None
821 gc.collect()
822 self.assertEqual(a(), None)
823 self.assertEqual(l, [a])
824
Antoine Pitroue11fecb2012-11-11 19:36:51 +0100825 def test_equality(self):
826 # Alive weakrefs defer equality testing to their underlying object.
827 x = Object(1)
828 y = Object(1)
829 z = Object(2)
830 a = weakref.ref(x)
831 b = weakref.ref(y)
832 c = weakref.ref(z)
833 d = weakref.ref(x)
834 # Note how we directly test the operators here, to stress both
835 # __eq__ and __ne__.
836 self.assertTrue(a == b)
837 self.assertFalse(a != b)
838 self.assertFalse(a == c)
839 self.assertTrue(a != c)
840 self.assertTrue(a == d)
841 self.assertFalse(a != d)
Serhiy Storchaka662db122019-08-08 08:42:54 +0300842 self.assertFalse(a == x)
843 self.assertTrue(a != x)
844 self.assertTrue(a == ALWAYS_EQ)
845 self.assertFalse(a != ALWAYS_EQ)
Antoine Pitroue11fecb2012-11-11 19:36:51 +0100846 del x, y, z
847 gc.collect()
848 for r in a, b, c:
849 # Sanity check
850 self.assertIs(r(), None)
851 # Dead weakrefs compare by identity: whether `a` and `d` are the
852 # same weakref object is an implementation detail, since they pointed
853 # to the same original object and didn't have a callback.
854 # (see issue #16453).
855 self.assertFalse(a == b)
856 self.assertTrue(a != b)
857 self.assertFalse(a == c)
858 self.assertTrue(a != c)
859 self.assertEqual(a == d, a is d)
860 self.assertEqual(a != d, a is not d)
861
862 def test_ordering(self):
863 # weakrefs cannot be ordered, even if the underlying objects can.
864 ops = [operator.lt, operator.gt, operator.le, operator.ge]
865 x = Object(1)
866 y = Object(1)
867 a = weakref.ref(x)
868 b = weakref.ref(y)
869 for op in ops:
870 self.assertRaises(TypeError, op, a, b)
871 # Same when dead.
872 del x, y
873 gc.collect()
874 for op in ops:
875 self.assertRaises(TypeError, op, a, b)
876
877 def test_hashing(self):
878 # Alive weakrefs hash the same as the underlying object
879 x = Object(42)
880 y = Object(42)
881 a = weakref.ref(x)
882 b = weakref.ref(y)
883 self.assertEqual(hash(a), hash(42))
884 del x, y
885 gc.collect()
886 # Dead weakrefs:
887 # - retain their hash is they were hashed when alive;
888 # - otherwise, cannot be hashed.
889 self.assertEqual(hash(a), hash(42))
890 self.assertRaises(TypeError, hash, b)
891
Antoine Pitrou62a0d6e2012-12-08 21:15:26 +0100892 def test_trashcan_16602(self):
893 # Issue #16602: when a weakref's target was part of a long
894 # deallocation chain, the trashcan mechanism could delay clearing
895 # of the weakref and make the target object visible from outside
896 # code even though its refcount had dropped to 0. A crash ensued.
897 class C:
898 def __init__(self, parent):
899 if not parent:
900 return
901 wself = weakref.ref(self)
902 def cb(wparent):
903 o = wself()
904 self.wparent = weakref.ref(parent, cb)
905
906 d = weakref.WeakKeyDictionary()
907 root = c = C(None)
908 for n in range(100):
909 d[c] = c = C(c)
910 del root
911 gc.collect()
912
Mark Dickinson556e94b2013-04-13 15:45:44 +0100913 def test_callback_attribute(self):
914 x = Object(1)
915 callback = lambda ref: None
916 ref1 = weakref.ref(x, callback)
917 self.assertIs(ref1.__callback__, callback)
918
919 ref2 = weakref.ref(x)
920 self.assertIsNone(ref2.__callback__)
921
922 def test_callback_attribute_after_deletion(self):
923 x = Object(1)
924 ref = weakref.ref(x, self.callback)
925 self.assertIsNotNone(ref.__callback__)
926 del x
927 support.gc_collect()
928 self.assertIsNone(ref.__callback__)
929
930 def test_set_callback_attribute(self):
931 x = Object(1)
932 callback = lambda ref: None
933 ref1 = weakref.ref(x, callback)
934 with self.assertRaises(AttributeError):
935 ref1.__callback__ = lambda ref: None
936
Benjamin Peterson8f657c32016-10-04 00:00:02 -0700937 def test_callback_gcs(self):
938 class ObjectWithDel(Object):
939 def __del__(self): pass
940 x = ObjectWithDel(1)
941 ref1 = weakref.ref(x, lambda ref: support.gc_collect())
942 del x
943 support.gc_collect()
944
Fred Drake0a4dd392004-07-02 18:57:45 +0000945
Amaury Forgeot d'Arcc856c7a2008-06-16 19:50:09 +0000946class SubclassableWeakrefTestCase(TestBase):
Fred Drake0a4dd392004-07-02 18:57:45 +0000947
948 def test_subclass_refs(self):
949 class MyRef(weakref.ref):
950 def __init__(self, ob, callback=None, value=42):
951 self.value = value
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000952 super().__init__(ob, callback)
Fred Drake0a4dd392004-07-02 18:57:45 +0000953 def __call__(self):
954 self.called = True
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000955 return super().__call__()
Fred Drake0a4dd392004-07-02 18:57:45 +0000956 o = Object("foo")
957 mr = MyRef(o, value=24)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200958 self.assertIs(mr(), o)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000959 self.assertTrue(mr.called)
Fred Drake0a4dd392004-07-02 18:57:45 +0000960 self.assertEqual(mr.value, 24)
961 del o
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200962 self.assertIsNone(mr())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000963 self.assertTrue(mr.called)
Fred Drake0a4dd392004-07-02 18:57:45 +0000964
965 def test_subclass_refs_dont_replace_standard_refs(self):
966 class MyRef(weakref.ref):
967 pass
968 o = Object(42)
969 r1 = MyRef(o)
970 r2 = weakref.ref(o)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200971 self.assertIsNot(r1, r2)
Fred Drake0a4dd392004-07-02 18:57:45 +0000972 self.assertEqual(weakref.getweakrefs(o), [r2, r1])
973 self.assertEqual(weakref.getweakrefcount(o), 2)
974 r3 = MyRef(o)
975 self.assertEqual(weakref.getweakrefcount(o), 3)
976 refs = weakref.getweakrefs(o)
977 self.assertEqual(len(refs), 3)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200978 self.assertIs(r2, refs[0])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000979 self.assertIn(r1, refs[1:])
980 self.assertIn(r3, refs[1:])
Fred Drake0a4dd392004-07-02 18:57:45 +0000981
982 def test_subclass_refs_dont_conflate_callbacks(self):
983 class MyRef(weakref.ref):
984 pass
985 o = Object(42)
986 r1 = MyRef(o, id)
987 r2 = MyRef(o, str)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200988 self.assertIsNot(r1, r2)
Fred Drake0a4dd392004-07-02 18:57:45 +0000989 refs = weakref.getweakrefs(o)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000990 self.assertIn(r1, refs)
991 self.assertIn(r2, refs)
Fred Drake0a4dd392004-07-02 18:57:45 +0000992
993 def test_subclass_refs_with_slots(self):
994 class MyRef(weakref.ref):
995 __slots__ = "slot1", "slot2"
996 def __new__(type, ob, callback, slot1, slot2):
997 return weakref.ref.__new__(type, ob, callback)
998 def __init__(self, ob, callback, slot1, slot2):
999 self.slot1 = slot1
1000 self.slot2 = slot2
1001 def meth(self):
1002 return self.slot1 + self.slot2
1003 o = Object(42)
1004 r = MyRef(o, None, "abc", "def")
1005 self.assertEqual(r.slot1, "abc")
1006 self.assertEqual(r.slot2, "def")
1007 self.assertEqual(r.meth(), "abcdef")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001008 self.assertFalse(hasattr(r, "__dict__"))
Fred Drake0a4dd392004-07-02 18:57:45 +00001009
Amaury Forgeot d'Arcc856c7a2008-06-16 19:50:09 +00001010 def test_subclass_refs_with_cycle(self):
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)cd14d5d2016-09-07 00:22:22 +00001011 """Confirm https://bugs.python.org/issue3100 is fixed."""
Amaury Forgeot d'Arcc856c7a2008-06-16 19:50:09 +00001012 # An instance of a weakref subclass can have attributes.
1013 # If such a weakref holds the only strong reference to the object,
1014 # deleting the weakref will delete the object. In this case,
1015 # the callback must not be called, because the ref object is
1016 # being deleted.
1017 class MyRef(weakref.ref):
1018 pass
1019
1020 # Use a local callback, for "regrtest -R::"
1021 # to detect refcounting problems
1022 def callback(w):
1023 self.cbcalled += 1
1024
1025 o = C()
1026 r1 = MyRef(o, callback)
1027 r1.o = o
1028 del o
1029
1030 del r1 # Used to crash here
1031
1032 self.assertEqual(self.cbcalled, 0)
1033
1034 # Same test, with two weakrefs to the same object
1035 # (since code paths are different)
1036 o = C()
1037 r1 = MyRef(o, callback)
1038 r2 = MyRef(o, callback)
1039 r1.r = r2
1040 r2.o = o
1041 del o
1042 del r2
1043
1044 del r1 # Used to crash here
1045
1046 self.assertEqual(self.cbcalled, 0)
1047
Fred Drake0a4dd392004-07-02 18:57:45 +00001048
Antoine Pitrouc3afba12012-11-17 18:57:38 +01001049class WeakMethodTestCase(unittest.TestCase):
1050
1051 def _subclass(self):
Martin Panter7462b6492015-11-02 03:37:02 +00001052 """Return an Object subclass overriding `some_method`."""
Antoine Pitrouc3afba12012-11-17 18:57:38 +01001053 class C(Object):
1054 def some_method(self):
1055 return 6
1056 return C
1057
1058 def test_alive(self):
1059 o = Object(1)
1060 r = weakref.WeakMethod(o.some_method)
1061 self.assertIsInstance(r, weakref.ReferenceType)
1062 self.assertIsInstance(r(), type(o.some_method))
1063 self.assertIs(r().__self__, o)
1064 self.assertIs(r().__func__, o.some_method.__func__)
1065 self.assertEqual(r()(), 4)
1066
1067 def test_object_dead(self):
1068 o = Object(1)
1069 r = weakref.WeakMethod(o.some_method)
1070 del o
1071 gc.collect()
1072 self.assertIs(r(), None)
1073
1074 def test_method_dead(self):
1075 C = self._subclass()
1076 o = C(1)
1077 r = weakref.WeakMethod(o.some_method)
1078 del C.some_method
1079 gc.collect()
1080 self.assertIs(r(), None)
1081
1082 def test_callback_when_object_dead(self):
1083 # Test callback behaviour when object dies first.
1084 C = self._subclass()
1085 calls = []
1086 def cb(arg):
1087 calls.append(arg)
1088 o = C(1)
1089 r = weakref.WeakMethod(o.some_method, cb)
1090 del o
1091 gc.collect()
1092 self.assertEqual(calls, [r])
1093 # Callback is only called once.
1094 C.some_method = Object.some_method
1095 gc.collect()
1096 self.assertEqual(calls, [r])
1097
1098 def test_callback_when_method_dead(self):
1099 # Test callback behaviour when method dies first.
1100 C = self._subclass()
1101 calls = []
1102 def cb(arg):
1103 calls.append(arg)
1104 o = C(1)
1105 r = weakref.WeakMethod(o.some_method, cb)
1106 del C.some_method
1107 gc.collect()
1108 self.assertEqual(calls, [r])
1109 # Callback is only called once.
1110 del o
1111 gc.collect()
1112 self.assertEqual(calls, [r])
1113
1114 @support.cpython_only
1115 def test_no_cycles(self):
1116 # A WeakMethod doesn't create any reference cycle to itself.
1117 o = Object(1)
1118 def cb(_):
1119 pass
1120 r = weakref.WeakMethod(o.some_method, cb)
1121 wr = weakref.ref(r)
1122 del r
1123 self.assertIs(wr(), None)
1124
1125 def test_equality(self):
1126 def _eq(a, b):
1127 self.assertTrue(a == b)
1128 self.assertFalse(a != b)
1129 def _ne(a, b):
1130 self.assertTrue(a != b)
1131 self.assertFalse(a == b)
1132 x = Object(1)
1133 y = Object(1)
1134 a = weakref.WeakMethod(x.some_method)
1135 b = weakref.WeakMethod(y.some_method)
1136 c = weakref.WeakMethod(x.other_method)
1137 d = weakref.WeakMethod(y.other_method)
1138 # Objects equal, same method
1139 _eq(a, b)
1140 _eq(c, d)
1141 # Objects equal, different method
1142 _ne(a, c)
1143 _ne(a, d)
1144 _ne(b, c)
1145 _ne(b, d)
1146 # Objects unequal, same or different method
1147 z = Object(2)
1148 e = weakref.WeakMethod(z.some_method)
1149 f = weakref.WeakMethod(z.other_method)
1150 _ne(a, e)
1151 _ne(a, f)
1152 _ne(b, e)
1153 _ne(b, f)
Serhiy Storchaka662db122019-08-08 08:42:54 +03001154 # Compare with different types
1155 _ne(a, x.some_method)
1156 _eq(a, ALWAYS_EQ)
Antoine Pitrouc3afba12012-11-17 18:57:38 +01001157 del x, y, z
1158 gc.collect()
1159 # Dead WeakMethods compare by identity
1160 refs = a, b, c, d, e, f
1161 for q in refs:
1162 for r in refs:
1163 self.assertEqual(q == r, q is r)
1164 self.assertEqual(q != r, q is not r)
1165
1166 def test_hashing(self):
1167 # Alive WeakMethods are hashable if the underlying object is
1168 # hashable.
1169 x = Object(1)
1170 y = Object(1)
1171 a = weakref.WeakMethod(x.some_method)
1172 b = weakref.WeakMethod(y.some_method)
1173 c = weakref.WeakMethod(y.other_method)
1174 # Since WeakMethod objects are equal, the hashes should be equal.
1175 self.assertEqual(hash(a), hash(b))
1176 ha = hash(a)
1177 # Dead WeakMethods retain their old hash value
1178 del x, y
1179 gc.collect()
1180 self.assertEqual(hash(a), ha)
1181 self.assertEqual(hash(b), ha)
1182 # If it wasn't hashed when alive, a dead WeakMethod cannot be hashed.
1183 self.assertRaises(TypeError, hash, c)
1184
1185
Fred Drakeb0fefc52001-03-23 04:22:45 +00001186class MappingTestCase(TestBase):
Martin v. Löwis5e163332001-02-27 18:36:56 +00001187
Fred Drakeb0fefc52001-03-23 04:22:45 +00001188 COUNT = 10
1189
Antoine Pitroubbe2f602012-03-01 16:26:35 +01001190 def check_len_cycles(self, dict_type, cons):
1191 N = 20
1192 items = [RefCycle() for i in range(N)]
1193 dct = dict_type(cons(o) for o in items)
1194 # Keep an iterator alive
1195 it = dct.items()
1196 try:
1197 next(it)
1198 except StopIteration:
1199 pass
1200 del items
1201 gc.collect()
1202 n1 = len(dct)
1203 del it
1204 gc.collect()
1205 n2 = len(dct)
1206 # one item may be kept alive inside the iterator
1207 self.assertIn(n1, (0, 1))
1208 self.assertEqual(n2, 0)
1209
1210 def test_weak_keyed_len_cycles(self):
1211 self.check_len_cycles(weakref.WeakKeyDictionary, lambda k: (k, 1))
1212
1213 def test_weak_valued_len_cycles(self):
1214 self.check_len_cycles(weakref.WeakValueDictionary, lambda k: (1, k))
1215
1216 def check_len_race(self, dict_type, cons):
1217 # Extended sanity checks for len() in the face of cyclic collection
1218 self.addCleanup(gc.set_threshold, *gc.get_threshold())
1219 for th in range(1, 100):
1220 N = 20
1221 gc.collect(0)
1222 gc.set_threshold(th, th, th)
1223 items = [RefCycle() for i in range(N)]
1224 dct = dict_type(cons(o) for o in items)
1225 del items
1226 # All items will be collected at next garbage collection pass
1227 it = dct.items()
1228 try:
1229 next(it)
1230 except StopIteration:
1231 pass
1232 n1 = len(dct)
1233 del it
1234 n2 = len(dct)
1235 self.assertGreaterEqual(n1, 0)
1236 self.assertLessEqual(n1, N)
1237 self.assertGreaterEqual(n2, 0)
1238 self.assertLessEqual(n2, n1)
1239
1240 def test_weak_keyed_len_race(self):
1241 self.check_len_race(weakref.WeakKeyDictionary, lambda k: (k, 1))
1242
1243 def test_weak_valued_len_race(self):
1244 self.check_len_race(weakref.WeakValueDictionary, lambda k: (1, k))
1245
Fred Drakeb0fefc52001-03-23 04:22:45 +00001246 def test_weak_values(self):
Fred Drake0e540c32001-05-02 05:44:22 +00001247 #
1248 # This exercises d.copy(), d.items(), d[], del d[], len(d).
1249 #
1250 dict, objects = self.make_weak_valued_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +00001251 for o in objects:
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001252 self.assertEqual(weakref.getweakrefcount(o), 1)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001253 self.assertIs(o, dict[o.arg],
Fred Drakeb0fefc52001-03-23 04:22:45 +00001254 "wrong object returned by weak dict!")
Barry Warsawecaab832008-09-04 01:42:51 +00001255 items1 = list(dict.items())
1256 items2 = list(dict.copy().items())
Fred Drakeb0fefc52001-03-23 04:22:45 +00001257 items1.sort()
1258 items2.sort()
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001259 self.assertEqual(items1, items2,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001260 "cloning of weak-valued dictionary did not work!")
1261 del items1, items2
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001262 self.assertEqual(len(dict), self.COUNT)
Fred Drakeb0fefc52001-03-23 04:22:45 +00001263 del objects[0]
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001264 self.assertEqual(len(dict), self.COUNT - 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001265 "deleting object did not cause dictionary update")
1266 del objects, o
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001267 self.assertEqual(len(dict), 0,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001268 "deleting the values did not clear the dictionary")
Fred Drake4fd06e02001-08-03 04:11:27 +00001269 # regression on SF bug #447152:
1270 dict = weakref.WeakValueDictionary()
1271 self.assertRaises(KeyError, dict.__getitem__, 1)
1272 dict[2] = C()
1273 self.assertRaises(KeyError, dict.__getitem__, 2)
Fred Drakeb0fefc52001-03-23 04:22:45 +00001274
1275 def test_weak_keys(self):
Fred Drake0e540c32001-05-02 05:44:22 +00001276 #
1277 # This exercises d.copy(), d.items(), d[] = v, d[], del d[],
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001278 # len(d), k in d.
Fred Drake0e540c32001-05-02 05:44:22 +00001279 #
1280 dict, objects = self.make_weak_keyed_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +00001281 for o in objects:
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001282 self.assertEqual(weakref.getweakrefcount(o), 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001283 "wrong number of weak references to %r!" % o)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001284 self.assertIs(o.arg, dict[o],
Fred Drakeb0fefc52001-03-23 04:22:45 +00001285 "wrong object returned by weak dict!")
1286 items1 = dict.items()
1287 items2 = dict.copy().items()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001288 self.assertEqual(set(items1), set(items2),
Fred Drakeb0fefc52001-03-23 04:22:45 +00001289 "cloning of weak-keyed dictionary did not work!")
1290 del items1, items2
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001291 self.assertEqual(len(dict), self.COUNT)
Fred Drakeb0fefc52001-03-23 04:22:45 +00001292 del objects[0]
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001293 self.assertEqual(len(dict), (self.COUNT - 1),
Fred Drakeb0fefc52001-03-23 04:22:45 +00001294 "deleting object did not cause dictionary update")
1295 del objects, o
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001296 self.assertEqual(len(dict), 0,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001297 "deleting the keys did not clear the dictionary")
Fred Drake752eda42001-11-06 16:38:34 +00001298 o = Object(42)
1299 dict[o] = "What is the meaning of the universe?"
Benjamin Peterson577473f2010-01-19 00:09:57 +00001300 self.assertIn(o, dict)
1301 self.assertNotIn(34, dict)
Martin v. Löwis5e163332001-02-27 18:36:56 +00001302
Fred Drake0e540c32001-05-02 05:44:22 +00001303 def test_weak_keyed_iters(self):
1304 dict, objects = self.make_weak_keyed_dict()
1305 self.check_iters(dict)
1306
Thomas Wouters477c8d52006-05-27 19:21:47 +00001307 # Test keyrefs()
1308 refs = dict.keyrefs()
1309 self.assertEqual(len(refs), len(objects))
1310 objects2 = list(objects)
1311 for wr in refs:
1312 ob = wr()
Benjamin Peterson577473f2010-01-19 00:09:57 +00001313 self.assertIn(ob, dict)
1314 self.assertIn(ob, dict)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001315 self.assertEqual(ob.arg, dict[ob])
1316 objects2.remove(ob)
1317 self.assertEqual(len(objects2), 0)
1318
1319 # Test iterkeyrefs()
1320 objects2 = list(objects)
Barry Warsawecaab832008-09-04 01:42:51 +00001321 self.assertEqual(len(list(dict.keyrefs())), len(objects))
1322 for wr in dict.keyrefs():
Thomas Wouters477c8d52006-05-27 19:21:47 +00001323 ob = wr()
Benjamin Peterson577473f2010-01-19 00:09:57 +00001324 self.assertIn(ob, dict)
1325 self.assertIn(ob, dict)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001326 self.assertEqual(ob.arg, dict[ob])
1327 objects2.remove(ob)
1328 self.assertEqual(len(objects2), 0)
1329
Fred Drake0e540c32001-05-02 05:44:22 +00001330 def test_weak_valued_iters(self):
1331 dict, objects = self.make_weak_valued_dict()
1332 self.check_iters(dict)
1333
Thomas Wouters477c8d52006-05-27 19:21:47 +00001334 # Test valuerefs()
1335 refs = dict.valuerefs()
1336 self.assertEqual(len(refs), len(objects))
1337 objects2 = list(objects)
1338 for wr in refs:
1339 ob = wr()
1340 self.assertEqual(ob, dict[ob.arg])
1341 self.assertEqual(ob.arg, dict[ob.arg].arg)
1342 objects2.remove(ob)
1343 self.assertEqual(len(objects2), 0)
1344
1345 # Test itervaluerefs()
1346 objects2 = list(objects)
1347 self.assertEqual(len(list(dict.itervaluerefs())), len(objects))
1348 for wr in dict.itervaluerefs():
1349 ob = wr()
1350 self.assertEqual(ob, dict[ob.arg])
1351 self.assertEqual(ob.arg, dict[ob.arg].arg)
1352 objects2.remove(ob)
1353 self.assertEqual(len(objects2), 0)
1354
Fred Drake0e540c32001-05-02 05:44:22 +00001355 def check_iters(self, dict):
1356 # item iterator:
Barry Warsawecaab832008-09-04 01:42:51 +00001357 items = list(dict.items())
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001358 for item in dict.items():
Fred Drake0e540c32001-05-02 05:44:22 +00001359 items.remove(item)
Barry Warsawecaab832008-09-04 01:42:51 +00001360 self.assertFalse(items, "items() did not touch all items")
Fred Drake0e540c32001-05-02 05:44:22 +00001361
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001362 # key iterator, via __iter__():
Guido van Rossum07f24362007-02-11 22:59:48 +00001363 keys = list(dict.keys())
Fred Drake0e540c32001-05-02 05:44:22 +00001364 for k in dict:
1365 keys.remove(k)
Barry Warsawecaab832008-09-04 01:42:51 +00001366 self.assertFalse(keys, "__iter__() did not touch all keys")
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001367
1368 # key iterator, via iterkeys():
Guido van Rossum07f24362007-02-11 22:59:48 +00001369 keys = list(dict.keys())
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001370 for k in dict.keys():
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001371 keys.remove(k)
Barry Warsawecaab832008-09-04 01:42:51 +00001372 self.assertFalse(keys, "iterkeys() did not touch all keys")
Fred Drake0e540c32001-05-02 05:44:22 +00001373
1374 # value iterator:
Guido van Rossum07f24362007-02-11 22:59:48 +00001375 values = list(dict.values())
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001376 for v in dict.values():
Fred Drake0e540c32001-05-02 05:44:22 +00001377 values.remove(v)
Barry Warsawecaab832008-09-04 01:42:51 +00001378 self.assertFalse(values,
Fred Drakef425b1e2003-07-14 21:37:17 +00001379 "itervalues() did not touch all values")
Fred Drake0e540c32001-05-02 05:44:22 +00001380
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001381 def check_weak_destroy_while_iterating(self, dict, objects, iter_name):
1382 n = len(dict)
1383 it = iter(getattr(dict, iter_name)())
1384 next(it) # Trigger internal iteration
1385 # Destroy an object
1386 del objects[-1]
1387 gc.collect() # just in case
1388 # We have removed either the first consumed object, or another one
1389 self.assertIn(len(list(it)), [len(objects), len(objects) - 1])
1390 del it
1391 # The removal has been committed
1392 self.assertEqual(len(dict), n - 1)
1393
1394 def check_weak_destroy_and_mutate_while_iterating(self, dict, testcontext):
1395 # Check that we can explicitly mutate the weak dict without
1396 # interfering with delayed removal.
1397 # `testcontext` should create an iterator, destroy one of the
1398 # weakref'ed objects and then return a new key/value pair corresponding
1399 # to the destroyed object.
1400 with testcontext() as (k, v):
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001401 self.assertNotIn(k, dict)
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001402 with testcontext() as (k, v):
1403 self.assertRaises(KeyError, dict.__delitem__, k)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001404 self.assertNotIn(k, dict)
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001405 with testcontext() as (k, v):
1406 self.assertRaises(KeyError, dict.pop, k)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001407 self.assertNotIn(k, dict)
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001408 with testcontext() as (k, v):
1409 dict[k] = v
1410 self.assertEqual(dict[k], v)
1411 ddict = copy.copy(dict)
1412 with testcontext() as (k, v):
1413 dict.update(ddict)
1414 self.assertEqual(dict, ddict)
1415 with testcontext() as (k, v):
1416 dict.clear()
1417 self.assertEqual(len(dict), 0)
1418
Antoine Pitrou1bf974d2014-10-05 20:02:28 +02001419 def check_weak_del_and_len_while_iterating(self, dict, testcontext):
1420 # Check that len() works when both iterating and removing keys
1421 # explicitly through various means (.pop(), .clear()...), while
1422 # implicit mutation is deferred because an iterator is alive.
1423 # (each call to testcontext() should schedule one item for removal
1424 # for this test to work properly)
1425 o = Object(123456)
1426 with testcontext():
1427 n = len(dict)
Victor Stinner742da042016-09-07 17:40:12 -07001428 # Since underlaying dict is ordered, first item is popped
1429 dict.pop(next(dict.keys()))
Antoine Pitrou1bf974d2014-10-05 20:02:28 +02001430 self.assertEqual(len(dict), n - 1)
1431 dict[o] = o
1432 self.assertEqual(len(dict), n)
Victor Stinner742da042016-09-07 17:40:12 -07001433 # last item in objects is removed from dict in context shutdown
Antoine Pitrou1bf974d2014-10-05 20:02:28 +02001434 with testcontext():
1435 self.assertEqual(len(dict), n - 1)
Victor Stinner742da042016-09-07 17:40:12 -07001436 # Then, (o, o) is popped
1437 dict.popitem()
Antoine Pitrou1bf974d2014-10-05 20:02:28 +02001438 self.assertEqual(len(dict), n - 2)
1439 with testcontext():
1440 self.assertEqual(len(dict), n - 3)
1441 del dict[next(dict.keys())]
1442 self.assertEqual(len(dict), n - 4)
1443 with testcontext():
1444 self.assertEqual(len(dict), n - 5)
1445 dict.popitem()
1446 self.assertEqual(len(dict), n - 6)
1447 with testcontext():
1448 dict.clear()
1449 self.assertEqual(len(dict), 0)
1450 self.assertEqual(len(dict), 0)
1451
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001452 def test_weak_keys_destroy_while_iterating(self):
1453 # Issue #7105: iterators shouldn't crash when a key is implicitly removed
1454 dict, objects = self.make_weak_keyed_dict()
1455 self.check_weak_destroy_while_iterating(dict, objects, 'keys')
1456 self.check_weak_destroy_while_iterating(dict, objects, 'items')
1457 self.check_weak_destroy_while_iterating(dict, objects, 'values')
1458 self.check_weak_destroy_while_iterating(dict, objects, 'keyrefs')
1459 dict, objects = self.make_weak_keyed_dict()
1460 @contextlib.contextmanager
1461 def testcontext():
1462 try:
1463 it = iter(dict.items())
1464 next(it)
1465 # Schedule a key/value for removal and recreate it
1466 v = objects.pop().arg
1467 gc.collect() # just in case
1468 yield Object(v), v
1469 finally:
1470 it = None # should commit all removals
Benjamin Peterson18bb7022014-08-24 18:02:15 -05001471 gc.collect()
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001472 self.check_weak_destroy_and_mutate_while_iterating(dict, testcontext)
Antoine Pitrou1bf974d2014-10-05 20:02:28 +02001473 # Issue #21173: len() fragile when keys are both implicitly and
1474 # explicitly removed.
1475 dict, objects = self.make_weak_keyed_dict()
1476 self.check_weak_del_and_len_while_iterating(dict, testcontext)
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001477
1478 def test_weak_values_destroy_while_iterating(self):
1479 # Issue #7105: iterators shouldn't crash when a key is implicitly removed
1480 dict, objects = self.make_weak_valued_dict()
1481 self.check_weak_destroy_while_iterating(dict, objects, 'keys')
1482 self.check_weak_destroy_while_iterating(dict, objects, 'items')
1483 self.check_weak_destroy_while_iterating(dict, objects, 'values')
1484 self.check_weak_destroy_while_iterating(dict, objects, 'itervaluerefs')
1485 self.check_weak_destroy_while_iterating(dict, objects, 'valuerefs')
1486 dict, objects = self.make_weak_valued_dict()
1487 @contextlib.contextmanager
1488 def testcontext():
1489 try:
1490 it = iter(dict.items())
1491 next(it)
1492 # Schedule a key/value for removal and recreate it
1493 k = objects.pop().arg
1494 gc.collect() # just in case
1495 yield k, Object(k)
1496 finally:
1497 it = None # should commit all removals
Benjamin Peterson18bb7022014-08-24 18:02:15 -05001498 gc.collect()
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001499 self.check_weak_destroy_and_mutate_while_iterating(dict, testcontext)
Antoine Pitrou1bf974d2014-10-05 20:02:28 +02001500 dict, objects = self.make_weak_valued_dict()
1501 self.check_weak_del_and_len_while_iterating(dict, testcontext)
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001502
Guido van Rossum009afb72002-06-10 20:00:52 +00001503 def test_make_weak_keyed_dict_from_dict(self):
1504 o = Object(3)
1505 dict = weakref.WeakKeyDictionary({o:364})
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001506 self.assertEqual(dict[o], 364)
Guido van Rossum009afb72002-06-10 20:00:52 +00001507
1508 def test_make_weak_keyed_dict_from_weak_keyed_dict(self):
1509 o = Object(3)
1510 dict = weakref.WeakKeyDictionary({o:364})
1511 dict2 = weakref.WeakKeyDictionary(dict)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001512 self.assertEqual(dict[o], 364)
Guido van Rossum009afb72002-06-10 20:00:52 +00001513
Fred Drake0e540c32001-05-02 05:44:22 +00001514 def make_weak_keyed_dict(self):
1515 dict = weakref.WeakKeyDictionary()
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001516 objects = list(map(Object, range(self.COUNT)))
Fred Drake0e540c32001-05-02 05:44:22 +00001517 for o in objects:
1518 dict[o] = o.arg
1519 return dict, objects
1520
Antoine Pitrouc06de472009-05-30 21:04:26 +00001521 def test_make_weak_valued_dict_from_dict(self):
1522 o = Object(3)
1523 dict = weakref.WeakValueDictionary({364:o})
1524 self.assertEqual(dict[364], o)
1525
1526 def test_make_weak_valued_dict_from_weak_valued_dict(self):
1527 o = Object(3)
1528 dict = weakref.WeakValueDictionary({364:o})
1529 dict2 = weakref.WeakValueDictionary(dict)
1530 self.assertEqual(dict[364], o)
1531
Serhiy Storchakab5102e32015-09-29 23:52:09 +03001532 def test_make_weak_valued_dict_misc(self):
1533 # errors
1534 self.assertRaises(TypeError, weakref.WeakValueDictionary.__init__)
1535 self.assertRaises(TypeError, weakref.WeakValueDictionary, {}, {})
1536 self.assertRaises(TypeError, weakref.WeakValueDictionary, (), ())
1537 # special keyword arguments
1538 o = Object(3)
1539 for kw in 'self', 'dict', 'other', 'iterable':
1540 d = weakref.WeakValueDictionary(**{kw: o})
1541 self.assertEqual(list(d.keys()), [kw])
1542 self.assertEqual(d[kw], o)
1543
Fred Drake0e540c32001-05-02 05:44:22 +00001544 def make_weak_valued_dict(self):
1545 dict = weakref.WeakValueDictionary()
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001546 objects = list(map(Object, range(self.COUNT)))
Fred Drake0e540c32001-05-02 05:44:22 +00001547 for o in objects:
1548 dict[o.arg] = o
1549 return dict, objects
1550
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001551 def check_popitem(self, klass, key1, value1, key2, value2):
1552 weakdict = klass()
1553 weakdict[key1] = value1
1554 weakdict[key2] = value2
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001555 self.assertEqual(len(weakdict), 2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001556 k, v = weakdict.popitem()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001557 self.assertEqual(len(weakdict), 1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001558 if k is key1:
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001559 self.assertIs(v, value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001560 else:
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001561 self.assertIs(v, value2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001562 k, v = weakdict.popitem()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001563 self.assertEqual(len(weakdict), 0)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001564 if k is key1:
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001565 self.assertIs(v, value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001566 else:
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001567 self.assertIs(v, value2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001568
1569 def test_weak_valued_dict_popitem(self):
1570 self.check_popitem(weakref.WeakValueDictionary,
1571 "key1", C(), "key2", C())
1572
1573 def test_weak_keyed_dict_popitem(self):
1574 self.check_popitem(weakref.WeakKeyDictionary,
1575 C(), "value 1", C(), "value 2")
1576
1577 def check_setdefault(self, klass, key, value1, value2):
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001578 self.assertIsNot(value1, value2,
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001579 "invalid test"
1580 " -- value parameters must be distinct objects")
1581 weakdict = klass()
1582 o = weakdict.setdefault(key, value1)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001583 self.assertIs(o, value1)
Benjamin Peterson577473f2010-01-19 00:09:57 +00001584 self.assertIn(key, weakdict)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001585 self.assertIs(weakdict.get(key), value1)
1586 self.assertIs(weakdict[key], value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001587
1588 o = weakdict.setdefault(key, value2)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001589 self.assertIs(o, value1)
Benjamin Peterson577473f2010-01-19 00:09:57 +00001590 self.assertIn(key, weakdict)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001591 self.assertIs(weakdict.get(key), value1)
1592 self.assertIs(weakdict[key], value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001593
1594 def test_weak_valued_dict_setdefault(self):
1595 self.check_setdefault(weakref.WeakValueDictionary,
1596 "key", C(), C())
1597
1598 def test_weak_keyed_dict_setdefault(self):
1599 self.check_setdefault(weakref.WeakKeyDictionary,
1600 C(), "value 1", "value 2")
1601
Fred Drakea0a4ab12001-04-16 17:37:27 +00001602 def check_update(self, klass, dict):
Fred Drake0e540c32001-05-02 05:44:22 +00001603 #
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001604 # This exercises d.update(), len(d), d.keys(), k in d,
Fred Drake0e540c32001-05-02 05:44:22 +00001605 # d.get(), d[].
1606 #
Fred Drakea0a4ab12001-04-16 17:37:27 +00001607 weakdict = klass()
1608 weakdict.update(dict)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001609 self.assertEqual(len(weakdict), len(dict))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001610 for k in weakdict.keys():
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001611 self.assertIn(k, dict, "mysterious new key appeared in weak dict")
Fred Drakea0a4ab12001-04-16 17:37:27 +00001612 v = dict.get(k)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001613 self.assertIs(v, weakdict[k])
1614 self.assertIs(v, weakdict.get(k))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001615 for k in dict.keys():
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001616 self.assertIn(k, weakdict, "original key disappeared in weak dict")
Fred Drakea0a4ab12001-04-16 17:37:27 +00001617 v = dict[k]
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001618 self.assertIs(v, weakdict[k])
1619 self.assertIs(v, weakdict.get(k))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001620
1621 def test_weak_valued_dict_update(self):
1622 self.check_update(weakref.WeakValueDictionary,
1623 {1: C(), 'a': C(), C(): C()})
Serhiy Storchakab5102e32015-09-29 23:52:09 +03001624 # errors
1625 self.assertRaises(TypeError, weakref.WeakValueDictionary.update)
1626 d = weakref.WeakValueDictionary()
1627 self.assertRaises(TypeError, d.update, {}, {})
1628 self.assertRaises(TypeError, d.update, (), ())
1629 self.assertEqual(list(d.keys()), [])
1630 # special keyword arguments
1631 o = Object(3)
1632 for kw in 'self', 'dict', 'other', 'iterable':
1633 d = weakref.WeakValueDictionary()
1634 d.update(**{kw: o})
1635 self.assertEqual(list(d.keys()), [kw])
1636 self.assertEqual(d[kw], o)
Fred Drakea0a4ab12001-04-16 17:37:27 +00001637
Curtis Bucher8f1ed212020-03-24 18:51:29 -07001638 def test_weak_valued_union_operators(self):
1639 a = C()
1640 b = C()
1641 c = C()
1642 wvd1 = weakref.WeakValueDictionary({1: a})
1643 wvd2 = weakref.WeakValueDictionary({1: b, 2: a})
1644 wvd3 = wvd1.copy()
1645 d1 = {1: c, 3: b}
1646 pairs = [(5, c), (6, b)]
1647
1648 tmp1 = wvd1 | wvd2 # Between two WeakValueDictionaries
1649 self.assertEqual(dict(tmp1), dict(wvd1) | dict(wvd2))
1650 self.assertIs(type(tmp1), weakref.WeakValueDictionary)
1651 wvd1 |= wvd2
1652 self.assertEqual(wvd1, tmp1)
1653
1654 tmp2 = wvd2 | d1 # Between WeakValueDictionary and mapping
1655 self.assertEqual(dict(tmp2), dict(wvd2) | d1)
1656 self.assertIs(type(tmp2), weakref.WeakValueDictionary)
1657 wvd2 |= d1
1658 self.assertEqual(wvd2, tmp2)
1659
1660 tmp3 = wvd3.copy() # Between WeakValueDictionary and iterable key, value
1661 tmp3 |= pairs
1662 self.assertEqual(dict(tmp3), dict(wvd3) | dict(pairs))
1663 self.assertIs(type(tmp3), weakref.WeakValueDictionary)
1664
1665 tmp4 = d1 | wvd3 # Testing .__ror__
1666 self.assertEqual(dict(tmp4), d1 | dict(wvd3))
1667 self.assertIs(type(tmp4), weakref.WeakValueDictionary)
1668
1669 del a
1670 self.assertNotIn(2, tmp1)
1671 self.assertNotIn(2, tmp2)
1672 self.assertNotIn(1, tmp3)
1673 self.assertNotIn(1, tmp4)
1674
Fred Drakea0a4ab12001-04-16 17:37:27 +00001675 def test_weak_keyed_dict_update(self):
1676 self.check_update(weakref.WeakKeyDictionary,
1677 {C(): 1, C(): 2, C(): 3})
1678
Fred Drakeccc75622001-09-06 14:52:39 +00001679 def test_weak_keyed_delitem(self):
1680 d = weakref.WeakKeyDictionary()
1681 o1 = Object('1')
1682 o2 = Object('2')
1683 d[o1] = 'something'
1684 d[o2] = 'something'
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001685 self.assertEqual(len(d), 2)
Fred Drakeccc75622001-09-06 14:52:39 +00001686 del d[o1]
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001687 self.assertEqual(len(d), 1)
Barry Warsawecaab832008-09-04 01:42:51 +00001688 self.assertEqual(list(d.keys()), [o2])
Fred Drakeccc75622001-09-06 14:52:39 +00001689
Curtis Bucher25e580a2020-03-23 13:49:46 -07001690 def test_weak_keyed_union_operators(self):
1691 o1 = C()
1692 o2 = C()
1693 o3 = C()
1694 wkd1 = weakref.WeakKeyDictionary({o1: 1, o2: 2})
1695 wkd2 = weakref.WeakKeyDictionary({o3: 3, o1: 4})
1696 wkd3 = wkd1.copy()
1697 d1 = {o2: '5', o3: '6'}
1698 pairs = [(o2, 7), (o3, 8)]
1699
1700 tmp1 = wkd1 | wkd2 # Between two WeakKeyDictionaries
1701 self.assertEqual(dict(tmp1), dict(wkd1) | dict(wkd2))
1702 self.assertIs(type(tmp1), weakref.WeakKeyDictionary)
1703 wkd1 |= wkd2
1704 self.assertEqual(wkd1, tmp1)
1705
1706 tmp2 = wkd2 | d1 # Between WeakKeyDictionary and mapping
1707 self.assertEqual(dict(tmp2), dict(wkd2) | d1)
1708 self.assertIs(type(tmp2), weakref.WeakKeyDictionary)
1709 wkd2 |= d1
1710 self.assertEqual(wkd2, tmp2)
1711
1712 tmp3 = wkd3.copy() # Between WeakKeyDictionary and iterable key, value
1713 tmp3 |= pairs
1714 self.assertEqual(dict(tmp3), dict(wkd3) | dict(pairs))
1715 self.assertIs(type(tmp3), weakref.WeakKeyDictionary)
1716
1717 tmp4 = d1 | wkd3 # Testing .__ror__
1718 self.assertEqual(dict(tmp4), d1 | dict(wkd3))
1719 self.assertIs(type(tmp4), weakref.WeakKeyDictionary)
1720
1721 del o1
1722 self.assertNotIn(4, tmp1.values())
1723 self.assertNotIn(4, tmp2.values())
1724 self.assertNotIn(1, tmp3.values())
1725 self.assertNotIn(1, tmp4.values())
1726
Fred Drakeccc75622001-09-06 14:52:39 +00001727 def test_weak_valued_delitem(self):
1728 d = weakref.WeakValueDictionary()
1729 o1 = Object('1')
1730 o2 = Object('2')
1731 d['something'] = o1
1732 d['something else'] = o2
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001733 self.assertEqual(len(d), 2)
Fred Drakeccc75622001-09-06 14:52:39 +00001734 del d['something']
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001735 self.assertEqual(len(d), 1)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001736 self.assertEqual(list(d.items()), [('something else', o2)])
Fred Drakeccc75622001-09-06 14:52:39 +00001737
Tim Peters886128f2003-05-25 01:45:11 +00001738 def test_weak_keyed_bad_delitem(self):
1739 d = weakref.WeakKeyDictionary()
1740 o = Object('1')
1741 # An attempt to delete an object that isn't there should raise
Tim Peters50d8b8b2003-05-25 17:44:31 +00001742 # KeyError. It didn't before 2.3.
Tim Peters886128f2003-05-25 01:45:11 +00001743 self.assertRaises(KeyError, d.__delitem__, o)
Tim Peters50d8b8b2003-05-25 17:44:31 +00001744 self.assertRaises(KeyError, d.__getitem__, o)
1745
1746 # If a key isn't of a weakly referencable type, __getitem__ and
1747 # __setitem__ raise TypeError. __delitem__ should too.
1748 self.assertRaises(TypeError, d.__delitem__, 13)
1749 self.assertRaises(TypeError, d.__getitem__, 13)
1750 self.assertRaises(TypeError, d.__setitem__, 13, 13)
Tim Peters886128f2003-05-25 01:45:11 +00001751
1752 def test_weak_keyed_cascading_deletes(self):
1753 # SF bug 742860. For some reason, before 2.3 __delitem__ iterated
1754 # over the keys via self.data.iterkeys(). If things vanished from
1755 # the dict during this (or got added), that caused a RuntimeError.
1756
1757 d = weakref.WeakKeyDictionary()
1758 mutate = False
1759
1760 class C(object):
1761 def __init__(self, i):
1762 self.value = i
1763 def __hash__(self):
1764 return hash(self.value)
1765 def __eq__(self, other):
1766 if mutate:
1767 # Side effect that mutates the dict, by removing the
1768 # last strong reference to a key.
1769 del objs[-1]
1770 return self.value == other.value
1771
1772 objs = [C(i) for i in range(4)]
1773 for o in objs:
1774 d[o] = o.value
1775 del o # now the only strong references to keys are in objs
1776 # Find the order in which iterkeys sees the keys.
Barry Warsawecaab832008-09-04 01:42:51 +00001777 objs = list(d.keys())
Tim Peters886128f2003-05-25 01:45:11 +00001778 # Reverse it, so that the iteration implementation of __delitem__
1779 # has to keep looping to find the first object we delete.
1780 objs.reverse()
Tim Peters50d8b8b2003-05-25 17:44:31 +00001781
Leo Ariasc3d95082018-02-03 18:36:10 -06001782 # Turn on mutation in C.__eq__. The first time through the loop,
Tim Peters886128f2003-05-25 01:45:11 +00001783 # under the iterkeys() business the first comparison will delete
1784 # the last item iterkeys() would see, and that causes a
1785 # RuntimeError: dictionary changed size during iteration
1786 # when the iterkeys() loop goes around to try comparing the next
Tim Peters50d8b8b2003-05-25 17:44:31 +00001787 # key. After this was fixed, it just deletes the last object *our*
Tim Peters886128f2003-05-25 01:45:11 +00001788 # "for o in obj" loop would have gotten to.
1789 mutate = True
1790 count = 0
1791 for o in objs:
1792 count += 1
1793 del d[o]
1794 self.assertEqual(len(d), 0)
1795 self.assertEqual(count, 2)
1796
Serhiy Storchaka0c937b32014-07-22 12:14:52 +03001797 def test_make_weak_valued_dict_repr(self):
1798 dict = weakref.WeakValueDictionary()
1799 self.assertRegex(repr(dict), '<WeakValueDictionary at 0x.*>')
1800
1801 def test_make_weak_keyed_dict_repr(self):
1802 dict = weakref.WeakKeyDictionary()
1803 self.assertRegex(repr(dict), '<WeakKeyDictionary at 0x.*>')
1804
Antoine Pitrouc1ee4882016-12-19 10:56:40 +01001805 def test_threaded_weak_valued_setdefault(self):
1806 d = weakref.WeakValueDictionary()
1807 with collect_in_thread():
1808 for i in range(100000):
1809 x = d.setdefault(10, RefCycle())
1810 self.assertIsNot(x, None) # we never put None in there!
1811 del x
1812
1813 def test_threaded_weak_valued_pop(self):
1814 d = weakref.WeakValueDictionary()
1815 with collect_in_thread():
1816 for i in range(100000):
1817 d[10] = RefCycle()
1818 x = d.pop(10, 10)
1819 self.assertIsNot(x, None) # we never put None in there!
1820
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001821 def test_threaded_weak_valued_consistency(self):
1822 # Issue #28427: old keys should not remove new values from
1823 # WeakValueDictionary when collecting from another thread.
1824 d = weakref.WeakValueDictionary()
1825 with collect_in_thread():
1826 for i in range(200000):
1827 o = RefCycle()
1828 d[10] = o
1829 # o is still alive, so the dict can't be empty
1830 self.assertEqual(len(d), 1)
1831 o = None # lose ref
1832
Fish96d37db2019-02-07 14:51:59 -05001833 def check_threaded_weak_dict_copy(self, type_, deepcopy):
1834 # `type_` should be either WeakKeyDictionary or WeakValueDictionary.
1835 # `deepcopy` should be either True or False.
1836 exc = []
1837
1838 class DummyKey:
1839 def __init__(self, ctr):
1840 self.ctr = ctr
1841
1842 class DummyValue:
1843 def __init__(self, ctr):
1844 self.ctr = ctr
1845
1846 def dict_copy(d, exc):
1847 try:
1848 if deepcopy is True:
1849 _ = copy.deepcopy(d)
1850 else:
1851 _ = d.copy()
1852 except Exception as ex:
1853 exc.append(ex)
1854
1855 def pop_and_collect(lst):
1856 gc_ctr = 0
1857 while lst:
1858 i = random.randint(0, len(lst) - 1)
1859 gc_ctr += 1
1860 lst.pop(i)
1861 if gc_ctr % 10000 == 0:
1862 gc.collect() # just in case
1863
1864 self.assertIn(type_, (weakref.WeakKeyDictionary, weakref.WeakValueDictionary))
1865
1866 d = type_()
1867 keys = []
1868 values = []
1869 # Initialize d with many entries
1870 for i in range(70000):
1871 k, v = DummyKey(i), DummyValue(i)
1872 keys.append(k)
1873 values.append(v)
1874 d[k] = v
1875 del k
1876 del v
1877
1878 t_copy = threading.Thread(target=dict_copy, args=(d, exc,))
1879 if type_ is weakref.WeakKeyDictionary:
1880 t_collect = threading.Thread(target=pop_and_collect, args=(keys,))
1881 else: # weakref.WeakValueDictionary
1882 t_collect = threading.Thread(target=pop_and_collect, args=(values,))
1883
1884 t_copy.start()
1885 t_collect.start()
1886
1887 t_copy.join()
1888 t_collect.join()
1889
1890 # Test exceptions
1891 if exc:
1892 raise exc[0]
1893
1894 def test_threaded_weak_key_dict_copy(self):
1895 # Issue #35615: Weakref keys or values getting GC'ed during dict
1896 # copying should not result in a crash.
1897 self.check_threaded_weak_dict_copy(weakref.WeakKeyDictionary, False)
1898
1899 def test_threaded_weak_key_dict_deepcopy(self):
1900 # Issue #35615: Weakref keys or values getting GC'ed during dict
1901 # copying should not result in a crash.
1902 self.check_threaded_weak_dict_copy(weakref.WeakKeyDictionary, True)
1903
1904 def test_threaded_weak_value_dict_copy(self):
1905 # Issue #35615: Weakref keys or values getting GC'ed during dict
1906 # copying should not result in a crash.
1907 self.check_threaded_weak_dict_copy(weakref.WeakValueDictionary, False)
1908
1909 def test_threaded_weak_value_dict_deepcopy(self):
1910 # Issue #35615: Weakref keys or values getting GC'ed during dict
1911 # copying should not result in a crash.
1912 self.check_threaded_weak_dict_copy(weakref.WeakValueDictionary, True)
1913
Victor Stinnera2af05a2019-09-09 16:55:58 +02001914 @support.cpython_only
1915 def test_remove_closure(self):
1916 d = weakref.WeakValueDictionary()
1917 self.assertIsNone(d._remove.__closure__)
1918
Antoine Pitrouc1ee4882016-12-19 10:56:40 +01001919
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001920from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001921
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001922class WeakValueDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +00001923 """Check that WeakValueDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001924 __ref = {"key1":Object(1), "key2":Object(2), "key3":Object(3)}
Walter Dörwald118f9312004-06-02 18:42:25 +00001925 type2test = weakref.WeakValueDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001926 def _reference(self):
1927 return self.__ref.copy()
1928
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001929class WeakKeyDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +00001930 """Check that WeakKeyDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001931 __ref = {Object("key1"):1, Object("key2"):2, Object("key3"):3}
Walter Dörwald118f9312004-06-02 18:42:25 +00001932 type2test = weakref.WeakKeyDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001933 def _reference(self):
1934 return self.__ref.copy()
Martin v. Löwis5e163332001-02-27 18:36:56 +00001935
Richard Oudkerk7a3dae052013-05-05 23:05:00 +01001936
1937class FinalizeTestCase(unittest.TestCase):
1938
1939 class A:
1940 pass
1941
1942 def _collect_if_necessary(self):
1943 # we create no ref-cycles so in CPython no gc should be needed
1944 if sys.implementation.name != 'cpython':
1945 support.gc_collect()
1946
1947 def test_finalize(self):
1948 def add(x,y,z):
1949 res.append(x + y + z)
1950 return x + y + z
1951
1952 a = self.A()
1953
1954 res = []
1955 f = weakref.finalize(a, add, 67, 43, z=89)
1956 self.assertEqual(f.alive, True)
1957 self.assertEqual(f.peek(), (a, add, (67,43), {'z':89}))
1958 self.assertEqual(f(), 199)
1959 self.assertEqual(f(), None)
1960 self.assertEqual(f(), None)
1961 self.assertEqual(f.peek(), None)
1962 self.assertEqual(f.detach(), None)
1963 self.assertEqual(f.alive, False)
1964 self.assertEqual(res, [199])
1965
1966 res = []
1967 f = weakref.finalize(a, add, 67, 43, 89)
1968 self.assertEqual(f.peek(), (a, add, (67,43,89), {}))
1969 self.assertEqual(f.detach(), (a, add, (67,43,89), {}))
1970 self.assertEqual(f(), None)
1971 self.assertEqual(f(), None)
1972 self.assertEqual(f.peek(), None)
1973 self.assertEqual(f.detach(), None)
1974 self.assertEqual(f.alive, False)
1975 self.assertEqual(res, [])
1976
1977 res = []
1978 f = weakref.finalize(a, add, x=67, y=43, z=89)
1979 del a
1980 self._collect_if_necessary()
1981 self.assertEqual(f(), None)
1982 self.assertEqual(f(), None)
1983 self.assertEqual(f.peek(), None)
1984 self.assertEqual(f.detach(), None)
1985 self.assertEqual(f.alive, False)
1986 self.assertEqual(res, [199])
1987
Serhiy Storchaka42a139e2019-04-01 09:16:35 +03001988 def test_arg_errors(self):
1989 def fin(*args, **kwargs):
1990 res.append((args, kwargs))
1991
1992 a = self.A()
1993
1994 res = []
1995 f = weakref.finalize(a, fin, 1, 2, func=3, obj=4)
1996 self.assertEqual(f.peek(), (a, fin, (1, 2), {'func': 3, 'obj': 4}))
1997 f()
1998 self.assertEqual(res, [((1, 2), {'func': 3, 'obj': 4})])
1999
Serhiy Storchaka142566c2019-06-05 18:22:31 +03002000 with self.assertRaises(TypeError):
2001 weakref.finalize(a, func=fin, arg=1)
2002 with self.assertRaises(TypeError):
2003 weakref.finalize(obj=a, func=fin, arg=1)
Serhiy Storchaka42a139e2019-04-01 09:16:35 +03002004 self.assertRaises(TypeError, weakref.finalize, a)
2005 self.assertRaises(TypeError, weakref.finalize)
2006
Richard Oudkerk7a3dae052013-05-05 23:05:00 +01002007 def test_order(self):
2008 a = self.A()
2009 res = []
2010
2011 f1 = weakref.finalize(a, res.append, 'f1')
2012 f2 = weakref.finalize(a, res.append, 'f2')
2013 f3 = weakref.finalize(a, res.append, 'f3')
2014 f4 = weakref.finalize(a, res.append, 'f4')
2015 f5 = weakref.finalize(a, res.append, 'f5')
2016
2017 # make sure finalizers can keep themselves alive
2018 del f1, f4
2019
2020 self.assertTrue(f2.alive)
2021 self.assertTrue(f3.alive)
2022 self.assertTrue(f5.alive)
2023
2024 self.assertTrue(f5.detach())
2025 self.assertFalse(f5.alive)
2026
2027 f5() # nothing because previously unregistered
2028 res.append('A')
2029 f3() # => res.append('f3')
2030 self.assertFalse(f3.alive)
2031 res.append('B')
2032 f3() # nothing because previously called
2033 res.append('C')
2034 del a
2035 self._collect_if_necessary()
2036 # => res.append('f4')
2037 # => res.append('f2')
2038 # => res.append('f1')
2039 self.assertFalse(f2.alive)
2040 res.append('D')
2041 f2() # nothing because previously called by gc
2042
2043 expected = ['A', 'f3', 'B', 'C', 'f4', 'f2', 'f1', 'D']
2044 self.assertEqual(res, expected)
2045
2046 def test_all_freed(self):
2047 # we want a weakrefable subclass of weakref.finalize
2048 class MyFinalizer(weakref.finalize):
2049 pass
2050
2051 a = self.A()
2052 res = []
2053 def callback():
2054 res.append(123)
2055 f = MyFinalizer(a, callback)
2056
2057 wr_callback = weakref.ref(callback)
2058 wr_f = weakref.ref(f)
2059 del callback, f
2060
2061 self.assertIsNotNone(wr_callback())
2062 self.assertIsNotNone(wr_f())
2063
2064 del a
2065 self._collect_if_necessary()
2066
2067 self.assertIsNone(wr_callback())
2068 self.assertIsNone(wr_f())
2069 self.assertEqual(res, [123])
2070
2071 @classmethod
2072 def run_in_child(cls):
2073 def error():
2074 # Create an atexit finalizer from inside a finalizer called
2075 # at exit. This should be the next to be run.
2076 g1 = weakref.finalize(cls, print, 'g1')
2077 print('f3 error')
2078 1/0
2079
2080 # cls should stay alive till atexit callbacks run
2081 f1 = weakref.finalize(cls, print, 'f1', _global_var)
2082 f2 = weakref.finalize(cls, print, 'f2', _global_var)
2083 f3 = weakref.finalize(cls, error)
2084 f4 = weakref.finalize(cls, print, 'f4', _global_var)
2085
2086 assert f1.atexit == True
2087 f2.atexit = False
2088 assert f3.atexit == True
2089 assert f4.atexit == True
2090
2091 def test_atexit(self):
2092 prog = ('from test.test_weakref import FinalizeTestCase;'+
2093 'FinalizeTestCase.run_in_child()')
2094 rc, out, err = script_helper.assert_python_ok('-c', prog)
2095 out = out.decode('ascii').splitlines()
2096 self.assertEqual(out, ['f4 foobar', 'f3 error', 'g1', 'f1 foobar'])
2097 self.assertTrue(b'ZeroDivisionError' in err)
2098
2099
Georg Brandlb533e262008-05-25 18:19:30 +00002100libreftest = """ Doctest for examples in the library reference: weakref.rst
Georg Brandl9a65d582005-07-02 19:07:30 +00002101
2102>>> import weakref
2103>>> class Dict(dict):
2104... pass
2105...
2106>>> obj = Dict(red=1, green=2, blue=3) # this object is weak referencable
2107>>> r = weakref.ref(obj)
Guido van Rossum7131f842007-02-09 20:13:25 +00002108>>> print(r() is obj)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002109True
Georg Brandl9a65d582005-07-02 19:07:30 +00002110
2111>>> import weakref
2112>>> class Object:
2113... pass
2114...
2115>>> o = Object()
2116>>> r = weakref.ref(o)
2117>>> o2 = r()
2118>>> o is o2
2119True
2120>>> del o, o2
Guido van Rossum7131f842007-02-09 20:13:25 +00002121>>> print(r())
Georg Brandl9a65d582005-07-02 19:07:30 +00002122None
2123
2124>>> import weakref
2125>>> class ExtendedRef(weakref.ref):
2126... def __init__(self, ob, callback=None, **annotations):
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002127... super().__init__(ob, callback)
Georg Brandl9a65d582005-07-02 19:07:30 +00002128... self.__counter = 0
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002129... for k, v in annotations.items():
Georg Brandl9a65d582005-07-02 19:07:30 +00002130... setattr(self, k, v)
2131... def __call__(self):
2132... '''Return a pair containing the referent and the number of
2133... times the reference has been called.
2134... '''
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002135... ob = super().__call__()
Georg Brandl9a65d582005-07-02 19:07:30 +00002136... if ob is not None:
2137... self.__counter += 1
2138... ob = (ob, self.__counter)
2139... return ob
Guido van Rossumd8faa362007-04-27 19:54:29 +00002140...
Georg Brandl9a65d582005-07-02 19:07:30 +00002141>>> class A: # not in docs from here, just testing the ExtendedRef
2142... pass
2143...
2144>>> a = A()
2145>>> r = ExtendedRef(a, foo=1, bar="baz")
2146>>> r.foo
21471
2148>>> r.bar
2149'baz'
2150>>> r()[1]
21511
2152>>> r()[1]
21532
2154>>> r()[0] is a
2155True
2156
2157
2158>>> import weakref
2159>>> _id2obj_dict = weakref.WeakValueDictionary()
2160>>> def remember(obj):
2161... oid = id(obj)
2162... _id2obj_dict[oid] = obj
2163... return oid
2164...
2165>>> def id2obj(oid):
2166... return _id2obj_dict[oid]
2167...
2168>>> a = A() # from here, just testing
2169>>> a_id = remember(a)
2170>>> id2obj(a_id) is a
2171True
2172>>> del a
2173>>> try:
2174... id2obj(a_id)
2175... except KeyError:
Guido van Rossum7131f842007-02-09 20:13:25 +00002176... print('OK')
Georg Brandl9a65d582005-07-02 19:07:30 +00002177... else:
Guido van Rossum7131f842007-02-09 20:13:25 +00002178... print('WeakValueDictionary error')
Georg Brandl9a65d582005-07-02 19:07:30 +00002179OK
2180
2181"""
2182
2183__test__ = {'libreftest' : libreftest}
2184
Fred Drake2e2be372001-09-20 21:33:42 +00002185def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002186 support.run_unittest(
Walter Dörwald21d3a322003-05-01 17:45:56 +00002187 ReferencesTestCase,
Antoine Pitrouc3afba12012-11-17 18:57:38 +01002188 WeakMethodTestCase,
Walter Dörwald21d3a322003-05-01 17:45:56 +00002189 MappingTestCase,
2190 WeakValueDictionaryTestCase,
Fred Drakef425b1e2003-07-14 21:37:17 +00002191 WeakKeyDictionaryTestCase,
Amaury Forgeot d'Arcc856c7a2008-06-16 19:50:09 +00002192 SubclassableWeakrefTestCase,
Richard Oudkerk7a3dae052013-05-05 23:05:00 +01002193 FinalizeTestCase,
Fred Drakef425b1e2003-07-14 21:37:17 +00002194 )
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002195 support.run_doctest(sys.modules[__name__])
Fred Drake2e2be372001-09-20 21:33:42 +00002196
2197
2198if __name__ == "__main__":
2199 test_main()