blob: 34831f1f3dd783ad8be896740727ade984f3e5d9 [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
252 def test_getweakrefs(self):
253 o = C()
254 ref1 = weakref.ref(o, self.callback)
255 ref2 = weakref.ref(o, self.callback)
256 del ref1
257 self.assert_(weakref.getweakrefs(o) == [ref2],
258 "list of refs does not match")
259
260 o = C()
261 ref1 = weakref.ref(o, self.callback)
262 ref2 = weakref.ref(o, self.callback)
263 del ref2
264 self.assert_(weakref.getweakrefs(o) == [ref1],
265 "list of refs does not match")
266
Fred Drake39c27f12001-10-18 18:06:05 +0000267 def test_newstyle_number_ops(self):
268 class F(float):
269 pass
270 f = F(2.0)
271 p = weakref.proxy(f)
272 self.assert_(p + 1.0 == 3.0)
273 self.assert_(1.0 + p == 3.0) # this used to SEGV
274
Fred Drake2a64f462001-12-10 23:46:02 +0000275 def test_callbacks_protected(self):
Guido van Rossum9eee5542002-08-22 20:21:30 +0000276 # Callbacks protected from already-set exceptions?
Fred Drake2a64f462001-12-10 23:46:02 +0000277 # Regression test for SF bug #478534.
278 class BogusError(Exception):
279 pass
280 data = {}
281 def remove(k):
282 del data[k]
283 def encapsulate():
284 f = lambda : ()
285 data[weakref.ref(f, remove)] = None
286 raise BogusError
287 try:
288 encapsulate()
289 except BogusError:
290 pass
291 else:
292 self.fail("exception not properly restored")
293 try:
294 encapsulate()
295 except BogusError:
296 pass
297 else:
298 self.fail("exception not properly restored")
299
Tim Petersadd09b42003-11-12 20:43:28 +0000300 def test_sf_bug_840829(self):
301 # "weakref callbacks and gc corrupt memory"
302 # subtype_dealloc erroneously exposed a new-style instance
303 # already in the process of getting deallocated to gc,
304 # causing double-deallocation if the instance had a weakref
305 # callback that triggered gc.
306 # If the bug exists, there probably won't be an obvious symptom
307 # in a release build. In a debug build, a segfault will occur
308 # when the second attempt to remove the instance from the "list
309 # of all objects" occurs.
310
311 import gc
312
313 class C(object):
314 pass
315
316 c = C()
317 wr = weakref.ref(c, lambda ignore: gc.collect())
318 del c
319
Tim Petersf7f9e992003-11-13 21:59:32 +0000320 # There endeth the first part. It gets worse.
321 del wr
322
323 c1 = C()
324 c1.i = C()
325 wr = weakref.ref(c1.i, lambda ignore: gc.collect())
326
327 c2 = C()
328 c2.c1 = c1
329 del c1 # still alive because c2 points to it
330
331 # Now when subtype_dealloc gets called on c2, it's not enough just
332 # that c2 is immune from gc while the weakref callbacks associated
333 # with c2 execute (there are none in this 2nd half of the test, btw).
334 # subtype_dealloc goes on to call the base classes' deallocs too,
335 # so any gc triggered by weakref callbacks associated with anything
336 # torn down by a base class dealloc can also trigger double
337 # deallocation of c2.
338 del c2
Fred Drake41deb1e2001-02-01 05:27:45 +0000339
Tim Peters403a2032003-11-20 21:21:46 +0000340 def test_callback_in_cycle_1(self):
341 import gc
342
343 class J(object):
344 pass
345
346 class II(object):
347 def acallback(self, ignore):
348 self.J
349
350 I = II()
351 I.J = J
352 I.wr = weakref.ref(J, I.acallback)
353
354 # Now J and II are each in a self-cycle (as all new-style class
355 # objects are, since their __mro__ points back to them). I holds
356 # both a weak reference (I.wr) and a strong reference (I.J) to class
357 # J. I is also in a cycle (I.wr points to a weakref that references
358 # I.acallback). When we del these three, they all become trash, but
359 # the cycles prevent any of them from getting cleaned up immediately.
360 # Instead they have to wait for cyclic gc to deduce that they're
361 # trash.
362 #
363 # gc used to call tp_clear on all of them, and the order in which
364 # it does that is pretty accidental. The exact order in which we
365 # built up these things manages to provoke gc into running tp_clear
366 # in just the right order (I last). Calling tp_clear on II leaves
367 # behind an insane class object (its __mro__ becomes NULL). Calling
368 # tp_clear on J breaks its self-cycle, but J doesn't get deleted
369 # just then because of the strong reference from I.J. Calling
370 # tp_clear on I starts to clear I's __dict__, and just happens to
371 # clear I.J first -- I.wr is still intact. That removes the last
372 # reference to J, which triggers the weakref callback. The callback
373 # tries to do "self.J", and instances of new-style classes look up
374 # attributes ("J") in the class dict first. The class (II) wants to
375 # search II.__mro__, but that's NULL. The result was a segfault in
376 # a release build, and an assert failure in a debug build.
377 del I, J, II
378 gc.collect()
379
380 def test_callback_in_cycle_2(self):
381 import gc
382
383 # This is just like test_callback_in_cycle_1, except that II is an
384 # old-style class. The symptom is different then: an instance of an
385 # old-style class looks in its own __dict__ first. 'J' happens to
386 # get cleared from I.__dict__ before 'wr', and 'J' was never in II's
387 # __dict__, so the attribute isn't found. The difference is that
388 # the old-style II doesn't have a NULL __mro__ (it doesn't have any
389 # __mro__), so no segfault occurs. Instead it got:
390 # test_callback_in_cycle_2 (__main__.ReferencesTestCase) ...
391 # Exception exceptions.AttributeError:
392 # "II instance has no attribute 'J'" in <bound method II.acallback
393 # of <?.II instance at 0x00B9B4B8>> ignored
394
395 class J(object):
396 pass
397
398 class II:
399 def acallback(self, ignore):
400 self.J
401
402 I = II()
403 I.J = J
404 I.wr = weakref.ref(J, I.acallback)
405
406 del I, J, II
407 gc.collect()
408
409 def test_callback_in_cycle_3(self):
410 import gc
411
412 # This one broke the first patch that fixed the last two. In this
413 # case, the objects reachable from the callback aren't also reachable
414 # from the object (c1) *triggering* the callback: you can get to
415 # c1 from c2, but not vice-versa. The result was that c2's __dict__
416 # got tp_clear'ed by the time the c2.cb callback got invoked.
417
418 class C:
419 def cb(self, ignore):
420 self.me
421 self.c1
422 self.wr
423
424 c1, c2 = C(), C()
425
426 c2.me = c2
427 c2.c1 = c1
428 c2.wr = weakref.ref(c1, c2.cb)
429
430 del c1, c2
431 gc.collect()
432
433 def test_callback_in_cycle_4(self):
434 import gc
435
436 # Like test_callback_in_cycle_3, except c2 and c1 have different
437 # classes. c2's class (C) isn't reachable from c1 then, so protecting
438 # objects reachable from the dying object (c1) isn't enough to stop
439 # c2's class (C) from getting tp_clear'ed before c2.cb is invoked.
440 # The result was a segfault (C.__mro__ was NULL when the callback
441 # tried to look up self.me).
442
443 class C(object):
444 def cb(self, ignore):
445 self.me
446 self.c1
447 self.wr
448
449 class D:
450 pass
451
452 c1, c2 = D(), C()
453
454 c2.me = c2
455 c2.c1 = c1
456 c2.wr = weakref.ref(c1, c2.cb)
457
458 del c1, c2, C, D
459 gc.collect()
460
461 def test_callback_in_cycle_resurrection(self):
462 import gc
463
464 # Do something nasty in a weakref callback: resurrect objects
465 # from dead cycles. For this to be attempted, the weakref and
466 # its callback must also be part of the cyclic trash (else the
467 # objects reachable via the callback couldn't be in cyclic trash
468 # to begin with -- the callback would act like an external root).
469 # But gc clears trash weakrefs with callbacks early now, which
470 # disables the callbacks, so the callbacks shouldn't get called
471 # at all (and so nothing actually gets resurrected).
472
473 alist = []
474 class C(object):
475 def __init__(self, value):
476 self.attribute = value
477
478 def acallback(self, ignore):
479 alist.append(self.c)
480
481 c1, c2 = C(1), C(2)
482 c1.c = c2
483 c2.c = c1
484 c1.wr = weakref.ref(c2, c1.acallback)
485 c2.wr = weakref.ref(c1, c2.acallback)
486
487 def C_went_away(ignore):
488 alist.append("C went away")
489 wr = weakref.ref(C, C_went_away)
490
491 del c1, c2, C # make them all trash
492 self.assertEqual(alist, []) # del isn't enough to reclaim anything
493
494 gc.collect()
495 # c1.wr and c2.wr were part of the cyclic trash, so should have
496 # been cleared without their callbacks executing. OTOH, the weakref
497 # to C is bound to a function local (wr), and wasn't trash, so that
498 # callback should have been invoked when C went away.
499 self.assertEqual(alist, ["C went away"])
500 # The remaining weakref should be dead now (its callback ran).
501 self.assertEqual(wr(), None)
502
503 del alist[:]
504 gc.collect()
505 self.assertEqual(alist, [])
506
507 def test_callbacks_on_callback(self):
508 import gc
509
510 # Set up weakref callbacks *on* weakref callbacks.
511 alist = []
512 def safe_callback(ignore):
513 alist.append("safe_callback called")
514
515 class C(object):
516 def cb(self, ignore):
517 alist.append("cb called")
518
519 c, d = C(), C()
520 c.other = d
521 d.other = c
522 callback = c.cb
523 c.wr = weakref.ref(d, callback) # this won't trigger
524 d.wr = weakref.ref(callback, d.cb) # ditto
525 external_wr = weakref.ref(callback, safe_callback) # but this will
526 self.assert_(external_wr() is callback)
527
528 # The weakrefs attached to c and d should get cleared, so that
529 # C.cb is never called. But external_wr isn't part of the cyclic
530 # trash, and no cyclic trash is reachable from it, so safe_callback
531 # should get invoked when the bound method object callback (c.cb)
532 # -- which is itself a callback, and also part of the cyclic trash --
533 # gets reclaimed at the end of gc.
534
535 del callback, c, d, C
536 self.assertEqual(alist, []) # del isn't enough to clean up cycles
537 gc.collect()
538 self.assertEqual(alist, ["safe_callback called"])
539 self.assertEqual(external_wr(), None)
540
541 del alist[:]
542 gc.collect()
543 self.assertEqual(alist, [])
544
Fred Drake41deb1e2001-02-01 05:27:45 +0000545class Object:
546 def __init__(self, arg):
547 self.arg = arg
548 def __repr__(self):
549 return "<Object %r>" % self.arg
550
Fred Drake41deb1e2001-02-01 05:27:45 +0000551
Fred Drakeb0fefc52001-03-23 04:22:45 +0000552class MappingTestCase(TestBase):
Martin v. Löwis5e163332001-02-27 18:36:56 +0000553
Fred Drakeb0fefc52001-03-23 04:22:45 +0000554 COUNT = 10
555
556 def test_weak_values(self):
Fred Drake0e540c32001-05-02 05:44:22 +0000557 #
558 # This exercises d.copy(), d.items(), d[], del d[], len(d).
559 #
560 dict, objects = self.make_weak_valued_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +0000561 for o in objects:
562 self.assert_(weakref.getweakrefcount(o) == 1,
563 "wrong number of weak references to %r!" % o)
564 self.assert_(o is dict[o.arg],
565 "wrong object returned by weak dict!")
566 items1 = dict.items()
567 items2 = dict.copy().items()
568 items1.sort()
569 items2.sort()
570 self.assert_(items1 == items2,
571 "cloning of weak-valued dictionary did not work!")
572 del items1, items2
573 self.assert_(len(dict) == self.COUNT)
574 del objects[0]
575 self.assert_(len(dict) == (self.COUNT - 1),
576 "deleting object did not cause dictionary update")
577 del objects, o
578 self.assert_(len(dict) == 0,
579 "deleting the values did not clear the dictionary")
Fred Drake4fd06e02001-08-03 04:11:27 +0000580 # regression on SF bug #447152:
581 dict = weakref.WeakValueDictionary()
582 self.assertRaises(KeyError, dict.__getitem__, 1)
583 dict[2] = C()
584 self.assertRaises(KeyError, dict.__getitem__, 2)
Fred Drakeb0fefc52001-03-23 04:22:45 +0000585
586 def test_weak_keys(self):
Fred Drake0e540c32001-05-02 05:44:22 +0000587 #
588 # This exercises d.copy(), d.items(), d[] = v, d[], del d[],
Fred Drake752eda42001-11-06 16:38:34 +0000589 # len(d), d.has_key().
Fred Drake0e540c32001-05-02 05:44:22 +0000590 #
591 dict, objects = self.make_weak_keyed_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +0000592 for o in objects:
593 self.assert_(weakref.getweakrefcount(o) == 1,
594 "wrong number of weak references to %r!" % o)
595 self.assert_(o.arg is dict[o],
596 "wrong object returned by weak dict!")
597 items1 = dict.items()
598 items2 = dict.copy().items()
Raymond Hettingera690a992003-11-16 16:17:49 +0000599 self.assert_(set(items1) == set(items2),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000600 "cloning of weak-keyed dictionary did not work!")
601 del items1, items2
602 self.assert_(len(dict) == self.COUNT)
603 del objects[0]
604 self.assert_(len(dict) == (self.COUNT - 1),
605 "deleting object did not cause dictionary update")
606 del objects, o
607 self.assert_(len(dict) == 0,
608 "deleting the keys did not clear the dictionary")
Fred Drake752eda42001-11-06 16:38:34 +0000609 o = Object(42)
610 dict[o] = "What is the meaning of the universe?"
611 self.assert_(dict.has_key(o))
612 self.assert_(not dict.has_key(34))
Martin v. Löwis5e163332001-02-27 18:36:56 +0000613
Fred Drake0e540c32001-05-02 05:44:22 +0000614 def test_weak_keyed_iters(self):
615 dict, objects = self.make_weak_keyed_dict()
616 self.check_iters(dict)
617
618 def test_weak_valued_iters(self):
619 dict, objects = self.make_weak_valued_dict()
620 self.check_iters(dict)
621
622 def check_iters(self, dict):
623 # item iterator:
624 items = dict.items()
625 for item in dict.iteritems():
626 items.remove(item)
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000627 self.assert_(len(items) == 0, "iteritems() did not touch all items")
Fred Drake0e540c32001-05-02 05:44:22 +0000628
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000629 # key iterator, via __iter__():
Fred Drake0e540c32001-05-02 05:44:22 +0000630 keys = dict.keys()
631 for k in dict:
632 keys.remove(k)
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000633 self.assert_(len(keys) == 0, "__iter__() did not touch all keys")
634
635 # key iterator, via iterkeys():
636 keys = dict.keys()
637 for k in dict.iterkeys():
638 keys.remove(k)
639 self.assert_(len(keys) == 0, "iterkeys() did not touch all keys")
Fred Drake0e540c32001-05-02 05:44:22 +0000640
641 # value iterator:
642 values = dict.values()
643 for v in dict.itervalues():
644 values.remove(v)
Fred Drakef425b1e2003-07-14 21:37:17 +0000645 self.assert_(len(values) == 0,
646 "itervalues() did not touch all values")
Fred Drake0e540c32001-05-02 05:44:22 +0000647
Guido van Rossum009afb72002-06-10 20:00:52 +0000648 def test_make_weak_keyed_dict_from_dict(self):
649 o = Object(3)
650 dict = weakref.WeakKeyDictionary({o:364})
651 self.assert_(dict[o] == 364)
652
653 def test_make_weak_keyed_dict_from_weak_keyed_dict(self):
654 o = Object(3)
655 dict = weakref.WeakKeyDictionary({o:364})
656 dict2 = weakref.WeakKeyDictionary(dict)
657 self.assert_(dict[o] == 364)
658
Fred Drake0e540c32001-05-02 05:44:22 +0000659 def make_weak_keyed_dict(self):
660 dict = weakref.WeakKeyDictionary()
661 objects = map(Object, range(self.COUNT))
662 for o in objects:
663 dict[o] = o.arg
664 return dict, objects
665
666 def make_weak_valued_dict(self):
667 dict = weakref.WeakValueDictionary()
668 objects = map(Object, range(self.COUNT))
669 for o in objects:
670 dict[o.arg] = o
671 return dict, objects
672
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000673 def check_popitem(self, klass, key1, value1, key2, value2):
674 weakdict = klass()
675 weakdict[key1] = value1
676 weakdict[key2] = value2
677 self.assert_(len(weakdict) == 2)
678 k, v = weakdict.popitem()
679 self.assert_(len(weakdict) == 1)
680 if k is key1:
681 self.assert_(v is value1)
682 else:
683 self.assert_(v is value2)
684 k, v = weakdict.popitem()
685 self.assert_(len(weakdict) == 0)
686 if k is key1:
687 self.assert_(v is value1)
688 else:
689 self.assert_(v is value2)
690
691 def test_weak_valued_dict_popitem(self):
692 self.check_popitem(weakref.WeakValueDictionary,
693 "key1", C(), "key2", C())
694
695 def test_weak_keyed_dict_popitem(self):
696 self.check_popitem(weakref.WeakKeyDictionary,
697 C(), "value 1", C(), "value 2")
698
699 def check_setdefault(self, klass, key, value1, value2):
700 self.assert_(value1 is not value2,
701 "invalid test"
702 " -- value parameters must be distinct objects")
703 weakdict = klass()
704 o = weakdict.setdefault(key, value1)
705 self.assert_(o is value1)
706 self.assert_(weakdict.has_key(key))
707 self.assert_(weakdict.get(key) is value1)
708 self.assert_(weakdict[key] is value1)
709
710 o = weakdict.setdefault(key, value2)
711 self.assert_(o is value1)
712 self.assert_(weakdict.has_key(key))
713 self.assert_(weakdict.get(key) is value1)
714 self.assert_(weakdict[key] is value1)
715
716 def test_weak_valued_dict_setdefault(self):
717 self.check_setdefault(weakref.WeakValueDictionary,
718 "key", C(), C())
719
720 def test_weak_keyed_dict_setdefault(self):
721 self.check_setdefault(weakref.WeakKeyDictionary,
722 C(), "value 1", "value 2")
723
Fred Drakea0a4ab12001-04-16 17:37:27 +0000724 def check_update(self, klass, dict):
Fred Drake0e540c32001-05-02 05:44:22 +0000725 #
726 # This exercises d.update(), len(d), d.keys(), d.has_key(),
727 # d.get(), d[].
728 #
Fred Drakea0a4ab12001-04-16 17:37:27 +0000729 weakdict = klass()
730 weakdict.update(dict)
731 self.assert_(len(weakdict) == len(dict))
732 for k in weakdict.keys():
733 self.assert_(dict.has_key(k),
734 "mysterious new key appeared in weak dict")
735 v = dict.get(k)
736 self.assert_(v is weakdict[k])
737 self.assert_(v is weakdict.get(k))
738 for k in dict.keys():
739 self.assert_(weakdict.has_key(k),
740 "original key disappeared in weak dict")
741 v = dict[k]
742 self.assert_(v is weakdict[k])
743 self.assert_(v is weakdict.get(k))
744
745 def test_weak_valued_dict_update(self):
746 self.check_update(weakref.WeakValueDictionary,
747 {1: C(), 'a': C(), C(): C()})
748
749 def test_weak_keyed_dict_update(self):
750 self.check_update(weakref.WeakKeyDictionary,
751 {C(): 1, C(): 2, C(): 3})
752
Fred Drakeccc75622001-09-06 14:52:39 +0000753 def test_weak_keyed_delitem(self):
754 d = weakref.WeakKeyDictionary()
755 o1 = Object('1')
756 o2 = Object('2')
757 d[o1] = 'something'
758 d[o2] = 'something'
759 self.assert_(len(d) == 2)
760 del d[o1]
761 self.assert_(len(d) == 1)
762 self.assert_(d.keys() == [o2])
763
764 def test_weak_valued_delitem(self):
765 d = weakref.WeakValueDictionary()
766 o1 = Object('1')
767 o2 = Object('2')
768 d['something'] = o1
769 d['something else'] = o2
770 self.assert_(len(d) == 2)
771 del d['something']
772 self.assert_(len(d) == 1)
773 self.assert_(d.items() == [('something else', o2)])
774
Tim Peters886128f2003-05-25 01:45:11 +0000775 def test_weak_keyed_bad_delitem(self):
776 d = weakref.WeakKeyDictionary()
777 o = Object('1')
778 # An attempt to delete an object that isn't there should raise
Tim Peters50d8b8b2003-05-25 17:44:31 +0000779 # KeyError. It didn't before 2.3.
Tim Peters886128f2003-05-25 01:45:11 +0000780 self.assertRaises(KeyError, d.__delitem__, o)
Tim Peters50d8b8b2003-05-25 17:44:31 +0000781 self.assertRaises(KeyError, d.__getitem__, o)
782
783 # If a key isn't of a weakly referencable type, __getitem__ and
784 # __setitem__ raise TypeError. __delitem__ should too.
785 self.assertRaises(TypeError, d.__delitem__, 13)
786 self.assertRaises(TypeError, d.__getitem__, 13)
787 self.assertRaises(TypeError, d.__setitem__, 13, 13)
Tim Peters886128f2003-05-25 01:45:11 +0000788
789 def test_weak_keyed_cascading_deletes(self):
790 # SF bug 742860. For some reason, before 2.3 __delitem__ iterated
791 # over the keys via self.data.iterkeys(). If things vanished from
792 # the dict during this (or got added), that caused a RuntimeError.
793
794 d = weakref.WeakKeyDictionary()
795 mutate = False
796
797 class C(object):
798 def __init__(self, i):
799 self.value = i
800 def __hash__(self):
801 return hash(self.value)
802 def __eq__(self, other):
803 if mutate:
804 # Side effect that mutates the dict, by removing the
805 # last strong reference to a key.
806 del objs[-1]
807 return self.value == other.value
808
809 objs = [C(i) for i in range(4)]
810 for o in objs:
811 d[o] = o.value
812 del o # now the only strong references to keys are in objs
813 # Find the order in which iterkeys sees the keys.
814 objs = d.keys()
815 # Reverse it, so that the iteration implementation of __delitem__
816 # has to keep looping to find the first object we delete.
817 objs.reverse()
Tim Peters50d8b8b2003-05-25 17:44:31 +0000818
Tim Peters886128f2003-05-25 01:45:11 +0000819 # Turn on mutation in C.__eq__. The first time thru the loop,
820 # under the iterkeys() business the first comparison will delete
821 # the last item iterkeys() would see, and that causes a
822 # RuntimeError: dictionary changed size during iteration
823 # when the iterkeys() loop goes around to try comparing the next
Tim Peters50d8b8b2003-05-25 17:44:31 +0000824 # key. After this was fixed, it just deletes the last object *our*
Tim Peters886128f2003-05-25 01:45:11 +0000825 # "for o in obj" loop would have gotten to.
826 mutate = True
827 count = 0
828 for o in objs:
829 count += 1
830 del d[o]
831 self.assertEqual(len(d), 0)
832 self.assertEqual(count, 2)
833
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000834from test_userdict import TestMappingProtocol
835
836class WeakValueDictionaryTestCase(TestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +0000837 """Check that WeakValueDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000838 __ref = {"key1":Object(1), "key2":Object(2), "key3":Object(3)}
839 _tested_class = weakref.WeakValueDictionary
840 def _reference(self):
841 return self.__ref.copy()
842
843class WeakKeyDictionaryTestCase(TestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +0000844 """Check that WeakKeyDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000845 __ref = {Object("key1"):1, Object("key2"):2, Object("key3"):3}
846 _tested_class = weakref.WeakKeyDictionary
847 def _reference(self):
848 return self.__ref.copy()
Martin v. Löwis5e163332001-02-27 18:36:56 +0000849
Fred Drake2e2be372001-09-20 21:33:42 +0000850def test_main():
Walter Dörwald21d3a322003-05-01 17:45:56 +0000851 test_support.run_unittest(
852 ReferencesTestCase,
853 MappingTestCase,
854 WeakValueDictionaryTestCase,
Fred Drakef425b1e2003-07-14 21:37:17 +0000855 WeakKeyDictionaryTestCase,
856 )
Fred Drake2e2be372001-09-20 21:33:42 +0000857
858
859if __name__ == "__main__":
860 test_main()