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