Debian Codegraph @

Lib/test/test_gc.py

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