Debian Codegraph @

Lib/test/test_cprofile.py

raw
1 """Test suite for the cProfile module."""
2
3 import sys
4 import unittest
5
6 # rip off all interesting stuff from test_profile
7 import cProfile
8 import tempfile
9 import textwrap
10 from test.test_profile import ProfileTest, regenerate_expected_output
11 from test.support.script_helper import assert_python_failure, assert_python_ok
12 from test import support
13
14
15 class CProfileTest(ProfileTest):
16 profilerclass = cProfile.Profile
17 profilermodule = cProfile
18 expected_max_output = "{built-in method builtins.max}"
19
20 def get_expected_output(self):
21 return _ProfileOutput
22
23 def test_bad_counter_during_dealloc(self):
24 # bpo-3895
25 import _lsprof
26
27 with support.catch_unraisable_exception() as cm:
28 obj = _lsprof.Profiler(lambda: int)
29 obj.enable()
30 obj.disable()
31 obj.clear()
32
33 self.assertEqual(cm.unraisable.exc_type, TypeError)
34
35 def test_crash_with_not_enough_args(self):
36 # gh-126220
37 import _lsprof
38
39 for profile in [_lsprof.Profiler(), cProfile.Profile()]:
40 for method in [
41 "_pystart_callback",
42 "_pyreturn_callback",
43 "_ccall_callback",
44 "_creturn_callback",
45 ]:
46 with self.subTest(profile=profile, method=method):
47 method_obj = getattr(profile, method)
48 with self.assertRaises(TypeError):
49 method_obj() # should not crash
50
51 def test_evil_external_timer(self):
52 # gh-120289
53 # Disabling profiler in external timer should not crash
54 import _lsprof
55 class EvilTimer():
56 def __init__(self, disable_count):
57 self.count = 0
58 self.disable_count = disable_count
59
60 def __call__(self):
61 self.count += 1
62 if self.count == self.disable_count:
63 profiler_with_evil_timer.disable()
64 return self.count
65
66 # this will trigger external timer to disable profiler at
67 # call event - in initContext in _lsprof.c
68 with support.catch_unraisable_exception() as cm:
69 profiler_with_evil_timer = _lsprof.Profiler(EvilTimer(1))
70 profiler_with_evil_timer.enable()
71 # Make a call to trigger timer
72 (lambda: None)()
73 profiler_with_evil_timer.disable()
74 profiler_with_evil_timer.clear()
75 self.assertEqual(cm.unraisable.exc_type, RuntimeError)
76
77 # this will trigger external timer to disable profiler at
78 # return event - in Stop in _lsprof.c
79 with support.catch_unraisable_exception() as cm:
80 profiler_with_evil_timer = _lsprof.Profiler(EvilTimer(2))
81 profiler_with_evil_timer.enable()
82 # Make a call to trigger timer
83 (lambda: None)()
84 profiler_with_evil_timer.disable()
85 profiler_with_evil_timer.clear()
86 self.assertEqual(cm.unraisable.exc_type, RuntimeError)
87
88 def test_profile_enable_disable(self):
89 prof = self.profilerclass()
90 # Make sure we clean ourselves up if the test fails for some reason.
91 self.addCleanup(prof.disable)
92
93 prof.enable()
94 self.assertEqual(
95 sys.monitoring.get_tool(sys.monitoring.PROFILER_ID), "cProfile")
96
97 prof.disable()
98 self.assertIs(sys.monitoring.get_tool(sys.monitoring.PROFILER_ID), None)
99
100 def test_profile_as_context_manager(self):
101 prof = self.profilerclass()
102 # Make sure we clean ourselves up if the test fails for some reason.
103 self.addCleanup(prof.disable)
104
105 with prof as __enter__return_value:
106 # profile.__enter__ should return itself.
107 self.assertIs(prof, __enter__return_value)
108
109 # profile should be set as the global profiler inside the
110 # with-block
111 self.assertEqual(
112 sys.monitoring.get_tool(sys.monitoring.PROFILER_ID), "cProfile")
113
114 # profile shouldn't be set once we leave the with-block.
115 self.assertIs(sys.monitoring.get_tool(sys.monitoring.PROFILER_ID), None)
116
117 def test_second_profiler(self):
118 pr = self.profilerclass()
119 pr2 = self.profilerclass()
120 pr.enable()
121 self.assertRaises(ValueError, pr2.enable)
122 pr.disable()
123
124 def test_throw(self):
125 """
126 gh-106152
127 generator.throw() should trigger a call in cProfile
128 """
129
130 def gen():
131 yield
132
133 pr = self.profilerclass()
134 pr.enable()
135 g = gen()
136 try:
137 g.throw(SyntaxError)
138 except SyntaxError:
139 pass
140 pr.disable()
141 pr.create_stats()
142
143 self.assertTrue(any("throw" in func[2] for func in pr.stats.keys())),
144
145 def test_bad_descriptor(self):
146 # gh-132250
147 # cProfile should not crash when the profiler callback fails to locate
148 # the actual function of a method.
149 with self.profilerclass() as prof:
150 with self.assertRaises(TypeError):
151 bytes.find(str())
152
153
154 class TestCommandLine(unittest.TestCase):
155 def test_sort(self):
156 rc, out, err = assert_python_failure('-m', 'cProfile', '-s', 'demo')
157 self.assertGreater(rc, 0)
158 self.assertIn(b"option -s: invalid choice: 'demo'", err)
159
160 def test_profile_script_importing_main(self):
161 """Check that scripts that reference __main__ see their own namespace
162 when being profiled."""
163 with tempfile.NamedTemporaryFile("w+", delete_on_close=False) as f:
164 f.write(textwrap.dedent("""\
165 class Foo:
166 pass
167 import __main__
168 assert Foo == __main__.Foo
169 """))
170 f.close()
171 assert_python_ok('-m', "cProfile", f.name)
172
173
174 def main():
175 if '-r' not in sys.argv:
176 unittest.main()
177 else:
178 regenerate_expected_output(__file__, CProfileTest)
179
180
181 # Don't remove this comment. Everything below it is auto-generated.
182 #--cut--------------------------------------------------------------------------
183 _ProfileOutput = {}
184 _ProfileOutput['print_stats'] = """\
185 28 0.028 0.001 0.028 0.001 profilee.py:110(__getattr__)
186 1 0.270 0.270 1.000 1.000 profilee.py:25(testfunc)
187 23/3 0.150 0.007 0.170 0.057 profilee.py:35(factorial)
188 20 0.020 0.001 0.020 0.001 profilee.py:48(mul)
189 2 0.040 0.020 0.600 0.300 profilee.py:55(helper)
190 4 0.116 0.029 0.120 0.030 profilee.py:73(helper1)
191 2 0.000 0.000 0.140 0.070 profilee.py:84(helper2_indirect)
192 8 0.312 0.039 0.400 0.050 profilee.py:88(helper2)
193 8 0.064 0.008 0.080 0.010 profilee.py:98(subhelper)"""
194 _ProfileOutput['print_callers'] = """\
195 profilee.py:110(__getattr__) <- 16 0.016 0.016 profilee.py:98(subhelper)
196 profilee.py:25(testfunc) <- 1 0.270 1.000 <string>:1(<module>)
197 profilee.py:35(factorial) <- 1 0.014 0.130 profilee.py:25(testfunc)
198 20/3 0.130 0.147 profilee.py:35(factorial)
199 2 0.006 0.040 profilee.py:84(helper2_indirect)
200 profilee.py:48(mul) <- 20 0.020 0.020 profilee.py:35(factorial)
201 profilee.py:55(helper) <- 2 0.040 0.600 profilee.py:25(testfunc)
202 profilee.py:73(helper1) <- 4 0.116 0.120 profilee.py:55(helper)
203 profilee.py:84(helper2_indirect) <- 2 0.000 0.140 profilee.py:55(helper)
204 profilee.py:88(helper2) <- 6 0.234 0.300 profilee.py:55(helper)
205 2 0.078 0.100 profilee.py:84(helper2_indirect)
206 profilee.py:98(subhelper) <- 8 0.064 0.080 profilee.py:88(helper2)
207 {built-in method builtins.hasattr} <- 4 0.000 0.004 profilee.py:73(helper1)
208 8 0.000 0.008 profilee.py:88(helper2)
209 {built-in method sys.exception} <- 4 0.000 0.000 profilee.py:73(helper1)
210 {method 'append' of 'list' objects} <- 4 0.000 0.000 profilee.py:73(helper1)"""
211 _ProfileOutput['print_callees'] = """\
212 <string>:1(<module>) -> 1 0.270 1.000 profilee.py:25(testfunc)
213 profilee.py:110(__getattr__) ->
214 profilee.py:25(testfunc) -> 1 0.014 0.130 profilee.py:35(factorial)
215 2 0.040 0.600 profilee.py:55(helper)
216 profilee.py:35(factorial) -> 20/3 0.130 0.147 profilee.py:35(factorial)
217 20 0.020 0.020 profilee.py:48(mul)
218 profilee.py:48(mul) ->
219 profilee.py:55(helper) -> 4 0.116 0.120 profilee.py:73(helper1)
220 2 0.000 0.140 profilee.py:84(helper2_indirect)
221 6 0.234 0.300 profilee.py:88(helper2)
222 profilee.py:73(helper1) -> 4 0.000 0.004 {built-in method builtins.hasattr}
223 profilee.py:84(helper2_indirect) -> 2 0.006 0.040 profilee.py:35(factorial)
224 2 0.078 0.100 profilee.py:88(helper2)
225 profilee.py:88(helper2) -> 8 0.064 0.080 profilee.py:98(subhelper)
226 profilee.py:98(subhelper) -> 16 0.016 0.016 profilee.py:110(__getattr__)
227 {built-in method builtins.hasattr} -> 12 0.012 0.012 profilee.py:110(__getattr__)"""
228
229 if __name__ == "__main__":
230 main()