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