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