Debian Codegraph @

lib-python/3/test/test_atexit.py

raw symbols SCIP
1 import atexit
2 import os
3 import sys
4 import textwrap
5 import unittest
6 from test import support
7 from test.support import script_helper
8
9
10 class GeneralTest(unittest.TestCase):
11 def test_general(self):
12 # Run _test_atexit.py in a subprocess since it calls atexit._clear()
13 script = support.findfile("_test_atexit.py")
14 script_helper.run_test_script(script)
15
16 class FunctionalTest(unittest.TestCase):
17 def test_shutdown(self):
18 # Actually test the shutdown mechanism in a subprocess
19 code = textwrap.dedent("""
20 import atexit
21
22 def f(msg):
23 print(msg)
24
25 atexit.register(f, "one")
26 atexit.register(f, "two")
27 """)
28 res = script_helper.assert_python_ok("-c", code)
29 self.assertEqual(res.out.decode().splitlines(), ["two", "one"])
30 self.assertFalse(res.err)
31
32 def test_atexit_instances(self):
33 # bpo-42639: It is safe to have more than one atexit instance.
34 code = textwrap.dedent("""
35 import sys
36 import atexit as atexit1
37 del sys.modules['atexit']
38 import atexit as atexit2
39 del sys.modules['atexit']
40
41 assert atexit2 is not atexit1
42
43 atexit1.register(print, "atexit1")
44 atexit2.register(print, "atexit2")
45 """)
46 res = script_helper.assert_python_ok("-c", code)
47 self.assertEqual(res.out.decode().splitlines(), ["atexit2", "atexit1"])
48 self.assertFalse(res.err)
49
50
51 @support.cpython_only
52 class SubinterpreterTest(unittest.TestCase):
53
54 @support.cpython_only
55 def test_callbacks_leak(self):
56 # This test shows a leak in refleak mode if atexit doesn't
57 # take care to free callbacks in its per-subinterpreter module
58 # state.
59 n = atexit._ncallbacks()
60 code = textwrap.dedent(r"""
61 import atexit
62 def f():
63 pass
64 atexit.register(f)
65 del atexit
66 """)
67 ret = support.run_in_subinterp(code)
68 self.assertEqual(ret, 0)
69 self.assertEqual(atexit._ncallbacks(), n)
70
71 @support.cpython_only
72 def test_callbacks_leak_refcycle(self):
73 # Similar to the above, but with a refcycle through the atexit
74 # module.
75 n = atexit._ncallbacks()
76 code = textwrap.dedent(r"""
77 import atexit
78 def f():
79 pass
80 atexit.register(f)
81 atexit.__atexit = atexit
82 """)
83 ret = support.run_in_subinterp(code)
84 self.assertEqual(ret, 0)
85 self.assertEqual(atexit._ncallbacks(), n)
86
87 @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()")
88 def test_callback_on_subinterpreter_teardown(self):
89 # This tests if a callback is called on
90 # subinterpreter teardown.
91 expected = b"The test has passed!"
92 r, w = os.pipe()
93
94 code = textwrap.dedent(r"""
95 import os
96 import atexit
97 def callback():
98 os.write({:d}, b"The test has passed!")
99 atexit.register(callback)
100 """.format(w))
101 ret = support.run_in_subinterp(code)
102 os.close(w)
103 self.assertEqual(os.read(r, len(expected)), expected)
104 os.close(r)
105
106
107 if __name__ == "__main__":
108 unittest.main()