blob: 7de7b77d094c48798b86146dc5f52fad04dd9246 [file] [log] [blame]
Fred Drakebc875f52004-02-04 23:14:14 +00001import gc
Fred Drake41deb1e2001-02-01 05:27:45 +00002import sys
Fred Drakeb0fefc52001-03-23 04:22:45 +00003import unittest
Raymond Hettinger53dbe392008-02-12 20:03:09 +00004import collections
Fred Drake41deb1e2001-02-01 05:27:45 +00005import weakref
6
Barry Warsaw04f357c2002-07-23 19:04:11 +00007from test import test_support
Fred Drake41deb1e2001-02-01 05:27:45 +00008
Thomas Woutersb2137042007-02-01 18:02:27 +00009# Used in ReferencesTestCase.test_ref_created_during_del() .
10ref_from_del = None
Fred Drake41deb1e2001-02-01 05:27:45 +000011
12class C:
Fred Drakeb0fefc52001-03-23 04:22:45 +000013 def method(self):
14 pass
Fred Drake41deb1e2001-02-01 05:27:45 +000015
16
Fred Drakeb0fefc52001-03-23 04:22:45 +000017class Callable:
18 bar = None
Fred Drake41deb1e2001-02-01 05:27:45 +000019
Fred Drakeb0fefc52001-03-23 04:22:45 +000020 def __call__(self, x):
21 self.bar = x
Fred Drake41deb1e2001-02-01 05:27:45 +000022
23
Fred Drakeb0fefc52001-03-23 04:22:45 +000024def create_function():
25 def f(): pass
26 return f
27
28def create_bound_method():
29 return C().method
30
Fred Drake41deb1e2001-02-01 05:27:45 +000031
Fred Drakeb0fefc52001-03-23 04:22:45 +000032class TestBase(unittest.TestCase):
33
34 def setUp(self):
35 self.cbcalled = 0
36
37 def callback(self, ref):
38 self.cbcalled += 1
Fred Drake41deb1e2001-02-01 05:27:45 +000039
40
Fred Drakeb0fefc52001-03-23 04:22:45 +000041class ReferencesTestCase(TestBase):
Fred Drake41deb1e2001-02-01 05:27:45 +000042
Fred Drakeb0fefc52001-03-23 04:22:45 +000043 def test_basic_ref(self):
44 self.check_basic_ref(C)
45 self.check_basic_ref(create_function)
46 self.check_basic_ref(create_bound_method)
Fred Drake41deb1e2001-02-01 05:27:45 +000047
Fred Drake43735da2002-04-11 03:59:42 +000048 # Just make sure the tp_repr handler doesn't raise an exception.
49 # Live reference:
50 o = C()
51 wr = weakref.ref(o)
Brett Cannon0b70cca2006-08-25 02:59:59 +000052 repr(wr)
Fred Drake43735da2002-04-11 03:59:42 +000053 # Dead reference:
54 del o
Brett Cannon0b70cca2006-08-25 02:59:59 +000055 repr(wr)
Fred Drake43735da2002-04-11 03:59:42 +000056
Fred Drakeb0fefc52001-03-23 04:22:45 +000057 def test_basic_callback(self):
58 self.check_basic_callback(C)
59 self.check_basic_callback(create_function)
60 self.check_basic_callback(create_bound_method)
Fred Drake41deb1e2001-02-01 05:27:45 +000061
Fred Drakeb0fefc52001-03-23 04:22:45 +000062 def test_multiple_callbacks(self):
63 o = C()
64 ref1 = weakref.ref(o, self.callback)
65 ref2 = weakref.ref(o, self.callback)
66 del o
67 self.assert_(ref1() is None,
68 "expected reference to be invalidated")
69 self.assert_(ref2() is None,
70 "expected reference to be invalidated")
71 self.assert_(self.cbcalled == 2,
72 "callback not called the right number of times")
Fred Drake41deb1e2001-02-01 05:27:45 +000073
Fred Drake705088e2001-04-13 17:18:15 +000074 def test_multiple_selfref_callbacks(self):
Guido van Rossum9eee5542002-08-22 20:21:30 +000075 # Make sure all references are invalidated before callbacks are called
Fred Drake705088e2001-04-13 17:18:15 +000076 #
77 # What's important here is that we're using the first
78 # reference in the callback invoked on the second reference
79 # (the most recently created ref is cleaned up first). This
80 # tests that all references to the object are invalidated
81 # before any of the callbacks are invoked, so that we only
82 # have one invocation of _weakref.c:cleanup_helper() active
83 # for a particular object at a time.
84 #
85 def callback(object, self=self):
86 self.ref()
87 c = C()
88 self.ref = weakref.ref(c, callback)
89 ref1 = weakref.ref(c, callback)
90 del c
91
Fred Drakeb0fefc52001-03-23 04:22:45 +000092 def test_proxy_ref(self):
93 o = C()
94 o.bar = 1
95 ref1 = weakref.proxy(o, self.callback)
96 ref2 = weakref.proxy(o, self.callback)
97 del o
Fred Drake41deb1e2001-02-01 05:27:45 +000098
Fred Drakeb0fefc52001-03-23 04:22:45 +000099 def check(proxy):
100 proxy.bar
Fred Drake41deb1e2001-02-01 05:27:45 +0000101
Neal Norwitz2633c692007-02-26 22:22:47 +0000102 self.assertRaises(ReferenceError, check, ref1)
103 self.assertRaises(ReferenceError, check, ref2)
104 self.assertRaises(ReferenceError, bool, weakref.proxy(C()))
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000105 self.assertEqual(self.cbcalled, 2)
Fred Drake41deb1e2001-02-01 05:27:45 +0000106
Fred Drakeb0fefc52001-03-23 04:22:45 +0000107 def check_basic_ref(self, factory):
108 o = factory()
109 ref = weakref.ref(o)
110 self.assert_(ref() is not None,
111 "weak reference to live object should be live")
112 o2 = ref()
113 self.assert_(o is o2,
114 "<ref>() should return original object if live")
Fred Drake41deb1e2001-02-01 05:27:45 +0000115
Fred Drakeb0fefc52001-03-23 04:22:45 +0000116 def check_basic_callback(self, factory):
117 self.cbcalled = 0
118 o = factory()
119 ref = weakref.ref(o, self.callback)
120 del o
Fred Drake705088e2001-04-13 17:18:15 +0000121 self.assert_(self.cbcalled == 1,
122 "callback did not properly set 'cbcalled'")
123 self.assert_(ref() is None,
124 "ref2 should be dead after deleting object reference")
Fred Drake41deb1e2001-02-01 05:27:45 +0000125
Fred Drakeb0fefc52001-03-23 04:22:45 +0000126 def test_ref_reuse(self):
127 o = C()
128 ref1 = weakref.ref(o)
129 # create a proxy to make sure that there's an intervening creation
130 # between these two; it should make no difference
131 proxy = weakref.proxy(o)
132 ref2 = weakref.ref(o)
133 self.assert_(ref1 is ref2,
134 "reference object w/out callback should be re-used")
Fred Drake41deb1e2001-02-01 05:27:45 +0000135
Fred Drakeb0fefc52001-03-23 04:22:45 +0000136 o = C()
137 proxy = weakref.proxy(o)
138 ref1 = weakref.ref(o)
139 ref2 = weakref.ref(o)
140 self.assert_(ref1 is ref2,
141 "reference object w/out callback should be re-used")
142 self.assert_(weakref.getweakrefcount(o) == 2,
143 "wrong weak ref count for object")
144 del proxy
145 self.assert_(weakref.getweakrefcount(o) == 1,
146 "wrong weak ref count for object after deleting proxy")
Fred Drake41deb1e2001-02-01 05:27:45 +0000147
Fred Drakeb0fefc52001-03-23 04:22:45 +0000148 def test_proxy_reuse(self):
149 o = C()
150 proxy1 = weakref.proxy(o)
151 ref = weakref.ref(o)
152 proxy2 = weakref.proxy(o)
153 self.assert_(proxy1 is proxy2,
154 "proxy object w/out callback should have been re-used")
155
156 def test_basic_proxy(self):
157 o = C()
158 self.check_proxy(o, weakref.proxy(o))
159
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000160 L = collections.UserList()
Fred Drake5935ff02001-12-19 16:54:23 +0000161 p = weakref.proxy(L)
162 self.failIf(p, "proxy for empty UserList should be false")
163 p.append(12)
164 self.assertEqual(len(L), 1)
165 self.failUnless(p, "proxy for non-empty UserList should be true")
166 p[:] = [2, 3]
167 self.assertEqual(len(L), 2)
168 self.assertEqual(len(p), 2)
Fred Drakef425b1e2003-07-14 21:37:17 +0000169 self.failUnless(3 in p,
170 "proxy didn't support __contains__() properly")
Fred Drake5935ff02001-12-19 16:54:23 +0000171 p[1] = 5
172 self.assertEqual(L[1], 5)
173 self.assertEqual(p[1], 5)
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000174 L2 = collections.UserList(L)
Fred Drake5935ff02001-12-19 16:54:23 +0000175 p2 = weakref.proxy(L2)
176 self.assertEqual(p, p2)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000177 ## self.assertEqual(repr(L2), repr(p2))
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000178 L3 = collections.UserList(range(10))
Fred Drake43735da2002-04-11 03:59:42 +0000179 p3 = weakref.proxy(L3)
180 self.assertEqual(L3[:], p3[:])
181 self.assertEqual(L3[5:], p3[5:])
182 self.assertEqual(L3[:5], p3[:5])
183 self.assertEqual(L3[2:5], p3[2:5])
Fred Drake5935ff02001-12-19 16:54:23 +0000184
Fred Drakeea2adc92004-02-03 19:56:46 +0000185 # The PyWeakref_* C API is documented as allowing either NULL or
186 # None as the value for the callback, where either means "no
187 # callback". The "no callback" ref and proxy objects are supposed
188 # to be shared so long as they exist by all callers so long as
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000189 # they are active. In Python 2.3.3 and earlier, this guarantee
Fred Drakeea2adc92004-02-03 19:56:46 +0000190 # was not honored, and was broken in different ways for
191 # PyWeakref_NewRef() and PyWeakref_NewProxy(). (Two tests.)
192
193 def test_shared_ref_without_callback(self):
194 self.check_shared_without_callback(weakref.ref)
195
196 def test_shared_proxy_without_callback(self):
197 self.check_shared_without_callback(weakref.proxy)
198
199 def check_shared_without_callback(self, makeref):
200 o = Object(1)
201 p1 = makeref(o, None)
202 p2 = makeref(o, None)
203 self.assert_(p1 is p2, "both callbacks were None in the C API")
204 del p1, p2
205 p1 = makeref(o)
206 p2 = makeref(o, None)
207 self.assert_(p1 is p2, "callbacks were NULL, None in the C API")
208 del p1, p2
209 p1 = makeref(o)
210 p2 = makeref(o)
211 self.assert_(p1 is p2, "both callbacks were NULL in the C API")
212 del p1, p2
213 p1 = makeref(o, None)
214 p2 = makeref(o)
215 self.assert_(p1 is p2, "callbacks were None, NULL in the C API")
216
Fred Drakeb0fefc52001-03-23 04:22:45 +0000217 def test_callable_proxy(self):
218 o = Callable()
219 ref1 = weakref.proxy(o)
220
221 self.check_proxy(o, ref1)
222
223 self.assert_(type(ref1) is weakref.CallableProxyType,
224 "proxy is not of callable type")
225 ref1('twinkies!')
226 self.assert_(o.bar == 'twinkies!',
227 "call through proxy not passed through to original")
Fred Drake3bb4d212001-10-18 19:28:29 +0000228 ref1(x='Splat.')
229 self.assert_(o.bar == 'Splat.',
230 "call through proxy not passed through to original")
Fred Drakeb0fefc52001-03-23 04:22:45 +0000231
232 # expect due to too few args
233 self.assertRaises(TypeError, ref1)
234
235 # expect due to too many args
236 self.assertRaises(TypeError, ref1, 1, 2, 3)
237
238 def check_proxy(self, o, proxy):
239 o.foo = 1
240 self.assert_(proxy.foo == 1,
241 "proxy does not reflect attribute addition")
242 o.foo = 2
243 self.assert_(proxy.foo == 2,
244 "proxy does not reflect attribute modification")
245 del o.foo
246 self.assert_(not hasattr(proxy, 'foo'),
247 "proxy does not reflect attribute removal")
248
249 proxy.foo = 1
250 self.assert_(o.foo == 1,
251 "object does not reflect attribute addition via proxy")
252 proxy.foo = 2
253 self.assert_(
254 o.foo == 2,
255 "object does not reflect attribute modification via proxy")
256 del proxy.foo
257 self.assert_(not hasattr(o, 'foo'),
258 "object does not reflect attribute removal via proxy")
259
Raymond Hettingerd693a812003-06-30 04:18:48 +0000260 def test_proxy_deletion(self):
261 # Test clearing of SF bug #762891
262 class Foo:
263 result = None
264 def __delitem__(self, accessor):
265 self.result = accessor
266 g = Foo()
267 f = weakref.proxy(g)
268 del f[0]
269 self.assertEqual(f.result, 0)
270
Raymond Hettingere6c470f2005-03-27 03:04:54 +0000271 def test_proxy_bool(self):
272 # Test clearing of SF bug #1170766
273 class List(list): pass
274 lyst = List()
275 self.assertEqual(bool(weakref.proxy(lyst)), bool(lyst))
276
Fred Drakeb0fefc52001-03-23 04:22:45 +0000277 def test_getweakrefcount(self):
278 o = C()
279 ref1 = weakref.ref(o)
280 ref2 = weakref.ref(o, self.callback)
281 self.assert_(weakref.getweakrefcount(o) == 2,
282 "got wrong number of weak reference objects")
283
284 proxy1 = weakref.proxy(o)
285 proxy2 = weakref.proxy(o, self.callback)
286 self.assert_(weakref.getweakrefcount(o) == 4,
287 "got wrong number of weak reference objects")
288
Fred Drakeea2adc92004-02-03 19:56:46 +0000289 del ref1, ref2, proxy1, proxy2
290 self.assert_(weakref.getweakrefcount(o) == 0,
291 "weak reference objects not unlinked from"
292 " referent when discarded.")
293
Walter Dörwaldb167b042003-12-11 12:34:05 +0000294 # assumes ints do not support weakrefs
295 self.assert_(weakref.getweakrefcount(1) == 0,
296 "got wrong number of weak reference objects for int")
297
Fred Drakeb0fefc52001-03-23 04:22:45 +0000298 def test_getweakrefs(self):
299 o = C()
300 ref1 = weakref.ref(o, self.callback)
301 ref2 = weakref.ref(o, self.callback)
302 del ref1
303 self.assert_(weakref.getweakrefs(o) == [ref2],
304 "list of refs does not match")
305
306 o = C()
307 ref1 = weakref.ref(o, self.callback)
308 ref2 = weakref.ref(o, self.callback)
309 del ref2
310 self.assert_(weakref.getweakrefs(o) == [ref1],
311 "list of refs does not match")
312
Fred Drakeea2adc92004-02-03 19:56:46 +0000313 del ref1
314 self.assert_(weakref.getweakrefs(o) == [],
315 "list of refs not cleared")
316
Walter Dörwaldb167b042003-12-11 12:34:05 +0000317 # assumes ints do not support weakrefs
318 self.assert_(weakref.getweakrefs(1) == [],
319 "list of refs does not match for int")
320
Fred Drake39c27f12001-10-18 18:06:05 +0000321 def test_newstyle_number_ops(self):
322 class F(float):
323 pass
324 f = F(2.0)
325 p = weakref.proxy(f)
326 self.assert_(p + 1.0 == 3.0)
327 self.assert_(1.0 + p == 3.0) # this used to SEGV
328
Fred Drake2a64f462001-12-10 23:46:02 +0000329 def test_callbacks_protected(self):
Guido van Rossum9eee5542002-08-22 20:21:30 +0000330 # Callbacks protected from already-set exceptions?
Fred Drake2a64f462001-12-10 23:46:02 +0000331 # Regression test for SF bug #478534.
332 class BogusError(Exception):
333 pass
334 data = {}
335 def remove(k):
336 del data[k]
337 def encapsulate():
338 f = lambda : ()
339 data[weakref.ref(f, remove)] = None
340 raise BogusError
341 try:
342 encapsulate()
343 except BogusError:
344 pass
345 else:
346 self.fail("exception not properly restored")
347 try:
348 encapsulate()
349 except BogusError:
350 pass
351 else:
352 self.fail("exception not properly restored")
353
Tim Petersadd09b42003-11-12 20:43:28 +0000354 def test_sf_bug_840829(self):
355 # "weakref callbacks and gc corrupt memory"
356 # subtype_dealloc erroneously exposed a new-style instance
357 # already in the process of getting deallocated to gc,
358 # causing double-deallocation if the instance had a weakref
359 # callback that triggered gc.
360 # If the bug exists, there probably won't be an obvious symptom
361 # in a release build. In a debug build, a segfault will occur
362 # when the second attempt to remove the instance from the "list
363 # of all objects" occurs.
364
365 import gc
366
367 class C(object):
368 pass
369
370 c = C()
371 wr = weakref.ref(c, lambda ignore: gc.collect())
372 del c
373
Tim Petersf7f9e992003-11-13 21:59:32 +0000374 # There endeth the first part. It gets worse.
375 del wr
376
377 c1 = C()
378 c1.i = C()
379 wr = weakref.ref(c1.i, lambda ignore: gc.collect())
380
381 c2 = C()
382 c2.c1 = c1
383 del c1 # still alive because c2 points to it
384
385 # Now when subtype_dealloc gets called on c2, it's not enough just
386 # that c2 is immune from gc while the weakref callbacks associated
387 # with c2 execute (there are none in this 2nd half of the test, btw).
388 # subtype_dealloc goes on to call the base classes' deallocs too,
389 # so any gc triggered by weakref callbacks associated with anything
390 # torn down by a base class dealloc can also trigger double
391 # deallocation of c2.
392 del c2
Fred Drake41deb1e2001-02-01 05:27:45 +0000393
Tim Peters403a2032003-11-20 21:21:46 +0000394 def test_callback_in_cycle_1(self):
395 import gc
396
397 class J(object):
398 pass
399
400 class II(object):
401 def acallback(self, ignore):
402 self.J
403
404 I = II()
405 I.J = J
406 I.wr = weakref.ref(J, I.acallback)
407
408 # Now J and II are each in a self-cycle (as all new-style class
409 # objects are, since their __mro__ points back to them). I holds
410 # both a weak reference (I.wr) and a strong reference (I.J) to class
411 # J. I is also in a cycle (I.wr points to a weakref that references
412 # I.acallback). When we del these three, they all become trash, but
413 # the cycles prevent any of them from getting cleaned up immediately.
414 # Instead they have to wait for cyclic gc to deduce that they're
415 # trash.
416 #
417 # gc used to call tp_clear on all of them, and the order in which
418 # it does that is pretty accidental. The exact order in which we
419 # built up these things manages to provoke gc into running tp_clear
420 # in just the right order (I last). Calling tp_clear on II leaves
421 # behind an insane class object (its __mro__ becomes NULL). Calling
422 # tp_clear on J breaks its self-cycle, but J doesn't get deleted
423 # just then because of the strong reference from I.J. Calling
424 # tp_clear on I starts to clear I's __dict__, and just happens to
425 # clear I.J first -- I.wr is still intact. That removes the last
426 # reference to J, which triggers the weakref callback. The callback
427 # tries to do "self.J", and instances of new-style classes look up
428 # attributes ("J") in the class dict first. The class (II) wants to
429 # search II.__mro__, but that's NULL. The result was a segfault in
430 # a release build, and an assert failure in a debug build.
431 del I, J, II
432 gc.collect()
433
434 def test_callback_in_cycle_2(self):
435 import gc
436
437 # This is just like test_callback_in_cycle_1, except that II is an
438 # old-style class. The symptom is different then: an instance of an
439 # old-style class looks in its own __dict__ first. 'J' happens to
440 # get cleared from I.__dict__ before 'wr', and 'J' was never in II's
441 # __dict__, so the attribute isn't found. The difference is that
442 # the old-style II doesn't have a NULL __mro__ (it doesn't have any
443 # __mro__), so no segfault occurs. Instead it got:
444 # test_callback_in_cycle_2 (__main__.ReferencesTestCase) ...
445 # Exception exceptions.AttributeError:
446 # "II instance has no attribute 'J'" in <bound method II.acallback
447 # of <?.II instance at 0x00B9B4B8>> ignored
448
449 class J(object):
450 pass
451
452 class II:
453 def acallback(self, ignore):
454 self.J
455
456 I = II()
457 I.J = J
458 I.wr = weakref.ref(J, I.acallback)
459
460 del I, J, II
461 gc.collect()
462
463 def test_callback_in_cycle_3(self):
464 import gc
465
466 # This one broke the first patch that fixed the last two. In this
467 # case, the objects reachable from the callback aren't also reachable
468 # from the object (c1) *triggering* the callback: you can get to
469 # c1 from c2, but not vice-versa. The result was that c2's __dict__
470 # got tp_clear'ed by the time the c2.cb callback got invoked.
471
472 class C:
473 def cb(self, ignore):
474 self.me
475 self.c1
476 self.wr
477
478 c1, c2 = C(), C()
479
480 c2.me = c2
481 c2.c1 = c1
482 c2.wr = weakref.ref(c1, c2.cb)
483
484 del c1, c2
485 gc.collect()
486
487 def test_callback_in_cycle_4(self):
488 import gc
489
490 # Like test_callback_in_cycle_3, except c2 and c1 have different
491 # classes. c2's class (C) isn't reachable from c1 then, so protecting
492 # objects reachable from the dying object (c1) isn't enough to stop
493 # c2's class (C) from getting tp_clear'ed before c2.cb is invoked.
494 # The result was a segfault (C.__mro__ was NULL when the callback
495 # tried to look up self.me).
496
497 class C(object):
498 def cb(self, ignore):
499 self.me
500 self.c1
501 self.wr
502
503 class D:
504 pass
505
506 c1, c2 = D(), C()
507
508 c2.me = c2
509 c2.c1 = c1
510 c2.wr = weakref.ref(c1, c2.cb)
511
512 del c1, c2, C, D
513 gc.collect()
514
515 def test_callback_in_cycle_resurrection(self):
516 import gc
517
518 # Do something nasty in a weakref callback: resurrect objects
519 # from dead cycles. For this to be attempted, the weakref and
520 # its callback must also be part of the cyclic trash (else the
521 # objects reachable via the callback couldn't be in cyclic trash
522 # to begin with -- the callback would act like an external root).
523 # But gc clears trash weakrefs with callbacks early now, which
524 # disables the callbacks, so the callbacks shouldn't get called
525 # at all (and so nothing actually gets resurrected).
526
527 alist = []
528 class C(object):
529 def __init__(self, value):
530 self.attribute = value
531
532 def acallback(self, ignore):
533 alist.append(self.c)
534
535 c1, c2 = C(1), C(2)
536 c1.c = c2
537 c2.c = c1
538 c1.wr = weakref.ref(c2, c1.acallback)
539 c2.wr = weakref.ref(c1, c2.acallback)
540
541 def C_went_away(ignore):
542 alist.append("C went away")
543 wr = weakref.ref(C, C_went_away)
544
545 del c1, c2, C # make them all trash
546 self.assertEqual(alist, []) # del isn't enough to reclaim anything
547
548 gc.collect()
549 # c1.wr and c2.wr were part of the cyclic trash, so should have
550 # been cleared without their callbacks executing. OTOH, the weakref
551 # to C is bound to a function local (wr), and wasn't trash, so that
552 # callback should have been invoked when C went away.
553 self.assertEqual(alist, ["C went away"])
554 # The remaining weakref should be dead now (its callback ran).
555 self.assertEqual(wr(), None)
556
557 del alist[:]
558 gc.collect()
559 self.assertEqual(alist, [])
560
561 def test_callbacks_on_callback(self):
562 import gc
563
564 # Set up weakref callbacks *on* weakref callbacks.
565 alist = []
566 def safe_callback(ignore):
567 alist.append("safe_callback called")
568
569 class C(object):
570 def cb(self, ignore):
571 alist.append("cb called")
572
573 c, d = C(), C()
574 c.other = d
575 d.other = c
576 callback = c.cb
577 c.wr = weakref.ref(d, callback) # this won't trigger
578 d.wr = weakref.ref(callback, d.cb) # ditto
579 external_wr = weakref.ref(callback, safe_callback) # but this will
580 self.assert_(external_wr() is callback)
581
582 # The weakrefs attached to c and d should get cleared, so that
583 # C.cb is never called. But external_wr isn't part of the cyclic
584 # trash, and no cyclic trash is reachable from it, so safe_callback
585 # should get invoked when the bound method object callback (c.cb)
586 # -- which is itself a callback, and also part of the cyclic trash --
587 # gets reclaimed at the end of gc.
588
589 del callback, c, d, C
590 self.assertEqual(alist, []) # del isn't enough to clean up cycles
591 gc.collect()
592 self.assertEqual(alist, ["safe_callback called"])
593 self.assertEqual(external_wr(), None)
594
595 del alist[:]
596 gc.collect()
597 self.assertEqual(alist, [])
598
Fred Drakebc875f52004-02-04 23:14:14 +0000599 def test_gc_during_ref_creation(self):
600 self.check_gc_during_creation(weakref.ref)
601
602 def test_gc_during_proxy_creation(self):
603 self.check_gc_during_creation(weakref.proxy)
604
605 def check_gc_during_creation(self, makeref):
606 thresholds = gc.get_threshold()
607 gc.set_threshold(1, 1, 1)
608 gc.collect()
Fred Drake55cf4342004-02-13 19:21:57 +0000609 class A:
610 pass
Fred Drakebc875f52004-02-04 23:14:14 +0000611
612 def callback(*args):
613 pass
614
Fred Drake55cf4342004-02-13 19:21:57 +0000615 referenced = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000616
Fred Drake55cf4342004-02-13 19:21:57 +0000617 a = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000618 a.a = a
619 a.wr = makeref(referenced)
620
621 try:
622 # now make sure the object and the ref get labeled as
623 # cyclic trash:
Fred Drake55cf4342004-02-13 19:21:57 +0000624 a = A()
625 weakref.ref(referenced, callback)
Fred Drakebc875f52004-02-04 23:14:14 +0000626
627 finally:
628 gc.set_threshold(*thresholds)
629
Thomas Woutersb2137042007-02-01 18:02:27 +0000630 def test_ref_created_during_del(self):
631 # Bug #1377858
632 # A weakref created in an object's __del__() would crash the
633 # interpreter when the weakref was cleaned up since it would refer to
634 # non-existent memory. This test should not segfault the interpreter.
635 class Target(object):
636 def __del__(self):
637 global ref_from_del
638 ref_from_del = weakref.ref(self)
639
640 w = Target()
641
Fred Drake0a4dd392004-07-02 18:57:45 +0000642
643class SubclassableWeakrefTestCase(unittest.TestCase):
644
645 def test_subclass_refs(self):
646 class MyRef(weakref.ref):
647 def __init__(self, ob, callback=None, value=42):
648 self.value = value
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000649 super().__init__(ob, callback)
Fred Drake0a4dd392004-07-02 18:57:45 +0000650 def __call__(self):
651 self.called = True
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000652 return super().__call__()
Fred Drake0a4dd392004-07-02 18:57:45 +0000653 o = Object("foo")
654 mr = MyRef(o, value=24)
655 self.assert_(mr() is o)
656 self.assert_(mr.called)
657 self.assertEqual(mr.value, 24)
658 del o
659 self.assert_(mr() is None)
660 self.assert_(mr.called)
661
662 def test_subclass_refs_dont_replace_standard_refs(self):
663 class MyRef(weakref.ref):
664 pass
665 o = Object(42)
666 r1 = MyRef(o)
667 r2 = weakref.ref(o)
668 self.assert_(r1 is not r2)
669 self.assertEqual(weakref.getweakrefs(o), [r2, r1])
670 self.assertEqual(weakref.getweakrefcount(o), 2)
671 r3 = MyRef(o)
672 self.assertEqual(weakref.getweakrefcount(o), 3)
673 refs = weakref.getweakrefs(o)
674 self.assertEqual(len(refs), 3)
675 self.assert_(r2 is refs[0])
676 self.assert_(r1 in refs[1:])
677 self.assert_(r3 in refs[1:])
678
679 def test_subclass_refs_dont_conflate_callbacks(self):
680 class MyRef(weakref.ref):
681 pass
682 o = Object(42)
683 r1 = MyRef(o, id)
684 r2 = MyRef(o, str)
685 self.assert_(r1 is not r2)
686 refs = weakref.getweakrefs(o)
687 self.assert_(r1 in refs)
688 self.assert_(r2 in refs)
689
690 def test_subclass_refs_with_slots(self):
691 class MyRef(weakref.ref):
692 __slots__ = "slot1", "slot2"
693 def __new__(type, ob, callback, slot1, slot2):
694 return weakref.ref.__new__(type, ob, callback)
695 def __init__(self, ob, callback, slot1, slot2):
696 self.slot1 = slot1
697 self.slot2 = slot2
698 def meth(self):
699 return self.slot1 + self.slot2
700 o = Object(42)
701 r = MyRef(o, None, "abc", "def")
702 self.assertEqual(r.slot1, "abc")
703 self.assertEqual(r.slot2, "def")
704 self.assertEqual(r.meth(), "abcdef")
705 self.failIf(hasattr(r, "__dict__"))
706
707
Fred Drake41deb1e2001-02-01 05:27:45 +0000708class Object:
709 def __init__(self, arg):
710 self.arg = arg
711 def __repr__(self):
712 return "<Object %r>" % self.arg
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000713 def __lt__(self, other):
714 if isinstance(other, Object):
715 return self.arg < other.arg
716 return NotImplemented
717 def __hash__(self):
718 return hash(self.arg)
Fred Drake41deb1e2001-02-01 05:27:45 +0000719
Fred Drake41deb1e2001-02-01 05:27:45 +0000720
Fred Drakeb0fefc52001-03-23 04:22:45 +0000721class MappingTestCase(TestBase):
Martin v. Löwis5e163332001-02-27 18:36:56 +0000722
Fred Drakeb0fefc52001-03-23 04:22:45 +0000723 COUNT = 10
724
725 def test_weak_values(self):
Fred Drake0e540c32001-05-02 05:44:22 +0000726 #
727 # This exercises d.copy(), d.items(), d[], del d[], len(d).
728 #
729 dict, objects = self.make_weak_valued_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +0000730 for o in objects:
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000731 self.assertEqual(weakref.getweakrefcount(o), 1)
Fred Drakeb0fefc52001-03-23 04:22:45 +0000732 self.assert_(o is dict[o.arg],
733 "wrong object returned by weak dict!")
734 items1 = dict.items()
735 items2 = dict.copy().items()
736 items1.sort()
737 items2.sort()
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000738 self.assertEqual(items1, items2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000739 "cloning of weak-valued dictionary did not work!")
740 del items1, items2
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000741 self.assertEqual(len(dict), self.COUNT)
Fred Drakeb0fefc52001-03-23 04:22:45 +0000742 del objects[0]
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000743 self.assertEqual(len(dict), self.COUNT - 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000744 "deleting object did not cause dictionary update")
745 del objects, o
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000746 self.assertEqual(len(dict), 0,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000747 "deleting the values did not clear the dictionary")
Fred Drake4fd06e02001-08-03 04:11:27 +0000748 # regression on SF bug #447152:
749 dict = weakref.WeakValueDictionary()
750 self.assertRaises(KeyError, dict.__getitem__, 1)
751 dict[2] = C()
752 self.assertRaises(KeyError, dict.__getitem__, 2)
Fred Drakeb0fefc52001-03-23 04:22:45 +0000753
754 def test_weak_keys(self):
Fred Drake0e540c32001-05-02 05:44:22 +0000755 #
756 # This exercises d.copy(), d.items(), d[] = v, d[], del d[],
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000757 # len(d), k in d.
Fred Drake0e540c32001-05-02 05:44:22 +0000758 #
759 dict, objects = self.make_weak_keyed_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +0000760 for o in objects:
761 self.assert_(weakref.getweakrefcount(o) == 1,
762 "wrong number of weak references to %r!" % o)
763 self.assert_(o.arg is dict[o],
764 "wrong object returned by weak dict!")
765 items1 = dict.items()
766 items2 = dict.copy().items()
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000767 self.assertEqual(set(items1), set(items2),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000768 "cloning of weak-keyed dictionary did not work!")
769 del items1, items2
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000770 self.assertEqual(len(dict), self.COUNT)
Fred Drakeb0fefc52001-03-23 04:22:45 +0000771 del objects[0]
772 self.assert_(len(dict) == (self.COUNT - 1),
773 "deleting object did not cause dictionary update")
774 del objects, o
775 self.assert_(len(dict) == 0,
776 "deleting the keys did not clear the dictionary")
Fred Drake752eda42001-11-06 16:38:34 +0000777 o = Object(42)
778 dict[o] = "What is the meaning of the universe?"
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000779 self.assert_(o in dict)
780 self.assert_(34 not in dict)
Martin v. Löwis5e163332001-02-27 18:36:56 +0000781
Fred Drake0e540c32001-05-02 05:44:22 +0000782 def test_weak_keyed_iters(self):
783 dict, objects = self.make_weak_keyed_dict()
784 self.check_iters(dict)
785
Thomas Wouters477c8d52006-05-27 19:21:47 +0000786 # Test keyrefs()
787 refs = dict.keyrefs()
788 self.assertEqual(len(refs), len(objects))
789 objects2 = list(objects)
790 for wr in refs:
791 ob = wr()
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000792 self.assert_(ob in dict)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000793 self.assert_(ob in dict)
794 self.assertEqual(ob.arg, dict[ob])
795 objects2.remove(ob)
796 self.assertEqual(len(objects2), 0)
797
798 # Test iterkeyrefs()
799 objects2 = list(objects)
800 self.assertEqual(len(list(dict.iterkeyrefs())), len(objects))
801 for wr in dict.iterkeyrefs():
802 ob = wr()
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000803 self.assert_(ob in dict)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000804 self.assert_(ob in dict)
805 self.assertEqual(ob.arg, dict[ob])
806 objects2.remove(ob)
807 self.assertEqual(len(objects2), 0)
808
Fred Drake0e540c32001-05-02 05:44:22 +0000809 def test_weak_valued_iters(self):
810 dict, objects = self.make_weak_valued_dict()
811 self.check_iters(dict)
812
Thomas Wouters477c8d52006-05-27 19:21:47 +0000813 # Test valuerefs()
814 refs = dict.valuerefs()
815 self.assertEqual(len(refs), len(objects))
816 objects2 = list(objects)
817 for wr in refs:
818 ob = wr()
819 self.assertEqual(ob, dict[ob.arg])
820 self.assertEqual(ob.arg, dict[ob.arg].arg)
821 objects2.remove(ob)
822 self.assertEqual(len(objects2), 0)
823
824 # Test itervaluerefs()
825 objects2 = list(objects)
826 self.assertEqual(len(list(dict.itervaluerefs())), len(objects))
827 for wr in dict.itervaluerefs():
828 ob = wr()
829 self.assertEqual(ob, dict[ob.arg])
830 self.assertEqual(ob.arg, dict[ob.arg].arg)
831 objects2.remove(ob)
832 self.assertEqual(len(objects2), 0)
833
Fred Drake0e540c32001-05-02 05:44:22 +0000834 def check_iters(self, dict):
835 # item iterator:
836 items = dict.items()
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000837 for item in dict.items():
Fred Drake0e540c32001-05-02 05:44:22 +0000838 items.remove(item)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000839 self.assert_(len(items) == 0, "items() did not touch all items")
Fred Drake0e540c32001-05-02 05:44:22 +0000840
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000841 # key iterator, via __iter__():
Guido van Rossum07f24362007-02-11 22:59:48 +0000842 keys = list(dict.keys())
Fred Drake0e540c32001-05-02 05:44:22 +0000843 for k in dict:
844 keys.remove(k)
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000845 self.assert_(len(keys) == 0, "__iter__() did not touch all keys")
846
847 # key iterator, via iterkeys():
Guido van Rossum07f24362007-02-11 22:59:48 +0000848 keys = list(dict.keys())
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000849 for k in dict.keys():
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000850 keys.remove(k)
851 self.assert_(len(keys) == 0, "iterkeys() did not touch all keys")
Fred Drake0e540c32001-05-02 05:44:22 +0000852
853 # value iterator:
Guido van Rossum07f24362007-02-11 22:59:48 +0000854 values = list(dict.values())
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000855 for v in dict.values():
Fred Drake0e540c32001-05-02 05:44:22 +0000856 values.remove(v)
Fred Drakef425b1e2003-07-14 21:37:17 +0000857 self.assert_(len(values) == 0,
858 "itervalues() did not touch all values")
Fred Drake0e540c32001-05-02 05:44:22 +0000859
Guido van Rossum009afb72002-06-10 20:00:52 +0000860 def test_make_weak_keyed_dict_from_dict(self):
861 o = Object(3)
862 dict = weakref.WeakKeyDictionary({o:364})
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000863 self.assertEqual(dict[o], 364)
Guido van Rossum009afb72002-06-10 20:00:52 +0000864
865 def test_make_weak_keyed_dict_from_weak_keyed_dict(self):
866 o = Object(3)
867 dict = weakref.WeakKeyDictionary({o:364})
868 dict2 = weakref.WeakKeyDictionary(dict)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000869 self.assertEqual(dict[o], 364)
Guido van Rossum009afb72002-06-10 20:00:52 +0000870
Fred Drake0e540c32001-05-02 05:44:22 +0000871 def make_weak_keyed_dict(self):
872 dict = weakref.WeakKeyDictionary()
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000873 objects = list(map(Object, range(self.COUNT)))
Fred Drake0e540c32001-05-02 05:44:22 +0000874 for o in objects:
875 dict[o] = o.arg
876 return dict, objects
877
878 def make_weak_valued_dict(self):
879 dict = weakref.WeakValueDictionary()
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000880 objects = list(map(Object, range(self.COUNT)))
Fred Drake0e540c32001-05-02 05:44:22 +0000881 for o in objects:
882 dict[o.arg] = o
883 return dict, objects
884
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000885 def check_popitem(self, klass, key1, value1, key2, value2):
886 weakdict = klass()
887 weakdict[key1] = value1
888 weakdict[key2] = value2
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000889 self.assertEqual(len(weakdict), 2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000890 k, v = weakdict.popitem()
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000891 self.assertEqual(len(weakdict), 1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000892 if k is key1:
893 self.assert_(v is value1)
894 else:
895 self.assert_(v is value2)
896 k, v = weakdict.popitem()
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000897 self.assertEqual(len(weakdict), 0)
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000898 if k is key1:
899 self.assert_(v is value1)
900 else:
901 self.assert_(v is value2)
902
903 def test_weak_valued_dict_popitem(self):
904 self.check_popitem(weakref.WeakValueDictionary,
905 "key1", C(), "key2", C())
906
907 def test_weak_keyed_dict_popitem(self):
908 self.check_popitem(weakref.WeakKeyDictionary,
909 C(), "value 1", C(), "value 2")
910
911 def check_setdefault(self, klass, key, value1, value2):
912 self.assert_(value1 is not value2,
913 "invalid test"
914 " -- value parameters must be distinct objects")
915 weakdict = klass()
916 o = weakdict.setdefault(key, value1)
917 self.assert_(o is value1)
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000918 self.assert_(key in weakdict)
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000919 self.assert_(weakdict.get(key) is value1)
920 self.assert_(weakdict[key] is value1)
921
922 o = weakdict.setdefault(key, value2)
923 self.assert_(o is value1)
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000924 self.assert_(key in weakdict)
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000925 self.assert_(weakdict.get(key) is value1)
926 self.assert_(weakdict[key] is value1)
927
928 def test_weak_valued_dict_setdefault(self):
929 self.check_setdefault(weakref.WeakValueDictionary,
930 "key", C(), C())
931
932 def test_weak_keyed_dict_setdefault(self):
933 self.check_setdefault(weakref.WeakKeyDictionary,
934 C(), "value 1", "value 2")
935
Fred Drakea0a4ab12001-04-16 17:37:27 +0000936 def check_update(self, klass, dict):
Fred Drake0e540c32001-05-02 05:44:22 +0000937 #
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000938 # This exercises d.update(), len(d), d.keys(), k in d,
Fred Drake0e540c32001-05-02 05:44:22 +0000939 # d.get(), d[].
940 #
Fred Drakea0a4ab12001-04-16 17:37:27 +0000941 weakdict = klass()
942 weakdict.update(dict)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000943 self.assertEqual(len(weakdict), len(dict))
Fred Drakea0a4ab12001-04-16 17:37:27 +0000944 for k in weakdict.keys():
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000945 self.assert_(k in dict,
Fred Drakea0a4ab12001-04-16 17:37:27 +0000946 "mysterious new key appeared in weak dict")
947 v = dict.get(k)
948 self.assert_(v is weakdict[k])
949 self.assert_(v is weakdict.get(k))
950 for k in dict.keys():
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000951 self.assert_(k in weakdict,
Fred Drakea0a4ab12001-04-16 17:37:27 +0000952 "original key disappeared in weak dict")
953 v = dict[k]
954 self.assert_(v is weakdict[k])
955 self.assert_(v is weakdict.get(k))
956
957 def test_weak_valued_dict_update(self):
958 self.check_update(weakref.WeakValueDictionary,
959 {1: C(), 'a': C(), C(): C()})
960
961 def test_weak_keyed_dict_update(self):
962 self.check_update(weakref.WeakKeyDictionary,
963 {C(): 1, C(): 2, C(): 3})
964
Fred Drakeccc75622001-09-06 14:52:39 +0000965 def test_weak_keyed_delitem(self):
966 d = weakref.WeakKeyDictionary()
967 o1 = Object('1')
968 o2 = Object('2')
969 d[o1] = 'something'
970 d[o2] = 'something'
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000971 self.assertEqual(len(d), 2)
Fred Drakeccc75622001-09-06 14:52:39 +0000972 del d[o1]
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000973 self.assertEqual(len(d), 1)
974 self.assertEqual(d.keys(), [o2])
Fred Drakeccc75622001-09-06 14:52:39 +0000975
976 def test_weak_valued_delitem(self):
977 d = weakref.WeakValueDictionary()
978 o1 = Object('1')
979 o2 = Object('2')
980 d['something'] = o1
981 d['something else'] = o2
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000982 self.assertEqual(len(d), 2)
Fred Drakeccc75622001-09-06 14:52:39 +0000983 del d['something']
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000984 self.assertEqual(len(d), 1)
Fred Drakeccc75622001-09-06 14:52:39 +0000985 self.assert_(d.items() == [('something else', o2)])
986
Tim Peters886128f2003-05-25 01:45:11 +0000987 def test_weak_keyed_bad_delitem(self):
988 d = weakref.WeakKeyDictionary()
989 o = Object('1')
990 # An attempt to delete an object that isn't there should raise
Tim Peters50d8b8b2003-05-25 17:44:31 +0000991 # KeyError. It didn't before 2.3.
Tim Peters886128f2003-05-25 01:45:11 +0000992 self.assertRaises(KeyError, d.__delitem__, o)
Tim Peters50d8b8b2003-05-25 17:44:31 +0000993 self.assertRaises(KeyError, d.__getitem__, o)
994
995 # If a key isn't of a weakly referencable type, __getitem__ and
996 # __setitem__ raise TypeError. __delitem__ should too.
997 self.assertRaises(TypeError, d.__delitem__, 13)
998 self.assertRaises(TypeError, d.__getitem__, 13)
999 self.assertRaises(TypeError, d.__setitem__, 13, 13)
Tim Peters886128f2003-05-25 01:45:11 +00001000
1001 def test_weak_keyed_cascading_deletes(self):
1002 # SF bug 742860. For some reason, before 2.3 __delitem__ iterated
1003 # over the keys via self.data.iterkeys(). If things vanished from
1004 # the dict during this (or got added), that caused a RuntimeError.
1005
1006 d = weakref.WeakKeyDictionary()
1007 mutate = False
1008
1009 class C(object):
1010 def __init__(self, i):
1011 self.value = i
1012 def __hash__(self):
1013 return hash(self.value)
1014 def __eq__(self, other):
1015 if mutate:
1016 # Side effect that mutates the dict, by removing the
1017 # last strong reference to a key.
1018 del objs[-1]
1019 return self.value == other.value
1020
1021 objs = [C(i) for i in range(4)]
1022 for o in objs:
1023 d[o] = o.value
1024 del o # now the only strong references to keys are in objs
1025 # Find the order in which iterkeys sees the keys.
1026 objs = d.keys()
1027 # Reverse it, so that the iteration implementation of __delitem__
1028 # has to keep looping to find the first object we delete.
1029 objs.reverse()
Tim Peters50d8b8b2003-05-25 17:44:31 +00001030
Tim Peters886128f2003-05-25 01:45:11 +00001031 # Turn on mutation in C.__eq__. The first time thru the loop,
1032 # under the iterkeys() business the first comparison will delete
1033 # the last item iterkeys() would see, and that causes a
1034 # RuntimeError: dictionary changed size during iteration
1035 # when the iterkeys() loop goes around to try comparing the next
Tim Peters50d8b8b2003-05-25 17:44:31 +00001036 # key. After this was fixed, it just deletes the last object *our*
Tim Peters886128f2003-05-25 01:45:11 +00001037 # "for o in obj" loop would have gotten to.
1038 mutate = True
1039 count = 0
1040 for o in objs:
1041 count += 1
1042 del d[o]
1043 self.assertEqual(len(d), 0)
1044 self.assertEqual(count, 2)
1045
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001046from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001047
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001048class WeakValueDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +00001049 """Check that WeakValueDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001050 __ref = {"key1":Object(1), "key2":Object(2), "key3":Object(3)}
Walter Dörwald118f9312004-06-02 18:42:25 +00001051 type2test = weakref.WeakValueDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001052 def _reference(self):
1053 return self.__ref.copy()
1054
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001055class WeakKeyDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +00001056 """Check that WeakKeyDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001057 __ref = {Object("key1"):1, Object("key2"):2, Object("key3"):3}
Walter Dörwald118f9312004-06-02 18:42:25 +00001058 type2test = weakref.WeakKeyDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001059 def _reference(self):
1060 return self.__ref.copy()
Martin v. Löwis5e163332001-02-27 18:36:56 +00001061
Georg Brandl9a65d582005-07-02 19:07:30 +00001062libreftest = """ Doctest for examples in the library reference: libweakref.tex
1063
1064>>> import weakref
1065>>> class Dict(dict):
1066... pass
1067...
1068>>> obj = Dict(red=1, green=2, blue=3) # this object is weak referencable
1069>>> r = weakref.ref(obj)
Guido van Rossum7131f842007-02-09 20:13:25 +00001070>>> print(r() is obj)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001071True
Georg Brandl9a65d582005-07-02 19:07:30 +00001072
1073>>> import weakref
1074>>> class Object:
1075... pass
1076...
1077>>> o = Object()
1078>>> r = weakref.ref(o)
1079>>> o2 = r()
1080>>> o is o2
1081True
1082>>> del o, o2
Guido van Rossum7131f842007-02-09 20:13:25 +00001083>>> print(r())
Georg Brandl9a65d582005-07-02 19:07:30 +00001084None
1085
1086>>> import weakref
1087>>> class ExtendedRef(weakref.ref):
1088... def __init__(self, ob, callback=None, **annotations):
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001089... super().__init__(ob, callback)
Georg Brandl9a65d582005-07-02 19:07:30 +00001090... self.__counter = 0
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001091... for k, v in annotations.items():
Georg Brandl9a65d582005-07-02 19:07:30 +00001092... setattr(self, k, v)
1093... def __call__(self):
1094... '''Return a pair containing the referent and the number of
1095... times the reference has been called.
1096... '''
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001097... ob = super().__call__()
Georg Brandl9a65d582005-07-02 19:07:30 +00001098... if ob is not None:
1099... self.__counter += 1
1100... ob = (ob, self.__counter)
1101... return ob
Guido van Rossumd8faa362007-04-27 19:54:29 +00001102...
Georg Brandl9a65d582005-07-02 19:07:30 +00001103>>> class A: # not in docs from here, just testing the ExtendedRef
1104... pass
1105...
1106>>> a = A()
1107>>> r = ExtendedRef(a, foo=1, bar="baz")
1108>>> r.foo
11091
1110>>> r.bar
1111'baz'
1112>>> r()[1]
11131
1114>>> r()[1]
11152
1116>>> r()[0] is a
1117True
1118
1119
1120>>> import weakref
1121>>> _id2obj_dict = weakref.WeakValueDictionary()
1122>>> def remember(obj):
1123... oid = id(obj)
1124... _id2obj_dict[oid] = obj
1125... return oid
1126...
1127>>> def id2obj(oid):
1128... return _id2obj_dict[oid]
1129...
1130>>> a = A() # from here, just testing
1131>>> a_id = remember(a)
1132>>> id2obj(a_id) is a
1133True
1134>>> del a
1135>>> try:
1136... id2obj(a_id)
1137... except KeyError:
Guido van Rossum7131f842007-02-09 20:13:25 +00001138... print('OK')
Georg Brandl9a65d582005-07-02 19:07:30 +00001139... else:
Guido van Rossum7131f842007-02-09 20:13:25 +00001140... print('WeakValueDictionary error')
Georg Brandl9a65d582005-07-02 19:07:30 +00001141OK
1142
1143"""
1144
1145__test__ = {'libreftest' : libreftest}
1146
Fred Drake2e2be372001-09-20 21:33:42 +00001147def test_main():
Walter Dörwald21d3a322003-05-01 17:45:56 +00001148 test_support.run_unittest(
1149 ReferencesTestCase,
1150 MappingTestCase,
1151 WeakValueDictionaryTestCase,
Fred Drakef425b1e2003-07-14 21:37:17 +00001152 WeakKeyDictionaryTestCase,
1153 )
Georg Brandl9a65d582005-07-02 19:07:30 +00001154 test_support.run_doctest(sys.modules[__name__])
Fred Drake2e2be372001-09-20 21:33:42 +00001155
1156
1157if __name__ == "__main__":
1158 test_main()