blob: 415d5ebbd728bf85cd444cee8c85c83c1b8b0b17 [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
Antoine Pitrou805f2832016-12-19 11:12:58 +01009import time
Fred Drake41deb1e2001-02-01 05:27:45 +000010
Barry Warsaw04f357c2002-07-23 19:04:11 +000011from test import test_support
Fred Drake41deb1e2001-02-01 05:27:45 +000012
Brett Cannonf5bee302007-01-23 23:21:22 +000013# Used in ReferencesTestCase.test_ref_created_during_del() .
14ref_from_del = None
Fred Drake41deb1e2001-02-01 05:27:45 +000015
16class C:
Fred Drakeb0fefc52001-03-23 04:22:45 +000017 def method(self):
18 pass
Fred Drake41deb1e2001-02-01 05:27:45 +000019
20
Fred Drakeb0fefc52001-03-23 04:22:45 +000021class Callable:
22 bar = None
Fred Drake41deb1e2001-02-01 05:27:45 +000023
Fred Drakeb0fefc52001-03-23 04:22:45 +000024 def __call__(self, x):
25 self.bar = x
Fred Drake41deb1e2001-02-01 05:27:45 +000026
27
Fred Drakeb0fefc52001-03-23 04:22:45 +000028def create_function():
29 def f(): pass
30 return f
31
32def create_bound_method():
33 return C().method
34
35def create_unbound_method():
36 return C.method
Fred Drake41deb1e2001-02-01 05:27:45 +000037
38
Antoine Pitroub704eab2012-11-11 19:36:51 +010039class Object:
40 def __init__(self, arg):
41 self.arg = arg
42 def __repr__(self):
43 return "<Object %r>" % self.arg
44 def __eq__(self, other):
45 if isinstance(other, Object):
46 return self.arg == other.arg
47 return NotImplemented
48 def __ne__(self, other):
49 if isinstance(other, Object):
50 return self.arg != other.arg
51 return NotImplemented
52 def __hash__(self):
53 return hash(self.arg)
54
55class RefCycle:
56 def __init__(self):
57 self.cycle = self
58
59
Antoine Pitrou805f2832016-12-19 11:12:58 +010060@contextlib.contextmanager
Victor Stinner1fef0152017-07-04 11:36:16 +020061def collect_in_thread(period=0.001):
Antoine Pitrou805f2832016-12-19 11:12:58 +010062 """
63 Ensure GC collections happen in a different thread, at a high frequency.
64 """
65 threading = test_support.import_module('threading')
66 please_stop = False
67
68 def collect():
69 while not please_stop:
70 time.sleep(period)
71 gc.collect()
72
73 with test_support.disable_gc():
74 old_interval = sys.getcheckinterval()
75 sys.setcheckinterval(20)
76 t = threading.Thread(target=collect)
77 t.start()
78 try:
79 yield
80 finally:
81 please_stop = True
82 t.join()
83 sys.setcheckinterval(old_interval)
84
85
Fred Drakeb0fefc52001-03-23 04:22:45 +000086class TestBase(unittest.TestCase):
87
88 def setUp(self):
89 self.cbcalled = 0
90
91 def callback(self, ref):
92 self.cbcalled += 1
Fred Drake41deb1e2001-02-01 05:27:45 +000093
94
Fred Drakeb0fefc52001-03-23 04:22:45 +000095class ReferencesTestCase(TestBase):
Fred Drake41deb1e2001-02-01 05:27:45 +000096
Fred Drakeb0fefc52001-03-23 04:22:45 +000097 def test_basic_ref(self):
98 self.check_basic_ref(C)
99 self.check_basic_ref(create_function)
100 self.check_basic_ref(create_bound_method)
101 self.check_basic_ref(create_unbound_method)
Fred Drake41deb1e2001-02-01 05:27:45 +0000102
Fred Drake43735da2002-04-11 03:59:42 +0000103 # Just make sure the tp_repr handler doesn't raise an exception.
104 # Live reference:
105 o = C()
106 wr = weakref.ref(o)
Florent Xicluna07627882010-03-21 01:14:24 +0000107 repr(wr)
Fred Drake43735da2002-04-11 03:59:42 +0000108 # Dead reference:
109 del o
Florent Xicluna07627882010-03-21 01:14:24 +0000110 repr(wr)
Fred Drake43735da2002-04-11 03:59:42 +0000111
Fred Drakeb0fefc52001-03-23 04:22:45 +0000112 def test_basic_callback(self):
113 self.check_basic_callback(C)
114 self.check_basic_callback(create_function)
115 self.check_basic_callback(create_bound_method)
116 self.check_basic_callback(create_unbound_method)
Fred Drake41deb1e2001-02-01 05:27:45 +0000117
Fred Drakeb0fefc52001-03-23 04:22:45 +0000118 def test_multiple_callbacks(self):
119 o = C()
120 ref1 = weakref.ref(o, self.callback)
121 ref2 = weakref.ref(o, self.callback)
122 del o
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200123 self.assertIsNone(ref1(), "expected reference to be invalidated")
124 self.assertIsNone(ref2(), "expected reference to be invalidated")
125 self.assertEqual(self.cbcalled, 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000126 "callback not called the right number of times")
Fred Drake41deb1e2001-02-01 05:27:45 +0000127
Fred Drake705088e2001-04-13 17:18:15 +0000128 def test_multiple_selfref_callbacks(self):
Guido van Rossum9eee5542002-08-22 20:21:30 +0000129 # Make sure all references are invalidated before callbacks are called
Fred Drake705088e2001-04-13 17:18:15 +0000130 #
131 # What's important here is that we're using the first
132 # reference in the callback invoked on the second reference
133 # (the most recently created ref is cleaned up first). This
134 # tests that all references to the object are invalidated
135 # before any of the callbacks are invoked, so that we only
136 # have one invocation of _weakref.c:cleanup_helper() active
137 # for a particular object at a time.
138 #
139 def callback(object, self=self):
140 self.ref()
141 c = C()
142 self.ref = weakref.ref(c, callback)
143 ref1 = weakref.ref(c, callback)
144 del c
145
Serhiy Storchaka816a5ff2016-05-07 15:41:09 +0300146 def test_constructor_kwargs(self):
147 c = C()
148 self.assertRaises(TypeError, weakref.ref, c, callback=None)
149
Fred Drakeb0fefc52001-03-23 04:22:45 +0000150 def test_proxy_ref(self):
151 o = C()
152 o.bar = 1
153 ref1 = weakref.proxy(o, self.callback)
154 ref2 = weakref.proxy(o, self.callback)
155 del o
Fred Drake41deb1e2001-02-01 05:27:45 +0000156
Fred Drakeb0fefc52001-03-23 04:22:45 +0000157 def check(proxy):
158 proxy.bar
Fred Drake41deb1e2001-02-01 05:27:45 +0000159
Fred Drakeb0fefc52001-03-23 04:22:45 +0000160 self.assertRaises(weakref.ReferenceError, check, ref1)
161 self.assertRaises(weakref.ReferenceError, check, ref2)
Neal Norwitzbdcb9412004-07-08 01:22:31 +0000162 self.assertRaises(weakref.ReferenceError, bool, weakref.proxy(C()))
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200163 self.assertEqual(self.cbcalled, 2)
Fred Drake41deb1e2001-02-01 05:27:45 +0000164
Fred Drakeb0fefc52001-03-23 04:22:45 +0000165 def check_basic_ref(self, factory):
166 o = factory()
167 ref = weakref.ref(o)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200168 self.assertIsNotNone(ref(),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000169 "weak reference to live object should be live")
170 o2 = ref()
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200171 self.assertIs(o, o2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000172 "<ref>() should return original object if live")
Fred Drake41deb1e2001-02-01 05:27:45 +0000173
Fred Drakeb0fefc52001-03-23 04:22:45 +0000174 def check_basic_callback(self, factory):
175 self.cbcalled = 0
176 o = factory()
177 ref = weakref.ref(o, self.callback)
178 del o
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200179 self.assertEqual(self.cbcalled, 1,
Fred Drake705088e2001-04-13 17:18:15 +0000180 "callback did not properly set 'cbcalled'")
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200181 self.assertIsNone(ref(),
Fred Drake705088e2001-04-13 17:18:15 +0000182 "ref2 should be dead after deleting object reference")
Fred Drake41deb1e2001-02-01 05:27:45 +0000183
Fred Drakeb0fefc52001-03-23 04:22:45 +0000184 def test_ref_reuse(self):
185 o = C()
186 ref1 = weakref.ref(o)
187 # create a proxy to make sure that there's an intervening creation
188 # between these two; it should make no difference
189 proxy = weakref.proxy(o)
190 ref2 = weakref.ref(o)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200191 self.assertIs(ref1, ref2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000192 "reference object w/out callback should be re-used")
Fred Drake41deb1e2001-02-01 05:27:45 +0000193
Fred Drakeb0fefc52001-03-23 04:22:45 +0000194 o = C()
195 proxy = weakref.proxy(o)
196 ref1 = weakref.ref(o)
197 ref2 = weakref.ref(o)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200198 self.assertIs(ref1, ref2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000199 "reference object w/out callback should be re-used")
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200200 self.assertEqual(weakref.getweakrefcount(o), 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000201 "wrong weak ref count for object")
202 del proxy
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200203 self.assertEqual(weakref.getweakrefcount(o), 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000204 "wrong weak ref count for object after deleting proxy")
Fred Drake41deb1e2001-02-01 05:27:45 +0000205
Fred Drakeb0fefc52001-03-23 04:22:45 +0000206 def test_proxy_reuse(self):
207 o = C()
208 proxy1 = weakref.proxy(o)
209 ref = weakref.ref(o)
210 proxy2 = weakref.proxy(o)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200211 self.assertIs(proxy1, proxy2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000212 "proxy object w/out callback should have been re-used")
213
214 def test_basic_proxy(self):
215 o = C()
216 self.check_proxy(o, weakref.proxy(o))
217
Fred Drake5935ff02001-12-19 16:54:23 +0000218 L = UserList.UserList()
219 p = weakref.proxy(L)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000220 self.assertFalse(p, "proxy for empty UserList should be false")
Fred Drake5935ff02001-12-19 16:54:23 +0000221 p.append(12)
222 self.assertEqual(len(L), 1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000223 self.assertTrue(p, "proxy for non-empty UserList should be true")
Florent Xicluna07627882010-03-21 01:14:24 +0000224 with test_support.check_py3k_warnings():
225 p[:] = [2, 3]
Fred Drake5935ff02001-12-19 16:54:23 +0000226 self.assertEqual(len(L), 2)
227 self.assertEqual(len(p), 2)
Ezio Melottiaa980582010-01-23 23:04:36 +0000228 self.assertIn(3, p, "proxy didn't support __contains__() properly")
Fred Drake5935ff02001-12-19 16:54:23 +0000229 p[1] = 5
230 self.assertEqual(L[1], 5)
231 self.assertEqual(p[1], 5)
232 L2 = UserList.UserList(L)
233 p2 = weakref.proxy(L2)
234 self.assertEqual(p, p2)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000235 ## self.assertEqual(repr(L2), repr(p2))
Fred Drake43735da2002-04-11 03:59:42 +0000236 L3 = UserList.UserList(range(10))
237 p3 = weakref.proxy(L3)
Florent Xicluna07627882010-03-21 01:14:24 +0000238 with test_support.check_py3k_warnings():
239 self.assertEqual(L3[:], p3[:])
240 self.assertEqual(L3[5:], p3[5:])
241 self.assertEqual(L3[:5], p3[:5])
242 self.assertEqual(L3[2:5], p3[2:5])
Fred Drake5935ff02001-12-19 16:54:23 +0000243
Benjamin Petersondc3c2392009-11-19 03:00:02 +0000244 def test_proxy_unicode(self):
245 # See bug 5037
246 class C(object):
247 def __str__(self):
248 return "string"
249 def __unicode__(self):
250 return u"unicode"
251 instance = C()
Ezio Melottiaa980582010-01-23 23:04:36 +0000252 self.assertIn("__unicode__", dir(weakref.proxy(instance)))
Benjamin Petersondc3c2392009-11-19 03:00:02 +0000253 self.assertEqual(unicode(weakref.proxy(instance)), u"unicode")
254
Georg Brandl88659b02008-05-20 08:40:43 +0000255 def test_proxy_index(self):
256 class C:
257 def __index__(self):
258 return 10
259 o = C()
260 p = weakref.proxy(o)
261 self.assertEqual(operator.index(p), 10)
262
263 def test_proxy_div(self):
264 class C:
265 def __floordiv__(self, other):
266 return 42
267 def __ifloordiv__(self, other):
268 return 21
269 o = C()
270 p = weakref.proxy(o)
271 self.assertEqual(p // 5, 42)
272 p //= 5
273 self.assertEqual(p, 21)
274
Fred Drakeea2adc92004-02-03 19:56:46 +0000275 # The PyWeakref_* C API is documented as allowing either NULL or
276 # None as the value for the callback, where either means "no
277 # callback". The "no callback" ref and proxy objects are supposed
278 # to be shared so long as they exist by all callers so long as
Walter Dörwaldda1ad322006-12-12 21:55:31 +0000279 # they are active. In Python 2.3.3 and earlier, this guarantee
Fred Drakeea2adc92004-02-03 19:56:46 +0000280 # was not honored, and was broken in different ways for
281 # PyWeakref_NewRef() and PyWeakref_NewProxy(). (Two tests.)
282
283 def test_shared_ref_without_callback(self):
284 self.check_shared_without_callback(weakref.ref)
285
286 def test_shared_proxy_without_callback(self):
287 self.check_shared_without_callback(weakref.proxy)
288
289 def check_shared_without_callback(self, makeref):
290 o = Object(1)
291 p1 = makeref(o, None)
292 p2 = makeref(o, None)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200293 self.assertIs(p1, p2, "both callbacks were None in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000294 del p1, p2
295 p1 = makeref(o)
296 p2 = makeref(o, None)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200297 self.assertIs(p1, p2, "callbacks were NULL, None in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000298 del p1, p2
299 p1 = makeref(o)
300 p2 = makeref(o)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200301 self.assertIs(p1, p2, "both callbacks were NULL in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000302 del p1, p2
303 p1 = makeref(o, None)
304 p2 = makeref(o)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200305 self.assertIs(p1, p2, "callbacks were None, NULL in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000306
Fred Drakeb0fefc52001-03-23 04:22:45 +0000307 def test_callable_proxy(self):
308 o = Callable()
309 ref1 = weakref.proxy(o)
310
311 self.check_proxy(o, ref1)
312
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200313 self.assertIs(type(ref1), weakref.CallableProxyType,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000314 "proxy is not of callable type")
315 ref1('twinkies!')
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200316 self.assertEqual(o.bar, 'twinkies!',
Fred Drakeb0fefc52001-03-23 04:22:45 +0000317 "call through proxy not passed through to original")
Fred Drake3bb4d212001-10-18 19:28:29 +0000318 ref1(x='Splat.')
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200319 self.assertEqual(o.bar, 'Splat.',
Fred Drake3bb4d212001-10-18 19:28:29 +0000320 "call through proxy not passed through to original")
Fred Drakeb0fefc52001-03-23 04:22:45 +0000321
322 # expect due to too few args
323 self.assertRaises(TypeError, ref1)
324
325 # expect due to too many args
326 self.assertRaises(TypeError, ref1, 1, 2, 3)
327
328 def check_proxy(self, o, proxy):
329 o.foo = 1
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200330 self.assertEqual(proxy.foo, 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000331 "proxy does not reflect attribute addition")
332 o.foo = 2
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200333 self.assertEqual(proxy.foo, 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000334 "proxy does not reflect attribute modification")
335 del o.foo
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200336 self.assertFalse(hasattr(proxy, 'foo'),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000337 "proxy does not reflect attribute removal")
338
339 proxy.foo = 1
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200340 self.assertEqual(o.foo, 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000341 "object does not reflect attribute addition via proxy")
342 proxy.foo = 2
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200343 self.assertEqual(o.foo, 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000344 "object does not reflect attribute modification via proxy")
345 del proxy.foo
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200346 self.assertFalse(hasattr(o, 'foo'),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000347 "object does not reflect attribute removal via proxy")
348
Raymond Hettingerd693a812003-06-30 04:18:48 +0000349 def test_proxy_deletion(self):
350 # Test clearing of SF bug #762891
351 class Foo:
352 result = None
353 def __delitem__(self, accessor):
354 self.result = accessor
355 g = Foo()
356 f = weakref.proxy(g)
357 del f[0]
358 self.assertEqual(f.result, 0)
359
Raymond Hettingere6c470f2005-03-27 03:04:54 +0000360 def test_proxy_bool(self):
361 # Test clearing of SF bug #1170766
362 class List(list): pass
363 lyst = List()
364 self.assertEqual(bool(weakref.proxy(lyst)), bool(lyst))
365
Fred Drakeb0fefc52001-03-23 04:22:45 +0000366 def test_getweakrefcount(self):
367 o = C()
368 ref1 = weakref.ref(o)
369 ref2 = weakref.ref(o, self.callback)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200370 self.assertEqual(weakref.getweakrefcount(o), 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000371 "got wrong number of weak reference objects")
372
373 proxy1 = weakref.proxy(o)
374 proxy2 = weakref.proxy(o, self.callback)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200375 self.assertEqual(weakref.getweakrefcount(o), 4,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000376 "got wrong number of weak reference objects")
377
Fred Drakeea2adc92004-02-03 19:56:46 +0000378 del ref1, ref2, proxy1, proxy2
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200379 self.assertEqual(weakref.getweakrefcount(o), 0,
Fred Drakeea2adc92004-02-03 19:56:46 +0000380 "weak reference objects not unlinked from"
381 " referent when discarded.")
382
Walter Dörwaldb167b042003-12-11 12:34:05 +0000383 # assumes ints do not support weakrefs
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200384 self.assertEqual(weakref.getweakrefcount(1), 0,
Walter Dörwaldb167b042003-12-11 12:34:05 +0000385 "got wrong number of weak reference objects for int")
386
Fred Drakeb0fefc52001-03-23 04:22:45 +0000387 def test_getweakrefs(self):
388 o = C()
389 ref1 = weakref.ref(o, self.callback)
390 ref2 = weakref.ref(o, self.callback)
391 del ref1
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200392 self.assertEqual(weakref.getweakrefs(o), [ref2],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000393 "list of refs does not match")
394
395 o = C()
396 ref1 = weakref.ref(o, self.callback)
397 ref2 = weakref.ref(o, self.callback)
398 del ref2
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200399 self.assertEqual(weakref.getweakrefs(o), [ref1],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000400 "list of refs does not match")
401
Fred Drakeea2adc92004-02-03 19:56:46 +0000402 del ref1
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200403 self.assertEqual(weakref.getweakrefs(o), [],
Fred Drakeea2adc92004-02-03 19:56:46 +0000404 "list of refs not cleared")
405
Walter Dörwaldb167b042003-12-11 12:34:05 +0000406 # assumes ints do not support weakrefs
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200407 self.assertEqual(weakref.getweakrefs(1), [],
Walter Dörwaldb167b042003-12-11 12:34:05 +0000408 "list of refs does not match for int")
409
Fred Drake39c27f12001-10-18 18:06:05 +0000410 def test_newstyle_number_ops(self):
411 class F(float):
412 pass
413 f = F(2.0)
414 p = weakref.proxy(f)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200415 self.assertEqual(p + 1.0, 3.0)
416 self.assertEqual(1.0 + p, 3.0) # this used to SEGV
Fred Drake39c27f12001-10-18 18:06:05 +0000417
Fred Drake2a64f462001-12-10 23:46:02 +0000418 def test_callbacks_protected(self):
Guido van Rossum9eee5542002-08-22 20:21:30 +0000419 # Callbacks protected from already-set exceptions?
Fred Drake2a64f462001-12-10 23:46:02 +0000420 # Regression test for SF bug #478534.
421 class BogusError(Exception):
422 pass
423 data = {}
424 def remove(k):
425 del data[k]
426 def encapsulate():
427 f = lambda : ()
428 data[weakref.ref(f, remove)] = None
429 raise BogusError
430 try:
431 encapsulate()
432 except BogusError:
433 pass
434 else:
435 self.fail("exception not properly restored")
436 try:
437 encapsulate()
438 except BogusError:
439 pass
440 else:
441 self.fail("exception not properly restored")
442
Tim Petersadd09b42003-11-12 20:43:28 +0000443 def test_sf_bug_840829(self):
444 # "weakref callbacks and gc corrupt memory"
445 # subtype_dealloc erroneously exposed a new-style instance
446 # already in the process of getting deallocated to gc,
447 # causing double-deallocation if the instance had a weakref
448 # callback that triggered gc.
449 # If the bug exists, there probably won't be an obvious symptom
450 # in a release build. In a debug build, a segfault will occur
451 # when the second attempt to remove the instance from the "list
452 # of all objects" occurs.
453
454 import gc
455
456 class C(object):
457 pass
458
459 c = C()
460 wr = weakref.ref(c, lambda ignore: gc.collect())
461 del c
462
Tim Petersf7f9e992003-11-13 21:59:32 +0000463 # There endeth the first part. It gets worse.
464 del wr
465
466 c1 = C()
467 c1.i = C()
468 wr = weakref.ref(c1.i, lambda ignore: gc.collect())
469
470 c2 = C()
471 c2.c1 = c1
472 del c1 # still alive because c2 points to it
473
474 # Now when subtype_dealloc gets called on c2, it's not enough just
475 # that c2 is immune from gc while the weakref callbacks associated
476 # with c2 execute (there are none in this 2nd half of the test, btw).
477 # subtype_dealloc goes on to call the base classes' deallocs too,
478 # so any gc triggered by weakref callbacks associated with anything
479 # torn down by a base class dealloc can also trigger double
480 # deallocation of c2.
481 del c2
Fred Drake41deb1e2001-02-01 05:27:45 +0000482
Tim Peters403a2032003-11-20 21:21:46 +0000483 def test_callback_in_cycle_1(self):
484 import gc
485
486 class J(object):
487 pass
488
489 class II(object):
490 def acallback(self, ignore):
491 self.J
492
493 I = II()
494 I.J = J
495 I.wr = weakref.ref(J, I.acallback)
496
497 # Now J and II are each in a self-cycle (as all new-style class
498 # objects are, since their __mro__ points back to them). I holds
499 # both a weak reference (I.wr) and a strong reference (I.J) to class
500 # J. I is also in a cycle (I.wr points to a weakref that references
501 # I.acallback). When we del these three, they all become trash, but
502 # the cycles prevent any of them from getting cleaned up immediately.
503 # Instead they have to wait for cyclic gc to deduce that they're
504 # trash.
505 #
506 # gc used to call tp_clear on all of them, and the order in which
507 # it does that is pretty accidental. The exact order in which we
508 # built up these things manages to provoke gc into running tp_clear
509 # in just the right order (I last). Calling tp_clear on II leaves
510 # behind an insane class object (its __mro__ becomes NULL). Calling
511 # tp_clear on J breaks its self-cycle, but J doesn't get deleted
512 # just then because of the strong reference from I.J. Calling
513 # tp_clear on I starts to clear I's __dict__, and just happens to
514 # clear I.J first -- I.wr is still intact. That removes the last
515 # reference to J, which triggers the weakref callback. The callback
516 # tries to do "self.J", and instances of new-style classes look up
517 # attributes ("J") in the class dict first. The class (II) wants to
518 # search II.__mro__, but that's NULL. The result was a segfault in
519 # a release build, and an assert failure in a debug build.
520 del I, J, II
521 gc.collect()
522
523 def test_callback_in_cycle_2(self):
524 import gc
525
526 # This is just like test_callback_in_cycle_1, except that II is an
527 # old-style class. The symptom is different then: an instance of an
528 # old-style class looks in its own __dict__ first. 'J' happens to
529 # get cleared from I.__dict__ before 'wr', and 'J' was never in II's
530 # __dict__, so the attribute isn't found. The difference is that
531 # the old-style II doesn't have a NULL __mro__ (it doesn't have any
532 # __mro__), so no segfault occurs. Instead it got:
533 # test_callback_in_cycle_2 (__main__.ReferencesTestCase) ...
534 # Exception exceptions.AttributeError:
535 # "II instance has no attribute 'J'" in <bound method II.acallback
536 # of <?.II instance at 0x00B9B4B8>> ignored
537
538 class J(object):
539 pass
540
541 class II:
542 def acallback(self, ignore):
543 self.J
544
545 I = II()
546 I.J = J
547 I.wr = weakref.ref(J, I.acallback)
548
549 del I, J, II
550 gc.collect()
551
552 def test_callback_in_cycle_3(self):
553 import gc
554
555 # This one broke the first patch that fixed the last two. In this
556 # case, the objects reachable from the callback aren't also reachable
557 # from the object (c1) *triggering* the callback: you can get to
558 # c1 from c2, but not vice-versa. The result was that c2's __dict__
559 # got tp_clear'ed by the time the c2.cb callback got invoked.
560
561 class C:
562 def cb(self, ignore):
563 self.me
564 self.c1
565 self.wr
566
567 c1, c2 = C(), C()
568
569 c2.me = c2
570 c2.c1 = c1
571 c2.wr = weakref.ref(c1, c2.cb)
572
573 del c1, c2
574 gc.collect()
575
576 def test_callback_in_cycle_4(self):
577 import gc
578
579 # Like test_callback_in_cycle_3, except c2 and c1 have different
580 # classes. c2's class (C) isn't reachable from c1 then, so protecting
581 # objects reachable from the dying object (c1) isn't enough to stop
582 # c2's class (C) from getting tp_clear'ed before c2.cb is invoked.
583 # The result was a segfault (C.__mro__ was NULL when the callback
584 # tried to look up self.me).
585
586 class C(object):
587 def cb(self, ignore):
588 self.me
589 self.c1
590 self.wr
591
592 class D:
593 pass
594
595 c1, c2 = D(), C()
596
597 c2.me = c2
598 c2.c1 = c1
599 c2.wr = weakref.ref(c1, c2.cb)
600
601 del c1, c2, C, D
602 gc.collect()
603
604 def test_callback_in_cycle_resurrection(self):
605 import gc
606
607 # Do something nasty in a weakref callback: resurrect objects
608 # from dead cycles. For this to be attempted, the weakref and
609 # its callback must also be part of the cyclic trash (else the
610 # objects reachable via the callback couldn't be in cyclic trash
611 # to begin with -- the callback would act like an external root).
612 # But gc clears trash weakrefs with callbacks early now, which
613 # disables the callbacks, so the callbacks shouldn't get called
614 # at all (and so nothing actually gets resurrected).
615
616 alist = []
617 class C(object):
618 def __init__(self, value):
619 self.attribute = value
620
621 def acallback(self, ignore):
622 alist.append(self.c)
623
624 c1, c2 = C(1), C(2)
625 c1.c = c2
626 c2.c = c1
627 c1.wr = weakref.ref(c2, c1.acallback)
628 c2.wr = weakref.ref(c1, c2.acallback)
629
630 def C_went_away(ignore):
631 alist.append("C went away")
632 wr = weakref.ref(C, C_went_away)
633
634 del c1, c2, C # make them all trash
635 self.assertEqual(alist, []) # del isn't enough to reclaim anything
636
637 gc.collect()
638 # c1.wr and c2.wr were part of the cyclic trash, so should have
639 # been cleared without their callbacks executing. OTOH, the weakref
640 # to C is bound to a function local (wr), and wasn't trash, so that
641 # callback should have been invoked when C went away.
642 self.assertEqual(alist, ["C went away"])
643 # The remaining weakref should be dead now (its callback ran).
644 self.assertEqual(wr(), None)
645
646 del alist[:]
647 gc.collect()
648 self.assertEqual(alist, [])
649
650 def test_callbacks_on_callback(self):
651 import gc
652
653 # Set up weakref callbacks *on* weakref callbacks.
654 alist = []
655 def safe_callback(ignore):
656 alist.append("safe_callback called")
657
658 class C(object):
659 def cb(self, ignore):
660 alist.append("cb called")
661
662 c, d = C(), C()
663 c.other = d
664 d.other = c
665 callback = c.cb
666 c.wr = weakref.ref(d, callback) # this won't trigger
667 d.wr = weakref.ref(callback, d.cb) # ditto
668 external_wr = weakref.ref(callback, safe_callback) # but this will
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200669 self.assertIs(external_wr(), callback)
Tim Peters403a2032003-11-20 21:21:46 +0000670
671 # The weakrefs attached to c and d should get cleared, so that
672 # C.cb is never called. But external_wr isn't part of the cyclic
673 # trash, and no cyclic trash is reachable from it, so safe_callback
674 # should get invoked when the bound method object callback (c.cb)
675 # -- which is itself a callback, and also part of the cyclic trash --
676 # gets reclaimed at the end of gc.
677
678 del callback, c, d, C
679 self.assertEqual(alist, []) # del isn't enough to clean up cycles
680 gc.collect()
681 self.assertEqual(alist, ["safe_callback called"])
682 self.assertEqual(external_wr(), None)
683
684 del alist[:]
685 gc.collect()
686 self.assertEqual(alist, [])
687
Fred Drakebc875f52004-02-04 23:14:14 +0000688 def test_gc_during_ref_creation(self):
689 self.check_gc_during_creation(weakref.ref)
690
691 def test_gc_during_proxy_creation(self):
692 self.check_gc_during_creation(weakref.proxy)
693
694 def check_gc_during_creation(self, makeref):
695 thresholds = gc.get_threshold()
696 gc.set_threshold(1, 1, 1)
697 gc.collect()
Fred Drake55cf4342004-02-13 19:21:57 +0000698 class A:
699 pass
Fred Drakebc875f52004-02-04 23:14:14 +0000700
701 def callback(*args):
702 pass
703
Fred Drake55cf4342004-02-13 19:21:57 +0000704 referenced = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000705
Fred Drake55cf4342004-02-13 19:21:57 +0000706 a = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000707 a.a = a
708 a.wr = makeref(referenced)
709
710 try:
711 # now make sure the object and the ref get labeled as
712 # cyclic trash:
Fred Drake55cf4342004-02-13 19:21:57 +0000713 a = A()
714 weakref.ref(referenced, callback)
Fred Drakebc875f52004-02-04 23:14:14 +0000715
716 finally:
717 gc.set_threshold(*thresholds)
718
Brett Cannonf5bee302007-01-23 23:21:22 +0000719 def test_ref_created_during_del(self):
720 # Bug #1377858
721 # A weakref created in an object's __del__() would crash the
722 # interpreter when the weakref was cleaned up since it would refer to
723 # non-existent memory. This test should not segfault the interpreter.
724 class Target(object):
725 def __del__(self):
726 global ref_from_del
727 ref_from_del = weakref.ref(self)
728
729 w = Target()
730
Benjamin Peterson97179b02008-09-09 20:55:01 +0000731 def test_init(self):
732 # Issue 3634
733 # <weakref to class>.__init__() doesn't check errors correctly
734 r = weakref.ref(Exception)
735 self.assertRaises(TypeError, r.__init__, 0, 0, 0, 0, 0)
736 # No exception should be raised here
737 gc.collect()
738
Antoine Pitroua57df2c2010-03-31 21:32:15 +0000739 def test_classes(self):
740 # Check that both old-style classes and new-style classes
741 # are weakrefable.
742 class A(object):
743 pass
744 class B:
745 pass
746 l = []
747 weakref.ref(int)
748 a = weakref.ref(A, l.append)
749 A = None
750 gc.collect()
751 self.assertEqual(a(), None)
752 self.assertEqual(l, [a])
753 b = weakref.ref(B, l.append)
754 B = None
755 gc.collect()
756 self.assertEqual(b(), None)
757 self.assertEqual(l, [a, b])
758
Antoine Pitroub704eab2012-11-11 19:36:51 +0100759 def test_equality(self):
760 # Alive weakrefs defer equality testing to their underlying object.
761 x = Object(1)
762 y = Object(1)
763 z = Object(2)
764 a = weakref.ref(x)
765 b = weakref.ref(y)
766 c = weakref.ref(z)
767 d = weakref.ref(x)
768 # Note how we directly test the operators here, to stress both
769 # __eq__ and __ne__.
770 self.assertTrue(a == b)
771 self.assertFalse(a != b)
772 self.assertFalse(a == c)
773 self.assertTrue(a != c)
774 self.assertTrue(a == d)
775 self.assertFalse(a != d)
776 del x, y, z
777 gc.collect()
778 for r in a, b, c:
779 # Sanity check
780 self.assertIs(r(), None)
781 # Dead weakrefs compare by identity: whether `a` and `d` are the
782 # same weakref object is an implementation detail, since they pointed
783 # to the same original object and didn't have a callback.
784 # (see issue #16453).
785 self.assertFalse(a == b)
786 self.assertTrue(a != b)
787 self.assertFalse(a == c)
788 self.assertTrue(a != c)
789 self.assertEqual(a == d, a is d)
790 self.assertEqual(a != d, a is not d)
791
792 def test_hashing(self):
793 # Alive weakrefs hash the same as the underlying object
794 x = Object(42)
795 y = Object(42)
796 a = weakref.ref(x)
797 b = weakref.ref(y)
798 self.assertEqual(hash(a), hash(42))
799 del x, y
800 gc.collect()
801 # Dead weakrefs:
802 # - retain their hash is they were hashed when alive;
803 # - otherwise, cannot be hashed.
804 self.assertEqual(hash(a), hash(42))
805 self.assertRaises(TypeError, hash, b)
806
Antoine Pitroud38c9902012-12-08 21:15:26 +0100807 def test_trashcan_16602(self):
808 # Issue #16602: when a weakref's target was part of a long
809 # deallocation chain, the trashcan mechanism could delay clearing
810 # of the weakref and make the target object visible from outside
811 # code even though its refcount had dropped to 0. A crash ensued.
812 class C(object):
813 def __init__(self, parent):
814 if not parent:
815 return
816 wself = weakref.ref(self)
817 def cb(wparent):
818 o = wself()
819 self.wparent = weakref.ref(parent, cb)
820
821 d = weakref.WeakKeyDictionary()
822 root = c = C(None)
823 for n in range(100):
824 d[c] = c = C(c)
825 del root
826 gc.collect()
827
Fred Drake0a4dd392004-07-02 18:57:45 +0000828
Amaury Forgeot d'Arca8919fe2008-06-16 19:12:42 +0000829class SubclassableWeakrefTestCase(TestBase):
Fred Drake0a4dd392004-07-02 18:57:45 +0000830
831 def test_subclass_refs(self):
832 class MyRef(weakref.ref):
833 def __init__(self, ob, callback=None, value=42):
834 self.value = value
835 super(MyRef, self).__init__(ob, callback)
836 def __call__(self):
837 self.called = True
838 return super(MyRef, self).__call__()
839 o = Object("foo")
840 mr = MyRef(o, value=24)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200841 self.assertIs(mr(), o)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000842 self.assertTrue(mr.called)
Fred Drake0a4dd392004-07-02 18:57:45 +0000843 self.assertEqual(mr.value, 24)
844 del o
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200845 self.assertIsNone(mr())
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000846 self.assertTrue(mr.called)
Fred Drake0a4dd392004-07-02 18:57:45 +0000847
848 def test_subclass_refs_dont_replace_standard_refs(self):
849 class MyRef(weakref.ref):
850 pass
851 o = Object(42)
852 r1 = MyRef(o)
853 r2 = weakref.ref(o)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200854 self.assertIsNot(r1, r2)
Fred Drake0a4dd392004-07-02 18:57:45 +0000855 self.assertEqual(weakref.getweakrefs(o), [r2, r1])
856 self.assertEqual(weakref.getweakrefcount(o), 2)
857 r3 = MyRef(o)
858 self.assertEqual(weakref.getweakrefcount(o), 3)
859 refs = weakref.getweakrefs(o)
860 self.assertEqual(len(refs), 3)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200861 self.assertIs(r2, refs[0])
Ezio Melottiaa980582010-01-23 23:04:36 +0000862 self.assertIn(r1, refs[1:])
863 self.assertIn(r3, refs[1:])
Fred Drake0a4dd392004-07-02 18:57:45 +0000864
865 def test_subclass_refs_dont_conflate_callbacks(self):
866 class MyRef(weakref.ref):
867 pass
868 o = Object(42)
869 r1 = MyRef(o, id)
870 r2 = MyRef(o, str)
Serhiy Storchakaca626b12013-11-17 13:20:50 +0200871 self.assertIsNot(r1, r2)
Fred Drake0a4dd392004-07-02 18:57:45 +0000872 refs = weakref.getweakrefs(o)
Ezio Melottiaa980582010-01-23 23:04:36 +0000873 self.assertIn(r1, refs)
874 self.assertIn(r2, refs)
Fred Drake0a4dd392004-07-02 18:57:45 +0000875
876 def test_subclass_refs_with_slots(self):
877 class MyRef(weakref.ref):
878 __slots__ = "slot1", "slot2"
879 def __new__(type, ob, callback, slot1, slot2):
880 return weakref.ref.__new__(type, ob, callback)
881 def __init__(self, ob, callback, slot1, slot2):
882 self.slot1 = slot1
883 self.slot2 = slot2
884 def meth(self):
885 return self.slot1 + self.slot2
886 o = Object(42)
887 r = MyRef(o, None, "abc", "def")
888 self.assertEqual(r.slot1, "abc")
889 self.assertEqual(r.slot2, "def")
890 self.assertEqual(r.meth(), "abcdef")
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000891 self.assertFalse(hasattr(r, "__dict__"))
Fred Drake0a4dd392004-07-02 18:57:45 +0000892
Amaury Forgeot d'Arca8919fe2008-06-16 19:12:42 +0000893 def test_subclass_refs_with_cycle(self):
894 # Bug #3110
895 # An instance of a weakref subclass can have attributes.
896 # If such a weakref holds the only strong reference to the object,
897 # deleting the weakref will delete the object. In this case,
898 # the callback must not be called, because the ref object is
899 # being deleted.
900 class MyRef(weakref.ref):
901 pass
902
903 # Use a local callback, for "regrtest -R::"
904 # to detect refcounting problems
905 def callback(w):
906 self.cbcalled += 1
907
908 o = C()
909 r1 = MyRef(o, callback)
910 r1.o = o
911 del o
912
913 del r1 # Used to crash here
914
915 self.assertEqual(self.cbcalled, 0)
916
917 # Same test, with two weakrefs to the same object
918 # (since code paths are different)
919 o = C()
920 r1 = MyRef(o, callback)
921 r2 = MyRef(o, callback)
922 r1.r = r2
923 r2.o = o
924 del o
925 del r2
926
927 del r1 # Used to crash here
928
929 self.assertEqual(self.cbcalled, 0)
930
Fred Drake0a4dd392004-07-02 18:57:45 +0000931
Fred Drakeb0fefc52001-03-23 04:22:45 +0000932class MappingTestCase(TestBase):
Martin v. Löwis5e163332001-02-27 18:36:56 +0000933
Fred Drakeb0fefc52001-03-23 04:22:45 +0000934 COUNT = 10
935
Antoine Pitrouc56bca32012-03-01 16:26:35 +0100936 def check_len_cycles(self, dict_type, cons):
937 N = 20
938 items = [RefCycle() for i in range(N)]
Kristján Valur Jónsson222b2842013-12-05 10:03:45 +0000939 dct = dict_type(cons(i, o) for i, o in enumerate(items))
Antoine Pitrouc56bca32012-03-01 16:26:35 +0100940 # Keep an iterator alive
941 it = dct.iteritems()
942 try:
943 next(it)
944 except StopIteration:
945 pass
946 del items
947 gc.collect()
948 n1 = len(dct)
Kristján Valur Jónsson222b2842013-12-05 10:03:45 +0000949 list(it)
Antoine Pitrouc56bca32012-03-01 16:26:35 +0100950 del it
951 gc.collect()
952 n2 = len(dct)
Kristján Valur Jónsson222b2842013-12-05 10:03:45 +0000953 # iteration should prevent garbage collection here
954 # Note that this is a test on an implementation detail. The requirement
955 # is only to provide stable iteration, not that the size of the container
956 # stay fixed.
957 self.assertEqual(n1, 20)
958 #self.assertIn(n1, (0, 1))
Antoine Pitrouc56bca32012-03-01 16:26:35 +0100959 self.assertEqual(n2, 0)
960
961 def test_weak_keyed_len_cycles(self):
Kristján Valur Jónsson222b2842013-12-05 10:03:45 +0000962 self.check_len_cycles(weakref.WeakKeyDictionary, lambda n, k: (k, n))
Antoine Pitrouc56bca32012-03-01 16:26:35 +0100963
964 def test_weak_valued_len_cycles(self):
Kristján Valur Jónsson222b2842013-12-05 10:03:45 +0000965 self.check_len_cycles(weakref.WeakValueDictionary, lambda n, k: (n, k))
Antoine Pitrouc56bca32012-03-01 16:26:35 +0100966
967 def check_len_race(self, dict_type, cons):
968 # Extended sanity checks for len() in the face of cyclic collection
969 self.addCleanup(gc.set_threshold, *gc.get_threshold())
970 for th in range(1, 100):
971 N = 20
972 gc.collect(0)
973 gc.set_threshold(th, th, th)
974 items = [RefCycle() for i in range(N)]
975 dct = dict_type(cons(o) for o in items)
976 del items
977 # All items will be collected at next garbage collection pass
978 it = dct.iteritems()
979 try:
980 next(it)
981 except StopIteration:
982 pass
983 n1 = len(dct)
984 del it
985 n2 = len(dct)
986 self.assertGreaterEqual(n1, 0)
987 self.assertLessEqual(n1, N)
988 self.assertGreaterEqual(n2, 0)
989 self.assertLessEqual(n2, n1)
990
991 def test_weak_keyed_len_race(self):
992 self.check_len_race(weakref.WeakKeyDictionary, lambda k: (k, 1))
993
994 def test_weak_valued_len_race(self):
995 self.check_len_race(weakref.WeakValueDictionary, lambda k: (1, k))
996
Fred Drakeb0fefc52001-03-23 04:22:45 +0000997 def test_weak_values(self):
Fred Drake0e540c32001-05-02 05:44:22 +0000998 #
999 # This exercises d.copy(), d.items(), d[], del d[], len(d).
1000 #
1001 dict, objects = self.make_weak_valued_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, dict[o.arg],
Fred Drakeb0fefc52001-03-23 04:22:45 +00001006 "wrong object returned by weak dict!")
1007 items1 = dict.items()
1008 items2 = dict.copy().items()
1009 items1.sort()
1010 items2.sort()
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001011 self.assertEqual(items1, items2,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001012 "cloning of weak-valued dictionary did not work!")
1013 del items1, items2
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001014 self.assertEqual(len(dict), self.COUNT)
Fred Drakeb0fefc52001-03-23 04:22:45 +00001015 del objects[0]
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001016 self.assertEqual(len(dict), (self.COUNT - 1),
Fred Drakeb0fefc52001-03-23 04:22:45 +00001017 "deleting object did not cause dictionary update")
1018 del objects, o
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001019 self.assertEqual(len(dict), 0,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001020 "deleting the values did not clear the dictionary")
Fred Drake4fd06e02001-08-03 04:11:27 +00001021 # regression on SF bug #447152:
1022 dict = weakref.WeakValueDictionary()
1023 self.assertRaises(KeyError, dict.__getitem__, 1)
1024 dict[2] = C()
1025 self.assertRaises(KeyError, dict.__getitem__, 2)
Fred Drakeb0fefc52001-03-23 04:22:45 +00001026
1027 def test_weak_keys(self):
Fred Drake0e540c32001-05-02 05:44:22 +00001028 #
1029 # This exercises d.copy(), d.items(), d[] = v, d[], del d[],
Florent Xicluna07627882010-03-21 01:14:24 +00001030 # len(d), in d.
Fred Drake0e540c32001-05-02 05:44:22 +00001031 #
1032 dict, objects = self.make_weak_keyed_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +00001033 for o in objects:
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001034 self.assertEqual(weakref.getweakrefcount(o), 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001035 "wrong number of weak references to %r!" % o)
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001036 self.assertIs(o.arg, dict[o],
Fred Drakeb0fefc52001-03-23 04:22:45 +00001037 "wrong object returned by weak dict!")
1038 items1 = dict.items()
1039 items2 = dict.copy().items()
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001040 self.assertEqual(set(items1), set(items2),
Fred Drakeb0fefc52001-03-23 04:22:45 +00001041 "cloning of weak-keyed dictionary did not work!")
1042 del items1, items2
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001043 self.assertEqual(len(dict), self.COUNT)
Fred Drakeb0fefc52001-03-23 04:22:45 +00001044 del objects[0]
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001045 self.assertEqual(len(dict), (self.COUNT - 1),
Fred Drakeb0fefc52001-03-23 04:22:45 +00001046 "deleting object did not cause dictionary update")
1047 del objects, o
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001048 self.assertEqual(len(dict), 0,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001049 "deleting the keys did not clear the dictionary")
Fred Drake752eda42001-11-06 16:38:34 +00001050 o = Object(42)
1051 dict[o] = "What is the meaning of the universe?"
Florent Xicluna07627882010-03-21 01:14:24 +00001052 self.assertIn(o, dict)
1053 self.assertNotIn(34, dict)
Martin v. Löwis5e163332001-02-27 18:36:56 +00001054
Fred Drake0e540c32001-05-02 05:44:22 +00001055 def test_weak_keyed_iters(self):
1056 dict, objects = self.make_weak_keyed_dict()
1057 self.check_iters(dict)
1058
Fred Drake017e68c2006-05-02 06:53:59 +00001059 # Test keyrefs()
1060 refs = dict.keyrefs()
1061 self.assertEqual(len(refs), len(objects))
1062 objects2 = list(objects)
1063 for wr in refs:
1064 ob = wr()
Ezio Melottiaa980582010-01-23 23:04:36 +00001065 self.assertIn(ob, dict)
Fred Drake017e68c2006-05-02 06:53:59 +00001066 self.assertEqual(ob.arg, dict[ob])
1067 objects2.remove(ob)
1068 self.assertEqual(len(objects2), 0)
1069
1070 # Test iterkeyrefs()
1071 objects2 = list(objects)
1072 self.assertEqual(len(list(dict.iterkeyrefs())), len(objects))
1073 for wr in dict.iterkeyrefs():
1074 ob = wr()
Ezio Melottiaa980582010-01-23 23:04:36 +00001075 self.assertIn(ob, dict)
Fred Drake017e68c2006-05-02 06:53:59 +00001076 self.assertEqual(ob.arg, dict[ob])
1077 objects2.remove(ob)
1078 self.assertEqual(len(objects2), 0)
1079
Fred Drake0e540c32001-05-02 05:44:22 +00001080 def test_weak_valued_iters(self):
1081 dict, objects = self.make_weak_valued_dict()
1082 self.check_iters(dict)
1083
Fred Drake017e68c2006-05-02 06:53:59 +00001084 # Test valuerefs()
1085 refs = dict.valuerefs()
1086 self.assertEqual(len(refs), len(objects))
1087 objects2 = list(objects)
1088 for wr in refs:
1089 ob = wr()
1090 self.assertEqual(ob, dict[ob.arg])
1091 self.assertEqual(ob.arg, dict[ob.arg].arg)
1092 objects2.remove(ob)
1093 self.assertEqual(len(objects2), 0)
1094
1095 # Test itervaluerefs()
1096 objects2 = list(objects)
1097 self.assertEqual(len(list(dict.itervaluerefs())), len(objects))
1098 for wr in dict.itervaluerefs():
1099 ob = wr()
1100 self.assertEqual(ob, dict[ob.arg])
1101 self.assertEqual(ob.arg, dict[ob.arg].arg)
1102 objects2.remove(ob)
1103 self.assertEqual(len(objects2), 0)
1104
Fred Drake0e540c32001-05-02 05:44:22 +00001105 def check_iters(self, dict):
1106 # item iterator:
1107 items = dict.items()
1108 for item in dict.iteritems():
1109 items.remove(item)
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001110 self.assertEqual(len(items), 0, "iteritems() did not touch all items")
Fred Drake0e540c32001-05-02 05:44:22 +00001111
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001112 # key iterator, via __iter__():
Fred Drake0e540c32001-05-02 05:44:22 +00001113 keys = dict.keys()
1114 for k in dict:
1115 keys.remove(k)
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001116 self.assertEqual(len(keys), 0, "__iter__() did not touch all keys")
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001117
1118 # key iterator, via iterkeys():
1119 keys = dict.keys()
1120 for k in dict.iterkeys():
1121 keys.remove(k)
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001122 self.assertEqual(len(keys), 0, "iterkeys() did not touch all keys")
Fred Drake0e540c32001-05-02 05:44:22 +00001123
1124 # value iterator:
1125 values = dict.values()
1126 for v in dict.itervalues():
1127 values.remove(v)
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001128 self.assertEqual(len(values), 0,
Fred Drakef425b1e2003-07-14 21:37:17 +00001129 "itervalues() did not touch all values")
Fred Drake0e540c32001-05-02 05:44:22 +00001130
Kristján Valur Jónsson222b2842013-12-05 10:03:45 +00001131 def check_weak_destroy_while_iterating(self, dict, objects, iter_name):
1132 n = len(dict)
1133 it = iter(getattr(dict, iter_name)())
1134 next(it) # Trigger internal iteration
1135 # Destroy an object
1136 del objects[-1]
1137 gc.collect() # just in case
1138 # We have removed either the first consumed object, or another one
1139 self.assertIn(len(list(it)), [len(objects), len(objects) - 1])
1140 del it
1141 # The removal has been committed
1142 self.assertEqual(len(dict), n - 1)
1143
1144 def check_weak_destroy_and_mutate_while_iterating(self, dict, testcontext):
1145 # Check that we can explicitly mutate the weak dict without
1146 # interfering with delayed removal.
1147 # `testcontext` should create an iterator, destroy one of the
1148 # weakref'ed objects and then return a new key/value pair corresponding
1149 # to the destroyed object.
1150 with testcontext() as (k, v):
1151 self.assertFalse(k in dict)
1152 with testcontext() as (k, v):
1153 self.assertRaises(KeyError, dict.__delitem__, k)
1154 self.assertFalse(k in dict)
1155 with testcontext() as (k, v):
1156 self.assertRaises(KeyError, dict.pop, k)
1157 self.assertFalse(k in dict)
1158 with testcontext() as (k, v):
1159 dict[k] = v
1160 self.assertEqual(dict[k], v)
1161 ddict = copy.copy(dict)
1162 with testcontext() as (k, v):
1163 dict.update(ddict)
1164 self.assertEqual(dict, ddict)
1165 with testcontext() as (k, v):
1166 dict.clear()
1167 self.assertEqual(len(dict), 0)
1168
1169 def test_weak_keys_destroy_while_iterating(self):
1170 # Issue #7105: iterators shouldn't crash when a key is implicitly removed
1171 dict, objects = self.make_weak_keyed_dict()
1172 self.check_weak_destroy_while_iterating(dict, objects, 'iterkeys')
1173 self.check_weak_destroy_while_iterating(dict, objects, 'iteritems')
1174 self.check_weak_destroy_while_iterating(dict, objects, 'itervalues')
1175 self.check_weak_destroy_while_iterating(dict, objects, 'iterkeyrefs')
1176 dict, objects = self.make_weak_keyed_dict()
1177 @contextlib.contextmanager
1178 def testcontext():
1179 try:
1180 it = iter(dict.iteritems())
1181 next(it)
1182 # Schedule a key/value for removal and recreate it
1183 v = objects.pop().arg
1184 gc.collect() # just in case
1185 yield Object(v), v
1186 finally:
1187 it = None # should commit all removals
Benjamin Peterson8a4448c2014-08-24 18:02:15 -05001188 gc.collect()
Kristján Valur Jónsson222b2842013-12-05 10:03:45 +00001189 self.check_weak_destroy_and_mutate_while_iterating(dict, testcontext)
1190
1191 def test_weak_values_destroy_while_iterating(self):
1192 # Issue #7105: iterators shouldn't crash when a key is implicitly removed
1193 dict, objects = self.make_weak_valued_dict()
1194 self.check_weak_destroy_while_iterating(dict, objects, 'iterkeys')
1195 self.check_weak_destroy_while_iterating(dict, objects, 'iteritems')
1196 self.check_weak_destroy_while_iterating(dict, objects, 'itervalues')
1197 self.check_weak_destroy_while_iterating(dict, objects, 'itervaluerefs')
1198 dict, objects = self.make_weak_valued_dict()
1199 @contextlib.contextmanager
1200 def testcontext():
1201 try:
1202 it = iter(dict.iteritems())
1203 next(it)
1204 # Schedule a key/value for removal and recreate it
1205 k = objects.pop().arg
1206 gc.collect() # just in case
1207 yield k, Object(k)
1208 finally:
1209 it = None # should commit all removals
Benjamin Peterson8a4448c2014-08-24 18:02:15 -05001210 gc.collect()
Kristján Valur Jónsson222b2842013-12-05 10:03:45 +00001211 self.check_weak_destroy_and_mutate_while_iterating(dict, testcontext)
1212
Guido van Rossum009afb72002-06-10 20:00:52 +00001213 def test_make_weak_keyed_dict_from_dict(self):
1214 o = Object(3)
1215 dict = weakref.WeakKeyDictionary({o:364})
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001216 self.assertEqual(dict[o], 364)
Guido van Rossum009afb72002-06-10 20:00:52 +00001217
1218 def test_make_weak_keyed_dict_from_weak_keyed_dict(self):
1219 o = Object(3)
1220 dict = weakref.WeakKeyDictionary({o:364})
1221 dict2 = weakref.WeakKeyDictionary(dict)
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001222 self.assertEqual(dict[o], 364)
Guido van Rossum009afb72002-06-10 20:00:52 +00001223
Fred Drake0e540c32001-05-02 05:44:22 +00001224 def make_weak_keyed_dict(self):
1225 dict = weakref.WeakKeyDictionary()
1226 objects = map(Object, range(self.COUNT))
1227 for o in objects:
1228 dict[o] = o.arg
1229 return dict, objects
1230
Serhiy Storchakaf522bbc2015-09-29 23:51:27 +03001231 def test_make_weak_valued_dict_misc(self):
1232 # errors
1233 self.assertRaises(TypeError, weakref.WeakValueDictionary.__init__)
1234 self.assertRaises(TypeError, weakref.WeakValueDictionary, {}, {})
1235 self.assertRaises(TypeError, weakref.WeakValueDictionary, (), ())
1236 # special keyword arguments
1237 o = Object(3)
1238 for kw in 'self', 'other', 'iterable':
1239 d = weakref.WeakValueDictionary(**{kw: o})
1240 self.assertEqual(list(d.keys()), [kw])
1241 self.assertEqual(d[kw], o)
1242
Fred Drake0e540c32001-05-02 05:44:22 +00001243 def make_weak_valued_dict(self):
1244 dict = weakref.WeakValueDictionary()
1245 objects = map(Object, range(self.COUNT))
1246 for o in objects:
1247 dict[o.arg] = o
1248 return dict, objects
1249
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001250 def check_popitem(self, klass, key1, value1, key2, value2):
1251 weakdict = klass()
1252 weakdict[key1] = value1
1253 weakdict[key2] = value2
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001254 self.assertEqual(len(weakdict), 2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001255 k, v = weakdict.popitem()
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001256 self.assertEqual(len(weakdict), 1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001257 if k is key1:
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001258 self.assertIs(v, value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001259 else:
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001260 self.assertIs(v, value2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001261 k, v = weakdict.popitem()
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001262 self.assertEqual(len(weakdict), 0)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001263 if k is key1:
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001264 self.assertIs(v, value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001265 else:
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001266 self.assertIs(v, value2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001267
1268 def test_weak_valued_dict_popitem(self):
1269 self.check_popitem(weakref.WeakValueDictionary,
1270 "key1", C(), "key2", C())
1271
1272 def test_weak_keyed_dict_popitem(self):
1273 self.check_popitem(weakref.WeakKeyDictionary,
1274 C(), "value 1", C(), "value 2")
1275
1276 def check_setdefault(self, klass, key, value1, value2):
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001277 self.assertIsNot(value1, value2,
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001278 "invalid test"
1279 " -- value parameters must be distinct objects")
1280 weakdict = klass()
1281 o = weakdict.setdefault(key, value1)
Florent Xicluna07627882010-03-21 01:14:24 +00001282 self.assertIs(o, value1)
1283 self.assertIn(key, weakdict)
1284 self.assertIs(weakdict.get(key), value1)
1285 self.assertIs(weakdict[key], value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001286
1287 o = weakdict.setdefault(key, value2)
Florent Xicluna07627882010-03-21 01:14:24 +00001288 self.assertIs(o, value1)
1289 self.assertIn(key, weakdict)
1290 self.assertIs(weakdict.get(key), value1)
1291 self.assertIs(weakdict[key], value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001292
1293 def test_weak_valued_dict_setdefault(self):
1294 self.check_setdefault(weakref.WeakValueDictionary,
1295 "key", C(), C())
1296
1297 def test_weak_keyed_dict_setdefault(self):
1298 self.check_setdefault(weakref.WeakKeyDictionary,
1299 C(), "value 1", "value 2")
1300
Fred Drakea0a4ab12001-04-16 17:37:27 +00001301 def check_update(self, klass, dict):
Fred Drake0e540c32001-05-02 05:44:22 +00001302 #
Florent Xicluna07627882010-03-21 01:14:24 +00001303 # This exercises d.update(), len(d), d.keys(), in d,
Fred Drake0e540c32001-05-02 05:44:22 +00001304 # d.get(), d[].
1305 #
Fred Drakea0a4ab12001-04-16 17:37:27 +00001306 weakdict = klass()
1307 weakdict.update(dict)
Florent Xicluna07627882010-03-21 01:14:24 +00001308 self.assertEqual(len(weakdict), len(dict))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001309 for k in weakdict.keys():
Florent Xicluna07627882010-03-21 01:14:24 +00001310 self.assertIn(k, dict,
Fred Drakea0a4ab12001-04-16 17:37:27 +00001311 "mysterious new key appeared in weak dict")
1312 v = dict.get(k)
Florent Xicluna07627882010-03-21 01:14:24 +00001313 self.assertIs(v, weakdict[k])
1314 self.assertIs(v, weakdict.get(k))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001315 for k in dict.keys():
Florent Xicluna07627882010-03-21 01:14:24 +00001316 self.assertIn(k, weakdict,
Fred Drakea0a4ab12001-04-16 17:37:27 +00001317 "original key disappeared in weak dict")
1318 v = dict[k]
Florent Xicluna07627882010-03-21 01:14:24 +00001319 self.assertIs(v, weakdict[k])
1320 self.assertIs(v, weakdict.get(k))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001321
1322 def test_weak_valued_dict_update(self):
1323 self.check_update(weakref.WeakValueDictionary,
1324 {1: C(), 'a': C(), C(): C()})
Serhiy Storchakaf522bbc2015-09-29 23:51:27 +03001325 # errors
1326 self.assertRaises(TypeError, weakref.WeakValueDictionary.update)
1327 d = weakref.WeakValueDictionary()
1328 self.assertRaises(TypeError, d.update, {}, {})
1329 self.assertRaises(TypeError, d.update, (), ())
1330 self.assertEqual(list(d.keys()), [])
1331 # special keyword arguments
1332 o = Object(3)
1333 for kw in 'self', 'dict', 'other', 'iterable':
1334 d = weakref.WeakValueDictionary()
1335 d.update(**{kw: o})
1336 self.assertEqual(list(d.keys()), [kw])
1337 self.assertEqual(d[kw], o)
Fred Drakea0a4ab12001-04-16 17:37:27 +00001338
1339 def test_weak_keyed_dict_update(self):
1340 self.check_update(weakref.WeakKeyDictionary,
1341 {C(): 1, C(): 2, C(): 3})
1342
Fred Drakeccc75622001-09-06 14:52:39 +00001343 def test_weak_keyed_delitem(self):
1344 d = weakref.WeakKeyDictionary()
1345 o1 = Object('1')
1346 o2 = Object('2')
1347 d[o1] = 'something'
1348 d[o2] = 'something'
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001349 self.assertEqual(len(d), 2)
Fred Drakeccc75622001-09-06 14:52:39 +00001350 del d[o1]
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001351 self.assertEqual(len(d), 1)
1352 self.assertEqual(d.keys(), [o2])
Fred Drakeccc75622001-09-06 14:52:39 +00001353
1354 def test_weak_valued_delitem(self):
1355 d = weakref.WeakValueDictionary()
1356 o1 = Object('1')
1357 o2 = Object('2')
1358 d['something'] = o1
1359 d['something else'] = o2
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001360 self.assertEqual(len(d), 2)
Fred Drakeccc75622001-09-06 14:52:39 +00001361 del d['something']
Serhiy Storchakaca626b12013-11-17 13:20:50 +02001362 self.assertEqual(len(d), 1)
1363 self.assertEqual(d.items(), [('something else', o2)])
Fred Drakeccc75622001-09-06 14:52:39 +00001364
Tim Peters886128f2003-05-25 01:45:11 +00001365 def test_weak_keyed_bad_delitem(self):
1366 d = weakref.WeakKeyDictionary()
1367 o = Object('1')
1368 # An attempt to delete an object that isn't there should raise
Tim Peters50d8b8b2003-05-25 17:44:31 +00001369 # KeyError. It didn't before 2.3.
Tim Peters886128f2003-05-25 01:45:11 +00001370 self.assertRaises(KeyError, d.__delitem__, o)
Tim Peters50d8b8b2003-05-25 17:44:31 +00001371 self.assertRaises(KeyError, d.__getitem__, o)
1372
1373 # If a key isn't of a weakly referencable type, __getitem__ and
1374 # __setitem__ raise TypeError. __delitem__ should too.
1375 self.assertRaises(TypeError, d.__delitem__, 13)
1376 self.assertRaises(TypeError, d.__getitem__, 13)
1377 self.assertRaises(TypeError, d.__setitem__, 13, 13)
Tim Peters886128f2003-05-25 01:45:11 +00001378
1379 def test_weak_keyed_cascading_deletes(self):
1380 # SF bug 742860. For some reason, before 2.3 __delitem__ iterated
1381 # over the keys via self.data.iterkeys(). If things vanished from
1382 # the dict during this (or got added), that caused a RuntimeError.
1383
1384 d = weakref.WeakKeyDictionary()
1385 mutate = False
1386
1387 class C(object):
1388 def __init__(self, i):
1389 self.value = i
1390 def __hash__(self):
1391 return hash(self.value)
1392 def __eq__(self, other):
1393 if mutate:
1394 # Side effect that mutates the dict, by removing the
1395 # last strong reference to a key.
1396 del objs[-1]
1397 return self.value == other.value
1398
1399 objs = [C(i) for i in range(4)]
1400 for o in objs:
1401 d[o] = o.value
1402 del o # now the only strong references to keys are in objs
1403 # Find the order in which iterkeys sees the keys.
1404 objs = d.keys()
1405 # Reverse it, so that the iteration implementation of __delitem__
1406 # has to keep looping to find the first object we delete.
1407 objs.reverse()
Tim Peters50d8b8b2003-05-25 17:44:31 +00001408
Tim Peters886128f2003-05-25 01:45:11 +00001409 # Turn on mutation in C.__eq__. The first time thru the loop,
1410 # under the iterkeys() business the first comparison will delete
1411 # the last item iterkeys() would see, and that causes a
1412 # RuntimeError: dictionary changed size during iteration
1413 # when the iterkeys() loop goes around to try comparing the next
Tim Peters50d8b8b2003-05-25 17:44:31 +00001414 # key. After this was fixed, it just deletes the last object *our*
Tim Peters886128f2003-05-25 01:45:11 +00001415 # "for o in obj" loop would have gotten to.
1416 mutate = True
1417 count = 0
1418 for o in objs:
1419 count += 1
1420 del d[o]
1421 self.assertEqual(len(d), 0)
1422 self.assertEqual(count, 2)
1423
Antoine Pitrou805f2832016-12-19 11:12:58 +01001424 def test_threaded_weak_valued_setdefault(self):
1425 d = weakref.WeakValueDictionary()
1426 with collect_in_thread():
1427 for i in range(50000):
1428 x = d.setdefault(10, RefCycle())
1429 self.assertIsNot(x, None) # we never put None in there!
1430 del x
1431
1432 def test_threaded_weak_valued_pop(self):
1433 d = weakref.WeakValueDictionary()
1434 with collect_in_thread():
1435 for i in range(50000):
1436 d[10] = RefCycle()
1437 x = d.pop(10, 10)
1438 self.assertIsNot(x, None) # we never put None in there!
1439
Antoine Pitrouf939b3c2016-12-27 15:08:27 +01001440 def test_threaded_weak_valued_consistency(self):
1441 # Issue #28427: old keys should not remove new values from
1442 # WeakValueDictionary when collecting from another thread.
1443 d = weakref.WeakValueDictionary()
1444 with collect_in_thread():
1445 for i in range(200000):
1446 o = RefCycle()
1447 d[10] = o
1448 # o is still alive, so the dict can't be empty
1449 self.assertEqual(len(d), 1)
1450 o = None # lose ref
1451
Antoine Pitrou805f2832016-12-19 11:12:58 +01001452
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001453from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001454
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001455class WeakValueDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +00001456 """Check that WeakValueDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001457 __ref = {"key1":Object(1), "key2":Object(2), "key3":Object(3)}
Walter Dörwald118f9312004-06-02 18:42:25 +00001458 type2test = weakref.WeakValueDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001459 def _reference(self):
1460 return self.__ref.copy()
1461
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001462class WeakKeyDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +00001463 """Check that WeakKeyDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001464 __ref = {Object("key1"):1, Object("key2"):2, Object("key3"):3}
Walter Dörwald118f9312004-06-02 18:42:25 +00001465 type2test = weakref.WeakKeyDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001466 def _reference(self):
1467 return self.__ref.copy()
Martin v. Löwis5e163332001-02-27 18:36:56 +00001468
Georg Brandl88659b02008-05-20 08:40:43 +00001469libreftest = """ Doctest for examples in the library reference: weakref.rst
Georg Brandl9a65d582005-07-02 19:07:30 +00001470
1471>>> import weakref
1472>>> class Dict(dict):
1473... pass
1474...
1475>>> obj = Dict(red=1, green=2, blue=3) # this object is weak referencable
1476>>> r = weakref.ref(obj)
Armin Rigoa3f09272006-05-28 19:13:17 +00001477>>> print r() is obj
1478True
Georg Brandl9a65d582005-07-02 19:07:30 +00001479
1480>>> import weakref
1481>>> class Object:
1482... pass
1483...
1484>>> o = Object()
1485>>> r = weakref.ref(o)
1486>>> o2 = r()
1487>>> o is o2
1488True
1489>>> del o, o2
1490>>> print r()
1491None
1492
1493>>> import weakref
1494>>> class ExtendedRef(weakref.ref):
1495... def __init__(self, ob, callback=None, **annotations):
1496... super(ExtendedRef, self).__init__(ob, callback)
1497... self.__counter = 0
1498... for k, v in annotations.iteritems():
1499... setattr(self, k, v)
1500... def __call__(self):
1501... '''Return a pair containing the referent and the number of
1502... times the reference has been called.
1503... '''
1504... ob = super(ExtendedRef, self).__call__()
1505... if ob is not None:
1506... self.__counter += 1
1507... ob = (ob, self.__counter)
1508... return ob
1509...
1510>>> class A: # not in docs from here, just testing the ExtendedRef
1511... pass
1512...
1513>>> a = A()
1514>>> r = ExtendedRef(a, foo=1, bar="baz")
1515>>> r.foo
15161
1517>>> r.bar
1518'baz'
1519>>> r()[1]
15201
1521>>> r()[1]
15222
1523>>> r()[0] is a
1524True
1525
1526
1527>>> import weakref
1528>>> _id2obj_dict = weakref.WeakValueDictionary()
1529>>> def remember(obj):
1530... oid = id(obj)
1531... _id2obj_dict[oid] = obj
1532... return oid
1533...
1534>>> def id2obj(oid):
1535... return _id2obj_dict[oid]
1536...
1537>>> a = A() # from here, just testing
1538>>> a_id = remember(a)
1539>>> id2obj(a_id) is a
1540True
1541>>> del a
1542>>> try:
1543... id2obj(a_id)
1544... except KeyError:
1545... print 'OK'
1546... else:
1547... print 'WeakValueDictionary error'
1548OK
1549
1550"""
1551
1552__test__ = {'libreftest' : libreftest}
1553
Fred Drake2e2be372001-09-20 21:33:42 +00001554def test_main():
Walter Dörwald21d3a322003-05-01 17:45:56 +00001555 test_support.run_unittest(
1556 ReferencesTestCase,
1557 MappingTestCase,
1558 WeakValueDictionaryTestCase,
Fred Drakef425b1e2003-07-14 21:37:17 +00001559 WeakKeyDictionaryTestCase,
Amaury Forgeot d'Arca8919fe2008-06-16 19:12:42 +00001560 SubclassableWeakrefTestCase,
Fred Drakef425b1e2003-07-14 21:37:17 +00001561 )
Georg Brandl9a65d582005-07-02 19:07:30 +00001562 test_support.run_doctest(sys.modules[__name__])
Fred Drake2e2be372001-09-20 21:33:42 +00001563
1564
1565if __name__ == "__main__":
1566 test_main()