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