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