blob: e14df9ea089427957994aefd3a4974f3da329aaf [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
Fred Drakeb0fefc52001-03-23 04:22:45 +0000394 def test_getweakrefcount(self):
395 o = C()
396 ref1 = weakref.ref(o)
397 ref2 = weakref.ref(o, self.callback)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200398 self.assertEqual(weakref.getweakrefcount(o), 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000399 "got wrong number of weak reference objects")
400
401 proxy1 = weakref.proxy(o)
402 proxy2 = weakref.proxy(o, self.callback)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200403 self.assertEqual(weakref.getweakrefcount(o), 4,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000404 "got wrong number of weak reference objects")
405
Fred Drakeea2adc92004-02-03 19:56:46 +0000406 del ref1, ref2, proxy1, proxy2
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200407 self.assertEqual(weakref.getweakrefcount(o), 0,
Fred Drakeea2adc92004-02-03 19:56:46 +0000408 "weak reference objects not unlinked from"
409 " referent when discarded.")
410
Walter Dörwaldb167b042003-12-11 12:34:05 +0000411 # assumes ints do not support weakrefs
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200412 self.assertEqual(weakref.getweakrefcount(1), 0,
Walter Dörwaldb167b042003-12-11 12:34:05 +0000413 "got wrong number of weak reference objects for int")
414
Fred Drakeb0fefc52001-03-23 04:22:45 +0000415 def test_getweakrefs(self):
416 o = C()
417 ref1 = weakref.ref(o, self.callback)
418 ref2 = weakref.ref(o, self.callback)
419 del ref1
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200420 self.assertEqual(weakref.getweakrefs(o), [ref2],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000421 "list of refs does not match")
422
423 o = C()
424 ref1 = weakref.ref(o, self.callback)
425 ref2 = weakref.ref(o, self.callback)
426 del ref2
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200427 self.assertEqual(weakref.getweakrefs(o), [ref1],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000428 "list of refs does not match")
429
Fred Drakeea2adc92004-02-03 19:56:46 +0000430 del ref1
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200431 self.assertEqual(weakref.getweakrefs(o), [],
Fred Drakeea2adc92004-02-03 19:56:46 +0000432 "list of refs not cleared")
433
Walter Dörwaldb167b042003-12-11 12:34:05 +0000434 # assumes ints do not support weakrefs
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200435 self.assertEqual(weakref.getweakrefs(1), [],
Walter Dörwaldb167b042003-12-11 12:34:05 +0000436 "list of refs does not match for int")
437
Fred Drake39c27f12001-10-18 18:06:05 +0000438 def test_newstyle_number_ops(self):
439 class F(float):
440 pass
441 f = F(2.0)
442 p = weakref.proxy(f)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200443 self.assertEqual(p + 1.0, 3.0)
444 self.assertEqual(1.0 + p, 3.0) # this used to SEGV
Fred Drake39c27f12001-10-18 18:06:05 +0000445
Fred Drake2a64f462001-12-10 23:46:02 +0000446 def test_callbacks_protected(self):
Guido van Rossum9eee5542002-08-22 20:21:30 +0000447 # Callbacks protected from already-set exceptions?
Fred Drake2a64f462001-12-10 23:46:02 +0000448 # Regression test for SF bug #478534.
449 class BogusError(Exception):
450 pass
451 data = {}
452 def remove(k):
453 del data[k]
454 def encapsulate():
455 f = lambda : ()
456 data[weakref.ref(f, remove)] = None
457 raise BogusError
458 try:
459 encapsulate()
460 except BogusError:
461 pass
462 else:
463 self.fail("exception not properly restored")
464 try:
465 encapsulate()
466 except BogusError:
467 pass
468 else:
469 self.fail("exception not properly restored")
470
Tim Petersadd09b42003-11-12 20:43:28 +0000471 def test_sf_bug_840829(self):
472 # "weakref callbacks and gc corrupt memory"
473 # subtype_dealloc erroneously exposed a new-style instance
474 # already in the process of getting deallocated to gc,
475 # causing double-deallocation if the instance had a weakref
476 # callback that triggered gc.
477 # If the bug exists, there probably won't be an obvious symptom
478 # in a release build. In a debug build, a segfault will occur
479 # when the second attempt to remove the instance from the "list
480 # of all objects" occurs.
481
482 import gc
483
484 class C(object):
485 pass
486
487 c = C()
488 wr = weakref.ref(c, lambda ignore: gc.collect())
489 del c
490
Tim Petersf7f9e992003-11-13 21:59:32 +0000491 # There endeth the first part. It gets worse.
492 del wr
493
494 c1 = C()
495 c1.i = C()
496 wr = weakref.ref(c1.i, lambda ignore: gc.collect())
497
498 c2 = C()
499 c2.c1 = c1
500 del c1 # still alive because c2 points to it
501
502 # Now when subtype_dealloc gets called on c2, it's not enough just
503 # that c2 is immune from gc while the weakref callbacks associated
504 # with c2 execute (there are none in this 2nd half of the test, btw).
505 # subtype_dealloc goes on to call the base classes' deallocs too,
506 # so any gc triggered by weakref callbacks associated with anything
507 # torn down by a base class dealloc can also trigger double
508 # deallocation of c2.
509 del c2
Fred Drake41deb1e2001-02-01 05:27:45 +0000510
Tim Peters403a2032003-11-20 21:21:46 +0000511 def test_callback_in_cycle_1(self):
512 import gc
513
514 class J(object):
515 pass
516
517 class II(object):
518 def acallback(self, ignore):
519 self.J
520
521 I = II()
522 I.J = J
523 I.wr = weakref.ref(J, I.acallback)
524
525 # Now J and II are each in a self-cycle (as all new-style class
526 # objects are, since their __mro__ points back to them). I holds
527 # both a weak reference (I.wr) and a strong reference (I.J) to class
528 # J. I is also in a cycle (I.wr points to a weakref that references
529 # I.acallback). When we del these three, they all become trash, but
530 # the cycles prevent any of them from getting cleaned up immediately.
531 # Instead they have to wait for cyclic gc to deduce that they're
532 # trash.
533 #
534 # gc used to call tp_clear on all of them, and the order in which
535 # it does that is pretty accidental. The exact order in which we
536 # built up these things manages to provoke gc into running tp_clear
537 # in just the right order (I last). Calling tp_clear on II leaves
538 # behind an insane class object (its __mro__ becomes NULL). Calling
539 # tp_clear on J breaks its self-cycle, but J doesn't get deleted
540 # just then because of the strong reference from I.J. Calling
541 # tp_clear on I starts to clear I's __dict__, and just happens to
542 # clear I.J first -- I.wr is still intact. That removes the last
543 # reference to J, which triggers the weakref callback. The callback
544 # tries to do "self.J", and instances of new-style classes look up
545 # attributes ("J") in the class dict first. The class (II) wants to
546 # search II.__mro__, but that's NULL. The result was a segfault in
547 # a release build, and an assert failure in a debug build.
548 del I, J, II
549 gc.collect()
550
551 def test_callback_in_cycle_2(self):
552 import gc
553
554 # This is just like test_callback_in_cycle_1, except that II is an
555 # old-style class. The symptom is different then: an instance of an
556 # old-style class looks in its own __dict__ first. 'J' happens to
557 # get cleared from I.__dict__ before 'wr', and 'J' was never in II's
558 # __dict__, so the attribute isn't found. The difference is that
559 # the old-style II doesn't have a NULL __mro__ (it doesn't have any
560 # __mro__), so no segfault occurs. Instead it got:
561 # test_callback_in_cycle_2 (__main__.ReferencesTestCase) ...
562 # Exception exceptions.AttributeError:
563 # "II instance has no attribute 'J'" in <bound method II.acallback
564 # of <?.II instance at 0x00B9B4B8>> ignored
565
566 class J(object):
567 pass
568
569 class II:
570 def acallback(self, ignore):
571 self.J
572
573 I = II()
574 I.J = J
575 I.wr = weakref.ref(J, I.acallback)
576
577 del I, J, II
578 gc.collect()
579
580 def test_callback_in_cycle_3(self):
581 import gc
582
583 # This one broke the first patch that fixed the last two. In this
584 # case, the objects reachable from the callback aren't also reachable
585 # from the object (c1) *triggering* the callback: you can get to
586 # c1 from c2, but not vice-versa. The result was that c2's __dict__
587 # got tp_clear'ed by the time the c2.cb callback got invoked.
588
589 class C:
590 def cb(self, ignore):
591 self.me
592 self.c1
593 self.wr
594
595 c1, c2 = C(), C()
596
597 c2.me = c2
598 c2.c1 = c1
599 c2.wr = weakref.ref(c1, c2.cb)
600
601 del c1, c2
602 gc.collect()
603
604 def test_callback_in_cycle_4(self):
605 import gc
606
607 # Like test_callback_in_cycle_3, except c2 and c1 have different
608 # classes. c2's class (C) isn't reachable from c1 then, so protecting
609 # objects reachable from the dying object (c1) isn't enough to stop
610 # c2's class (C) from getting tp_clear'ed before c2.cb is invoked.
611 # The result was a segfault (C.__mro__ was NULL when the callback
612 # tried to look up self.me).
613
614 class C(object):
615 def cb(self, ignore):
616 self.me
617 self.c1
618 self.wr
619
620 class D:
621 pass
622
623 c1, c2 = D(), C()
624
625 c2.me = c2
626 c2.c1 = c1
627 c2.wr = weakref.ref(c1, c2.cb)
628
629 del c1, c2, C, D
630 gc.collect()
631
Serhiy Storchakaa7930372016-07-03 22:27:26 +0300632 @support.requires_type_collecting
Tim Peters403a2032003-11-20 21:21:46 +0000633 def test_callback_in_cycle_resurrection(self):
634 import gc
635
636 # Do something nasty in a weakref callback: resurrect objects
637 # from dead cycles. For this to be attempted, the weakref and
638 # its callback must also be part of the cyclic trash (else the
639 # objects reachable via the callback couldn't be in cyclic trash
640 # to begin with -- the callback would act like an external root).
641 # But gc clears trash weakrefs with callbacks early now, which
642 # disables the callbacks, so the callbacks shouldn't get called
643 # at all (and so nothing actually gets resurrected).
644
645 alist = []
646 class C(object):
647 def __init__(self, value):
648 self.attribute = value
649
650 def acallback(self, ignore):
651 alist.append(self.c)
652
653 c1, c2 = C(1), C(2)
654 c1.c = c2
655 c2.c = c1
656 c1.wr = weakref.ref(c2, c1.acallback)
657 c2.wr = weakref.ref(c1, c2.acallback)
658
659 def C_went_away(ignore):
660 alist.append("C went away")
661 wr = weakref.ref(C, C_went_away)
662
663 del c1, c2, C # make them all trash
664 self.assertEqual(alist, []) # del isn't enough to reclaim anything
665
666 gc.collect()
667 # c1.wr and c2.wr were part of the cyclic trash, so should have
668 # been cleared without their callbacks executing. OTOH, the weakref
669 # to C is bound to a function local (wr), and wasn't trash, so that
670 # callback should have been invoked when C went away.
671 self.assertEqual(alist, ["C went away"])
672 # The remaining weakref should be dead now (its callback ran).
673 self.assertEqual(wr(), None)
674
675 del alist[:]
676 gc.collect()
677 self.assertEqual(alist, [])
678
679 def test_callbacks_on_callback(self):
680 import gc
681
682 # Set up weakref callbacks *on* weakref callbacks.
683 alist = []
684 def safe_callback(ignore):
685 alist.append("safe_callback called")
686
687 class C(object):
688 def cb(self, ignore):
689 alist.append("cb called")
690
691 c, d = C(), C()
692 c.other = d
693 d.other = c
694 callback = c.cb
695 c.wr = weakref.ref(d, callback) # this won't trigger
696 d.wr = weakref.ref(callback, d.cb) # ditto
697 external_wr = weakref.ref(callback, safe_callback) # but this will
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200698 self.assertIs(external_wr(), callback)
Tim Peters403a2032003-11-20 21:21:46 +0000699
700 # The weakrefs attached to c and d should get cleared, so that
701 # C.cb is never called. But external_wr isn't part of the cyclic
702 # trash, and no cyclic trash is reachable from it, so safe_callback
703 # should get invoked when the bound method object callback (c.cb)
704 # -- which is itself a callback, and also part of the cyclic trash --
705 # gets reclaimed at the end of gc.
706
707 del callback, c, d, C
708 self.assertEqual(alist, []) # del isn't enough to clean up cycles
709 gc.collect()
710 self.assertEqual(alist, ["safe_callback called"])
711 self.assertEqual(external_wr(), None)
712
713 del alist[:]
714 gc.collect()
715 self.assertEqual(alist, [])
716
Fred Drakebc875f52004-02-04 23:14:14 +0000717 def test_gc_during_ref_creation(self):
718 self.check_gc_during_creation(weakref.ref)
719
720 def test_gc_during_proxy_creation(self):
721 self.check_gc_during_creation(weakref.proxy)
722
723 def check_gc_during_creation(self, makeref):
724 thresholds = gc.get_threshold()
725 gc.set_threshold(1, 1, 1)
726 gc.collect()
Fred Drake55cf4342004-02-13 19:21:57 +0000727 class A:
728 pass
Fred Drakebc875f52004-02-04 23:14:14 +0000729
730 def callback(*args):
731 pass
732
Fred Drake55cf4342004-02-13 19:21:57 +0000733 referenced = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000734
Fred Drake55cf4342004-02-13 19:21:57 +0000735 a = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000736 a.a = a
737 a.wr = makeref(referenced)
738
739 try:
740 # now make sure the object and the ref get labeled as
741 # cyclic trash:
Fred Drake55cf4342004-02-13 19:21:57 +0000742 a = A()
743 weakref.ref(referenced, callback)
Fred Drakebc875f52004-02-04 23:14:14 +0000744
745 finally:
746 gc.set_threshold(*thresholds)
747
Thomas Woutersb2137042007-02-01 18:02:27 +0000748 def test_ref_created_during_del(self):
749 # Bug #1377858
750 # A weakref created in an object's __del__() would crash the
751 # interpreter when the weakref was cleaned up since it would refer to
752 # non-existent memory. This test should not segfault the interpreter.
753 class Target(object):
754 def __del__(self):
755 global ref_from_del
756 ref_from_del = weakref.ref(self)
757
758 w = Target()
759
Benjamin Peterson9aa42992008-09-10 21:57:34 +0000760 def test_init(self):
761 # Issue 3634
762 # <weakref to class>.__init__() doesn't check errors correctly
763 r = weakref.ref(Exception)
764 self.assertRaises(TypeError, r.__init__, 0, 0, 0, 0, 0)
765 # No exception should be raised here
766 gc.collect()
767
Antoine Pitrou3af01a12010-03-31 21:40:47 +0000768 def test_classes(self):
769 # Check that classes are weakrefable.
770 class A(object):
771 pass
772 l = []
773 weakref.ref(int)
774 a = weakref.ref(A, l.append)
775 A = None
776 gc.collect()
777 self.assertEqual(a(), None)
778 self.assertEqual(l, [a])
779
Antoine Pitroue11fecb2012-11-11 19:36:51 +0100780 def test_equality(self):
781 # Alive weakrefs defer equality testing to their underlying object.
782 x = Object(1)
783 y = Object(1)
784 z = Object(2)
785 a = weakref.ref(x)
786 b = weakref.ref(y)
787 c = weakref.ref(z)
788 d = weakref.ref(x)
789 # Note how we directly test the operators here, to stress both
790 # __eq__ and __ne__.
791 self.assertTrue(a == b)
792 self.assertFalse(a != b)
793 self.assertFalse(a == c)
794 self.assertTrue(a != c)
795 self.assertTrue(a == d)
796 self.assertFalse(a != d)
Serhiy Storchaka662db122019-08-08 08:42:54 +0300797 self.assertFalse(a == x)
798 self.assertTrue(a != x)
799 self.assertTrue(a == ALWAYS_EQ)
800 self.assertFalse(a != ALWAYS_EQ)
Antoine Pitroue11fecb2012-11-11 19:36:51 +0100801 del x, y, z
802 gc.collect()
803 for r in a, b, c:
804 # Sanity check
805 self.assertIs(r(), None)
806 # Dead weakrefs compare by identity: whether `a` and `d` are the
807 # same weakref object is an implementation detail, since they pointed
808 # to the same original object and didn't have a callback.
809 # (see issue #16453).
810 self.assertFalse(a == b)
811 self.assertTrue(a != b)
812 self.assertFalse(a == c)
813 self.assertTrue(a != c)
814 self.assertEqual(a == d, a is d)
815 self.assertEqual(a != d, a is not d)
816
817 def test_ordering(self):
818 # weakrefs cannot be ordered, even if the underlying objects can.
819 ops = [operator.lt, operator.gt, operator.le, operator.ge]
820 x = Object(1)
821 y = Object(1)
822 a = weakref.ref(x)
823 b = weakref.ref(y)
824 for op in ops:
825 self.assertRaises(TypeError, op, a, b)
826 # Same when dead.
827 del x, y
828 gc.collect()
829 for op in ops:
830 self.assertRaises(TypeError, op, a, b)
831
832 def test_hashing(self):
833 # Alive weakrefs hash the same as the underlying object
834 x = Object(42)
835 y = Object(42)
836 a = weakref.ref(x)
837 b = weakref.ref(y)
838 self.assertEqual(hash(a), hash(42))
839 del x, y
840 gc.collect()
841 # Dead weakrefs:
842 # - retain their hash is they were hashed when alive;
843 # - otherwise, cannot be hashed.
844 self.assertEqual(hash(a), hash(42))
845 self.assertRaises(TypeError, hash, b)
846
Antoine Pitrou62a0d6e2012-12-08 21:15:26 +0100847 def test_trashcan_16602(self):
848 # Issue #16602: when a weakref's target was part of a long
849 # deallocation chain, the trashcan mechanism could delay clearing
850 # of the weakref and make the target object visible from outside
851 # code even though its refcount had dropped to 0. A crash ensued.
852 class C:
853 def __init__(self, parent):
854 if not parent:
855 return
856 wself = weakref.ref(self)
857 def cb(wparent):
858 o = wself()
859 self.wparent = weakref.ref(parent, cb)
860
861 d = weakref.WeakKeyDictionary()
862 root = c = C(None)
863 for n in range(100):
864 d[c] = c = C(c)
865 del root
866 gc.collect()
867
Mark Dickinson556e94b2013-04-13 15:45:44 +0100868 def test_callback_attribute(self):
869 x = Object(1)
870 callback = lambda ref: None
871 ref1 = weakref.ref(x, callback)
872 self.assertIs(ref1.__callback__, callback)
873
874 ref2 = weakref.ref(x)
875 self.assertIsNone(ref2.__callback__)
876
877 def test_callback_attribute_after_deletion(self):
878 x = Object(1)
879 ref = weakref.ref(x, self.callback)
880 self.assertIsNotNone(ref.__callback__)
881 del x
882 support.gc_collect()
883 self.assertIsNone(ref.__callback__)
884
885 def test_set_callback_attribute(self):
886 x = Object(1)
887 callback = lambda ref: None
888 ref1 = weakref.ref(x, callback)
889 with self.assertRaises(AttributeError):
890 ref1.__callback__ = lambda ref: None
891
Benjamin Peterson8f657c32016-10-04 00:00:02 -0700892 def test_callback_gcs(self):
893 class ObjectWithDel(Object):
894 def __del__(self): pass
895 x = ObjectWithDel(1)
896 ref1 = weakref.ref(x, lambda ref: support.gc_collect())
897 del x
898 support.gc_collect()
899
Fred Drake0a4dd392004-07-02 18:57:45 +0000900
Amaury Forgeot d'Arcc856c7a2008-06-16 19:50:09 +0000901class SubclassableWeakrefTestCase(TestBase):
Fred Drake0a4dd392004-07-02 18:57:45 +0000902
903 def test_subclass_refs(self):
904 class MyRef(weakref.ref):
905 def __init__(self, ob, callback=None, value=42):
906 self.value = value
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000907 super().__init__(ob, callback)
Fred Drake0a4dd392004-07-02 18:57:45 +0000908 def __call__(self):
909 self.called = True
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000910 return super().__call__()
Fred Drake0a4dd392004-07-02 18:57:45 +0000911 o = Object("foo")
912 mr = MyRef(o, value=24)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200913 self.assertIs(mr(), o)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000914 self.assertTrue(mr.called)
Fred Drake0a4dd392004-07-02 18:57:45 +0000915 self.assertEqual(mr.value, 24)
916 del o
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200917 self.assertIsNone(mr())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000918 self.assertTrue(mr.called)
Fred Drake0a4dd392004-07-02 18:57:45 +0000919
920 def test_subclass_refs_dont_replace_standard_refs(self):
921 class MyRef(weakref.ref):
922 pass
923 o = Object(42)
924 r1 = MyRef(o)
925 r2 = weakref.ref(o)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200926 self.assertIsNot(r1, r2)
Fred Drake0a4dd392004-07-02 18:57:45 +0000927 self.assertEqual(weakref.getweakrefs(o), [r2, r1])
928 self.assertEqual(weakref.getweakrefcount(o), 2)
929 r3 = MyRef(o)
930 self.assertEqual(weakref.getweakrefcount(o), 3)
931 refs = weakref.getweakrefs(o)
932 self.assertEqual(len(refs), 3)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200933 self.assertIs(r2, refs[0])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000934 self.assertIn(r1, refs[1:])
935 self.assertIn(r3, refs[1:])
Fred Drake0a4dd392004-07-02 18:57:45 +0000936
937 def test_subclass_refs_dont_conflate_callbacks(self):
938 class MyRef(weakref.ref):
939 pass
940 o = Object(42)
941 r1 = MyRef(o, id)
942 r2 = MyRef(o, str)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200943 self.assertIsNot(r1, r2)
Fred Drake0a4dd392004-07-02 18:57:45 +0000944 refs = weakref.getweakrefs(o)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000945 self.assertIn(r1, refs)
946 self.assertIn(r2, refs)
Fred Drake0a4dd392004-07-02 18:57:45 +0000947
948 def test_subclass_refs_with_slots(self):
949 class MyRef(weakref.ref):
950 __slots__ = "slot1", "slot2"
951 def __new__(type, ob, callback, slot1, slot2):
952 return weakref.ref.__new__(type, ob, callback)
953 def __init__(self, ob, callback, slot1, slot2):
954 self.slot1 = slot1
955 self.slot2 = slot2
956 def meth(self):
957 return self.slot1 + self.slot2
958 o = Object(42)
959 r = MyRef(o, None, "abc", "def")
960 self.assertEqual(r.slot1, "abc")
961 self.assertEqual(r.slot2, "def")
962 self.assertEqual(r.meth(), "abcdef")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000963 self.assertFalse(hasattr(r, "__dict__"))
Fred Drake0a4dd392004-07-02 18:57:45 +0000964
Amaury Forgeot d'Arcc856c7a2008-06-16 19:50:09 +0000965 def test_subclass_refs_with_cycle(self):
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)cd14d5d2016-09-07 00:22:22 +0000966 """Confirm https://bugs.python.org/issue3100 is fixed."""
Amaury Forgeot d'Arcc856c7a2008-06-16 19:50:09 +0000967 # An instance of a weakref subclass can have attributes.
968 # If such a weakref holds the only strong reference to the object,
969 # deleting the weakref will delete the object. In this case,
970 # the callback must not be called, because the ref object is
971 # being deleted.
972 class MyRef(weakref.ref):
973 pass
974
975 # Use a local callback, for "regrtest -R::"
976 # to detect refcounting problems
977 def callback(w):
978 self.cbcalled += 1
979
980 o = C()
981 r1 = MyRef(o, callback)
982 r1.o = o
983 del o
984
985 del r1 # Used to crash here
986
987 self.assertEqual(self.cbcalled, 0)
988
989 # Same test, with two weakrefs to the same object
990 # (since code paths are different)
991 o = C()
992 r1 = MyRef(o, callback)
993 r2 = MyRef(o, callback)
994 r1.r = r2
995 r2.o = o
996 del o
997 del r2
998
999 del r1 # Used to crash here
1000
1001 self.assertEqual(self.cbcalled, 0)
1002
Fred Drake0a4dd392004-07-02 18:57:45 +00001003
Antoine Pitrouc3afba12012-11-17 18:57:38 +01001004class WeakMethodTestCase(unittest.TestCase):
1005
1006 def _subclass(self):
Martin Panter7462b6492015-11-02 03:37:02 +00001007 """Return an Object subclass overriding `some_method`."""
Antoine Pitrouc3afba12012-11-17 18:57:38 +01001008 class C(Object):
1009 def some_method(self):
1010 return 6
1011 return C
1012
1013 def test_alive(self):
1014 o = Object(1)
1015 r = weakref.WeakMethod(o.some_method)
1016 self.assertIsInstance(r, weakref.ReferenceType)
1017 self.assertIsInstance(r(), type(o.some_method))
1018 self.assertIs(r().__self__, o)
1019 self.assertIs(r().__func__, o.some_method.__func__)
1020 self.assertEqual(r()(), 4)
1021
1022 def test_object_dead(self):
1023 o = Object(1)
1024 r = weakref.WeakMethod(o.some_method)
1025 del o
1026 gc.collect()
1027 self.assertIs(r(), None)
1028
1029 def test_method_dead(self):
1030 C = self._subclass()
1031 o = C(1)
1032 r = weakref.WeakMethod(o.some_method)
1033 del C.some_method
1034 gc.collect()
1035 self.assertIs(r(), None)
1036
1037 def test_callback_when_object_dead(self):
1038 # Test callback behaviour when object dies first.
1039 C = self._subclass()
1040 calls = []
1041 def cb(arg):
1042 calls.append(arg)
1043 o = C(1)
1044 r = weakref.WeakMethod(o.some_method, cb)
1045 del o
1046 gc.collect()
1047 self.assertEqual(calls, [r])
1048 # Callback is only called once.
1049 C.some_method = Object.some_method
1050 gc.collect()
1051 self.assertEqual(calls, [r])
1052
1053 def test_callback_when_method_dead(self):
1054 # Test callback behaviour when method dies first.
1055 C = self._subclass()
1056 calls = []
1057 def cb(arg):
1058 calls.append(arg)
1059 o = C(1)
1060 r = weakref.WeakMethod(o.some_method, cb)
1061 del C.some_method
1062 gc.collect()
1063 self.assertEqual(calls, [r])
1064 # Callback is only called once.
1065 del o
1066 gc.collect()
1067 self.assertEqual(calls, [r])
1068
1069 @support.cpython_only
1070 def test_no_cycles(self):
1071 # A WeakMethod doesn't create any reference cycle to itself.
1072 o = Object(1)
1073 def cb(_):
1074 pass
1075 r = weakref.WeakMethod(o.some_method, cb)
1076 wr = weakref.ref(r)
1077 del r
1078 self.assertIs(wr(), None)
1079
1080 def test_equality(self):
1081 def _eq(a, b):
1082 self.assertTrue(a == b)
1083 self.assertFalse(a != b)
1084 def _ne(a, b):
1085 self.assertTrue(a != b)
1086 self.assertFalse(a == b)
1087 x = Object(1)
1088 y = Object(1)
1089 a = weakref.WeakMethod(x.some_method)
1090 b = weakref.WeakMethod(y.some_method)
1091 c = weakref.WeakMethod(x.other_method)
1092 d = weakref.WeakMethod(y.other_method)
1093 # Objects equal, same method
1094 _eq(a, b)
1095 _eq(c, d)
1096 # Objects equal, different method
1097 _ne(a, c)
1098 _ne(a, d)
1099 _ne(b, c)
1100 _ne(b, d)
1101 # Objects unequal, same or different method
1102 z = Object(2)
1103 e = weakref.WeakMethod(z.some_method)
1104 f = weakref.WeakMethod(z.other_method)
1105 _ne(a, e)
1106 _ne(a, f)
1107 _ne(b, e)
1108 _ne(b, f)
Serhiy Storchaka662db122019-08-08 08:42:54 +03001109 # Compare with different types
1110 _ne(a, x.some_method)
1111 _eq(a, ALWAYS_EQ)
Antoine Pitrouc3afba12012-11-17 18:57:38 +01001112 del x, y, z
1113 gc.collect()
1114 # Dead WeakMethods compare by identity
1115 refs = a, b, c, d, e, f
1116 for q in refs:
1117 for r in refs:
1118 self.assertEqual(q == r, q is r)
1119 self.assertEqual(q != r, q is not r)
1120
1121 def test_hashing(self):
1122 # Alive WeakMethods are hashable if the underlying object is
1123 # hashable.
1124 x = Object(1)
1125 y = Object(1)
1126 a = weakref.WeakMethod(x.some_method)
1127 b = weakref.WeakMethod(y.some_method)
1128 c = weakref.WeakMethod(y.other_method)
1129 # Since WeakMethod objects are equal, the hashes should be equal.
1130 self.assertEqual(hash(a), hash(b))
1131 ha = hash(a)
1132 # Dead WeakMethods retain their old hash value
1133 del x, y
1134 gc.collect()
1135 self.assertEqual(hash(a), ha)
1136 self.assertEqual(hash(b), ha)
1137 # If it wasn't hashed when alive, a dead WeakMethod cannot be hashed.
1138 self.assertRaises(TypeError, hash, c)
1139
1140
Fred Drakeb0fefc52001-03-23 04:22:45 +00001141class MappingTestCase(TestBase):
Martin v. Löwis5e163332001-02-27 18:36:56 +00001142
Fred Drakeb0fefc52001-03-23 04:22:45 +00001143 COUNT = 10
1144
Antoine Pitroubbe2f602012-03-01 16:26:35 +01001145 def check_len_cycles(self, dict_type, cons):
1146 N = 20
1147 items = [RefCycle() for i in range(N)]
1148 dct = dict_type(cons(o) for o in items)
1149 # Keep an iterator alive
1150 it = dct.items()
1151 try:
1152 next(it)
1153 except StopIteration:
1154 pass
1155 del items
1156 gc.collect()
1157 n1 = len(dct)
1158 del it
1159 gc.collect()
1160 n2 = len(dct)
1161 # one item may be kept alive inside the iterator
1162 self.assertIn(n1, (0, 1))
1163 self.assertEqual(n2, 0)
1164
1165 def test_weak_keyed_len_cycles(self):
1166 self.check_len_cycles(weakref.WeakKeyDictionary, lambda k: (k, 1))
1167
1168 def test_weak_valued_len_cycles(self):
1169 self.check_len_cycles(weakref.WeakValueDictionary, lambda k: (1, k))
1170
1171 def check_len_race(self, dict_type, cons):
1172 # Extended sanity checks for len() in the face of cyclic collection
1173 self.addCleanup(gc.set_threshold, *gc.get_threshold())
1174 for th in range(1, 100):
1175 N = 20
1176 gc.collect(0)
1177 gc.set_threshold(th, th, th)
1178 items = [RefCycle() for i in range(N)]
1179 dct = dict_type(cons(o) for o in items)
1180 del items
1181 # All items will be collected at next garbage collection pass
1182 it = dct.items()
1183 try:
1184 next(it)
1185 except StopIteration:
1186 pass
1187 n1 = len(dct)
1188 del it
1189 n2 = len(dct)
1190 self.assertGreaterEqual(n1, 0)
1191 self.assertLessEqual(n1, N)
1192 self.assertGreaterEqual(n2, 0)
1193 self.assertLessEqual(n2, n1)
1194
1195 def test_weak_keyed_len_race(self):
1196 self.check_len_race(weakref.WeakKeyDictionary, lambda k: (k, 1))
1197
1198 def test_weak_valued_len_race(self):
1199 self.check_len_race(weakref.WeakValueDictionary, lambda k: (1, k))
1200
Fred Drakeb0fefc52001-03-23 04:22:45 +00001201 def test_weak_values(self):
Fred Drake0e540c32001-05-02 05:44:22 +00001202 #
1203 # This exercises d.copy(), d.items(), d[], del d[], len(d).
1204 #
1205 dict, objects = self.make_weak_valued_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +00001206 for o in objects:
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001207 self.assertEqual(weakref.getweakrefcount(o), 1)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001208 self.assertIs(o, dict[o.arg],
Fred Drakeb0fefc52001-03-23 04:22:45 +00001209 "wrong object returned by weak dict!")
Barry Warsawecaab832008-09-04 01:42:51 +00001210 items1 = list(dict.items())
1211 items2 = list(dict.copy().items())
Fred Drakeb0fefc52001-03-23 04:22:45 +00001212 items1.sort()
1213 items2.sort()
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001214 self.assertEqual(items1, items2,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001215 "cloning of weak-valued dictionary did not work!")
1216 del items1, items2
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001217 self.assertEqual(len(dict), self.COUNT)
Fred Drakeb0fefc52001-03-23 04:22:45 +00001218 del objects[0]
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001219 self.assertEqual(len(dict), self.COUNT - 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001220 "deleting object did not cause dictionary update")
1221 del objects, o
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001222 self.assertEqual(len(dict), 0,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001223 "deleting the values did not clear the dictionary")
Fred Drake4fd06e02001-08-03 04:11:27 +00001224 # regression on SF bug #447152:
1225 dict = weakref.WeakValueDictionary()
1226 self.assertRaises(KeyError, dict.__getitem__, 1)
1227 dict[2] = C()
1228 self.assertRaises(KeyError, dict.__getitem__, 2)
Fred Drakeb0fefc52001-03-23 04:22:45 +00001229
1230 def test_weak_keys(self):
Fred Drake0e540c32001-05-02 05:44:22 +00001231 #
1232 # This exercises d.copy(), d.items(), d[] = v, d[], del d[],
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001233 # len(d), k in d.
Fred Drake0e540c32001-05-02 05:44:22 +00001234 #
1235 dict, objects = self.make_weak_keyed_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +00001236 for o in objects:
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001237 self.assertEqual(weakref.getweakrefcount(o), 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001238 "wrong number of weak references to %r!" % o)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001239 self.assertIs(o.arg, dict[o],
Fred Drakeb0fefc52001-03-23 04:22:45 +00001240 "wrong object returned by weak dict!")
1241 items1 = dict.items()
1242 items2 = dict.copy().items()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001243 self.assertEqual(set(items1), set(items2),
Fred Drakeb0fefc52001-03-23 04:22:45 +00001244 "cloning of weak-keyed dictionary did not work!")
1245 del items1, items2
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001246 self.assertEqual(len(dict), self.COUNT)
Fred Drakeb0fefc52001-03-23 04:22:45 +00001247 del objects[0]
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001248 self.assertEqual(len(dict), (self.COUNT - 1),
Fred Drakeb0fefc52001-03-23 04:22:45 +00001249 "deleting object did not cause dictionary update")
1250 del objects, o
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001251 self.assertEqual(len(dict), 0,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001252 "deleting the keys did not clear the dictionary")
Fred Drake752eda42001-11-06 16:38:34 +00001253 o = Object(42)
1254 dict[o] = "What is the meaning of the universe?"
Benjamin Peterson577473f2010-01-19 00:09:57 +00001255 self.assertIn(o, dict)
1256 self.assertNotIn(34, dict)
Martin v. Löwis5e163332001-02-27 18:36:56 +00001257
Fred Drake0e540c32001-05-02 05:44:22 +00001258 def test_weak_keyed_iters(self):
1259 dict, objects = self.make_weak_keyed_dict()
1260 self.check_iters(dict)
1261
Thomas Wouters477c8d52006-05-27 19:21:47 +00001262 # Test keyrefs()
1263 refs = dict.keyrefs()
1264 self.assertEqual(len(refs), len(objects))
1265 objects2 = list(objects)
1266 for wr in refs:
1267 ob = wr()
Benjamin Peterson577473f2010-01-19 00:09:57 +00001268 self.assertIn(ob, dict)
1269 self.assertIn(ob, dict)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001270 self.assertEqual(ob.arg, dict[ob])
1271 objects2.remove(ob)
1272 self.assertEqual(len(objects2), 0)
1273
1274 # Test iterkeyrefs()
1275 objects2 = list(objects)
Barry Warsawecaab832008-09-04 01:42:51 +00001276 self.assertEqual(len(list(dict.keyrefs())), len(objects))
1277 for wr in dict.keyrefs():
Thomas Wouters477c8d52006-05-27 19:21:47 +00001278 ob = wr()
Benjamin Peterson577473f2010-01-19 00:09:57 +00001279 self.assertIn(ob, dict)
1280 self.assertIn(ob, dict)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001281 self.assertEqual(ob.arg, dict[ob])
1282 objects2.remove(ob)
1283 self.assertEqual(len(objects2), 0)
1284
Fred Drake0e540c32001-05-02 05:44:22 +00001285 def test_weak_valued_iters(self):
1286 dict, objects = self.make_weak_valued_dict()
1287 self.check_iters(dict)
1288
Thomas Wouters477c8d52006-05-27 19:21:47 +00001289 # Test valuerefs()
1290 refs = dict.valuerefs()
1291 self.assertEqual(len(refs), len(objects))
1292 objects2 = list(objects)
1293 for wr in refs:
1294 ob = wr()
1295 self.assertEqual(ob, dict[ob.arg])
1296 self.assertEqual(ob.arg, dict[ob.arg].arg)
1297 objects2.remove(ob)
1298 self.assertEqual(len(objects2), 0)
1299
1300 # Test itervaluerefs()
1301 objects2 = list(objects)
1302 self.assertEqual(len(list(dict.itervaluerefs())), len(objects))
1303 for wr in dict.itervaluerefs():
1304 ob = wr()
1305 self.assertEqual(ob, dict[ob.arg])
1306 self.assertEqual(ob.arg, dict[ob.arg].arg)
1307 objects2.remove(ob)
1308 self.assertEqual(len(objects2), 0)
1309
Fred Drake0e540c32001-05-02 05:44:22 +00001310 def check_iters(self, dict):
1311 # item iterator:
Barry Warsawecaab832008-09-04 01:42:51 +00001312 items = list(dict.items())
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001313 for item in dict.items():
Fred Drake0e540c32001-05-02 05:44:22 +00001314 items.remove(item)
Barry Warsawecaab832008-09-04 01:42:51 +00001315 self.assertFalse(items, "items() did not touch all items")
Fred Drake0e540c32001-05-02 05:44:22 +00001316
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001317 # key iterator, via __iter__():
Guido van Rossum07f24362007-02-11 22:59:48 +00001318 keys = list(dict.keys())
Fred Drake0e540c32001-05-02 05:44:22 +00001319 for k in dict:
1320 keys.remove(k)
Barry Warsawecaab832008-09-04 01:42:51 +00001321 self.assertFalse(keys, "__iter__() did not touch all keys")
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001322
1323 # key iterator, via iterkeys():
Guido van Rossum07f24362007-02-11 22:59:48 +00001324 keys = list(dict.keys())
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001325 for k in dict.keys():
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001326 keys.remove(k)
Barry Warsawecaab832008-09-04 01:42:51 +00001327 self.assertFalse(keys, "iterkeys() did not touch all keys")
Fred Drake0e540c32001-05-02 05:44:22 +00001328
1329 # value iterator:
Guido van Rossum07f24362007-02-11 22:59:48 +00001330 values = list(dict.values())
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001331 for v in dict.values():
Fred Drake0e540c32001-05-02 05:44:22 +00001332 values.remove(v)
Barry Warsawecaab832008-09-04 01:42:51 +00001333 self.assertFalse(values,
Fred Drakef425b1e2003-07-14 21:37:17 +00001334 "itervalues() did not touch all values")
Fred Drake0e540c32001-05-02 05:44:22 +00001335
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001336 def check_weak_destroy_while_iterating(self, dict, objects, iter_name):
1337 n = len(dict)
1338 it = iter(getattr(dict, iter_name)())
1339 next(it) # Trigger internal iteration
1340 # Destroy an object
1341 del objects[-1]
1342 gc.collect() # just in case
1343 # We have removed either the first consumed object, or another one
1344 self.assertIn(len(list(it)), [len(objects), len(objects) - 1])
1345 del it
1346 # The removal has been committed
1347 self.assertEqual(len(dict), n - 1)
1348
1349 def check_weak_destroy_and_mutate_while_iterating(self, dict, testcontext):
1350 # Check that we can explicitly mutate the weak dict without
1351 # interfering with delayed removal.
1352 # `testcontext` should create an iterator, destroy one of the
1353 # weakref'ed objects and then return a new key/value pair corresponding
1354 # to the destroyed object.
1355 with testcontext() as (k, v):
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001356 self.assertNotIn(k, dict)
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001357 with testcontext() as (k, v):
1358 self.assertRaises(KeyError, dict.__delitem__, k)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001359 self.assertNotIn(k, dict)
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001360 with testcontext() as (k, v):
1361 self.assertRaises(KeyError, dict.pop, k)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001362 self.assertNotIn(k, dict)
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001363 with testcontext() as (k, v):
1364 dict[k] = v
1365 self.assertEqual(dict[k], v)
1366 ddict = copy.copy(dict)
1367 with testcontext() as (k, v):
1368 dict.update(ddict)
1369 self.assertEqual(dict, ddict)
1370 with testcontext() as (k, v):
1371 dict.clear()
1372 self.assertEqual(len(dict), 0)
1373
Antoine Pitrou1bf974d2014-10-05 20:02:28 +02001374 def check_weak_del_and_len_while_iterating(self, dict, testcontext):
1375 # Check that len() works when both iterating and removing keys
1376 # explicitly through various means (.pop(), .clear()...), while
1377 # implicit mutation is deferred because an iterator is alive.
1378 # (each call to testcontext() should schedule one item for removal
1379 # for this test to work properly)
1380 o = Object(123456)
1381 with testcontext():
1382 n = len(dict)
Victor Stinner742da042016-09-07 17:40:12 -07001383 # Since underlaying dict is ordered, first item is popped
1384 dict.pop(next(dict.keys()))
Antoine Pitrou1bf974d2014-10-05 20:02:28 +02001385 self.assertEqual(len(dict), n - 1)
1386 dict[o] = o
1387 self.assertEqual(len(dict), n)
Victor Stinner742da042016-09-07 17:40:12 -07001388 # last item in objects is removed from dict in context shutdown
Antoine Pitrou1bf974d2014-10-05 20:02:28 +02001389 with testcontext():
1390 self.assertEqual(len(dict), n - 1)
Victor Stinner742da042016-09-07 17:40:12 -07001391 # Then, (o, o) is popped
1392 dict.popitem()
Antoine Pitrou1bf974d2014-10-05 20:02:28 +02001393 self.assertEqual(len(dict), n - 2)
1394 with testcontext():
1395 self.assertEqual(len(dict), n - 3)
1396 del dict[next(dict.keys())]
1397 self.assertEqual(len(dict), n - 4)
1398 with testcontext():
1399 self.assertEqual(len(dict), n - 5)
1400 dict.popitem()
1401 self.assertEqual(len(dict), n - 6)
1402 with testcontext():
1403 dict.clear()
1404 self.assertEqual(len(dict), 0)
1405 self.assertEqual(len(dict), 0)
1406
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001407 def test_weak_keys_destroy_while_iterating(self):
1408 # Issue #7105: iterators shouldn't crash when a key is implicitly removed
1409 dict, objects = self.make_weak_keyed_dict()
1410 self.check_weak_destroy_while_iterating(dict, objects, 'keys')
1411 self.check_weak_destroy_while_iterating(dict, objects, 'items')
1412 self.check_weak_destroy_while_iterating(dict, objects, 'values')
1413 self.check_weak_destroy_while_iterating(dict, objects, 'keyrefs')
1414 dict, objects = self.make_weak_keyed_dict()
1415 @contextlib.contextmanager
1416 def testcontext():
1417 try:
1418 it = iter(dict.items())
1419 next(it)
1420 # Schedule a key/value for removal and recreate it
1421 v = objects.pop().arg
1422 gc.collect() # just in case
1423 yield Object(v), v
1424 finally:
1425 it = None # should commit all removals
Benjamin Peterson18bb7022014-08-24 18:02:15 -05001426 gc.collect()
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001427 self.check_weak_destroy_and_mutate_while_iterating(dict, testcontext)
Antoine Pitrou1bf974d2014-10-05 20:02:28 +02001428 # Issue #21173: len() fragile when keys are both implicitly and
1429 # explicitly removed.
1430 dict, objects = self.make_weak_keyed_dict()
1431 self.check_weak_del_and_len_while_iterating(dict, testcontext)
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001432
1433 def test_weak_values_destroy_while_iterating(self):
1434 # Issue #7105: iterators shouldn't crash when a key is implicitly removed
1435 dict, objects = self.make_weak_valued_dict()
1436 self.check_weak_destroy_while_iterating(dict, objects, 'keys')
1437 self.check_weak_destroy_while_iterating(dict, objects, 'items')
1438 self.check_weak_destroy_while_iterating(dict, objects, 'values')
1439 self.check_weak_destroy_while_iterating(dict, objects, 'itervaluerefs')
1440 self.check_weak_destroy_while_iterating(dict, objects, 'valuerefs')
1441 dict, objects = self.make_weak_valued_dict()
1442 @contextlib.contextmanager
1443 def testcontext():
1444 try:
1445 it = iter(dict.items())
1446 next(it)
1447 # Schedule a key/value for removal and recreate it
1448 k = objects.pop().arg
1449 gc.collect() # just in case
1450 yield k, Object(k)
1451 finally:
1452 it = None # should commit all removals
Benjamin Peterson18bb7022014-08-24 18:02:15 -05001453 gc.collect()
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001454 self.check_weak_destroy_and_mutate_while_iterating(dict, testcontext)
Antoine Pitrou1bf974d2014-10-05 20:02:28 +02001455 dict, objects = self.make_weak_valued_dict()
1456 self.check_weak_del_and_len_while_iterating(dict, testcontext)
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001457
Guido van Rossum009afb72002-06-10 20:00:52 +00001458 def test_make_weak_keyed_dict_from_dict(self):
1459 o = Object(3)
1460 dict = weakref.WeakKeyDictionary({o:364})
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001461 self.assertEqual(dict[o], 364)
Guido van Rossum009afb72002-06-10 20:00:52 +00001462
1463 def test_make_weak_keyed_dict_from_weak_keyed_dict(self):
1464 o = Object(3)
1465 dict = weakref.WeakKeyDictionary({o:364})
1466 dict2 = weakref.WeakKeyDictionary(dict)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001467 self.assertEqual(dict[o], 364)
Guido van Rossum009afb72002-06-10 20:00:52 +00001468
Fred Drake0e540c32001-05-02 05:44:22 +00001469 def make_weak_keyed_dict(self):
1470 dict = weakref.WeakKeyDictionary()
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001471 objects = list(map(Object, range(self.COUNT)))
Fred Drake0e540c32001-05-02 05:44:22 +00001472 for o in objects:
1473 dict[o] = o.arg
1474 return dict, objects
1475
Antoine Pitrouc06de472009-05-30 21:04:26 +00001476 def test_make_weak_valued_dict_from_dict(self):
1477 o = Object(3)
1478 dict = weakref.WeakValueDictionary({364:o})
1479 self.assertEqual(dict[364], o)
1480
1481 def test_make_weak_valued_dict_from_weak_valued_dict(self):
1482 o = Object(3)
1483 dict = weakref.WeakValueDictionary({364:o})
1484 dict2 = weakref.WeakValueDictionary(dict)
1485 self.assertEqual(dict[364], o)
1486
Serhiy Storchakab5102e32015-09-29 23:52:09 +03001487 def test_make_weak_valued_dict_misc(self):
1488 # errors
1489 self.assertRaises(TypeError, weakref.WeakValueDictionary.__init__)
1490 self.assertRaises(TypeError, weakref.WeakValueDictionary, {}, {})
1491 self.assertRaises(TypeError, weakref.WeakValueDictionary, (), ())
1492 # special keyword arguments
1493 o = Object(3)
1494 for kw in 'self', 'dict', 'other', 'iterable':
1495 d = weakref.WeakValueDictionary(**{kw: o})
1496 self.assertEqual(list(d.keys()), [kw])
1497 self.assertEqual(d[kw], o)
1498
Fred Drake0e540c32001-05-02 05:44:22 +00001499 def make_weak_valued_dict(self):
1500 dict = weakref.WeakValueDictionary()
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001501 objects = list(map(Object, range(self.COUNT)))
Fred Drake0e540c32001-05-02 05:44:22 +00001502 for o in objects:
1503 dict[o.arg] = o
1504 return dict, objects
1505
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001506 def check_popitem(self, klass, key1, value1, key2, value2):
1507 weakdict = klass()
1508 weakdict[key1] = value1
1509 weakdict[key2] = value2
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001510 self.assertEqual(len(weakdict), 2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001511 k, v = weakdict.popitem()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001512 self.assertEqual(len(weakdict), 1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001513 if k is key1:
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001514 self.assertIs(v, value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001515 else:
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001516 self.assertIs(v, value2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001517 k, v = weakdict.popitem()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001518 self.assertEqual(len(weakdict), 0)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001519 if k is key1:
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001520 self.assertIs(v, value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001521 else:
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001522 self.assertIs(v, value2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001523
1524 def test_weak_valued_dict_popitem(self):
1525 self.check_popitem(weakref.WeakValueDictionary,
1526 "key1", C(), "key2", C())
1527
1528 def test_weak_keyed_dict_popitem(self):
1529 self.check_popitem(weakref.WeakKeyDictionary,
1530 C(), "value 1", C(), "value 2")
1531
1532 def check_setdefault(self, klass, key, value1, value2):
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001533 self.assertIsNot(value1, value2,
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001534 "invalid test"
1535 " -- value parameters must be distinct objects")
1536 weakdict = klass()
1537 o = weakdict.setdefault(key, value1)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001538 self.assertIs(o, value1)
Benjamin Peterson577473f2010-01-19 00:09:57 +00001539 self.assertIn(key, weakdict)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001540 self.assertIs(weakdict.get(key), value1)
1541 self.assertIs(weakdict[key], value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001542
1543 o = weakdict.setdefault(key, value2)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001544 self.assertIs(o, value1)
Benjamin Peterson577473f2010-01-19 00:09:57 +00001545 self.assertIn(key, weakdict)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001546 self.assertIs(weakdict.get(key), value1)
1547 self.assertIs(weakdict[key], value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001548
1549 def test_weak_valued_dict_setdefault(self):
1550 self.check_setdefault(weakref.WeakValueDictionary,
1551 "key", C(), C())
1552
1553 def test_weak_keyed_dict_setdefault(self):
1554 self.check_setdefault(weakref.WeakKeyDictionary,
1555 C(), "value 1", "value 2")
1556
Fred Drakea0a4ab12001-04-16 17:37:27 +00001557 def check_update(self, klass, dict):
Fred Drake0e540c32001-05-02 05:44:22 +00001558 #
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001559 # This exercises d.update(), len(d), d.keys(), k in d,
Fred Drake0e540c32001-05-02 05:44:22 +00001560 # d.get(), d[].
1561 #
Fred Drakea0a4ab12001-04-16 17:37:27 +00001562 weakdict = klass()
1563 weakdict.update(dict)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001564 self.assertEqual(len(weakdict), len(dict))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001565 for k in weakdict.keys():
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001566 self.assertIn(k, dict, "mysterious new key appeared in weak dict")
Fred Drakea0a4ab12001-04-16 17:37:27 +00001567 v = dict.get(k)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001568 self.assertIs(v, weakdict[k])
1569 self.assertIs(v, weakdict.get(k))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001570 for k in dict.keys():
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001571 self.assertIn(k, weakdict, "original key disappeared in weak dict")
Fred Drakea0a4ab12001-04-16 17:37:27 +00001572 v = dict[k]
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001573 self.assertIs(v, weakdict[k])
1574 self.assertIs(v, weakdict.get(k))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001575
1576 def test_weak_valued_dict_update(self):
1577 self.check_update(weakref.WeakValueDictionary,
1578 {1: C(), 'a': C(), C(): C()})
Serhiy Storchakab5102e32015-09-29 23:52:09 +03001579 # errors
1580 self.assertRaises(TypeError, weakref.WeakValueDictionary.update)
1581 d = weakref.WeakValueDictionary()
1582 self.assertRaises(TypeError, d.update, {}, {})
1583 self.assertRaises(TypeError, d.update, (), ())
1584 self.assertEqual(list(d.keys()), [])
1585 # special keyword arguments
1586 o = Object(3)
1587 for kw in 'self', 'dict', 'other', 'iterable':
1588 d = weakref.WeakValueDictionary()
1589 d.update(**{kw: o})
1590 self.assertEqual(list(d.keys()), [kw])
1591 self.assertEqual(d[kw], o)
Fred Drakea0a4ab12001-04-16 17:37:27 +00001592
1593 def test_weak_keyed_dict_update(self):
1594 self.check_update(weakref.WeakKeyDictionary,
1595 {C(): 1, C(): 2, C(): 3})
1596
Fred Drakeccc75622001-09-06 14:52:39 +00001597 def test_weak_keyed_delitem(self):
1598 d = weakref.WeakKeyDictionary()
1599 o1 = Object('1')
1600 o2 = Object('2')
1601 d[o1] = 'something'
1602 d[o2] = 'something'
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001603 self.assertEqual(len(d), 2)
Fred Drakeccc75622001-09-06 14:52:39 +00001604 del d[o1]
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001605 self.assertEqual(len(d), 1)
Barry Warsawecaab832008-09-04 01:42:51 +00001606 self.assertEqual(list(d.keys()), [o2])
Fred Drakeccc75622001-09-06 14:52:39 +00001607
1608 def test_weak_valued_delitem(self):
1609 d = weakref.WeakValueDictionary()
1610 o1 = Object('1')
1611 o2 = Object('2')
1612 d['something'] = o1
1613 d['something else'] = o2
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001614 self.assertEqual(len(d), 2)
Fred Drakeccc75622001-09-06 14:52:39 +00001615 del d['something']
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001616 self.assertEqual(len(d), 1)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001617 self.assertEqual(list(d.items()), [('something else', o2)])
Fred Drakeccc75622001-09-06 14:52:39 +00001618
Tim Peters886128f2003-05-25 01:45:11 +00001619 def test_weak_keyed_bad_delitem(self):
1620 d = weakref.WeakKeyDictionary()
1621 o = Object('1')
1622 # An attempt to delete an object that isn't there should raise
Tim Peters50d8b8b2003-05-25 17:44:31 +00001623 # KeyError. It didn't before 2.3.
Tim Peters886128f2003-05-25 01:45:11 +00001624 self.assertRaises(KeyError, d.__delitem__, o)
Tim Peters50d8b8b2003-05-25 17:44:31 +00001625 self.assertRaises(KeyError, d.__getitem__, o)
1626
1627 # If a key isn't of a weakly referencable type, __getitem__ and
1628 # __setitem__ raise TypeError. __delitem__ should too.
1629 self.assertRaises(TypeError, d.__delitem__, 13)
1630 self.assertRaises(TypeError, d.__getitem__, 13)
1631 self.assertRaises(TypeError, d.__setitem__, 13, 13)
Tim Peters886128f2003-05-25 01:45:11 +00001632
1633 def test_weak_keyed_cascading_deletes(self):
1634 # SF bug 742860. For some reason, before 2.3 __delitem__ iterated
1635 # over the keys via self.data.iterkeys(). If things vanished from
1636 # the dict during this (or got added), that caused a RuntimeError.
1637
1638 d = weakref.WeakKeyDictionary()
1639 mutate = False
1640
1641 class C(object):
1642 def __init__(self, i):
1643 self.value = i
1644 def __hash__(self):
1645 return hash(self.value)
1646 def __eq__(self, other):
1647 if mutate:
1648 # Side effect that mutates the dict, by removing the
1649 # last strong reference to a key.
1650 del objs[-1]
1651 return self.value == other.value
1652
1653 objs = [C(i) for i in range(4)]
1654 for o in objs:
1655 d[o] = o.value
1656 del o # now the only strong references to keys are in objs
1657 # Find the order in which iterkeys sees the keys.
Barry Warsawecaab832008-09-04 01:42:51 +00001658 objs = list(d.keys())
Tim Peters886128f2003-05-25 01:45:11 +00001659 # Reverse it, so that the iteration implementation of __delitem__
1660 # has to keep looping to find the first object we delete.
1661 objs.reverse()
Tim Peters50d8b8b2003-05-25 17:44:31 +00001662
Leo Ariasc3d95082018-02-03 18:36:10 -06001663 # Turn on mutation in C.__eq__. The first time through the loop,
Tim Peters886128f2003-05-25 01:45:11 +00001664 # under the iterkeys() business the first comparison will delete
1665 # the last item iterkeys() would see, and that causes a
1666 # RuntimeError: dictionary changed size during iteration
1667 # when the iterkeys() loop goes around to try comparing the next
Tim Peters50d8b8b2003-05-25 17:44:31 +00001668 # key. After this was fixed, it just deletes the last object *our*
Tim Peters886128f2003-05-25 01:45:11 +00001669 # "for o in obj" loop would have gotten to.
1670 mutate = True
1671 count = 0
1672 for o in objs:
1673 count += 1
1674 del d[o]
1675 self.assertEqual(len(d), 0)
1676 self.assertEqual(count, 2)
1677
Serhiy Storchaka0c937b32014-07-22 12:14:52 +03001678 def test_make_weak_valued_dict_repr(self):
1679 dict = weakref.WeakValueDictionary()
1680 self.assertRegex(repr(dict), '<WeakValueDictionary at 0x.*>')
1681
1682 def test_make_weak_keyed_dict_repr(self):
1683 dict = weakref.WeakKeyDictionary()
1684 self.assertRegex(repr(dict), '<WeakKeyDictionary at 0x.*>')
1685
Antoine Pitrouc1ee4882016-12-19 10:56:40 +01001686 def test_threaded_weak_valued_setdefault(self):
1687 d = weakref.WeakValueDictionary()
1688 with collect_in_thread():
1689 for i in range(100000):
1690 x = d.setdefault(10, RefCycle())
1691 self.assertIsNot(x, None) # we never put None in there!
1692 del x
1693
1694 def test_threaded_weak_valued_pop(self):
1695 d = weakref.WeakValueDictionary()
1696 with collect_in_thread():
1697 for i in range(100000):
1698 d[10] = RefCycle()
1699 x = d.pop(10, 10)
1700 self.assertIsNot(x, None) # we never put None in there!
1701
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001702 def test_threaded_weak_valued_consistency(self):
1703 # Issue #28427: old keys should not remove new values from
1704 # WeakValueDictionary when collecting from another thread.
1705 d = weakref.WeakValueDictionary()
1706 with collect_in_thread():
1707 for i in range(200000):
1708 o = RefCycle()
1709 d[10] = o
1710 # o is still alive, so the dict can't be empty
1711 self.assertEqual(len(d), 1)
1712 o = None # lose ref
1713
Fish96d37db2019-02-07 14:51:59 -05001714 def check_threaded_weak_dict_copy(self, type_, deepcopy):
1715 # `type_` should be either WeakKeyDictionary or WeakValueDictionary.
1716 # `deepcopy` should be either True or False.
1717 exc = []
1718
1719 class DummyKey:
1720 def __init__(self, ctr):
1721 self.ctr = ctr
1722
1723 class DummyValue:
1724 def __init__(self, ctr):
1725 self.ctr = ctr
1726
1727 def dict_copy(d, exc):
1728 try:
1729 if deepcopy is True:
1730 _ = copy.deepcopy(d)
1731 else:
1732 _ = d.copy()
1733 except Exception as ex:
1734 exc.append(ex)
1735
1736 def pop_and_collect(lst):
1737 gc_ctr = 0
1738 while lst:
1739 i = random.randint(0, len(lst) - 1)
1740 gc_ctr += 1
1741 lst.pop(i)
1742 if gc_ctr % 10000 == 0:
1743 gc.collect() # just in case
1744
1745 self.assertIn(type_, (weakref.WeakKeyDictionary, weakref.WeakValueDictionary))
1746
1747 d = type_()
1748 keys = []
1749 values = []
1750 # Initialize d with many entries
1751 for i in range(70000):
1752 k, v = DummyKey(i), DummyValue(i)
1753 keys.append(k)
1754 values.append(v)
1755 d[k] = v
1756 del k
1757 del v
1758
1759 t_copy = threading.Thread(target=dict_copy, args=(d, exc,))
1760 if type_ is weakref.WeakKeyDictionary:
1761 t_collect = threading.Thread(target=pop_and_collect, args=(keys,))
1762 else: # weakref.WeakValueDictionary
1763 t_collect = threading.Thread(target=pop_and_collect, args=(values,))
1764
1765 t_copy.start()
1766 t_collect.start()
1767
1768 t_copy.join()
1769 t_collect.join()
1770
1771 # Test exceptions
1772 if exc:
1773 raise exc[0]
1774
1775 def test_threaded_weak_key_dict_copy(self):
1776 # Issue #35615: Weakref keys or values getting GC'ed during dict
1777 # copying should not result in a crash.
1778 self.check_threaded_weak_dict_copy(weakref.WeakKeyDictionary, False)
1779
1780 def test_threaded_weak_key_dict_deepcopy(self):
1781 # Issue #35615: Weakref keys or values getting GC'ed during dict
1782 # copying should not result in a crash.
1783 self.check_threaded_weak_dict_copy(weakref.WeakKeyDictionary, True)
1784
1785 def test_threaded_weak_value_dict_copy(self):
1786 # Issue #35615: Weakref keys or values getting GC'ed during dict
1787 # copying should not result in a crash.
1788 self.check_threaded_weak_dict_copy(weakref.WeakValueDictionary, False)
1789
1790 def test_threaded_weak_value_dict_deepcopy(self):
1791 # Issue #35615: Weakref keys or values getting GC'ed during dict
1792 # copying should not result in a crash.
1793 self.check_threaded_weak_dict_copy(weakref.WeakValueDictionary, True)
1794
Victor Stinnera2af05a2019-09-09 16:55:58 +02001795 @support.cpython_only
1796 def test_remove_closure(self):
1797 d = weakref.WeakValueDictionary()
1798 self.assertIsNone(d._remove.__closure__)
1799
Antoine Pitrouc1ee4882016-12-19 10:56:40 +01001800
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001801from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001802
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001803class WeakValueDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +00001804 """Check that WeakValueDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001805 __ref = {"key1":Object(1), "key2":Object(2), "key3":Object(3)}
Walter Dörwald118f9312004-06-02 18:42:25 +00001806 type2test = weakref.WeakValueDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001807 def _reference(self):
1808 return self.__ref.copy()
1809
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001810class WeakKeyDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +00001811 """Check that WeakKeyDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001812 __ref = {Object("key1"):1, Object("key2"):2, Object("key3"):3}
Walter Dörwald118f9312004-06-02 18:42:25 +00001813 type2test = weakref.WeakKeyDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001814 def _reference(self):
1815 return self.__ref.copy()
Martin v. Löwis5e163332001-02-27 18:36:56 +00001816
Richard Oudkerk7a3dae02013-05-05 23:05:00 +01001817
1818class FinalizeTestCase(unittest.TestCase):
1819
1820 class A:
1821 pass
1822
1823 def _collect_if_necessary(self):
1824 # we create no ref-cycles so in CPython no gc should be needed
1825 if sys.implementation.name != 'cpython':
1826 support.gc_collect()
1827
1828 def test_finalize(self):
1829 def add(x,y,z):
1830 res.append(x + y + z)
1831 return x + y + z
1832
1833 a = self.A()
1834
1835 res = []
1836 f = weakref.finalize(a, add, 67, 43, z=89)
1837 self.assertEqual(f.alive, True)
1838 self.assertEqual(f.peek(), (a, add, (67,43), {'z':89}))
1839 self.assertEqual(f(), 199)
1840 self.assertEqual(f(), None)
1841 self.assertEqual(f(), None)
1842 self.assertEqual(f.peek(), None)
1843 self.assertEqual(f.detach(), None)
1844 self.assertEqual(f.alive, False)
1845 self.assertEqual(res, [199])
1846
1847 res = []
1848 f = weakref.finalize(a, add, 67, 43, 89)
1849 self.assertEqual(f.peek(), (a, add, (67,43,89), {}))
1850 self.assertEqual(f.detach(), (a, add, (67,43,89), {}))
1851 self.assertEqual(f(), None)
1852 self.assertEqual(f(), None)
1853 self.assertEqual(f.peek(), None)
1854 self.assertEqual(f.detach(), None)
1855 self.assertEqual(f.alive, False)
1856 self.assertEqual(res, [])
1857
1858 res = []
1859 f = weakref.finalize(a, add, x=67, y=43, z=89)
1860 del a
1861 self._collect_if_necessary()
1862 self.assertEqual(f(), None)
1863 self.assertEqual(f(), None)
1864 self.assertEqual(f.peek(), None)
1865 self.assertEqual(f.detach(), None)
1866 self.assertEqual(f.alive, False)
1867 self.assertEqual(res, [199])
1868
Serhiy Storchaka42a139e2019-04-01 09:16:35 +03001869 def test_arg_errors(self):
1870 def fin(*args, **kwargs):
1871 res.append((args, kwargs))
1872
1873 a = self.A()
1874
1875 res = []
1876 f = weakref.finalize(a, fin, 1, 2, func=3, obj=4)
1877 self.assertEqual(f.peek(), (a, fin, (1, 2), {'func': 3, 'obj': 4}))
1878 f()
1879 self.assertEqual(res, [((1, 2), {'func': 3, 'obj': 4})])
1880
Serhiy Storchaka142566c2019-06-05 18:22:31 +03001881 with self.assertRaises(TypeError):
1882 weakref.finalize(a, func=fin, arg=1)
1883 with self.assertRaises(TypeError):
1884 weakref.finalize(obj=a, func=fin, arg=1)
Serhiy Storchaka42a139e2019-04-01 09:16:35 +03001885 self.assertRaises(TypeError, weakref.finalize, a)
1886 self.assertRaises(TypeError, weakref.finalize)
1887
Richard Oudkerk7a3dae02013-05-05 23:05:00 +01001888 def test_order(self):
1889 a = self.A()
1890 res = []
1891
1892 f1 = weakref.finalize(a, res.append, 'f1')
1893 f2 = weakref.finalize(a, res.append, 'f2')
1894 f3 = weakref.finalize(a, res.append, 'f3')
1895 f4 = weakref.finalize(a, res.append, 'f4')
1896 f5 = weakref.finalize(a, res.append, 'f5')
1897
1898 # make sure finalizers can keep themselves alive
1899 del f1, f4
1900
1901 self.assertTrue(f2.alive)
1902 self.assertTrue(f3.alive)
1903 self.assertTrue(f5.alive)
1904
1905 self.assertTrue(f5.detach())
1906 self.assertFalse(f5.alive)
1907
1908 f5() # nothing because previously unregistered
1909 res.append('A')
1910 f3() # => res.append('f3')
1911 self.assertFalse(f3.alive)
1912 res.append('B')
1913 f3() # nothing because previously called
1914 res.append('C')
1915 del a
1916 self._collect_if_necessary()
1917 # => res.append('f4')
1918 # => res.append('f2')
1919 # => res.append('f1')
1920 self.assertFalse(f2.alive)
1921 res.append('D')
1922 f2() # nothing because previously called by gc
1923
1924 expected = ['A', 'f3', 'B', 'C', 'f4', 'f2', 'f1', 'D']
1925 self.assertEqual(res, expected)
1926
1927 def test_all_freed(self):
1928 # we want a weakrefable subclass of weakref.finalize
1929 class MyFinalizer(weakref.finalize):
1930 pass
1931
1932 a = self.A()
1933 res = []
1934 def callback():
1935 res.append(123)
1936 f = MyFinalizer(a, callback)
1937
1938 wr_callback = weakref.ref(callback)
1939 wr_f = weakref.ref(f)
1940 del callback, f
1941
1942 self.assertIsNotNone(wr_callback())
1943 self.assertIsNotNone(wr_f())
1944
1945 del a
1946 self._collect_if_necessary()
1947
1948 self.assertIsNone(wr_callback())
1949 self.assertIsNone(wr_f())
1950 self.assertEqual(res, [123])
1951
1952 @classmethod
1953 def run_in_child(cls):
1954 def error():
1955 # Create an atexit finalizer from inside a finalizer called
1956 # at exit. This should be the next to be run.
1957 g1 = weakref.finalize(cls, print, 'g1')
1958 print('f3 error')
1959 1/0
1960
1961 # cls should stay alive till atexit callbacks run
1962 f1 = weakref.finalize(cls, print, 'f1', _global_var)
1963 f2 = weakref.finalize(cls, print, 'f2', _global_var)
1964 f3 = weakref.finalize(cls, error)
1965 f4 = weakref.finalize(cls, print, 'f4', _global_var)
1966
1967 assert f1.atexit == True
1968 f2.atexit = False
1969 assert f3.atexit == True
1970 assert f4.atexit == True
1971
1972 def test_atexit(self):
1973 prog = ('from test.test_weakref import FinalizeTestCase;'+
1974 'FinalizeTestCase.run_in_child()')
1975 rc, out, err = script_helper.assert_python_ok('-c', prog)
1976 out = out.decode('ascii').splitlines()
1977 self.assertEqual(out, ['f4 foobar', 'f3 error', 'g1', 'f1 foobar'])
1978 self.assertTrue(b'ZeroDivisionError' in err)
1979
1980
Georg Brandlb533e262008-05-25 18:19:30 +00001981libreftest = """ Doctest for examples in the library reference: weakref.rst
Georg Brandl9a65d582005-07-02 19:07:30 +00001982
1983>>> import weakref
1984>>> class Dict(dict):
1985... pass
1986...
1987>>> obj = Dict(red=1, green=2, blue=3) # this object is weak referencable
1988>>> r = weakref.ref(obj)
Guido van Rossum7131f842007-02-09 20:13:25 +00001989>>> print(r() is obj)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001990True
Georg Brandl9a65d582005-07-02 19:07:30 +00001991
1992>>> import weakref
1993>>> class Object:
1994... pass
1995...
1996>>> o = Object()
1997>>> r = weakref.ref(o)
1998>>> o2 = r()
1999>>> o is o2
2000True
2001>>> del o, o2
Guido van Rossum7131f842007-02-09 20:13:25 +00002002>>> print(r())
Georg Brandl9a65d582005-07-02 19:07:30 +00002003None
2004
2005>>> import weakref
2006>>> class ExtendedRef(weakref.ref):
2007... def __init__(self, ob, callback=None, **annotations):
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002008... super().__init__(ob, callback)
Georg Brandl9a65d582005-07-02 19:07:30 +00002009... self.__counter = 0
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002010... for k, v in annotations.items():
Georg Brandl9a65d582005-07-02 19:07:30 +00002011... setattr(self, k, v)
2012... def __call__(self):
2013... '''Return a pair containing the referent and the number of
2014... times the reference has been called.
2015... '''
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002016... ob = super().__call__()
Georg Brandl9a65d582005-07-02 19:07:30 +00002017... if ob is not None:
2018... self.__counter += 1
2019... ob = (ob, self.__counter)
2020... return ob
Guido van Rossumd8faa362007-04-27 19:54:29 +00002021...
Georg Brandl9a65d582005-07-02 19:07:30 +00002022>>> class A: # not in docs from here, just testing the ExtendedRef
2023... pass
2024...
2025>>> a = A()
2026>>> r = ExtendedRef(a, foo=1, bar="baz")
2027>>> r.foo
20281
2029>>> r.bar
2030'baz'
2031>>> r()[1]
20321
2033>>> r()[1]
20342
2035>>> r()[0] is a
2036True
2037
2038
2039>>> import weakref
2040>>> _id2obj_dict = weakref.WeakValueDictionary()
2041>>> def remember(obj):
2042... oid = id(obj)
2043... _id2obj_dict[oid] = obj
2044... return oid
2045...
2046>>> def id2obj(oid):
2047... return _id2obj_dict[oid]
2048...
2049>>> a = A() # from here, just testing
2050>>> a_id = remember(a)
2051>>> id2obj(a_id) is a
2052True
2053>>> del a
2054>>> try:
2055... id2obj(a_id)
2056... except KeyError:
Guido van Rossum7131f842007-02-09 20:13:25 +00002057... print('OK')
Georg Brandl9a65d582005-07-02 19:07:30 +00002058... else:
Guido van Rossum7131f842007-02-09 20:13:25 +00002059... print('WeakValueDictionary error')
Georg Brandl9a65d582005-07-02 19:07:30 +00002060OK
2061
2062"""
2063
2064__test__ = {'libreftest' : libreftest}
2065
Fred Drake2e2be372001-09-20 21:33:42 +00002066def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002067 support.run_unittest(
Walter Dörwald21d3a322003-05-01 17:45:56 +00002068 ReferencesTestCase,
Antoine Pitrouc3afba12012-11-17 18:57:38 +01002069 WeakMethodTestCase,
Walter Dörwald21d3a322003-05-01 17:45:56 +00002070 MappingTestCase,
2071 WeakValueDictionaryTestCase,
Fred Drakef425b1e2003-07-14 21:37:17 +00002072 WeakKeyDictionaryTestCase,
Amaury Forgeot d'Arcc856c7a2008-06-16 19:50:09 +00002073 SubclassableWeakrefTestCase,
Richard Oudkerk7a3dae02013-05-05 23:05:00 +01002074 FinalizeTestCase,
Fred Drakef425b1e2003-07-14 21:37:17 +00002075 )
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002076 support.run_doctest(sys.modules[__name__])
Fred Drake2e2be372001-09-20 21:33:42 +00002077
2078
2079if __name__ == "__main__":
2080 test_main()