blob: d42922a2d2216b43090aa885aacf79168dd6f529 [file] [log] [blame]
Fred Drake41deb1e2001-02-01 05:27:45 +00001import sys
Fred Drakeb0fefc52001-03-23 04:22:45 +00002import unittest
Fred Drake5935ff02001-12-19 16:54:23 +00003import UserList
Fred Drake41deb1e2001-02-01 05:27:45 +00004import weakref
5
Barry Warsaw04f357c2002-07-23 19:04:11 +00006from test import test_support
Fred Drake41deb1e2001-02-01 05:27:45 +00007
8
9class C:
Fred Drakeb0fefc52001-03-23 04:22:45 +000010 def method(self):
11 pass
Fred Drake41deb1e2001-02-01 05:27:45 +000012
13
Fred Drakeb0fefc52001-03-23 04:22:45 +000014class Callable:
15 bar = None
Fred Drake41deb1e2001-02-01 05:27:45 +000016
Fred Drakeb0fefc52001-03-23 04:22:45 +000017 def __call__(self, x):
18 self.bar = x
Fred Drake41deb1e2001-02-01 05:27:45 +000019
20
Fred Drakeb0fefc52001-03-23 04:22:45 +000021def create_function():
22 def f(): pass
23 return f
24
25def create_bound_method():
26 return C().method
27
28def create_unbound_method():
29 return C.method
Fred Drake41deb1e2001-02-01 05:27:45 +000030
31
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)
47 self.check_basic_ref(create_unbound_method)
Fred Drake41deb1e2001-02-01 05:27:45 +000048
Fred Drake43735da2002-04-11 03:59:42 +000049 # Just make sure the tp_repr handler doesn't raise an exception.
50 # Live reference:
51 o = C()
52 wr = weakref.ref(o)
53 `wr`
54 # Dead reference:
55 del o
56 `wr`
57
Fred Drakeb0fefc52001-03-23 04:22:45 +000058 def test_basic_callback(self):
59 self.check_basic_callback(C)
60 self.check_basic_callback(create_function)
61 self.check_basic_callback(create_bound_method)
62 self.check_basic_callback(create_unbound_method)
Fred Drake41deb1e2001-02-01 05:27:45 +000063
Fred Drakeb0fefc52001-03-23 04:22:45 +000064 def test_multiple_callbacks(self):
65 o = C()
66 ref1 = weakref.ref(o, self.callback)
67 ref2 = weakref.ref(o, self.callback)
68 del o
69 self.assert_(ref1() is None,
70 "expected reference to be invalidated")
71 self.assert_(ref2() is None,
72 "expected reference to be invalidated")
73 self.assert_(self.cbcalled == 2,
74 "callback not called the right number of times")
Fred Drake41deb1e2001-02-01 05:27:45 +000075
Fred Drake705088e2001-04-13 17:18:15 +000076 def test_multiple_selfref_callbacks(self):
Guido van Rossum9eee5542002-08-22 20:21:30 +000077 # Make sure all references are invalidated before callbacks are called
Fred Drake705088e2001-04-13 17:18:15 +000078 #
79 # What's important here is that we're using the first
80 # reference in the callback invoked on the second reference
81 # (the most recently created ref is cleaned up first). This
82 # tests that all references to the object are invalidated
83 # before any of the callbacks are invoked, so that we only
84 # have one invocation of _weakref.c:cleanup_helper() active
85 # for a particular object at a time.
86 #
87 def callback(object, self=self):
88 self.ref()
89 c = C()
90 self.ref = weakref.ref(c, callback)
91 ref1 = weakref.ref(c, callback)
92 del c
93
Fred Drakeb0fefc52001-03-23 04:22:45 +000094 def test_proxy_ref(self):
95 o = C()
96 o.bar = 1
97 ref1 = weakref.proxy(o, self.callback)
98 ref2 = weakref.proxy(o, self.callback)
99 del o
Fred Drake41deb1e2001-02-01 05:27:45 +0000100
Fred Drakeb0fefc52001-03-23 04:22:45 +0000101 def check(proxy):
102 proxy.bar
Fred Drake41deb1e2001-02-01 05:27:45 +0000103
Fred Drakeb0fefc52001-03-23 04:22:45 +0000104 self.assertRaises(weakref.ReferenceError, check, ref1)
105 self.assertRaises(weakref.ReferenceError, check, ref2)
106 self.assert_(self.cbcalled == 2)
Fred Drake41deb1e2001-02-01 05:27:45 +0000107
Fred Drakeb0fefc52001-03-23 04:22:45 +0000108 def check_basic_ref(self, factory):
109 o = factory()
110 ref = weakref.ref(o)
111 self.assert_(ref() is not None,
112 "weak reference to live object should be live")
113 o2 = ref()
114 self.assert_(o is o2,
115 "<ref>() should return original object if live")
Fred Drake41deb1e2001-02-01 05:27:45 +0000116
Fred Drakeb0fefc52001-03-23 04:22:45 +0000117 def check_basic_callback(self, factory):
118 self.cbcalled = 0
119 o = factory()
120 ref = weakref.ref(o, self.callback)
121 del o
Fred Drake705088e2001-04-13 17:18:15 +0000122 self.assert_(self.cbcalled == 1,
123 "callback did not properly set 'cbcalled'")
124 self.assert_(ref() is None,
125 "ref2 should be dead after deleting object reference")
Fred Drake41deb1e2001-02-01 05:27:45 +0000126
Fred Drakeb0fefc52001-03-23 04:22:45 +0000127 def test_ref_reuse(self):
128 o = C()
129 ref1 = weakref.ref(o)
130 # create a proxy to make sure that there's an intervening creation
131 # between these two; it should make no difference
132 proxy = weakref.proxy(o)
133 ref2 = weakref.ref(o)
134 self.assert_(ref1 is ref2,
135 "reference object w/out callback should be re-used")
Fred Drake41deb1e2001-02-01 05:27:45 +0000136
Fred Drakeb0fefc52001-03-23 04:22:45 +0000137 o = C()
138 proxy = weakref.proxy(o)
139 ref1 = weakref.ref(o)
140 ref2 = weakref.ref(o)
141 self.assert_(ref1 is ref2,
142 "reference object w/out callback should be re-used")
143 self.assert_(weakref.getweakrefcount(o) == 2,
144 "wrong weak ref count for object")
145 del proxy
146 self.assert_(weakref.getweakrefcount(o) == 1,
147 "wrong weak ref count for object after deleting proxy")
Fred Drake41deb1e2001-02-01 05:27:45 +0000148
Fred Drakeb0fefc52001-03-23 04:22:45 +0000149 def test_proxy_reuse(self):
150 o = C()
151 proxy1 = weakref.proxy(o)
152 ref = weakref.ref(o)
153 proxy2 = weakref.proxy(o)
154 self.assert_(proxy1 is proxy2,
155 "proxy object w/out callback should have been re-used")
156
157 def test_basic_proxy(self):
158 o = C()
159 self.check_proxy(o, weakref.proxy(o))
160
Fred Drake5935ff02001-12-19 16:54:23 +0000161 L = UserList.UserList()
162 p = weakref.proxy(L)
163 self.failIf(p, "proxy for empty UserList should be false")
164 p.append(12)
165 self.assertEqual(len(L), 1)
166 self.failUnless(p, "proxy for non-empty UserList should be true")
167 p[:] = [2, 3]
168 self.assertEqual(len(L), 2)
169 self.assertEqual(len(p), 2)
Fred Drakef425b1e2003-07-14 21:37:17 +0000170 self.failUnless(3 in p,
171 "proxy didn't support __contains__() properly")
Fred Drake5935ff02001-12-19 16:54:23 +0000172 p[1] = 5
173 self.assertEqual(L[1], 5)
174 self.assertEqual(p[1], 5)
175 L2 = UserList.UserList(L)
176 p2 = weakref.proxy(L2)
177 self.assertEqual(p, p2)
Fred Drake43735da2002-04-11 03:59:42 +0000178 ## self.assertEqual(`L2`, `p2`)
179 L3 = UserList.UserList(range(10))
180 p3 = weakref.proxy(L3)
181 self.assertEqual(L3[:], p3[:])
182 self.assertEqual(L3[5:], p3[5:])
183 self.assertEqual(L3[:5], p3[:5])
184 self.assertEqual(L3[2:5], p3[2:5])
Fred Drake5935ff02001-12-19 16:54:23 +0000185
Fred Drakeb0fefc52001-03-23 04:22:45 +0000186 def test_callable_proxy(self):
187 o = Callable()
188 ref1 = weakref.proxy(o)
189
190 self.check_proxy(o, ref1)
191
192 self.assert_(type(ref1) is weakref.CallableProxyType,
193 "proxy is not of callable type")
194 ref1('twinkies!')
195 self.assert_(o.bar == 'twinkies!',
196 "call through proxy not passed through to original")
Fred Drake3bb4d212001-10-18 19:28:29 +0000197 ref1(x='Splat.')
198 self.assert_(o.bar == 'Splat.',
199 "call through proxy not passed through to original")
Fred Drakeb0fefc52001-03-23 04:22:45 +0000200
201 # expect due to too few args
202 self.assertRaises(TypeError, ref1)
203
204 # expect due to too many args
205 self.assertRaises(TypeError, ref1, 1, 2, 3)
206
207 def check_proxy(self, o, proxy):
208 o.foo = 1
209 self.assert_(proxy.foo == 1,
210 "proxy does not reflect attribute addition")
211 o.foo = 2
212 self.assert_(proxy.foo == 2,
213 "proxy does not reflect attribute modification")
214 del o.foo
215 self.assert_(not hasattr(proxy, 'foo'),
216 "proxy does not reflect attribute removal")
217
218 proxy.foo = 1
219 self.assert_(o.foo == 1,
220 "object does not reflect attribute addition via proxy")
221 proxy.foo = 2
222 self.assert_(
223 o.foo == 2,
224 "object does not reflect attribute modification via proxy")
225 del proxy.foo
226 self.assert_(not hasattr(o, 'foo'),
227 "object does not reflect attribute removal via proxy")
228
Raymond Hettingerd693a812003-06-30 04:18:48 +0000229 def test_proxy_deletion(self):
230 # Test clearing of SF bug #762891
231 class Foo:
232 result = None
233 def __delitem__(self, accessor):
234 self.result = accessor
235 g = Foo()
236 f = weakref.proxy(g)
237 del f[0]
238 self.assertEqual(f.result, 0)
239
Fred Drakeb0fefc52001-03-23 04:22:45 +0000240 def test_getweakrefcount(self):
241 o = C()
242 ref1 = weakref.ref(o)
243 ref2 = weakref.ref(o, self.callback)
244 self.assert_(weakref.getweakrefcount(o) == 2,
245 "got wrong number of weak reference objects")
246
247 proxy1 = weakref.proxy(o)
248 proxy2 = weakref.proxy(o, self.callback)
249 self.assert_(weakref.getweakrefcount(o) == 4,
250 "got wrong number of weak reference objects")
251
Walter Dörwaldb167b042003-12-11 12:34:05 +0000252 # assumes ints do not support weakrefs
253 self.assert_(weakref.getweakrefcount(1) == 0,
254 "got wrong number of weak reference objects for int")
255
Fred Drakeb0fefc52001-03-23 04:22:45 +0000256 def test_getweakrefs(self):
257 o = C()
258 ref1 = weakref.ref(o, self.callback)
259 ref2 = weakref.ref(o, self.callback)
260 del ref1
261 self.assert_(weakref.getweakrefs(o) == [ref2],
262 "list of refs does not match")
263
264 o = C()
265 ref1 = weakref.ref(o, self.callback)
266 ref2 = weakref.ref(o, self.callback)
267 del ref2
268 self.assert_(weakref.getweakrefs(o) == [ref1],
269 "list of refs does not match")
270
Walter Dörwaldb167b042003-12-11 12:34:05 +0000271 # assumes ints do not support weakrefs
272 self.assert_(weakref.getweakrefs(1) == [],
273 "list of refs does not match for int")
274
Fred Drake39c27f12001-10-18 18:06:05 +0000275 def test_newstyle_number_ops(self):
276 class F(float):
277 pass
278 f = F(2.0)
279 p = weakref.proxy(f)
280 self.assert_(p + 1.0 == 3.0)
281 self.assert_(1.0 + p == 3.0) # this used to SEGV
282
Fred Drake2a64f462001-12-10 23:46:02 +0000283 def test_callbacks_protected(self):
Guido van Rossum9eee5542002-08-22 20:21:30 +0000284 # Callbacks protected from already-set exceptions?
Fred Drake2a64f462001-12-10 23:46:02 +0000285 # Regression test for SF bug #478534.
286 class BogusError(Exception):
287 pass
288 data = {}
289 def remove(k):
290 del data[k]
291 def encapsulate():
292 f = lambda : ()
293 data[weakref.ref(f, remove)] = None
294 raise BogusError
295 try:
296 encapsulate()
297 except BogusError:
298 pass
299 else:
300 self.fail("exception not properly restored")
301 try:
302 encapsulate()
303 except BogusError:
304 pass
305 else:
306 self.fail("exception not properly restored")
307
Tim Petersadd09b42003-11-12 20:43:28 +0000308 def test_sf_bug_840829(self):
309 # "weakref callbacks and gc corrupt memory"
310 # subtype_dealloc erroneously exposed a new-style instance
311 # already in the process of getting deallocated to gc,
312 # causing double-deallocation if the instance had a weakref
313 # callback that triggered gc.
314 # If the bug exists, there probably won't be an obvious symptom
315 # in a release build. In a debug build, a segfault will occur
316 # when the second attempt to remove the instance from the "list
317 # of all objects" occurs.
318
319 import gc
320
321 class C(object):
322 pass
323
324 c = C()
325 wr = weakref.ref(c, lambda ignore: gc.collect())
326 del c
327
Tim Petersf7f9e992003-11-13 21:59:32 +0000328 # There endeth the first part. It gets worse.
329 del wr
330
331 c1 = C()
332 c1.i = C()
333 wr = weakref.ref(c1.i, lambda ignore: gc.collect())
334
335 c2 = C()
336 c2.c1 = c1
337 del c1 # still alive because c2 points to it
338
339 # Now when subtype_dealloc gets called on c2, it's not enough just
340 # that c2 is immune from gc while the weakref callbacks associated
341 # with c2 execute (there are none in this 2nd half of the test, btw).
342 # subtype_dealloc goes on to call the base classes' deallocs too,
343 # so any gc triggered by weakref callbacks associated with anything
344 # torn down by a base class dealloc can also trigger double
345 # deallocation of c2.
346 del c2
Fred Drake41deb1e2001-02-01 05:27:45 +0000347
Tim Peters403a2032003-11-20 21:21:46 +0000348 def test_callback_in_cycle_1(self):
349 import gc
350
351 class J(object):
352 pass
353
354 class II(object):
355 def acallback(self, ignore):
356 self.J
357
358 I = II()
359 I.J = J
360 I.wr = weakref.ref(J, I.acallback)
361
362 # Now J and II are each in a self-cycle (as all new-style class
363 # objects are, since their __mro__ points back to them). I holds
364 # both a weak reference (I.wr) and a strong reference (I.J) to class
365 # J. I is also in a cycle (I.wr points to a weakref that references
366 # I.acallback). When we del these three, they all become trash, but
367 # the cycles prevent any of them from getting cleaned up immediately.
368 # Instead they have to wait for cyclic gc to deduce that they're
369 # trash.
370 #
371 # gc used to call tp_clear on all of them, and the order in which
372 # it does that is pretty accidental. The exact order in which we
373 # built up these things manages to provoke gc into running tp_clear
374 # in just the right order (I last). Calling tp_clear on II leaves
375 # behind an insane class object (its __mro__ becomes NULL). Calling
376 # tp_clear on J breaks its self-cycle, but J doesn't get deleted
377 # just then because of the strong reference from I.J. Calling
378 # tp_clear on I starts to clear I's __dict__, and just happens to
379 # clear I.J first -- I.wr is still intact. That removes the last
380 # reference to J, which triggers the weakref callback. The callback
381 # tries to do "self.J", and instances of new-style classes look up
382 # attributes ("J") in the class dict first. The class (II) wants to
383 # search II.__mro__, but that's NULL. The result was a segfault in
384 # a release build, and an assert failure in a debug build.
385 del I, J, II
386 gc.collect()
387
388 def test_callback_in_cycle_2(self):
389 import gc
390
391 # This is just like test_callback_in_cycle_1, except that II is an
392 # old-style class. The symptom is different then: an instance of an
393 # old-style class looks in its own __dict__ first. 'J' happens to
394 # get cleared from I.__dict__ before 'wr', and 'J' was never in II's
395 # __dict__, so the attribute isn't found. The difference is that
396 # the old-style II doesn't have a NULL __mro__ (it doesn't have any
397 # __mro__), so no segfault occurs. Instead it got:
398 # test_callback_in_cycle_2 (__main__.ReferencesTestCase) ...
399 # Exception exceptions.AttributeError:
400 # "II instance has no attribute 'J'" in <bound method II.acallback
401 # of <?.II instance at 0x00B9B4B8>> ignored
402
403 class J(object):
404 pass
405
406 class II:
407 def acallback(self, ignore):
408 self.J
409
410 I = II()
411 I.J = J
412 I.wr = weakref.ref(J, I.acallback)
413
414 del I, J, II
415 gc.collect()
416
417 def test_callback_in_cycle_3(self):
418 import gc
419
420 # This one broke the first patch that fixed the last two. In this
421 # case, the objects reachable from the callback aren't also reachable
422 # from the object (c1) *triggering* the callback: you can get to
423 # c1 from c2, but not vice-versa. The result was that c2's __dict__
424 # got tp_clear'ed by the time the c2.cb callback got invoked.
425
426 class C:
427 def cb(self, ignore):
428 self.me
429 self.c1
430 self.wr
431
432 c1, c2 = C(), C()
433
434 c2.me = c2
435 c2.c1 = c1
436 c2.wr = weakref.ref(c1, c2.cb)
437
438 del c1, c2
439 gc.collect()
440
441 def test_callback_in_cycle_4(self):
442 import gc
443
444 # Like test_callback_in_cycle_3, except c2 and c1 have different
445 # classes. c2's class (C) isn't reachable from c1 then, so protecting
446 # objects reachable from the dying object (c1) isn't enough to stop
447 # c2's class (C) from getting tp_clear'ed before c2.cb is invoked.
448 # The result was a segfault (C.__mro__ was NULL when the callback
449 # tried to look up self.me).
450
451 class C(object):
452 def cb(self, ignore):
453 self.me
454 self.c1
455 self.wr
456
457 class D:
458 pass
459
460 c1, c2 = D(), C()
461
462 c2.me = c2
463 c2.c1 = c1
464 c2.wr = weakref.ref(c1, c2.cb)
465
466 del c1, c2, C, D
467 gc.collect()
468
469 def test_callback_in_cycle_resurrection(self):
470 import gc
471
472 # Do something nasty in a weakref callback: resurrect objects
473 # from dead cycles. For this to be attempted, the weakref and
474 # its callback must also be part of the cyclic trash (else the
475 # objects reachable via the callback couldn't be in cyclic trash
476 # to begin with -- the callback would act like an external root).
477 # But gc clears trash weakrefs with callbacks early now, which
478 # disables the callbacks, so the callbacks shouldn't get called
479 # at all (and so nothing actually gets resurrected).
480
481 alist = []
482 class C(object):
483 def __init__(self, value):
484 self.attribute = value
485
486 def acallback(self, ignore):
487 alist.append(self.c)
488
489 c1, c2 = C(1), C(2)
490 c1.c = c2
491 c2.c = c1
492 c1.wr = weakref.ref(c2, c1.acallback)
493 c2.wr = weakref.ref(c1, c2.acallback)
494
495 def C_went_away(ignore):
496 alist.append("C went away")
497 wr = weakref.ref(C, C_went_away)
498
499 del c1, c2, C # make them all trash
500 self.assertEqual(alist, []) # del isn't enough to reclaim anything
501
502 gc.collect()
503 # c1.wr and c2.wr were part of the cyclic trash, so should have
504 # been cleared without their callbacks executing. OTOH, the weakref
505 # to C is bound to a function local (wr), and wasn't trash, so that
506 # callback should have been invoked when C went away.
507 self.assertEqual(alist, ["C went away"])
508 # The remaining weakref should be dead now (its callback ran).
509 self.assertEqual(wr(), None)
510
511 del alist[:]
512 gc.collect()
513 self.assertEqual(alist, [])
514
515 def test_callbacks_on_callback(self):
516 import gc
517
518 # Set up weakref callbacks *on* weakref callbacks.
519 alist = []
520 def safe_callback(ignore):
521 alist.append("safe_callback called")
522
523 class C(object):
524 def cb(self, ignore):
525 alist.append("cb called")
526
527 c, d = C(), C()
528 c.other = d
529 d.other = c
530 callback = c.cb
531 c.wr = weakref.ref(d, callback) # this won't trigger
532 d.wr = weakref.ref(callback, d.cb) # ditto
533 external_wr = weakref.ref(callback, safe_callback) # but this will
534 self.assert_(external_wr() is callback)
535
536 # The weakrefs attached to c and d should get cleared, so that
537 # C.cb is never called. But external_wr isn't part of the cyclic
538 # trash, and no cyclic trash is reachable from it, so safe_callback
539 # should get invoked when the bound method object callback (c.cb)
540 # -- which is itself a callback, and also part of the cyclic trash --
541 # gets reclaimed at the end of gc.
542
543 del callback, c, d, C
544 self.assertEqual(alist, []) # del isn't enough to clean up cycles
545 gc.collect()
546 self.assertEqual(alist, ["safe_callback called"])
547 self.assertEqual(external_wr(), None)
548
549 del alist[:]
550 gc.collect()
551 self.assertEqual(alist, [])
552
Fred Drake41deb1e2001-02-01 05:27:45 +0000553class Object:
554 def __init__(self, arg):
555 self.arg = arg
556 def __repr__(self):
557 return "<Object %r>" % self.arg
558
Fred Drake41deb1e2001-02-01 05:27:45 +0000559
Fred Drakeb0fefc52001-03-23 04:22:45 +0000560class MappingTestCase(TestBase):
Martin v. Löwis5e163332001-02-27 18:36:56 +0000561
Fred Drakeb0fefc52001-03-23 04:22:45 +0000562 COUNT = 10
563
564 def test_weak_values(self):
Fred Drake0e540c32001-05-02 05:44:22 +0000565 #
566 # This exercises d.copy(), d.items(), d[], del d[], len(d).
567 #
568 dict, objects = self.make_weak_valued_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +0000569 for o in objects:
570 self.assert_(weakref.getweakrefcount(o) == 1,
571 "wrong number of weak references to %r!" % o)
572 self.assert_(o is dict[o.arg],
573 "wrong object returned by weak dict!")
574 items1 = dict.items()
575 items2 = dict.copy().items()
576 items1.sort()
577 items2.sort()
578 self.assert_(items1 == items2,
579 "cloning of weak-valued dictionary did not work!")
580 del items1, items2
581 self.assert_(len(dict) == self.COUNT)
582 del objects[0]
583 self.assert_(len(dict) == (self.COUNT - 1),
584 "deleting object did not cause dictionary update")
585 del objects, o
586 self.assert_(len(dict) == 0,
587 "deleting the values did not clear the dictionary")
Fred Drake4fd06e02001-08-03 04:11:27 +0000588 # regression on SF bug #447152:
589 dict = weakref.WeakValueDictionary()
590 self.assertRaises(KeyError, dict.__getitem__, 1)
591 dict[2] = C()
592 self.assertRaises(KeyError, dict.__getitem__, 2)
Fred Drakeb0fefc52001-03-23 04:22:45 +0000593
594 def test_weak_keys(self):
Fred Drake0e540c32001-05-02 05:44:22 +0000595 #
596 # This exercises d.copy(), d.items(), d[] = v, d[], del d[],
Fred Drake752eda42001-11-06 16:38:34 +0000597 # len(d), d.has_key().
Fred Drake0e540c32001-05-02 05:44:22 +0000598 #
599 dict, objects = self.make_weak_keyed_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +0000600 for o in objects:
601 self.assert_(weakref.getweakrefcount(o) == 1,
602 "wrong number of weak references to %r!" % o)
603 self.assert_(o.arg is dict[o],
604 "wrong object returned by weak dict!")
605 items1 = dict.items()
606 items2 = dict.copy().items()
Raymond Hettingera690a992003-11-16 16:17:49 +0000607 self.assert_(set(items1) == set(items2),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000608 "cloning of weak-keyed dictionary did not work!")
609 del items1, items2
610 self.assert_(len(dict) == self.COUNT)
611 del objects[0]
612 self.assert_(len(dict) == (self.COUNT - 1),
613 "deleting object did not cause dictionary update")
614 del objects, o
615 self.assert_(len(dict) == 0,
616 "deleting the keys did not clear the dictionary")
Fred Drake752eda42001-11-06 16:38:34 +0000617 o = Object(42)
618 dict[o] = "What is the meaning of the universe?"
619 self.assert_(dict.has_key(o))
620 self.assert_(not dict.has_key(34))
Martin v. Löwis5e163332001-02-27 18:36:56 +0000621
Fred Drake0e540c32001-05-02 05:44:22 +0000622 def test_weak_keyed_iters(self):
623 dict, objects = self.make_weak_keyed_dict()
624 self.check_iters(dict)
625
626 def test_weak_valued_iters(self):
627 dict, objects = self.make_weak_valued_dict()
628 self.check_iters(dict)
629
630 def check_iters(self, dict):
631 # item iterator:
632 items = dict.items()
633 for item in dict.iteritems():
634 items.remove(item)
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000635 self.assert_(len(items) == 0, "iteritems() did not touch all items")
Fred Drake0e540c32001-05-02 05:44:22 +0000636
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000637 # key iterator, via __iter__():
Fred Drake0e540c32001-05-02 05:44:22 +0000638 keys = dict.keys()
639 for k in dict:
640 keys.remove(k)
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000641 self.assert_(len(keys) == 0, "__iter__() did not touch all keys")
642
643 # key iterator, via iterkeys():
644 keys = dict.keys()
645 for k in dict.iterkeys():
646 keys.remove(k)
647 self.assert_(len(keys) == 0, "iterkeys() did not touch all keys")
Fred Drake0e540c32001-05-02 05:44:22 +0000648
649 # value iterator:
650 values = dict.values()
651 for v in dict.itervalues():
652 values.remove(v)
Fred Drakef425b1e2003-07-14 21:37:17 +0000653 self.assert_(len(values) == 0,
654 "itervalues() did not touch all values")
Fred Drake0e540c32001-05-02 05:44:22 +0000655
Guido van Rossum009afb72002-06-10 20:00:52 +0000656 def test_make_weak_keyed_dict_from_dict(self):
657 o = Object(3)
658 dict = weakref.WeakKeyDictionary({o:364})
659 self.assert_(dict[o] == 364)
660
661 def test_make_weak_keyed_dict_from_weak_keyed_dict(self):
662 o = Object(3)
663 dict = weakref.WeakKeyDictionary({o:364})
664 dict2 = weakref.WeakKeyDictionary(dict)
665 self.assert_(dict[o] == 364)
666
Fred Drake0e540c32001-05-02 05:44:22 +0000667 def make_weak_keyed_dict(self):
668 dict = weakref.WeakKeyDictionary()
669 objects = map(Object, range(self.COUNT))
670 for o in objects:
671 dict[o] = o.arg
672 return dict, objects
673
674 def make_weak_valued_dict(self):
675 dict = weakref.WeakValueDictionary()
676 objects = map(Object, range(self.COUNT))
677 for o in objects:
678 dict[o.arg] = o
679 return dict, objects
680
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000681 def check_popitem(self, klass, key1, value1, key2, value2):
682 weakdict = klass()
683 weakdict[key1] = value1
684 weakdict[key2] = value2
685 self.assert_(len(weakdict) == 2)
686 k, v = weakdict.popitem()
687 self.assert_(len(weakdict) == 1)
688 if k is key1:
689 self.assert_(v is value1)
690 else:
691 self.assert_(v is value2)
692 k, v = weakdict.popitem()
693 self.assert_(len(weakdict) == 0)
694 if k is key1:
695 self.assert_(v is value1)
696 else:
697 self.assert_(v is value2)
698
699 def test_weak_valued_dict_popitem(self):
700 self.check_popitem(weakref.WeakValueDictionary,
701 "key1", C(), "key2", C())
702
703 def test_weak_keyed_dict_popitem(self):
704 self.check_popitem(weakref.WeakKeyDictionary,
705 C(), "value 1", C(), "value 2")
706
707 def check_setdefault(self, klass, key, value1, value2):
708 self.assert_(value1 is not value2,
709 "invalid test"
710 " -- value parameters must be distinct objects")
711 weakdict = klass()
712 o = weakdict.setdefault(key, value1)
713 self.assert_(o is value1)
714 self.assert_(weakdict.has_key(key))
715 self.assert_(weakdict.get(key) is value1)
716 self.assert_(weakdict[key] is value1)
717
718 o = weakdict.setdefault(key, value2)
719 self.assert_(o is value1)
720 self.assert_(weakdict.has_key(key))
721 self.assert_(weakdict.get(key) is value1)
722 self.assert_(weakdict[key] is value1)
723
724 def test_weak_valued_dict_setdefault(self):
725 self.check_setdefault(weakref.WeakValueDictionary,
726 "key", C(), C())
727
728 def test_weak_keyed_dict_setdefault(self):
729 self.check_setdefault(weakref.WeakKeyDictionary,
730 C(), "value 1", "value 2")
731
Fred Drakea0a4ab12001-04-16 17:37:27 +0000732 def check_update(self, klass, dict):
Fred Drake0e540c32001-05-02 05:44:22 +0000733 #
734 # This exercises d.update(), len(d), d.keys(), d.has_key(),
735 # d.get(), d[].
736 #
Fred Drakea0a4ab12001-04-16 17:37:27 +0000737 weakdict = klass()
738 weakdict.update(dict)
739 self.assert_(len(weakdict) == len(dict))
740 for k in weakdict.keys():
741 self.assert_(dict.has_key(k),
742 "mysterious new key appeared in weak dict")
743 v = dict.get(k)
744 self.assert_(v is weakdict[k])
745 self.assert_(v is weakdict.get(k))
746 for k in dict.keys():
747 self.assert_(weakdict.has_key(k),
748 "original key disappeared in weak dict")
749 v = dict[k]
750 self.assert_(v is weakdict[k])
751 self.assert_(v is weakdict.get(k))
752
753 def test_weak_valued_dict_update(self):
754 self.check_update(weakref.WeakValueDictionary,
755 {1: C(), 'a': C(), C(): C()})
756
757 def test_weak_keyed_dict_update(self):
758 self.check_update(weakref.WeakKeyDictionary,
759 {C(): 1, C(): 2, C(): 3})
760
Fred Drakeccc75622001-09-06 14:52:39 +0000761 def test_weak_keyed_delitem(self):
762 d = weakref.WeakKeyDictionary()
763 o1 = Object('1')
764 o2 = Object('2')
765 d[o1] = 'something'
766 d[o2] = 'something'
767 self.assert_(len(d) == 2)
768 del d[o1]
769 self.assert_(len(d) == 1)
770 self.assert_(d.keys() == [o2])
771
772 def test_weak_valued_delitem(self):
773 d = weakref.WeakValueDictionary()
774 o1 = Object('1')
775 o2 = Object('2')
776 d['something'] = o1
777 d['something else'] = o2
778 self.assert_(len(d) == 2)
779 del d['something']
780 self.assert_(len(d) == 1)
781 self.assert_(d.items() == [('something else', o2)])
782
Tim Peters886128f2003-05-25 01:45:11 +0000783 def test_weak_keyed_bad_delitem(self):
784 d = weakref.WeakKeyDictionary()
785 o = Object('1')
786 # An attempt to delete an object that isn't there should raise
Tim Peters50d8b8b2003-05-25 17:44:31 +0000787 # KeyError. It didn't before 2.3.
Tim Peters886128f2003-05-25 01:45:11 +0000788 self.assertRaises(KeyError, d.__delitem__, o)
Tim Peters50d8b8b2003-05-25 17:44:31 +0000789 self.assertRaises(KeyError, d.__getitem__, o)
790
791 # If a key isn't of a weakly referencable type, __getitem__ and
792 # __setitem__ raise TypeError. __delitem__ should too.
793 self.assertRaises(TypeError, d.__delitem__, 13)
794 self.assertRaises(TypeError, d.__getitem__, 13)
795 self.assertRaises(TypeError, d.__setitem__, 13, 13)
Tim Peters886128f2003-05-25 01:45:11 +0000796
797 def test_weak_keyed_cascading_deletes(self):
798 # SF bug 742860. For some reason, before 2.3 __delitem__ iterated
799 # over the keys via self.data.iterkeys(). If things vanished from
800 # the dict during this (or got added), that caused a RuntimeError.
801
802 d = weakref.WeakKeyDictionary()
803 mutate = False
804
805 class C(object):
806 def __init__(self, i):
807 self.value = i
808 def __hash__(self):
809 return hash(self.value)
810 def __eq__(self, other):
811 if mutate:
812 # Side effect that mutates the dict, by removing the
813 # last strong reference to a key.
814 del objs[-1]
815 return self.value == other.value
816
817 objs = [C(i) for i in range(4)]
818 for o in objs:
819 d[o] = o.value
820 del o # now the only strong references to keys are in objs
821 # Find the order in which iterkeys sees the keys.
822 objs = d.keys()
823 # Reverse it, so that the iteration implementation of __delitem__
824 # has to keep looping to find the first object we delete.
825 objs.reverse()
Tim Peters50d8b8b2003-05-25 17:44:31 +0000826
Tim Peters886128f2003-05-25 01:45:11 +0000827 # Turn on mutation in C.__eq__. The first time thru the loop,
828 # under the iterkeys() business the first comparison will delete
829 # the last item iterkeys() would see, and that causes a
830 # RuntimeError: dictionary changed size during iteration
831 # when the iterkeys() loop goes around to try comparing the next
Tim Peters50d8b8b2003-05-25 17:44:31 +0000832 # key. After this was fixed, it just deletes the last object *our*
Tim Peters886128f2003-05-25 01:45:11 +0000833 # "for o in obj" loop would have gotten to.
834 mutate = True
835 count = 0
836 for o in objs:
837 count += 1
838 del d[o]
839 self.assertEqual(len(d), 0)
840 self.assertEqual(count, 2)
841
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000842from test_userdict import TestMappingProtocol
843
844class WeakValueDictionaryTestCase(TestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +0000845 """Check that WeakValueDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000846 __ref = {"key1":Object(1), "key2":Object(2), "key3":Object(3)}
847 _tested_class = weakref.WeakValueDictionary
848 def _reference(self):
849 return self.__ref.copy()
850
851class WeakKeyDictionaryTestCase(TestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +0000852 """Check that WeakKeyDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000853 __ref = {Object("key1"):1, Object("key2"):2, Object("key3"):3}
854 _tested_class = weakref.WeakKeyDictionary
855 def _reference(self):
856 return self.__ref.copy()
Martin v. Löwis5e163332001-02-27 18:36:56 +0000857
Fred Drake2e2be372001-09-20 21:33:42 +0000858def test_main():
Walter Dörwald21d3a322003-05-01 17:45:56 +0000859 test_support.run_unittest(
860 ReferencesTestCase,
861 MappingTestCase,
862 WeakValueDictionaryTestCase,
Fred Drakef425b1e2003-07-14 21:37:17 +0000863 WeakKeyDictionaryTestCase,
864 )
Fred Drake2e2be372001-09-20 21:33:42 +0000865
866
867if __name__ == "__main__":
868 test_main()