blob: c025512790cd451500698abdfba20a736cb20ec1 [file] [log] [blame]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001import unittest
Brett Cannon7a540732011-02-22 03:04:06 +00002from test.support import (verbose, refcount_test, run_unittest,
Serhiy Storchakaf28ba362014-02-07 10:10:55 +02003 strip_python_stderr, cpython_only)
Antoine Pitrou5f454a02013-05-06 21:15:57 +02004from test.script_helper import assert_python_ok, make_script, temp_dir
5
Neil Schemenauer88c761a2001-07-12 13:25:53 +00006import sys
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02007import time
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00008import gc
Tim Petersead8b7a2004-10-30 23:09:22 +00009import weakref
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000010
Antoine Pitrou2b0218a2012-09-06 00:59:49 +020011try:
12 import threading
13except ImportError:
14 threading = None
15
Serhiy Storchakaf28ba362014-02-07 10:10:55 +020016try:
17 from _testcapi import with_tp_del
18except 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 Rossumd8faa362007-04-27 19:54:29 +000025### Support code
26###############################################################################
Tim Peters0f81ab62003-04-08 16:39:48 +000027
Tim Petersead8b7a2004-10-30 23:09:22 +000028# 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.
33class C1055820(object):
34 def __init__(self, i):
35 self.i = i
36 self.loop = self
37
38class 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 Storchakaf28ba362014-02-07 10:10:55 +020052@with_tp_del
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +000053class 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 Pitrou796564c2013-07-30 19:59:21 +020065 def __tp_del__(self):
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +000066 pass
Tim Petersead8b7a2004-10-30 23:09:22 +000067
Guido van Rossumd8faa362007-04-27 19:54:29 +000068### Tests
69###############################################################################
Tim Petersead8b7a2004-10-30 23:09:22 +000070
Guido van Rossumd8faa362007-04-27 19:54:29 +000071class 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 Petersead8b7a2004-10-30 23:09:22 +000078
Guido van Rossumd8faa362007-04-27 19:54:29 +000079 def test_dict(self):
80 d = {}
81 d[1] = d
82 gc.collect()
83 del d
84 self.assertEqual(gc.collect(), 1)
Tim Petersead8b7a2004-10-30 23:09:22 +000085
Guido van Rossumd8faa362007-04-27 19:54:29 +000086 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 Petersead8b7a2004-10-30 23:09:22 +000095
Guido van Rossumd8faa362007-04-27 19:54:29 +000096 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 Petersead8b7a2004-10-30 23:09:22 +0000103
Guido van Rossumd8faa362007-04-27 19:54:29 +0000104 def test_newstyleclass(self):
105 class A(object):
106 pass
107 gc.collect()
108 del A
109 self.assertNotEqual(gc.collect(), 0)
Tim Petersead8b7a2004-10-30 23:09:22 +0000110
Guido van Rossumd8faa362007-04-27 19:54:29 +0000111 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 Petersead8b7a2004-10-30 23:09:22 +0000119
Guido van Rossumd8faa362007-04-27 19:54:29 +0000120 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 Petersead8b7a2004-10-30 23:09:22 +0000143
Guido van Rossumd8faa362007-04-27 19:54:29 +0000144 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 Petersead8b7a2004-10-30 23:09:22 +0000153
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200154 @cpython_only
Antoine Pitrou796564c2013-07-30 19:59:21 +0200155 def test_legacy_finalizer(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000156 # A() is uncollectable if it is part of a cycle, make sure it shows up
157 # in gc.garbage.
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200158 @with_tp_del
Guido van Rossumd8faa362007-04-27 19:54:29 +0000159 class A:
Antoine Pitrou796564c2013-07-30 19:59:21 +0200160 def __tp_del__(self): pass
Guido van Rossumd8faa362007-04-27 19:54:29 +0000161 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 Petersead8b7a2004-10-30 23:09:22 +0000179
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200180 @cpython_only
Antoine Pitrou796564c2013-07-30 19:59:21 +0200181 def test_legacy_finalizer_newclass(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000182 # A() is uncollectable if it is part of a cycle, make sure it shows up
183 # in gc.garbage.
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200184 @with_tp_del
Guido van Rossumd8faa362007-04-27 19:54:29 +0000185 class A(object):
Antoine Pitrou796564c2013-07-30 19:59:21 +0200186 def __tp_del__(self): pass
Guido van Rossumd8faa362007-04-27 19:54:29 +0000187 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 Petersead8b7a2004-10-30 23:09:22 +0000205
Guido van Rossumd8faa362007-04-27 19:54:29 +0000206 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 Petersead8b7a2004-10-30 23:09:22 +0000214
Brett Cannon7a540732011-02-22 03:04:06 +0000215 @refcount_test
Guido van Rossumd8faa362007-04-27 19:54:29 +0000216 def test_frame(self):
217 def f():
218 frame = sys._getframe()
219 gc.collect()
220 f()
221 self.assertEqual(gc.collect(), 1)
Tim Petersead8b7a2004-10-30 23:09:22 +0000222
Guido van Rossumd8faa362007-04-27 19:54:29 +0000223 def test_saveall(self):
224 # Verify that cyclic garbage like lists show up in gc.garbage if the
225 # SAVEALL option is enabled.
Tim Petersead8b7a2004-10-30 23:09:22 +0000226
Guido van Rossumd8faa362007-04-27 19:54:29 +0000227 # 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 Heimesa156e092008-02-16 07:38:31 +0000277 # The following two tests are fragile:
278 # They precisely count the number of allocations,
279 # which is highly implementation-dependent.
Antoine Pitroub35f29a2011-04-04 19:50:42 +0200280 # 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 Cannon7a540732011-02-22 03:04:06 +0000283 @refcount_test
Guido van Rossumd8faa362007-04-27 19:54:29 +0000284 def test_get_count(self):
285 gc.collect()
Antoine Pitroub35f29a2011-04-04 19:50:42 +0200286 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 Rossumd8faa362007-04-27 19:54:29 +0000296
Brett Cannon7a540732011-02-22 03:04:06 +0000297 @refcount_test
Guido van Rossumd8faa362007-04-27 19:54:29 +0000298 def test_collect_generations(self):
299 gc.collect()
Antoine Pitroub35f29a2011-04-04 19:50:42 +0200300 # This object will "trickle" into generation N + 1 after
301 # each call to collect(N)
302 x = []
Guido van Rossumd8faa362007-04-27 19:54:29 +0000303 gc.collect(0)
Antoine Pitroub35f29a2011-04-04 19:50:42 +0200304 # x is now in gen 1
305 a, b, c = gc.get_count()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000306 gc.collect(1)
Antoine Pitroub35f29a2011-04-04 19:50:42 +0200307 # x is now in gen 2
308 d, e, f = gc.get_count()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000309 gc.collect(2)
Antoine Pitroub35f29a2011-04-04 19:50:42 +0200310 # 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 Rossumd8faa362007-04-27 19:54:29 +0000317
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 Pitrou2b0218a2012-09-06 00:59:49 +0200353 @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)
Serhiy Storchaka9db55002015-03-28 20:38:37 +0200405 try:
406 for t in threads:
407 t.start()
408 finally:
409 time.sleep(1.0)
410 exit = True
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200411 for t in threads:
412 t.join()
413 finally:
414 sys.setswitchinterval(old_switchinterval)
415 gc.collect()
416 self.assertEqual(len(C.inits), len(C.dels))
417
Guido van Rossumd8faa362007-04-27 19:54:29 +0000418 def test_boom(self):
419 class Boom:
420 def __getattr__(self, someattribute):
421 del self.attr
422 raise AttributeError
423
424 a = Boom()
425 b = Boom()
426 a.attr = b
427 b.attr = a
428
429 gc.collect()
430 garbagelen = len(gc.garbage)
431 del a, b
432 # a<->b are in a trash cycle now. Collection will invoke
433 # Boom.__getattr__ (to see whether a and b have __del__ methods), and
434 # __getattr__ deletes the internal "attr" attributes as a side effect.
435 # That causes the trash cycle to get reclaimed via refcounts falling to
436 # 0, thus mutating the trash graph as a side effect of merely asking
437 # whether __del__ exists. This used to (before 2.3b1) crash Python.
438 # Now __getattr__ isn't called.
439 self.assertEqual(gc.collect(), 4)
440 self.assertEqual(len(gc.garbage), garbagelen)
441
442 def test_boom2(self):
443 class Boom2:
444 def __init__(self):
445 self.x = 0
446
447 def __getattr__(self, someattribute):
448 self.x += 1
449 if self.x > 1:
450 del self.attr
451 raise AttributeError
452
453 a = Boom2()
454 b = Boom2()
455 a.attr = b
456 b.attr = a
457
458 gc.collect()
459 garbagelen = len(gc.garbage)
460 del a, b
461 # Much like test_boom(), except that __getattr__ doesn't break the
462 # cycle until the second time gc checks for __del__. As of 2.3b1,
463 # there isn't a second time, so this simply cleans up the trash cycle.
464 # We expect a, b, a.__dict__ and b.__dict__ (4 objects) to get
465 # reclaimed this way.
466 self.assertEqual(gc.collect(), 4)
467 self.assertEqual(len(gc.garbage), garbagelen)
468
469 def test_boom_new(self):
470 # boom__new and boom2_new are exactly like boom and boom2, except use
471 # new-style classes.
472
473 class Boom_New(object):
474 def __getattr__(self, someattribute):
475 del self.attr
476 raise AttributeError
477
478 a = Boom_New()
479 b = Boom_New()
480 a.attr = b
481 b.attr = a
482
483 gc.collect()
484 garbagelen = len(gc.garbage)
485 del a, b
486 self.assertEqual(gc.collect(), 4)
487 self.assertEqual(len(gc.garbage), garbagelen)
488
489 def test_boom2_new(self):
490 class Boom2_New(object):
491 def __init__(self):
492 self.x = 0
493
494 def __getattr__(self, someattribute):
495 self.x += 1
496 if self.x > 1:
497 del self.attr
498 raise AttributeError
499
500 a = Boom2_New()
501 b = Boom2_New()
502 a.attr = b
503 b.attr = a
504
505 gc.collect()
506 garbagelen = len(gc.garbage)
507 del a, b
508 self.assertEqual(gc.collect(), 4)
509 self.assertEqual(len(gc.garbage), garbagelen)
510
511 def test_get_referents(self):
512 alist = [1, 3, 5]
513 got = gc.get_referents(alist)
514 got.sort()
515 self.assertEqual(got, alist)
516
517 atuple = tuple(alist)
518 got = gc.get_referents(atuple)
519 got.sort()
520 self.assertEqual(got, alist)
521
522 adict = {1: 3, 5: 7}
523 expected = [1, 3, 5, 7]
524 got = gc.get_referents(adict)
525 got.sort()
526 self.assertEqual(got, expected)
527
528 got = gc.get_referents([1, 2], {3: 4}, (0, 0, 0))
529 got.sort()
Guido van Rossum805365e2007-05-07 22:24:25 +0000530 self.assertEqual(got, [0, 0] + list(range(5)))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000531
532 self.assertEqual(gc.get_referents(1, 'a', 4j), [])
533
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000534 def test_is_tracked(self):
535 # Atomic built-in types are not tracked, user-defined objects and
536 # mutable containers are.
537 # NOTE: types with special optimizations (e.g. tuple) have tests
538 # in their own test files instead.
539 self.assertFalse(gc.is_tracked(None))
540 self.assertFalse(gc.is_tracked(1))
541 self.assertFalse(gc.is_tracked(1.0))
542 self.assertFalse(gc.is_tracked(1.0 + 5.0j))
543 self.assertFalse(gc.is_tracked(True))
544 self.assertFalse(gc.is_tracked(False))
545 self.assertFalse(gc.is_tracked(b"a"))
546 self.assertFalse(gc.is_tracked("a"))
547 self.assertFalse(gc.is_tracked(bytearray(b"a")))
548 self.assertFalse(gc.is_tracked(type))
549 self.assertFalse(gc.is_tracked(int))
550 self.assertFalse(gc.is_tracked(object))
551 self.assertFalse(gc.is_tracked(object()))
552
553 class UserClass:
554 pass
555 self.assertTrue(gc.is_tracked(gc))
556 self.assertTrue(gc.is_tracked(UserClass))
557 self.assertTrue(gc.is_tracked(UserClass()))
558 self.assertTrue(gc.is_tracked([]))
559 self.assertTrue(gc.is_tracked(set()))
560
Guido van Rossumd8faa362007-04-27 19:54:29 +0000561 def test_bug1055820b(self):
562 # Corresponds to temp2b.py in the bug report.
563
564 ouch = []
565 def callback(ignored):
566 ouch[:] = [wr() for wr in WRs]
567
568 Cs = [C1055820(i) for i in range(2)]
569 WRs = [weakref.ref(c, callback) for c in Cs]
570 c = None
571
572 gc.collect()
573 self.assertEqual(len(ouch), 0)
574 # Make the two instances trash, and collect again. The bug was that
575 # the callback materialized a strong reference to an instance, but gc
576 # cleared the instance's dict anyway.
577 Cs = None
578 gc.collect()
579 self.assertEqual(len(ouch), 2) # else the callbacks didn't run
580 for x in ouch:
581 # If the callback resurrected one of these guys, the instance
582 # would be damaged, with an empty __dict__.
583 self.assertEqual(x, None)
584
Tim Peters5fbc7b12014-05-08 17:42:19 -0500585 def test_bug21435(self):
586 # This is a poor test - its only virtue is that it happened to
587 # segfault on Tim's Windows box before the patch for 21435 was
588 # applied. That's a nasty bug relying on specific pieces of cyclic
589 # trash appearing in exactly the right order in finalize_garbage()'s
590 # input list.
591 # But there's no reliable way to force that order from Python code,
592 # so over time chances are good this test won't really be testing much
593 # of anything anymore. Still, if it blows up, there's _some_
594 # problem ;-)
595 gc.collect()
596
597 class A:
598 pass
599
600 class B:
601 def __init__(self, x):
602 self.x = x
603
604 def __del__(self):
605 self.attr = None
606
607 def do_work():
608 a = A()
609 b = B(A())
610
611 a.attr = b
612 b.attr = a
613
614 do_work()
615 gc.collect() # this blows up (bad C pointer) when it fails
616
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200617 @cpython_only
Antoine Pitrou696e0352010-08-08 22:18:46 +0000618 def test_garbage_at_shutdown(self):
619 import subprocess
620 code = """if 1:
621 import gc
Antoine Pitrou796564c2013-07-30 19:59:21 +0200622 import _testcapi
623 @_testcapi.with_tp_del
Antoine Pitrou696e0352010-08-08 22:18:46 +0000624 class X:
625 def __init__(self, name):
626 self.name = name
627 def __repr__(self):
628 return "<X %%r>" %% self.name
Antoine Pitrou796564c2013-07-30 19:59:21 +0200629 def __tp_del__(self):
Antoine Pitrou696e0352010-08-08 22:18:46 +0000630 pass
631
632 x = X('first')
633 x.x = x
634 x.y = X('second')
635 del x
Antoine Pitrou2ed94eb2010-09-14 09:48:39 +0000636 gc.set_debug(%s)
Antoine Pitrou696e0352010-08-08 22:18:46 +0000637 """
638 def run_command(code):
Georg Brandl08be72d2010-10-24 15:11:22 +0000639 p = subprocess.Popen([sys.executable, "-Wd", "-c", code],
Antoine Pitrou696e0352010-08-08 22:18:46 +0000640 stdout=subprocess.PIPE,
641 stderr=subprocess.PIPE)
642 stdout, stderr = p.communicate()
Brian Curtin8291af22010-11-01 16:40:17 +0000643 p.stdout.close()
644 p.stderr.close()
Antoine Pitrou696e0352010-08-08 22:18:46 +0000645 self.assertEqual(p.returncode, 0)
646 self.assertEqual(stdout.strip(), b"")
647 return strip_python_stderr(stderr)
648
Antoine Pitrou2ed94eb2010-09-14 09:48:39 +0000649 stderr = run_command(code % "0")
Georg Brandl08be72d2010-10-24 15:11:22 +0000650 self.assertIn(b"ResourceWarning: gc: 2 uncollectable objects at "
651 b"shutdown; use", stderr)
Antoine Pitrouaee47562010-09-16 15:04:49 +0000652 self.assertNotIn(b"<X 'first'>", stderr)
Antoine Pitrou696e0352010-08-08 22:18:46 +0000653 # With DEBUG_UNCOLLECTABLE, the garbage list gets printed
Antoine Pitrou2ed94eb2010-09-14 09:48:39 +0000654 stderr = run_command(code % "gc.DEBUG_UNCOLLECTABLE")
Georg Brandl08be72d2010-10-24 15:11:22 +0000655 self.assertIn(b"ResourceWarning: gc: 2 uncollectable objects at "
656 b"shutdown", stderr)
Antoine Pitrouaee47562010-09-16 15:04:49 +0000657 self.assertTrue(
658 (b"[<X 'first'>, <X 'second'>]" in stderr) or
659 (b"[<X 'second'>, <X 'first'>]" in stderr), stderr)
Antoine Pitrou2ed94eb2010-09-14 09:48:39 +0000660 # With DEBUG_SAVEALL, no additional message should get printed
661 # (because gc.garbage also contains normally reclaimable cyclic
662 # references, and its elements get printed at runtime anyway).
663 stderr = run_command(code % "gc.DEBUG_SAVEALL")
664 self.assertNotIn(b"uncollectable objects at shutdown", stderr)
665
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200666 def test_gc_main_module_at_shutdown(self):
667 # Create a reference cycle through the __main__ module and check
668 # it gets collected at interpreter shutdown.
669 code = """if 1:
670 import weakref
671 class C:
672 def __del__(self):
673 print('__del__ called')
674 l = [C()]
675 l.append(l)
676 """
677 rc, out, err = assert_python_ok('-c', code)
678 self.assertEqual(out.strip(), b'__del__ called')
679
680 def test_gc_ordinary_module_at_shutdown(self):
681 # Same as above, but with a non-__main__ module.
682 with temp_dir() as script_dir:
683 module = """if 1:
684 import weakref
685 class C:
686 def __del__(self):
687 print('__del__ called')
688 l = [C()]
689 l.append(l)
690 """
691 code = """if 1:
692 import sys
693 sys.path.insert(0, %r)
694 import gctest
695 """ % (script_dir,)
696 make_script(script_dir, 'gctest', module)
697 rc, out, err = assert_python_ok('-c', code)
698 self.assertEqual(out.strip(), b'__del__ called')
699
Antoine Pitroud4156c12012-10-30 22:43:19 +0100700 def test_get_stats(self):
701 stats = gc.get_stats()
702 self.assertEqual(len(stats), 3)
703 for st in stats:
704 self.assertIsInstance(st, dict)
705 self.assertEqual(set(st),
706 {"collected", "collections", "uncollectable"})
707 self.assertGreaterEqual(st["collected"], 0)
708 self.assertGreaterEqual(st["collections"], 0)
709 self.assertGreaterEqual(st["uncollectable"], 0)
710 # Check that collection counts are incremented correctly
711 if gc.isenabled():
712 self.addCleanup(gc.enable)
713 gc.disable()
714 old = gc.get_stats()
715 gc.collect(0)
716 new = gc.get_stats()
717 self.assertEqual(new[0]["collections"], old[0]["collections"] + 1)
718 self.assertEqual(new[1]["collections"], old[1]["collections"])
719 self.assertEqual(new[2]["collections"], old[2]["collections"])
720 gc.collect(2)
721 new = gc.get_stats()
722 self.assertEqual(new[0]["collections"], old[0]["collections"] + 1)
723 self.assertEqual(new[1]["collections"], old[1]["collections"])
724 self.assertEqual(new[2]["collections"], old[2]["collections"] + 1)
725
Antoine Pitrou696e0352010-08-08 22:18:46 +0000726
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +0000727class GCCallbackTests(unittest.TestCase):
728 def setUp(self):
729 # Save gc state and disable it.
730 self.enabled = gc.isenabled()
731 gc.disable()
732 self.debug = gc.get_debug()
733 gc.set_debug(0)
734 gc.callbacks.append(self.cb1)
735 gc.callbacks.append(self.cb2)
Antoine Pitrou6b64fc62012-04-16 21:29:02 +0200736 self.othergarbage = []
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +0000737
738 def tearDown(self):
739 # Restore gc state
740 del self.visit
741 gc.callbacks.remove(self.cb1)
742 gc.callbacks.remove(self.cb2)
743 gc.set_debug(self.debug)
744 if self.enabled:
745 gc.enable()
746 # destroy any uncollectables
747 gc.collect()
748 for obj in gc.garbage:
749 if isinstance(obj, Uncollectable):
750 obj.partner = None
751 del gc.garbage[:]
Antoine Pitrou6b64fc62012-04-16 21:29:02 +0200752 del self.othergarbage
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +0000753 gc.collect()
754
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +0000755 def preclean(self):
756 # Remove all fluff from the system. Invoke this function
757 # manually rather than through self.setUp() for maximum
758 # safety.
759 self.visit = []
760 gc.collect()
761 garbage, gc.garbage[:] = gc.garbage[:], []
762 self.othergarbage.append(garbage)
763 self.visit = []
764
765 def cb1(self, phase, info):
766 self.visit.append((1, phase, dict(info)))
767
768 def cb2(self, phase, info):
769 self.visit.append((2, phase, dict(info)))
770 if phase == "stop" and hasattr(self, "cleanup"):
771 # Clean Uncollectable from garbage
772 uc = [e for e in gc.garbage if isinstance(e, Uncollectable)]
773 gc.garbage[:] = [e for e in gc.garbage
774 if not isinstance(e, Uncollectable)]
775 for e in uc:
776 e.partner = None
777
Antoine Pitroude3c73b2012-04-16 21:29:58 +0200778 def test_collect(self):
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +0000779 self.preclean()
780 gc.collect()
781 # Algorithmically verify the contents of self.visit
782 # because it is long and tortuous.
783
784 # Count the number of visits to each callback
785 n = [v[0] for v in self.visit]
786 n1 = [i for i in n if i == 1]
787 n2 = [i for i in n if i == 2]
788 self.assertEqual(n1, [1]*2)
789 self.assertEqual(n2, [2]*2)
790
791 # Count that we got the right number of start and stop callbacks.
792 n = [v[1] for v in self.visit]
793 n1 = [i for i in n if i == "start"]
794 n2 = [i for i in n if i == "stop"]
795 self.assertEqual(n1, ["start"]*2)
796 self.assertEqual(n2, ["stop"]*2)
797
798 # Check that we got the right info dict for all callbacks
799 for v in self.visit:
800 info = v[2]
801 self.assertTrue("generation" in info)
802 self.assertTrue("collected" in info)
803 self.assertTrue("uncollectable" in info)
804
Antoine Pitroude3c73b2012-04-16 21:29:58 +0200805 def test_collect_generation(self):
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +0000806 self.preclean()
807 gc.collect(2)
808 for v in self.visit:
809 info = v[2]
810 self.assertEqual(info["generation"], 2)
811
Serhiy Storchakaf28ba362014-02-07 10:10:55 +0200812 @cpython_only
Antoine Pitroude3c73b2012-04-16 21:29:58 +0200813 def test_collect_garbage(self):
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +0000814 self.preclean()
815 # Each of these cause four objects to be garbage: Two
816 # Uncolectables and their instance dicts.
817 Uncollectable()
818 Uncollectable()
819 C1055820(666)
820 gc.collect()
821 for v in self.visit:
822 if v[1] != "stop":
823 continue
824 info = v[2]
825 self.assertEqual(info["collected"], 2)
826 self.assertEqual(info["uncollectable"], 8)
827
828 # We should now have the Uncollectables in gc.garbage
829 self.assertEqual(len(gc.garbage), 4)
830 for e in gc.garbage:
831 self.assertIsInstance(e, Uncollectable)
832
833 # Now, let our callback handle the Uncollectable instances
834 self.cleanup=True
835 self.visit = []
836 gc.garbage[:] = []
837 gc.collect()
838 for v in self.visit:
839 if v[1] != "stop":
840 continue
841 info = v[2]
842 self.assertEqual(info["collected"], 0)
843 self.assertEqual(info["uncollectable"], 4)
844
845 # Uncollectables should be gone
846 self.assertEqual(len(gc.garbage), 0)
847
848
Guido van Rossumd8faa362007-04-27 19:54:29 +0000849class GCTogglingTests(unittest.TestCase):
850 def setUp(self):
851 gc.enable()
852
853 def tearDown(self):
854 gc.disable()
855
856 def test_bug1055820c(self):
857 # Corresponds to temp2c.py in the bug report. This is pretty
858 # elaborate.
859
860 c0 = C1055820(0)
861 # Move c0 into generation 2.
862 gc.collect()
863
864 c1 = C1055820(1)
865 c1.keep_c0_alive = c0
866 del c0.loop # now only c1 keeps c0 alive
867
868 c2 = C1055820(2)
869 c2wr = weakref.ref(c2) # no callback!
870
871 ouch = []
872 def callback(ignored):
Tim Petersead8b7a2004-10-30 23:09:22 +0000873 ouch[:] = [c2wr()]
874
Guido van Rossumd8faa362007-04-27 19:54:29 +0000875 # The callback gets associated with a wr on an object in generation 2.
876 c0wr = weakref.ref(c0, callback)
Tim Petersead8b7a2004-10-30 23:09:22 +0000877
Guido van Rossumd8faa362007-04-27 19:54:29 +0000878 c0 = c1 = c2 = None
Tim Petersead8b7a2004-10-30 23:09:22 +0000879
Guido van Rossumd8faa362007-04-27 19:54:29 +0000880 # What we've set up: c0, c1, and c2 are all trash now. c0 is in
881 # generation 2. The only thing keeping it alive is that c1 points to
882 # it. c1 and c2 are in generation 0, and are in self-loops. There's a
883 # global weakref to c2 (c2wr), but that weakref has no callback.
884 # There's also a global weakref to c0 (c0wr), and that does have a
885 # callback, and that callback references c2 via c2wr().
886 #
887 # c0 has a wr with callback, which references c2wr
888 # ^
889 # |
890 # | Generation 2 above dots
891 #. . . . . . . .|. . . . . . . . . . . . . . . . . . . . . . . .
892 # | Generation 0 below dots
893 # |
894 # |
895 # ^->c1 ^->c2 has a wr but no callback
896 # | | | |
897 # <--v <--v
898 #
899 # So this is the nightmare: when generation 0 gets collected, we see
900 # that c2 has a callback-free weakref, and c1 doesn't even have a
901 # weakref. Collecting generation 0 doesn't see c0 at all, and c0 is
902 # the only object that has a weakref with a callback. gc clears c1
903 # and c2. Clearing c1 has the side effect of dropping the refcount on
904 # c0 to 0, so c0 goes away (despite that it's in an older generation)
905 # and c0's wr callback triggers. That in turn materializes a reference
906 # to c2 via c2wr(), but c2 gets cleared anyway by gc.
Tim Petersead8b7a2004-10-30 23:09:22 +0000907
Guido van Rossumd8faa362007-04-27 19:54:29 +0000908 # We want to let gc happen "naturally", to preserve the distinction
909 # between generations.
910 junk = []
911 i = 0
912 detector = GC_Detector()
913 while not detector.gc_happened:
914 i += 1
915 if i > 10000:
916 self.fail("gc didn't happen after 10000 iterations")
917 self.assertEqual(len(ouch), 0)
918 junk.append([]) # this will eventually trigger gc
Tim Petersead8b7a2004-10-30 23:09:22 +0000919
Guido van Rossumd8faa362007-04-27 19:54:29 +0000920 self.assertEqual(len(ouch), 1) # else the callback wasn't invoked
921 for x in ouch:
922 # If the callback resurrected c2, the instance would be damaged,
923 # with an empty __dict__.
924 self.assertEqual(x, None)
Tim Petersead8b7a2004-10-30 23:09:22 +0000925
Guido van Rossumd8faa362007-04-27 19:54:29 +0000926 def test_bug1055820d(self):
927 # Corresponds to temp2d.py in the bug report. This is very much like
928 # test_bug1055820c, but uses a __del__ method instead of a weakref
929 # callback to sneak in a resurrection of cyclic trash.
Tim Petersead8b7a2004-10-30 23:09:22 +0000930
Guido van Rossumd8faa362007-04-27 19:54:29 +0000931 ouch = []
932 class D(C1055820):
933 def __del__(self):
934 ouch[:] = [c2wr()]
Tim Petersead8b7a2004-10-30 23:09:22 +0000935
Guido van Rossumd8faa362007-04-27 19:54:29 +0000936 d0 = D(0)
937 # Move all the above into generation 2.
938 gc.collect()
Tim Petersead8b7a2004-10-30 23:09:22 +0000939
Guido van Rossumd8faa362007-04-27 19:54:29 +0000940 c1 = C1055820(1)
941 c1.keep_d0_alive = d0
942 del d0.loop # now only c1 keeps d0 alive
Tim Petersead8b7a2004-10-30 23:09:22 +0000943
Guido van Rossumd8faa362007-04-27 19:54:29 +0000944 c2 = C1055820(2)
945 c2wr = weakref.ref(c2) # no callback!
Tim Petersead8b7a2004-10-30 23:09:22 +0000946
Guido van Rossumd8faa362007-04-27 19:54:29 +0000947 d0 = c1 = c2 = None
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000948
Guido van Rossumd8faa362007-04-27 19:54:29 +0000949 # What we've set up: d0, c1, and c2 are all trash now. d0 is in
950 # generation 2. The only thing keeping it alive is that c1 points to
951 # it. c1 and c2 are in generation 0, and are in self-loops. There's
952 # a global weakref to c2 (c2wr), but that weakref has no callback.
953 # There are no other weakrefs.
954 #
955 # d0 has a __del__ method that references c2wr
956 # ^
957 # |
958 # | Generation 2 above dots
959 #. . . . . . . .|. . . . . . . . . . . . . . . . . . . . . . . .
960 # | Generation 0 below dots
961 # |
962 # |
963 # ^->c1 ^->c2 has a wr but no callback
964 # | | | |
965 # <--v <--v
966 #
967 # So this is the nightmare: when generation 0 gets collected, we see
968 # that c2 has a callback-free weakref, and c1 doesn't even have a
969 # weakref. Collecting generation 0 doesn't see d0 at all. gc clears
970 # c1 and c2. Clearing c1 has the side effect of dropping the refcount
971 # on d0 to 0, so d0 goes away (despite that it's in an older
972 # generation) and d0's __del__ triggers. That in turn materializes
973 # a reference to c2 via c2wr(), but c2 gets cleared anyway by gc.
974
975 # We want to let gc happen "naturally", to preserve the distinction
976 # between generations.
977 detector = GC_Detector()
978 junk = []
979 i = 0
980 while not detector.gc_happened:
981 i += 1
982 if i > 10000:
983 self.fail("gc didn't happen after 10000 iterations")
984 self.assertEqual(len(ouch), 0)
985 junk.append([]) # this will eventually trigger gc
986
987 self.assertEqual(len(ouch), 1) # else __del__ wasn't invoked
988 for x in ouch:
989 # If __del__ resurrected c2, the instance would be damaged, with an
990 # empty __dict__.
991 self.assertEqual(x, None)
992
993def test_main():
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000994 enabled = gc.isenabled()
995 gc.disable()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000996 assert not gc.isenabled()
Neil Schemenauerfaae2662000-09-22 15:26:20 +0000997 debug = gc.get_debug()
998 gc.set_debug(debug & ~gc.DEBUG_LEAK) # this test is supposed to leak
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000999
Neil Schemenauerfaae2662000-09-22 15:26:20 +00001000 try:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001001 gc.collect() # Delete 2nd generation garbage
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +00001002 run_unittest(GCTests, GCTogglingTests, GCCallbackTests)
Neil Schemenauerfaae2662000-09-22 15:26:20 +00001003 finally:
1004 gc.set_debug(debug)
1005 # test gc.enable() even if GC is disabled by default
1006 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001007 print("restoring automatic collection")
Neil Schemenauerfaae2662000-09-22 15:26:20 +00001008 # make sure to always test gc.enable()
1009 gc.enable()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001010 assert gc.isenabled()
Neil Schemenauerfaae2662000-09-22 15:26:20 +00001011 if not enabled:
1012 gc.disable()
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001013
Guido van Rossumd8faa362007-04-27 19:54:29 +00001014if __name__ == "__main__":
1015 test_main()