blob: 01a8a6eaf5a23cc9e95e821b1cc044d0dbbfa290 [file] [log] [blame]
Guido van Rossumf137f752001-10-04 00:58:24 +00001"""Test suite for the profile module."""
2
Christian Heimes2202f872008-02-06 14:31:34 +00003import sys
4import pstats
5import unittest
Giampaolo Rodola'b071d4f2013-02-12 14:31:06 +01006import os
Christian Heimes2202f872008-02-06 14:31:34 +00007from difflib import unified_diff
8from io import StringIO
Giampaolo Rodola'b071d4f2013-02-12 14:31:06 +01009from test.support import TESTFN, run_unittest, unlink
10from contextlib import contextmanager
Guido van Rossumf137f752001-10-04 00:58:24 +000011
Christian Heimes2202f872008-02-06 14:31:34 +000012import profile
13from test.profilee import testfunc, timer
Mario Corcheroad1a25f2018-11-05 15:03:46 +030014from test.support.script_helper import assert_python_failure, assert_python_ok
Tim Peters527e64f2001-10-04 05:36:56 +000015
Christian Heimes2202f872008-02-06 14:31:34 +000016
17class ProfileTest(unittest.TestCase):
18
19 profilerclass = profile.Profile
Giampaolo Rodola'b071d4f2013-02-12 14:31:06 +010020 profilermodule = profile
Christian Heimes2202f872008-02-06 14:31:34 +000021 methodnames = ['print_stats', 'print_callers', 'print_callees']
Antoine Pitrou8e124f32009-05-30 21:41:10 +000022 expected_max_output = ':0(max)'
Benjamin Peterson7d766532008-10-06 22:05:00 +000023
Giampaolo Rodola'b071d4f2013-02-12 14:31:06 +010024 def tearDown(self):
25 unlink(TESTFN)
26
Benjamin Peterson7d766532008-10-06 22:05:00 +000027 def get_expected_output(self):
28 return _ProfileOutput
Christian Heimes2202f872008-02-06 14:31:34 +000029
30 @classmethod
31 def do_profiling(cls):
32 results = []
33 prof = cls.profilerclass(timer, 0.001)
Christian Heimesdae2a892008-04-19 00:55:37 +000034 start_timer = timer()
Christian Heimes2202f872008-02-06 14:31:34 +000035 prof.runctx("testfunc()", globals(), locals())
Christian Heimesdae2a892008-04-19 00:55:37 +000036 results.append(timer() - start_timer)
Christian Heimes2202f872008-02-06 14:31:34 +000037 for methodname in cls.methodnames:
38 s = StringIO()
39 stats = pstats.Stats(prof, stream=s)
40 stats.strip_dirs().sort_stats("stdname")
41 getattr(stats, methodname)()
Brett Cannonc17b35c2008-03-01 04:28:23 +000042 output = s.getvalue().splitlines()
43 mod_name = testfunc.__module__.rsplit('.', 1)[1]
44 # Only compare against stats originating from the test file.
45 # Prevents outside code (e.g., the io module) from causing
46 # unexpected output.
47 output = [line.rstrip() for line in output if mod_name in line]
48 results.append('\n'.join(output))
Christian Heimes2202f872008-02-06 14:31:34 +000049 return results
50
51 def test_cprofile(self):
52 results = self.do_profiling()
Benjamin Peterson7d766532008-10-06 22:05:00 +000053 expected = self.get_expected_output()
Christian Heimesdae2a892008-04-19 00:55:37 +000054 self.assertEqual(results[0], 1000)
jdemeyerac9240b2018-05-09 06:16:35 +020055 fail = []
Christian Heimes2202f872008-02-06 14:31:34 +000056 for i, method in enumerate(self.methodnames):
jdemeyerac9240b2018-05-09 06:16:35 +020057 a = expected[method]
58 b = results[i+1]
59 if a != b:
60 fail.append(f"\nStats.{method} output for "
61 f"{self.profilerclass.__name__} "
62 "does not fit expectation:")
63 fail.extend(unified_diff(a.split('\n'), b.split('\n'),
64 lineterm=""))
65 if fail:
66 self.fail("\n".join(fail))
Christian Heimes2202f872008-02-06 14:31:34 +000067
Antoine Pitrou8e124f32009-05-30 21:41:10 +000068 def test_calling_conventions(self):
69 # Issue #5330: profile and cProfile wouldn't report C functions called
70 # with keyword arguments. We test all calling conventions.
71 stmts = [
72 "max([0])",
73 "max([0], key=int)",
74 "max([0], **dict(key=int))",
75 "max(*([0],))",
76 "max(*([0],), key=int)",
77 "max(*([0],), **dict(key=int))",
78 ]
79 for stmt in stmts:
80 s = StringIO()
81 prof = self.profilerclass(timer, 0.001)
82 prof.runctx(stmt, globals(), locals())
83 stats = pstats.Stats(prof, stream=s)
84 stats.print_stats()
85 res = s.getvalue()
Ezio Melottib58e0bd2010-01-23 15:40:09 +000086 self.assertIn(self.expected_max_output, res,
Antoine Pitrou8e124f32009-05-30 21:41:10 +000087 "Profiling {0!r} didn't report max:\n{1}".format(stmt, res))
88
Giampaolo Rodola'b071d4f2013-02-12 14:31:06 +010089 def test_run(self):
90 with silent():
Giampaolo Rodola'58cf4532013-02-12 15:23:21 +010091 self.profilermodule.run("int('1')")
92 self.profilermodule.run("int('1')", filename=TESTFN)
Giampaolo Rodola'b071d4f2013-02-12 14:31:06 +010093 self.assertTrue(os.path.exists(TESTFN))
94
95 def test_runctx(self):
96 with silent():
97 self.profilermodule.runctx("testfunc()", globals(), locals())
98 self.profilermodule.runctx("testfunc()", globals(), locals(),
99 filename=TESTFN)
100 self.assertTrue(os.path.exists(TESTFN))
101
Mario Corcheroad1a25f2018-11-05 15:03:46 +0300102 def test_run_profile_as_module(self):
103 # Test that -m switch needs an argument
104 assert_python_failure('-m', self.profilermodule.__name__, '-m')
105
106 # Test failure for not-existent module
107 assert_python_failure('-m', self.profilermodule.__name__,
108 '-m', 'random_module_xyz')
109
110 # Test successful run
111 assert_python_ok('-m', self.profilermodule.__name__,
112 '-m', 'timeit', '-n', '1')
113
Christian Heimes2202f872008-02-06 14:31:34 +0000114
115def regenerate_expected_output(filename, cls):
116 filename = filename.rstrip('co')
117 print('Regenerating %s...' % filename)
118 results = cls.do_profiling()
119
120 newfile = []
121 with open(filename, 'r') as f:
122 for line in f:
123 newfile.append(line)
Brett Cannonc17b35c2008-03-01 04:28:23 +0000124 if line.startswith('#--cut'):
Christian Heimes2202f872008-02-06 14:31:34 +0000125 break
126
127 with open(filename, 'w') as f:
128 f.writelines(newfile)
Benjamin Peterson7d766532008-10-06 22:05:00 +0000129 f.write("_ProfileOutput = {}\n")
Christian Heimes2202f872008-02-06 14:31:34 +0000130 for i, method in enumerate(cls.methodnames):
Benjamin Peterson7d766532008-10-06 22:05:00 +0000131 f.write('_ProfileOutput[%r] = """\\\n%s"""\n' % (
132 method, results[i+1]))
Christian Heimes2202f872008-02-06 14:31:34 +0000133 f.write('\nif __name__ == "__main__":\n main()\n')
134
Giampaolo Rodola'b071d4f2013-02-12 14:31:06 +0100135@contextmanager
136def silent():
137 stdout = sys.stdout
138 try:
139 sys.stdout = StringIO()
140 yield
141 finally:
142 sys.stdout = stdout
Armin Rigoa871ef22006-02-08 12:53:56 +0000143
144def test_main():
Christian Heimes2202f872008-02-06 14:31:34 +0000145 run_unittest(ProfileTest)
Guido van Rossumf137f752001-10-04 00:58:24 +0000146
Christian Heimes2202f872008-02-06 14:31:34 +0000147def main():
148 if '-r' not in sys.argv:
149 test_main()
Armin Rigoa871ef22006-02-08 12:53:56 +0000150 else:
Christian Heimes2202f872008-02-06 14:31:34 +0000151 regenerate_expected_output(__file__, ProfileTest)
Armin Rigoa871ef22006-02-08 12:53:56 +0000152
Guido van Rossumf137f752001-10-04 00:58:24 +0000153
Christian Heimes2202f872008-02-06 14:31:34 +0000154# Don't remove this comment. Everything below it is auto-generated.
155#--cut--------------------------------------------------------------------------
Benjamin Peterson7d766532008-10-06 22:05:00 +0000156_ProfileOutput = {}
157_ProfileOutput['print_stats'] = """\
Christian Heimes2202f872008-02-06 14:31:34 +0000158 28 27.972 0.999 27.972 0.999 profilee.py:110(__getattr__)
159 1 269.996 269.996 999.769 999.769 profilee.py:25(testfunc)
160 23/3 149.937 6.519 169.917 56.639 profilee.py:35(factorial)
161 20 19.980 0.999 19.980 0.999 profilee.py:48(mul)
162 2 39.986 19.993 599.830 299.915 profilee.py:55(helper)
163 4 115.984 28.996 119.964 29.991 profilee.py:73(helper1)
164 2 -0.006 -0.003 139.946 69.973 profilee.py:84(helper2_indirect)
165 8 311.976 38.997 399.912 49.989 profilee.py:88(helper2)
Brett Cannonc17b35c2008-03-01 04:28:23 +0000166 8 63.976 7.997 79.960 9.995 profilee.py:98(subhelper)"""
Benjamin Peterson7d766532008-10-06 22:05:00 +0000167_ProfileOutput['print_callers'] = """\
Christian Heimes2202f872008-02-06 14:31:34 +0000168:0(append) <- profilee.py:73(helper1)(4) 119.964
169:0(exc_info) <- profilee.py:73(helper1)(4) 119.964
Christian Heimes2202f872008-02-06 14:31:34 +0000170:0(hasattr) <- profilee.py:73(helper1)(4) 119.964
171 profilee.py:88(helper2)(8) 399.912
Christian Heimes2202f872008-02-06 14:31:34 +0000172profilee.py:110(__getattr__) <- :0(hasattr)(12) 11.964
173 profilee.py:98(subhelper)(16) 79.960
174profilee.py:25(testfunc) <- <string>:1(<module>)(1) 999.767
175profilee.py:35(factorial) <- profilee.py:25(testfunc)(1) 999.769
176 profilee.py:35(factorial)(20) 169.917
177 profilee.py:84(helper2_indirect)(2) 139.946
178profilee.py:48(mul) <- profilee.py:35(factorial)(20) 169.917
179profilee.py:55(helper) <- profilee.py:25(testfunc)(2) 999.769
180profilee.py:73(helper1) <- profilee.py:55(helper)(4) 599.830
181profilee.py:84(helper2_indirect) <- profilee.py:55(helper)(2) 599.830
182profilee.py:88(helper2) <- profilee.py:55(helper)(6) 599.830
183 profilee.py:84(helper2_indirect)(2) 139.946
Brett Cannonc17b35c2008-03-01 04:28:23 +0000184profilee.py:98(subhelper) <- profilee.py:88(helper2)(8) 399.912"""
Benjamin Peterson7d766532008-10-06 22:05:00 +0000185_ProfileOutput['print_callees'] = """\
Christian Heimes2202f872008-02-06 14:31:34 +0000186:0(hasattr) -> profilee.py:110(__getattr__)(12) 27.972
Christian Heimes2202f872008-02-06 14:31:34 +0000187<string>:1(<module>) -> profilee.py:25(testfunc)(1) 999.769
Christian Heimes2202f872008-02-06 14:31:34 +0000188profilee.py:110(__getattr__) ->
189profilee.py:25(testfunc) -> profilee.py:35(factorial)(1) 169.917
190 profilee.py:55(helper)(2) 599.830
191profilee.py:35(factorial) -> profilee.py:35(factorial)(20) 169.917
192 profilee.py:48(mul)(20) 19.980
193profilee.py:48(mul) ->
194profilee.py:55(helper) -> profilee.py:73(helper1)(4) 119.964
195 profilee.py:84(helper2_indirect)(2) 139.946
196 profilee.py:88(helper2)(6) 399.912
197profilee.py:73(helper1) -> :0(append)(4) -0.004
Christian Heimes2202f872008-02-06 14:31:34 +0000198profilee.py:84(helper2_indirect) -> profilee.py:35(factorial)(2) 169.917
199 profilee.py:88(helper2)(2) 399.912
200profilee.py:88(helper2) -> :0(hasattr)(8) 11.964
201 profilee.py:98(subhelper)(8) 79.960
Brett Cannonc17b35c2008-03-01 04:28:23 +0000202profilee.py:98(subhelper) -> profilee.py:110(__getattr__)(16) 27.972"""
Guido van Rossumf137f752001-10-04 00:58:24 +0000203
204if __name__ == "__main__":
Christian Heimes2202f872008-02-06 14:31:34 +0000205 main()