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