blob: 1a5314ccff315a4d216658fdd80cab1eb0d57392 [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 Oudkerk7a3dae02013-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
Miss Islington (bot)659030c2021-07-24 02:45:13 -0700414 def test_proxy_next(self):
415 arr = [4, 5, 6]
416 def iterator_func():
417 yield from arr
418 it = iterator_func()
419
420 class IteratesWeakly:
421 def __iter__(self):
422 return weakref.proxy(it)
423
424 weak_it = IteratesWeakly()
425
426 # Calls proxy.__next__
427 self.assertEqual(list(weak_it), [4, 5, 6])
428
429 def test_proxy_bad_next(self):
430 # bpo-44720: PyIter_Next() shouldn't be called if the reference
431 # isn't an iterator.
432
433 not_an_iterator = lambda: 0
434
435 class A:
436 def __iter__(self):
437 return weakref.proxy(not_an_iterator)
438 a = A()
439
440 msg = "Weakref proxy referenced a non-iterator"
441 with self.assertRaisesRegex(TypeError, msg):
442 list(a)
443
Pablo Galindo96074de2020-05-05 22:58:19 +0100444 def test_proxy_reversed(self):
445 class MyObj:
446 def __len__(self):
447 return 3
448 def __reversed__(self):
449 return iter('cba')
450
451 obj = MyObj()
452 self.assertEqual("".join(reversed(weakref.proxy(obj))), "cba")
453
454 def test_proxy_hash(self):
Pablo Galindo96074de2020-05-05 22:58:19 +0100455 class MyObj:
456 def __hash__(self):
Miss Islington (bot)2df13e12021-06-29 16:19:06 -0700457 return 42
Pablo Galindo96074de2020-05-05 22:58:19 +0100458
459 obj = MyObj()
Miss Islington (bot)2df13e12021-06-29 16:19:06 -0700460 with self.assertRaises(TypeError):
461 hash(weakref.proxy(obj))
462
463 class MyObj:
464 __hash__ = None
465
466 obj = MyObj()
467 with self.assertRaises(TypeError):
468 hash(weakref.proxy(obj))
Pablo Galindo96074de2020-05-05 22:58:19 +0100469
Fred Drakeb0fefc52001-03-23 04:22:45 +0000470 def test_getweakrefcount(self):
471 o = C()
472 ref1 = weakref.ref(o)
473 ref2 = weakref.ref(o, self.callback)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200474 self.assertEqual(weakref.getweakrefcount(o), 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000475 "got wrong number of weak reference objects")
476
477 proxy1 = weakref.proxy(o)
478 proxy2 = weakref.proxy(o, self.callback)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200479 self.assertEqual(weakref.getweakrefcount(o), 4,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000480 "got wrong number of weak reference objects")
481
Fred Drakeea2adc92004-02-03 19:56:46 +0000482 del ref1, ref2, proxy1, proxy2
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200483 self.assertEqual(weakref.getweakrefcount(o), 0,
Fred Drakeea2adc92004-02-03 19:56:46 +0000484 "weak reference objects not unlinked from"
485 " referent when discarded.")
486
Walter Dörwaldb167b042003-12-11 12:34:05 +0000487 # assumes ints do not support weakrefs
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200488 self.assertEqual(weakref.getweakrefcount(1), 0,
Walter Dörwaldb167b042003-12-11 12:34:05 +0000489 "got wrong number of weak reference objects for int")
490
Fred Drakeb0fefc52001-03-23 04:22:45 +0000491 def test_getweakrefs(self):
492 o = C()
493 ref1 = weakref.ref(o, self.callback)
494 ref2 = weakref.ref(o, self.callback)
495 del ref1
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200496 self.assertEqual(weakref.getweakrefs(o), [ref2],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000497 "list of refs does not match")
498
499 o = C()
500 ref1 = weakref.ref(o, self.callback)
501 ref2 = weakref.ref(o, self.callback)
502 del ref2
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200503 self.assertEqual(weakref.getweakrefs(o), [ref1],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000504 "list of refs does not match")
505
Fred Drakeea2adc92004-02-03 19:56:46 +0000506 del ref1
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200507 self.assertEqual(weakref.getweakrefs(o), [],
Fred Drakeea2adc92004-02-03 19:56:46 +0000508 "list of refs not cleared")
509
Walter Dörwaldb167b042003-12-11 12:34:05 +0000510 # assumes ints do not support weakrefs
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200511 self.assertEqual(weakref.getweakrefs(1), [],
Walter Dörwaldb167b042003-12-11 12:34:05 +0000512 "list of refs does not match for int")
513
Fred Drake39c27f12001-10-18 18:06:05 +0000514 def test_newstyle_number_ops(self):
515 class F(float):
516 pass
517 f = F(2.0)
518 p = weakref.proxy(f)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200519 self.assertEqual(p + 1.0, 3.0)
520 self.assertEqual(1.0 + p, 3.0) # this used to SEGV
Fred Drake39c27f12001-10-18 18:06:05 +0000521
Fred Drake2a64f462001-12-10 23:46:02 +0000522 def test_callbacks_protected(self):
Guido van Rossum9eee5542002-08-22 20:21:30 +0000523 # Callbacks protected from already-set exceptions?
Fred Drake2a64f462001-12-10 23:46:02 +0000524 # Regression test for SF bug #478534.
525 class BogusError(Exception):
526 pass
527 data = {}
528 def remove(k):
529 del data[k]
530 def encapsulate():
531 f = lambda : ()
532 data[weakref.ref(f, remove)] = None
533 raise BogusError
534 try:
535 encapsulate()
536 except BogusError:
537 pass
538 else:
539 self.fail("exception not properly restored")
540 try:
541 encapsulate()
542 except BogusError:
543 pass
544 else:
545 self.fail("exception not properly restored")
546
Tim Petersadd09b42003-11-12 20:43:28 +0000547 def test_sf_bug_840829(self):
548 # "weakref callbacks and gc corrupt memory"
549 # subtype_dealloc erroneously exposed a new-style instance
550 # already in the process of getting deallocated to gc,
551 # causing double-deallocation if the instance had a weakref
552 # callback that triggered gc.
553 # If the bug exists, there probably won't be an obvious symptom
554 # in a release build. In a debug build, a segfault will occur
555 # when the second attempt to remove the instance from the "list
556 # of all objects" occurs.
557
558 import gc
559
560 class C(object):
561 pass
562
563 c = C()
564 wr = weakref.ref(c, lambda ignore: gc.collect())
565 del c
566
Tim Petersf7f9e992003-11-13 21:59:32 +0000567 # There endeth the first part. It gets worse.
568 del wr
569
570 c1 = C()
571 c1.i = C()
572 wr = weakref.ref(c1.i, lambda ignore: gc.collect())
573
574 c2 = C()
575 c2.c1 = c1
576 del c1 # still alive because c2 points to it
577
578 # Now when subtype_dealloc gets called on c2, it's not enough just
579 # that c2 is immune from gc while the weakref callbacks associated
580 # with c2 execute (there are none in this 2nd half of the test, btw).
581 # subtype_dealloc goes on to call the base classes' deallocs too,
582 # so any gc triggered by weakref callbacks associated with anything
583 # torn down by a base class dealloc can also trigger double
584 # deallocation of c2.
585 del c2
Fred Drake41deb1e2001-02-01 05:27:45 +0000586
Tim Peters403a2032003-11-20 21:21:46 +0000587 def test_callback_in_cycle_1(self):
588 import gc
589
590 class J(object):
591 pass
592
593 class II(object):
594 def acallback(self, ignore):
595 self.J
596
597 I = II()
598 I.J = J
599 I.wr = weakref.ref(J, I.acallback)
600
601 # Now J and II are each in a self-cycle (as all new-style class
602 # objects are, since their __mro__ points back to them). I holds
603 # both a weak reference (I.wr) and a strong reference (I.J) to class
604 # J. I is also in a cycle (I.wr points to a weakref that references
605 # I.acallback). When we del these three, they all become trash, but
606 # the cycles prevent any of them from getting cleaned up immediately.
607 # Instead they have to wait for cyclic gc to deduce that they're
608 # trash.
609 #
610 # gc used to call tp_clear on all of them, and the order in which
611 # it does that is pretty accidental. The exact order in which we
612 # built up these things manages to provoke gc into running tp_clear
613 # in just the right order (I last). Calling tp_clear on II leaves
614 # behind an insane class object (its __mro__ becomes NULL). Calling
615 # tp_clear on J breaks its self-cycle, but J doesn't get deleted
616 # just then because of the strong reference from I.J. Calling
617 # tp_clear on I starts to clear I's __dict__, and just happens to
618 # clear I.J first -- I.wr is still intact. That removes the last
619 # reference to J, which triggers the weakref callback. The callback
620 # tries to do "self.J", and instances of new-style classes look up
621 # attributes ("J") in the class dict first. The class (II) wants to
622 # search II.__mro__, but that's NULL. The result was a segfault in
623 # a release build, and an assert failure in a debug build.
624 del I, J, II
625 gc.collect()
626
627 def test_callback_in_cycle_2(self):
628 import gc
629
630 # This is just like test_callback_in_cycle_1, except that II is an
631 # old-style class. The symptom is different then: an instance of an
632 # old-style class looks in its own __dict__ first. 'J' happens to
633 # get cleared from I.__dict__ before 'wr', and 'J' was never in II's
634 # __dict__, so the attribute isn't found. The difference is that
635 # the old-style II doesn't have a NULL __mro__ (it doesn't have any
636 # __mro__), so no segfault occurs. Instead it got:
637 # test_callback_in_cycle_2 (__main__.ReferencesTestCase) ...
638 # Exception exceptions.AttributeError:
639 # "II instance has no attribute 'J'" in <bound method II.acallback
640 # of <?.II instance at 0x00B9B4B8>> ignored
641
642 class J(object):
643 pass
644
645 class II:
646 def acallback(self, ignore):
647 self.J
648
649 I = II()
650 I.J = J
651 I.wr = weakref.ref(J, I.acallback)
652
653 del I, J, II
654 gc.collect()
655
656 def test_callback_in_cycle_3(self):
657 import gc
658
659 # This one broke the first patch that fixed the last two. In this
660 # case, the objects reachable from the callback aren't also reachable
661 # from the object (c1) *triggering* the callback: you can get to
662 # c1 from c2, but not vice-versa. The result was that c2's __dict__
663 # got tp_clear'ed by the time the c2.cb callback got invoked.
664
665 class C:
666 def cb(self, ignore):
667 self.me
668 self.c1
669 self.wr
670
671 c1, c2 = C(), C()
672
673 c2.me = c2
674 c2.c1 = c1
675 c2.wr = weakref.ref(c1, c2.cb)
676
677 del c1, c2
678 gc.collect()
679
680 def test_callback_in_cycle_4(self):
681 import gc
682
683 # Like test_callback_in_cycle_3, except c2 and c1 have different
684 # classes. c2's class (C) isn't reachable from c1 then, so protecting
685 # objects reachable from the dying object (c1) isn't enough to stop
686 # c2's class (C) from getting tp_clear'ed before c2.cb is invoked.
687 # The result was a segfault (C.__mro__ was NULL when the callback
688 # tried to look up self.me).
689
690 class C(object):
691 def cb(self, ignore):
692 self.me
693 self.c1
694 self.wr
695
696 class D:
697 pass
698
699 c1, c2 = D(), C()
700
701 c2.me = c2
702 c2.c1 = c1
703 c2.wr = weakref.ref(c1, c2.cb)
704
705 del c1, c2, C, D
706 gc.collect()
707
708 def test_callback_in_cycle_resurrection(self):
709 import gc
710
711 # Do something nasty in a weakref callback: resurrect objects
712 # from dead cycles. For this to be attempted, the weakref and
713 # its callback must also be part of the cyclic trash (else the
714 # objects reachable via the callback couldn't be in cyclic trash
715 # to begin with -- the callback would act like an external root).
716 # But gc clears trash weakrefs with callbacks early now, which
717 # disables the callbacks, so the callbacks shouldn't get called
718 # at all (and so nothing actually gets resurrected).
719
720 alist = []
721 class C(object):
722 def __init__(self, value):
723 self.attribute = value
724
725 def acallback(self, ignore):
726 alist.append(self.c)
727
728 c1, c2 = C(1), C(2)
729 c1.c = c2
730 c2.c = c1
731 c1.wr = weakref.ref(c2, c1.acallback)
732 c2.wr = weakref.ref(c1, c2.acallback)
733
734 def C_went_away(ignore):
735 alist.append("C went away")
736 wr = weakref.ref(C, C_went_away)
737
738 del c1, c2, C # make them all trash
739 self.assertEqual(alist, []) # del isn't enough to reclaim anything
740
741 gc.collect()
742 # c1.wr and c2.wr were part of the cyclic trash, so should have
743 # been cleared without their callbacks executing. OTOH, the weakref
744 # to C is bound to a function local (wr), and wasn't trash, so that
745 # callback should have been invoked when C went away.
746 self.assertEqual(alist, ["C went away"])
747 # The remaining weakref should be dead now (its callback ran).
748 self.assertEqual(wr(), None)
749
750 del alist[:]
751 gc.collect()
752 self.assertEqual(alist, [])
753
754 def test_callbacks_on_callback(self):
755 import gc
756
757 # Set up weakref callbacks *on* weakref callbacks.
758 alist = []
759 def safe_callback(ignore):
760 alist.append("safe_callback called")
761
762 class C(object):
763 def cb(self, ignore):
764 alist.append("cb called")
765
766 c, d = C(), C()
767 c.other = d
768 d.other = c
769 callback = c.cb
770 c.wr = weakref.ref(d, callback) # this won't trigger
771 d.wr = weakref.ref(callback, d.cb) # ditto
772 external_wr = weakref.ref(callback, safe_callback) # but this will
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200773 self.assertIs(external_wr(), callback)
Tim Peters403a2032003-11-20 21:21:46 +0000774
775 # The weakrefs attached to c and d should get cleared, so that
776 # C.cb is never called. But external_wr isn't part of the cyclic
777 # trash, and no cyclic trash is reachable from it, so safe_callback
778 # should get invoked when the bound method object callback (c.cb)
779 # -- which is itself a callback, and also part of the cyclic trash --
780 # gets reclaimed at the end of gc.
781
782 del callback, c, d, C
783 self.assertEqual(alist, []) # del isn't enough to clean up cycles
784 gc.collect()
785 self.assertEqual(alist, ["safe_callback called"])
786 self.assertEqual(external_wr(), None)
787
788 del alist[:]
789 gc.collect()
790 self.assertEqual(alist, [])
791
Fred Drakebc875f52004-02-04 23:14:14 +0000792 def test_gc_during_ref_creation(self):
793 self.check_gc_during_creation(weakref.ref)
794
795 def test_gc_during_proxy_creation(self):
796 self.check_gc_during_creation(weakref.proxy)
797
798 def check_gc_during_creation(self, makeref):
799 thresholds = gc.get_threshold()
800 gc.set_threshold(1, 1, 1)
801 gc.collect()
Fred Drake55cf4342004-02-13 19:21:57 +0000802 class A:
803 pass
Fred Drakebc875f52004-02-04 23:14:14 +0000804
805 def callback(*args):
806 pass
807
Fred Drake55cf4342004-02-13 19:21:57 +0000808 referenced = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000809
Fred Drake55cf4342004-02-13 19:21:57 +0000810 a = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000811 a.a = a
812 a.wr = makeref(referenced)
813
814 try:
815 # now make sure the object and the ref get labeled as
816 # cyclic trash:
Fred Drake55cf4342004-02-13 19:21:57 +0000817 a = A()
818 weakref.ref(referenced, callback)
Fred Drakebc875f52004-02-04 23:14:14 +0000819
820 finally:
821 gc.set_threshold(*thresholds)
822
Thomas Woutersb2137042007-02-01 18:02:27 +0000823 def test_ref_created_during_del(self):
824 # Bug #1377858
825 # A weakref created in an object's __del__() would crash the
826 # interpreter when the weakref was cleaned up since it would refer to
827 # non-existent memory. This test should not segfault the interpreter.
828 class Target(object):
829 def __del__(self):
830 global ref_from_del
831 ref_from_del = weakref.ref(self)
832
833 w = Target()
834
Benjamin Peterson9aa42992008-09-10 21:57:34 +0000835 def test_init(self):
836 # Issue 3634
837 # <weakref to class>.__init__() doesn't check errors correctly
838 r = weakref.ref(Exception)
839 self.assertRaises(TypeError, r.__init__, 0, 0, 0, 0, 0)
840 # No exception should be raised here
841 gc.collect()
842
Antoine Pitrou3af01a12010-03-31 21:40:47 +0000843 def test_classes(self):
844 # Check that classes are weakrefable.
845 class A(object):
846 pass
847 l = []
848 weakref.ref(int)
849 a = weakref.ref(A, l.append)
850 A = None
851 gc.collect()
852 self.assertEqual(a(), None)
853 self.assertEqual(l, [a])
854
Antoine Pitroue11fecb2012-11-11 19:36:51 +0100855 def test_equality(self):
856 # Alive weakrefs defer equality testing to their underlying object.
857 x = Object(1)
858 y = Object(1)
859 z = Object(2)
860 a = weakref.ref(x)
861 b = weakref.ref(y)
862 c = weakref.ref(z)
863 d = weakref.ref(x)
864 # Note how we directly test the operators here, to stress both
865 # __eq__ and __ne__.
866 self.assertTrue(a == b)
867 self.assertFalse(a != b)
868 self.assertFalse(a == c)
869 self.assertTrue(a != c)
870 self.assertTrue(a == d)
871 self.assertFalse(a != d)
Serhiy Storchaka662db122019-08-08 08:42:54 +0300872 self.assertFalse(a == x)
873 self.assertTrue(a != x)
874 self.assertTrue(a == ALWAYS_EQ)
875 self.assertFalse(a != ALWAYS_EQ)
Antoine Pitroue11fecb2012-11-11 19:36:51 +0100876 del x, y, z
877 gc.collect()
878 for r in a, b, c:
879 # Sanity check
880 self.assertIs(r(), None)
881 # Dead weakrefs compare by identity: whether `a` and `d` are the
882 # same weakref object is an implementation detail, since they pointed
883 # to the same original object and didn't have a callback.
884 # (see issue #16453).
885 self.assertFalse(a == b)
886 self.assertTrue(a != b)
887 self.assertFalse(a == c)
888 self.assertTrue(a != c)
889 self.assertEqual(a == d, a is d)
890 self.assertEqual(a != d, a is not d)
891
892 def test_ordering(self):
893 # weakrefs cannot be ordered, even if the underlying objects can.
894 ops = [operator.lt, operator.gt, operator.le, operator.ge]
895 x = Object(1)
896 y = Object(1)
897 a = weakref.ref(x)
898 b = weakref.ref(y)
899 for op in ops:
900 self.assertRaises(TypeError, op, a, b)
901 # Same when dead.
902 del x, y
903 gc.collect()
904 for op in ops:
905 self.assertRaises(TypeError, op, a, b)
906
907 def test_hashing(self):
908 # Alive weakrefs hash the same as the underlying object
909 x = Object(42)
910 y = Object(42)
911 a = weakref.ref(x)
912 b = weakref.ref(y)
913 self.assertEqual(hash(a), hash(42))
914 del x, y
915 gc.collect()
916 # Dead weakrefs:
917 # - retain their hash is they were hashed when alive;
918 # - otherwise, cannot be hashed.
919 self.assertEqual(hash(a), hash(42))
920 self.assertRaises(TypeError, hash, b)
921
Antoine Pitrou62a0d6e2012-12-08 21:15:26 +0100922 def test_trashcan_16602(self):
923 # Issue #16602: when a weakref's target was part of a long
924 # deallocation chain, the trashcan mechanism could delay clearing
925 # of the weakref and make the target object visible from outside
926 # code even though its refcount had dropped to 0. A crash ensued.
927 class C:
928 def __init__(self, parent):
929 if not parent:
930 return
931 wself = weakref.ref(self)
932 def cb(wparent):
933 o = wself()
934 self.wparent = weakref.ref(parent, cb)
935
936 d = weakref.WeakKeyDictionary()
937 root = c = C(None)
938 for n in range(100):
939 d[c] = c = C(c)
940 del root
941 gc.collect()
942
Mark Dickinson556e94b2013-04-13 15:45:44 +0100943 def test_callback_attribute(self):
944 x = Object(1)
945 callback = lambda ref: None
946 ref1 = weakref.ref(x, callback)
947 self.assertIs(ref1.__callback__, callback)
948
949 ref2 = weakref.ref(x)
950 self.assertIsNone(ref2.__callback__)
951
952 def test_callback_attribute_after_deletion(self):
953 x = Object(1)
954 ref = weakref.ref(x, self.callback)
955 self.assertIsNotNone(ref.__callback__)
956 del x
957 support.gc_collect()
958 self.assertIsNone(ref.__callback__)
959
960 def test_set_callback_attribute(self):
961 x = Object(1)
962 callback = lambda ref: None
963 ref1 = weakref.ref(x, callback)
964 with self.assertRaises(AttributeError):
965 ref1.__callback__ = lambda ref: None
966
Benjamin Peterson8f657c32016-10-04 00:00:02 -0700967 def test_callback_gcs(self):
968 class ObjectWithDel(Object):
969 def __del__(self): pass
970 x = ObjectWithDel(1)
971 ref1 = weakref.ref(x, lambda ref: support.gc_collect())
972 del x
973 support.gc_collect()
974
Fred Drake0a4dd392004-07-02 18:57:45 +0000975
Amaury Forgeot d'Arcc856c7a2008-06-16 19:50:09 +0000976class SubclassableWeakrefTestCase(TestBase):
Fred Drake0a4dd392004-07-02 18:57:45 +0000977
978 def test_subclass_refs(self):
979 class MyRef(weakref.ref):
980 def __init__(self, ob, callback=None, value=42):
981 self.value = value
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000982 super().__init__(ob, callback)
Fred Drake0a4dd392004-07-02 18:57:45 +0000983 def __call__(self):
984 self.called = True
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000985 return super().__call__()
Fred Drake0a4dd392004-07-02 18:57:45 +0000986 o = Object("foo")
987 mr = MyRef(o, value=24)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200988 self.assertIs(mr(), o)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000989 self.assertTrue(mr.called)
Fred Drake0a4dd392004-07-02 18:57:45 +0000990 self.assertEqual(mr.value, 24)
991 del o
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200992 self.assertIsNone(mr())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000993 self.assertTrue(mr.called)
Fred Drake0a4dd392004-07-02 18:57:45 +0000994
995 def test_subclass_refs_dont_replace_standard_refs(self):
996 class MyRef(weakref.ref):
997 pass
998 o = Object(42)
999 r1 = MyRef(o)
1000 r2 = weakref.ref(o)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001001 self.assertIsNot(r1, r2)
Fred Drake0a4dd392004-07-02 18:57:45 +00001002 self.assertEqual(weakref.getweakrefs(o), [r2, r1])
1003 self.assertEqual(weakref.getweakrefcount(o), 2)
1004 r3 = MyRef(o)
1005 self.assertEqual(weakref.getweakrefcount(o), 3)
1006 refs = weakref.getweakrefs(o)
1007 self.assertEqual(len(refs), 3)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001008 self.assertIs(r2, refs[0])
Benjamin Peterson577473f2010-01-19 00:09:57 +00001009 self.assertIn(r1, refs[1:])
1010 self.assertIn(r3, refs[1:])
Fred Drake0a4dd392004-07-02 18:57:45 +00001011
1012 def test_subclass_refs_dont_conflate_callbacks(self):
1013 class MyRef(weakref.ref):
1014 pass
1015 o = Object(42)
1016 r1 = MyRef(o, id)
1017 r2 = MyRef(o, str)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001018 self.assertIsNot(r1, r2)
Fred Drake0a4dd392004-07-02 18:57:45 +00001019 refs = weakref.getweakrefs(o)
Benjamin Peterson577473f2010-01-19 00:09:57 +00001020 self.assertIn(r1, refs)
1021 self.assertIn(r2, refs)
Fred Drake0a4dd392004-07-02 18:57:45 +00001022
1023 def test_subclass_refs_with_slots(self):
1024 class MyRef(weakref.ref):
1025 __slots__ = "slot1", "slot2"
1026 def __new__(type, ob, callback, slot1, slot2):
1027 return weakref.ref.__new__(type, ob, callback)
1028 def __init__(self, ob, callback, slot1, slot2):
1029 self.slot1 = slot1
1030 self.slot2 = slot2
1031 def meth(self):
1032 return self.slot1 + self.slot2
1033 o = Object(42)
1034 r = MyRef(o, None, "abc", "def")
1035 self.assertEqual(r.slot1, "abc")
1036 self.assertEqual(r.slot2, "def")
1037 self.assertEqual(r.meth(), "abcdef")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001038 self.assertFalse(hasattr(r, "__dict__"))
Fred Drake0a4dd392004-07-02 18:57:45 +00001039
Amaury Forgeot d'Arcc856c7a2008-06-16 19:50:09 +00001040 def test_subclass_refs_with_cycle(self):
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)cd14d5d2016-09-07 00:22:22 +00001041 """Confirm https://bugs.python.org/issue3100 is fixed."""
Amaury Forgeot d'Arcc856c7a2008-06-16 19:50:09 +00001042 # An instance of a weakref subclass can have attributes.
1043 # If such a weakref holds the only strong reference to the object,
1044 # deleting the weakref will delete the object. In this case,
1045 # the callback must not be called, because the ref object is
1046 # being deleted.
1047 class MyRef(weakref.ref):
1048 pass
1049
1050 # Use a local callback, for "regrtest -R::"
1051 # to detect refcounting problems
1052 def callback(w):
1053 self.cbcalled += 1
1054
1055 o = C()
1056 r1 = MyRef(o, callback)
1057 r1.o = o
1058 del o
1059
1060 del r1 # Used to crash here
1061
1062 self.assertEqual(self.cbcalled, 0)
1063
1064 # Same test, with two weakrefs to the same object
1065 # (since code paths are different)
1066 o = C()
1067 r1 = MyRef(o, callback)
1068 r2 = MyRef(o, callback)
1069 r1.r = r2
1070 r2.o = o
1071 del o
1072 del r2
1073
1074 del r1 # Used to crash here
1075
1076 self.assertEqual(self.cbcalled, 0)
1077
Fred Drake0a4dd392004-07-02 18:57:45 +00001078
Antoine Pitrouc3afba12012-11-17 18:57:38 +01001079class WeakMethodTestCase(unittest.TestCase):
1080
1081 def _subclass(self):
Martin Panter7462b6492015-11-02 03:37:02 +00001082 """Return an Object subclass overriding `some_method`."""
Antoine Pitrouc3afba12012-11-17 18:57:38 +01001083 class C(Object):
1084 def some_method(self):
1085 return 6
1086 return C
1087
1088 def test_alive(self):
1089 o = Object(1)
1090 r = weakref.WeakMethod(o.some_method)
1091 self.assertIsInstance(r, weakref.ReferenceType)
1092 self.assertIsInstance(r(), type(o.some_method))
1093 self.assertIs(r().__self__, o)
1094 self.assertIs(r().__func__, o.some_method.__func__)
1095 self.assertEqual(r()(), 4)
1096
1097 def test_object_dead(self):
1098 o = Object(1)
1099 r = weakref.WeakMethod(o.some_method)
1100 del o
1101 gc.collect()
1102 self.assertIs(r(), None)
1103
1104 def test_method_dead(self):
1105 C = self._subclass()
1106 o = C(1)
1107 r = weakref.WeakMethod(o.some_method)
1108 del C.some_method
1109 gc.collect()
1110 self.assertIs(r(), None)
1111
1112 def test_callback_when_object_dead(self):
1113 # Test callback behaviour when object dies first.
1114 C = self._subclass()
1115 calls = []
1116 def cb(arg):
1117 calls.append(arg)
1118 o = C(1)
1119 r = weakref.WeakMethod(o.some_method, cb)
1120 del o
1121 gc.collect()
1122 self.assertEqual(calls, [r])
1123 # Callback is only called once.
1124 C.some_method = Object.some_method
1125 gc.collect()
1126 self.assertEqual(calls, [r])
1127
1128 def test_callback_when_method_dead(self):
1129 # Test callback behaviour when method dies first.
1130 C = self._subclass()
1131 calls = []
1132 def cb(arg):
1133 calls.append(arg)
1134 o = C(1)
1135 r = weakref.WeakMethod(o.some_method, cb)
1136 del C.some_method
1137 gc.collect()
1138 self.assertEqual(calls, [r])
1139 # Callback is only called once.
1140 del o
1141 gc.collect()
1142 self.assertEqual(calls, [r])
1143
1144 @support.cpython_only
1145 def test_no_cycles(self):
1146 # A WeakMethod doesn't create any reference cycle to itself.
1147 o = Object(1)
1148 def cb(_):
1149 pass
1150 r = weakref.WeakMethod(o.some_method, cb)
1151 wr = weakref.ref(r)
1152 del r
1153 self.assertIs(wr(), None)
1154
1155 def test_equality(self):
1156 def _eq(a, b):
1157 self.assertTrue(a == b)
1158 self.assertFalse(a != b)
1159 def _ne(a, b):
1160 self.assertTrue(a != b)
1161 self.assertFalse(a == b)
1162 x = Object(1)
1163 y = Object(1)
1164 a = weakref.WeakMethod(x.some_method)
1165 b = weakref.WeakMethod(y.some_method)
1166 c = weakref.WeakMethod(x.other_method)
1167 d = weakref.WeakMethod(y.other_method)
1168 # Objects equal, same method
1169 _eq(a, b)
1170 _eq(c, d)
1171 # Objects equal, different method
1172 _ne(a, c)
1173 _ne(a, d)
1174 _ne(b, c)
1175 _ne(b, d)
1176 # Objects unequal, same or different method
1177 z = Object(2)
1178 e = weakref.WeakMethod(z.some_method)
1179 f = weakref.WeakMethod(z.other_method)
1180 _ne(a, e)
1181 _ne(a, f)
1182 _ne(b, e)
1183 _ne(b, f)
Serhiy Storchaka662db122019-08-08 08:42:54 +03001184 # Compare with different types
1185 _ne(a, x.some_method)
1186 _eq(a, ALWAYS_EQ)
Antoine Pitrouc3afba12012-11-17 18:57:38 +01001187 del x, y, z
1188 gc.collect()
1189 # Dead WeakMethods compare by identity
1190 refs = a, b, c, d, e, f
1191 for q in refs:
1192 for r in refs:
1193 self.assertEqual(q == r, q is r)
1194 self.assertEqual(q != r, q is not r)
1195
1196 def test_hashing(self):
1197 # Alive WeakMethods are hashable if the underlying object is
1198 # hashable.
1199 x = Object(1)
1200 y = Object(1)
1201 a = weakref.WeakMethod(x.some_method)
1202 b = weakref.WeakMethod(y.some_method)
1203 c = weakref.WeakMethod(y.other_method)
1204 # Since WeakMethod objects are equal, the hashes should be equal.
1205 self.assertEqual(hash(a), hash(b))
1206 ha = hash(a)
1207 # Dead WeakMethods retain their old hash value
1208 del x, y
1209 gc.collect()
1210 self.assertEqual(hash(a), ha)
1211 self.assertEqual(hash(b), ha)
1212 # If it wasn't hashed when alive, a dead WeakMethod cannot be hashed.
1213 self.assertRaises(TypeError, hash, c)
1214
1215
Fred Drakeb0fefc52001-03-23 04:22:45 +00001216class MappingTestCase(TestBase):
Martin v. Löwis5e163332001-02-27 18:36:56 +00001217
Fred Drakeb0fefc52001-03-23 04:22:45 +00001218 COUNT = 10
1219
Antoine Pitroubbe2f602012-03-01 16:26:35 +01001220 def check_len_cycles(self, dict_type, cons):
1221 N = 20
1222 items = [RefCycle() for i in range(N)]
1223 dct = dict_type(cons(o) for o in items)
1224 # Keep an iterator alive
1225 it = dct.items()
1226 try:
1227 next(it)
1228 except StopIteration:
1229 pass
1230 del items
1231 gc.collect()
1232 n1 = len(dct)
1233 del it
1234 gc.collect()
1235 n2 = len(dct)
1236 # one item may be kept alive inside the iterator
1237 self.assertIn(n1, (0, 1))
1238 self.assertEqual(n2, 0)
1239
1240 def test_weak_keyed_len_cycles(self):
1241 self.check_len_cycles(weakref.WeakKeyDictionary, lambda k: (k, 1))
1242
1243 def test_weak_valued_len_cycles(self):
1244 self.check_len_cycles(weakref.WeakValueDictionary, lambda k: (1, k))
1245
1246 def check_len_race(self, dict_type, cons):
1247 # Extended sanity checks for len() in the face of cyclic collection
1248 self.addCleanup(gc.set_threshold, *gc.get_threshold())
1249 for th in range(1, 100):
1250 N = 20
1251 gc.collect(0)
1252 gc.set_threshold(th, th, th)
1253 items = [RefCycle() for i in range(N)]
1254 dct = dict_type(cons(o) for o in items)
1255 del items
1256 # All items will be collected at next garbage collection pass
1257 it = dct.items()
1258 try:
1259 next(it)
1260 except StopIteration:
1261 pass
1262 n1 = len(dct)
1263 del it
1264 n2 = len(dct)
1265 self.assertGreaterEqual(n1, 0)
1266 self.assertLessEqual(n1, N)
1267 self.assertGreaterEqual(n2, 0)
1268 self.assertLessEqual(n2, n1)
1269
1270 def test_weak_keyed_len_race(self):
1271 self.check_len_race(weakref.WeakKeyDictionary, lambda k: (k, 1))
1272
1273 def test_weak_valued_len_race(self):
1274 self.check_len_race(weakref.WeakValueDictionary, lambda k: (1, k))
1275
Fred Drakeb0fefc52001-03-23 04:22:45 +00001276 def test_weak_values(self):
Fred Drake0e540c32001-05-02 05:44:22 +00001277 #
1278 # This exercises d.copy(), d.items(), d[], del d[], len(d).
1279 #
1280 dict, objects = self.make_weak_valued_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +00001281 for o in objects:
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001282 self.assertEqual(weakref.getweakrefcount(o), 1)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001283 self.assertIs(o, dict[o.arg],
Fred Drakeb0fefc52001-03-23 04:22:45 +00001284 "wrong object returned by weak dict!")
Barry Warsawecaab832008-09-04 01:42:51 +00001285 items1 = list(dict.items())
1286 items2 = list(dict.copy().items())
Fred Drakeb0fefc52001-03-23 04:22:45 +00001287 items1.sort()
1288 items2.sort()
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001289 self.assertEqual(items1, items2,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001290 "cloning of weak-valued dictionary did not work!")
1291 del items1, items2
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001292 self.assertEqual(len(dict), self.COUNT)
Fred Drakeb0fefc52001-03-23 04:22:45 +00001293 del objects[0]
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001294 self.assertEqual(len(dict), self.COUNT - 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001295 "deleting object did not cause dictionary update")
1296 del objects, o
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001297 self.assertEqual(len(dict), 0,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001298 "deleting the values did not clear the dictionary")
Fred Drake4fd06e02001-08-03 04:11:27 +00001299 # regression on SF bug #447152:
1300 dict = weakref.WeakValueDictionary()
1301 self.assertRaises(KeyError, dict.__getitem__, 1)
1302 dict[2] = C()
1303 self.assertRaises(KeyError, dict.__getitem__, 2)
Fred Drakeb0fefc52001-03-23 04:22:45 +00001304
1305 def test_weak_keys(self):
Fred Drake0e540c32001-05-02 05:44:22 +00001306 #
1307 # This exercises d.copy(), d.items(), d[] = v, d[], del d[],
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001308 # len(d), k in d.
Fred Drake0e540c32001-05-02 05:44:22 +00001309 #
1310 dict, objects = self.make_weak_keyed_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +00001311 for o in objects:
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001312 self.assertEqual(weakref.getweakrefcount(o), 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001313 "wrong number of weak references to %r!" % o)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001314 self.assertIs(o.arg, dict[o],
Fred Drakeb0fefc52001-03-23 04:22:45 +00001315 "wrong object returned by weak dict!")
1316 items1 = dict.items()
1317 items2 = dict.copy().items()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001318 self.assertEqual(set(items1), set(items2),
Fred Drakeb0fefc52001-03-23 04:22:45 +00001319 "cloning of weak-keyed dictionary did not work!")
1320 del items1, items2
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001321 self.assertEqual(len(dict), self.COUNT)
Fred Drakeb0fefc52001-03-23 04:22:45 +00001322 del objects[0]
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001323 self.assertEqual(len(dict), (self.COUNT - 1),
Fred Drakeb0fefc52001-03-23 04:22:45 +00001324 "deleting object did not cause dictionary update")
1325 del objects, o
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001326 self.assertEqual(len(dict), 0,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001327 "deleting the keys did not clear the dictionary")
Fred Drake752eda42001-11-06 16:38:34 +00001328 o = Object(42)
1329 dict[o] = "What is the meaning of the universe?"
Benjamin Peterson577473f2010-01-19 00:09:57 +00001330 self.assertIn(o, dict)
1331 self.assertNotIn(34, dict)
Martin v. Löwis5e163332001-02-27 18:36:56 +00001332
Fred Drake0e540c32001-05-02 05:44:22 +00001333 def test_weak_keyed_iters(self):
1334 dict, objects = self.make_weak_keyed_dict()
1335 self.check_iters(dict)
1336
Thomas Wouters477c8d52006-05-27 19:21:47 +00001337 # Test keyrefs()
1338 refs = dict.keyrefs()
1339 self.assertEqual(len(refs), len(objects))
1340 objects2 = list(objects)
1341 for wr in refs:
1342 ob = wr()
Benjamin Peterson577473f2010-01-19 00:09:57 +00001343 self.assertIn(ob, dict)
1344 self.assertIn(ob, dict)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001345 self.assertEqual(ob.arg, dict[ob])
1346 objects2.remove(ob)
1347 self.assertEqual(len(objects2), 0)
1348
1349 # Test iterkeyrefs()
1350 objects2 = list(objects)
Barry Warsawecaab832008-09-04 01:42:51 +00001351 self.assertEqual(len(list(dict.keyrefs())), len(objects))
1352 for wr in dict.keyrefs():
Thomas Wouters477c8d52006-05-27 19:21:47 +00001353 ob = wr()
Benjamin Peterson577473f2010-01-19 00:09:57 +00001354 self.assertIn(ob, dict)
1355 self.assertIn(ob, dict)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001356 self.assertEqual(ob.arg, dict[ob])
1357 objects2.remove(ob)
1358 self.assertEqual(len(objects2), 0)
1359
Fred Drake0e540c32001-05-02 05:44:22 +00001360 def test_weak_valued_iters(self):
1361 dict, objects = self.make_weak_valued_dict()
1362 self.check_iters(dict)
1363
Thomas Wouters477c8d52006-05-27 19:21:47 +00001364 # Test valuerefs()
1365 refs = dict.valuerefs()
1366 self.assertEqual(len(refs), len(objects))
1367 objects2 = list(objects)
1368 for wr in refs:
1369 ob = wr()
1370 self.assertEqual(ob, dict[ob.arg])
1371 self.assertEqual(ob.arg, dict[ob.arg].arg)
1372 objects2.remove(ob)
1373 self.assertEqual(len(objects2), 0)
1374
1375 # Test itervaluerefs()
1376 objects2 = list(objects)
1377 self.assertEqual(len(list(dict.itervaluerefs())), len(objects))
1378 for wr in dict.itervaluerefs():
1379 ob = wr()
1380 self.assertEqual(ob, dict[ob.arg])
1381 self.assertEqual(ob.arg, dict[ob.arg].arg)
1382 objects2.remove(ob)
1383 self.assertEqual(len(objects2), 0)
1384
Fred Drake0e540c32001-05-02 05:44:22 +00001385 def check_iters(self, dict):
1386 # item iterator:
Barry Warsawecaab832008-09-04 01:42:51 +00001387 items = list(dict.items())
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001388 for item in dict.items():
Fred Drake0e540c32001-05-02 05:44:22 +00001389 items.remove(item)
Barry Warsawecaab832008-09-04 01:42:51 +00001390 self.assertFalse(items, "items() did not touch all items")
Fred Drake0e540c32001-05-02 05:44:22 +00001391
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001392 # key iterator, via __iter__():
Guido van Rossum07f24362007-02-11 22:59:48 +00001393 keys = list(dict.keys())
Fred Drake0e540c32001-05-02 05:44:22 +00001394 for k in dict:
1395 keys.remove(k)
Barry Warsawecaab832008-09-04 01:42:51 +00001396 self.assertFalse(keys, "__iter__() did not touch all keys")
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001397
1398 # key iterator, via iterkeys():
Guido van Rossum07f24362007-02-11 22:59:48 +00001399 keys = list(dict.keys())
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001400 for k in dict.keys():
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001401 keys.remove(k)
Barry Warsawecaab832008-09-04 01:42:51 +00001402 self.assertFalse(keys, "iterkeys() did not touch all keys")
Fred Drake0e540c32001-05-02 05:44:22 +00001403
1404 # value iterator:
Guido van Rossum07f24362007-02-11 22:59:48 +00001405 values = list(dict.values())
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001406 for v in dict.values():
Fred Drake0e540c32001-05-02 05:44:22 +00001407 values.remove(v)
Barry Warsawecaab832008-09-04 01:42:51 +00001408 self.assertFalse(values,
Fred Drakef425b1e2003-07-14 21:37:17 +00001409 "itervalues() did not touch all values")
Fred Drake0e540c32001-05-02 05:44:22 +00001410
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001411 def check_weak_destroy_while_iterating(self, dict, objects, iter_name):
1412 n = len(dict)
1413 it = iter(getattr(dict, iter_name)())
1414 next(it) # Trigger internal iteration
1415 # Destroy an object
1416 del objects[-1]
1417 gc.collect() # just in case
1418 # We have removed either the first consumed object, or another one
1419 self.assertIn(len(list(it)), [len(objects), len(objects) - 1])
1420 del it
1421 # The removal has been committed
1422 self.assertEqual(len(dict), n - 1)
1423
1424 def check_weak_destroy_and_mutate_while_iterating(self, dict, testcontext):
1425 # Check that we can explicitly mutate the weak dict without
1426 # interfering with delayed removal.
1427 # `testcontext` should create an iterator, destroy one of the
1428 # weakref'ed objects and then return a new key/value pair corresponding
1429 # to the destroyed object.
1430 with testcontext() as (k, v):
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001431 self.assertNotIn(k, dict)
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001432 with testcontext() as (k, v):
1433 self.assertRaises(KeyError, dict.__delitem__, k)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001434 self.assertNotIn(k, dict)
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001435 with testcontext() as (k, v):
1436 self.assertRaises(KeyError, dict.pop, k)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001437 self.assertNotIn(k, dict)
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001438 with testcontext() as (k, v):
1439 dict[k] = v
1440 self.assertEqual(dict[k], v)
1441 ddict = copy.copy(dict)
1442 with testcontext() as (k, v):
1443 dict.update(ddict)
1444 self.assertEqual(dict, ddict)
1445 with testcontext() as (k, v):
1446 dict.clear()
1447 self.assertEqual(len(dict), 0)
1448
Antoine Pitrou1bf974d2014-10-05 20:02:28 +02001449 def check_weak_del_and_len_while_iterating(self, dict, testcontext):
1450 # Check that len() works when both iterating and removing keys
1451 # explicitly through various means (.pop(), .clear()...), while
1452 # implicit mutation is deferred because an iterator is alive.
1453 # (each call to testcontext() should schedule one item for removal
1454 # for this test to work properly)
1455 o = Object(123456)
1456 with testcontext():
1457 n = len(dict)
Victor Stinner742da042016-09-07 17:40:12 -07001458 # Since underlaying dict is ordered, first item is popped
1459 dict.pop(next(dict.keys()))
Antoine Pitrou1bf974d2014-10-05 20:02:28 +02001460 self.assertEqual(len(dict), n - 1)
1461 dict[o] = o
1462 self.assertEqual(len(dict), n)
Victor Stinner742da042016-09-07 17:40:12 -07001463 # last item in objects is removed from dict in context shutdown
Antoine Pitrou1bf974d2014-10-05 20:02:28 +02001464 with testcontext():
1465 self.assertEqual(len(dict), n - 1)
Victor Stinner742da042016-09-07 17:40:12 -07001466 # Then, (o, o) is popped
1467 dict.popitem()
Antoine Pitrou1bf974d2014-10-05 20:02:28 +02001468 self.assertEqual(len(dict), n - 2)
1469 with testcontext():
1470 self.assertEqual(len(dict), n - 3)
1471 del dict[next(dict.keys())]
1472 self.assertEqual(len(dict), n - 4)
1473 with testcontext():
1474 self.assertEqual(len(dict), n - 5)
1475 dict.popitem()
1476 self.assertEqual(len(dict), n - 6)
1477 with testcontext():
1478 dict.clear()
1479 self.assertEqual(len(dict), 0)
1480 self.assertEqual(len(dict), 0)
1481
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001482 def test_weak_keys_destroy_while_iterating(self):
1483 # Issue #7105: iterators shouldn't crash when a key is implicitly removed
1484 dict, objects = self.make_weak_keyed_dict()
1485 self.check_weak_destroy_while_iterating(dict, objects, 'keys')
1486 self.check_weak_destroy_while_iterating(dict, objects, 'items')
1487 self.check_weak_destroy_while_iterating(dict, objects, 'values')
1488 self.check_weak_destroy_while_iterating(dict, objects, 'keyrefs')
1489 dict, objects = self.make_weak_keyed_dict()
1490 @contextlib.contextmanager
1491 def testcontext():
1492 try:
1493 it = iter(dict.items())
1494 next(it)
1495 # Schedule a key/value for removal and recreate it
1496 v = objects.pop().arg
1497 gc.collect() # just in case
1498 yield Object(v), v
1499 finally:
1500 it = None # should commit all removals
Benjamin Peterson18bb7022014-08-24 18:02:15 -05001501 gc.collect()
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001502 self.check_weak_destroy_and_mutate_while_iterating(dict, testcontext)
Antoine Pitrou1bf974d2014-10-05 20:02:28 +02001503 # Issue #21173: len() fragile when keys are both implicitly and
1504 # explicitly removed.
1505 dict, objects = self.make_weak_keyed_dict()
1506 self.check_weak_del_and_len_while_iterating(dict, testcontext)
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001507
1508 def test_weak_values_destroy_while_iterating(self):
1509 # Issue #7105: iterators shouldn't crash when a key is implicitly removed
1510 dict, objects = self.make_weak_valued_dict()
1511 self.check_weak_destroy_while_iterating(dict, objects, 'keys')
1512 self.check_weak_destroy_while_iterating(dict, objects, 'items')
1513 self.check_weak_destroy_while_iterating(dict, objects, 'values')
1514 self.check_weak_destroy_while_iterating(dict, objects, 'itervaluerefs')
1515 self.check_weak_destroy_while_iterating(dict, objects, 'valuerefs')
1516 dict, objects = self.make_weak_valued_dict()
1517 @contextlib.contextmanager
1518 def testcontext():
1519 try:
1520 it = iter(dict.items())
1521 next(it)
1522 # Schedule a key/value for removal and recreate it
1523 k = objects.pop().arg
1524 gc.collect() # just in case
1525 yield k, Object(k)
1526 finally:
1527 it = None # should commit all removals
Benjamin Peterson18bb7022014-08-24 18:02:15 -05001528 gc.collect()
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001529 self.check_weak_destroy_and_mutate_while_iterating(dict, testcontext)
Antoine Pitrou1bf974d2014-10-05 20:02:28 +02001530 dict, objects = self.make_weak_valued_dict()
1531 self.check_weak_del_and_len_while_iterating(dict, testcontext)
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001532
Guido van Rossum009afb72002-06-10 20:00:52 +00001533 def test_make_weak_keyed_dict_from_dict(self):
1534 o = Object(3)
1535 dict = weakref.WeakKeyDictionary({o:364})
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001536 self.assertEqual(dict[o], 364)
Guido van Rossum009afb72002-06-10 20:00:52 +00001537
1538 def test_make_weak_keyed_dict_from_weak_keyed_dict(self):
1539 o = Object(3)
1540 dict = weakref.WeakKeyDictionary({o:364})
1541 dict2 = weakref.WeakKeyDictionary(dict)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001542 self.assertEqual(dict[o], 364)
Guido van Rossum009afb72002-06-10 20:00:52 +00001543
Fred Drake0e540c32001-05-02 05:44:22 +00001544 def make_weak_keyed_dict(self):
1545 dict = weakref.WeakKeyDictionary()
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] = o.arg
1549 return dict, objects
1550
Antoine Pitrouc06de472009-05-30 21:04:26 +00001551 def test_make_weak_valued_dict_from_dict(self):
1552 o = Object(3)
1553 dict = weakref.WeakValueDictionary({364:o})
1554 self.assertEqual(dict[364], o)
1555
1556 def test_make_weak_valued_dict_from_weak_valued_dict(self):
1557 o = Object(3)
1558 dict = weakref.WeakValueDictionary({364:o})
1559 dict2 = weakref.WeakValueDictionary(dict)
1560 self.assertEqual(dict[364], o)
1561
Serhiy Storchakab5102e32015-09-29 23:52:09 +03001562 def test_make_weak_valued_dict_misc(self):
1563 # errors
1564 self.assertRaises(TypeError, weakref.WeakValueDictionary.__init__)
1565 self.assertRaises(TypeError, weakref.WeakValueDictionary, {}, {})
1566 self.assertRaises(TypeError, weakref.WeakValueDictionary, (), ())
1567 # special keyword arguments
1568 o = Object(3)
1569 for kw in 'self', 'dict', 'other', 'iterable':
1570 d = weakref.WeakValueDictionary(**{kw: o})
1571 self.assertEqual(list(d.keys()), [kw])
1572 self.assertEqual(d[kw], o)
1573
Fred Drake0e540c32001-05-02 05:44:22 +00001574 def make_weak_valued_dict(self):
1575 dict = weakref.WeakValueDictionary()
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001576 objects = list(map(Object, range(self.COUNT)))
Fred Drake0e540c32001-05-02 05:44:22 +00001577 for o in objects:
1578 dict[o.arg] = o
1579 return dict, objects
1580
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001581 def check_popitem(self, klass, key1, value1, key2, value2):
1582 weakdict = klass()
1583 weakdict[key1] = value1
1584 weakdict[key2] = value2
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001585 self.assertEqual(len(weakdict), 2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001586 k, v = weakdict.popitem()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001587 self.assertEqual(len(weakdict), 1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001588 if k is key1:
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001589 self.assertIs(v, value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001590 else:
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001591 self.assertIs(v, value2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001592 k, v = weakdict.popitem()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001593 self.assertEqual(len(weakdict), 0)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001594 if k is key1:
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001595 self.assertIs(v, value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001596 else:
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001597 self.assertIs(v, value2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001598
1599 def test_weak_valued_dict_popitem(self):
1600 self.check_popitem(weakref.WeakValueDictionary,
1601 "key1", C(), "key2", C())
1602
1603 def test_weak_keyed_dict_popitem(self):
1604 self.check_popitem(weakref.WeakKeyDictionary,
1605 C(), "value 1", C(), "value 2")
1606
1607 def check_setdefault(self, klass, key, value1, value2):
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001608 self.assertIsNot(value1, value2,
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001609 "invalid test"
1610 " -- value parameters must be distinct objects")
1611 weakdict = klass()
1612 o = weakdict.setdefault(key, value1)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001613 self.assertIs(o, value1)
Benjamin Peterson577473f2010-01-19 00:09:57 +00001614 self.assertIn(key, weakdict)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001615 self.assertIs(weakdict.get(key), value1)
1616 self.assertIs(weakdict[key], value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001617
1618 o = weakdict.setdefault(key, value2)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001619 self.assertIs(o, value1)
Benjamin Peterson577473f2010-01-19 00:09:57 +00001620 self.assertIn(key, weakdict)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001621 self.assertIs(weakdict.get(key), value1)
1622 self.assertIs(weakdict[key], value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001623
1624 def test_weak_valued_dict_setdefault(self):
1625 self.check_setdefault(weakref.WeakValueDictionary,
1626 "key", C(), C())
1627
1628 def test_weak_keyed_dict_setdefault(self):
1629 self.check_setdefault(weakref.WeakKeyDictionary,
1630 C(), "value 1", "value 2")
1631
Fred Drakea0a4ab12001-04-16 17:37:27 +00001632 def check_update(self, klass, dict):
Fred Drake0e540c32001-05-02 05:44:22 +00001633 #
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001634 # This exercises d.update(), len(d), d.keys(), k in d,
Fred Drake0e540c32001-05-02 05:44:22 +00001635 # d.get(), d[].
1636 #
Fred Drakea0a4ab12001-04-16 17:37:27 +00001637 weakdict = klass()
1638 weakdict.update(dict)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001639 self.assertEqual(len(weakdict), len(dict))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001640 for k in weakdict.keys():
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001641 self.assertIn(k, dict, "mysterious new key appeared in weak dict")
Fred Drakea0a4ab12001-04-16 17:37:27 +00001642 v = dict.get(k)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001643 self.assertIs(v, weakdict[k])
1644 self.assertIs(v, weakdict.get(k))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001645 for k in dict.keys():
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001646 self.assertIn(k, weakdict, "original key disappeared in weak dict")
Fred Drakea0a4ab12001-04-16 17:37:27 +00001647 v = dict[k]
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001648 self.assertIs(v, weakdict[k])
1649 self.assertIs(v, weakdict.get(k))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001650
1651 def test_weak_valued_dict_update(self):
1652 self.check_update(weakref.WeakValueDictionary,
1653 {1: C(), 'a': C(), C(): C()})
Serhiy Storchakab5102e32015-09-29 23:52:09 +03001654 # errors
1655 self.assertRaises(TypeError, weakref.WeakValueDictionary.update)
1656 d = weakref.WeakValueDictionary()
1657 self.assertRaises(TypeError, d.update, {}, {})
1658 self.assertRaises(TypeError, d.update, (), ())
1659 self.assertEqual(list(d.keys()), [])
1660 # special keyword arguments
1661 o = Object(3)
1662 for kw in 'self', 'dict', 'other', 'iterable':
1663 d = weakref.WeakValueDictionary()
1664 d.update(**{kw: o})
1665 self.assertEqual(list(d.keys()), [kw])
1666 self.assertEqual(d[kw], o)
Fred Drakea0a4ab12001-04-16 17:37:27 +00001667
Curtis Bucher8f1ed212020-03-24 18:51:29 -07001668 def test_weak_valued_union_operators(self):
1669 a = C()
1670 b = C()
1671 c = C()
1672 wvd1 = weakref.WeakValueDictionary({1: a})
1673 wvd2 = weakref.WeakValueDictionary({1: b, 2: a})
1674 wvd3 = wvd1.copy()
1675 d1 = {1: c, 3: b}
1676 pairs = [(5, c), (6, b)]
1677
1678 tmp1 = wvd1 | wvd2 # Between two WeakValueDictionaries
1679 self.assertEqual(dict(tmp1), dict(wvd1) | dict(wvd2))
1680 self.assertIs(type(tmp1), weakref.WeakValueDictionary)
1681 wvd1 |= wvd2
1682 self.assertEqual(wvd1, tmp1)
1683
1684 tmp2 = wvd2 | d1 # Between WeakValueDictionary and mapping
1685 self.assertEqual(dict(tmp2), dict(wvd2) | d1)
1686 self.assertIs(type(tmp2), weakref.WeakValueDictionary)
1687 wvd2 |= d1
1688 self.assertEqual(wvd2, tmp2)
1689
1690 tmp3 = wvd3.copy() # Between WeakValueDictionary and iterable key, value
1691 tmp3 |= pairs
1692 self.assertEqual(dict(tmp3), dict(wvd3) | dict(pairs))
1693 self.assertIs(type(tmp3), weakref.WeakValueDictionary)
1694
1695 tmp4 = d1 | wvd3 # Testing .__ror__
1696 self.assertEqual(dict(tmp4), d1 | dict(wvd3))
1697 self.assertIs(type(tmp4), weakref.WeakValueDictionary)
1698
1699 del a
1700 self.assertNotIn(2, tmp1)
1701 self.assertNotIn(2, tmp2)
1702 self.assertNotIn(1, tmp3)
1703 self.assertNotIn(1, tmp4)
1704
Fred Drakea0a4ab12001-04-16 17:37:27 +00001705 def test_weak_keyed_dict_update(self):
1706 self.check_update(weakref.WeakKeyDictionary,
1707 {C(): 1, C(): 2, C(): 3})
1708
Fred Drakeccc75622001-09-06 14:52:39 +00001709 def test_weak_keyed_delitem(self):
1710 d = weakref.WeakKeyDictionary()
1711 o1 = Object('1')
1712 o2 = Object('2')
1713 d[o1] = 'something'
1714 d[o2] = 'something'
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001715 self.assertEqual(len(d), 2)
Fred Drakeccc75622001-09-06 14:52:39 +00001716 del d[o1]
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001717 self.assertEqual(len(d), 1)
Barry Warsawecaab832008-09-04 01:42:51 +00001718 self.assertEqual(list(d.keys()), [o2])
Fred Drakeccc75622001-09-06 14:52:39 +00001719
Curtis Bucher25e580a2020-03-23 13:49:46 -07001720 def test_weak_keyed_union_operators(self):
1721 o1 = C()
1722 o2 = C()
1723 o3 = C()
1724 wkd1 = weakref.WeakKeyDictionary({o1: 1, o2: 2})
1725 wkd2 = weakref.WeakKeyDictionary({o3: 3, o1: 4})
1726 wkd3 = wkd1.copy()
1727 d1 = {o2: '5', o3: '6'}
1728 pairs = [(o2, 7), (o3, 8)]
1729
1730 tmp1 = wkd1 | wkd2 # Between two WeakKeyDictionaries
1731 self.assertEqual(dict(tmp1), dict(wkd1) | dict(wkd2))
1732 self.assertIs(type(tmp1), weakref.WeakKeyDictionary)
1733 wkd1 |= wkd2
1734 self.assertEqual(wkd1, tmp1)
1735
1736 tmp2 = wkd2 | d1 # Between WeakKeyDictionary and mapping
1737 self.assertEqual(dict(tmp2), dict(wkd2) | d1)
1738 self.assertIs(type(tmp2), weakref.WeakKeyDictionary)
1739 wkd2 |= d1
1740 self.assertEqual(wkd2, tmp2)
1741
1742 tmp3 = wkd3.copy() # Between WeakKeyDictionary and iterable key, value
1743 tmp3 |= pairs
1744 self.assertEqual(dict(tmp3), dict(wkd3) | dict(pairs))
1745 self.assertIs(type(tmp3), weakref.WeakKeyDictionary)
1746
1747 tmp4 = d1 | wkd3 # Testing .__ror__
1748 self.assertEqual(dict(tmp4), d1 | dict(wkd3))
1749 self.assertIs(type(tmp4), weakref.WeakKeyDictionary)
1750
1751 del o1
1752 self.assertNotIn(4, tmp1.values())
1753 self.assertNotIn(4, tmp2.values())
1754 self.assertNotIn(1, tmp3.values())
1755 self.assertNotIn(1, tmp4.values())
1756
Fred Drakeccc75622001-09-06 14:52:39 +00001757 def test_weak_valued_delitem(self):
1758 d = weakref.WeakValueDictionary()
1759 o1 = Object('1')
1760 o2 = Object('2')
1761 d['something'] = o1
1762 d['something else'] = o2
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001763 self.assertEqual(len(d), 2)
Fred Drakeccc75622001-09-06 14:52:39 +00001764 del d['something']
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001765 self.assertEqual(len(d), 1)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001766 self.assertEqual(list(d.items()), [('something else', o2)])
Fred Drakeccc75622001-09-06 14:52:39 +00001767
Tim Peters886128f2003-05-25 01:45:11 +00001768 def test_weak_keyed_bad_delitem(self):
1769 d = weakref.WeakKeyDictionary()
1770 o = Object('1')
1771 # An attempt to delete an object that isn't there should raise
Tim Peters50d8b8b2003-05-25 17:44:31 +00001772 # KeyError. It didn't before 2.3.
Tim Peters886128f2003-05-25 01:45:11 +00001773 self.assertRaises(KeyError, d.__delitem__, o)
Tim Peters50d8b8b2003-05-25 17:44:31 +00001774 self.assertRaises(KeyError, d.__getitem__, o)
1775
1776 # If a key isn't of a weakly referencable type, __getitem__ and
1777 # __setitem__ raise TypeError. __delitem__ should too.
1778 self.assertRaises(TypeError, d.__delitem__, 13)
1779 self.assertRaises(TypeError, d.__getitem__, 13)
1780 self.assertRaises(TypeError, d.__setitem__, 13, 13)
Tim Peters886128f2003-05-25 01:45:11 +00001781
1782 def test_weak_keyed_cascading_deletes(self):
1783 # SF bug 742860. For some reason, before 2.3 __delitem__ iterated
1784 # over the keys via self.data.iterkeys(). If things vanished from
1785 # the dict during this (or got added), that caused a RuntimeError.
1786
1787 d = weakref.WeakKeyDictionary()
1788 mutate = False
1789
1790 class C(object):
1791 def __init__(self, i):
1792 self.value = i
1793 def __hash__(self):
1794 return hash(self.value)
1795 def __eq__(self, other):
1796 if mutate:
1797 # Side effect that mutates the dict, by removing the
1798 # last strong reference to a key.
1799 del objs[-1]
1800 return self.value == other.value
1801
1802 objs = [C(i) for i in range(4)]
1803 for o in objs:
1804 d[o] = o.value
1805 del o # now the only strong references to keys are in objs
1806 # Find the order in which iterkeys sees the keys.
Barry Warsawecaab832008-09-04 01:42:51 +00001807 objs = list(d.keys())
Tim Peters886128f2003-05-25 01:45:11 +00001808 # Reverse it, so that the iteration implementation of __delitem__
1809 # has to keep looping to find the first object we delete.
1810 objs.reverse()
Tim Peters50d8b8b2003-05-25 17:44:31 +00001811
Leo Ariasc3d95082018-02-03 18:36:10 -06001812 # Turn on mutation in C.__eq__. The first time through the loop,
Tim Peters886128f2003-05-25 01:45:11 +00001813 # under the iterkeys() business the first comparison will delete
1814 # the last item iterkeys() would see, and that causes a
1815 # RuntimeError: dictionary changed size during iteration
1816 # when the iterkeys() loop goes around to try comparing the next
Tim Peters50d8b8b2003-05-25 17:44:31 +00001817 # key. After this was fixed, it just deletes the last object *our*
Tim Peters886128f2003-05-25 01:45:11 +00001818 # "for o in obj" loop would have gotten to.
1819 mutate = True
1820 count = 0
1821 for o in objs:
1822 count += 1
1823 del d[o]
1824 self.assertEqual(len(d), 0)
1825 self.assertEqual(count, 2)
1826
Serhiy Storchaka0c937b32014-07-22 12:14:52 +03001827 def test_make_weak_valued_dict_repr(self):
1828 dict = weakref.WeakValueDictionary()
1829 self.assertRegex(repr(dict), '<WeakValueDictionary at 0x.*>')
1830
1831 def test_make_weak_keyed_dict_repr(self):
1832 dict = weakref.WeakKeyDictionary()
1833 self.assertRegex(repr(dict), '<WeakKeyDictionary at 0x.*>')
1834
Antoine Pitrouc1ee4882016-12-19 10:56:40 +01001835 def test_threaded_weak_valued_setdefault(self):
1836 d = weakref.WeakValueDictionary()
1837 with collect_in_thread():
1838 for i in range(100000):
1839 x = d.setdefault(10, RefCycle())
1840 self.assertIsNot(x, None) # we never put None in there!
1841 del x
1842
1843 def test_threaded_weak_valued_pop(self):
1844 d = weakref.WeakValueDictionary()
1845 with collect_in_thread():
1846 for i in range(100000):
1847 d[10] = RefCycle()
1848 x = d.pop(10, 10)
1849 self.assertIsNot(x, None) # we never put None in there!
1850
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001851 def test_threaded_weak_valued_consistency(self):
1852 # Issue #28427: old keys should not remove new values from
1853 # WeakValueDictionary when collecting from another thread.
1854 d = weakref.WeakValueDictionary()
1855 with collect_in_thread():
1856 for i in range(200000):
1857 o = RefCycle()
1858 d[10] = o
1859 # o is still alive, so the dict can't be empty
1860 self.assertEqual(len(d), 1)
1861 o = None # lose ref
1862
Fish96d37db2019-02-07 14:51:59 -05001863 def check_threaded_weak_dict_copy(self, type_, deepcopy):
1864 # `type_` should be either WeakKeyDictionary or WeakValueDictionary.
1865 # `deepcopy` should be either True or False.
1866 exc = []
1867
1868 class DummyKey:
1869 def __init__(self, ctr):
1870 self.ctr = ctr
1871
1872 class DummyValue:
1873 def __init__(self, ctr):
1874 self.ctr = ctr
1875
1876 def dict_copy(d, exc):
1877 try:
1878 if deepcopy is True:
1879 _ = copy.deepcopy(d)
1880 else:
1881 _ = d.copy()
1882 except Exception as ex:
1883 exc.append(ex)
1884
1885 def pop_and_collect(lst):
1886 gc_ctr = 0
1887 while lst:
1888 i = random.randint(0, len(lst) - 1)
1889 gc_ctr += 1
1890 lst.pop(i)
1891 if gc_ctr % 10000 == 0:
1892 gc.collect() # just in case
1893
1894 self.assertIn(type_, (weakref.WeakKeyDictionary, weakref.WeakValueDictionary))
1895
1896 d = type_()
1897 keys = []
1898 values = []
1899 # Initialize d with many entries
1900 for i in range(70000):
1901 k, v = DummyKey(i), DummyValue(i)
1902 keys.append(k)
1903 values.append(v)
1904 d[k] = v
1905 del k
1906 del v
1907
1908 t_copy = threading.Thread(target=dict_copy, args=(d, exc,))
1909 if type_ is weakref.WeakKeyDictionary:
1910 t_collect = threading.Thread(target=pop_and_collect, args=(keys,))
1911 else: # weakref.WeakValueDictionary
1912 t_collect = threading.Thread(target=pop_and_collect, args=(values,))
1913
1914 t_copy.start()
1915 t_collect.start()
1916
1917 t_copy.join()
1918 t_collect.join()
1919
1920 # Test exceptions
1921 if exc:
1922 raise exc[0]
1923
1924 def test_threaded_weak_key_dict_copy(self):
1925 # Issue #35615: Weakref keys or values getting GC'ed during dict
1926 # copying should not result in a crash.
1927 self.check_threaded_weak_dict_copy(weakref.WeakKeyDictionary, False)
1928
1929 def test_threaded_weak_key_dict_deepcopy(self):
1930 # Issue #35615: Weakref keys or values getting GC'ed during dict
1931 # copying should not result in a crash.
1932 self.check_threaded_weak_dict_copy(weakref.WeakKeyDictionary, True)
1933
1934 def test_threaded_weak_value_dict_copy(self):
1935 # Issue #35615: Weakref keys or values getting GC'ed during dict
1936 # copying should not result in a crash.
1937 self.check_threaded_weak_dict_copy(weakref.WeakValueDictionary, False)
1938
1939 def test_threaded_weak_value_dict_deepcopy(self):
1940 # Issue #35615: Weakref keys or values getting GC'ed during dict
1941 # copying should not result in a crash.
1942 self.check_threaded_weak_dict_copy(weakref.WeakValueDictionary, True)
1943
Victor Stinnera2af05a2019-09-09 16:55:58 +02001944 @support.cpython_only
1945 def test_remove_closure(self):
1946 d = weakref.WeakValueDictionary()
1947 self.assertIsNone(d._remove.__closure__)
1948
Antoine Pitrouc1ee4882016-12-19 10:56:40 +01001949
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001950from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001951
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001952class WeakValueDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +00001953 """Check that WeakValueDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001954 __ref = {"key1":Object(1), "key2":Object(2), "key3":Object(3)}
Walter Dörwald118f9312004-06-02 18:42:25 +00001955 type2test = weakref.WeakValueDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001956 def _reference(self):
1957 return self.__ref.copy()
1958
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001959class WeakKeyDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +00001960 """Check that WeakKeyDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001961 __ref = {Object("key1"):1, Object("key2"):2, Object("key3"):3}
Walter Dörwald118f9312004-06-02 18:42:25 +00001962 type2test = weakref.WeakKeyDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001963 def _reference(self):
1964 return self.__ref.copy()
Martin v. Löwis5e163332001-02-27 18:36:56 +00001965
Richard Oudkerk7a3dae02013-05-05 23:05:00 +01001966
1967class FinalizeTestCase(unittest.TestCase):
1968
1969 class A:
1970 pass
1971
1972 def _collect_if_necessary(self):
1973 # we create no ref-cycles so in CPython no gc should be needed
1974 if sys.implementation.name != 'cpython':
1975 support.gc_collect()
1976
1977 def test_finalize(self):
1978 def add(x,y,z):
1979 res.append(x + y + z)
1980 return x + y + z
1981
1982 a = self.A()
1983
1984 res = []
1985 f = weakref.finalize(a, add, 67, 43, z=89)
1986 self.assertEqual(f.alive, True)
1987 self.assertEqual(f.peek(), (a, add, (67,43), {'z':89}))
1988 self.assertEqual(f(), 199)
1989 self.assertEqual(f(), None)
1990 self.assertEqual(f(), None)
1991 self.assertEqual(f.peek(), None)
1992 self.assertEqual(f.detach(), None)
1993 self.assertEqual(f.alive, False)
1994 self.assertEqual(res, [199])
1995
1996 res = []
1997 f = weakref.finalize(a, add, 67, 43, 89)
1998 self.assertEqual(f.peek(), (a, add, (67,43,89), {}))
1999 self.assertEqual(f.detach(), (a, add, (67,43,89), {}))
2000 self.assertEqual(f(), None)
2001 self.assertEqual(f(), None)
2002 self.assertEqual(f.peek(), None)
2003 self.assertEqual(f.detach(), None)
2004 self.assertEqual(f.alive, False)
2005 self.assertEqual(res, [])
2006
2007 res = []
2008 f = weakref.finalize(a, add, x=67, y=43, z=89)
2009 del a
2010 self._collect_if_necessary()
2011 self.assertEqual(f(), None)
2012 self.assertEqual(f(), None)
2013 self.assertEqual(f.peek(), None)
2014 self.assertEqual(f.detach(), None)
2015 self.assertEqual(f.alive, False)
2016 self.assertEqual(res, [199])
2017
Serhiy Storchaka42a139e2019-04-01 09:16:35 +03002018 def test_arg_errors(self):
2019 def fin(*args, **kwargs):
2020 res.append((args, kwargs))
2021
2022 a = self.A()
2023
2024 res = []
2025 f = weakref.finalize(a, fin, 1, 2, func=3, obj=4)
2026 self.assertEqual(f.peek(), (a, fin, (1, 2), {'func': 3, 'obj': 4}))
2027 f()
2028 self.assertEqual(res, [((1, 2), {'func': 3, 'obj': 4})])
2029
Serhiy Storchaka142566c2019-06-05 18:22:31 +03002030 with self.assertRaises(TypeError):
2031 weakref.finalize(a, func=fin, arg=1)
2032 with self.assertRaises(TypeError):
2033 weakref.finalize(obj=a, func=fin, arg=1)
Serhiy Storchaka42a139e2019-04-01 09:16:35 +03002034 self.assertRaises(TypeError, weakref.finalize, a)
2035 self.assertRaises(TypeError, weakref.finalize)
2036
Richard Oudkerk7a3dae02013-05-05 23:05:00 +01002037 def test_order(self):
2038 a = self.A()
2039 res = []
2040
2041 f1 = weakref.finalize(a, res.append, 'f1')
2042 f2 = weakref.finalize(a, res.append, 'f2')
2043 f3 = weakref.finalize(a, res.append, 'f3')
2044 f4 = weakref.finalize(a, res.append, 'f4')
2045 f5 = weakref.finalize(a, res.append, 'f5')
2046
2047 # make sure finalizers can keep themselves alive
2048 del f1, f4
2049
2050 self.assertTrue(f2.alive)
2051 self.assertTrue(f3.alive)
2052 self.assertTrue(f5.alive)
2053
2054 self.assertTrue(f5.detach())
2055 self.assertFalse(f5.alive)
2056
2057 f5() # nothing because previously unregistered
2058 res.append('A')
2059 f3() # => res.append('f3')
2060 self.assertFalse(f3.alive)
2061 res.append('B')
2062 f3() # nothing because previously called
2063 res.append('C')
2064 del a
2065 self._collect_if_necessary()
2066 # => res.append('f4')
2067 # => res.append('f2')
2068 # => res.append('f1')
2069 self.assertFalse(f2.alive)
2070 res.append('D')
2071 f2() # nothing because previously called by gc
2072
2073 expected = ['A', 'f3', 'B', 'C', 'f4', 'f2', 'f1', 'D']
2074 self.assertEqual(res, expected)
2075
2076 def test_all_freed(self):
2077 # we want a weakrefable subclass of weakref.finalize
2078 class MyFinalizer(weakref.finalize):
2079 pass
2080
2081 a = self.A()
2082 res = []
2083 def callback():
2084 res.append(123)
2085 f = MyFinalizer(a, callback)
2086
2087 wr_callback = weakref.ref(callback)
2088 wr_f = weakref.ref(f)
2089 del callback, f
2090
2091 self.assertIsNotNone(wr_callback())
2092 self.assertIsNotNone(wr_f())
2093
2094 del a
2095 self._collect_if_necessary()
2096
2097 self.assertIsNone(wr_callback())
2098 self.assertIsNone(wr_f())
2099 self.assertEqual(res, [123])
2100
2101 @classmethod
2102 def run_in_child(cls):
2103 def error():
2104 # Create an atexit finalizer from inside a finalizer called
2105 # at exit. This should be the next to be run.
2106 g1 = weakref.finalize(cls, print, 'g1')
2107 print('f3 error')
2108 1/0
2109
2110 # cls should stay alive till atexit callbacks run
2111 f1 = weakref.finalize(cls, print, 'f1', _global_var)
2112 f2 = weakref.finalize(cls, print, 'f2', _global_var)
2113 f3 = weakref.finalize(cls, error)
2114 f4 = weakref.finalize(cls, print, 'f4', _global_var)
2115
2116 assert f1.atexit == True
2117 f2.atexit = False
2118 assert f3.atexit == True
2119 assert f4.atexit == True
2120
2121 def test_atexit(self):
2122 prog = ('from test.test_weakref import FinalizeTestCase;'+
2123 'FinalizeTestCase.run_in_child()')
2124 rc, out, err = script_helper.assert_python_ok('-c', prog)
2125 out = out.decode('ascii').splitlines()
2126 self.assertEqual(out, ['f4 foobar', 'f3 error', 'g1', 'f1 foobar'])
2127 self.assertTrue(b'ZeroDivisionError' in err)
2128
2129
Georg Brandlb533e262008-05-25 18:19:30 +00002130libreftest = """ Doctest for examples in the library reference: weakref.rst
Georg Brandl9a65d582005-07-02 19:07:30 +00002131
2132>>> import weakref
2133>>> class Dict(dict):
2134... pass
2135...
2136>>> obj = Dict(red=1, green=2, blue=3) # this object is weak referencable
2137>>> r = weakref.ref(obj)
Guido van Rossum7131f842007-02-09 20:13:25 +00002138>>> print(r() is obj)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002139True
Georg Brandl9a65d582005-07-02 19:07:30 +00002140
2141>>> import weakref
2142>>> class Object:
2143... pass
2144...
2145>>> o = Object()
2146>>> r = weakref.ref(o)
2147>>> o2 = r()
2148>>> o is o2
2149True
2150>>> del o, o2
Guido van Rossum7131f842007-02-09 20:13:25 +00002151>>> print(r())
Georg Brandl9a65d582005-07-02 19:07:30 +00002152None
2153
2154>>> import weakref
2155>>> class ExtendedRef(weakref.ref):
2156... def __init__(self, ob, callback=None, **annotations):
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002157... super().__init__(ob, callback)
Georg Brandl9a65d582005-07-02 19:07:30 +00002158... self.__counter = 0
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002159... for k, v in annotations.items():
Georg Brandl9a65d582005-07-02 19:07:30 +00002160... setattr(self, k, v)
2161... def __call__(self):
2162... '''Return a pair containing the referent and the number of
2163... times the reference has been called.
2164... '''
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002165... ob = super().__call__()
Georg Brandl9a65d582005-07-02 19:07:30 +00002166... if ob is not None:
2167... self.__counter += 1
2168... ob = (ob, self.__counter)
2169... return ob
Guido van Rossumd8faa362007-04-27 19:54:29 +00002170...
Georg Brandl9a65d582005-07-02 19:07:30 +00002171>>> class A: # not in docs from here, just testing the ExtendedRef
2172... pass
2173...
2174>>> a = A()
2175>>> r = ExtendedRef(a, foo=1, bar="baz")
2176>>> r.foo
21771
2178>>> r.bar
2179'baz'
2180>>> r()[1]
21811
2182>>> r()[1]
21832
2184>>> r()[0] is a
2185True
2186
2187
2188>>> import weakref
2189>>> _id2obj_dict = weakref.WeakValueDictionary()
2190>>> def remember(obj):
2191... oid = id(obj)
2192... _id2obj_dict[oid] = obj
2193... return oid
2194...
2195>>> def id2obj(oid):
2196... return _id2obj_dict[oid]
2197...
2198>>> a = A() # from here, just testing
2199>>> a_id = remember(a)
2200>>> id2obj(a_id) is a
2201True
2202>>> del a
2203>>> try:
2204... id2obj(a_id)
2205... except KeyError:
Guido van Rossum7131f842007-02-09 20:13:25 +00002206... print('OK')
Georg Brandl9a65d582005-07-02 19:07:30 +00002207... else:
Guido van Rossum7131f842007-02-09 20:13:25 +00002208... print('WeakValueDictionary error')
Georg Brandl9a65d582005-07-02 19:07:30 +00002209OK
2210
2211"""
2212
2213__test__ = {'libreftest' : libreftest}
2214
Fred Drake2e2be372001-09-20 21:33:42 +00002215def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002216 support.run_unittest(
Walter Dörwald21d3a322003-05-01 17:45:56 +00002217 ReferencesTestCase,
Antoine Pitrouc3afba12012-11-17 18:57:38 +01002218 WeakMethodTestCase,
Walter Dörwald21d3a322003-05-01 17:45:56 +00002219 MappingTestCase,
2220 WeakValueDictionaryTestCase,
Fred Drakef425b1e2003-07-14 21:37:17 +00002221 WeakKeyDictionaryTestCase,
Amaury Forgeot d'Arcc856c7a2008-06-16 19:50:09 +00002222 SubclassableWeakrefTestCase,
Richard Oudkerk7a3dae02013-05-05 23:05:00 +01002223 FinalizeTestCase,
Fred Drakef425b1e2003-07-14 21:37:17 +00002224 )
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002225 support.run_doctest(sys.modules[__name__])
Fred Drake2e2be372001-09-20 21:33:42 +00002226
2227
2228if __name__ == "__main__":
2229 test_main()