blob: 74b9a878521d95683147e705a63af9ca1be8e1a6 [file] [log] [blame]
Fred Drakebc875f52004-02-04 23:14:14 +00001import gc
Fred Drake41deb1e2001-02-01 05:27:45 +00002import sys
Fred Drakeb0fefc52001-03-23 04:22:45 +00003import unittest
Raymond Hettinger53dbe392008-02-12 20:03:09 +00004import collections
Fred Drake41deb1e2001-02-01 05:27:45 +00005import weakref
Georg Brandlb533e262008-05-25 18:19:30 +00006import operator
Antoine Pitrouc1baa602010-01-08 17:54:23 +00007import contextlib
8import copy
Fred Drake41deb1e2001-02-01 05:27:45 +00009
Benjamin Petersonee8712c2008-05-20 21:35:26 +000010from test import support
Fred Drake41deb1e2001-02-01 05:27:45 +000011
Thomas Woutersb2137042007-02-01 18:02:27 +000012# Used in ReferencesTestCase.test_ref_created_during_del() .
13ref_from_del = None
Fred Drake41deb1e2001-02-01 05:27:45 +000014
15class C:
Fred Drakeb0fefc52001-03-23 04:22:45 +000016 def method(self):
17 pass
Fred Drake41deb1e2001-02-01 05:27:45 +000018
19
Fred Drakeb0fefc52001-03-23 04:22:45 +000020class Callable:
21 bar = None
Fred Drake41deb1e2001-02-01 05:27:45 +000022
Fred Drakeb0fefc52001-03-23 04:22:45 +000023 def __call__(self, x):
24 self.bar = x
Fred Drake41deb1e2001-02-01 05:27:45 +000025
26
Fred Drakeb0fefc52001-03-23 04:22:45 +000027def create_function():
28 def f(): pass
29 return f
30
31def create_bound_method():
32 return C().method
33
Fred Drake41deb1e2001-02-01 05:27:45 +000034
Fred Drakeb0fefc52001-03-23 04:22:45 +000035class TestBase(unittest.TestCase):
36
37 def setUp(self):
38 self.cbcalled = 0
39
40 def callback(self, ref):
41 self.cbcalled += 1
Fred Drake41deb1e2001-02-01 05:27:45 +000042
43
Fred Drakeb0fefc52001-03-23 04:22:45 +000044class ReferencesTestCase(TestBase):
Fred Drake41deb1e2001-02-01 05:27:45 +000045
Fred Drakeb0fefc52001-03-23 04:22:45 +000046 def test_basic_ref(self):
47 self.check_basic_ref(C)
48 self.check_basic_ref(create_function)
49 self.check_basic_ref(create_bound_method)
Fred Drake41deb1e2001-02-01 05:27:45 +000050
Fred Drake43735da2002-04-11 03:59:42 +000051 # Just make sure the tp_repr handler doesn't raise an exception.
52 # Live reference:
53 o = C()
54 wr = weakref.ref(o)
Brett Cannon0b70cca2006-08-25 02:59:59 +000055 repr(wr)
Fred Drake43735da2002-04-11 03:59:42 +000056 # Dead reference:
57 del o
Brett Cannon0b70cca2006-08-25 02:59:59 +000058 repr(wr)
Fred Drake43735da2002-04-11 03:59:42 +000059
Fred Drakeb0fefc52001-03-23 04:22:45 +000060 def test_basic_callback(self):
61 self.check_basic_callback(C)
62 self.check_basic_callback(create_function)
63 self.check_basic_callback(create_bound_method)
Fred Drake41deb1e2001-02-01 05:27:45 +000064
Fred Drakeb0fefc52001-03-23 04:22:45 +000065 def test_multiple_callbacks(self):
66 o = C()
67 ref1 = weakref.ref(o, self.callback)
68 ref2 = weakref.ref(o, self.callback)
69 del o
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000070 self.assertTrue(ref1() is None,
Fred Drakeb0fefc52001-03-23 04:22:45 +000071 "expected reference to be invalidated")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000072 self.assertTrue(ref2() is None,
Fred Drakeb0fefc52001-03-23 04:22:45 +000073 "expected reference to be invalidated")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000074 self.assertTrue(self.cbcalled == 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +000075 "callback not called the right number of times")
Fred Drake41deb1e2001-02-01 05:27:45 +000076
Fred Drake705088e2001-04-13 17:18:15 +000077 def test_multiple_selfref_callbacks(self):
Guido van Rossum9eee5542002-08-22 20:21:30 +000078 # Make sure all references are invalidated before callbacks are called
Fred Drake705088e2001-04-13 17:18:15 +000079 #
80 # What's important here is that we're using the first
81 # reference in the callback invoked on the second reference
82 # (the most recently created ref is cleaned up first). This
83 # tests that all references to the object are invalidated
84 # before any of the callbacks are invoked, so that we only
85 # have one invocation of _weakref.c:cleanup_helper() active
86 # for a particular object at a time.
87 #
88 def callback(object, self=self):
89 self.ref()
90 c = C()
91 self.ref = weakref.ref(c, callback)
92 ref1 = weakref.ref(c, callback)
93 del c
94
Fred Drakeb0fefc52001-03-23 04:22:45 +000095 def test_proxy_ref(self):
96 o = C()
97 o.bar = 1
98 ref1 = weakref.proxy(o, self.callback)
99 ref2 = weakref.proxy(o, self.callback)
100 del o
Fred Drake41deb1e2001-02-01 05:27:45 +0000101
Fred Drakeb0fefc52001-03-23 04:22:45 +0000102 def check(proxy):
103 proxy.bar
Fred Drake41deb1e2001-02-01 05:27:45 +0000104
Neal Norwitz2633c692007-02-26 22:22:47 +0000105 self.assertRaises(ReferenceError, check, ref1)
106 self.assertRaises(ReferenceError, check, ref2)
107 self.assertRaises(ReferenceError, bool, weakref.proxy(C()))
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000108 self.assertEqual(self.cbcalled, 2)
Fred Drake41deb1e2001-02-01 05:27:45 +0000109
Fred Drakeb0fefc52001-03-23 04:22:45 +0000110 def check_basic_ref(self, factory):
111 o = factory()
112 ref = weakref.ref(o)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000113 self.assertTrue(ref() is not None,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000114 "weak reference to live object should be live")
115 o2 = ref()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000116 self.assertTrue(o is o2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000117 "<ref>() should return original object if live")
Fred Drake41deb1e2001-02-01 05:27:45 +0000118
Fred Drakeb0fefc52001-03-23 04:22:45 +0000119 def check_basic_callback(self, factory):
120 self.cbcalled = 0
121 o = factory()
122 ref = weakref.ref(o, self.callback)
123 del o
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000124 self.assertTrue(self.cbcalled == 1,
Fred Drake705088e2001-04-13 17:18:15 +0000125 "callback did not properly set 'cbcalled'")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000126 self.assertTrue(ref() is None,
Fred Drake705088e2001-04-13 17:18:15 +0000127 "ref2 should be dead after deleting object reference")
Fred Drake41deb1e2001-02-01 05:27:45 +0000128
Fred Drakeb0fefc52001-03-23 04:22:45 +0000129 def test_ref_reuse(self):
130 o = C()
131 ref1 = weakref.ref(o)
132 # create a proxy to make sure that there's an intervening creation
133 # between these two; it should make no difference
134 proxy = weakref.proxy(o)
135 ref2 = weakref.ref(o)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000136 self.assertTrue(ref1 is ref2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000137 "reference object w/out callback should be re-used")
Fred Drake41deb1e2001-02-01 05:27:45 +0000138
Fred Drakeb0fefc52001-03-23 04:22:45 +0000139 o = C()
140 proxy = weakref.proxy(o)
141 ref1 = weakref.ref(o)
142 ref2 = weakref.ref(o)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000143 self.assertTrue(ref1 is ref2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000144 "reference object w/out callback should be re-used")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000145 self.assertTrue(weakref.getweakrefcount(o) == 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000146 "wrong weak ref count for object")
147 del proxy
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000148 self.assertTrue(weakref.getweakrefcount(o) == 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000149 "wrong weak ref count for object after deleting proxy")
Fred Drake41deb1e2001-02-01 05:27:45 +0000150
Fred Drakeb0fefc52001-03-23 04:22:45 +0000151 def test_proxy_reuse(self):
152 o = C()
153 proxy1 = weakref.proxy(o)
154 ref = weakref.ref(o)
155 proxy2 = weakref.proxy(o)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000156 self.assertTrue(proxy1 is proxy2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000157 "proxy object w/out callback should have been re-used")
158
159 def test_basic_proxy(self):
160 o = C()
161 self.check_proxy(o, weakref.proxy(o))
162
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000163 L = collections.UserList()
Fred Drake5935ff02001-12-19 16:54:23 +0000164 p = weakref.proxy(L)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000165 self.assertFalse(p, "proxy for empty UserList should be false")
Fred Drake5935ff02001-12-19 16:54:23 +0000166 p.append(12)
167 self.assertEqual(len(L), 1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000168 self.assertTrue(p, "proxy for non-empty UserList should be true")
Fred Drake5935ff02001-12-19 16:54:23 +0000169 p[:] = [2, 3]
170 self.assertEqual(len(L), 2)
171 self.assertEqual(len(p), 2)
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000172 self.assertIn(3, p, "proxy didn't support __contains__() properly")
Fred Drake5935ff02001-12-19 16:54:23 +0000173 p[1] = 5
174 self.assertEqual(L[1], 5)
175 self.assertEqual(p[1], 5)
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000176 L2 = collections.UserList(L)
Fred Drake5935ff02001-12-19 16:54:23 +0000177 p2 = weakref.proxy(L2)
178 self.assertEqual(p, p2)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000179 ## self.assertEqual(repr(L2), repr(p2))
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000180 L3 = collections.UserList(range(10))
Fred Drake43735da2002-04-11 03:59:42 +0000181 p3 = weakref.proxy(L3)
182 self.assertEqual(L3[:], p3[:])
183 self.assertEqual(L3[5:], p3[5:])
184 self.assertEqual(L3[:5], p3[:5])
185 self.assertEqual(L3[2:5], p3[2:5])
Fred Drake5935ff02001-12-19 16:54:23 +0000186
Benjamin Peterson32019772009-11-19 03:08:32 +0000187 def test_proxy_unicode(self):
188 # See bug 5037
189 class C(object):
190 def __str__(self):
191 return "string"
192 def __bytes__(self):
193 return b"bytes"
194 instance = C()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000195 self.assertIn("__bytes__", dir(weakref.proxy(instance)))
Benjamin Peterson32019772009-11-19 03:08:32 +0000196 self.assertEqual(bytes(weakref.proxy(instance)), b"bytes")
197
Georg Brandlb533e262008-05-25 18:19:30 +0000198 def test_proxy_index(self):
199 class C:
200 def __index__(self):
201 return 10
202 o = C()
203 p = weakref.proxy(o)
204 self.assertEqual(operator.index(p), 10)
205
206 def test_proxy_div(self):
207 class C:
208 def __floordiv__(self, other):
209 return 42
210 def __ifloordiv__(self, other):
211 return 21
212 o = C()
213 p = weakref.proxy(o)
214 self.assertEqual(p // 5, 42)
215 p //= 5
216 self.assertEqual(p, 21)
217
Fred Drakeea2adc92004-02-03 19:56:46 +0000218 # The PyWeakref_* C API is documented as allowing either NULL or
219 # None as the value for the callback, where either means "no
220 # callback". The "no callback" ref and proxy objects are supposed
221 # to be shared so long as they exist by all callers so long as
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000222 # they are active. In Python 2.3.3 and earlier, this guarantee
Fred Drakeea2adc92004-02-03 19:56:46 +0000223 # was not honored, and was broken in different ways for
224 # PyWeakref_NewRef() and PyWeakref_NewProxy(). (Two tests.)
225
226 def test_shared_ref_without_callback(self):
227 self.check_shared_without_callback(weakref.ref)
228
229 def test_shared_proxy_without_callback(self):
230 self.check_shared_without_callback(weakref.proxy)
231
232 def check_shared_without_callback(self, makeref):
233 o = Object(1)
234 p1 = makeref(o, None)
235 p2 = makeref(o, None)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000236 self.assertTrue(p1 is p2, "both callbacks were None in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000237 del p1, p2
238 p1 = makeref(o)
239 p2 = makeref(o, None)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000240 self.assertTrue(p1 is p2, "callbacks were NULL, None in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000241 del p1, p2
242 p1 = makeref(o)
243 p2 = makeref(o)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000244 self.assertTrue(p1 is p2, "both callbacks were NULL in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000245 del p1, p2
246 p1 = makeref(o, None)
247 p2 = makeref(o)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000248 self.assertTrue(p1 is p2, "callbacks were None, NULL in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000249
Fred Drakeb0fefc52001-03-23 04:22:45 +0000250 def test_callable_proxy(self):
251 o = Callable()
252 ref1 = weakref.proxy(o)
253
254 self.check_proxy(o, ref1)
255
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000256 self.assertTrue(type(ref1) is weakref.CallableProxyType,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000257 "proxy is not of callable type")
258 ref1('twinkies!')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000259 self.assertTrue(o.bar == 'twinkies!',
Fred Drakeb0fefc52001-03-23 04:22:45 +0000260 "call through proxy not passed through to original")
Fred Drake3bb4d212001-10-18 19:28:29 +0000261 ref1(x='Splat.')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000262 self.assertTrue(o.bar == 'Splat.',
Fred Drake3bb4d212001-10-18 19:28:29 +0000263 "call through proxy not passed through to original")
Fred Drakeb0fefc52001-03-23 04:22:45 +0000264
265 # expect due to too few args
266 self.assertRaises(TypeError, ref1)
267
268 # expect due to too many args
269 self.assertRaises(TypeError, ref1, 1, 2, 3)
270
271 def check_proxy(self, o, proxy):
272 o.foo = 1
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000273 self.assertTrue(proxy.foo == 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000274 "proxy does not reflect attribute addition")
275 o.foo = 2
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000276 self.assertTrue(proxy.foo == 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000277 "proxy does not reflect attribute modification")
278 del o.foo
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000279 self.assertTrue(not hasattr(proxy, 'foo'),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000280 "proxy does not reflect attribute removal")
281
282 proxy.foo = 1
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000283 self.assertTrue(o.foo == 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000284 "object does not reflect attribute addition via proxy")
285 proxy.foo = 2
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000286 self.assertTrue(
Fred Drakeb0fefc52001-03-23 04:22:45 +0000287 o.foo == 2,
288 "object does not reflect attribute modification via proxy")
289 del proxy.foo
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000290 self.assertTrue(not hasattr(o, 'foo'),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000291 "object does not reflect attribute removal via proxy")
292
Raymond Hettingerd693a812003-06-30 04:18:48 +0000293 def test_proxy_deletion(self):
294 # Test clearing of SF bug #762891
295 class Foo:
296 result = None
297 def __delitem__(self, accessor):
298 self.result = accessor
299 g = Foo()
300 f = weakref.proxy(g)
301 del f[0]
302 self.assertEqual(f.result, 0)
303
Raymond Hettingere6c470f2005-03-27 03:04:54 +0000304 def test_proxy_bool(self):
305 # Test clearing of SF bug #1170766
306 class List(list): pass
307 lyst = List()
308 self.assertEqual(bool(weakref.proxy(lyst)), bool(lyst))
309
Fred Drakeb0fefc52001-03-23 04:22:45 +0000310 def test_getweakrefcount(self):
311 o = C()
312 ref1 = weakref.ref(o)
313 ref2 = weakref.ref(o, self.callback)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000314 self.assertTrue(weakref.getweakrefcount(o) == 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000315 "got wrong number of weak reference objects")
316
317 proxy1 = weakref.proxy(o)
318 proxy2 = weakref.proxy(o, self.callback)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000319 self.assertTrue(weakref.getweakrefcount(o) == 4,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000320 "got wrong number of weak reference objects")
321
Fred Drakeea2adc92004-02-03 19:56:46 +0000322 del ref1, ref2, proxy1, proxy2
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000323 self.assertTrue(weakref.getweakrefcount(o) == 0,
Fred Drakeea2adc92004-02-03 19:56:46 +0000324 "weak reference objects not unlinked from"
325 " referent when discarded.")
326
Walter Dörwaldb167b042003-12-11 12:34:05 +0000327 # assumes ints do not support weakrefs
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000328 self.assertTrue(weakref.getweakrefcount(1) == 0,
Walter Dörwaldb167b042003-12-11 12:34:05 +0000329 "got wrong number of weak reference objects for int")
330
Fred Drakeb0fefc52001-03-23 04:22:45 +0000331 def test_getweakrefs(self):
332 o = C()
333 ref1 = weakref.ref(o, self.callback)
334 ref2 = weakref.ref(o, self.callback)
335 del ref1
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000336 self.assertTrue(weakref.getweakrefs(o) == [ref2],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000337 "list of refs does not match")
338
339 o = C()
340 ref1 = weakref.ref(o, self.callback)
341 ref2 = weakref.ref(o, self.callback)
342 del ref2
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000343 self.assertTrue(weakref.getweakrefs(o) == [ref1],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000344 "list of refs does not match")
345
Fred Drakeea2adc92004-02-03 19:56:46 +0000346 del ref1
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000347 self.assertTrue(weakref.getweakrefs(o) == [],
Fred Drakeea2adc92004-02-03 19:56:46 +0000348 "list of refs not cleared")
349
Walter Dörwaldb167b042003-12-11 12:34:05 +0000350 # assumes ints do not support weakrefs
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000351 self.assertTrue(weakref.getweakrefs(1) == [],
Walter Dörwaldb167b042003-12-11 12:34:05 +0000352 "list of refs does not match for int")
353
Fred Drake39c27f12001-10-18 18:06:05 +0000354 def test_newstyle_number_ops(self):
355 class F(float):
356 pass
357 f = F(2.0)
358 p = weakref.proxy(f)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000359 self.assertTrue(p + 1.0 == 3.0)
360 self.assertTrue(1.0 + p == 3.0) # this used to SEGV
Fred Drake39c27f12001-10-18 18:06:05 +0000361
Fred Drake2a64f462001-12-10 23:46:02 +0000362 def test_callbacks_protected(self):
Guido van Rossum9eee5542002-08-22 20:21:30 +0000363 # Callbacks protected from already-set exceptions?
Fred Drake2a64f462001-12-10 23:46:02 +0000364 # Regression test for SF bug #478534.
365 class BogusError(Exception):
366 pass
367 data = {}
368 def remove(k):
369 del data[k]
370 def encapsulate():
371 f = lambda : ()
372 data[weakref.ref(f, remove)] = None
373 raise BogusError
374 try:
375 encapsulate()
376 except BogusError:
377 pass
378 else:
379 self.fail("exception not properly restored")
380 try:
381 encapsulate()
382 except BogusError:
383 pass
384 else:
385 self.fail("exception not properly restored")
386
Tim Petersadd09b42003-11-12 20:43:28 +0000387 def test_sf_bug_840829(self):
388 # "weakref callbacks and gc corrupt memory"
389 # subtype_dealloc erroneously exposed a new-style instance
390 # already in the process of getting deallocated to gc,
391 # causing double-deallocation if the instance had a weakref
392 # callback that triggered gc.
393 # If the bug exists, there probably won't be an obvious symptom
394 # in a release build. In a debug build, a segfault will occur
395 # when the second attempt to remove the instance from the "list
396 # of all objects" occurs.
397
398 import gc
399
400 class C(object):
401 pass
402
403 c = C()
404 wr = weakref.ref(c, lambda ignore: gc.collect())
405 del c
406
Tim Petersf7f9e992003-11-13 21:59:32 +0000407 # There endeth the first part. It gets worse.
408 del wr
409
410 c1 = C()
411 c1.i = C()
412 wr = weakref.ref(c1.i, lambda ignore: gc.collect())
413
414 c2 = C()
415 c2.c1 = c1
416 del c1 # still alive because c2 points to it
417
418 # Now when subtype_dealloc gets called on c2, it's not enough just
419 # that c2 is immune from gc while the weakref callbacks associated
420 # with c2 execute (there are none in this 2nd half of the test, btw).
421 # subtype_dealloc goes on to call the base classes' deallocs too,
422 # so any gc triggered by weakref callbacks associated with anything
423 # torn down by a base class dealloc can also trigger double
424 # deallocation of c2.
425 del c2
Fred Drake41deb1e2001-02-01 05:27:45 +0000426
Tim Peters403a2032003-11-20 21:21:46 +0000427 def test_callback_in_cycle_1(self):
428 import gc
429
430 class J(object):
431 pass
432
433 class II(object):
434 def acallback(self, ignore):
435 self.J
436
437 I = II()
438 I.J = J
439 I.wr = weakref.ref(J, I.acallback)
440
441 # Now J and II are each in a self-cycle (as all new-style class
442 # objects are, since their __mro__ points back to them). I holds
443 # both a weak reference (I.wr) and a strong reference (I.J) to class
444 # J. I is also in a cycle (I.wr points to a weakref that references
445 # I.acallback). When we del these three, they all become trash, but
446 # the cycles prevent any of them from getting cleaned up immediately.
447 # Instead they have to wait for cyclic gc to deduce that they're
448 # trash.
449 #
450 # gc used to call tp_clear on all of them, and the order in which
451 # it does that is pretty accidental. The exact order in which we
452 # built up these things manages to provoke gc into running tp_clear
453 # in just the right order (I last). Calling tp_clear on II leaves
454 # behind an insane class object (its __mro__ becomes NULL). Calling
455 # tp_clear on J breaks its self-cycle, but J doesn't get deleted
456 # just then because of the strong reference from I.J. Calling
457 # tp_clear on I starts to clear I's __dict__, and just happens to
458 # clear I.J first -- I.wr is still intact. That removes the last
459 # reference to J, which triggers the weakref callback. The callback
460 # tries to do "self.J", and instances of new-style classes look up
461 # attributes ("J") in the class dict first. The class (II) wants to
462 # search II.__mro__, but that's NULL. The result was a segfault in
463 # a release build, and an assert failure in a debug build.
464 del I, J, II
465 gc.collect()
466
467 def test_callback_in_cycle_2(self):
468 import gc
469
470 # This is just like test_callback_in_cycle_1, except that II is an
471 # old-style class. The symptom is different then: an instance of an
472 # old-style class looks in its own __dict__ first. 'J' happens to
473 # get cleared from I.__dict__ before 'wr', and 'J' was never in II's
474 # __dict__, so the attribute isn't found. The difference is that
475 # the old-style II doesn't have a NULL __mro__ (it doesn't have any
476 # __mro__), so no segfault occurs. Instead it got:
477 # test_callback_in_cycle_2 (__main__.ReferencesTestCase) ...
478 # Exception exceptions.AttributeError:
479 # "II instance has no attribute 'J'" in <bound method II.acallback
480 # of <?.II instance at 0x00B9B4B8>> ignored
481
482 class J(object):
483 pass
484
485 class II:
486 def acallback(self, ignore):
487 self.J
488
489 I = II()
490 I.J = J
491 I.wr = weakref.ref(J, I.acallback)
492
493 del I, J, II
494 gc.collect()
495
496 def test_callback_in_cycle_3(self):
497 import gc
498
499 # This one broke the first patch that fixed the last two. In this
500 # case, the objects reachable from the callback aren't also reachable
501 # from the object (c1) *triggering* the callback: you can get to
502 # c1 from c2, but not vice-versa. The result was that c2's __dict__
503 # got tp_clear'ed by the time the c2.cb callback got invoked.
504
505 class C:
506 def cb(self, ignore):
507 self.me
508 self.c1
509 self.wr
510
511 c1, c2 = C(), C()
512
513 c2.me = c2
514 c2.c1 = c1
515 c2.wr = weakref.ref(c1, c2.cb)
516
517 del c1, c2
518 gc.collect()
519
520 def test_callback_in_cycle_4(self):
521 import gc
522
523 # Like test_callback_in_cycle_3, except c2 and c1 have different
524 # classes. c2's class (C) isn't reachable from c1 then, so protecting
525 # objects reachable from the dying object (c1) isn't enough to stop
526 # c2's class (C) from getting tp_clear'ed before c2.cb is invoked.
527 # The result was a segfault (C.__mro__ was NULL when the callback
528 # tried to look up self.me).
529
530 class C(object):
531 def cb(self, ignore):
532 self.me
533 self.c1
534 self.wr
535
536 class D:
537 pass
538
539 c1, c2 = D(), C()
540
541 c2.me = c2
542 c2.c1 = c1
543 c2.wr = weakref.ref(c1, c2.cb)
544
545 del c1, c2, C, D
546 gc.collect()
547
548 def test_callback_in_cycle_resurrection(self):
549 import gc
550
551 # Do something nasty in a weakref callback: resurrect objects
552 # from dead cycles. For this to be attempted, the weakref and
553 # its callback must also be part of the cyclic trash (else the
554 # objects reachable via the callback couldn't be in cyclic trash
555 # to begin with -- the callback would act like an external root).
556 # But gc clears trash weakrefs with callbacks early now, which
557 # disables the callbacks, so the callbacks shouldn't get called
558 # at all (and so nothing actually gets resurrected).
559
560 alist = []
561 class C(object):
562 def __init__(self, value):
563 self.attribute = value
564
565 def acallback(self, ignore):
566 alist.append(self.c)
567
568 c1, c2 = C(1), C(2)
569 c1.c = c2
570 c2.c = c1
571 c1.wr = weakref.ref(c2, c1.acallback)
572 c2.wr = weakref.ref(c1, c2.acallback)
573
574 def C_went_away(ignore):
575 alist.append("C went away")
576 wr = weakref.ref(C, C_went_away)
577
578 del c1, c2, C # make them all trash
579 self.assertEqual(alist, []) # del isn't enough to reclaim anything
580
581 gc.collect()
582 # c1.wr and c2.wr were part of the cyclic trash, so should have
583 # been cleared without their callbacks executing. OTOH, the weakref
584 # to C is bound to a function local (wr), and wasn't trash, so that
585 # callback should have been invoked when C went away.
586 self.assertEqual(alist, ["C went away"])
587 # The remaining weakref should be dead now (its callback ran).
588 self.assertEqual(wr(), None)
589
590 del alist[:]
591 gc.collect()
592 self.assertEqual(alist, [])
593
594 def test_callbacks_on_callback(self):
595 import gc
596
597 # Set up weakref callbacks *on* weakref callbacks.
598 alist = []
599 def safe_callback(ignore):
600 alist.append("safe_callback called")
601
602 class C(object):
603 def cb(self, ignore):
604 alist.append("cb called")
605
606 c, d = C(), C()
607 c.other = d
608 d.other = c
609 callback = c.cb
610 c.wr = weakref.ref(d, callback) # this won't trigger
611 d.wr = weakref.ref(callback, d.cb) # ditto
612 external_wr = weakref.ref(callback, safe_callback) # but this will
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000613 self.assertTrue(external_wr() is callback)
Tim Peters403a2032003-11-20 21:21:46 +0000614
615 # The weakrefs attached to c and d should get cleared, so that
616 # C.cb is never called. But external_wr isn't part of the cyclic
617 # trash, and no cyclic trash is reachable from it, so safe_callback
618 # should get invoked when the bound method object callback (c.cb)
619 # -- which is itself a callback, and also part of the cyclic trash --
620 # gets reclaimed at the end of gc.
621
622 del callback, c, d, C
623 self.assertEqual(alist, []) # del isn't enough to clean up cycles
624 gc.collect()
625 self.assertEqual(alist, ["safe_callback called"])
626 self.assertEqual(external_wr(), None)
627
628 del alist[:]
629 gc.collect()
630 self.assertEqual(alist, [])
631
Fred Drakebc875f52004-02-04 23:14:14 +0000632 def test_gc_during_ref_creation(self):
633 self.check_gc_during_creation(weakref.ref)
634
635 def test_gc_during_proxy_creation(self):
636 self.check_gc_during_creation(weakref.proxy)
637
638 def check_gc_during_creation(self, makeref):
639 thresholds = gc.get_threshold()
640 gc.set_threshold(1, 1, 1)
641 gc.collect()
Fred Drake55cf4342004-02-13 19:21:57 +0000642 class A:
643 pass
Fred Drakebc875f52004-02-04 23:14:14 +0000644
645 def callback(*args):
646 pass
647
Fred Drake55cf4342004-02-13 19:21:57 +0000648 referenced = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000649
Fred Drake55cf4342004-02-13 19:21:57 +0000650 a = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000651 a.a = a
652 a.wr = makeref(referenced)
653
654 try:
655 # now make sure the object and the ref get labeled as
656 # cyclic trash:
Fred Drake55cf4342004-02-13 19:21:57 +0000657 a = A()
658 weakref.ref(referenced, callback)
Fred Drakebc875f52004-02-04 23:14:14 +0000659
660 finally:
661 gc.set_threshold(*thresholds)
662
Thomas Woutersb2137042007-02-01 18:02:27 +0000663 def test_ref_created_during_del(self):
664 # Bug #1377858
665 # A weakref created in an object's __del__() would crash the
666 # interpreter when the weakref was cleaned up since it would refer to
667 # non-existent memory. This test should not segfault the interpreter.
668 class Target(object):
669 def __del__(self):
670 global ref_from_del
671 ref_from_del = weakref.ref(self)
672
673 w = Target()
674
Benjamin Peterson9aa42992008-09-10 21:57:34 +0000675 def test_init(self):
676 # Issue 3634
677 # <weakref to class>.__init__() doesn't check errors correctly
678 r = weakref.ref(Exception)
679 self.assertRaises(TypeError, r.__init__, 0, 0, 0, 0, 0)
680 # No exception should be raised here
681 gc.collect()
682
Antoine Pitrou3af01a12010-03-31 21:40:47 +0000683 def test_classes(self):
684 # Check that classes are weakrefable.
685 class A(object):
686 pass
687 l = []
688 weakref.ref(int)
689 a = weakref.ref(A, l.append)
690 A = None
691 gc.collect()
692 self.assertEqual(a(), None)
693 self.assertEqual(l, [a])
694
Fred Drake0a4dd392004-07-02 18:57:45 +0000695
Amaury Forgeot d'Arcc856c7a2008-06-16 19:50:09 +0000696class SubclassableWeakrefTestCase(TestBase):
Fred Drake0a4dd392004-07-02 18:57:45 +0000697
698 def test_subclass_refs(self):
699 class MyRef(weakref.ref):
700 def __init__(self, ob, callback=None, value=42):
701 self.value = value
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000702 super().__init__(ob, callback)
Fred Drake0a4dd392004-07-02 18:57:45 +0000703 def __call__(self):
704 self.called = True
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000705 return super().__call__()
Fred Drake0a4dd392004-07-02 18:57:45 +0000706 o = Object("foo")
707 mr = MyRef(o, value=24)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000708 self.assertTrue(mr() is o)
709 self.assertTrue(mr.called)
Fred Drake0a4dd392004-07-02 18:57:45 +0000710 self.assertEqual(mr.value, 24)
711 del o
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000712 self.assertTrue(mr() is None)
713 self.assertTrue(mr.called)
Fred Drake0a4dd392004-07-02 18:57:45 +0000714
715 def test_subclass_refs_dont_replace_standard_refs(self):
716 class MyRef(weakref.ref):
717 pass
718 o = Object(42)
719 r1 = MyRef(o)
720 r2 = weakref.ref(o)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000721 self.assertTrue(r1 is not r2)
Fred Drake0a4dd392004-07-02 18:57:45 +0000722 self.assertEqual(weakref.getweakrefs(o), [r2, r1])
723 self.assertEqual(weakref.getweakrefcount(o), 2)
724 r3 = MyRef(o)
725 self.assertEqual(weakref.getweakrefcount(o), 3)
726 refs = weakref.getweakrefs(o)
727 self.assertEqual(len(refs), 3)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000728 self.assertTrue(r2 is refs[0])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000729 self.assertIn(r1, refs[1:])
730 self.assertIn(r3, refs[1:])
Fred Drake0a4dd392004-07-02 18:57:45 +0000731
732 def test_subclass_refs_dont_conflate_callbacks(self):
733 class MyRef(weakref.ref):
734 pass
735 o = Object(42)
736 r1 = MyRef(o, id)
737 r2 = MyRef(o, str)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000738 self.assertTrue(r1 is not r2)
Fred Drake0a4dd392004-07-02 18:57:45 +0000739 refs = weakref.getweakrefs(o)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000740 self.assertIn(r1, refs)
741 self.assertIn(r2, refs)
Fred Drake0a4dd392004-07-02 18:57:45 +0000742
743 def test_subclass_refs_with_slots(self):
744 class MyRef(weakref.ref):
745 __slots__ = "slot1", "slot2"
746 def __new__(type, ob, callback, slot1, slot2):
747 return weakref.ref.__new__(type, ob, callback)
748 def __init__(self, ob, callback, slot1, slot2):
749 self.slot1 = slot1
750 self.slot2 = slot2
751 def meth(self):
752 return self.slot1 + self.slot2
753 o = Object(42)
754 r = MyRef(o, None, "abc", "def")
755 self.assertEqual(r.slot1, "abc")
756 self.assertEqual(r.slot2, "def")
757 self.assertEqual(r.meth(), "abcdef")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000758 self.assertFalse(hasattr(r, "__dict__"))
Fred Drake0a4dd392004-07-02 18:57:45 +0000759
Amaury Forgeot d'Arcc856c7a2008-06-16 19:50:09 +0000760 def test_subclass_refs_with_cycle(self):
761 # Bug #3110
762 # An instance of a weakref subclass can have attributes.
763 # If such a weakref holds the only strong reference to the object,
764 # deleting the weakref will delete the object. In this case,
765 # the callback must not be called, because the ref object is
766 # being deleted.
767 class MyRef(weakref.ref):
768 pass
769
770 # Use a local callback, for "regrtest -R::"
771 # to detect refcounting problems
772 def callback(w):
773 self.cbcalled += 1
774
775 o = C()
776 r1 = MyRef(o, callback)
777 r1.o = o
778 del o
779
780 del r1 # Used to crash here
781
782 self.assertEqual(self.cbcalled, 0)
783
784 # Same test, with two weakrefs to the same object
785 # (since code paths are different)
786 o = C()
787 r1 = MyRef(o, callback)
788 r2 = MyRef(o, callback)
789 r1.r = r2
790 r2.o = o
791 del o
792 del r2
793
794 del r1 # Used to crash here
795
796 self.assertEqual(self.cbcalled, 0)
797
Fred Drake0a4dd392004-07-02 18:57:45 +0000798
Fred Drake41deb1e2001-02-01 05:27:45 +0000799class Object:
800 def __init__(self, arg):
801 self.arg = arg
802 def __repr__(self):
803 return "<Object %r>" % self.arg
Antoine Pitrouc1baa602010-01-08 17:54:23 +0000804 def __eq__(self, other):
805 if isinstance(other, Object):
806 return self.arg == other.arg
807 return NotImplemented
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000808 def __lt__(self, other):
809 if isinstance(other, Object):
810 return self.arg < other.arg
811 return NotImplemented
812 def __hash__(self):
813 return hash(self.arg)
Fred Drake41deb1e2001-02-01 05:27:45 +0000814
Antoine Pitroubbe2f602012-03-01 16:26:35 +0100815class RefCycle:
816 def __init__(self):
817 self.cycle = self
818
Fred Drake41deb1e2001-02-01 05:27:45 +0000819
Fred Drakeb0fefc52001-03-23 04:22:45 +0000820class MappingTestCase(TestBase):
Martin v. Löwis5e163332001-02-27 18:36:56 +0000821
Fred Drakeb0fefc52001-03-23 04:22:45 +0000822 COUNT = 10
823
Antoine Pitroubbe2f602012-03-01 16:26:35 +0100824 def check_len_cycles(self, dict_type, cons):
825 N = 20
826 items = [RefCycle() for i in range(N)]
827 dct = dict_type(cons(o) for o in items)
828 # Keep an iterator alive
829 it = dct.items()
830 try:
831 next(it)
832 except StopIteration:
833 pass
834 del items
835 gc.collect()
836 n1 = len(dct)
837 del it
838 gc.collect()
839 n2 = len(dct)
840 # one item may be kept alive inside the iterator
841 self.assertIn(n1, (0, 1))
842 self.assertEqual(n2, 0)
843
844 def test_weak_keyed_len_cycles(self):
845 self.check_len_cycles(weakref.WeakKeyDictionary, lambda k: (k, 1))
846
847 def test_weak_valued_len_cycles(self):
848 self.check_len_cycles(weakref.WeakValueDictionary, lambda k: (1, k))
849
850 def check_len_race(self, dict_type, cons):
851 # Extended sanity checks for len() in the face of cyclic collection
852 self.addCleanup(gc.set_threshold, *gc.get_threshold())
853 for th in range(1, 100):
854 N = 20
855 gc.collect(0)
856 gc.set_threshold(th, th, th)
857 items = [RefCycle() for i in range(N)]
858 dct = dict_type(cons(o) for o in items)
859 del items
860 # All items will be collected at next garbage collection pass
861 it = dct.items()
862 try:
863 next(it)
864 except StopIteration:
865 pass
866 n1 = len(dct)
867 del it
868 n2 = len(dct)
869 self.assertGreaterEqual(n1, 0)
870 self.assertLessEqual(n1, N)
871 self.assertGreaterEqual(n2, 0)
872 self.assertLessEqual(n2, n1)
873
874 def test_weak_keyed_len_race(self):
875 self.check_len_race(weakref.WeakKeyDictionary, lambda k: (k, 1))
876
877 def test_weak_valued_len_race(self):
878 self.check_len_race(weakref.WeakValueDictionary, lambda k: (1, k))
879
Fred Drakeb0fefc52001-03-23 04:22:45 +0000880 def test_weak_values(self):
Fred Drake0e540c32001-05-02 05:44:22 +0000881 #
882 # This exercises d.copy(), d.items(), d[], del d[], len(d).
883 #
884 dict, objects = self.make_weak_valued_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +0000885 for o in objects:
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000886 self.assertEqual(weakref.getweakrefcount(o), 1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000887 self.assertTrue(o is dict[o.arg],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000888 "wrong object returned by weak dict!")
Barry Warsawecaab832008-09-04 01:42:51 +0000889 items1 = list(dict.items())
890 items2 = list(dict.copy().items())
Fred Drakeb0fefc52001-03-23 04:22:45 +0000891 items1.sort()
892 items2.sort()
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000893 self.assertEqual(items1, items2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000894 "cloning of weak-valued dictionary did not work!")
895 del items1, items2
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000896 self.assertEqual(len(dict), self.COUNT)
Fred Drakeb0fefc52001-03-23 04:22:45 +0000897 del objects[0]
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000898 self.assertEqual(len(dict), self.COUNT - 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000899 "deleting object did not cause dictionary update")
900 del objects, o
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000901 self.assertEqual(len(dict), 0,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000902 "deleting the values did not clear the dictionary")
Fred Drake4fd06e02001-08-03 04:11:27 +0000903 # regression on SF bug #447152:
904 dict = weakref.WeakValueDictionary()
905 self.assertRaises(KeyError, dict.__getitem__, 1)
906 dict[2] = C()
907 self.assertRaises(KeyError, dict.__getitem__, 2)
Fred Drakeb0fefc52001-03-23 04:22:45 +0000908
909 def test_weak_keys(self):
Fred Drake0e540c32001-05-02 05:44:22 +0000910 #
911 # This exercises d.copy(), d.items(), d[] = v, d[], del d[],
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000912 # len(d), k in d.
Fred Drake0e540c32001-05-02 05:44:22 +0000913 #
914 dict, objects = self.make_weak_keyed_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +0000915 for o in objects:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000916 self.assertTrue(weakref.getweakrefcount(o) == 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000917 "wrong number of weak references to %r!" % o)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000918 self.assertTrue(o.arg is dict[o],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000919 "wrong object returned by weak dict!")
920 items1 = dict.items()
921 items2 = dict.copy().items()
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000922 self.assertEqual(set(items1), set(items2),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000923 "cloning of weak-keyed dictionary did not work!")
924 del items1, items2
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000925 self.assertEqual(len(dict), self.COUNT)
Fred Drakeb0fefc52001-03-23 04:22:45 +0000926 del objects[0]
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000927 self.assertTrue(len(dict) == (self.COUNT - 1),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000928 "deleting object did not cause dictionary update")
929 del objects, o
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000930 self.assertTrue(len(dict) == 0,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000931 "deleting the keys did not clear the dictionary")
Fred Drake752eda42001-11-06 16:38:34 +0000932 o = Object(42)
933 dict[o] = "What is the meaning of the universe?"
Benjamin Peterson577473f2010-01-19 00:09:57 +0000934 self.assertIn(o, dict)
935 self.assertNotIn(34, dict)
Martin v. Löwis5e163332001-02-27 18:36:56 +0000936
Fred Drake0e540c32001-05-02 05:44:22 +0000937 def test_weak_keyed_iters(self):
938 dict, objects = self.make_weak_keyed_dict()
939 self.check_iters(dict)
940
Thomas Wouters477c8d52006-05-27 19:21:47 +0000941 # Test keyrefs()
942 refs = dict.keyrefs()
943 self.assertEqual(len(refs), len(objects))
944 objects2 = list(objects)
945 for wr in refs:
946 ob = wr()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000947 self.assertIn(ob, dict)
948 self.assertIn(ob, dict)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000949 self.assertEqual(ob.arg, dict[ob])
950 objects2.remove(ob)
951 self.assertEqual(len(objects2), 0)
952
953 # Test iterkeyrefs()
954 objects2 = list(objects)
Barry Warsawecaab832008-09-04 01:42:51 +0000955 self.assertEqual(len(list(dict.keyrefs())), len(objects))
956 for wr in dict.keyrefs():
Thomas Wouters477c8d52006-05-27 19:21:47 +0000957 ob = wr()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000958 self.assertIn(ob, dict)
959 self.assertIn(ob, dict)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000960 self.assertEqual(ob.arg, dict[ob])
961 objects2.remove(ob)
962 self.assertEqual(len(objects2), 0)
963
Fred Drake0e540c32001-05-02 05:44:22 +0000964 def test_weak_valued_iters(self):
965 dict, objects = self.make_weak_valued_dict()
966 self.check_iters(dict)
967
Thomas Wouters477c8d52006-05-27 19:21:47 +0000968 # Test valuerefs()
969 refs = dict.valuerefs()
970 self.assertEqual(len(refs), len(objects))
971 objects2 = list(objects)
972 for wr in refs:
973 ob = wr()
974 self.assertEqual(ob, dict[ob.arg])
975 self.assertEqual(ob.arg, dict[ob.arg].arg)
976 objects2.remove(ob)
977 self.assertEqual(len(objects2), 0)
978
979 # Test itervaluerefs()
980 objects2 = list(objects)
981 self.assertEqual(len(list(dict.itervaluerefs())), len(objects))
982 for wr in dict.itervaluerefs():
983 ob = wr()
984 self.assertEqual(ob, dict[ob.arg])
985 self.assertEqual(ob.arg, dict[ob.arg].arg)
986 objects2.remove(ob)
987 self.assertEqual(len(objects2), 0)
988
Fred Drake0e540c32001-05-02 05:44:22 +0000989 def check_iters(self, dict):
990 # item iterator:
Barry Warsawecaab832008-09-04 01:42:51 +0000991 items = list(dict.items())
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000992 for item in dict.items():
Fred Drake0e540c32001-05-02 05:44:22 +0000993 items.remove(item)
Barry Warsawecaab832008-09-04 01:42:51 +0000994 self.assertFalse(items, "items() did not touch all items")
Fred Drake0e540c32001-05-02 05:44:22 +0000995
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000996 # key iterator, via __iter__():
Guido van Rossum07f24362007-02-11 22:59:48 +0000997 keys = list(dict.keys())
Fred Drake0e540c32001-05-02 05:44:22 +0000998 for k in dict:
999 keys.remove(k)
Barry Warsawecaab832008-09-04 01:42:51 +00001000 self.assertFalse(keys, "__iter__() did not touch all keys")
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001001
1002 # key iterator, via iterkeys():
Guido van Rossum07f24362007-02-11 22:59:48 +00001003 keys = list(dict.keys())
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001004 for k in dict.keys():
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001005 keys.remove(k)
Barry Warsawecaab832008-09-04 01:42:51 +00001006 self.assertFalse(keys, "iterkeys() did not touch all keys")
Fred Drake0e540c32001-05-02 05:44:22 +00001007
1008 # value iterator:
Guido van Rossum07f24362007-02-11 22:59:48 +00001009 values = list(dict.values())
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001010 for v in dict.values():
Fred Drake0e540c32001-05-02 05:44:22 +00001011 values.remove(v)
Barry Warsawecaab832008-09-04 01:42:51 +00001012 self.assertFalse(values,
Fred Drakef425b1e2003-07-14 21:37:17 +00001013 "itervalues() did not touch all values")
Fred Drake0e540c32001-05-02 05:44:22 +00001014
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001015 def check_weak_destroy_while_iterating(self, dict, objects, iter_name):
1016 n = len(dict)
1017 it = iter(getattr(dict, iter_name)())
1018 next(it) # Trigger internal iteration
1019 # Destroy an object
1020 del objects[-1]
1021 gc.collect() # just in case
1022 # We have removed either the first consumed object, or another one
1023 self.assertIn(len(list(it)), [len(objects), len(objects) - 1])
1024 del it
1025 # The removal has been committed
1026 self.assertEqual(len(dict), n - 1)
1027
1028 def check_weak_destroy_and_mutate_while_iterating(self, dict, testcontext):
1029 # Check that we can explicitly mutate the weak dict without
1030 # interfering with delayed removal.
1031 # `testcontext` should create an iterator, destroy one of the
1032 # weakref'ed objects and then return a new key/value pair corresponding
1033 # to the destroyed object.
1034 with testcontext() as (k, v):
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001035 self.assertNotIn(k, dict)
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001036 with testcontext() as (k, v):
1037 self.assertRaises(KeyError, dict.__delitem__, k)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001038 self.assertNotIn(k, dict)
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001039 with testcontext() as (k, v):
1040 self.assertRaises(KeyError, dict.pop, k)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001041 self.assertNotIn(k, dict)
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001042 with testcontext() as (k, v):
1043 dict[k] = v
1044 self.assertEqual(dict[k], v)
1045 ddict = copy.copy(dict)
1046 with testcontext() as (k, v):
1047 dict.update(ddict)
1048 self.assertEqual(dict, ddict)
1049 with testcontext() as (k, v):
1050 dict.clear()
1051 self.assertEqual(len(dict), 0)
1052
1053 def test_weak_keys_destroy_while_iterating(self):
1054 # Issue #7105: iterators shouldn't crash when a key is implicitly removed
1055 dict, objects = self.make_weak_keyed_dict()
1056 self.check_weak_destroy_while_iterating(dict, objects, 'keys')
1057 self.check_weak_destroy_while_iterating(dict, objects, 'items')
1058 self.check_weak_destroy_while_iterating(dict, objects, 'values')
1059 self.check_weak_destroy_while_iterating(dict, objects, 'keyrefs')
1060 dict, objects = self.make_weak_keyed_dict()
1061 @contextlib.contextmanager
1062 def testcontext():
1063 try:
1064 it = iter(dict.items())
1065 next(it)
1066 # Schedule a key/value for removal and recreate it
1067 v = objects.pop().arg
1068 gc.collect() # just in case
1069 yield Object(v), v
1070 finally:
1071 it = None # should commit all removals
1072 self.check_weak_destroy_and_mutate_while_iterating(dict, testcontext)
1073
1074 def test_weak_values_destroy_while_iterating(self):
1075 # Issue #7105: iterators shouldn't crash when a key is implicitly removed
1076 dict, objects = self.make_weak_valued_dict()
1077 self.check_weak_destroy_while_iterating(dict, objects, 'keys')
1078 self.check_weak_destroy_while_iterating(dict, objects, 'items')
1079 self.check_weak_destroy_while_iterating(dict, objects, 'values')
1080 self.check_weak_destroy_while_iterating(dict, objects, 'itervaluerefs')
1081 self.check_weak_destroy_while_iterating(dict, objects, 'valuerefs')
1082 dict, objects = self.make_weak_valued_dict()
1083 @contextlib.contextmanager
1084 def testcontext():
1085 try:
1086 it = iter(dict.items())
1087 next(it)
1088 # Schedule a key/value for removal and recreate it
1089 k = objects.pop().arg
1090 gc.collect() # just in case
1091 yield k, Object(k)
1092 finally:
1093 it = None # should commit all removals
1094 self.check_weak_destroy_and_mutate_while_iterating(dict, testcontext)
1095
Guido van Rossum009afb72002-06-10 20:00:52 +00001096 def test_make_weak_keyed_dict_from_dict(self):
1097 o = Object(3)
1098 dict = weakref.WeakKeyDictionary({o:364})
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001099 self.assertEqual(dict[o], 364)
Guido van Rossum009afb72002-06-10 20:00:52 +00001100
1101 def test_make_weak_keyed_dict_from_weak_keyed_dict(self):
1102 o = Object(3)
1103 dict = weakref.WeakKeyDictionary({o:364})
1104 dict2 = weakref.WeakKeyDictionary(dict)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001105 self.assertEqual(dict[o], 364)
Guido van Rossum009afb72002-06-10 20:00:52 +00001106
Fred Drake0e540c32001-05-02 05:44:22 +00001107 def make_weak_keyed_dict(self):
1108 dict = weakref.WeakKeyDictionary()
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001109 objects = list(map(Object, range(self.COUNT)))
Fred Drake0e540c32001-05-02 05:44:22 +00001110 for o in objects:
1111 dict[o] = o.arg
1112 return dict, objects
1113
Antoine Pitrouc06de472009-05-30 21:04:26 +00001114 def test_make_weak_valued_dict_from_dict(self):
1115 o = Object(3)
1116 dict = weakref.WeakValueDictionary({364:o})
1117 self.assertEqual(dict[364], o)
1118
1119 def test_make_weak_valued_dict_from_weak_valued_dict(self):
1120 o = Object(3)
1121 dict = weakref.WeakValueDictionary({364:o})
1122 dict2 = weakref.WeakValueDictionary(dict)
1123 self.assertEqual(dict[364], o)
1124
Fred Drake0e540c32001-05-02 05:44:22 +00001125 def make_weak_valued_dict(self):
1126 dict = weakref.WeakValueDictionary()
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001127 objects = list(map(Object, range(self.COUNT)))
Fred Drake0e540c32001-05-02 05:44:22 +00001128 for o in objects:
1129 dict[o.arg] = o
1130 return dict, objects
1131
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001132 def check_popitem(self, klass, key1, value1, key2, value2):
1133 weakdict = klass()
1134 weakdict[key1] = value1
1135 weakdict[key2] = value2
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001136 self.assertEqual(len(weakdict), 2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001137 k, v = weakdict.popitem()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001138 self.assertEqual(len(weakdict), 1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001139 if k is key1:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001140 self.assertTrue(v is value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001141 else:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001142 self.assertTrue(v is value2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001143 k, v = weakdict.popitem()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001144 self.assertEqual(len(weakdict), 0)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001145 if k is key1:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001146 self.assertTrue(v is value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001147 else:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001148 self.assertTrue(v is value2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001149
1150 def test_weak_valued_dict_popitem(self):
1151 self.check_popitem(weakref.WeakValueDictionary,
1152 "key1", C(), "key2", C())
1153
1154 def test_weak_keyed_dict_popitem(self):
1155 self.check_popitem(weakref.WeakKeyDictionary,
1156 C(), "value 1", C(), "value 2")
1157
1158 def check_setdefault(self, klass, key, value1, value2):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001159 self.assertTrue(value1 is not value2,
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001160 "invalid test"
1161 " -- value parameters must be distinct objects")
1162 weakdict = klass()
1163 o = weakdict.setdefault(key, value1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001164 self.assertTrue(o is value1)
Benjamin Peterson577473f2010-01-19 00:09:57 +00001165 self.assertIn(key, weakdict)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001166 self.assertTrue(weakdict.get(key) is value1)
1167 self.assertTrue(weakdict[key] is value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001168
1169 o = weakdict.setdefault(key, value2)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001170 self.assertTrue(o is value1)
Benjamin Peterson577473f2010-01-19 00:09:57 +00001171 self.assertIn(key, weakdict)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001172 self.assertTrue(weakdict.get(key) is value1)
1173 self.assertTrue(weakdict[key] is value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001174
1175 def test_weak_valued_dict_setdefault(self):
1176 self.check_setdefault(weakref.WeakValueDictionary,
1177 "key", C(), C())
1178
1179 def test_weak_keyed_dict_setdefault(self):
1180 self.check_setdefault(weakref.WeakKeyDictionary,
1181 C(), "value 1", "value 2")
1182
Fred Drakea0a4ab12001-04-16 17:37:27 +00001183 def check_update(self, klass, dict):
Fred Drake0e540c32001-05-02 05:44:22 +00001184 #
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001185 # This exercises d.update(), len(d), d.keys(), k in d,
Fred Drake0e540c32001-05-02 05:44:22 +00001186 # d.get(), d[].
1187 #
Fred Drakea0a4ab12001-04-16 17:37:27 +00001188 weakdict = klass()
1189 weakdict.update(dict)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001190 self.assertEqual(len(weakdict), len(dict))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001191 for k in weakdict.keys():
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001192 self.assertIn(k, dict, "mysterious new key appeared in weak dict")
Fred Drakea0a4ab12001-04-16 17:37:27 +00001193 v = dict.get(k)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001194 self.assertTrue(v is weakdict[k])
1195 self.assertTrue(v is weakdict.get(k))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001196 for k in dict.keys():
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001197 self.assertIn(k, weakdict, "original key disappeared in weak dict")
Fred Drakea0a4ab12001-04-16 17:37:27 +00001198 v = dict[k]
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001199 self.assertTrue(v is weakdict[k])
1200 self.assertTrue(v is weakdict.get(k))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001201
1202 def test_weak_valued_dict_update(self):
1203 self.check_update(weakref.WeakValueDictionary,
1204 {1: C(), 'a': C(), C(): C()})
1205
1206 def test_weak_keyed_dict_update(self):
1207 self.check_update(weakref.WeakKeyDictionary,
1208 {C(): 1, C(): 2, C(): 3})
1209
Fred Drakeccc75622001-09-06 14:52:39 +00001210 def test_weak_keyed_delitem(self):
1211 d = weakref.WeakKeyDictionary()
1212 o1 = Object('1')
1213 o2 = Object('2')
1214 d[o1] = 'something'
1215 d[o2] = 'something'
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001216 self.assertEqual(len(d), 2)
Fred Drakeccc75622001-09-06 14:52:39 +00001217 del d[o1]
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001218 self.assertEqual(len(d), 1)
Barry Warsawecaab832008-09-04 01:42:51 +00001219 self.assertEqual(list(d.keys()), [o2])
Fred Drakeccc75622001-09-06 14:52:39 +00001220
1221 def test_weak_valued_delitem(self):
1222 d = weakref.WeakValueDictionary()
1223 o1 = Object('1')
1224 o2 = Object('2')
1225 d['something'] = o1
1226 d['something else'] = o2
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001227 self.assertEqual(len(d), 2)
Fred Drakeccc75622001-09-06 14:52:39 +00001228 del d['something']
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001229 self.assertEqual(len(d), 1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001230 self.assertTrue(list(d.items()) == [('something else', o2)])
Fred Drakeccc75622001-09-06 14:52:39 +00001231
Tim Peters886128f2003-05-25 01:45:11 +00001232 def test_weak_keyed_bad_delitem(self):
1233 d = weakref.WeakKeyDictionary()
1234 o = Object('1')
1235 # An attempt to delete an object that isn't there should raise
Tim Peters50d8b8b2003-05-25 17:44:31 +00001236 # KeyError. It didn't before 2.3.
Tim Peters886128f2003-05-25 01:45:11 +00001237 self.assertRaises(KeyError, d.__delitem__, o)
Tim Peters50d8b8b2003-05-25 17:44:31 +00001238 self.assertRaises(KeyError, d.__getitem__, o)
1239
1240 # If a key isn't of a weakly referencable type, __getitem__ and
1241 # __setitem__ raise TypeError. __delitem__ should too.
1242 self.assertRaises(TypeError, d.__delitem__, 13)
1243 self.assertRaises(TypeError, d.__getitem__, 13)
1244 self.assertRaises(TypeError, d.__setitem__, 13, 13)
Tim Peters886128f2003-05-25 01:45:11 +00001245
1246 def test_weak_keyed_cascading_deletes(self):
1247 # SF bug 742860. For some reason, before 2.3 __delitem__ iterated
1248 # over the keys via self.data.iterkeys(). If things vanished from
1249 # the dict during this (or got added), that caused a RuntimeError.
1250
1251 d = weakref.WeakKeyDictionary()
1252 mutate = False
1253
1254 class C(object):
1255 def __init__(self, i):
1256 self.value = i
1257 def __hash__(self):
1258 return hash(self.value)
1259 def __eq__(self, other):
1260 if mutate:
1261 # Side effect that mutates the dict, by removing the
1262 # last strong reference to a key.
1263 del objs[-1]
1264 return self.value == other.value
1265
1266 objs = [C(i) for i in range(4)]
1267 for o in objs:
1268 d[o] = o.value
1269 del o # now the only strong references to keys are in objs
1270 # Find the order in which iterkeys sees the keys.
Barry Warsawecaab832008-09-04 01:42:51 +00001271 objs = list(d.keys())
Tim Peters886128f2003-05-25 01:45:11 +00001272 # Reverse it, so that the iteration implementation of __delitem__
1273 # has to keep looping to find the first object we delete.
1274 objs.reverse()
Tim Peters50d8b8b2003-05-25 17:44:31 +00001275
Tim Peters886128f2003-05-25 01:45:11 +00001276 # Turn on mutation in C.__eq__. The first time thru the loop,
1277 # under the iterkeys() business the first comparison will delete
1278 # the last item iterkeys() would see, and that causes a
1279 # RuntimeError: dictionary changed size during iteration
1280 # when the iterkeys() loop goes around to try comparing the next
Tim Peters50d8b8b2003-05-25 17:44:31 +00001281 # key. After this was fixed, it just deletes the last object *our*
Tim Peters886128f2003-05-25 01:45:11 +00001282 # "for o in obj" loop would have gotten to.
1283 mutate = True
1284 count = 0
1285 for o in objs:
1286 count += 1
1287 del d[o]
1288 self.assertEqual(len(d), 0)
1289 self.assertEqual(count, 2)
1290
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001291from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001292
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001293class WeakValueDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +00001294 """Check that WeakValueDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001295 __ref = {"key1":Object(1), "key2":Object(2), "key3":Object(3)}
Walter Dörwald118f9312004-06-02 18:42:25 +00001296 type2test = weakref.WeakValueDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001297 def _reference(self):
1298 return self.__ref.copy()
1299
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001300class WeakKeyDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +00001301 """Check that WeakKeyDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001302 __ref = {Object("key1"):1, Object("key2"):2, Object("key3"):3}
Walter Dörwald118f9312004-06-02 18:42:25 +00001303 type2test = weakref.WeakKeyDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001304 def _reference(self):
1305 return self.__ref.copy()
Martin v. Löwis5e163332001-02-27 18:36:56 +00001306
Georg Brandlb533e262008-05-25 18:19:30 +00001307libreftest = """ Doctest for examples in the library reference: weakref.rst
Georg Brandl9a65d582005-07-02 19:07:30 +00001308
1309>>> import weakref
1310>>> class Dict(dict):
1311... pass
1312...
1313>>> obj = Dict(red=1, green=2, blue=3) # this object is weak referencable
1314>>> r = weakref.ref(obj)
Guido van Rossum7131f842007-02-09 20:13:25 +00001315>>> print(r() is obj)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001316True
Georg Brandl9a65d582005-07-02 19:07:30 +00001317
1318>>> import weakref
1319>>> class Object:
1320... pass
1321...
1322>>> o = Object()
1323>>> r = weakref.ref(o)
1324>>> o2 = r()
1325>>> o is o2
1326True
1327>>> del o, o2
Guido van Rossum7131f842007-02-09 20:13:25 +00001328>>> print(r())
Georg Brandl9a65d582005-07-02 19:07:30 +00001329None
1330
1331>>> import weakref
1332>>> class ExtendedRef(weakref.ref):
1333... def __init__(self, ob, callback=None, **annotations):
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001334... super().__init__(ob, callback)
Georg Brandl9a65d582005-07-02 19:07:30 +00001335... self.__counter = 0
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001336... for k, v in annotations.items():
Georg Brandl9a65d582005-07-02 19:07:30 +00001337... setattr(self, k, v)
1338... def __call__(self):
1339... '''Return a pair containing the referent and the number of
1340... times the reference has been called.
1341... '''
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001342... ob = super().__call__()
Georg Brandl9a65d582005-07-02 19:07:30 +00001343... if ob is not None:
1344... self.__counter += 1
1345... ob = (ob, self.__counter)
1346... return ob
Guido van Rossumd8faa362007-04-27 19:54:29 +00001347...
Georg Brandl9a65d582005-07-02 19:07:30 +00001348>>> class A: # not in docs from here, just testing the ExtendedRef
1349... pass
1350...
1351>>> a = A()
1352>>> r = ExtendedRef(a, foo=1, bar="baz")
1353>>> r.foo
13541
1355>>> r.bar
1356'baz'
1357>>> r()[1]
13581
1359>>> r()[1]
13602
1361>>> r()[0] is a
1362True
1363
1364
1365>>> import weakref
1366>>> _id2obj_dict = weakref.WeakValueDictionary()
1367>>> def remember(obj):
1368... oid = id(obj)
1369... _id2obj_dict[oid] = obj
1370... return oid
1371...
1372>>> def id2obj(oid):
1373... return _id2obj_dict[oid]
1374...
1375>>> a = A() # from here, just testing
1376>>> a_id = remember(a)
1377>>> id2obj(a_id) is a
1378True
1379>>> del a
1380>>> try:
1381... id2obj(a_id)
1382... except KeyError:
Guido van Rossum7131f842007-02-09 20:13:25 +00001383... print('OK')
Georg Brandl9a65d582005-07-02 19:07:30 +00001384... else:
Guido van Rossum7131f842007-02-09 20:13:25 +00001385... print('WeakValueDictionary error')
Georg Brandl9a65d582005-07-02 19:07:30 +00001386OK
1387
1388"""
1389
1390__test__ = {'libreftest' : libreftest}
1391
Fred Drake2e2be372001-09-20 21:33:42 +00001392def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001393 support.run_unittest(
Walter Dörwald21d3a322003-05-01 17:45:56 +00001394 ReferencesTestCase,
1395 MappingTestCase,
1396 WeakValueDictionaryTestCase,
Fred Drakef425b1e2003-07-14 21:37:17 +00001397 WeakKeyDictionaryTestCase,
Amaury Forgeot d'Arcc856c7a2008-06-16 19:50:09 +00001398 SubclassableWeakrefTestCase,
Fred Drakef425b1e2003-07-14 21:37:17 +00001399 )
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001400 support.run_doctest(sys.modules[__name__])
Fred Drake2e2be372001-09-20 21:33:42 +00001401
1402
1403if __name__ == "__main__":
1404 test_main()