blob: cc0a755edc416478e6e0e97f1dd7e4b64a904fb4 [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
Fred Drake5935ff02001-12-19 16:54:23 +00004import UserList
Fred Drake41deb1e2001-02-01 05:27:45 +00005import weakref
Georg Brandl88659b02008-05-20 08:40:43 +00006import operator
Kristján Valur Jónsson222b2842013-12-05 10:03:45 +00007import contextlib
8import copy
Fred Drake41deb1e2001-02-01 05:27:45 +00009
Barry Warsaw04f357c2002-07-23 19:04:11 +000010from test import test_support
Fred Drake41deb1e2001-02-01 05:27:45 +000011
Brett Cannonf5bee302007-01-23 23:21:22 +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
34def create_unbound_method():
35 return C.method
Fred Drake41deb1e2001-02-01 05:27:45 +000036
37
Antoine Pitroub704eab2012-11-11 19:36:51 +010038class Object:
39 def __init__(self, arg):
40 self.arg = arg
41 def __repr__(self):
42 return "<Object %r>" % self.arg
43 def __eq__(self, other):
44 if isinstance(other, Object):
45 return self.arg == other.arg
46 return NotImplemented
47 def __ne__(self, other):
48 if isinstance(other, Object):
49 return self.arg != other.arg
50 return NotImplemented
51 def __hash__(self):
52 return hash(self.arg)
53
54class RefCycle:
55 def __init__(self):
56 self.cycle = self
57
58
Fred Drakeb0fefc52001-03-23 04:22:45 +000059class TestBase(unittest.TestCase):
60
61 def setUp(self):
62 self.cbcalled = 0
63
64 def callback(self, ref):
65 self.cbcalled += 1
Fred Drake41deb1e2001-02-01 05:27:45 +000066
67
Fred Drakeb0fefc52001-03-23 04:22:45 +000068class ReferencesTestCase(TestBase):
Fred Drake41deb1e2001-02-01 05:27:45 +000069
Fred Drakeb0fefc52001-03-23 04:22:45 +000070 def test_basic_ref(self):
71 self.check_basic_ref(C)
72 self.check_basic_ref(create_function)
73 self.check_basic_ref(create_bound_method)
74 self.check_basic_ref(create_unbound_method)
Fred Drake41deb1e2001-02-01 05:27:45 +000075
Fred Drake43735da2002-04-11 03:59:42 +000076 # Just make sure the tp_repr handler doesn't raise an exception.
77 # Live reference:
78 o = C()
79 wr = weakref.ref(o)
Florent Xicluna07627882010-03-21 01:14:24 +000080 repr(wr)
Fred Drake43735da2002-04-11 03:59:42 +000081 # Dead reference:
82 del o
Florent Xicluna07627882010-03-21 01:14:24 +000083 repr(wr)
Fred Drake43735da2002-04-11 03:59:42 +000084
Fred Drakeb0fefc52001-03-23 04:22:45 +000085 def test_basic_callback(self):
86 self.check_basic_callback(C)
87 self.check_basic_callback(create_function)
88 self.check_basic_callback(create_bound_method)
89 self.check_basic_callback(create_unbound_method)
Fred Drake41deb1e2001-02-01 05:27:45 +000090
Fred Drakeb0fefc52001-03-23 04:22:45 +000091 def test_multiple_callbacks(self):
92 o = C()
93 ref1 = weakref.ref(o, self.callback)
94 ref2 = weakref.ref(o, self.callback)
95 del o
Serhiy Storchakaca626b12013-11-17 13:20:50 +020096 self.assertIsNone(ref1(), "expected reference to be invalidated")
97 self.assertIsNone(ref2(), "expected reference to be invalidated")
98 self.assertEqual(self.cbcalled, 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +000099 "callback not called the right number of times")
Fred Drake41deb1e2001-02-01 05:27:45 +0000100
Fred Drake705088e2001-04-13 17:18:15 +0000101 def test_multiple_selfref_callbacks(self):
Guido van Rossum9eee5542002-08-22 20:21:30 +0000102 # Make sure all references are invalidated before callbacks are called
Fred Drake705088e2001-04-13 17:18:15 +0000103 #
104 # What's important here is that we're using the first
105 # reference in the callback invoked on the second reference
106 # (the most recently created ref is cleaned up first). This
107 # tests that all references to the object are invalidated
108 # before any of the callbacks are invoked, so that we only
109 # have one invocation of _weakref.c:cleanup_helper() active
110 # for a particular object at a time.
111 #
112 def callback(object, self=self):
113 self.ref()
114 c = C()
115 self.ref = weakref.ref(c, callback)
116 ref1 = weakref.ref(c, callback)
117 del c
118
Fred Drakeb0fefc52001-03-23 04:22:45 +0000119 def test_proxy_ref(self):
120 o = C()
121 o.bar = 1
122 ref1 = weakref.proxy(o, self.callback)
123 ref2 = weakref.proxy(o, self.callback)
124 del o
Fred Drake41deb1e2001-02-01 05:27:45 +0000125
Fred Drakeb0fefc52001-03-23 04:22:45 +0000126 def check(proxy):
127 proxy.bar
Fred Drake41deb1e2001-02-01 05:27:45 +0000128
Fred Drakeb0fefc52001-03-23 04:22:45 +0000129 self.assertRaises(weakref.ReferenceError, check, ref1)
130 self.assertRaises(weakref.ReferenceError, check, ref2)
Neal Norwitzbdcb9412004-07-08 01:22:31 +0000131 self.assertRaises(weakref.ReferenceError, bool, weakref.proxy(C()))
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200132 self.assertEqual(self.cbcalled, 2)
Fred Drake41deb1e2001-02-01 05:27:45 +0000133
Fred Drakeb0fefc52001-03-23 04:22:45 +0000134 def check_basic_ref(self, factory):
135 o = factory()
136 ref = weakref.ref(o)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200137 self.assertIsNotNone(ref(),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000138 "weak reference to live object should be live")
139 o2 = ref()
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200140 self.assertIs(o, o2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000141 "<ref>() should return original object if live")
Fred Drake41deb1e2001-02-01 05:27:45 +0000142
Fred Drakeb0fefc52001-03-23 04:22:45 +0000143 def check_basic_callback(self, factory):
144 self.cbcalled = 0
145 o = factory()
146 ref = weakref.ref(o, self.callback)
147 del o
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200148 self.assertEqual(self.cbcalled, 1,
Fred Drake705088e2001-04-13 17:18:15 +0000149 "callback did not properly set 'cbcalled'")
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200150 self.assertIsNone(ref(),
Fred Drake705088e2001-04-13 17:18:15 +0000151 "ref2 should be dead after deleting object reference")
Fred Drake41deb1e2001-02-01 05:27:45 +0000152
Fred Drakeb0fefc52001-03-23 04:22:45 +0000153 def test_ref_reuse(self):
154 o = C()
155 ref1 = weakref.ref(o)
156 # create a proxy to make sure that there's an intervening creation
157 # between these two; it should make no difference
158 proxy = weakref.proxy(o)
159 ref2 = weakref.ref(o)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200160 self.assertIs(ref1, ref2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000161 "reference object w/out callback should be re-used")
Fred Drake41deb1e2001-02-01 05:27:45 +0000162
Fred Drakeb0fefc52001-03-23 04:22:45 +0000163 o = C()
164 proxy = weakref.proxy(o)
165 ref1 = weakref.ref(o)
166 ref2 = weakref.ref(o)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200167 self.assertIs(ref1, ref2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000168 "reference object w/out callback should be re-used")
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200169 self.assertEqual(weakref.getweakrefcount(o), 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000170 "wrong weak ref count for object")
171 del proxy
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200172 self.assertEqual(weakref.getweakrefcount(o), 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000173 "wrong weak ref count for object after deleting proxy")
Fred Drake41deb1e2001-02-01 05:27:45 +0000174
Fred Drakeb0fefc52001-03-23 04:22:45 +0000175 def test_proxy_reuse(self):
176 o = C()
177 proxy1 = weakref.proxy(o)
178 ref = weakref.ref(o)
179 proxy2 = weakref.proxy(o)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200180 self.assertIs(proxy1, proxy2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000181 "proxy object w/out callback should have been re-used")
182
183 def test_basic_proxy(self):
184 o = C()
185 self.check_proxy(o, weakref.proxy(o))
186
Fred Drake5935ff02001-12-19 16:54:23 +0000187 L = UserList.UserList()
188 p = weakref.proxy(L)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000189 self.assertFalse(p, "proxy for empty UserList should be false")
Fred Drake5935ff02001-12-19 16:54:23 +0000190 p.append(12)
191 self.assertEqual(len(L), 1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000192 self.assertTrue(p, "proxy for non-empty UserList should be true")
Florent Xicluna07627882010-03-21 01:14:24 +0000193 with test_support.check_py3k_warnings():
194 p[:] = [2, 3]
Fred Drake5935ff02001-12-19 16:54:23 +0000195 self.assertEqual(len(L), 2)
196 self.assertEqual(len(p), 2)
Ezio Melottiaa980582010-01-23 23:04:36 +0000197 self.assertIn(3, p, "proxy didn't support __contains__() properly")
Fred Drake5935ff02001-12-19 16:54:23 +0000198 p[1] = 5
199 self.assertEqual(L[1], 5)
200 self.assertEqual(p[1], 5)
201 L2 = UserList.UserList(L)
202 p2 = weakref.proxy(L2)
203 self.assertEqual(p, p2)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000204 ## self.assertEqual(repr(L2), repr(p2))
Fred Drake43735da2002-04-11 03:59:42 +0000205 L3 = UserList.UserList(range(10))
206 p3 = weakref.proxy(L3)
Florent Xicluna07627882010-03-21 01:14:24 +0000207 with test_support.check_py3k_warnings():
208 self.assertEqual(L3[:], p3[:])
209 self.assertEqual(L3[5:], p3[5:])
210 self.assertEqual(L3[:5], p3[:5])
211 self.assertEqual(L3[2:5], p3[2:5])
Fred Drake5935ff02001-12-19 16:54:23 +0000212
Benjamin Petersondc3c2392009-11-19 03:00:02 +0000213 def test_proxy_unicode(self):
214 # See bug 5037
215 class C(object):
216 def __str__(self):
217 return "string"
218 def __unicode__(self):
219 return u"unicode"
220 instance = C()
Ezio Melottiaa980582010-01-23 23:04:36 +0000221 self.assertIn("__unicode__", dir(weakref.proxy(instance)))
Benjamin Petersondc3c2392009-11-19 03:00:02 +0000222 self.assertEqual(unicode(weakref.proxy(instance)), u"unicode")
223
Georg Brandl88659b02008-05-20 08:40:43 +0000224 def test_proxy_index(self):
225 class C:
226 def __index__(self):
227 return 10
228 o = C()
229 p = weakref.proxy(o)
230 self.assertEqual(operator.index(p), 10)
231
232 def test_proxy_div(self):
233 class C:
234 def __floordiv__(self, other):
235 return 42
236 def __ifloordiv__(self, other):
237 return 21
238 o = C()
239 p = weakref.proxy(o)
240 self.assertEqual(p // 5, 42)
241 p //= 5
242 self.assertEqual(p, 21)
243
Fred Drakeea2adc92004-02-03 19:56:46 +0000244 # The PyWeakref_* C API is documented as allowing either NULL or
245 # None as the value for the callback, where either means "no
246 # callback". The "no callback" ref and proxy objects are supposed
247 # to be shared so long as they exist by all callers so long as
Walter Dörwaldda1ad322006-12-12 21:55:31 +0000248 # they are active. In Python 2.3.3 and earlier, this guarantee
Fred Drakeea2adc92004-02-03 19:56:46 +0000249 # was not honored, and was broken in different ways for
250 # PyWeakref_NewRef() and PyWeakref_NewProxy(). (Two tests.)
251
252 def test_shared_ref_without_callback(self):
253 self.check_shared_without_callback(weakref.ref)
254
255 def test_shared_proxy_without_callback(self):
256 self.check_shared_without_callback(weakref.proxy)
257
258 def check_shared_without_callback(self, makeref):
259 o = Object(1)
260 p1 = makeref(o, None)
261 p2 = makeref(o, None)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200262 self.assertIs(p1, p2, "both callbacks were None in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000263 del p1, p2
264 p1 = makeref(o)
265 p2 = makeref(o, None)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200266 self.assertIs(p1, p2, "callbacks were NULL, None in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000267 del p1, p2
268 p1 = makeref(o)
269 p2 = makeref(o)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200270 self.assertIs(p1, p2, "both callbacks were NULL in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000271 del p1, p2
272 p1 = makeref(o, None)
273 p2 = makeref(o)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200274 self.assertIs(p1, p2, "callbacks were None, NULL in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000275
Fred Drakeb0fefc52001-03-23 04:22:45 +0000276 def test_callable_proxy(self):
277 o = Callable()
278 ref1 = weakref.proxy(o)
279
280 self.check_proxy(o, ref1)
281
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200282 self.assertIs(type(ref1), weakref.CallableProxyType,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000283 "proxy is not of callable type")
284 ref1('twinkies!')
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200285 self.assertEqual(o.bar, 'twinkies!',
Fred Drakeb0fefc52001-03-23 04:22:45 +0000286 "call through proxy not passed through to original")
Fred Drake3bb4d212001-10-18 19:28:29 +0000287 ref1(x='Splat.')
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200288 self.assertEqual(o.bar, 'Splat.',
Fred Drake3bb4d212001-10-18 19:28:29 +0000289 "call through proxy not passed through to original")
Fred Drakeb0fefc52001-03-23 04:22:45 +0000290
291 # expect due to too few args
292 self.assertRaises(TypeError, ref1)
293
294 # expect due to too many args
295 self.assertRaises(TypeError, ref1, 1, 2, 3)
296
297 def check_proxy(self, o, proxy):
298 o.foo = 1
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200299 self.assertEqual(proxy.foo, 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000300 "proxy does not reflect attribute addition")
301 o.foo = 2
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200302 self.assertEqual(proxy.foo, 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000303 "proxy does not reflect attribute modification")
304 del o.foo
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200305 self.assertFalse(hasattr(proxy, 'foo'),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000306 "proxy does not reflect attribute removal")
307
308 proxy.foo = 1
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200309 self.assertEqual(o.foo, 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000310 "object does not reflect attribute addition via proxy")
311 proxy.foo = 2
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200312 self.assertEqual(o.foo, 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000313 "object does not reflect attribute modification via proxy")
314 del proxy.foo
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200315 self.assertFalse(hasattr(o, 'foo'),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000316 "object does not reflect attribute removal via proxy")
317
Raymond Hettingerd693a812003-06-30 04:18:48 +0000318 def test_proxy_deletion(self):
319 # Test clearing of SF bug #762891
320 class Foo:
321 result = None
322 def __delitem__(self, accessor):
323 self.result = accessor
324 g = Foo()
325 f = weakref.proxy(g)
326 del f[0]
327 self.assertEqual(f.result, 0)
328
Raymond Hettingere6c470f2005-03-27 03:04:54 +0000329 def test_proxy_bool(self):
330 # Test clearing of SF bug #1170766
331 class List(list): pass
332 lyst = List()
333 self.assertEqual(bool(weakref.proxy(lyst)), bool(lyst))
334
Fred Drakeb0fefc52001-03-23 04:22:45 +0000335 def test_getweakrefcount(self):
336 o = C()
337 ref1 = weakref.ref(o)
338 ref2 = weakref.ref(o, self.callback)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200339 self.assertEqual(weakref.getweakrefcount(o), 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000340 "got wrong number of weak reference objects")
341
342 proxy1 = weakref.proxy(o)
343 proxy2 = weakref.proxy(o, self.callback)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200344 self.assertEqual(weakref.getweakrefcount(o), 4,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000345 "got wrong number of weak reference objects")
346
Fred Drakeea2adc92004-02-03 19:56:46 +0000347 del ref1, ref2, proxy1, proxy2
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200348 self.assertEqual(weakref.getweakrefcount(o), 0,
Fred Drakeea2adc92004-02-03 19:56:46 +0000349 "weak reference objects not unlinked from"
350 " referent when discarded.")
351
Walter Dörwaldb167b042003-12-11 12:34:05 +0000352 # assumes ints do not support weakrefs
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200353 self.assertEqual(weakref.getweakrefcount(1), 0,
Walter Dörwaldb167b042003-12-11 12:34:05 +0000354 "got wrong number of weak reference objects for int")
355
Fred Drakeb0fefc52001-03-23 04:22:45 +0000356 def test_getweakrefs(self):
357 o = C()
358 ref1 = weakref.ref(o, self.callback)
359 ref2 = weakref.ref(o, self.callback)
360 del ref1
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200361 self.assertEqual(weakref.getweakrefs(o), [ref2],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000362 "list of refs does not match")
363
364 o = C()
365 ref1 = weakref.ref(o, self.callback)
366 ref2 = weakref.ref(o, self.callback)
367 del ref2
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200368 self.assertEqual(weakref.getweakrefs(o), [ref1],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000369 "list of refs does not match")
370
Fred Drakeea2adc92004-02-03 19:56:46 +0000371 del ref1
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200372 self.assertEqual(weakref.getweakrefs(o), [],
Fred Drakeea2adc92004-02-03 19:56:46 +0000373 "list of refs not cleared")
374
Walter Dörwaldb167b042003-12-11 12:34:05 +0000375 # assumes ints do not support weakrefs
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200376 self.assertEqual(weakref.getweakrefs(1), [],
Walter Dörwaldb167b042003-12-11 12:34:05 +0000377 "list of refs does not match for int")
378
Fred Drake39c27f12001-10-18 18:06:05 +0000379 def test_newstyle_number_ops(self):
380 class F(float):
381 pass
382 f = F(2.0)
383 p = weakref.proxy(f)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200384 self.assertEqual(p + 1.0, 3.0)
385 self.assertEqual(1.0 + p, 3.0) # this used to SEGV
Fred Drake39c27f12001-10-18 18:06:05 +0000386
Fred Drake2a64f462001-12-10 23:46:02 +0000387 def test_callbacks_protected(self):
Guido van Rossum9eee5542002-08-22 20:21:30 +0000388 # Callbacks protected from already-set exceptions?
Fred Drake2a64f462001-12-10 23:46:02 +0000389 # Regression test for SF bug #478534.
390 class BogusError(Exception):
391 pass
392 data = {}
393 def remove(k):
394 del data[k]
395 def encapsulate():
396 f = lambda : ()
397 data[weakref.ref(f, remove)] = None
398 raise BogusError
399 try:
400 encapsulate()
401 except BogusError:
402 pass
403 else:
404 self.fail("exception not properly restored")
405 try:
406 encapsulate()
407 except BogusError:
408 pass
409 else:
410 self.fail("exception not properly restored")
411
Tim Petersadd09b42003-11-12 20:43:28 +0000412 def test_sf_bug_840829(self):
413 # "weakref callbacks and gc corrupt memory"
414 # subtype_dealloc erroneously exposed a new-style instance
415 # already in the process of getting deallocated to gc,
416 # causing double-deallocation if the instance had a weakref
417 # callback that triggered gc.
418 # If the bug exists, there probably won't be an obvious symptom
419 # in a release build. In a debug build, a segfault will occur
420 # when the second attempt to remove the instance from the "list
421 # of all objects" occurs.
422
423 import gc
424
425 class C(object):
426 pass
427
428 c = C()
429 wr = weakref.ref(c, lambda ignore: gc.collect())
430 del c
431
Tim Petersf7f9e992003-11-13 21:59:32 +0000432 # There endeth the first part. It gets worse.
433 del wr
434
435 c1 = C()
436 c1.i = C()
437 wr = weakref.ref(c1.i, lambda ignore: gc.collect())
438
439 c2 = C()
440 c2.c1 = c1
441 del c1 # still alive because c2 points to it
442
443 # Now when subtype_dealloc gets called on c2, it's not enough just
444 # that c2 is immune from gc while the weakref callbacks associated
445 # with c2 execute (there are none in this 2nd half of the test, btw).
446 # subtype_dealloc goes on to call the base classes' deallocs too,
447 # so any gc triggered by weakref callbacks associated with anything
448 # torn down by a base class dealloc can also trigger double
449 # deallocation of c2.
450 del c2
Fred Drake41deb1e2001-02-01 05:27:45 +0000451
Tim Peters403a2032003-11-20 21:21:46 +0000452 def test_callback_in_cycle_1(self):
453 import gc
454
455 class J(object):
456 pass
457
458 class II(object):
459 def acallback(self, ignore):
460 self.J
461
462 I = II()
463 I.J = J
464 I.wr = weakref.ref(J, I.acallback)
465
466 # Now J and II are each in a self-cycle (as all new-style class
467 # objects are, since their __mro__ points back to them). I holds
468 # both a weak reference (I.wr) and a strong reference (I.J) to class
469 # J. I is also in a cycle (I.wr points to a weakref that references
470 # I.acallback). When we del these three, they all become trash, but
471 # the cycles prevent any of them from getting cleaned up immediately.
472 # Instead they have to wait for cyclic gc to deduce that they're
473 # trash.
474 #
475 # gc used to call tp_clear on all of them, and the order in which
476 # it does that is pretty accidental. The exact order in which we
477 # built up these things manages to provoke gc into running tp_clear
478 # in just the right order (I last). Calling tp_clear on II leaves
479 # behind an insane class object (its __mro__ becomes NULL). Calling
480 # tp_clear on J breaks its self-cycle, but J doesn't get deleted
481 # just then because of the strong reference from I.J. Calling
482 # tp_clear on I starts to clear I's __dict__, and just happens to
483 # clear I.J first -- I.wr is still intact. That removes the last
484 # reference to J, which triggers the weakref callback. The callback
485 # tries to do "self.J", and instances of new-style classes look up
486 # attributes ("J") in the class dict first. The class (II) wants to
487 # search II.__mro__, but that's NULL. The result was a segfault in
488 # a release build, and an assert failure in a debug build.
489 del I, J, II
490 gc.collect()
491
492 def test_callback_in_cycle_2(self):
493 import gc
494
495 # This is just like test_callback_in_cycle_1, except that II is an
496 # old-style class. The symptom is different then: an instance of an
497 # old-style class looks in its own __dict__ first. 'J' happens to
498 # get cleared from I.__dict__ before 'wr', and 'J' was never in II's
499 # __dict__, so the attribute isn't found. The difference is that
500 # the old-style II doesn't have a NULL __mro__ (it doesn't have any
501 # __mro__), so no segfault occurs. Instead it got:
502 # test_callback_in_cycle_2 (__main__.ReferencesTestCase) ...
503 # Exception exceptions.AttributeError:
504 # "II instance has no attribute 'J'" in <bound method II.acallback
505 # of <?.II instance at 0x00B9B4B8>> ignored
506
507 class J(object):
508 pass
509
510 class II:
511 def acallback(self, ignore):
512 self.J
513
514 I = II()
515 I.J = J
516 I.wr = weakref.ref(J, I.acallback)
517
518 del I, J, II
519 gc.collect()
520
521 def test_callback_in_cycle_3(self):
522 import gc
523
524 # This one broke the first patch that fixed the last two. In this
525 # case, the objects reachable from the callback aren't also reachable
526 # from the object (c1) *triggering* the callback: you can get to
527 # c1 from c2, but not vice-versa. The result was that c2's __dict__
528 # got tp_clear'ed by the time the c2.cb callback got invoked.
529
530 class C:
531 def cb(self, ignore):
532 self.me
533 self.c1
534 self.wr
535
536 c1, c2 = C(), C()
537
538 c2.me = c2
539 c2.c1 = c1
540 c2.wr = weakref.ref(c1, c2.cb)
541
542 del c1, c2
543 gc.collect()
544
545 def test_callback_in_cycle_4(self):
546 import gc
547
548 # Like test_callback_in_cycle_3, except c2 and c1 have different
549 # classes. c2's class (C) isn't reachable from c1 then, so protecting
550 # objects reachable from the dying object (c1) isn't enough to stop
551 # c2's class (C) from getting tp_clear'ed before c2.cb is invoked.
552 # The result was a segfault (C.__mro__ was NULL when the callback
553 # tried to look up self.me).
554
555 class C(object):
556 def cb(self, ignore):
557 self.me
558 self.c1
559 self.wr
560
561 class D:
562 pass
563
564 c1, c2 = D(), C()
565
566 c2.me = c2
567 c2.c1 = c1
568 c2.wr = weakref.ref(c1, c2.cb)
569
570 del c1, c2, C, D
571 gc.collect()
572
573 def test_callback_in_cycle_resurrection(self):
574 import gc
575
576 # Do something nasty in a weakref callback: resurrect objects
577 # from dead cycles. For this to be attempted, the weakref and
578 # its callback must also be part of the cyclic trash (else the
579 # objects reachable via the callback couldn't be in cyclic trash
580 # to begin with -- the callback would act like an external root).
581 # But gc clears trash weakrefs with callbacks early now, which
582 # disables the callbacks, so the callbacks shouldn't get called
583 # at all (and so nothing actually gets resurrected).
584
585 alist = []
586 class C(object):
587 def __init__(self, value):
588 self.attribute = value
589
590 def acallback(self, ignore):
591 alist.append(self.c)
592
593 c1, c2 = C(1), C(2)
594 c1.c = c2
595 c2.c = c1
596 c1.wr = weakref.ref(c2, c1.acallback)
597 c2.wr = weakref.ref(c1, c2.acallback)
598
599 def C_went_away(ignore):
600 alist.append("C went away")
601 wr = weakref.ref(C, C_went_away)
602
603 del c1, c2, C # make them all trash
604 self.assertEqual(alist, []) # del isn't enough to reclaim anything
605
606 gc.collect()
607 # c1.wr and c2.wr were part of the cyclic trash, so should have
608 # been cleared without their callbacks executing. OTOH, the weakref
609 # to C is bound to a function local (wr), and wasn't trash, so that
610 # callback should have been invoked when C went away.
611 self.assertEqual(alist, ["C went away"])
612 # The remaining weakref should be dead now (its callback ran).
613 self.assertEqual(wr(), None)
614
615 del alist[:]
616 gc.collect()
617 self.assertEqual(alist, [])
618
619 def test_callbacks_on_callback(self):
620 import gc
621
622 # Set up weakref callbacks *on* weakref callbacks.
623 alist = []
624 def safe_callback(ignore):
625 alist.append("safe_callback called")
626
627 class C(object):
628 def cb(self, ignore):
629 alist.append("cb called")
630
631 c, d = C(), C()
632 c.other = d
633 d.other = c
634 callback = c.cb
635 c.wr = weakref.ref(d, callback) # this won't trigger
636 d.wr = weakref.ref(callback, d.cb) # ditto
637 external_wr = weakref.ref(callback, safe_callback) # but this will
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200638 self.assertIs(external_wr(), callback)
Tim Peters403a2032003-11-20 21:21:46 +0000639
640 # The weakrefs attached to c and d should get cleared, so that
641 # C.cb is never called. But external_wr isn't part of the cyclic
642 # trash, and no cyclic trash is reachable from it, so safe_callback
643 # should get invoked when the bound method object callback (c.cb)
644 # -- which is itself a callback, and also part of the cyclic trash --
645 # gets reclaimed at the end of gc.
646
647 del callback, c, d, C
648 self.assertEqual(alist, []) # del isn't enough to clean up cycles
649 gc.collect()
650 self.assertEqual(alist, ["safe_callback called"])
651 self.assertEqual(external_wr(), None)
652
653 del alist[:]
654 gc.collect()
655 self.assertEqual(alist, [])
656
Fred Drakebc875f52004-02-04 23:14:14 +0000657 def test_gc_during_ref_creation(self):
658 self.check_gc_during_creation(weakref.ref)
659
660 def test_gc_during_proxy_creation(self):
661 self.check_gc_during_creation(weakref.proxy)
662
663 def check_gc_during_creation(self, makeref):
664 thresholds = gc.get_threshold()
665 gc.set_threshold(1, 1, 1)
666 gc.collect()
Fred Drake55cf4342004-02-13 19:21:57 +0000667 class A:
668 pass
Fred Drakebc875f52004-02-04 23:14:14 +0000669
670 def callback(*args):
671 pass
672
Fred Drake55cf4342004-02-13 19:21:57 +0000673 referenced = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000674
Fred Drake55cf4342004-02-13 19:21:57 +0000675 a = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000676 a.a = a
677 a.wr = makeref(referenced)
678
679 try:
680 # now make sure the object and the ref get labeled as
681 # cyclic trash:
Fred Drake55cf4342004-02-13 19:21:57 +0000682 a = A()
683 weakref.ref(referenced, callback)
Fred Drakebc875f52004-02-04 23:14:14 +0000684
685 finally:
686 gc.set_threshold(*thresholds)
687
Brett Cannonf5bee302007-01-23 23:21:22 +0000688 def test_ref_created_during_del(self):
689 # Bug #1377858
690 # A weakref created in an object's __del__() would crash the
691 # interpreter when the weakref was cleaned up since it would refer to
692 # non-existent memory. This test should not segfault the interpreter.
693 class Target(object):
694 def __del__(self):
695 global ref_from_del
696 ref_from_del = weakref.ref(self)
697
698 w = Target()
699
Benjamin Peterson97179b02008-09-09 20:55:01 +0000700 def test_init(self):
701 # Issue 3634
702 # <weakref to class>.__init__() doesn't check errors correctly
703 r = weakref.ref(Exception)
704 self.assertRaises(TypeError, r.__init__, 0, 0, 0, 0, 0)
705 # No exception should be raised here
706 gc.collect()
707
Antoine Pitroua57df2c2010-03-31 21:32:15 +0000708 def test_classes(self):
709 # Check that both old-style classes and new-style classes
710 # are weakrefable.
711 class A(object):
712 pass
713 class B:
714 pass
715 l = []
716 weakref.ref(int)
717 a = weakref.ref(A, l.append)
718 A = None
719 gc.collect()
720 self.assertEqual(a(), None)
721 self.assertEqual(l, [a])
722 b = weakref.ref(B, l.append)
723 B = None
724 gc.collect()
725 self.assertEqual(b(), None)
726 self.assertEqual(l, [a, b])
727
Antoine Pitroub704eab2012-11-11 19:36:51 +0100728 def test_equality(self):
729 # Alive weakrefs defer equality testing to their underlying object.
730 x = Object(1)
731 y = Object(1)
732 z = Object(2)
733 a = weakref.ref(x)
734 b = weakref.ref(y)
735 c = weakref.ref(z)
736 d = weakref.ref(x)
737 # Note how we directly test the operators here, to stress both
738 # __eq__ and __ne__.
739 self.assertTrue(a == b)
740 self.assertFalse(a != b)
741 self.assertFalse(a == c)
742 self.assertTrue(a != c)
743 self.assertTrue(a == d)
744 self.assertFalse(a != d)
745 del x, y, z
746 gc.collect()
747 for r in a, b, c:
748 # Sanity check
749 self.assertIs(r(), None)
750 # Dead weakrefs compare by identity: whether `a` and `d` are the
751 # same weakref object is an implementation detail, since they pointed
752 # to the same original object and didn't have a callback.
753 # (see issue #16453).
754 self.assertFalse(a == b)
755 self.assertTrue(a != b)
756 self.assertFalse(a == c)
757 self.assertTrue(a != c)
758 self.assertEqual(a == d, a is d)
759 self.assertEqual(a != d, a is not d)
760
761 def test_hashing(self):
762 # Alive weakrefs hash the same as the underlying object
763 x = Object(42)
764 y = Object(42)
765 a = weakref.ref(x)
766 b = weakref.ref(y)
767 self.assertEqual(hash(a), hash(42))
768 del x, y
769 gc.collect()
770 # Dead weakrefs:
771 # - retain their hash is they were hashed when alive;
772 # - otherwise, cannot be hashed.
773 self.assertEqual(hash(a), hash(42))
774 self.assertRaises(TypeError, hash, b)
775
Antoine Pitroud38c9902012-12-08 21:15:26 +0100776 def test_trashcan_16602(self):
777 # Issue #16602: when a weakref's target was part of a long
778 # deallocation chain, the trashcan mechanism could delay clearing
779 # of the weakref and make the target object visible from outside
780 # code even though its refcount had dropped to 0. A crash ensued.
781 class C(object):
782 def __init__(self, parent):
783 if not parent:
784 return
785 wself = weakref.ref(self)
786 def cb(wparent):
787 o = wself()
788 self.wparent = weakref.ref(parent, cb)
789
790 d = weakref.WeakKeyDictionary()
791 root = c = C(None)
792 for n in range(100):
793 d[c] = c = C(c)
794 del root
795 gc.collect()
796
Fred Drake0a4dd392004-07-02 18:57:45 +0000797
Amaury Forgeot d'Arca8919fe2008-06-16 19:12:42 +0000798class SubclassableWeakrefTestCase(TestBase):
Fred Drake0a4dd392004-07-02 18:57:45 +0000799
800 def test_subclass_refs(self):
801 class MyRef(weakref.ref):
802 def __init__(self, ob, callback=None, value=42):
803 self.value = value
804 super(MyRef, self).__init__(ob, callback)
805 def __call__(self):
806 self.called = True
807 return super(MyRef, self).__call__()
808 o = Object("foo")
809 mr = MyRef(o, value=24)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200810 self.assertIs(mr(), o)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000811 self.assertTrue(mr.called)
Fred Drake0a4dd392004-07-02 18:57:45 +0000812 self.assertEqual(mr.value, 24)
813 del o
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200814 self.assertIsNone(mr())
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000815 self.assertTrue(mr.called)
Fred Drake0a4dd392004-07-02 18:57:45 +0000816
817 def test_subclass_refs_dont_replace_standard_refs(self):
818 class MyRef(weakref.ref):
819 pass
820 o = Object(42)
821 r1 = MyRef(o)
822 r2 = weakref.ref(o)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200823 self.assertIsNot(r1, r2)
Fred Drake0a4dd392004-07-02 18:57:45 +0000824 self.assertEqual(weakref.getweakrefs(o), [r2, r1])
825 self.assertEqual(weakref.getweakrefcount(o), 2)
826 r3 = MyRef(o)
827 self.assertEqual(weakref.getweakrefcount(o), 3)
828 refs = weakref.getweakrefs(o)
829 self.assertEqual(len(refs), 3)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200830 self.assertIs(r2, refs[0])
Ezio Melottiaa980582010-01-23 23:04:36 +0000831 self.assertIn(r1, refs[1:])
832 self.assertIn(r3, refs[1:])
Fred Drake0a4dd392004-07-02 18:57:45 +0000833
834 def test_subclass_refs_dont_conflate_callbacks(self):
835 class MyRef(weakref.ref):
836 pass
837 o = Object(42)
838 r1 = MyRef(o, id)
839 r2 = MyRef(o, str)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200840 self.assertIsNot(r1, r2)
Fred Drake0a4dd392004-07-02 18:57:45 +0000841 refs = weakref.getweakrefs(o)
Ezio Melottiaa980582010-01-23 23:04:36 +0000842 self.assertIn(r1, refs)
843 self.assertIn(r2, refs)
Fred Drake0a4dd392004-07-02 18:57:45 +0000844
845 def test_subclass_refs_with_slots(self):
846 class MyRef(weakref.ref):
847 __slots__ = "slot1", "slot2"
848 def __new__(type, ob, callback, slot1, slot2):
849 return weakref.ref.__new__(type, ob, callback)
850 def __init__(self, ob, callback, slot1, slot2):
851 self.slot1 = slot1
852 self.slot2 = slot2
853 def meth(self):
854 return self.slot1 + self.slot2
855 o = Object(42)
856 r = MyRef(o, None, "abc", "def")
857 self.assertEqual(r.slot1, "abc")
858 self.assertEqual(r.slot2, "def")
859 self.assertEqual(r.meth(), "abcdef")
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000860 self.assertFalse(hasattr(r, "__dict__"))
Fred Drake0a4dd392004-07-02 18:57:45 +0000861
Amaury Forgeot d'Arca8919fe2008-06-16 19:12:42 +0000862 def test_subclass_refs_with_cycle(self):
863 # Bug #3110
864 # An instance of a weakref subclass can have attributes.
865 # If such a weakref holds the only strong reference to the object,
866 # deleting the weakref will delete the object. In this case,
867 # the callback must not be called, because the ref object is
868 # being deleted.
869 class MyRef(weakref.ref):
870 pass
871
872 # Use a local callback, for "regrtest -R::"
873 # to detect refcounting problems
874 def callback(w):
875 self.cbcalled += 1
876
877 o = C()
878 r1 = MyRef(o, callback)
879 r1.o = o
880 del o
881
882 del r1 # Used to crash here
883
884 self.assertEqual(self.cbcalled, 0)
885
886 # Same test, with two weakrefs to the same object
887 # (since code paths are different)
888 o = C()
889 r1 = MyRef(o, callback)
890 r2 = MyRef(o, callback)
891 r1.r = r2
892 r2.o = o
893 del o
894 del r2
895
896 del r1 # Used to crash here
897
898 self.assertEqual(self.cbcalled, 0)
899
Fred Drake0a4dd392004-07-02 18:57:45 +0000900
Fred Drakeb0fefc52001-03-23 04:22:45 +0000901class MappingTestCase(TestBase):
Martin v. Löwis5e163332001-02-27 18:36:56 +0000902
Fred Drakeb0fefc52001-03-23 04:22:45 +0000903 COUNT = 10
904
Antoine Pitrouc56bca32012-03-01 16:26:35 +0100905 def check_len_cycles(self, dict_type, cons):
906 N = 20
907 items = [RefCycle() for i in range(N)]
Kristján Valur Jónsson222b2842013-12-05 10:03:45 +0000908 dct = dict_type(cons(i, o) for i, o in enumerate(items))
Antoine Pitrouc56bca32012-03-01 16:26:35 +0100909 # Keep an iterator alive
910 it = dct.iteritems()
911 try:
912 next(it)
913 except StopIteration:
914 pass
915 del items
916 gc.collect()
917 n1 = len(dct)
Kristján Valur Jónsson222b2842013-12-05 10:03:45 +0000918 list(it)
Antoine Pitrouc56bca32012-03-01 16:26:35 +0100919 del it
920 gc.collect()
921 n2 = len(dct)
Kristján Valur Jónsson222b2842013-12-05 10:03:45 +0000922 # iteration should prevent garbage collection here
923 # Note that this is a test on an implementation detail. The requirement
924 # is only to provide stable iteration, not that the size of the container
925 # stay fixed.
926 self.assertEqual(n1, 20)
927 #self.assertIn(n1, (0, 1))
Antoine Pitrouc56bca32012-03-01 16:26:35 +0100928 self.assertEqual(n2, 0)
929
930 def test_weak_keyed_len_cycles(self):
Kristján Valur Jónsson222b2842013-12-05 10:03:45 +0000931 self.check_len_cycles(weakref.WeakKeyDictionary, lambda n, k: (k, n))
Antoine Pitrouc56bca32012-03-01 16:26:35 +0100932
933 def test_weak_valued_len_cycles(self):
Kristján Valur Jónsson222b2842013-12-05 10:03:45 +0000934 self.check_len_cycles(weakref.WeakValueDictionary, lambda n, k: (n, k))
Antoine Pitrouc56bca32012-03-01 16:26:35 +0100935
936 def check_len_race(self, dict_type, cons):
937 # Extended sanity checks for len() in the face of cyclic collection
938 self.addCleanup(gc.set_threshold, *gc.get_threshold())
939 for th in range(1, 100):
940 N = 20
941 gc.collect(0)
942 gc.set_threshold(th, th, th)
943 items = [RefCycle() for i in range(N)]
944 dct = dict_type(cons(o) for o in items)
945 del items
946 # All items will be collected at next garbage collection pass
947 it = dct.iteritems()
948 try:
949 next(it)
950 except StopIteration:
951 pass
952 n1 = len(dct)
953 del it
954 n2 = len(dct)
955 self.assertGreaterEqual(n1, 0)
956 self.assertLessEqual(n1, N)
957 self.assertGreaterEqual(n2, 0)
958 self.assertLessEqual(n2, n1)
959
960 def test_weak_keyed_len_race(self):
961 self.check_len_race(weakref.WeakKeyDictionary, lambda k: (k, 1))
962
963 def test_weak_valued_len_race(self):
964 self.check_len_race(weakref.WeakValueDictionary, lambda k: (1, k))
965
Fred Drakeb0fefc52001-03-23 04:22:45 +0000966 def test_weak_values(self):
Fred Drake0e540c32001-05-02 05:44:22 +0000967 #
968 # This exercises d.copy(), d.items(), d[], del d[], len(d).
969 #
970 dict, objects = self.make_weak_valued_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +0000971 for o in objects:
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200972 self.assertEqual(weakref.getweakrefcount(o), 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000973 "wrong number of weak references to %r!" % o)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200974 self.assertIs(o, dict[o.arg],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000975 "wrong object returned by weak dict!")
976 items1 = dict.items()
977 items2 = dict.copy().items()
978 items1.sort()
979 items2.sort()
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200980 self.assertEqual(items1, items2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000981 "cloning of weak-valued dictionary did not work!")
982 del items1, items2
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200983 self.assertEqual(len(dict), self.COUNT)
Fred Drakeb0fefc52001-03-23 04:22:45 +0000984 del objects[0]
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200985 self.assertEqual(len(dict), (self.COUNT - 1),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000986 "deleting object did not cause dictionary update")
987 del objects, o
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200988 self.assertEqual(len(dict), 0,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000989 "deleting the values did not clear the dictionary")
Fred Drake4fd06e02001-08-03 04:11:27 +0000990 # regression on SF bug #447152:
991 dict = weakref.WeakValueDictionary()
992 self.assertRaises(KeyError, dict.__getitem__, 1)
993 dict[2] = C()
994 self.assertRaises(KeyError, dict.__getitem__, 2)
Fred Drakeb0fefc52001-03-23 04:22:45 +0000995
996 def test_weak_keys(self):
Fred Drake0e540c32001-05-02 05:44:22 +0000997 #
998 # This exercises d.copy(), d.items(), d[] = v, d[], del d[],
Florent Xicluna07627882010-03-21 01:14:24 +0000999 # len(d), in d.
Fred Drake0e540c32001-05-02 05:44:22 +00001000 #
1001 dict, objects = self.make_weak_keyed_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +00001002 for o in objects:
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001003 self.assertEqual(weakref.getweakrefcount(o), 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001004 "wrong number of weak references to %r!" % o)
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001005 self.assertIs(o.arg, dict[o],
Fred Drakeb0fefc52001-03-23 04:22:45 +00001006 "wrong object returned by weak dict!")
1007 items1 = dict.items()
1008 items2 = dict.copy().items()
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001009 self.assertEqual(set(items1), set(items2),
Fred Drakeb0fefc52001-03-23 04:22:45 +00001010 "cloning of weak-keyed dictionary did not work!")
1011 del items1, items2
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001012 self.assertEqual(len(dict), self.COUNT)
Fred Drakeb0fefc52001-03-23 04:22:45 +00001013 del objects[0]
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001014 self.assertEqual(len(dict), (self.COUNT - 1),
Fred Drakeb0fefc52001-03-23 04:22:45 +00001015 "deleting object did not cause dictionary update")
1016 del objects, o
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001017 self.assertEqual(len(dict), 0,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001018 "deleting the keys did not clear the dictionary")
Fred Drake752eda42001-11-06 16:38:34 +00001019 o = Object(42)
1020 dict[o] = "What is the meaning of the universe?"
Florent Xicluna07627882010-03-21 01:14:24 +00001021 self.assertIn(o, dict)
1022 self.assertNotIn(34, dict)
Martin v. Löwis5e163332001-02-27 18:36:56 +00001023
Fred Drake0e540c32001-05-02 05:44:22 +00001024 def test_weak_keyed_iters(self):
1025 dict, objects = self.make_weak_keyed_dict()
1026 self.check_iters(dict)
1027
Fred Drake017e68c2006-05-02 06:53:59 +00001028 # Test keyrefs()
1029 refs = dict.keyrefs()
1030 self.assertEqual(len(refs), len(objects))
1031 objects2 = list(objects)
1032 for wr in refs:
1033 ob = wr()
Ezio Melottiaa980582010-01-23 23:04:36 +00001034 self.assertIn(ob, dict)
Fred Drake017e68c2006-05-02 06:53:59 +00001035 self.assertEqual(ob.arg, dict[ob])
1036 objects2.remove(ob)
1037 self.assertEqual(len(objects2), 0)
1038
1039 # Test iterkeyrefs()
1040 objects2 = list(objects)
1041 self.assertEqual(len(list(dict.iterkeyrefs())), len(objects))
1042 for wr in dict.iterkeyrefs():
1043 ob = wr()
Ezio Melottiaa980582010-01-23 23:04:36 +00001044 self.assertIn(ob, dict)
Fred Drake017e68c2006-05-02 06:53:59 +00001045 self.assertEqual(ob.arg, dict[ob])
1046 objects2.remove(ob)
1047 self.assertEqual(len(objects2), 0)
1048
Fred Drake0e540c32001-05-02 05:44:22 +00001049 def test_weak_valued_iters(self):
1050 dict, objects = self.make_weak_valued_dict()
1051 self.check_iters(dict)
1052
Fred Drake017e68c2006-05-02 06:53:59 +00001053 # Test valuerefs()
1054 refs = dict.valuerefs()
1055 self.assertEqual(len(refs), len(objects))
1056 objects2 = list(objects)
1057 for wr in refs:
1058 ob = wr()
1059 self.assertEqual(ob, dict[ob.arg])
1060 self.assertEqual(ob.arg, dict[ob.arg].arg)
1061 objects2.remove(ob)
1062 self.assertEqual(len(objects2), 0)
1063
1064 # Test itervaluerefs()
1065 objects2 = list(objects)
1066 self.assertEqual(len(list(dict.itervaluerefs())), len(objects))
1067 for wr in dict.itervaluerefs():
1068 ob = wr()
1069 self.assertEqual(ob, dict[ob.arg])
1070 self.assertEqual(ob.arg, dict[ob.arg].arg)
1071 objects2.remove(ob)
1072 self.assertEqual(len(objects2), 0)
1073
Fred Drake0e540c32001-05-02 05:44:22 +00001074 def check_iters(self, dict):
1075 # item iterator:
1076 items = dict.items()
1077 for item in dict.iteritems():
1078 items.remove(item)
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001079 self.assertEqual(len(items), 0, "iteritems() did not touch all items")
Fred Drake0e540c32001-05-02 05:44:22 +00001080
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001081 # key iterator, via __iter__():
Fred Drake0e540c32001-05-02 05:44:22 +00001082 keys = dict.keys()
1083 for k in dict:
1084 keys.remove(k)
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001085 self.assertEqual(len(keys), 0, "__iter__() did not touch all keys")
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001086
1087 # key iterator, via iterkeys():
1088 keys = dict.keys()
1089 for k in dict.iterkeys():
1090 keys.remove(k)
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001091 self.assertEqual(len(keys), 0, "iterkeys() did not touch all keys")
Fred Drake0e540c32001-05-02 05:44:22 +00001092
1093 # value iterator:
1094 values = dict.values()
1095 for v in dict.itervalues():
1096 values.remove(v)
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001097 self.assertEqual(len(values), 0,
Fred Drakef425b1e2003-07-14 21:37:17 +00001098 "itervalues() did not touch all values")
Fred Drake0e540c32001-05-02 05:44:22 +00001099
Kristján Valur Jónsson222b2842013-12-05 10:03:45 +00001100 def check_weak_destroy_while_iterating(self, dict, objects, iter_name):
1101 n = len(dict)
1102 it = iter(getattr(dict, iter_name)())
1103 next(it) # Trigger internal iteration
1104 # Destroy an object
1105 del objects[-1]
1106 gc.collect() # just in case
1107 # We have removed either the first consumed object, or another one
1108 self.assertIn(len(list(it)), [len(objects), len(objects) - 1])
1109 del it
1110 # The removal has been committed
1111 self.assertEqual(len(dict), n - 1)
1112
1113 def check_weak_destroy_and_mutate_while_iterating(self, dict, testcontext):
1114 # Check that we can explicitly mutate the weak dict without
1115 # interfering with delayed removal.
1116 # `testcontext` should create an iterator, destroy one of the
1117 # weakref'ed objects and then return a new key/value pair corresponding
1118 # to the destroyed object.
1119 with testcontext() as (k, v):
1120 self.assertFalse(k in dict)
1121 with testcontext() as (k, v):
1122 self.assertRaises(KeyError, dict.__delitem__, k)
1123 self.assertFalse(k in dict)
1124 with testcontext() as (k, v):
1125 self.assertRaises(KeyError, dict.pop, k)
1126 self.assertFalse(k in dict)
1127 with testcontext() as (k, v):
1128 dict[k] = v
1129 self.assertEqual(dict[k], v)
1130 ddict = copy.copy(dict)
1131 with testcontext() as (k, v):
1132 dict.update(ddict)
1133 self.assertEqual(dict, ddict)
1134 with testcontext() as (k, v):
1135 dict.clear()
1136 self.assertEqual(len(dict), 0)
1137
1138 def test_weak_keys_destroy_while_iterating(self):
1139 # Issue #7105: iterators shouldn't crash when a key is implicitly removed
1140 dict, objects = self.make_weak_keyed_dict()
1141 self.check_weak_destroy_while_iterating(dict, objects, 'iterkeys')
1142 self.check_weak_destroy_while_iterating(dict, objects, 'iteritems')
1143 self.check_weak_destroy_while_iterating(dict, objects, 'itervalues')
1144 self.check_weak_destroy_while_iterating(dict, objects, 'iterkeyrefs')
1145 dict, objects = self.make_weak_keyed_dict()
1146 @contextlib.contextmanager
1147 def testcontext():
1148 try:
1149 it = iter(dict.iteritems())
1150 next(it)
1151 # Schedule a key/value for removal and recreate it
1152 v = objects.pop().arg
1153 gc.collect() # just in case
1154 yield Object(v), v
1155 finally:
1156 it = None # should commit all removals
Benjamin Peterson8a4448c2014-08-24 18:02:15 -05001157 gc.collect()
Kristján Valur Jónsson222b2842013-12-05 10:03:45 +00001158 self.check_weak_destroy_and_mutate_while_iterating(dict, testcontext)
1159
1160 def test_weak_values_destroy_while_iterating(self):
1161 # Issue #7105: iterators shouldn't crash when a key is implicitly removed
1162 dict, objects = self.make_weak_valued_dict()
1163 self.check_weak_destroy_while_iterating(dict, objects, 'iterkeys')
1164 self.check_weak_destroy_while_iterating(dict, objects, 'iteritems')
1165 self.check_weak_destroy_while_iterating(dict, objects, 'itervalues')
1166 self.check_weak_destroy_while_iterating(dict, objects, 'itervaluerefs')
1167 dict, objects = self.make_weak_valued_dict()
1168 @contextlib.contextmanager
1169 def testcontext():
1170 try:
1171 it = iter(dict.iteritems())
1172 next(it)
1173 # Schedule a key/value for removal and recreate it
1174 k = objects.pop().arg
1175 gc.collect() # just in case
1176 yield k, Object(k)
1177 finally:
1178 it = None # should commit all removals
Benjamin Peterson8a4448c2014-08-24 18:02:15 -05001179 gc.collect()
Kristján Valur Jónsson222b2842013-12-05 10:03:45 +00001180 self.check_weak_destroy_and_mutate_while_iterating(dict, testcontext)
1181
Guido van Rossum009afb72002-06-10 20:00:52 +00001182 def test_make_weak_keyed_dict_from_dict(self):
1183 o = Object(3)
1184 dict = weakref.WeakKeyDictionary({o:364})
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001185 self.assertEqual(dict[o], 364)
Guido van Rossum009afb72002-06-10 20:00:52 +00001186
1187 def test_make_weak_keyed_dict_from_weak_keyed_dict(self):
1188 o = Object(3)
1189 dict = weakref.WeakKeyDictionary({o:364})
1190 dict2 = weakref.WeakKeyDictionary(dict)
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001191 self.assertEqual(dict[o], 364)
Guido van Rossum009afb72002-06-10 20:00:52 +00001192
Fred Drake0e540c32001-05-02 05:44:22 +00001193 def make_weak_keyed_dict(self):
1194 dict = weakref.WeakKeyDictionary()
1195 objects = map(Object, range(self.COUNT))
1196 for o in objects:
1197 dict[o] = o.arg
1198 return dict, objects
1199
1200 def make_weak_valued_dict(self):
1201 dict = weakref.WeakValueDictionary()
1202 objects = map(Object, range(self.COUNT))
1203 for o in objects:
1204 dict[o.arg] = o
1205 return dict, objects
1206
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001207 def check_popitem(self, klass, key1, value1, key2, value2):
1208 weakdict = klass()
1209 weakdict[key1] = value1
1210 weakdict[key2] = value2
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001211 self.assertEqual(len(weakdict), 2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001212 k, v = weakdict.popitem()
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001213 self.assertEqual(len(weakdict), 1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001214 if k is key1:
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001215 self.assertIs(v, value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001216 else:
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001217 self.assertIs(v, value2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001218 k, v = weakdict.popitem()
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001219 self.assertEqual(len(weakdict), 0)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001220 if k is key1:
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001221 self.assertIs(v, value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001222 else:
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001223 self.assertIs(v, value2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001224
1225 def test_weak_valued_dict_popitem(self):
1226 self.check_popitem(weakref.WeakValueDictionary,
1227 "key1", C(), "key2", C())
1228
1229 def test_weak_keyed_dict_popitem(self):
1230 self.check_popitem(weakref.WeakKeyDictionary,
1231 C(), "value 1", C(), "value 2")
1232
1233 def check_setdefault(self, klass, key, value1, value2):
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001234 self.assertIsNot(value1, value2,
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001235 "invalid test"
1236 " -- value parameters must be distinct objects")
1237 weakdict = klass()
1238 o = weakdict.setdefault(key, value1)
Florent Xicluna07627882010-03-21 01:14:24 +00001239 self.assertIs(o, value1)
1240 self.assertIn(key, weakdict)
1241 self.assertIs(weakdict.get(key), value1)
1242 self.assertIs(weakdict[key], value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001243
1244 o = weakdict.setdefault(key, value2)
Florent Xicluna07627882010-03-21 01:14:24 +00001245 self.assertIs(o, value1)
1246 self.assertIn(key, weakdict)
1247 self.assertIs(weakdict.get(key), value1)
1248 self.assertIs(weakdict[key], value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001249
1250 def test_weak_valued_dict_setdefault(self):
1251 self.check_setdefault(weakref.WeakValueDictionary,
1252 "key", C(), C())
1253
1254 def test_weak_keyed_dict_setdefault(self):
1255 self.check_setdefault(weakref.WeakKeyDictionary,
1256 C(), "value 1", "value 2")
1257
Fred Drakea0a4ab12001-04-16 17:37:27 +00001258 def check_update(self, klass, dict):
Fred Drake0e540c32001-05-02 05:44:22 +00001259 #
Florent Xicluna07627882010-03-21 01:14:24 +00001260 # This exercises d.update(), len(d), d.keys(), in d,
Fred Drake0e540c32001-05-02 05:44:22 +00001261 # d.get(), d[].
1262 #
Fred Drakea0a4ab12001-04-16 17:37:27 +00001263 weakdict = klass()
1264 weakdict.update(dict)
Florent Xicluna07627882010-03-21 01:14:24 +00001265 self.assertEqual(len(weakdict), len(dict))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001266 for k in weakdict.keys():
Florent Xicluna07627882010-03-21 01:14:24 +00001267 self.assertIn(k, dict,
Fred Drakea0a4ab12001-04-16 17:37:27 +00001268 "mysterious new key appeared in weak dict")
1269 v = dict.get(k)
Florent Xicluna07627882010-03-21 01:14:24 +00001270 self.assertIs(v, weakdict[k])
1271 self.assertIs(v, weakdict.get(k))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001272 for k in dict.keys():
Florent Xicluna07627882010-03-21 01:14:24 +00001273 self.assertIn(k, weakdict,
Fred Drakea0a4ab12001-04-16 17:37:27 +00001274 "original key disappeared in weak dict")
1275 v = dict[k]
Florent Xicluna07627882010-03-21 01:14:24 +00001276 self.assertIs(v, weakdict[k])
1277 self.assertIs(v, weakdict.get(k))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001278
1279 def test_weak_valued_dict_update(self):
1280 self.check_update(weakref.WeakValueDictionary,
1281 {1: C(), 'a': C(), C(): C()})
1282
1283 def test_weak_keyed_dict_update(self):
1284 self.check_update(weakref.WeakKeyDictionary,
1285 {C(): 1, C(): 2, C(): 3})
1286
Fred Drakeccc75622001-09-06 14:52:39 +00001287 def test_weak_keyed_delitem(self):
1288 d = weakref.WeakKeyDictionary()
1289 o1 = Object('1')
1290 o2 = Object('2')
1291 d[o1] = 'something'
1292 d[o2] = 'something'
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001293 self.assertEqual(len(d), 2)
Fred Drakeccc75622001-09-06 14:52:39 +00001294 del d[o1]
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001295 self.assertEqual(len(d), 1)
1296 self.assertEqual(d.keys(), [o2])
Fred Drakeccc75622001-09-06 14:52:39 +00001297
1298 def test_weak_valued_delitem(self):
1299 d = weakref.WeakValueDictionary()
1300 o1 = Object('1')
1301 o2 = Object('2')
1302 d['something'] = o1
1303 d['something else'] = o2
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001304 self.assertEqual(len(d), 2)
Fred Drakeccc75622001-09-06 14:52:39 +00001305 del d['something']
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001306 self.assertEqual(len(d), 1)
1307 self.assertEqual(d.items(), [('something else', o2)])
Fred Drakeccc75622001-09-06 14:52:39 +00001308
Tim Peters886128f2003-05-25 01:45:11 +00001309 def test_weak_keyed_bad_delitem(self):
1310 d = weakref.WeakKeyDictionary()
1311 o = Object('1')
1312 # An attempt to delete an object that isn't there should raise
Tim Peters50d8b8b2003-05-25 17:44:31 +00001313 # KeyError. It didn't before 2.3.
Tim Peters886128f2003-05-25 01:45:11 +00001314 self.assertRaises(KeyError, d.__delitem__, o)
Tim Peters50d8b8b2003-05-25 17:44:31 +00001315 self.assertRaises(KeyError, d.__getitem__, o)
1316
1317 # If a key isn't of a weakly referencable type, __getitem__ and
1318 # __setitem__ raise TypeError. __delitem__ should too.
1319 self.assertRaises(TypeError, d.__delitem__, 13)
1320 self.assertRaises(TypeError, d.__getitem__, 13)
1321 self.assertRaises(TypeError, d.__setitem__, 13, 13)
Tim Peters886128f2003-05-25 01:45:11 +00001322
1323 def test_weak_keyed_cascading_deletes(self):
1324 # SF bug 742860. For some reason, before 2.3 __delitem__ iterated
1325 # over the keys via self.data.iterkeys(). If things vanished from
1326 # the dict during this (or got added), that caused a RuntimeError.
1327
1328 d = weakref.WeakKeyDictionary()
1329 mutate = False
1330
1331 class C(object):
1332 def __init__(self, i):
1333 self.value = i
1334 def __hash__(self):
1335 return hash(self.value)
1336 def __eq__(self, other):
1337 if mutate:
1338 # Side effect that mutates the dict, by removing the
1339 # last strong reference to a key.
1340 del objs[-1]
1341 return self.value == other.value
1342
1343 objs = [C(i) for i in range(4)]
1344 for o in objs:
1345 d[o] = o.value
1346 del o # now the only strong references to keys are in objs
1347 # Find the order in which iterkeys sees the keys.
1348 objs = d.keys()
1349 # Reverse it, so that the iteration implementation of __delitem__
1350 # has to keep looping to find the first object we delete.
1351 objs.reverse()
Tim Peters50d8b8b2003-05-25 17:44:31 +00001352
Tim Peters886128f2003-05-25 01:45:11 +00001353 # Turn on mutation in C.__eq__. The first time thru the loop,
1354 # under the iterkeys() business the first comparison will delete
1355 # the last item iterkeys() would see, and that causes a
1356 # RuntimeError: dictionary changed size during iteration
1357 # when the iterkeys() loop goes around to try comparing the next
Tim Peters50d8b8b2003-05-25 17:44:31 +00001358 # key. After this was fixed, it just deletes the last object *our*
Tim Peters886128f2003-05-25 01:45:11 +00001359 # "for o in obj" loop would have gotten to.
1360 mutate = True
1361 count = 0
1362 for o in objs:
1363 count += 1
1364 del d[o]
1365 self.assertEqual(len(d), 0)
1366 self.assertEqual(count, 2)
1367
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001368from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001369
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001370class WeakValueDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +00001371 """Check that WeakValueDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001372 __ref = {"key1":Object(1), "key2":Object(2), "key3":Object(3)}
Walter Dörwald118f9312004-06-02 18:42:25 +00001373 type2test = weakref.WeakValueDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001374 def _reference(self):
1375 return self.__ref.copy()
1376
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001377class WeakKeyDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +00001378 """Check that WeakKeyDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001379 __ref = {Object("key1"):1, Object("key2"):2, Object("key3"):3}
Walter Dörwald118f9312004-06-02 18:42:25 +00001380 type2test = weakref.WeakKeyDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001381 def _reference(self):
1382 return self.__ref.copy()
Martin v. Löwis5e163332001-02-27 18:36:56 +00001383
Georg Brandl88659b02008-05-20 08:40:43 +00001384libreftest = """ Doctest for examples in the library reference: weakref.rst
Georg Brandl9a65d582005-07-02 19:07:30 +00001385
1386>>> import weakref
1387>>> class Dict(dict):
1388... pass
1389...
1390>>> obj = Dict(red=1, green=2, blue=3) # this object is weak referencable
1391>>> r = weakref.ref(obj)
Armin Rigoa3f09272006-05-28 19:13:17 +00001392>>> print r() is obj
1393True
Georg Brandl9a65d582005-07-02 19:07:30 +00001394
1395>>> import weakref
1396>>> class Object:
1397... pass
1398...
1399>>> o = Object()
1400>>> r = weakref.ref(o)
1401>>> o2 = r()
1402>>> o is o2
1403True
1404>>> del o, o2
1405>>> print r()
1406None
1407
1408>>> import weakref
1409>>> class ExtendedRef(weakref.ref):
1410... def __init__(self, ob, callback=None, **annotations):
1411... super(ExtendedRef, self).__init__(ob, callback)
1412... self.__counter = 0
1413... for k, v in annotations.iteritems():
1414... setattr(self, k, v)
1415... def __call__(self):
1416... '''Return a pair containing the referent and the number of
1417... times the reference has been called.
1418... '''
1419... ob = super(ExtendedRef, self).__call__()
1420... if ob is not None:
1421... self.__counter += 1
1422... ob = (ob, self.__counter)
1423... return ob
1424...
1425>>> class A: # not in docs from here, just testing the ExtendedRef
1426... pass
1427...
1428>>> a = A()
1429>>> r = ExtendedRef(a, foo=1, bar="baz")
1430>>> r.foo
14311
1432>>> r.bar
1433'baz'
1434>>> r()[1]
14351
1436>>> r()[1]
14372
1438>>> r()[0] is a
1439True
1440
1441
1442>>> import weakref
1443>>> _id2obj_dict = weakref.WeakValueDictionary()
1444>>> def remember(obj):
1445... oid = id(obj)
1446... _id2obj_dict[oid] = obj
1447... return oid
1448...
1449>>> def id2obj(oid):
1450... return _id2obj_dict[oid]
1451...
1452>>> a = A() # from here, just testing
1453>>> a_id = remember(a)
1454>>> id2obj(a_id) is a
1455True
1456>>> del a
1457>>> try:
1458... id2obj(a_id)
1459... except KeyError:
1460... print 'OK'
1461... else:
1462... print 'WeakValueDictionary error'
1463OK
1464
1465"""
1466
1467__test__ = {'libreftest' : libreftest}
1468
Fred Drake2e2be372001-09-20 21:33:42 +00001469def test_main():
Walter Dörwald21d3a322003-05-01 17:45:56 +00001470 test_support.run_unittest(
1471 ReferencesTestCase,
1472 MappingTestCase,
1473 WeakValueDictionaryTestCase,
Fred Drakef425b1e2003-07-14 21:37:17 +00001474 WeakKeyDictionaryTestCase,
Amaury Forgeot d'Arca8919fe2008-06-16 19:12:42 +00001475 SubclassableWeakrefTestCase,
Fred Drakef425b1e2003-07-14 21:37:17 +00001476 )
Georg Brandl9a65d582005-07-02 19:07:30 +00001477 test_support.run_doctest(sys.modules[__name__])
Fred Drake2e2be372001-09-20 21:33:42 +00001478
1479
1480if __name__ == "__main__":
1481 test_main()