Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1 | import unittest |
Brett Cannon | 7a54073 | 2011-02-22 03:04:06 +0000 | [diff] [blame] | 2 | from test.support import (verbose, refcount_test, run_unittest, |
Serhiy Storchaka | f28ba36 | 2014-02-07 10:10:55 +0200 | [diff] [blame] | 3 | strip_python_stderr, cpython_only) |
Antoine Pitrou | 5f454a0 | 2013-05-06 21:15:57 +0200 | [diff] [blame] | 4 | from test.script_helper import assert_python_ok, make_script, temp_dir |
| 5 | |
Neil Schemenauer | 88c761a | 2001-07-12 13:25:53 +0000 | [diff] [blame] | 6 | import sys |
Antoine Pitrou | 2b0218a | 2012-09-06 00:59:49 +0200 | [diff] [blame] | 7 | import time |
Jeremy Hylton | c5007aa | 2000-06-30 05:02:53 +0000 | [diff] [blame] | 8 | import gc |
Tim Peters | ead8b7a | 2004-10-30 23:09:22 +0000 | [diff] [blame] | 9 | import weakref |
Jeremy Hylton | c5007aa | 2000-06-30 05:02:53 +0000 | [diff] [blame] | 10 | |
Antoine Pitrou | 2b0218a | 2012-09-06 00:59:49 +0200 | [diff] [blame] | 11 | try: |
| 12 | import threading |
| 13 | except ImportError: |
| 14 | threading = None |
| 15 | |
Serhiy Storchaka | f28ba36 | 2014-02-07 10:10:55 +0200 | [diff] [blame] | 16 | try: |
| 17 | from _testcapi import with_tp_del |
| 18 | except ImportError: |
| 19 | def with_tp_del(cls): |
| 20 | class C(object): |
| 21 | def __new__(cls, *args, **kwargs): |
| 22 | raise TypeError('requires _testcapi.with_tp_del') |
| 23 | return C |
| 24 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 25 | ### Support code |
| 26 | ############################################################################### |
Tim Peters | 0f81ab6 | 2003-04-08 16:39:48 +0000 | [diff] [blame] | 27 | |
Tim Peters | ead8b7a | 2004-10-30 23:09:22 +0000 | [diff] [blame] | 28 | # Bug 1055820 has several tests of longstanding bugs involving weakrefs and |
| 29 | # cyclic gc. |
| 30 | |
| 31 | # An instance of C1055820 has a self-loop, so becomes cyclic trash when |
| 32 | # unreachable. |
| 33 | class C1055820(object): |
| 34 | def __init__(self, i): |
| 35 | self.i = i |
| 36 | self.loop = self |
| 37 | |
| 38 | class GC_Detector(object): |
| 39 | # Create an instance I. Then gc hasn't happened again so long as |
| 40 | # I.gc_happened is false. |
| 41 | |
| 42 | def __init__(self): |
| 43 | self.gc_happened = False |
| 44 | |
| 45 | def it_happened(ignored): |
| 46 | self.gc_happened = True |
| 47 | |
| 48 | # Create a piece of cyclic trash that triggers it_happened when |
| 49 | # gc collects it. |
| 50 | self.wr = weakref.ref(C1055820(666), it_happened) |
| 51 | |
Serhiy Storchaka | f28ba36 | 2014-02-07 10:10:55 +0200 | [diff] [blame] | 52 | @with_tp_del |
Kristján Valur Jónsson | 69c6352 | 2012-04-15 11:41:32 +0000 | [diff] [blame] | 53 | class Uncollectable(object): |
| 54 | """Create a reference cycle with multiple __del__ methods. |
| 55 | |
| 56 | An object in a reference cycle will never have zero references, |
| 57 | and so must be garbage collected. If one or more objects in the |
| 58 | cycle have __del__ methods, the gc refuses to guess an order, |
| 59 | and leaves the cycle uncollected.""" |
| 60 | def __init__(self, partner=None): |
| 61 | if partner is None: |
| 62 | self.partner = Uncollectable(partner=self) |
| 63 | else: |
| 64 | self.partner = partner |
Antoine Pitrou | 796564c | 2013-07-30 19:59:21 +0200 | [diff] [blame] | 65 | def __tp_del__(self): |
Kristján Valur Jónsson | 69c6352 | 2012-04-15 11:41:32 +0000 | [diff] [blame] | 66 | pass |
Tim Peters | ead8b7a | 2004-10-30 23:09:22 +0000 | [diff] [blame] | 67 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 68 | ### Tests |
| 69 | ############################################################################### |
Tim Peters | ead8b7a | 2004-10-30 23:09:22 +0000 | [diff] [blame] | 70 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 71 | class GCTests(unittest.TestCase): |
| 72 | def test_list(self): |
| 73 | l = [] |
| 74 | l.append(l) |
| 75 | gc.collect() |
| 76 | del l |
| 77 | self.assertEqual(gc.collect(), 1) |
Tim Peters | ead8b7a | 2004-10-30 23:09:22 +0000 | [diff] [blame] | 78 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 79 | def test_dict(self): |
| 80 | d = {} |
| 81 | d[1] = d |
| 82 | gc.collect() |
| 83 | del d |
| 84 | self.assertEqual(gc.collect(), 1) |
Tim Peters | ead8b7a | 2004-10-30 23:09:22 +0000 | [diff] [blame] | 85 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 86 | def test_tuple(self): |
| 87 | # since tuples are immutable we close the loop with a list |
| 88 | l = [] |
| 89 | t = (l,) |
| 90 | l.append(t) |
| 91 | gc.collect() |
| 92 | del t |
| 93 | del l |
| 94 | self.assertEqual(gc.collect(), 2) |
Tim Peters | ead8b7a | 2004-10-30 23:09:22 +0000 | [diff] [blame] | 95 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 96 | def test_class(self): |
| 97 | class A: |
| 98 | pass |
| 99 | A.a = A |
| 100 | gc.collect() |
| 101 | del A |
| 102 | self.assertNotEqual(gc.collect(), 0) |
Tim Peters | ead8b7a | 2004-10-30 23:09:22 +0000 | [diff] [blame] | 103 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 104 | def test_newstyleclass(self): |
| 105 | class A(object): |
| 106 | pass |
| 107 | gc.collect() |
| 108 | del A |
| 109 | self.assertNotEqual(gc.collect(), 0) |
Tim Peters | ead8b7a | 2004-10-30 23:09:22 +0000 | [diff] [blame] | 110 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 111 | def test_instance(self): |
| 112 | class A: |
| 113 | pass |
| 114 | a = A() |
| 115 | a.a = a |
| 116 | gc.collect() |
| 117 | del a |
| 118 | self.assertNotEqual(gc.collect(), 0) |
Tim Peters | ead8b7a | 2004-10-30 23:09:22 +0000 | [diff] [blame] | 119 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 120 | def test_newinstance(self): |
| 121 | class A(object): |
| 122 | pass |
| 123 | a = A() |
| 124 | a.a = a |
| 125 | gc.collect() |
| 126 | del a |
| 127 | self.assertNotEqual(gc.collect(), 0) |
| 128 | class B(list): |
| 129 | pass |
| 130 | class C(B, A): |
| 131 | pass |
| 132 | a = C() |
| 133 | a.a = a |
| 134 | gc.collect() |
| 135 | del a |
| 136 | self.assertNotEqual(gc.collect(), 0) |
| 137 | del B, C |
| 138 | self.assertNotEqual(gc.collect(), 0) |
| 139 | A.a = A() |
| 140 | del A |
| 141 | self.assertNotEqual(gc.collect(), 0) |
| 142 | self.assertEqual(gc.collect(), 0) |
Tim Peters | ead8b7a | 2004-10-30 23:09:22 +0000 | [diff] [blame] | 143 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 144 | def test_method(self): |
| 145 | # Tricky: self.__init__ is a bound method, it references the instance. |
| 146 | class A: |
| 147 | def __init__(self): |
| 148 | self.init = self.__init__ |
| 149 | a = A() |
| 150 | gc.collect() |
| 151 | del a |
| 152 | self.assertNotEqual(gc.collect(), 0) |
Tim Peters | ead8b7a | 2004-10-30 23:09:22 +0000 | [diff] [blame] | 153 | |
Serhiy Storchaka | f28ba36 | 2014-02-07 10:10:55 +0200 | [diff] [blame] | 154 | @cpython_only |
Antoine Pitrou | 796564c | 2013-07-30 19:59:21 +0200 | [diff] [blame] | 155 | def test_legacy_finalizer(self): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 156 | # A() is uncollectable if it is part of a cycle, make sure it shows up |
| 157 | # in gc.garbage. |
Serhiy Storchaka | f28ba36 | 2014-02-07 10:10:55 +0200 | [diff] [blame] | 158 | @with_tp_del |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 159 | class A: |
Antoine Pitrou | 796564c | 2013-07-30 19:59:21 +0200 | [diff] [blame] | 160 | def __tp_del__(self): pass |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 161 | class B: |
| 162 | pass |
| 163 | a = A() |
| 164 | a.a = a |
| 165 | id_a = id(a) |
| 166 | b = B() |
| 167 | b.b = b |
| 168 | gc.collect() |
| 169 | del a |
| 170 | del b |
| 171 | self.assertNotEqual(gc.collect(), 0) |
| 172 | for obj in gc.garbage: |
| 173 | if id(obj) == id_a: |
| 174 | del obj.a |
| 175 | break |
| 176 | else: |
| 177 | self.fail("didn't find obj in garbage (finalizer)") |
| 178 | gc.garbage.remove(obj) |
Tim Peters | ead8b7a | 2004-10-30 23:09:22 +0000 | [diff] [blame] | 179 | |
Serhiy Storchaka | f28ba36 | 2014-02-07 10:10:55 +0200 | [diff] [blame] | 180 | @cpython_only |
Antoine Pitrou | 796564c | 2013-07-30 19:59:21 +0200 | [diff] [blame] | 181 | def test_legacy_finalizer_newclass(self): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 182 | # A() is uncollectable if it is part of a cycle, make sure it shows up |
| 183 | # in gc.garbage. |
Serhiy Storchaka | f28ba36 | 2014-02-07 10:10:55 +0200 | [diff] [blame] | 184 | @with_tp_del |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 185 | class A(object): |
Antoine Pitrou | 796564c | 2013-07-30 19:59:21 +0200 | [diff] [blame] | 186 | def __tp_del__(self): pass |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 187 | class B(object): |
| 188 | pass |
| 189 | a = A() |
| 190 | a.a = a |
| 191 | id_a = id(a) |
| 192 | b = B() |
| 193 | b.b = b |
| 194 | gc.collect() |
| 195 | del a |
| 196 | del b |
| 197 | self.assertNotEqual(gc.collect(), 0) |
| 198 | for obj in gc.garbage: |
| 199 | if id(obj) == id_a: |
| 200 | del obj.a |
| 201 | break |
| 202 | else: |
| 203 | self.fail("didn't find obj in garbage (finalizer)") |
| 204 | gc.garbage.remove(obj) |
Tim Peters | ead8b7a | 2004-10-30 23:09:22 +0000 | [diff] [blame] | 205 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 206 | def test_function(self): |
| 207 | # Tricky: f -> d -> f, code should call d.clear() after the exec to |
| 208 | # break the cycle. |
| 209 | d = {} |
| 210 | exec("def f(): pass\n", d) |
| 211 | gc.collect() |
| 212 | del d |
| 213 | self.assertEqual(gc.collect(), 2) |
Tim Peters | ead8b7a | 2004-10-30 23:09:22 +0000 | [diff] [blame] | 214 | |
Brett Cannon | 7a54073 | 2011-02-22 03:04:06 +0000 | [diff] [blame] | 215 | @refcount_test |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 216 | def test_frame(self): |
| 217 | def f(): |
| 218 | frame = sys._getframe() |
| 219 | gc.collect() |
| 220 | f() |
| 221 | self.assertEqual(gc.collect(), 1) |
Tim Peters | ead8b7a | 2004-10-30 23:09:22 +0000 | [diff] [blame] | 222 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 223 | def test_saveall(self): |
| 224 | # Verify that cyclic garbage like lists show up in gc.garbage if the |
| 225 | # SAVEALL option is enabled. |
Tim Peters | ead8b7a | 2004-10-30 23:09:22 +0000 | [diff] [blame] | 226 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 227 | # First make sure we don't save away other stuff that just happens to |
| 228 | # be waiting for collection. |
| 229 | gc.collect() |
| 230 | # if this fails, someone else created immortal trash |
| 231 | self.assertEqual(gc.garbage, []) |
| 232 | |
| 233 | L = [] |
| 234 | L.append(L) |
| 235 | id_L = id(L) |
| 236 | |
| 237 | debug = gc.get_debug() |
| 238 | gc.set_debug(debug | gc.DEBUG_SAVEALL) |
| 239 | del L |
| 240 | gc.collect() |
| 241 | gc.set_debug(debug) |
| 242 | |
| 243 | self.assertEqual(len(gc.garbage), 1) |
| 244 | obj = gc.garbage.pop() |
| 245 | self.assertEqual(id(obj), id_L) |
| 246 | |
| 247 | def test_del(self): |
| 248 | # __del__ methods can trigger collection, make this to happen |
| 249 | thresholds = gc.get_threshold() |
| 250 | gc.enable() |
| 251 | gc.set_threshold(1) |
| 252 | |
| 253 | class A: |
| 254 | def __del__(self): |
| 255 | dir(self) |
| 256 | a = A() |
| 257 | del a |
| 258 | |
| 259 | gc.disable() |
| 260 | gc.set_threshold(*thresholds) |
| 261 | |
| 262 | def test_del_newclass(self): |
| 263 | # __del__ methods can trigger collection, make this to happen |
| 264 | thresholds = gc.get_threshold() |
| 265 | gc.enable() |
| 266 | gc.set_threshold(1) |
| 267 | |
| 268 | class A(object): |
| 269 | def __del__(self): |
| 270 | dir(self) |
| 271 | a = A() |
| 272 | del a |
| 273 | |
| 274 | gc.disable() |
| 275 | gc.set_threshold(*thresholds) |
| 276 | |
Christian Heimes | a156e09 | 2008-02-16 07:38:31 +0000 | [diff] [blame] | 277 | # The following two tests are fragile: |
| 278 | # They precisely count the number of allocations, |
| 279 | # which is highly implementation-dependent. |
Antoine Pitrou | b35f29a | 2011-04-04 19:50:42 +0200 | [diff] [blame] | 280 | # For example, disposed tuples are not freed, but reused. |
| 281 | # To minimize variations, though, we first store the get_count() results |
| 282 | # and check them at the end. |
Brett Cannon | 7a54073 | 2011-02-22 03:04:06 +0000 | [diff] [blame] | 283 | @refcount_test |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 284 | def test_get_count(self): |
| 285 | gc.collect() |
Antoine Pitrou | b35f29a | 2011-04-04 19:50:42 +0200 | [diff] [blame] | 286 | a, b, c = gc.get_count() |
| 287 | x = [] |
| 288 | d, e, f = gc.get_count() |
| 289 | self.assertEqual((b, c), (0, 0)) |
| 290 | self.assertEqual((e, f), (0, 0)) |
| 291 | # This is less fragile than asserting that a equals 0. |
| 292 | self.assertLess(a, 5) |
| 293 | # Between the two calls to get_count(), at least one object was |
| 294 | # created (the list). |
| 295 | self.assertGreater(d, a) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 296 | |
Brett Cannon | 7a54073 | 2011-02-22 03:04:06 +0000 | [diff] [blame] | 297 | @refcount_test |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 298 | def test_collect_generations(self): |
| 299 | gc.collect() |
Antoine Pitrou | b35f29a | 2011-04-04 19:50:42 +0200 | [diff] [blame] | 300 | # This object will "trickle" into generation N + 1 after |
| 301 | # each call to collect(N) |
| 302 | x = [] |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 303 | gc.collect(0) |
Antoine Pitrou | b35f29a | 2011-04-04 19:50:42 +0200 | [diff] [blame] | 304 | # x is now in gen 1 |
| 305 | a, b, c = gc.get_count() |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 306 | gc.collect(1) |
Antoine Pitrou | b35f29a | 2011-04-04 19:50:42 +0200 | [diff] [blame] | 307 | # x is now in gen 2 |
| 308 | d, e, f = gc.get_count() |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 309 | gc.collect(2) |
Antoine Pitrou | b35f29a | 2011-04-04 19:50:42 +0200 | [diff] [blame] | 310 | # x is now in gen 3 |
| 311 | g, h, i = gc.get_count() |
| 312 | # We don't check a, d, g since their exact values depends on |
| 313 | # internal implementation details of the interpreter. |
| 314 | self.assertEqual((b, c), (1, 0)) |
| 315 | self.assertEqual((e, f), (0, 1)) |
| 316 | self.assertEqual((h, i), (0, 0)) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 317 | |
| 318 | def test_trashcan(self): |
| 319 | class Ouch: |
| 320 | n = 0 |
| 321 | def __del__(self): |
| 322 | Ouch.n = Ouch.n + 1 |
| 323 | if Ouch.n % 17 == 0: |
| 324 | gc.collect() |
| 325 | |
| 326 | # "trashcan" is a hack to prevent stack overflow when deallocating |
| 327 | # very deeply nested tuples etc. It works in part by abusing the |
| 328 | # type pointer and refcount fields, and that can yield horrible |
| 329 | # problems when gc tries to traverse the structures. |
| 330 | # If this test fails (as it does in 2.0, 2.1 and 2.2), it will |
| 331 | # most likely die via segfault. |
| 332 | |
| 333 | # Note: In 2.3 the possibility for compiling without cyclic gc was |
| 334 | # removed, and that in turn allows the trashcan mechanism to work |
| 335 | # via much simpler means (e.g., it never abuses the type pointer or |
| 336 | # refcount fields anymore). Since it's much less likely to cause a |
| 337 | # problem now, the various constants in this expensive (we force a lot |
| 338 | # of full collections) test are cut back from the 2.2 version. |
| 339 | gc.enable() |
| 340 | N = 150 |
| 341 | for count in range(2): |
| 342 | t = [] |
| 343 | for i in range(N): |
| 344 | t = [t, Ouch()] |
| 345 | u = [] |
| 346 | for i in range(N): |
| 347 | u = [u, Ouch()] |
| 348 | v = {} |
| 349 | for i in range(N): |
| 350 | v = {1: v, 2: Ouch()} |
| 351 | gc.disable() |
| 352 | |
Antoine Pitrou | 2b0218a | 2012-09-06 00:59:49 +0200 | [diff] [blame] | 353 | @unittest.skipUnless(threading, "test meaningless on builds without threads") |
| 354 | def test_trashcan_threads(self): |
| 355 | # Issue #13992: trashcan mechanism should be thread-safe |
| 356 | NESTING = 60 |
| 357 | N_THREADS = 2 |
| 358 | |
| 359 | def sleeper_gen(): |
| 360 | """A generator that releases the GIL when closed or dealloc'ed.""" |
| 361 | try: |
| 362 | yield |
| 363 | finally: |
| 364 | time.sleep(0.000001) |
| 365 | |
| 366 | class C(list): |
| 367 | # Appending to a list is atomic, which avoids the use of a lock. |
| 368 | inits = [] |
| 369 | dels = [] |
| 370 | def __init__(self, alist): |
| 371 | self[:] = alist |
| 372 | C.inits.append(None) |
| 373 | def __del__(self): |
| 374 | # This __del__ is called by subtype_dealloc(). |
| 375 | C.dels.append(None) |
| 376 | # `g` will release the GIL when garbage-collected. This |
| 377 | # helps assert subtype_dealloc's behaviour when threads |
| 378 | # switch in the middle of it. |
| 379 | g = sleeper_gen() |
| 380 | next(g) |
| 381 | # Now that __del__ is finished, subtype_dealloc will proceed |
| 382 | # to call list_dealloc, which also uses the trashcan mechanism. |
| 383 | |
| 384 | def make_nested(): |
| 385 | """Create a sufficiently nested container object so that the |
| 386 | trashcan mechanism is invoked when deallocating it.""" |
| 387 | x = C([]) |
| 388 | for i in range(NESTING): |
| 389 | x = [C([x])] |
| 390 | del x |
| 391 | |
| 392 | def run_thread(): |
| 393 | """Exercise make_nested() in a loop.""" |
| 394 | while not exit: |
| 395 | make_nested() |
| 396 | |
| 397 | old_switchinterval = sys.getswitchinterval() |
| 398 | sys.setswitchinterval(1e-5) |
| 399 | try: |
| 400 | exit = False |
| 401 | threads = [] |
| 402 | for i in range(N_THREADS): |
| 403 | t = threading.Thread(target=run_thread) |
| 404 | threads.append(t) |
| 405 | for t in threads: |
| 406 | t.start() |
| 407 | time.sleep(1.0) |
| 408 | exit = True |
| 409 | for t in threads: |
| 410 | t.join() |
| 411 | finally: |
| 412 | sys.setswitchinterval(old_switchinterval) |
| 413 | gc.collect() |
| 414 | self.assertEqual(len(C.inits), len(C.dels)) |
| 415 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 416 | def test_boom(self): |
| 417 | class Boom: |
| 418 | def __getattr__(self, someattribute): |
| 419 | del self.attr |
| 420 | raise AttributeError |
| 421 | |
| 422 | a = Boom() |
| 423 | b = Boom() |
| 424 | a.attr = b |
| 425 | b.attr = a |
| 426 | |
| 427 | gc.collect() |
| 428 | garbagelen = len(gc.garbage) |
| 429 | del a, b |
| 430 | # a<->b are in a trash cycle now. Collection will invoke |
| 431 | # Boom.__getattr__ (to see whether a and b have __del__ methods), and |
| 432 | # __getattr__ deletes the internal "attr" attributes as a side effect. |
| 433 | # That causes the trash cycle to get reclaimed via refcounts falling to |
| 434 | # 0, thus mutating the trash graph as a side effect of merely asking |
| 435 | # whether __del__ exists. This used to (before 2.3b1) crash Python. |
| 436 | # Now __getattr__ isn't called. |
| 437 | self.assertEqual(gc.collect(), 4) |
| 438 | self.assertEqual(len(gc.garbage), garbagelen) |
| 439 | |
| 440 | def test_boom2(self): |
| 441 | class Boom2: |
| 442 | def __init__(self): |
| 443 | self.x = 0 |
| 444 | |
| 445 | def __getattr__(self, someattribute): |
| 446 | self.x += 1 |
| 447 | if self.x > 1: |
| 448 | del self.attr |
| 449 | raise AttributeError |
| 450 | |
| 451 | a = Boom2() |
| 452 | b = Boom2() |
| 453 | a.attr = b |
| 454 | b.attr = a |
| 455 | |
| 456 | gc.collect() |
| 457 | garbagelen = len(gc.garbage) |
| 458 | del a, b |
| 459 | # Much like test_boom(), except that __getattr__ doesn't break the |
| 460 | # cycle until the second time gc checks for __del__. As of 2.3b1, |
| 461 | # there isn't a second time, so this simply cleans up the trash cycle. |
| 462 | # We expect a, b, a.__dict__ and b.__dict__ (4 objects) to get |
| 463 | # reclaimed this way. |
| 464 | self.assertEqual(gc.collect(), 4) |
| 465 | self.assertEqual(len(gc.garbage), garbagelen) |
| 466 | |
| 467 | def test_boom_new(self): |
| 468 | # boom__new and boom2_new are exactly like boom and boom2, except use |
| 469 | # new-style classes. |
| 470 | |
| 471 | class Boom_New(object): |
| 472 | def __getattr__(self, someattribute): |
| 473 | del self.attr |
| 474 | raise AttributeError |
| 475 | |
| 476 | a = Boom_New() |
| 477 | b = Boom_New() |
| 478 | a.attr = b |
| 479 | b.attr = a |
| 480 | |
| 481 | gc.collect() |
| 482 | garbagelen = len(gc.garbage) |
| 483 | del a, b |
| 484 | self.assertEqual(gc.collect(), 4) |
| 485 | self.assertEqual(len(gc.garbage), garbagelen) |
| 486 | |
| 487 | def test_boom2_new(self): |
| 488 | class Boom2_New(object): |
| 489 | def __init__(self): |
| 490 | self.x = 0 |
| 491 | |
| 492 | def __getattr__(self, someattribute): |
| 493 | self.x += 1 |
| 494 | if self.x > 1: |
| 495 | del self.attr |
| 496 | raise AttributeError |
| 497 | |
| 498 | a = Boom2_New() |
| 499 | b = Boom2_New() |
| 500 | a.attr = b |
| 501 | b.attr = a |
| 502 | |
| 503 | gc.collect() |
| 504 | garbagelen = len(gc.garbage) |
| 505 | del a, b |
| 506 | self.assertEqual(gc.collect(), 4) |
| 507 | self.assertEqual(len(gc.garbage), garbagelen) |
| 508 | |
| 509 | def test_get_referents(self): |
| 510 | alist = [1, 3, 5] |
| 511 | got = gc.get_referents(alist) |
| 512 | got.sort() |
| 513 | self.assertEqual(got, alist) |
| 514 | |
| 515 | atuple = tuple(alist) |
| 516 | got = gc.get_referents(atuple) |
| 517 | got.sort() |
| 518 | self.assertEqual(got, alist) |
| 519 | |
| 520 | adict = {1: 3, 5: 7} |
| 521 | expected = [1, 3, 5, 7] |
| 522 | got = gc.get_referents(adict) |
| 523 | got.sort() |
| 524 | self.assertEqual(got, expected) |
| 525 | |
| 526 | got = gc.get_referents([1, 2], {3: 4}, (0, 0, 0)) |
| 527 | got.sort() |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 528 | self.assertEqual(got, [0, 0] + list(range(5))) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 529 | |
| 530 | self.assertEqual(gc.get_referents(1, 'a', 4j), []) |
| 531 | |
Antoine Pitrou | 3a652b1 | 2009-03-23 18:52:06 +0000 | [diff] [blame] | 532 | def test_is_tracked(self): |
| 533 | # Atomic built-in types are not tracked, user-defined objects and |
| 534 | # mutable containers are. |
| 535 | # NOTE: types with special optimizations (e.g. tuple) have tests |
| 536 | # in their own test files instead. |
| 537 | self.assertFalse(gc.is_tracked(None)) |
| 538 | self.assertFalse(gc.is_tracked(1)) |
| 539 | self.assertFalse(gc.is_tracked(1.0)) |
| 540 | self.assertFalse(gc.is_tracked(1.0 + 5.0j)) |
| 541 | self.assertFalse(gc.is_tracked(True)) |
| 542 | self.assertFalse(gc.is_tracked(False)) |
| 543 | self.assertFalse(gc.is_tracked(b"a")) |
| 544 | self.assertFalse(gc.is_tracked("a")) |
| 545 | self.assertFalse(gc.is_tracked(bytearray(b"a"))) |
| 546 | self.assertFalse(gc.is_tracked(type)) |
| 547 | self.assertFalse(gc.is_tracked(int)) |
| 548 | self.assertFalse(gc.is_tracked(object)) |
| 549 | self.assertFalse(gc.is_tracked(object())) |
| 550 | |
| 551 | class UserClass: |
| 552 | pass |
| 553 | self.assertTrue(gc.is_tracked(gc)) |
| 554 | self.assertTrue(gc.is_tracked(UserClass)) |
| 555 | self.assertTrue(gc.is_tracked(UserClass())) |
| 556 | self.assertTrue(gc.is_tracked([])) |
| 557 | self.assertTrue(gc.is_tracked(set())) |
| 558 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 559 | def test_bug1055820b(self): |
| 560 | # Corresponds to temp2b.py in the bug report. |
| 561 | |
| 562 | ouch = [] |
| 563 | def callback(ignored): |
| 564 | ouch[:] = [wr() for wr in WRs] |
| 565 | |
| 566 | Cs = [C1055820(i) for i in range(2)] |
| 567 | WRs = [weakref.ref(c, callback) for c in Cs] |
| 568 | c = None |
| 569 | |
| 570 | gc.collect() |
| 571 | self.assertEqual(len(ouch), 0) |
| 572 | # Make the two instances trash, and collect again. The bug was that |
| 573 | # the callback materialized a strong reference to an instance, but gc |
| 574 | # cleared the instance's dict anyway. |
| 575 | Cs = None |
| 576 | gc.collect() |
| 577 | self.assertEqual(len(ouch), 2) # else the callbacks didn't run |
| 578 | for x in ouch: |
| 579 | # If the callback resurrected one of these guys, the instance |
| 580 | # would be damaged, with an empty __dict__. |
| 581 | self.assertEqual(x, None) |
| 582 | |
Serhiy Storchaka | f28ba36 | 2014-02-07 10:10:55 +0200 | [diff] [blame] | 583 | @cpython_only |
Antoine Pitrou | 696e035 | 2010-08-08 22:18:46 +0000 | [diff] [blame] | 584 | def test_garbage_at_shutdown(self): |
| 585 | import subprocess |
| 586 | code = """if 1: |
| 587 | import gc |
Antoine Pitrou | 796564c | 2013-07-30 19:59:21 +0200 | [diff] [blame] | 588 | import _testcapi |
| 589 | @_testcapi.with_tp_del |
Antoine Pitrou | 696e035 | 2010-08-08 22:18:46 +0000 | [diff] [blame] | 590 | class X: |
| 591 | def __init__(self, name): |
| 592 | self.name = name |
| 593 | def __repr__(self): |
| 594 | return "<X %%r>" %% self.name |
Antoine Pitrou | 796564c | 2013-07-30 19:59:21 +0200 | [diff] [blame] | 595 | def __tp_del__(self): |
Antoine Pitrou | 696e035 | 2010-08-08 22:18:46 +0000 | [diff] [blame] | 596 | pass |
| 597 | |
| 598 | x = X('first') |
| 599 | x.x = x |
| 600 | x.y = X('second') |
| 601 | del x |
Antoine Pitrou | 2ed94eb | 2010-09-14 09:48:39 +0000 | [diff] [blame] | 602 | gc.set_debug(%s) |
Antoine Pitrou | 696e035 | 2010-08-08 22:18:46 +0000 | [diff] [blame] | 603 | """ |
| 604 | def run_command(code): |
Georg Brandl | 08be72d | 2010-10-24 15:11:22 +0000 | [diff] [blame] | 605 | p = subprocess.Popen([sys.executable, "-Wd", "-c", code], |
Antoine Pitrou | 696e035 | 2010-08-08 22:18:46 +0000 | [diff] [blame] | 606 | stdout=subprocess.PIPE, |
| 607 | stderr=subprocess.PIPE) |
| 608 | stdout, stderr = p.communicate() |
Brian Curtin | 8291af2 | 2010-11-01 16:40:17 +0000 | [diff] [blame] | 609 | p.stdout.close() |
| 610 | p.stderr.close() |
Antoine Pitrou | 696e035 | 2010-08-08 22:18:46 +0000 | [diff] [blame] | 611 | self.assertEqual(p.returncode, 0) |
| 612 | self.assertEqual(stdout.strip(), b"") |
| 613 | return strip_python_stderr(stderr) |
| 614 | |
Antoine Pitrou | 2ed94eb | 2010-09-14 09:48:39 +0000 | [diff] [blame] | 615 | stderr = run_command(code % "0") |
Georg Brandl | 08be72d | 2010-10-24 15:11:22 +0000 | [diff] [blame] | 616 | self.assertIn(b"ResourceWarning: gc: 2 uncollectable objects at " |
| 617 | b"shutdown; use", stderr) |
Antoine Pitrou | aee4756 | 2010-09-16 15:04:49 +0000 | [diff] [blame] | 618 | self.assertNotIn(b"<X 'first'>", stderr) |
Antoine Pitrou | 696e035 | 2010-08-08 22:18:46 +0000 | [diff] [blame] | 619 | # With DEBUG_UNCOLLECTABLE, the garbage list gets printed |
Antoine Pitrou | 2ed94eb | 2010-09-14 09:48:39 +0000 | [diff] [blame] | 620 | stderr = run_command(code % "gc.DEBUG_UNCOLLECTABLE") |
Georg Brandl | 08be72d | 2010-10-24 15:11:22 +0000 | [diff] [blame] | 621 | self.assertIn(b"ResourceWarning: gc: 2 uncollectable objects at " |
| 622 | b"shutdown", stderr) |
Antoine Pitrou | aee4756 | 2010-09-16 15:04:49 +0000 | [diff] [blame] | 623 | self.assertTrue( |
| 624 | (b"[<X 'first'>, <X 'second'>]" in stderr) or |
| 625 | (b"[<X 'second'>, <X 'first'>]" in stderr), stderr) |
Antoine Pitrou | 2ed94eb | 2010-09-14 09:48:39 +0000 | [diff] [blame] | 626 | # With DEBUG_SAVEALL, no additional message should get printed |
| 627 | # (because gc.garbage also contains normally reclaimable cyclic |
| 628 | # references, and its elements get printed at runtime anyway). |
| 629 | stderr = run_command(code % "gc.DEBUG_SAVEALL") |
| 630 | self.assertNotIn(b"uncollectable objects at shutdown", stderr) |
| 631 | |
Antoine Pitrou | 5f454a0 | 2013-05-06 21:15:57 +0200 | [diff] [blame] | 632 | def test_gc_main_module_at_shutdown(self): |
| 633 | # Create a reference cycle through the __main__ module and check |
| 634 | # it gets collected at interpreter shutdown. |
| 635 | code = """if 1: |
| 636 | import weakref |
| 637 | class C: |
| 638 | def __del__(self): |
| 639 | print('__del__ called') |
| 640 | l = [C()] |
| 641 | l.append(l) |
| 642 | """ |
| 643 | rc, out, err = assert_python_ok('-c', code) |
| 644 | self.assertEqual(out.strip(), b'__del__ called') |
| 645 | |
| 646 | def test_gc_ordinary_module_at_shutdown(self): |
| 647 | # Same as above, but with a non-__main__ module. |
| 648 | with temp_dir() as script_dir: |
| 649 | module = """if 1: |
| 650 | import weakref |
| 651 | class C: |
| 652 | def __del__(self): |
| 653 | print('__del__ called') |
| 654 | l = [C()] |
| 655 | l.append(l) |
| 656 | """ |
| 657 | code = """if 1: |
| 658 | import sys |
| 659 | sys.path.insert(0, %r) |
| 660 | import gctest |
| 661 | """ % (script_dir,) |
| 662 | make_script(script_dir, 'gctest', module) |
| 663 | rc, out, err = assert_python_ok('-c', code) |
| 664 | self.assertEqual(out.strip(), b'__del__ called') |
| 665 | |
Antoine Pitrou | d4156c1 | 2012-10-30 22:43:19 +0100 | [diff] [blame] | 666 | def test_get_stats(self): |
| 667 | stats = gc.get_stats() |
| 668 | self.assertEqual(len(stats), 3) |
| 669 | for st in stats: |
| 670 | self.assertIsInstance(st, dict) |
| 671 | self.assertEqual(set(st), |
| 672 | {"collected", "collections", "uncollectable"}) |
| 673 | self.assertGreaterEqual(st["collected"], 0) |
| 674 | self.assertGreaterEqual(st["collections"], 0) |
| 675 | self.assertGreaterEqual(st["uncollectable"], 0) |
| 676 | # Check that collection counts are incremented correctly |
| 677 | if gc.isenabled(): |
| 678 | self.addCleanup(gc.enable) |
| 679 | gc.disable() |
| 680 | old = gc.get_stats() |
| 681 | gc.collect(0) |
| 682 | new = gc.get_stats() |
| 683 | self.assertEqual(new[0]["collections"], old[0]["collections"] + 1) |
| 684 | self.assertEqual(new[1]["collections"], old[1]["collections"]) |
| 685 | self.assertEqual(new[2]["collections"], old[2]["collections"]) |
| 686 | gc.collect(2) |
| 687 | new = gc.get_stats() |
| 688 | self.assertEqual(new[0]["collections"], old[0]["collections"] + 1) |
| 689 | self.assertEqual(new[1]["collections"], old[1]["collections"]) |
| 690 | self.assertEqual(new[2]["collections"], old[2]["collections"] + 1) |
| 691 | |
Antoine Pitrou | 696e035 | 2010-08-08 22:18:46 +0000 | [diff] [blame] | 692 | |
Kristján Valur Jónsson | 69c6352 | 2012-04-15 11:41:32 +0000 | [diff] [blame] | 693 | class GCCallbackTests(unittest.TestCase): |
| 694 | def setUp(self): |
| 695 | # Save gc state and disable it. |
| 696 | self.enabled = gc.isenabled() |
| 697 | gc.disable() |
| 698 | self.debug = gc.get_debug() |
| 699 | gc.set_debug(0) |
| 700 | gc.callbacks.append(self.cb1) |
| 701 | gc.callbacks.append(self.cb2) |
Antoine Pitrou | 6b64fc6 | 2012-04-16 21:29:02 +0200 | [diff] [blame] | 702 | self.othergarbage = [] |
Kristján Valur Jónsson | 69c6352 | 2012-04-15 11:41:32 +0000 | [diff] [blame] | 703 | |
| 704 | def tearDown(self): |
| 705 | # Restore gc state |
| 706 | del self.visit |
| 707 | gc.callbacks.remove(self.cb1) |
| 708 | gc.callbacks.remove(self.cb2) |
| 709 | gc.set_debug(self.debug) |
| 710 | if self.enabled: |
| 711 | gc.enable() |
| 712 | # destroy any uncollectables |
| 713 | gc.collect() |
| 714 | for obj in gc.garbage: |
| 715 | if isinstance(obj, Uncollectable): |
| 716 | obj.partner = None |
| 717 | del gc.garbage[:] |
Antoine Pitrou | 6b64fc6 | 2012-04-16 21:29:02 +0200 | [diff] [blame] | 718 | del self.othergarbage |
Kristján Valur Jónsson | 69c6352 | 2012-04-15 11:41:32 +0000 | [diff] [blame] | 719 | gc.collect() |
| 720 | |
Kristján Valur Jónsson | 69c6352 | 2012-04-15 11:41:32 +0000 | [diff] [blame] | 721 | def preclean(self): |
| 722 | # Remove all fluff from the system. Invoke this function |
| 723 | # manually rather than through self.setUp() for maximum |
| 724 | # safety. |
| 725 | self.visit = [] |
| 726 | gc.collect() |
| 727 | garbage, gc.garbage[:] = gc.garbage[:], [] |
| 728 | self.othergarbage.append(garbage) |
| 729 | self.visit = [] |
| 730 | |
| 731 | def cb1(self, phase, info): |
| 732 | self.visit.append((1, phase, dict(info))) |
| 733 | |
| 734 | def cb2(self, phase, info): |
| 735 | self.visit.append((2, phase, dict(info))) |
| 736 | if phase == "stop" and hasattr(self, "cleanup"): |
| 737 | # Clean Uncollectable from garbage |
| 738 | uc = [e for e in gc.garbage if isinstance(e, Uncollectable)] |
| 739 | gc.garbage[:] = [e for e in gc.garbage |
| 740 | if not isinstance(e, Uncollectable)] |
| 741 | for e in uc: |
| 742 | e.partner = None |
| 743 | |
Antoine Pitrou | de3c73b | 2012-04-16 21:29:58 +0200 | [diff] [blame] | 744 | def test_collect(self): |
Kristján Valur Jónsson | 69c6352 | 2012-04-15 11:41:32 +0000 | [diff] [blame] | 745 | self.preclean() |
| 746 | gc.collect() |
| 747 | # Algorithmically verify the contents of self.visit |
| 748 | # because it is long and tortuous. |
| 749 | |
| 750 | # Count the number of visits to each callback |
| 751 | n = [v[0] for v in self.visit] |
| 752 | n1 = [i for i in n if i == 1] |
| 753 | n2 = [i for i in n if i == 2] |
| 754 | self.assertEqual(n1, [1]*2) |
| 755 | self.assertEqual(n2, [2]*2) |
| 756 | |
| 757 | # Count that we got the right number of start and stop callbacks. |
| 758 | n = [v[1] for v in self.visit] |
| 759 | n1 = [i for i in n if i == "start"] |
| 760 | n2 = [i for i in n if i == "stop"] |
| 761 | self.assertEqual(n1, ["start"]*2) |
| 762 | self.assertEqual(n2, ["stop"]*2) |
| 763 | |
| 764 | # Check that we got the right info dict for all callbacks |
| 765 | for v in self.visit: |
| 766 | info = v[2] |
| 767 | self.assertTrue("generation" in info) |
| 768 | self.assertTrue("collected" in info) |
| 769 | self.assertTrue("uncollectable" in info) |
| 770 | |
Antoine Pitrou | de3c73b | 2012-04-16 21:29:58 +0200 | [diff] [blame] | 771 | def test_collect_generation(self): |
Kristján Valur Jónsson | 69c6352 | 2012-04-15 11:41:32 +0000 | [diff] [blame] | 772 | self.preclean() |
| 773 | gc.collect(2) |
| 774 | for v in self.visit: |
| 775 | info = v[2] |
| 776 | self.assertEqual(info["generation"], 2) |
| 777 | |
Serhiy Storchaka | f28ba36 | 2014-02-07 10:10:55 +0200 | [diff] [blame] | 778 | @cpython_only |
Antoine Pitrou | de3c73b | 2012-04-16 21:29:58 +0200 | [diff] [blame] | 779 | def test_collect_garbage(self): |
Kristján Valur Jónsson | 69c6352 | 2012-04-15 11:41:32 +0000 | [diff] [blame] | 780 | self.preclean() |
| 781 | # Each of these cause four objects to be garbage: Two |
| 782 | # Uncolectables and their instance dicts. |
| 783 | Uncollectable() |
| 784 | Uncollectable() |
| 785 | C1055820(666) |
| 786 | gc.collect() |
| 787 | for v in self.visit: |
| 788 | if v[1] != "stop": |
| 789 | continue |
| 790 | info = v[2] |
| 791 | self.assertEqual(info["collected"], 2) |
| 792 | self.assertEqual(info["uncollectable"], 8) |
| 793 | |
| 794 | # We should now have the Uncollectables in gc.garbage |
| 795 | self.assertEqual(len(gc.garbage), 4) |
| 796 | for e in gc.garbage: |
| 797 | self.assertIsInstance(e, Uncollectable) |
| 798 | |
| 799 | # Now, let our callback handle the Uncollectable instances |
| 800 | self.cleanup=True |
| 801 | self.visit = [] |
| 802 | gc.garbage[:] = [] |
| 803 | gc.collect() |
| 804 | for v in self.visit: |
| 805 | if v[1] != "stop": |
| 806 | continue |
| 807 | info = v[2] |
| 808 | self.assertEqual(info["collected"], 0) |
| 809 | self.assertEqual(info["uncollectable"], 4) |
| 810 | |
| 811 | # Uncollectables should be gone |
| 812 | self.assertEqual(len(gc.garbage), 0) |
| 813 | |
| 814 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 815 | class GCTogglingTests(unittest.TestCase): |
| 816 | def setUp(self): |
| 817 | gc.enable() |
| 818 | |
| 819 | def tearDown(self): |
| 820 | gc.disable() |
| 821 | |
| 822 | def test_bug1055820c(self): |
| 823 | # Corresponds to temp2c.py in the bug report. This is pretty |
| 824 | # elaborate. |
| 825 | |
| 826 | c0 = C1055820(0) |
| 827 | # Move c0 into generation 2. |
| 828 | gc.collect() |
| 829 | |
| 830 | c1 = C1055820(1) |
| 831 | c1.keep_c0_alive = c0 |
| 832 | del c0.loop # now only c1 keeps c0 alive |
| 833 | |
| 834 | c2 = C1055820(2) |
| 835 | c2wr = weakref.ref(c2) # no callback! |
| 836 | |
| 837 | ouch = [] |
| 838 | def callback(ignored): |
Tim Peters | ead8b7a | 2004-10-30 23:09:22 +0000 | [diff] [blame] | 839 | ouch[:] = [c2wr()] |
| 840 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 841 | # The callback gets associated with a wr on an object in generation 2. |
| 842 | c0wr = weakref.ref(c0, callback) |
Tim Peters | ead8b7a | 2004-10-30 23:09:22 +0000 | [diff] [blame] | 843 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 844 | c0 = c1 = c2 = None |
Tim Peters | ead8b7a | 2004-10-30 23:09:22 +0000 | [diff] [blame] | 845 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 846 | # What we've set up: c0, c1, and c2 are all trash now. c0 is in |
| 847 | # generation 2. The only thing keeping it alive is that c1 points to |
| 848 | # it. c1 and c2 are in generation 0, and are in self-loops. There's a |
| 849 | # global weakref to c2 (c2wr), but that weakref has no callback. |
| 850 | # There's also a global weakref to c0 (c0wr), and that does have a |
| 851 | # callback, and that callback references c2 via c2wr(). |
| 852 | # |
| 853 | # c0 has a wr with callback, which references c2wr |
| 854 | # ^ |
| 855 | # | |
| 856 | # | Generation 2 above dots |
| 857 | #. . . . . . . .|. . . . . . . . . . . . . . . . . . . . . . . . |
| 858 | # | Generation 0 below dots |
| 859 | # | |
| 860 | # | |
| 861 | # ^->c1 ^->c2 has a wr but no callback |
| 862 | # | | | | |
| 863 | # <--v <--v |
| 864 | # |
| 865 | # So this is the nightmare: when generation 0 gets collected, we see |
| 866 | # that c2 has a callback-free weakref, and c1 doesn't even have a |
| 867 | # weakref. Collecting generation 0 doesn't see c0 at all, and c0 is |
| 868 | # the only object that has a weakref with a callback. gc clears c1 |
| 869 | # and c2. Clearing c1 has the side effect of dropping the refcount on |
| 870 | # c0 to 0, so c0 goes away (despite that it's in an older generation) |
| 871 | # and c0's wr callback triggers. That in turn materializes a reference |
| 872 | # to c2 via c2wr(), but c2 gets cleared anyway by gc. |
Tim Peters | ead8b7a | 2004-10-30 23:09:22 +0000 | [diff] [blame] | 873 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 874 | # We want to let gc happen "naturally", to preserve the distinction |
| 875 | # between generations. |
| 876 | junk = [] |
| 877 | i = 0 |
| 878 | detector = GC_Detector() |
| 879 | while not detector.gc_happened: |
| 880 | i += 1 |
| 881 | if i > 10000: |
| 882 | self.fail("gc didn't happen after 10000 iterations") |
| 883 | self.assertEqual(len(ouch), 0) |
| 884 | junk.append([]) # this will eventually trigger gc |
Tim Peters | ead8b7a | 2004-10-30 23:09:22 +0000 | [diff] [blame] | 885 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 886 | self.assertEqual(len(ouch), 1) # else the callback wasn't invoked |
| 887 | for x in ouch: |
| 888 | # If the callback resurrected c2, the instance would be damaged, |
| 889 | # with an empty __dict__. |
| 890 | self.assertEqual(x, None) |
Tim Peters | ead8b7a | 2004-10-30 23:09:22 +0000 | [diff] [blame] | 891 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 892 | def test_bug1055820d(self): |
| 893 | # Corresponds to temp2d.py in the bug report. This is very much like |
| 894 | # test_bug1055820c, but uses a __del__ method instead of a weakref |
| 895 | # callback to sneak in a resurrection of cyclic trash. |
Tim Peters | ead8b7a | 2004-10-30 23:09:22 +0000 | [diff] [blame] | 896 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 897 | ouch = [] |
| 898 | class D(C1055820): |
| 899 | def __del__(self): |
| 900 | ouch[:] = [c2wr()] |
Tim Peters | ead8b7a | 2004-10-30 23:09:22 +0000 | [diff] [blame] | 901 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 902 | d0 = D(0) |
| 903 | # Move all the above into generation 2. |
| 904 | gc.collect() |
Tim Peters | ead8b7a | 2004-10-30 23:09:22 +0000 | [diff] [blame] | 905 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 906 | c1 = C1055820(1) |
| 907 | c1.keep_d0_alive = d0 |
| 908 | del d0.loop # now only c1 keeps d0 alive |
Tim Peters | ead8b7a | 2004-10-30 23:09:22 +0000 | [diff] [blame] | 909 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 910 | c2 = C1055820(2) |
| 911 | c2wr = weakref.ref(c2) # no callback! |
Tim Peters | ead8b7a | 2004-10-30 23:09:22 +0000 | [diff] [blame] | 912 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 913 | d0 = c1 = c2 = None |
Vladimir Marangozov | f9d20c3 | 2000-08-06 22:45:31 +0000 | [diff] [blame] | 914 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 915 | # What we've set up: d0, c1, and c2 are all trash now. d0 is in |
| 916 | # generation 2. The only thing keeping it alive is that c1 points to |
| 917 | # it. c1 and c2 are in generation 0, and are in self-loops. There's |
| 918 | # a global weakref to c2 (c2wr), but that weakref has no callback. |
| 919 | # There are no other weakrefs. |
| 920 | # |
| 921 | # d0 has a __del__ method that references c2wr |
| 922 | # ^ |
| 923 | # | |
| 924 | # | Generation 2 above dots |
| 925 | #. . . . . . . .|. . . . . . . . . . . . . . . . . . . . . . . . |
| 926 | # | Generation 0 below dots |
| 927 | # | |
| 928 | # | |
| 929 | # ^->c1 ^->c2 has a wr but no callback |
| 930 | # | | | | |
| 931 | # <--v <--v |
| 932 | # |
| 933 | # So this is the nightmare: when generation 0 gets collected, we see |
| 934 | # that c2 has a callback-free weakref, and c1 doesn't even have a |
| 935 | # weakref. Collecting generation 0 doesn't see d0 at all. gc clears |
| 936 | # c1 and c2. Clearing c1 has the side effect of dropping the refcount |
| 937 | # on d0 to 0, so d0 goes away (despite that it's in an older |
| 938 | # generation) and d0's __del__ triggers. That in turn materializes |
| 939 | # a reference to c2 via c2wr(), but c2 gets cleared anyway by gc. |
| 940 | |
| 941 | # We want to let gc happen "naturally", to preserve the distinction |
| 942 | # between generations. |
| 943 | detector = GC_Detector() |
| 944 | junk = [] |
| 945 | i = 0 |
| 946 | while not detector.gc_happened: |
| 947 | i += 1 |
| 948 | if i > 10000: |
| 949 | self.fail("gc didn't happen after 10000 iterations") |
| 950 | self.assertEqual(len(ouch), 0) |
| 951 | junk.append([]) # this will eventually trigger gc |
| 952 | |
| 953 | self.assertEqual(len(ouch), 1) # else __del__ wasn't invoked |
| 954 | for x in ouch: |
| 955 | # If __del__ resurrected c2, the instance would be damaged, with an |
| 956 | # empty __dict__. |
| 957 | self.assertEqual(x, None) |
| 958 | |
| 959 | def test_main(): |
Vladimir Marangozov | f9d20c3 | 2000-08-06 22:45:31 +0000 | [diff] [blame] | 960 | enabled = gc.isenabled() |
| 961 | gc.disable() |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 962 | assert not gc.isenabled() |
Neil Schemenauer | faae266 | 2000-09-22 15:26:20 +0000 | [diff] [blame] | 963 | debug = gc.get_debug() |
| 964 | gc.set_debug(debug & ~gc.DEBUG_LEAK) # this test is supposed to leak |
Vladimir Marangozov | f9d20c3 | 2000-08-06 22:45:31 +0000 | [diff] [blame] | 965 | |
Neil Schemenauer | faae266 | 2000-09-22 15:26:20 +0000 | [diff] [blame] | 966 | try: |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 967 | gc.collect() # Delete 2nd generation garbage |
Kristján Valur Jónsson | 69c6352 | 2012-04-15 11:41:32 +0000 | [diff] [blame] | 968 | run_unittest(GCTests, GCTogglingTests, GCCallbackTests) |
Neil Schemenauer | faae266 | 2000-09-22 15:26:20 +0000 | [diff] [blame] | 969 | finally: |
| 970 | gc.set_debug(debug) |
| 971 | # test gc.enable() even if GC is disabled by default |
| 972 | if verbose: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 973 | print("restoring automatic collection") |
Neil Schemenauer | faae266 | 2000-09-22 15:26:20 +0000 | [diff] [blame] | 974 | # make sure to always test gc.enable() |
| 975 | gc.enable() |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 976 | assert gc.isenabled() |
Neil Schemenauer | faae266 | 2000-09-22 15:26:20 +0000 | [diff] [blame] | 977 | if not enabled: |
| 978 | gc.disable() |
Vladimir Marangozov | f9d20c3 | 2000-08-06 22:45:31 +0000 | [diff] [blame] | 979 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 980 | if __name__ == "__main__": |
| 981 | test_main() |