Debian Codegraph @

lib-python/3/test/test_gc.py

raw symbols SCIP
1 import unittest
2 import unittest.mock
3 from test.support import (verbose, refcount_test,
4 cpython_only, requires_subprocess)
5 from test.support.import_helper import import_module
6 from test.support.os_helper import temp_dir, TESTFN, unlink
7 from test.support.script_helper import assert_python_ok, make_script
8 from test.support import threading_helper
9
10 import gc
11 import sys
12 import sysconfig
13 import textwrap
14 import threading
15 import time
16 import weakref
17
18 try:
19 from _testcapi import with_tp_del
20 except ImportError:
21 def with_tp_del(cls):
22 class C(object):
23 def __new__(cls, *args, **kwargs):
24 raise TypeError('requires _testcapi.with_tp_del')
25 return C
26
27 try:
28 from _testcapi import ContainerNoGC
29 except ImportError:
30 ContainerNoGC = None
31
32 ### Support code
33 ###############################################################################
34
35 # Bug 1055820 has several tests of longstanding bugs involving weakrefs and
36 # cyclic gc.
37
38 # An instance of C1055820 has a self-loop, so becomes cyclic trash when
39 # unreachable.
40 class C1055820(object):
41 def __init__(self, i):
42 self.i = i
43 self.loop = self
44
45 class GC_Detector(object):
46 # Create an instance I. Then gc hasn't happened again so long as
47 # I.gc_happened is false.
48
49 def __init__(self):
50 self.gc_happened = False
51
52 def it_happened(ignored):
53 self.gc_happened = True
54
55 # Create a piece of cyclic trash that triggers it_happened when
56 # gc collects it.
57 self.wr = weakref.ref(C1055820(666), it_happened)
58
59 @with_tp_del
60 class Uncollectable(object):
61 """Create a reference cycle with multiple __del__ methods.
62
63 An object in a reference cycle will never have zero references,
64 and so must be garbage collected. If one or more objects in the
65 cycle have __del__ methods, the gc refuses to guess an order,
66 and leaves the cycle uncollected."""
67 def __init__(self, partner=None):
68 if partner is None:
69 self.partner = Uncollectable(partner=self)
70 else:
71 self.partner = partner
72 def __tp_del__(self):
73 pass
74
75 if sysconfig.get_config_vars().get('PY_CFLAGS', ''):
76 BUILD_WITH_NDEBUG = ('-DNDEBUG' in sysconfig.get_config_vars()['PY_CFLAGS'])
77 else:
78 # Usually, sys.gettotalrefcount() is only present if Python has been
79 # compiled in debug mode. If it's missing, expect that Python has
80 # been released in release mode: with NDEBUG defined.
81 BUILD_WITH_NDEBUG = (not hasattr(sys, 'gettotalrefcount'))
82
83 ### Tests
84 ###############################################################################
85
86 @cpython_only
87 class GCTests(unittest.TestCase):
88 def test_list(self):
89 l = []
90 l.append(l)
91 gc.collect()
92 del l
93 self.assertEqual(gc.collect(), 1)
94
95 def test_dict(self):
96 d = {}
97 d[1] = d
98 gc.collect()
99 del d
100 self.assertEqual(gc.collect(), 1)
101
102 def test_tuple(self):
103 # since tuples are immutable we close the loop with a list
104 l = []
105 t = (l,)
106 l.append(t)
107 gc.collect()
108 del t
109 del l
110 self.assertEqual(gc.collect(), 2)
111
112 def test_class(self):
113 class A:
114 pass
115 A.a = A
116 gc.collect()
117 del A
118 self.assertNotEqual(gc.collect(), 0)
119
120 def test_newstyleclass(self):
121 class A(object):
122 pass
123 gc.collect()
124 del A
125 self.assertNotEqual(gc.collect(), 0)
126
127 def test_instance(self):
128 class A:
129 pass
130 a = A()
131 a.a = a
132 gc.collect()
133 del a
134 self.assertNotEqual(gc.collect(), 0)
135
136 def test_newinstance(self):
137 class A(object):
138 pass
139 a = A()
140 a.a = a
141 gc.collect()
142 del a
143 self.assertNotEqual(gc.collect(), 0)
144 class B(list):
145 pass
146 class C(B, A):
147 pass
148 a = C()
149 a.a = a
150 gc.collect()
151 del a
152 self.assertNotEqual(gc.collect(), 0)
153 del B, C
154 self.assertNotEqual(gc.collect(), 0)
155 A.a = A()
156 del A
157 self.assertNotEqual(gc.collect(), 0)
158 self.assertEqual(gc.collect(), 0)
159
160 def test_method(self):
161 # Tricky: self.__init__ is a bound method, it references the instance.
162 class A:
163 def __init__(self):
164 self.init = self.__init__
165 a = A()
166 gc.collect()
167 del a
168 self.assertNotEqual(gc.collect(), 0)
169
170 @cpython_only
171 def test_legacy_finalizer(self):
172 # A() is uncollectable if it is part of a cycle, make sure it shows up
173 # in gc.garbage.
174 @with_tp_del
175 class A:
176 def __tp_del__(self): pass
177 class B:
178 pass
179 a = A()
180 a.a = a
181 id_a = id(a)
182 b = B()
183 b.b = b
184 gc.collect()
185 del a
186 del b
187 self.assertNotEqual(gc.collect(), 0)
188 for obj in gc.garbage:
189 if id(obj) == id_a:
190 del obj.a
191 break
192 else:
193 self.fail("didn't find obj in garbage (finalizer)")
194 gc.garbage.remove(obj)
195
196 @cpython_only
197 def test_legacy_finalizer_newclass(self):
198 # A() is uncollectable if it is part of a cycle, make sure it shows up
199 # in gc.garbage.
200 @with_tp_del
201 class A(object):
202 def __tp_del__(self): pass
203 class B(object):
204 pass
205 a = A()
206 a.a = a
207 id_a = id(a)
208 b = B()
209 b.b = b
210 gc.collect()
211 del a
212 del b
213 self.assertNotEqual(gc.collect(), 0)
214 for obj in gc.garbage:
215 if id(obj) == id_a:
216 del obj.a
217 break
218 else:
219 self.fail("didn't find obj in garbage (finalizer)")
220 gc.garbage.remove(obj)
221
222 def test_function(self):
223 # Tricky: f -> d -> f, code should call d.clear() after the exec to
224 # break the cycle.
225 d = {}
226 exec("def f(): pass\n", d)
227 gc.collect()
228 del d
229 self.assertEqual(gc.collect(), 2)
230
231 def test_function_tp_clear_leaves_consistent_state(self):
232 # https://github.com/python/cpython/issues/91636
233 code = """if 1:
234
235 import gc
236 import weakref
237
238 class LateFin:
239 __slots__ = ('ref',)
240
241 def __del__(self):
242
243 # 8. Now `latefin`'s finalizer is called. Here we
244 # obtain a reference to `func`, which is currently
245 # undergoing `tp_clear`.
246 global func
247 func = self.ref()
248
249 class Cyclic(tuple):
250 __slots__ = ()
251
252 # 4. The finalizers of all garbage objects are called. In
253 # this case this is only us as `func` doesn't have a
254 # finalizer.
255 def __del__(self):
256
257 # 5. Create a weakref to `func` now. If we had created
258 # it earlier, it would have been cleared by the
259 # garbage collector before calling the finalizers.
260 self[1].ref = weakref.ref(self[0])
261
262 # 6. Drop the global reference to `latefin`. The only
263 # remaining reference is the one we have.
264 global latefin
265 del latefin
266
267 # 7. Now `func` is `tp_clear`-ed. This drops the last
268 # reference to `Cyclic`, which gets `tp_dealloc`-ed.
269 # This drops the last reference to `latefin`.
270
271 latefin = LateFin()
272 def func():
273 pass
274 cyc = tuple.__new__(Cyclic, (func, latefin))
275
276 # 1. Create a reference cycle of `cyc` and `func`.
277 func.__module__ = cyc
278
279 # 2. Make the cycle unreachable, but keep the global reference
280 # to `latefin` so that it isn't detected as garbage. This
281 # way its finalizer will not be called immediately.
282 del func, cyc
283
284 # 3. Invoke garbage collection,
285 # which will find `cyc` and `func` as garbage.
286 gc.collect()
287
288 # 9. Previously, this would crash because `func_qualname`
289 # had been NULL-ed out by func_clear().
290 print(f"{func=}")
291 """
292 # We're mostly just checking that this doesn't crash.
293 rc, stdout, stderr = assert_python_ok("-c", code)
294 self.assertEqual(rc, 0)
295 self.assertRegex(stdout, rb"""\A\s*func=<function at \S+>\s*\Z""")
296 self.assertFalse(stderr)
297
298 @refcount_test
299 def test_frame(self):
300 def f():
301 frame = sys._getframe()
302 gc.collect()
303 f()
304 self.assertEqual(gc.collect(), 1)
305
306 def test_saveall(self):
307 # Verify that cyclic garbage like lists show up in gc.garbage if the
308 # SAVEALL option is enabled.
309
310 # First make sure we don't save away other stuff that just happens to
311 # be waiting for collection.
312 gc.collect()
313 # if this fails, someone else created immortal trash
314 self.assertEqual(gc.garbage, [])
315
316 L = []
317 L.append(L)
318 id_L = id(L)
319
320 debug = gc.get_debug()
321 gc.set_debug(debug | gc.DEBUG_SAVEALL)
322 del L
323 gc.collect()
324 gc.set_debug(debug)
325
326 self.assertEqual(len(gc.garbage), 1)
327 obj = gc.garbage.pop()
328 self.assertEqual(id(obj), id_L)
329
330 def test_del(self):
331 # __del__ methods can trigger collection, make this to happen
332 thresholds = gc.get_threshold()
333 gc.enable()
334 gc.set_threshold(1)
335
336 class A:
337 def __del__(self):
338 dir(self)
339 a = A()
340 del a
341
342 gc.disable()
343 gc.set_threshold(*thresholds)
344
345 def test_del_newclass(self):
346 # __del__ methods can trigger collection, make this to happen
347 thresholds = gc.get_threshold()
348 gc.enable()
349 gc.set_threshold(1)
350
351 class A(object):
352 def __del__(self):
353 dir(self)
354 a = A()
355 del a
356
357 gc.disable()
358 gc.set_threshold(*thresholds)
359
360 # The following two tests are fragile:
361 # They precisely count the number of allocations,
362 # which is highly implementation-dependent.
363 # For example, disposed tuples are not freed, but reused.
364 # To minimize variations, though, we first store the get_count() results
365 # and check them at the end.
366 @refcount_test
367 def test_get_count(self):
368 gc.collect()
369 a, b, c = gc.get_count()
370 x = []
371 d, e, f = gc.get_count()
372 self.assertEqual((b, c), (0, 0))
373 self.assertEqual((e, f), (0, 0))
374 # This is less fragile than asserting that a equals 0.
375 self.assertLess(a, 5)
376 # Between the two calls to get_count(), at least one object was
377 # created (the list).
378 self.assertGreater(d, a)
379
380 @refcount_test
381 def test_collect_generations(self):
382 gc.collect()
383 # This object will "trickle" into generation N + 1 after
384 # each call to collect(N)
385 x = []
386 gc.collect(0)
387 # x is now in gen 1
388 a, b, c = gc.get_count()
389 gc.collect(1)
390 # x is now in gen 2
391 d, e, f = gc.get_count()
392 gc.collect(2)
393 # x is now in gen 3
394 g, h, i = gc.get_count()
395 # We don't check a, d, g since their exact values depends on
396 # internal implementation details of the interpreter.
397 self.assertEqual((b, c), (1, 0))
398 self.assertEqual((e, f), (0, 1))
399 self.assertEqual((h, i), (0, 0))
400
401 def test_trashcan(self):
402 class Ouch:
403 n = 0
404 def __del__(self):
405 Ouch.n = Ouch.n + 1
406 if Ouch.n % 17 == 0:
407 gc.collect()
408
409 # "trashcan" is a hack to prevent stack overflow when deallocating
410 # very deeply nested tuples etc. It works in part by abusing the
411 # type pointer and refcount fields, and that can yield horrible
412 # problems when gc tries to traverse the structures.
413 # If this test fails (as it does in 2.0, 2.1 and 2.2), it will
414 # most likely die via segfault.
415
416 # Note: In 2.3 the possibility for compiling without cyclic gc was
417 # removed, and that in turn allows the trashcan mechanism to work
418 # via much simpler means (e.g., it never abuses the type pointer or
419 # refcount fields anymore). Since it's much less likely to cause a
420 # problem now, the various constants in this expensive (we force a lot
421 # of full collections) test are cut back from the 2.2 version.
422 gc.enable()
423 N = 150
424 for count in range(2):
425 t = []
426 for i in range(N):
427 t = [t, Ouch()]
428 u = []
429 for i in range(N):
430 u = [u, Ouch()]
431 v = {}
432 for i in range(N):
433 v = {1: v, 2: Ouch()}
434 gc.disable()
435
436 @threading_helper.requires_working_threading()
437 def test_trashcan_threads(self):
438 # Issue #13992: trashcan mechanism should be thread-safe
439 NESTING = 60
440 N_THREADS = 2
441
442 def sleeper_gen():
443 """A generator that releases the GIL when closed or dealloc'ed."""
444 try:
445 yield
446 finally:
447 time.sleep(0.000001)
448
449 class C(list):
450 # Appending to a list is atomic, which avoids the use of a lock.
451 inits = []
452 dels = []
453 def __init__(self, alist):
454 self[:] = alist
455 C.inits.append(None)
456 def __del__(self):
457 # This __del__ is called by subtype_dealloc().
458 C.dels.append(None)
459 # `g` will release the GIL when garbage-collected. This
460 # helps assert subtype_dealloc's behaviour when threads
461 # switch in the middle of it.
462 g = sleeper_gen()
463 next(g)
464 # Now that __del__ is finished, subtype_dealloc will proceed
465 # to call list_dealloc, which also uses the trashcan mechanism.
466
467 def make_nested():
468 """Create a sufficiently nested container object so that the
469 trashcan mechanism is invoked when deallocating it."""
470 x = C([])
471 for i in range(NESTING):
472 x = [C([x])]
473 del x
474
475 def run_thread():
476 """Exercise make_nested() in a loop."""
477 while not exit:
478 make_nested()
479
480 old_switchinterval = sys.getswitchinterval()
481 sys.setswitchinterval(1e-5)
482 try:
483 exit = []
484 threads = []
485 for i in range(N_THREADS):
486 t = threading.Thread(target=run_thread)
487 threads.append(t)
488 with threading_helper.start_threads(threads, lambda: exit.append(1)):
489 time.sleep(1.0)
490 finally:
491 sys.setswitchinterval(old_switchinterval)
492 gc.collect()
493 self.assertEqual(len(C.inits), len(C.dels))
494
495 def test_boom(self):
496 class Boom:
497 def __getattr__(self, someattribute):
498 del self.attr
499 raise AttributeError
500
501 a = Boom()
502 b = Boom()
503 a.attr = b
504 b.attr = a
505
506 gc.collect()
507 garbagelen = len(gc.garbage)
508 del a, b
509 # a<->b are in a trash cycle now. Collection will invoke
510 # Boom.__getattr__ (to see whether a and b have __del__ methods), and
511 # __getattr__ deletes the internal "attr" attributes as a side effect.
512 # That causes the trash cycle to get reclaimed via refcounts falling to
513 # 0, thus mutating the trash graph as a side effect of merely asking
514 # whether __del__ exists. This used to (before 2.3b1) crash Python.
515 # Now __getattr__ isn't called.
516 self.assertEqual(gc.collect(), 2)
517 self.assertEqual(len(gc.garbage), garbagelen)
518
519 def test_boom2(self):
520 class Boom2:
521 def __init__(self):
522 self.x = 0
523
524 def __getattr__(self, someattribute):
525 self.x += 1
526 if self.x > 1:
527 del self.attr
528 raise AttributeError
529
530 a = Boom2()
531 b = Boom2()
532 a.attr = b
533 b.attr = a
534
535 gc.collect()
536 garbagelen = len(gc.garbage)
537 del a, b
538 # Much like test_boom(), except that __getattr__ doesn't break the
539 # cycle until the second time gc checks for __del__. As of 2.3b1,
540 # there isn't a second time, so this simply cleans up the trash cycle.
541 # We expect a, b, a.__dict__ and b.__dict__ (4 objects) to get
542 # reclaimed this way.
543 self.assertEqual(gc.collect(), 2)
544 self.assertEqual(len(gc.garbage), garbagelen)
545
546 def test_get_referents(self):
547 alist = [1, 3, 5]
548 got = gc.get_referents(alist)
549 got.sort()
550 self.assertEqual(got, alist)
551
552 atuple = tuple(alist)
553 got = gc.get_referents(atuple)
554 got.sort()
555 self.assertEqual(got, alist)
556
557 adict = {1: 3, 5: 7}
558 expected = [1, 3, 5, 7]
559 got = gc.get_referents(adict)
560 got.sort()
561 self.assertEqual(got, expected)
562
563 got = gc.get_referents([1, 2], {3: 4}, (0, 0, 0))
564 got.sort()
565 self.assertEqual(got, [0, 0] + list(range(5)))
566
567 self.assertEqual(gc.get_referents(1, 'a', 4j), [])
568
569 def test_is_tracked(self):
570 # Atomic built-in types are not tracked, user-defined objects and
571 # mutable containers are.
572 # NOTE: types with special optimizations (e.g. tuple) have tests
573 # in their own test files instead.
574 self.assertFalse(gc.is_tracked(None))
575 self.assertFalse(gc.is_tracked(1))
576 self.assertFalse(gc.is_tracked(1.0))
577 self.assertFalse(gc.is_tracked(1.0 + 5.0j))
578 self.assertFalse(gc.is_tracked(True))
579 self.assertFalse(gc.is_tracked(False))
580 self.assertFalse(gc.is_tracked(b"a"))
581 self.assertFalse(gc.is_tracked("a"))
582 self.assertFalse(gc.is_tracked(bytearray(b"a")))
583 self.assertFalse(gc.is_tracked(type))
584 self.assertFalse(gc.is_tracked(int))
585 self.assertFalse(gc.is_tracked(object))
586 self.assertFalse(gc.is_tracked(object()))
587
588 class UserClass:
589 pass
590
591 class UserInt(int):
592 pass
593
594 # Base class is object; no extra fields.
595 class UserClassSlots:
596 __slots__ = ()
597
598 # Base class is fixed size larger than object; no extra fields.
599 class UserFloatSlots(float):
600 __slots__ = ()
601
602 # Base class is variable size; no extra fields.
603 class UserIntSlots(int):
604 __slots__ = ()
605
606 self.assertTrue(gc.is_tracked(gc))
607 self.assertTrue(gc.is_tracked(UserClass))
608 self.assertTrue(gc.is_tracked(UserClass()))
609 self.assertTrue(gc.is_tracked(UserInt()))
610 self.assertTrue(gc.is_tracked([]))
611 self.assertTrue(gc.is_tracked(set()))
612 self.assertTrue(gc.is_tracked(UserClassSlots()))
613 self.assertTrue(gc.is_tracked(UserFloatSlots()))
614 self.assertTrue(gc.is_tracked(UserIntSlots()))
615
616 def test_is_finalized(self):
617 # Objects not tracked by the always gc return false
618 self.assertFalse(gc.is_finalized(3))
619
620 storage = []
621 class Lazarus:
622 def __del__(self):
623 storage.append(self)
624
625 lazarus = Lazarus()
626 self.assertFalse(gc.is_finalized(lazarus))
627
628 del lazarus
629 gc.collect()
630
631 lazarus = storage.pop()
632 self.assertTrue(gc.is_finalized(lazarus))
633
634 def test_bug1055820b(self):
635 # Corresponds to temp2b.py in the bug report.
636
637 ouch = []
638 def callback(ignored):
639 ouch[:] = [wr() for wr in WRs]
640
641 Cs = [C1055820(i) for i in range(2)]
642 WRs = [weakref.ref(c, callback) for c in Cs]
643 c = None
644
645 gc.collect()
646 self.assertEqual(len(ouch), 0)
647 # Make the two instances trash, and collect again. The bug was that
648 # the callback materialized a strong reference to an instance, but gc
649 # cleared the instance's dict anyway.
650 Cs = None
651 gc.collect()
652 self.assertEqual(len(ouch), 2) # else the callbacks didn't run
653 for x in ouch:
654 # If the callback resurrected one of these guys, the instance
655 # would be damaged, with an empty __dict__.
656 self.assertEqual(x, None)
657
658 def test_bug21435(self):
659 # This is a poor test - its only virtue is that it happened to
660 # segfault on Tim's Windows box before the patch for 21435 was
661 # applied. That's a nasty bug relying on specific pieces of cyclic
662 # trash appearing in exactly the right order in finalize_garbage()'s
663 # input list.
664 # But there's no reliable way to force that order from Python code,
665 # so over time chances are good this test won't really be testing much
666 # of anything anymore. Still, if it blows up, there's _some_
667 # problem ;-)
668 gc.collect()
669
670 class A:
671 pass
672
673 class B:
674 def __init__(self, x):
675 self.x = x
676
677 def __del__(self):
678 self.attr = None
679
680 def do_work():
681 a = A()
682 b = B(A())
683
684 a.attr = b
685 b.attr = a
686
687 do_work()
688 gc.collect() # this blows up (bad C pointer) when it fails
689
690 @cpython_only
691 @requires_subprocess()
692 def test_garbage_at_shutdown(self):
693 import subprocess
694 code = """if 1:
695 import gc
696 import _testcapi
697 @_testcapi.with_tp_del
698 class X:
699 def __init__(self, name):
700 self.name = name
701 def __repr__(self):
702 return "<X %%r>" %% self.name
703 def __tp_del__(self):
704 pass
705
706 x = X('first')
707 x.x = x
708 x.y = X('second')
709 del x
710 gc.set_debug(%s)
711 """
712 def run_command(code):
713 p = subprocess.Popen([sys.executable, "-Wd", "-c", code],
714 stdout=subprocess.PIPE,
715 stderr=subprocess.PIPE)
716 stdout, stderr = p.communicate()
717 p.stdout.close()
718 p.stderr.close()
719 self.assertEqual(p.returncode, 0)
720 self.assertEqual(stdout, b"")
721 return stderr
722
723 stderr = run_command(code % "0")
724 self.assertIn(b"ResourceWarning: gc: 2 uncollectable objects at "
725 b"shutdown; use", stderr)
726 self.assertNotIn(b"<X 'first'>", stderr)
727 # With DEBUG_UNCOLLECTABLE, the garbage list gets printed
728 stderr = run_command(code % "gc.DEBUG_UNCOLLECTABLE")
729 self.assertIn(b"ResourceWarning: gc: 2 uncollectable objects at "
730 b"shutdown", stderr)
731 self.assertTrue(
732 (b"[<X 'first'>, <X 'second'>]" in stderr) or
733 (b"[<X 'second'>, <X 'first'>]" in stderr), stderr)
734 # With DEBUG_SAVEALL, no additional message should get printed
735 # (because gc.garbage also contains normally reclaimable cyclic
736 # references, and its elements get printed at runtime anyway).
737 stderr = run_command(code % "gc.DEBUG_SAVEALL")
738 self.assertNotIn(b"uncollectable objects at shutdown", stderr)
739
740 def test_gc_main_module_at_shutdown(self):
741 # Create a reference cycle through the __main__ module and check
742 # it gets collected at interpreter shutdown.
743 code = """if 1:
744 class C:
745 def __del__(self):
746 print('__del__ called')
747 l = [C()]
748 l.append(l)
749 """
750 rc, out, err = assert_python_ok('-c', code)
751 self.assertEqual(out.strip(), b'__del__ called')
752
753 def test_gc_ordinary_module_at_shutdown(self):
754 # Same as above, but with a non-__main__ module.
755 with temp_dir() as script_dir:
756 module = """if 1:
757 class C:
758 def __del__(self):
759 print('__del__ called')
760 l = [C()]
761 l.append(l)
762 """
763 code = """if 1:
764 import sys
765 sys.path.insert(0, %r)
766 import gctest
767 """ % (script_dir,)
768 make_script(script_dir, 'gctest', module)
769 rc, out, err = assert_python_ok('-c', code)
770 self.assertEqual(out.strip(), b'__del__ called')
771
772 def test_global_del_SystemExit(self):
773 code = """if 1:
774 class ClassWithDel:
775 def __del__(self):
776 print('__del__ called')
777 a = ClassWithDel()
778 a.link = a
779 raise SystemExit(0)"""
780 self.addCleanup(unlink, TESTFN)
781 with open(TESTFN, 'w', encoding="utf-8") as script:
782 script.write(code)
783 rc, out, err = assert_python_ok(TESTFN)
784 self.assertEqual(out.strip(), b'__del__ called')
785
786 def test_get_stats(self):
787 stats = gc.get_stats()
788 self.assertEqual(len(stats), 3)
789 for st in stats:
790 self.assertIsInstance(st, dict)
791 self.assertEqual(set(st),
792 {"collected", "collections", "uncollectable"})
793 self.assertGreaterEqual(st["collected"], 0)
794 self.assertGreaterEqual(st["collections"], 0)
795 self.assertGreaterEqual(st["uncollectable"], 0)
796 # Check that collection counts are incremented correctly
797 if gc.isenabled():
798 self.addCleanup(gc.enable)
799 gc.disable()
800 old = gc.get_stats()
801 gc.collect(0)
802 new = gc.get_stats()
803 self.assertEqual(new[0]["collections"], old[0]["collections"] + 1)
804 self.assertEqual(new[1]["collections"], old[1]["collections"])
805 self.assertEqual(new[2]["collections"], old[2]["collections"])
806 gc.collect(2)
807 new = gc.get_stats()
808 self.assertEqual(new[0]["collections"], old[0]["collections"] + 1)
809 self.assertEqual(new[1]["collections"], old[1]["collections"])
810 self.assertEqual(new[2]["collections"], old[2]["collections"] + 1)
811
812 def test_freeze(self):
813 gc.freeze()
814 self.assertGreater(gc.get_freeze_count(), 0)
815 gc.unfreeze()
816 self.assertEqual(gc.get_freeze_count(), 0)
817
818 def test_get_objects(self):
819 gc.collect()
820 l = []
821 l.append(l)
822 self.assertTrue(
823 any(l is element for element in gc.get_objects(generation=0))
824 )
825 self.assertFalse(
826 any(l is element for element in gc.get_objects(generation=1))
827 )
828 self.assertFalse(
829 any(l is element for element in gc.get_objects(generation=2))
830 )
831 gc.collect(generation=0)
832 self.assertFalse(
833 any(l is element for element in gc.get_objects(generation=0))
834 )
835 self.assertTrue(
836 any(l is element for element in gc.get_objects(generation=1))
837 )
838 self.assertFalse(
839 any(l is element for element in gc.get_objects(generation=2))
840 )
841 gc.collect(generation=1)
842 self.assertFalse(
843 any(l is element for element in gc.get_objects(generation=0))
844 )
845 self.assertFalse(
846 any(l is element for element in gc.get_objects(generation=1))
847 )
848 self.assertTrue(
849 any(l is element for element in gc.get_objects(generation=2))
850 )
851 gc.collect(generation=2)
852 self.assertFalse(
853 any(l is element for element in gc.get_objects(generation=0))
854 )
855 self.assertFalse(
856 any(l is element for element in gc.get_objects(generation=1))
857 )
858 self.assertTrue(
859 any(l is element for element in gc.get_objects(generation=2))
860 )
861 del l
862 gc.collect()
863
864 def test_get_objects_arguments(self):
865 gc.collect()
866 self.assertEqual(len(gc.get_objects()),
867 len(gc.get_objects(generation=None)))
868
869 self.assertRaises(ValueError, gc.get_objects, 1000)
870 self.assertRaises(ValueError, gc.get_objects, -1000)
871 self.assertRaises(TypeError, gc.get_objects, "1")
872 self.assertRaises(TypeError, gc.get_objects, 1.234)
873
874 def test_resurrection_only_happens_once_per_object(self):
875 class A: # simple self-loop
876 def __init__(self):
877 self.me = self
878
879 class Lazarus(A):
880 resurrected = 0
881 resurrected_instances = []
882
883 def __del__(self):
884 Lazarus.resurrected += 1
885 Lazarus.resurrected_instances.append(self)
886
887 gc.collect()
888 gc.disable()
889
890 # We start with 0 resurrections
891 laz = Lazarus()
892 self.assertEqual(Lazarus.resurrected, 0)
893
894 # Deleting the instance and triggering a collection
895 # resurrects the object
896 del laz
897 gc.collect()
898 self.assertEqual(Lazarus.resurrected, 1)
899 self.assertEqual(len(Lazarus.resurrected_instances), 1)
900
901 # Clearing the references and forcing a collection
902 # should not resurrect the object again.
903 Lazarus.resurrected_instances.clear()
904 self.assertEqual(Lazarus.resurrected, 1)
905 gc.collect()
906 self.assertEqual(Lazarus.resurrected, 1)
907
908 gc.enable()
909
910 def test_resurrection_is_transitive(self):
911 class Cargo:
912 def __init__(self):
913 self.me = self
914
915 class Lazarus:
916 resurrected_instances = []
917
918 def __del__(self):
919 Lazarus.resurrected_instances.append(self)
920
921 gc.collect()
922 gc.disable()
923
924 laz = Lazarus()
925 cargo = Cargo()
926 cargo_id = id(cargo)
927
928 # Create a cycle between cargo and laz
929 laz.cargo = cargo
930 cargo.laz = laz
931
932 # Drop the references, force a collection and check that
933 # everything was resurrected.
934 del laz, cargo
935 gc.collect()
936 self.assertEqual(len(Lazarus.resurrected_instances), 1)
937 instance = Lazarus.resurrected_instances.pop()
938 self.assertTrue(hasattr(instance, "cargo"))
939 self.assertEqual(id(instance.cargo), cargo_id)
940
941 gc.collect()
942 gc.enable()
943
944 def test_resurrection_does_not_block_cleanup_of_other_objects(self):
945
946 # When a finalizer resurrects objects, stats were reporting them as
947 # having been collected. This affected both collect()'s return
948 # value and the dicts returned by get_stats().
949 N = 100
950
951 class A: # simple self-loop
952 def __init__(self):
953 self.me = self
954
955 class Z(A): # resurrecting __del__
956 def __del__(self):
957 zs.append(self)
958
959 zs = []
960
961 def getstats():
962 d = gc.get_stats()[-1]
963 return d['collected'], d['uncollectable']
964
965 gc.collect()
966 gc.disable()
967
968 # No problems if just collecting A() instances.
969 oldc, oldnc = getstats()
970 for i in range(N):
971 A()
972 t = gc.collect()
973 c, nc = getstats()
974 self.assertEqual(t, N) # instance objects
975 self.assertEqual(c - oldc, N)
976 self.assertEqual(nc - oldnc, 0)
977
978 # But Z() is not actually collected.
979 oldc, oldnc = c, nc
980 Z()
981 # Nothing is collected - Z() is merely resurrected.
982 t = gc.collect()
983 c, nc = getstats()
984 self.assertEqual(t, 0)
985 self.assertEqual(c - oldc, 0)
986 self.assertEqual(nc - oldnc, 0)
987
988 # Z() should not prevent anything else from being collected.
989 oldc, oldnc = c, nc
990 for i in range(N):
991 A()
992 Z()
993 t = gc.collect()
994 c, nc = getstats()
995 self.assertEqual(t, N)
996 self.assertEqual(c - oldc, N)
997 self.assertEqual(nc - oldnc, 0)
998
999 # The A() trash should have been reclaimed already but the
1000 # 2 copies of Z are still in zs (and the associated dicts).
1001 oldc, oldnc = c, nc
1002 zs.clear()
1003 t = gc.collect()
1004 c, nc = getstats()
1005 self.assertEqual(t, 2)
1006 self.assertEqual(c - oldc, 2)
1007 self.assertEqual(nc - oldnc, 0)
1008
1009 gc.enable()
1010
1011 @unittest.skipIf(ContainerNoGC is None,
1012 'requires ContainerNoGC extension type')
1013 def test_trash_weakref_clear(self):
1014 # Test that trash weakrefs are properly cleared (bpo-38006).
1015 #
1016 # Structure we are creating:
1017 #
1018 # Z <- Y <- A--+--> WZ -> C
1019 # ^ |
1020 # +--+
1021 # where:
1022 # WZ is a weakref to Z with callback C
1023 # Y doesn't implement tp_traverse
1024 # A contains a reference to itself, Y and WZ
1025 #
1026 # A, Y, Z, WZ are all trash. The GC doesn't know that Z is trash
1027 # because Y does not implement tp_traverse. To show the bug, WZ needs
1028 # to live long enough so that Z is deallocated before it. Then, if
1029 # gcmodule is buggy, when Z is being deallocated, C will run.
1030 #
1031 # To ensure WZ lives long enough, we put it in a second reference
1032 # cycle. That trick only works due to the ordering of the GC prev/next
1033 # linked lists. So, this test is a bit fragile.
1034 #
1035 # The bug reported in bpo-38006 is caused because the GC did not
1036 # clear WZ before starting the process of calling tp_clear on the
1037 # trash. Normally, handle_weakrefs() would find the weakref via Z and
1038 # clear it. However, since the GC cannot find Z, WR is not cleared and
1039 # it can execute during delete_garbage(). That can lead to disaster
1040 # since the callback might tinker with objects that have already had
1041 # tp_clear called on them (leaving them in possibly invalid states).
1042
1043 callback = unittest.mock.Mock()
1044
1045 class A:
1046 __slots__ = ['a', 'y', 'wz']
1047
1048 class Z:
1049 pass
1050
1051 # setup required object graph, as described above
1052 a = A()
1053 a.a = a
1054 a.y = ContainerNoGC(Z())
1055 a.wz = weakref.ref(a.y.value, callback)
1056 # create second cycle to keep WZ alive longer
1057 wr_cycle = [a.wz]
1058 wr_cycle.append(wr_cycle)
1059 # ensure trash unrelated to this test is gone
1060 gc.collect()
1061 gc.disable()
1062 # release references and create trash
1063 del a, wr_cycle
1064 gc.collect()
1065 # if called, it means there is a bug in the GC. The weakref should be
1066 # cleared before Z dies.
1067 callback.assert_not_called()
1068 gc.enable()
1069
1070
1071 class GCCallbackTests(unittest.TestCase):
1072 def setUp(self):
1073 # Save gc state and disable it.
1074 self.enabled = gc.isenabled()
1075 gc.disable()
1076 self.debug = gc.get_debug()
1077 gc.set_debug(0)
1078 gc.callbacks.append(self.cb1)
1079 gc.callbacks.append(self.cb2)
1080 self.othergarbage = []
1081
1082 def tearDown(self):
1083 # Restore gc state
1084 del self.visit
1085 gc.callbacks.remove(self.cb1)
1086 gc.callbacks.remove(self.cb2)
1087 gc.set_debug(self.debug)
1088 if self.enabled:
1089 gc.enable()
1090 # destroy any uncollectables
1091 gc.collect()
1092 for obj in gc.garbage:
1093 if isinstance(obj, Uncollectable):
1094 obj.partner = None
1095 del gc.garbage[:]
1096 del self.othergarbage
1097 gc.collect()
1098
1099 def preclean(self):
1100 # Remove all fluff from the system. Invoke this function
1101 # manually rather than through self.setUp() for maximum
1102 # safety.
1103 self.visit = []
1104 gc.collect()
1105 garbage, gc.garbage[:] = gc.garbage[:], []
1106 self.othergarbage.append(garbage)
1107 self.visit = []
1108
1109 def cb1(self, phase, info):
1110 self.visit.append((1, phase, dict(info)))
1111
1112 def cb2(self, phase, info):
1113 self.visit.append((2, phase, dict(info)))
1114 if phase == "stop" and hasattr(self, "cleanup"):
1115 # Clean Uncollectable from garbage
1116 uc = [e for e in gc.garbage if isinstance(e, Uncollectable)]
1117 gc.garbage[:] = [e for e in gc.garbage
1118 if not isinstance(e, Uncollectable)]
1119 for e in uc:
1120 e.partner = None
1121
1122 def test_collect(self):
1123 self.preclean()
1124 gc.collect()
1125 # Algorithmically verify the contents of self.visit
1126 # because it is long and tortuous.
1127
1128 # Count the number of visits to each callback
1129 n = [v[0] for v in self.visit]
1130 n1 = [i for i in n if i == 1]
1131 n2 = [i for i in n if i == 2]
1132 self.assertEqual(n1, [1]*2)
1133 self.assertEqual(n2, [2]*2)
1134
1135 # Count that we got the right number of start and stop callbacks.
1136 n = [v[1] for v in self.visit]
1137 n1 = [i for i in n if i == "start"]
1138 n2 = [i for i in n if i == "stop"]
1139 self.assertEqual(n1, ["start"]*2)
1140 self.assertEqual(n2, ["stop"]*2)
1141
1142 # Check that we got the right info dict for all callbacks
1143 for v in self.visit:
1144 info = v[2]
1145 self.assertTrue("generation" in info)
1146 self.assertTrue("collected" in info)
1147 self.assertTrue("uncollectable" in info)
1148
1149 def test_collect_generation(self):
1150 self.preclean()
1151 gc.collect(2)
1152 for v in self.visit:
1153 info = v[2]
1154 self.assertEqual(info["generation"], 2)
1155
1156 @cpython_only
1157 def test_collect_garbage(self):
1158 self.preclean()
1159 # Each of these cause two objects to be garbage:
1160 Uncollectable()
1161 Uncollectable()
1162 C1055820(666)
1163 gc.collect()
1164 for v in self.visit:
1165 if v[1] != "stop":
1166 continue
1167 info = v[2]
1168 self.assertEqual(info["collected"], 1)
1169 self.assertEqual(info["uncollectable"], 4)
1170
1171 # We should now have the Uncollectables in gc.garbage
1172 self.assertEqual(len(gc.garbage), 4)
1173 for e in gc.garbage:
1174 self.assertIsInstance(e, Uncollectable)
1175
1176 # Now, let our callback handle the Uncollectable instances
1177 self.cleanup=True
1178 self.visit = []
1179 gc.garbage[:] = []
1180 gc.collect()
1181 for v in self.visit:
1182 if v[1] != "stop":
1183 continue
1184 info = v[2]
1185 self.assertEqual(info["collected"], 0)
1186 self.assertEqual(info["uncollectable"], 2)
1187
1188 # Uncollectables should be gone
1189 self.assertEqual(len(gc.garbage), 0)
1190
1191
1192 @unittest.skipIf(BUILD_WITH_NDEBUG,
1193 'built with -NDEBUG')
1194 def test_refcount_errors(self):
1195 self.preclean()
1196 # Verify the "handling" of objects with broken refcounts
1197
1198 # Skip the test if ctypes is not available
1199 import_module("ctypes")
1200
1201 import subprocess
1202 code = textwrap.dedent('''
1203 from test.support import gc_collect, SuppressCrashReport
1204
1205 a = [1, 2, 3]
1206 b = [a]
1207
1208 # Avoid coredump when Py_FatalError() calls abort()
1209 SuppressCrashReport().__enter__()
1210
1211 # Simulate the refcount of "a" being too low (compared to the
1212 # references held on it by live data), but keeping it above zero
1213 # (to avoid deallocating it):
1214 import ctypes
1215 ctypes.pythonapi.Py_DecRef(ctypes.py_object(a))
1216
1217 # The garbage collector should now have a fatal error
1218 # when it reaches the broken object
1219 gc_collect()
1220 ''')
1221 p = subprocess.Popen([sys.executable, "-c", code],
1222 stdout=subprocess.PIPE,
1223 stderr=subprocess.PIPE)
1224 stdout, stderr = p.communicate()
1225 p.stdout.close()
1226 p.stderr.close()
1227 # Verify that stderr has a useful error message:
1228 self.assertRegex(stderr,
1229 br'gcmodule\.c:[0-9]+: gc_decref: Assertion "gc_get_refs\(g\) > 0" failed.')
1230 self.assertRegex(stderr,
1231 br'refcount is too small')
1232 # "address : 0x7fb5062efc18"
1233 # "address : 7FB5062EFC18"
1234 address_regex = br'[0-9a-fA-Fx]+'
1235 self.assertRegex(stderr,
1236 br'object address : ' + address_regex)
1237 self.assertRegex(stderr,
1238 br'object refcount : 1')
1239 self.assertRegex(stderr,
1240 br'object type : ' + address_regex)
1241 self.assertRegex(stderr,
1242 br'object type name: list')
1243 self.assertRegex(stderr,
1244 br'object repr : \[1, 2, 3\]')
1245
1246
1247 class GCTogglingTests(unittest.TestCase):
1248 def setUp(self):
1249 gc.enable()
1250
1251 def tearDown(self):
1252 gc.disable()
1253
1254 def test_bug1055820c(self):
1255 # Corresponds to temp2c.py in the bug report. This is pretty
1256 # elaborate.
1257
1258 c0 = C1055820(0)
1259 # Move c0 into generation 2.
1260 gc.collect()
1261
1262 c1 = C1055820(1)
1263 c1.keep_c0_alive = c0
1264 del c0.loop # now only c1 keeps c0 alive
1265
1266 c2 = C1055820(2)
1267 c2wr = weakref.ref(c2) # no callback!
1268
1269 ouch = []
1270 def callback(ignored):
1271 ouch[:] = [c2wr()]
1272
1273 # The callback gets associated with a wr on an object in generation 2.
1274 c0wr = weakref.ref(c0, callback)
1275
1276 c0 = c1 = c2 = None
1277
1278 # What we've set up: c0, c1, and c2 are all trash now. c0 is in
1279 # generation 2. The only thing keeping it alive is that c1 points to
1280 # it. c1 and c2 are in generation 0, and are in self-loops. There's a
1281 # global weakref to c2 (c2wr), but that weakref has no callback.
1282 # There's also a global weakref to c0 (c0wr), and that does have a
1283 # callback, and that callback references c2 via c2wr().
1284 #
1285 # c0 has a wr with callback, which references c2wr
1286 # ^
1287 # |
1288 # | Generation 2 above dots
1289 #. . . . . . . .|. . . . . . . . . . . . . . . . . . . . . . . .
1290 # | Generation 0 below dots
1291 # |
1292 # |
1293 # ^->c1 ^->c2 has a wr but no callback
1294 # | | | |
1295 # <--v <--v
1296 #
1297 # So this is the nightmare: when generation 0 gets collected, we see
1298 # that c2 has a callback-free weakref, and c1 doesn't even have a
1299 # weakref. Collecting generation 0 doesn't see c0 at all, and c0 is
1300 # the only object that has a weakref with a callback. gc clears c1
1301 # and c2. Clearing c1 has the side effect of dropping the refcount on
1302 # c0 to 0, so c0 goes away (despite that it's in an older generation)
1303 # and c0's wr callback triggers. That in turn materializes a reference
1304 # to c2 via c2wr(), but c2 gets cleared anyway by gc.
1305
1306 # We want to let gc happen "naturally", to preserve the distinction
1307 # between generations.
1308 junk = []
1309 i = 0
1310 detector = GC_Detector()
1311 while not detector.gc_happened:
1312 i += 1
1313 if i > 10000:
1314 self.fail("gc didn't happen after 10000 iterations")
1315 self.assertEqual(len(ouch), 0)
1316 junk.append([]) # this will eventually trigger gc
1317
1318 self.assertEqual(len(ouch), 1) # else the callback wasn't invoked
1319 for x in ouch:
1320 # If the callback resurrected c2, the instance would be damaged,
1321 # with an empty __dict__.
1322 self.assertEqual(x, None)
1323
1324 def test_bug1055820d(self):
1325 # Corresponds to temp2d.py in the bug report. This is very much like
1326 # test_bug1055820c, but uses a __del__ method instead of a weakref
1327 # callback to sneak in a resurrection of cyclic trash.
1328
1329 ouch = []
1330 class D(C1055820):
1331 def __del__(self):
1332 ouch[:] = [c2wr()]
1333
1334 d0 = D(0)
1335 # Move all the above into generation 2.
1336 gc.collect()
1337
1338 c1 = C1055820(1)
1339 c1.keep_d0_alive = d0
1340 del d0.loop # now only c1 keeps d0 alive
1341
1342 c2 = C1055820(2)
1343 c2wr = weakref.ref(c2) # no callback!
1344
1345 d0 = c1 = c2 = None
1346
1347 # What we've set up: d0, c1, and c2 are all trash now. d0 is in
1348 # generation 2. The only thing keeping it alive is that c1 points to
1349 # it. c1 and c2 are in generation 0, and are in self-loops. There's
1350 # a global weakref to c2 (c2wr), but that weakref has no callback.
1351 # There are no other weakrefs.
1352 #
1353 # d0 has a __del__ method that references c2wr
1354 # ^
1355 # |
1356 # | Generation 2 above dots
1357 #. . . . . . . .|. . . . . . . . . . . . . . . . . . . . . . . .
1358 # | Generation 0 below dots
1359 # |
1360 # |
1361 # ^->c1 ^->c2 has a wr but no callback
1362 # | | | |
1363 # <--v <--v
1364 #
1365 # So this is the nightmare: when generation 0 gets collected, we see
1366 # that c2 has a callback-free weakref, and c1 doesn't even have a
1367 # weakref. Collecting generation 0 doesn't see d0 at all. gc clears
1368 # c1 and c2. Clearing c1 has the side effect of dropping the refcount
1369 # on d0 to 0, so d0 goes away (despite that it's in an older
1370 # generation) and d0's __del__ triggers. That in turn materializes
1371 # a reference to c2 via c2wr(), but c2 gets cleared anyway by gc.
1372
1373 # We want to let gc happen "naturally", to preserve the distinction
1374 # between generations.
1375 detector = GC_Detector()
1376 junk = []
1377 i = 0
1378 while not detector.gc_happened:
1379 i += 1
1380 if i > 10000:
1381 self.fail("gc didn't happen after 10000 iterations")
1382 self.assertEqual(len(ouch), 0)
1383 junk.append([]) # this will eventually trigger gc
1384
1385 self.assertEqual(len(ouch), 1) # else __del__ wasn't invoked
1386 for x in ouch:
1387 # If __del__ resurrected c2, the instance would be damaged, with an
1388 # empty __dict__.
1389 self.assertEqual(x, None)
1390
1391
1392 class PythonFinalizationTests(unittest.TestCase):
1393 def test_ast_fini(self):
1394 # bpo-44184: Regression test for subtype_dealloc() when deallocating
1395 # an AST instance also destroy its AST type: subtype_dealloc() must
1396 # not access the type memory after deallocating the instance, since
1397 # the type memory can be freed as well. The test is also related to
1398 # _PyAST_Fini() which clears references to AST types.
1399 code = textwrap.dedent("""
1400 import ast
1401 import codecs
1402
1403 # Small AST tree to keep their AST types alive
1404 tree = ast.parse("def f(x, y): return 2*x-y")
1405 x = [tree]
1406 x.append(x)
1407
1408 # Put the cycle somewhere to survive until the last GC collection.
1409 # Codec search functions are only cleared at the end of
1410 # interpreter_clear().
1411 def search_func(encoding):
1412 return None
1413 search_func.a = x
1414 codecs.register(search_func)
1415 """)
1416 assert_python_ok("-c", code)
1417
1418
1419 def setUpModule():
1420 global enabled, debug
1421 enabled = gc.isenabled()
1422 gc.disable()
1423 assert not gc.isenabled()
1424 debug = gc.get_debug()
1425 gc.set_debug(debug & ~gc.DEBUG_LEAK) # this test is supposed to leak
1426 gc.collect() # Delete 2nd generation garbage
1427
1428
1429 def tearDownModule():
1430 gc.set_debug(debug)
1431 # test gc.enable() even if GC is disabled by default
1432 if verbose:
1433 print("restoring automatic collection")
1434 # make sure to always test gc.enable()
1435 gc.enable()
1436 assert gc.isenabled()
1437 if not enabled:
1438 gc.disable()
1439
1440
1441 if __name__ == "__main__":
1442 unittest.main()