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