Fred Drake | bc875f5 | 2004-02-04 23:14:14 +0000 | [diff] [blame] | 1 | import gc |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 2 | import sys |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 3 | import unittest |
Fred Drake | 5935ff0 | 2001-12-19 16:54:23 +0000 | [diff] [blame] | 4 | import UserList |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 5 | import weakref |
| 6 | |
Barry Warsaw | 04f357c | 2002-07-23 19:04:11 +0000 | [diff] [blame] | 7 | from test import test_support |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 8 | |
| 9 | |
| 10 | class C: |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 11 | def method(self): |
| 12 | pass |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 13 | |
| 14 | |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 15 | class Callable: |
| 16 | bar = None |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 17 | |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 18 | def __call__(self, x): |
| 19 | self.bar = x |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 20 | |
| 21 | |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 22 | def create_function(): |
| 23 | def f(): pass |
| 24 | return f |
| 25 | |
| 26 | def create_bound_method(): |
| 27 | return C().method |
| 28 | |
| 29 | def create_unbound_method(): |
| 30 | return C.method |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 31 | |
| 32 | |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 33 | class TestBase(unittest.TestCase): |
| 34 | |
| 35 | def setUp(self): |
| 36 | self.cbcalled = 0 |
| 37 | |
| 38 | def callback(self, ref): |
| 39 | self.cbcalled += 1 |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 40 | |
| 41 | |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 42 | class ReferencesTestCase(TestBase): |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 43 | |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 44 | def test_basic_ref(self): |
| 45 | self.check_basic_ref(C) |
| 46 | self.check_basic_ref(create_function) |
| 47 | self.check_basic_ref(create_bound_method) |
| 48 | self.check_basic_ref(create_unbound_method) |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 49 | |
Fred Drake | 43735da | 2002-04-11 03:59:42 +0000 | [diff] [blame] | 50 | # Just make sure the tp_repr handler doesn't raise an exception. |
| 51 | # Live reference: |
| 52 | o = C() |
| 53 | wr = weakref.ref(o) |
| 54 | `wr` |
| 55 | # Dead reference: |
| 56 | del o |
| 57 | `wr` |
| 58 | |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 59 | def test_basic_callback(self): |
| 60 | self.check_basic_callback(C) |
| 61 | self.check_basic_callback(create_function) |
| 62 | self.check_basic_callback(create_bound_method) |
| 63 | self.check_basic_callback(create_unbound_method) |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 64 | |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 65 | def test_multiple_callbacks(self): |
| 66 | o = C() |
| 67 | ref1 = weakref.ref(o, self.callback) |
| 68 | ref2 = weakref.ref(o, self.callback) |
| 69 | del o |
| 70 | self.assert_(ref1() is None, |
| 71 | "expected reference to be invalidated") |
| 72 | self.assert_(ref2() is None, |
| 73 | "expected reference to be invalidated") |
| 74 | self.assert_(self.cbcalled == 2, |
| 75 | "callback not called the right number of times") |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 76 | |
Fred Drake | 705088e | 2001-04-13 17:18:15 +0000 | [diff] [blame] | 77 | def test_multiple_selfref_callbacks(self): |
Guido van Rossum | 9eee554 | 2002-08-22 20:21:30 +0000 | [diff] [blame] | 78 | # Make sure all references are invalidated before callbacks are called |
Fred Drake | 705088e | 2001-04-13 17:18:15 +0000 | [diff] [blame] | 79 | # |
| 80 | # What's important here is that we're using the first |
| 81 | # reference in the callback invoked on the second reference |
| 82 | # (the most recently created ref is cleaned up first). This |
| 83 | # tests that all references to the object are invalidated |
| 84 | # before any of the callbacks are invoked, so that we only |
| 85 | # have one invocation of _weakref.c:cleanup_helper() active |
| 86 | # for a particular object at a time. |
| 87 | # |
| 88 | def callback(object, self=self): |
| 89 | self.ref() |
| 90 | c = C() |
| 91 | self.ref = weakref.ref(c, callback) |
| 92 | ref1 = weakref.ref(c, callback) |
| 93 | del c |
| 94 | |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 95 | def test_proxy_ref(self): |
| 96 | o = C() |
| 97 | o.bar = 1 |
| 98 | ref1 = weakref.proxy(o, self.callback) |
| 99 | ref2 = weakref.proxy(o, self.callback) |
| 100 | del o |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 101 | |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 102 | def check(proxy): |
| 103 | proxy.bar |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 104 | |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 105 | self.assertRaises(weakref.ReferenceError, check, ref1) |
| 106 | self.assertRaises(weakref.ReferenceError, check, ref2) |
Neal Norwitz | bdcb941 | 2004-07-08 01:22:31 +0000 | [diff] [blame] | 107 | self.assertRaises(weakref.ReferenceError, bool, weakref.proxy(C())) |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 108 | self.assert_(self.cbcalled == 2) |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 109 | |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 110 | def check_basic_ref(self, factory): |
| 111 | o = factory() |
| 112 | ref = weakref.ref(o) |
| 113 | self.assert_(ref() is not None, |
| 114 | "weak reference to live object should be live") |
| 115 | o2 = ref() |
| 116 | self.assert_(o is o2, |
| 117 | "<ref>() should return original object if live") |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 118 | |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 119 | def check_basic_callback(self, factory): |
| 120 | self.cbcalled = 0 |
| 121 | o = factory() |
| 122 | ref = weakref.ref(o, self.callback) |
| 123 | del o |
Fred Drake | 705088e | 2001-04-13 17:18:15 +0000 | [diff] [blame] | 124 | self.assert_(self.cbcalled == 1, |
| 125 | "callback did not properly set 'cbcalled'") |
| 126 | self.assert_(ref() is None, |
| 127 | "ref2 should be dead after deleting object reference") |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 128 | |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 129 | def test_ref_reuse(self): |
| 130 | o = C() |
| 131 | ref1 = weakref.ref(o) |
| 132 | # create a proxy to make sure that there's an intervening creation |
| 133 | # between these two; it should make no difference |
| 134 | proxy = weakref.proxy(o) |
| 135 | ref2 = weakref.ref(o) |
| 136 | self.assert_(ref1 is ref2, |
| 137 | "reference object w/out callback should be re-used") |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 138 | |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 139 | o = C() |
| 140 | proxy = weakref.proxy(o) |
| 141 | ref1 = weakref.ref(o) |
| 142 | ref2 = weakref.ref(o) |
| 143 | self.assert_(ref1 is ref2, |
| 144 | "reference object w/out callback should be re-used") |
| 145 | self.assert_(weakref.getweakrefcount(o) == 2, |
| 146 | "wrong weak ref count for object") |
| 147 | del proxy |
| 148 | self.assert_(weakref.getweakrefcount(o) == 1, |
| 149 | "wrong weak ref count for object after deleting proxy") |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 150 | |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 151 | def test_proxy_reuse(self): |
| 152 | o = C() |
| 153 | proxy1 = weakref.proxy(o) |
| 154 | ref = weakref.ref(o) |
| 155 | proxy2 = weakref.proxy(o) |
| 156 | self.assert_(proxy1 is proxy2, |
| 157 | "proxy object w/out callback should have been re-used") |
| 158 | |
| 159 | def test_basic_proxy(self): |
| 160 | o = C() |
| 161 | self.check_proxy(o, weakref.proxy(o)) |
| 162 | |
Fred Drake | 5935ff0 | 2001-12-19 16:54:23 +0000 | [diff] [blame] | 163 | L = UserList.UserList() |
| 164 | p = weakref.proxy(L) |
| 165 | self.failIf(p, "proxy for empty UserList should be false") |
| 166 | p.append(12) |
| 167 | self.assertEqual(len(L), 1) |
| 168 | self.failUnless(p, "proxy for non-empty UserList should be true") |
| 169 | p[:] = [2, 3] |
| 170 | self.assertEqual(len(L), 2) |
| 171 | self.assertEqual(len(p), 2) |
Fred Drake | f425b1e | 2003-07-14 21:37:17 +0000 | [diff] [blame] | 172 | self.failUnless(3 in p, |
| 173 | "proxy didn't support __contains__() properly") |
Fred Drake | 5935ff0 | 2001-12-19 16:54:23 +0000 | [diff] [blame] | 174 | p[1] = 5 |
| 175 | self.assertEqual(L[1], 5) |
| 176 | self.assertEqual(p[1], 5) |
| 177 | L2 = UserList.UserList(L) |
| 178 | p2 = weakref.proxy(L2) |
| 179 | self.assertEqual(p, p2) |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 180 | ## self.assertEqual(repr(L2), repr(p2)) |
Fred Drake | 43735da | 2002-04-11 03:59:42 +0000 | [diff] [blame] | 181 | L3 = UserList.UserList(range(10)) |
| 182 | p3 = weakref.proxy(L3) |
| 183 | self.assertEqual(L3[:], p3[:]) |
| 184 | self.assertEqual(L3[5:], p3[5:]) |
| 185 | self.assertEqual(L3[:5], p3[:5]) |
| 186 | self.assertEqual(L3[2:5], p3[2:5]) |
Fred Drake | 5935ff0 | 2001-12-19 16:54:23 +0000 | [diff] [blame] | 187 | |
Fred Drake | ea2adc9 | 2004-02-03 19:56:46 +0000 | [diff] [blame] | 188 | # The PyWeakref_* C API is documented as allowing either NULL or |
| 189 | # None as the value for the callback, where either means "no |
| 190 | # callback". The "no callback" ref and proxy objects are supposed |
| 191 | # to be shared so long as they exist by all callers so long as |
| 192 | # they are active. In Python 2.3.3 and earlier, this guaranttee |
| 193 | # was not honored, and was broken in different ways for |
| 194 | # PyWeakref_NewRef() and PyWeakref_NewProxy(). (Two tests.) |
| 195 | |
| 196 | def test_shared_ref_without_callback(self): |
| 197 | self.check_shared_without_callback(weakref.ref) |
| 198 | |
| 199 | def test_shared_proxy_without_callback(self): |
| 200 | self.check_shared_without_callback(weakref.proxy) |
| 201 | |
| 202 | def check_shared_without_callback(self, makeref): |
| 203 | o = Object(1) |
| 204 | p1 = makeref(o, None) |
| 205 | p2 = makeref(o, None) |
| 206 | self.assert_(p1 is p2, "both callbacks were None in the C API") |
| 207 | del p1, p2 |
| 208 | p1 = makeref(o) |
| 209 | p2 = makeref(o, None) |
| 210 | self.assert_(p1 is p2, "callbacks were NULL, None in the C API") |
| 211 | del p1, p2 |
| 212 | p1 = makeref(o) |
| 213 | p2 = makeref(o) |
| 214 | self.assert_(p1 is p2, "both callbacks were NULL in the C API") |
| 215 | del p1, p2 |
| 216 | p1 = makeref(o, None) |
| 217 | p2 = makeref(o) |
| 218 | self.assert_(p1 is p2, "callbacks were None, NULL in the C API") |
| 219 | |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 220 | def test_callable_proxy(self): |
| 221 | o = Callable() |
| 222 | ref1 = weakref.proxy(o) |
| 223 | |
| 224 | self.check_proxy(o, ref1) |
| 225 | |
| 226 | self.assert_(type(ref1) is weakref.CallableProxyType, |
| 227 | "proxy is not of callable type") |
| 228 | ref1('twinkies!') |
| 229 | self.assert_(o.bar == 'twinkies!', |
| 230 | "call through proxy not passed through to original") |
Fred Drake | 3bb4d21 | 2001-10-18 19:28:29 +0000 | [diff] [blame] | 231 | ref1(x='Splat.') |
| 232 | self.assert_(o.bar == 'Splat.', |
| 233 | "call through proxy not passed through to original") |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 234 | |
| 235 | # expect due to too few args |
| 236 | self.assertRaises(TypeError, ref1) |
| 237 | |
| 238 | # expect due to too many args |
| 239 | self.assertRaises(TypeError, ref1, 1, 2, 3) |
| 240 | |
| 241 | def check_proxy(self, o, proxy): |
| 242 | o.foo = 1 |
| 243 | self.assert_(proxy.foo == 1, |
| 244 | "proxy does not reflect attribute addition") |
| 245 | o.foo = 2 |
| 246 | self.assert_(proxy.foo == 2, |
| 247 | "proxy does not reflect attribute modification") |
| 248 | del o.foo |
| 249 | self.assert_(not hasattr(proxy, 'foo'), |
| 250 | "proxy does not reflect attribute removal") |
| 251 | |
| 252 | proxy.foo = 1 |
| 253 | self.assert_(o.foo == 1, |
| 254 | "object does not reflect attribute addition via proxy") |
| 255 | proxy.foo = 2 |
| 256 | self.assert_( |
| 257 | o.foo == 2, |
| 258 | "object does not reflect attribute modification via proxy") |
| 259 | del proxy.foo |
| 260 | self.assert_(not hasattr(o, 'foo'), |
| 261 | "object does not reflect attribute removal via proxy") |
| 262 | |
Raymond Hettinger | d693a81 | 2003-06-30 04:18:48 +0000 | [diff] [blame] | 263 | def test_proxy_deletion(self): |
| 264 | # Test clearing of SF bug #762891 |
| 265 | class Foo: |
| 266 | result = None |
| 267 | def __delitem__(self, accessor): |
| 268 | self.result = accessor |
| 269 | g = Foo() |
| 270 | f = weakref.proxy(g) |
| 271 | del f[0] |
| 272 | self.assertEqual(f.result, 0) |
| 273 | |
Raymond Hettinger | e6c470f | 2005-03-27 03:04:54 +0000 | [diff] [blame] | 274 | def test_proxy_bool(self): |
| 275 | # Test clearing of SF bug #1170766 |
| 276 | class List(list): pass |
| 277 | lyst = List() |
| 278 | self.assertEqual(bool(weakref.proxy(lyst)), bool(lyst)) |
| 279 | |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 280 | def test_getweakrefcount(self): |
| 281 | o = C() |
| 282 | ref1 = weakref.ref(o) |
| 283 | ref2 = weakref.ref(o, self.callback) |
| 284 | self.assert_(weakref.getweakrefcount(o) == 2, |
| 285 | "got wrong number of weak reference objects") |
| 286 | |
| 287 | proxy1 = weakref.proxy(o) |
| 288 | proxy2 = weakref.proxy(o, self.callback) |
| 289 | self.assert_(weakref.getweakrefcount(o) == 4, |
| 290 | "got wrong number of weak reference objects") |
| 291 | |
Fred Drake | ea2adc9 | 2004-02-03 19:56:46 +0000 | [diff] [blame] | 292 | del ref1, ref2, proxy1, proxy2 |
| 293 | self.assert_(weakref.getweakrefcount(o) == 0, |
| 294 | "weak reference objects not unlinked from" |
| 295 | " referent when discarded.") |
| 296 | |
Walter Dörwald | b167b04 | 2003-12-11 12:34:05 +0000 | [diff] [blame] | 297 | # assumes ints do not support weakrefs |
| 298 | self.assert_(weakref.getweakrefcount(1) == 0, |
| 299 | "got wrong number of weak reference objects for int") |
| 300 | |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 301 | def test_getweakrefs(self): |
| 302 | o = C() |
| 303 | ref1 = weakref.ref(o, self.callback) |
| 304 | ref2 = weakref.ref(o, self.callback) |
| 305 | del ref1 |
| 306 | self.assert_(weakref.getweakrefs(o) == [ref2], |
| 307 | "list of refs does not match") |
| 308 | |
| 309 | o = C() |
| 310 | ref1 = weakref.ref(o, self.callback) |
| 311 | ref2 = weakref.ref(o, self.callback) |
| 312 | del ref2 |
| 313 | self.assert_(weakref.getweakrefs(o) == [ref1], |
| 314 | "list of refs does not match") |
| 315 | |
Fred Drake | ea2adc9 | 2004-02-03 19:56:46 +0000 | [diff] [blame] | 316 | del ref1 |
| 317 | self.assert_(weakref.getweakrefs(o) == [], |
| 318 | "list of refs not cleared") |
| 319 | |
Walter Dörwald | b167b04 | 2003-12-11 12:34:05 +0000 | [diff] [blame] | 320 | # assumes ints do not support weakrefs |
| 321 | self.assert_(weakref.getweakrefs(1) == [], |
| 322 | "list of refs does not match for int") |
| 323 | |
Fred Drake | 39c27f1 | 2001-10-18 18:06:05 +0000 | [diff] [blame] | 324 | def test_newstyle_number_ops(self): |
| 325 | class F(float): |
| 326 | pass |
| 327 | f = F(2.0) |
| 328 | p = weakref.proxy(f) |
| 329 | self.assert_(p + 1.0 == 3.0) |
| 330 | self.assert_(1.0 + p == 3.0) # this used to SEGV |
| 331 | |
Fred Drake | 2a64f46 | 2001-12-10 23:46:02 +0000 | [diff] [blame] | 332 | def test_callbacks_protected(self): |
Guido van Rossum | 9eee554 | 2002-08-22 20:21:30 +0000 | [diff] [blame] | 333 | # Callbacks protected from already-set exceptions? |
Fred Drake | 2a64f46 | 2001-12-10 23:46:02 +0000 | [diff] [blame] | 334 | # Regression test for SF bug #478534. |
| 335 | class BogusError(Exception): |
| 336 | pass |
| 337 | data = {} |
| 338 | def remove(k): |
| 339 | del data[k] |
| 340 | def encapsulate(): |
| 341 | f = lambda : () |
| 342 | data[weakref.ref(f, remove)] = None |
| 343 | raise BogusError |
| 344 | try: |
| 345 | encapsulate() |
| 346 | except BogusError: |
| 347 | pass |
| 348 | else: |
| 349 | self.fail("exception not properly restored") |
| 350 | try: |
| 351 | encapsulate() |
| 352 | except BogusError: |
| 353 | pass |
| 354 | else: |
| 355 | self.fail("exception not properly restored") |
| 356 | |
Tim Peters | add09b4 | 2003-11-12 20:43:28 +0000 | [diff] [blame] | 357 | def test_sf_bug_840829(self): |
| 358 | # "weakref callbacks and gc corrupt memory" |
| 359 | # subtype_dealloc erroneously exposed a new-style instance |
| 360 | # already in the process of getting deallocated to gc, |
| 361 | # causing double-deallocation if the instance had a weakref |
| 362 | # callback that triggered gc. |
| 363 | # If the bug exists, there probably won't be an obvious symptom |
| 364 | # in a release build. In a debug build, a segfault will occur |
| 365 | # when the second attempt to remove the instance from the "list |
| 366 | # of all objects" occurs. |
| 367 | |
| 368 | import gc |
| 369 | |
| 370 | class C(object): |
| 371 | pass |
| 372 | |
| 373 | c = C() |
| 374 | wr = weakref.ref(c, lambda ignore: gc.collect()) |
| 375 | del c |
| 376 | |
Tim Peters | f7f9e99 | 2003-11-13 21:59:32 +0000 | [diff] [blame] | 377 | # There endeth the first part. It gets worse. |
| 378 | del wr |
| 379 | |
| 380 | c1 = C() |
| 381 | c1.i = C() |
| 382 | wr = weakref.ref(c1.i, lambda ignore: gc.collect()) |
| 383 | |
| 384 | c2 = C() |
| 385 | c2.c1 = c1 |
| 386 | del c1 # still alive because c2 points to it |
| 387 | |
| 388 | # Now when subtype_dealloc gets called on c2, it's not enough just |
| 389 | # that c2 is immune from gc while the weakref callbacks associated |
| 390 | # with c2 execute (there are none in this 2nd half of the test, btw). |
| 391 | # subtype_dealloc goes on to call the base classes' deallocs too, |
| 392 | # so any gc triggered by weakref callbacks associated with anything |
| 393 | # torn down by a base class dealloc can also trigger double |
| 394 | # deallocation of c2. |
| 395 | del c2 |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 396 | |
Tim Peters | 403a203 | 2003-11-20 21:21:46 +0000 | [diff] [blame] | 397 | def test_callback_in_cycle_1(self): |
| 398 | import gc |
| 399 | |
| 400 | class J(object): |
| 401 | pass |
| 402 | |
| 403 | class II(object): |
| 404 | def acallback(self, ignore): |
| 405 | self.J |
| 406 | |
| 407 | I = II() |
| 408 | I.J = J |
| 409 | I.wr = weakref.ref(J, I.acallback) |
| 410 | |
| 411 | # Now J and II are each in a self-cycle (as all new-style class |
| 412 | # objects are, since their __mro__ points back to them). I holds |
| 413 | # both a weak reference (I.wr) and a strong reference (I.J) to class |
| 414 | # J. I is also in a cycle (I.wr points to a weakref that references |
| 415 | # I.acallback). When we del these three, they all become trash, but |
| 416 | # the cycles prevent any of them from getting cleaned up immediately. |
| 417 | # Instead they have to wait for cyclic gc to deduce that they're |
| 418 | # trash. |
| 419 | # |
| 420 | # gc used to call tp_clear on all of them, and the order in which |
| 421 | # it does that is pretty accidental. The exact order in which we |
| 422 | # built up these things manages to provoke gc into running tp_clear |
| 423 | # in just the right order (I last). Calling tp_clear on II leaves |
| 424 | # behind an insane class object (its __mro__ becomes NULL). Calling |
| 425 | # tp_clear on J breaks its self-cycle, but J doesn't get deleted |
| 426 | # just then because of the strong reference from I.J. Calling |
| 427 | # tp_clear on I starts to clear I's __dict__, and just happens to |
| 428 | # clear I.J first -- I.wr is still intact. That removes the last |
| 429 | # reference to J, which triggers the weakref callback. The callback |
| 430 | # tries to do "self.J", and instances of new-style classes look up |
| 431 | # attributes ("J") in the class dict first. The class (II) wants to |
| 432 | # search II.__mro__, but that's NULL. The result was a segfault in |
| 433 | # a release build, and an assert failure in a debug build. |
| 434 | del I, J, II |
| 435 | gc.collect() |
| 436 | |
| 437 | def test_callback_in_cycle_2(self): |
| 438 | import gc |
| 439 | |
| 440 | # This is just like test_callback_in_cycle_1, except that II is an |
| 441 | # old-style class. The symptom is different then: an instance of an |
| 442 | # old-style class looks in its own __dict__ first. 'J' happens to |
| 443 | # get cleared from I.__dict__ before 'wr', and 'J' was never in II's |
| 444 | # __dict__, so the attribute isn't found. The difference is that |
| 445 | # the old-style II doesn't have a NULL __mro__ (it doesn't have any |
| 446 | # __mro__), so no segfault occurs. Instead it got: |
| 447 | # test_callback_in_cycle_2 (__main__.ReferencesTestCase) ... |
| 448 | # Exception exceptions.AttributeError: |
| 449 | # "II instance has no attribute 'J'" in <bound method II.acallback |
| 450 | # of <?.II instance at 0x00B9B4B8>> ignored |
| 451 | |
| 452 | class J(object): |
| 453 | pass |
| 454 | |
| 455 | class II: |
| 456 | def acallback(self, ignore): |
| 457 | self.J |
| 458 | |
| 459 | I = II() |
| 460 | I.J = J |
| 461 | I.wr = weakref.ref(J, I.acallback) |
| 462 | |
| 463 | del I, J, II |
| 464 | gc.collect() |
| 465 | |
| 466 | def test_callback_in_cycle_3(self): |
| 467 | import gc |
| 468 | |
| 469 | # This one broke the first patch that fixed the last two. In this |
| 470 | # case, the objects reachable from the callback aren't also reachable |
| 471 | # from the object (c1) *triggering* the callback: you can get to |
| 472 | # c1 from c2, but not vice-versa. The result was that c2's __dict__ |
| 473 | # got tp_clear'ed by the time the c2.cb callback got invoked. |
| 474 | |
| 475 | class C: |
| 476 | def cb(self, ignore): |
| 477 | self.me |
| 478 | self.c1 |
| 479 | self.wr |
| 480 | |
| 481 | c1, c2 = C(), C() |
| 482 | |
| 483 | c2.me = c2 |
| 484 | c2.c1 = c1 |
| 485 | c2.wr = weakref.ref(c1, c2.cb) |
| 486 | |
| 487 | del c1, c2 |
| 488 | gc.collect() |
| 489 | |
| 490 | def test_callback_in_cycle_4(self): |
| 491 | import gc |
| 492 | |
| 493 | # Like test_callback_in_cycle_3, except c2 and c1 have different |
| 494 | # classes. c2's class (C) isn't reachable from c1 then, so protecting |
| 495 | # objects reachable from the dying object (c1) isn't enough to stop |
| 496 | # c2's class (C) from getting tp_clear'ed before c2.cb is invoked. |
| 497 | # The result was a segfault (C.__mro__ was NULL when the callback |
| 498 | # tried to look up self.me). |
| 499 | |
| 500 | class C(object): |
| 501 | def cb(self, ignore): |
| 502 | self.me |
| 503 | self.c1 |
| 504 | self.wr |
| 505 | |
| 506 | class D: |
| 507 | pass |
| 508 | |
| 509 | c1, c2 = D(), C() |
| 510 | |
| 511 | c2.me = c2 |
| 512 | c2.c1 = c1 |
| 513 | c2.wr = weakref.ref(c1, c2.cb) |
| 514 | |
| 515 | del c1, c2, C, D |
| 516 | gc.collect() |
| 517 | |
| 518 | def test_callback_in_cycle_resurrection(self): |
| 519 | import gc |
| 520 | |
| 521 | # Do something nasty in a weakref callback: resurrect objects |
| 522 | # from dead cycles. For this to be attempted, the weakref and |
| 523 | # its callback must also be part of the cyclic trash (else the |
| 524 | # objects reachable via the callback couldn't be in cyclic trash |
| 525 | # to begin with -- the callback would act like an external root). |
| 526 | # But gc clears trash weakrefs with callbacks early now, which |
| 527 | # disables the callbacks, so the callbacks shouldn't get called |
| 528 | # at all (and so nothing actually gets resurrected). |
| 529 | |
| 530 | alist = [] |
| 531 | class C(object): |
| 532 | def __init__(self, value): |
| 533 | self.attribute = value |
| 534 | |
| 535 | def acallback(self, ignore): |
| 536 | alist.append(self.c) |
| 537 | |
| 538 | c1, c2 = C(1), C(2) |
| 539 | c1.c = c2 |
| 540 | c2.c = c1 |
| 541 | c1.wr = weakref.ref(c2, c1.acallback) |
| 542 | c2.wr = weakref.ref(c1, c2.acallback) |
| 543 | |
| 544 | def C_went_away(ignore): |
| 545 | alist.append("C went away") |
| 546 | wr = weakref.ref(C, C_went_away) |
| 547 | |
| 548 | del c1, c2, C # make them all trash |
| 549 | self.assertEqual(alist, []) # del isn't enough to reclaim anything |
| 550 | |
| 551 | gc.collect() |
| 552 | # c1.wr and c2.wr were part of the cyclic trash, so should have |
| 553 | # been cleared without their callbacks executing. OTOH, the weakref |
| 554 | # to C is bound to a function local (wr), and wasn't trash, so that |
| 555 | # callback should have been invoked when C went away. |
| 556 | self.assertEqual(alist, ["C went away"]) |
| 557 | # The remaining weakref should be dead now (its callback ran). |
| 558 | self.assertEqual(wr(), None) |
| 559 | |
| 560 | del alist[:] |
| 561 | gc.collect() |
| 562 | self.assertEqual(alist, []) |
| 563 | |
| 564 | def test_callbacks_on_callback(self): |
| 565 | import gc |
| 566 | |
| 567 | # Set up weakref callbacks *on* weakref callbacks. |
| 568 | alist = [] |
| 569 | def safe_callback(ignore): |
| 570 | alist.append("safe_callback called") |
| 571 | |
| 572 | class C(object): |
| 573 | def cb(self, ignore): |
| 574 | alist.append("cb called") |
| 575 | |
| 576 | c, d = C(), C() |
| 577 | c.other = d |
| 578 | d.other = c |
| 579 | callback = c.cb |
| 580 | c.wr = weakref.ref(d, callback) # this won't trigger |
| 581 | d.wr = weakref.ref(callback, d.cb) # ditto |
| 582 | external_wr = weakref.ref(callback, safe_callback) # but this will |
| 583 | self.assert_(external_wr() is callback) |
| 584 | |
| 585 | # The weakrefs attached to c and d should get cleared, so that |
| 586 | # C.cb is never called. But external_wr isn't part of the cyclic |
| 587 | # trash, and no cyclic trash is reachable from it, so safe_callback |
| 588 | # should get invoked when the bound method object callback (c.cb) |
| 589 | # -- which is itself a callback, and also part of the cyclic trash -- |
| 590 | # gets reclaimed at the end of gc. |
| 591 | |
| 592 | del callback, c, d, C |
| 593 | self.assertEqual(alist, []) # del isn't enough to clean up cycles |
| 594 | gc.collect() |
| 595 | self.assertEqual(alist, ["safe_callback called"]) |
| 596 | self.assertEqual(external_wr(), None) |
| 597 | |
| 598 | del alist[:] |
| 599 | gc.collect() |
| 600 | self.assertEqual(alist, []) |
| 601 | |
Fred Drake | bc875f5 | 2004-02-04 23:14:14 +0000 | [diff] [blame] | 602 | def test_gc_during_ref_creation(self): |
| 603 | self.check_gc_during_creation(weakref.ref) |
| 604 | |
| 605 | def test_gc_during_proxy_creation(self): |
| 606 | self.check_gc_during_creation(weakref.proxy) |
| 607 | |
| 608 | def check_gc_during_creation(self, makeref): |
| 609 | thresholds = gc.get_threshold() |
| 610 | gc.set_threshold(1, 1, 1) |
| 611 | gc.collect() |
Fred Drake | 55cf434 | 2004-02-13 19:21:57 +0000 | [diff] [blame] | 612 | class A: |
| 613 | pass |
Fred Drake | bc875f5 | 2004-02-04 23:14:14 +0000 | [diff] [blame] | 614 | |
| 615 | def callback(*args): |
| 616 | pass |
| 617 | |
Fred Drake | 55cf434 | 2004-02-13 19:21:57 +0000 | [diff] [blame] | 618 | referenced = A() |
Fred Drake | bc875f5 | 2004-02-04 23:14:14 +0000 | [diff] [blame] | 619 | |
Fred Drake | 55cf434 | 2004-02-13 19:21:57 +0000 | [diff] [blame] | 620 | a = A() |
Fred Drake | bc875f5 | 2004-02-04 23:14:14 +0000 | [diff] [blame] | 621 | a.a = a |
| 622 | a.wr = makeref(referenced) |
| 623 | |
| 624 | try: |
| 625 | # now make sure the object and the ref get labeled as |
| 626 | # cyclic trash: |
Fred Drake | 55cf434 | 2004-02-13 19:21:57 +0000 | [diff] [blame] | 627 | a = A() |
| 628 | weakref.ref(referenced, callback) |
Fred Drake | bc875f5 | 2004-02-04 23:14:14 +0000 | [diff] [blame] | 629 | |
| 630 | finally: |
| 631 | gc.set_threshold(*thresholds) |
| 632 | |
Fred Drake | 0a4dd39 | 2004-07-02 18:57:45 +0000 | [diff] [blame] | 633 | |
| 634 | class SubclassableWeakrefTestCase(unittest.TestCase): |
| 635 | |
| 636 | def test_subclass_refs(self): |
| 637 | class MyRef(weakref.ref): |
| 638 | def __init__(self, ob, callback=None, value=42): |
| 639 | self.value = value |
| 640 | super(MyRef, self).__init__(ob, callback) |
| 641 | def __call__(self): |
| 642 | self.called = True |
| 643 | return super(MyRef, self).__call__() |
| 644 | o = Object("foo") |
| 645 | mr = MyRef(o, value=24) |
| 646 | self.assert_(mr() is o) |
| 647 | self.assert_(mr.called) |
| 648 | self.assertEqual(mr.value, 24) |
| 649 | del o |
| 650 | self.assert_(mr() is None) |
| 651 | self.assert_(mr.called) |
| 652 | |
| 653 | def test_subclass_refs_dont_replace_standard_refs(self): |
| 654 | class MyRef(weakref.ref): |
| 655 | pass |
| 656 | o = Object(42) |
| 657 | r1 = MyRef(o) |
| 658 | r2 = weakref.ref(o) |
| 659 | self.assert_(r1 is not r2) |
| 660 | self.assertEqual(weakref.getweakrefs(o), [r2, r1]) |
| 661 | self.assertEqual(weakref.getweakrefcount(o), 2) |
| 662 | r3 = MyRef(o) |
| 663 | self.assertEqual(weakref.getweakrefcount(o), 3) |
| 664 | refs = weakref.getweakrefs(o) |
| 665 | self.assertEqual(len(refs), 3) |
| 666 | self.assert_(r2 is refs[0]) |
| 667 | self.assert_(r1 in refs[1:]) |
| 668 | self.assert_(r3 in refs[1:]) |
| 669 | |
| 670 | def test_subclass_refs_dont_conflate_callbacks(self): |
| 671 | class MyRef(weakref.ref): |
| 672 | pass |
| 673 | o = Object(42) |
| 674 | r1 = MyRef(o, id) |
| 675 | r2 = MyRef(o, str) |
| 676 | self.assert_(r1 is not r2) |
| 677 | refs = weakref.getweakrefs(o) |
| 678 | self.assert_(r1 in refs) |
| 679 | self.assert_(r2 in refs) |
| 680 | |
| 681 | def test_subclass_refs_with_slots(self): |
| 682 | class MyRef(weakref.ref): |
| 683 | __slots__ = "slot1", "slot2" |
| 684 | def __new__(type, ob, callback, slot1, slot2): |
| 685 | return weakref.ref.__new__(type, ob, callback) |
| 686 | def __init__(self, ob, callback, slot1, slot2): |
| 687 | self.slot1 = slot1 |
| 688 | self.slot2 = slot2 |
| 689 | def meth(self): |
| 690 | return self.slot1 + self.slot2 |
| 691 | o = Object(42) |
| 692 | r = MyRef(o, None, "abc", "def") |
| 693 | self.assertEqual(r.slot1, "abc") |
| 694 | self.assertEqual(r.slot2, "def") |
| 695 | self.assertEqual(r.meth(), "abcdef") |
| 696 | self.failIf(hasattr(r, "__dict__")) |
| 697 | |
| 698 | |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 699 | class Object: |
| 700 | def __init__(self, arg): |
| 701 | self.arg = arg |
| 702 | def __repr__(self): |
| 703 | return "<Object %r>" % self.arg |
| 704 | |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 705 | |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 706 | class MappingTestCase(TestBase): |
Martin v. Löwis | 5e16333 | 2001-02-27 18:36:56 +0000 | [diff] [blame] | 707 | |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 708 | COUNT = 10 |
| 709 | |
| 710 | def test_weak_values(self): |
Fred Drake | 0e540c3 | 2001-05-02 05:44:22 +0000 | [diff] [blame] | 711 | # |
| 712 | # This exercises d.copy(), d.items(), d[], del d[], len(d). |
| 713 | # |
| 714 | dict, objects = self.make_weak_valued_dict() |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 715 | for o in objects: |
| 716 | self.assert_(weakref.getweakrefcount(o) == 1, |
| 717 | "wrong number of weak references to %r!" % o) |
| 718 | self.assert_(o is dict[o.arg], |
| 719 | "wrong object returned by weak dict!") |
| 720 | items1 = dict.items() |
| 721 | items2 = dict.copy().items() |
| 722 | items1.sort() |
| 723 | items2.sort() |
| 724 | self.assert_(items1 == items2, |
| 725 | "cloning of weak-valued dictionary did not work!") |
| 726 | del items1, items2 |
| 727 | self.assert_(len(dict) == self.COUNT) |
| 728 | del objects[0] |
| 729 | self.assert_(len(dict) == (self.COUNT - 1), |
| 730 | "deleting object did not cause dictionary update") |
| 731 | del objects, o |
| 732 | self.assert_(len(dict) == 0, |
| 733 | "deleting the values did not clear the dictionary") |
Fred Drake | 4fd06e0 | 2001-08-03 04:11:27 +0000 | [diff] [blame] | 734 | # regression on SF bug #447152: |
| 735 | dict = weakref.WeakValueDictionary() |
| 736 | self.assertRaises(KeyError, dict.__getitem__, 1) |
| 737 | dict[2] = C() |
| 738 | self.assertRaises(KeyError, dict.__getitem__, 2) |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 739 | |
| 740 | def test_weak_keys(self): |
Fred Drake | 0e540c3 | 2001-05-02 05:44:22 +0000 | [diff] [blame] | 741 | # |
| 742 | # This exercises d.copy(), d.items(), d[] = v, d[], del d[], |
Fred Drake | 752eda4 | 2001-11-06 16:38:34 +0000 | [diff] [blame] | 743 | # len(d), d.has_key(). |
Fred Drake | 0e540c3 | 2001-05-02 05:44:22 +0000 | [diff] [blame] | 744 | # |
| 745 | dict, objects = self.make_weak_keyed_dict() |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 746 | for o in objects: |
| 747 | self.assert_(weakref.getweakrefcount(o) == 1, |
| 748 | "wrong number of weak references to %r!" % o) |
| 749 | self.assert_(o.arg is dict[o], |
| 750 | "wrong object returned by weak dict!") |
| 751 | items1 = dict.items() |
| 752 | items2 = dict.copy().items() |
Raymond Hettinger | a690a99 | 2003-11-16 16:17:49 +0000 | [diff] [blame] | 753 | self.assert_(set(items1) == set(items2), |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 754 | "cloning of weak-keyed dictionary did not work!") |
| 755 | del items1, items2 |
| 756 | self.assert_(len(dict) == self.COUNT) |
| 757 | del objects[0] |
| 758 | self.assert_(len(dict) == (self.COUNT - 1), |
| 759 | "deleting object did not cause dictionary update") |
| 760 | del objects, o |
| 761 | self.assert_(len(dict) == 0, |
| 762 | "deleting the keys did not clear the dictionary") |
Fred Drake | 752eda4 | 2001-11-06 16:38:34 +0000 | [diff] [blame] | 763 | o = Object(42) |
| 764 | dict[o] = "What is the meaning of the universe?" |
| 765 | self.assert_(dict.has_key(o)) |
| 766 | self.assert_(not dict.has_key(34)) |
Martin v. Löwis | 5e16333 | 2001-02-27 18:36:56 +0000 | [diff] [blame] | 767 | |
Fred Drake | 0e540c3 | 2001-05-02 05:44:22 +0000 | [diff] [blame] | 768 | def test_weak_keyed_iters(self): |
| 769 | dict, objects = self.make_weak_keyed_dict() |
| 770 | self.check_iters(dict) |
| 771 | |
Fred Drake | 017e68c | 2006-05-02 06:53:59 +0000 | [diff] [blame] | 772 | # Test keyrefs() |
| 773 | refs = dict.keyrefs() |
| 774 | self.assertEqual(len(refs), len(objects)) |
| 775 | objects2 = list(objects) |
| 776 | for wr in refs: |
| 777 | ob = wr() |
| 778 | self.assert_(dict.has_key(ob)) |
| 779 | self.assert_(ob in dict) |
| 780 | self.assertEqual(ob.arg, dict[ob]) |
| 781 | objects2.remove(ob) |
| 782 | self.assertEqual(len(objects2), 0) |
| 783 | |
| 784 | # Test iterkeyrefs() |
| 785 | objects2 = list(objects) |
| 786 | self.assertEqual(len(list(dict.iterkeyrefs())), len(objects)) |
| 787 | for wr in dict.iterkeyrefs(): |
| 788 | ob = wr() |
| 789 | self.assert_(dict.has_key(ob)) |
| 790 | self.assert_(ob in dict) |
| 791 | self.assertEqual(ob.arg, dict[ob]) |
| 792 | objects2.remove(ob) |
| 793 | self.assertEqual(len(objects2), 0) |
| 794 | |
Fred Drake | 0e540c3 | 2001-05-02 05:44:22 +0000 | [diff] [blame] | 795 | def test_weak_valued_iters(self): |
| 796 | dict, objects = self.make_weak_valued_dict() |
| 797 | self.check_iters(dict) |
| 798 | |
Fred Drake | 017e68c | 2006-05-02 06:53:59 +0000 | [diff] [blame] | 799 | # Test valuerefs() |
| 800 | refs = dict.valuerefs() |
| 801 | self.assertEqual(len(refs), len(objects)) |
| 802 | objects2 = list(objects) |
| 803 | for wr in refs: |
| 804 | ob = wr() |
| 805 | self.assertEqual(ob, dict[ob.arg]) |
| 806 | self.assertEqual(ob.arg, dict[ob.arg].arg) |
| 807 | objects2.remove(ob) |
| 808 | self.assertEqual(len(objects2), 0) |
| 809 | |
| 810 | # Test itervaluerefs() |
| 811 | objects2 = list(objects) |
| 812 | self.assertEqual(len(list(dict.itervaluerefs())), len(objects)) |
| 813 | for wr in dict.itervaluerefs(): |
| 814 | ob = wr() |
| 815 | self.assertEqual(ob, dict[ob.arg]) |
| 816 | self.assertEqual(ob.arg, dict[ob.arg].arg) |
| 817 | objects2.remove(ob) |
| 818 | self.assertEqual(len(objects2), 0) |
| 819 | |
Fred Drake | 0e540c3 | 2001-05-02 05:44:22 +0000 | [diff] [blame] | 820 | def check_iters(self, dict): |
| 821 | # item iterator: |
| 822 | items = dict.items() |
| 823 | for item in dict.iteritems(): |
| 824 | items.remove(item) |
Fred Drake | aaa48ff | 2001-05-10 17:16:38 +0000 | [diff] [blame] | 825 | self.assert_(len(items) == 0, "iteritems() did not touch all items") |
Fred Drake | 0e540c3 | 2001-05-02 05:44:22 +0000 | [diff] [blame] | 826 | |
Fred Drake | aaa48ff | 2001-05-10 17:16:38 +0000 | [diff] [blame] | 827 | # key iterator, via __iter__(): |
Fred Drake | 0e540c3 | 2001-05-02 05:44:22 +0000 | [diff] [blame] | 828 | keys = dict.keys() |
| 829 | for k in dict: |
| 830 | keys.remove(k) |
Fred Drake | aaa48ff | 2001-05-10 17:16:38 +0000 | [diff] [blame] | 831 | self.assert_(len(keys) == 0, "__iter__() did not touch all keys") |
| 832 | |
| 833 | # key iterator, via iterkeys(): |
| 834 | keys = dict.keys() |
| 835 | for k in dict.iterkeys(): |
| 836 | keys.remove(k) |
| 837 | self.assert_(len(keys) == 0, "iterkeys() did not touch all keys") |
Fred Drake | 0e540c3 | 2001-05-02 05:44:22 +0000 | [diff] [blame] | 838 | |
| 839 | # value iterator: |
| 840 | values = dict.values() |
| 841 | for v in dict.itervalues(): |
| 842 | values.remove(v) |
Fred Drake | f425b1e | 2003-07-14 21:37:17 +0000 | [diff] [blame] | 843 | self.assert_(len(values) == 0, |
| 844 | "itervalues() did not touch all values") |
Fred Drake | 0e540c3 | 2001-05-02 05:44:22 +0000 | [diff] [blame] | 845 | |
Guido van Rossum | 009afb7 | 2002-06-10 20:00:52 +0000 | [diff] [blame] | 846 | def test_make_weak_keyed_dict_from_dict(self): |
| 847 | o = Object(3) |
| 848 | dict = weakref.WeakKeyDictionary({o:364}) |
| 849 | self.assert_(dict[o] == 364) |
| 850 | |
| 851 | def test_make_weak_keyed_dict_from_weak_keyed_dict(self): |
| 852 | o = Object(3) |
| 853 | dict = weakref.WeakKeyDictionary({o:364}) |
| 854 | dict2 = weakref.WeakKeyDictionary(dict) |
| 855 | self.assert_(dict[o] == 364) |
| 856 | |
Fred Drake | 0e540c3 | 2001-05-02 05:44:22 +0000 | [diff] [blame] | 857 | def make_weak_keyed_dict(self): |
| 858 | dict = weakref.WeakKeyDictionary() |
| 859 | objects = map(Object, range(self.COUNT)) |
| 860 | for o in objects: |
| 861 | dict[o] = o.arg |
| 862 | return dict, objects |
| 863 | |
| 864 | def make_weak_valued_dict(self): |
| 865 | dict = weakref.WeakValueDictionary() |
| 866 | objects = map(Object, range(self.COUNT)) |
| 867 | for o in objects: |
| 868 | dict[o.arg] = o |
| 869 | return dict, objects |
| 870 | |
Fred Drake | aaa48ff | 2001-05-10 17:16:38 +0000 | [diff] [blame] | 871 | def check_popitem(self, klass, key1, value1, key2, value2): |
| 872 | weakdict = klass() |
| 873 | weakdict[key1] = value1 |
| 874 | weakdict[key2] = value2 |
| 875 | self.assert_(len(weakdict) == 2) |
| 876 | k, v = weakdict.popitem() |
| 877 | self.assert_(len(weakdict) == 1) |
| 878 | if k is key1: |
| 879 | self.assert_(v is value1) |
| 880 | else: |
| 881 | self.assert_(v is value2) |
| 882 | k, v = weakdict.popitem() |
| 883 | self.assert_(len(weakdict) == 0) |
| 884 | if k is key1: |
| 885 | self.assert_(v is value1) |
| 886 | else: |
| 887 | self.assert_(v is value2) |
| 888 | |
| 889 | def test_weak_valued_dict_popitem(self): |
| 890 | self.check_popitem(weakref.WeakValueDictionary, |
| 891 | "key1", C(), "key2", C()) |
| 892 | |
| 893 | def test_weak_keyed_dict_popitem(self): |
| 894 | self.check_popitem(weakref.WeakKeyDictionary, |
| 895 | C(), "value 1", C(), "value 2") |
| 896 | |
| 897 | def check_setdefault(self, klass, key, value1, value2): |
| 898 | self.assert_(value1 is not value2, |
| 899 | "invalid test" |
| 900 | " -- value parameters must be distinct objects") |
| 901 | weakdict = klass() |
| 902 | o = weakdict.setdefault(key, value1) |
| 903 | self.assert_(o is value1) |
| 904 | self.assert_(weakdict.has_key(key)) |
| 905 | self.assert_(weakdict.get(key) is value1) |
| 906 | self.assert_(weakdict[key] is value1) |
| 907 | |
| 908 | o = weakdict.setdefault(key, value2) |
| 909 | self.assert_(o is value1) |
| 910 | self.assert_(weakdict.has_key(key)) |
| 911 | self.assert_(weakdict.get(key) is value1) |
| 912 | self.assert_(weakdict[key] is value1) |
| 913 | |
| 914 | def test_weak_valued_dict_setdefault(self): |
| 915 | self.check_setdefault(weakref.WeakValueDictionary, |
| 916 | "key", C(), C()) |
| 917 | |
| 918 | def test_weak_keyed_dict_setdefault(self): |
| 919 | self.check_setdefault(weakref.WeakKeyDictionary, |
| 920 | C(), "value 1", "value 2") |
| 921 | |
Fred Drake | a0a4ab1 | 2001-04-16 17:37:27 +0000 | [diff] [blame] | 922 | def check_update(self, klass, dict): |
Fred Drake | 0e540c3 | 2001-05-02 05:44:22 +0000 | [diff] [blame] | 923 | # |
| 924 | # This exercises d.update(), len(d), d.keys(), d.has_key(), |
| 925 | # d.get(), d[]. |
| 926 | # |
Fred Drake | a0a4ab1 | 2001-04-16 17:37:27 +0000 | [diff] [blame] | 927 | weakdict = klass() |
| 928 | weakdict.update(dict) |
| 929 | self.assert_(len(weakdict) == len(dict)) |
| 930 | for k in weakdict.keys(): |
| 931 | self.assert_(dict.has_key(k), |
| 932 | "mysterious new key appeared in weak dict") |
| 933 | v = dict.get(k) |
| 934 | self.assert_(v is weakdict[k]) |
| 935 | self.assert_(v is weakdict.get(k)) |
| 936 | for k in dict.keys(): |
| 937 | self.assert_(weakdict.has_key(k), |
| 938 | "original key disappeared in weak dict") |
| 939 | v = dict[k] |
| 940 | self.assert_(v is weakdict[k]) |
| 941 | self.assert_(v is weakdict.get(k)) |
| 942 | |
| 943 | def test_weak_valued_dict_update(self): |
| 944 | self.check_update(weakref.WeakValueDictionary, |
| 945 | {1: C(), 'a': C(), C(): C()}) |
| 946 | |
| 947 | def test_weak_keyed_dict_update(self): |
| 948 | self.check_update(weakref.WeakKeyDictionary, |
| 949 | {C(): 1, C(): 2, C(): 3}) |
| 950 | |
Fred Drake | ccc7562 | 2001-09-06 14:52:39 +0000 | [diff] [blame] | 951 | def test_weak_keyed_delitem(self): |
| 952 | d = weakref.WeakKeyDictionary() |
| 953 | o1 = Object('1') |
| 954 | o2 = Object('2') |
| 955 | d[o1] = 'something' |
| 956 | d[o2] = 'something' |
| 957 | self.assert_(len(d) == 2) |
| 958 | del d[o1] |
| 959 | self.assert_(len(d) == 1) |
| 960 | self.assert_(d.keys() == [o2]) |
| 961 | |
| 962 | def test_weak_valued_delitem(self): |
| 963 | d = weakref.WeakValueDictionary() |
| 964 | o1 = Object('1') |
| 965 | o2 = Object('2') |
| 966 | d['something'] = o1 |
| 967 | d['something else'] = o2 |
| 968 | self.assert_(len(d) == 2) |
| 969 | del d['something'] |
| 970 | self.assert_(len(d) == 1) |
| 971 | self.assert_(d.items() == [('something else', o2)]) |
| 972 | |
Tim Peters | 886128f | 2003-05-25 01:45:11 +0000 | [diff] [blame] | 973 | def test_weak_keyed_bad_delitem(self): |
| 974 | d = weakref.WeakKeyDictionary() |
| 975 | o = Object('1') |
| 976 | # An attempt to delete an object that isn't there should raise |
Tim Peters | 50d8b8b | 2003-05-25 17:44:31 +0000 | [diff] [blame] | 977 | # KeyError. It didn't before 2.3. |
Tim Peters | 886128f | 2003-05-25 01:45:11 +0000 | [diff] [blame] | 978 | self.assertRaises(KeyError, d.__delitem__, o) |
Tim Peters | 50d8b8b | 2003-05-25 17:44:31 +0000 | [diff] [blame] | 979 | self.assertRaises(KeyError, d.__getitem__, o) |
| 980 | |
| 981 | # If a key isn't of a weakly referencable type, __getitem__ and |
| 982 | # __setitem__ raise TypeError. __delitem__ should too. |
| 983 | self.assertRaises(TypeError, d.__delitem__, 13) |
| 984 | self.assertRaises(TypeError, d.__getitem__, 13) |
| 985 | self.assertRaises(TypeError, d.__setitem__, 13, 13) |
Tim Peters | 886128f | 2003-05-25 01:45:11 +0000 | [diff] [blame] | 986 | |
| 987 | def test_weak_keyed_cascading_deletes(self): |
| 988 | # SF bug 742860. For some reason, before 2.3 __delitem__ iterated |
| 989 | # over the keys via self.data.iterkeys(). If things vanished from |
| 990 | # the dict during this (or got added), that caused a RuntimeError. |
| 991 | |
| 992 | d = weakref.WeakKeyDictionary() |
| 993 | mutate = False |
| 994 | |
| 995 | class C(object): |
| 996 | def __init__(self, i): |
| 997 | self.value = i |
| 998 | def __hash__(self): |
| 999 | return hash(self.value) |
| 1000 | def __eq__(self, other): |
| 1001 | if mutate: |
| 1002 | # Side effect that mutates the dict, by removing the |
| 1003 | # last strong reference to a key. |
| 1004 | del objs[-1] |
| 1005 | return self.value == other.value |
| 1006 | |
| 1007 | objs = [C(i) for i in range(4)] |
| 1008 | for o in objs: |
| 1009 | d[o] = o.value |
| 1010 | del o # now the only strong references to keys are in objs |
| 1011 | # Find the order in which iterkeys sees the keys. |
| 1012 | objs = d.keys() |
| 1013 | # Reverse it, so that the iteration implementation of __delitem__ |
| 1014 | # has to keep looping to find the first object we delete. |
| 1015 | objs.reverse() |
Tim Peters | 50d8b8b | 2003-05-25 17:44:31 +0000 | [diff] [blame] | 1016 | |
Tim Peters | 886128f | 2003-05-25 01:45:11 +0000 | [diff] [blame] | 1017 | # Turn on mutation in C.__eq__. The first time thru the loop, |
| 1018 | # under the iterkeys() business the first comparison will delete |
| 1019 | # the last item iterkeys() would see, and that causes a |
| 1020 | # RuntimeError: dictionary changed size during iteration |
| 1021 | # when the iterkeys() loop goes around to try comparing the next |
Tim Peters | 50d8b8b | 2003-05-25 17:44:31 +0000 | [diff] [blame] | 1022 | # key. After this was fixed, it just deletes the last object *our* |
Tim Peters | 886128f | 2003-05-25 01:45:11 +0000 | [diff] [blame] | 1023 | # "for o in obj" loop would have gotten to. |
| 1024 | mutate = True |
| 1025 | count = 0 |
| 1026 | for o in objs: |
| 1027 | count += 1 |
| 1028 | del d[o] |
| 1029 | self.assertEqual(len(d), 0) |
| 1030 | self.assertEqual(count, 2) |
| 1031 | |
Walter Dörwald | 0a6d0ff | 2004-05-31 16:29:04 +0000 | [diff] [blame] | 1032 | from test import mapping_tests |
Raymond Hettinger | 2c2d322 | 2003-03-09 07:05:43 +0000 | [diff] [blame] | 1033 | |
Walter Dörwald | 0a6d0ff | 2004-05-31 16:29:04 +0000 | [diff] [blame] | 1034 | class WeakValueDictionaryTestCase(mapping_tests.BasicTestMappingProtocol): |
Fred Drake | f425b1e | 2003-07-14 21:37:17 +0000 | [diff] [blame] | 1035 | """Check that WeakValueDictionary conforms to the mapping protocol""" |
Raymond Hettinger | 2c2d322 | 2003-03-09 07:05:43 +0000 | [diff] [blame] | 1036 | __ref = {"key1":Object(1), "key2":Object(2), "key3":Object(3)} |
Walter Dörwald | 118f931 | 2004-06-02 18:42:25 +0000 | [diff] [blame] | 1037 | type2test = weakref.WeakValueDictionary |
Raymond Hettinger | 2c2d322 | 2003-03-09 07:05:43 +0000 | [diff] [blame] | 1038 | def _reference(self): |
| 1039 | return self.__ref.copy() |
| 1040 | |
Walter Dörwald | 0a6d0ff | 2004-05-31 16:29:04 +0000 | [diff] [blame] | 1041 | class WeakKeyDictionaryTestCase(mapping_tests.BasicTestMappingProtocol): |
Fred Drake | f425b1e | 2003-07-14 21:37:17 +0000 | [diff] [blame] | 1042 | """Check that WeakKeyDictionary conforms to the mapping protocol""" |
Raymond Hettinger | 2c2d322 | 2003-03-09 07:05:43 +0000 | [diff] [blame] | 1043 | __ref = {Object("key1"):1, Object("key2"):2, Object("key3"):3} |
Walter Dörwald | 118f931 | 2004-06-02 18:42:25 +0000 | [diff] [blame] | 1044 | type2test = weakref.WeakKeyDictionary |
Raymond Hettinger | 2c2d322 | 2003-03-09 07:05:43 +0000 | [diff] [blame] | 1045 | def _reference(self): |
| 1046 | return self.__ref.copy() |
Martin v. Löwis | 5e16333 | 2001-02-27 18:36:56 +0000 | [diff] [blame] | 1047 | |
Georg Brandl | 9a65d58 | 2005-07-02 19:07:30 +0000 | [diff] [blame] | 1048 | libreftest = """ Doctest for examples in the library reference: libweakref.tex |
| 1049 | |
| 1050 | >>> import weakref |
| 1051 | >>> class Dict(dict): |
| 1052 | ... pass |
| 1053 | ... |
| 1054 | >>> obj = Dict(red=1, green=2, blue=3) # this object is weak referencable |
| 1055 | >>> r = weakref.ref(obj) |
Armin Rigo | a3f0927 | 2006-05-28 19:13:17 +0000 | [diff] [blame] | 1056 | >>> print r() is obj |
| 1057 | True |
Georg Brandl | 9a65d58 | 2005-07-02 19:07:30 +0000 | [diff] [blame] | 1058 | |
| 1059 | >>> import weakref |
| 1060 | >>> class Object: |
| 1061 | ... pass |
| 1062 | ... |
| 1063 | >>> o = Object() |
| 1064 | >>> r = weakref.ref(o) |
| 1065 | >>> o2 = r() |
| 1066 | >>> o is o2 |
| 1067 | True |
| 1068 | >>> del o, o2 |
| 1069 | >>> print r() |
| 1070 | None |
| 1071 | |
| 1072 | >>> import weakref |
| 1073 | >>> class ExtendedRef(weakref.ref): |
| 1074 | ... def __init__(self, ob, callback=None, **annotations): |
| 1075 | ... super(ExtendedRef, self).__init__(ob, callback) |
| 1076 | ... self.__counter = 0 |
| 1077 | ... for k, v in annotations.iteritems(): |
| 1078 | ... setattr(self, k, v) |
| 1079 | ... def __call__(self): |
| 1080 | ... '''Return a pair containing the referent and the number of |
| 1081 | ... times the reference has been called. |
| 1082 | ... ''' |
| 1083 | ... ob = super(ExtendedRef, self).__call__() |
| 1084 | ... if ob is not None: |
| 1085 | ... self.__counter += 1 |
| 1086 | ... ob = (ob, self.__counter) |
| 1087 | ... return ob |
| 1088 | ... |
| 1089 | >>> class A: # not in docs from here, just testing the ExtendedRef |
| 1090 | ... pass |
| 1091 | ... |
| 1092 | >>> a = A() |
| 1093 | >>> r = ExtendedRef(a, foo=1, bar="baz") |
| 1094 | >>> r.foo |
| 1095 | 1 |
| 1096 | >>> r.bar |
| 1097 | 'baz' |
| 1098 | >>> r()[1] |
| 1099 | 1 |
| 1100 | >>> r()[1] |
| 1101 | 2 |
| 1102 | >>> r()[0] is a |
| 1103 | True |
| 1104 | |
| 1105 | |
| 1106 | >>> import weakref |
| 1107 | >>> _id2obj_dict = weakref.WeakValueDictionary() |
| 1108 | >>> def remember(obj): |
| 1109 | ... oid = id(obj) |
| 1110 | ... _id2obj_dict[oid] = obj |
| 1111 | ... return oid |
| 1112 | ... |
| 1113 | >>> def id2obj(oid): |
| 1114 | ... return _id2obj_dict[oid] |
| 1115 | ... |
| 1116 | >>> a = A() # from here, just testing |
| 1117 | >>> a_id = remember(a) |
| 1118 | >>> id2obj(a_id) is a |
| 1119 | True |
| 1120 | >>> del a |
| 1121 | >>> try: |
| 1122 | ... id2obj(a_id) |
| 1123 | ... except KeyError: |
| 1124 | ... print 'OK' |
| 1125 | ... else: |
| 1126 | ... print 'WeakValueDictionary error' |
| 1127 | OK |
| 1128 | |
| 1129 | """ |
| 1130 | |
| 1131 | __test__ = {'libreftest' : libreftest} |
| 1132 | |
Fred Drake | 2e2be37 | 2001-09-20 21:33:42 +0000 | [diff] [blame] | 1133 | def test_main(): |
Walter Dörwald | 21d3a32 | 2003-05-01 17:45:56 +0000 | [diff] [blame] | 1134 | test_support.run_unittest( |
| 1135 | ReferencesTestCase, |
| 1136 | MappingTestCase, |
| 1137 | WeakValueDictionaryTestCase, |
Fred Drake | f425b1e | 2003-07-14 21:37:17 +0000 | [diff] [blame] | 1138 | WeakKeyDictionaryTestCase, |
| 1139 | ) |
Georg Brandl | 9a65d58 | 2005-07-02 19:07:30 +0000 | [diff] [blame] | 1140 | test_support.run_doctest(sys.modules[__name__]) |
Fred Drake | 2e2be37 | 2001-09-20 21:33:42 +0000 | [diff] [blame] | 1141 | |
| 1142 | |
| 1143 | if __name__ == "__main__": |
| 1144 | test_main() |