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