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