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