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