blob: 1bdf30acbb54b23b0c3abcd119d44d2c413f0446 [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
Hai Shia089d212020-07-06 17:15:08 +08009from test.support import run_unittest
Anthony Sottile3c0ac182020-10-18 13:48:31 -070010from test.support.os_helper import TESTFN, unlink, temp_dir, change_cwd
Giampaolo Rodola'b071d4f2013-02-12 14:31:06 +010011from contextlib import contextmanager
Guido van Rossumf137f752001-10-04 00:58:24 +000012
Christian Heimes2202f872008-02-06 14:31:34 +000013import profile
14from test.profilee import testfunc, timer
Mario Corcheroad1a25f2018-11-05 15:03:46 +030015from test.support.script_helper import assert_python_failure, assert_python_ok
Tim Peters527e64f2001-10-04 05:36:56 +000016
Christian Heimes2202f872008-02-06 14:31:34 +000017
18class ProfileTest(unittest.TestCase):
19
20 profilerclass = profile.Profile
Giampaolo Rodola'b071d4f2013-02-12 14:31:06 +010021 profilermodule = profile
Christian Heimes2202f872008-02-06 14:31:34 +000022 methodnames = ['print_stats', 'print_callers', 'print_callees']
Antoine Pitrou8e124f32009-05-30 21:41:10 +000023 expected_max_output = ':0(max)'
Benjamin Peterson7d766532008-10-06 22:05:00 +000024
Giampaolo Rodola'b071d4f2013-02-12 14:31:06 +010025 def tearDown(self):
26 unlink(TESTFN)
27
Benjamin Peterson7d766532008-10-06 22:05:00 +000028 def get_expected_output(self):
29 return _ProfileOutput
Christian Heimes2202f872008-02-06 14:31:34 +000030
31 @classmethod
32 def do_profiling(cls):
33 results = []
34 prof = cls.profilerclass(timer, 0.001)
Christian Heimesdae2a892008-04-19 00:55:37 +000035 start_timer = timer()
Christian Heimes2202f872008-02-06 14:31:34 +000036 prof.runctx("testfunc()", globals(), locals())
Christian Heimesdae2a892008-04-19 00:55:37 +000037 results.append(timer() - start_timer)
Christian Heimes2202f872008-02-06 14:31:34 +000038 for methodname in cls.methodnames:
39 s = StringIO()
40 stats = pstats.Stats(prof, stream=s)
41 stats.strip_dirs().sort_stats("stdname")
42 getattr(stats, methodname)()
Brett Cannonc17b35c2008-03-01 04:28:23 +000043 output = s.getvalue().splitlines()
44 mod_name = testfunc.__module__.rsplit('.', 1)[1]
45 # Only compare against stats originating from the test file.
46 # Prevents outside code (e.g., the io module) from causing
47 # unexpected output.
48 output = [line.rstrip() for line in output if mod_name in line]
49 results.append('\n'.join(output))
Christian Heimes2202f872008-02-06 14:31:34 +000050 return results
51
52 def test_cprofile(self):
53 results = self.do_profiling()
Benjamin Peterson7d766532008-10-06 22:05:00 +000054 expected = self.get_expected_output()
Christian Heimesdae2a892008-04-19 00:55:37 +000055 self.assertEqual(results[0], 1000)
jdemeyerac9240b2018-05-09 06:16:35 +020056 fail = []
Christian Heimes2202f872008-02-06 14:31:34 +000057 for i, method in enumerate(self.methodnames):
jdemeyerac9240b2018-05-09 06:16:35 +020058 a = expected[method]
59 b = results[i+1]
60 if a != b:
61 fail.append(f"\nStats.{method} output for "
62 f"{self.profilerclass.__name__} "
63 "does not fit expectation:")
64 fail.extend(unified_diff(a.split('\n'), b.split('\n'),
65 lineterm=""))
66 if fail:
67 self.fail("\n".join(fail))
Christian Heimes2202f872008-02-06 14:31:34 +000068
Antoine Pitrou8e124f32009-05-30 21:41:10 +000069 def test_calling_conventions(self):
70 # Issue #5330: profile and cProfile wouldn't report C functions called
71 # with keyword arguments. We test all calling conventions.
72 stmts = [
73 "max([0])",
74 "max([0], key=int)",
75 "max([0], **dict(key=int))",
76 "max(*([0],))",
77 "max(*([0],), key=int)",
78 "max(*([0],), **dict(key=int))",
79 ]
80 for stmt in stmts:
81 s = StringIO()
82 prof = self.profilerclass(timer, 0.001)
83 prof.runctx(stmt, globals(), locals())
84 stats = pstats.Stats(prof, stream=s)
85 stats.print_stats()
86 res = s.getvalue()
Ezio Melottib58e0bd2010-01-23 15:40:09 +000087 self.assertIn(self.expected_max_output, res,
Antoine Pitrou8e124f32009-05-30 21:41:10 +000088 "Profiling {0!r} didn't report max:\n{1}".format(stmt, res))
89
Giampaolo Rodola'b071d4f2013-02-12 14:31:06 +010090 def test_run(self):
91 with silent():
Giampaolo Rodola'58cf4532013-02-12 15:23:21 +010092 self.profilermodule.run("int('1')")
93 self.profilermodule.run("int('1')", filename=TESTFN)
Giampaolo Rodola'b071d4f2013-02-12 14:31:06 +010094 self.assertTrue(os.path.exists(TESTFN))
95
96 def test_runctx(self):
97 with silent():
98 self.profilermodule.runctx("testfunc()", globals(), locals())
99 self.profilermodule.runctx("testfunc()", globals(), locals(),
100 filename=TESTFN)
101 self.assertTrue(os.path.exists(TESTFN))
102
Mario Corcheroad1a25f2018-11-05 15:03:46 +0300103 def test_run_profile_as_module(self):
104 # Test that -m switch needs an argument
105 assert_python_failure('-m', self.profilermodule.__name__, '-m')
106
107 # Test failure for not-existent module
108 assert_python_failure('-m', self.profilermodule.__name__,
109 '-m', 'random_module_xyz')
110
111 # Test successful run
112 assert_python_ok('-m', self.profilermodule.__name__,
113 '-m', 'timeit', '-n', '1')
114
Anthony Sottile3c0ac182020-10-18 13:48:31 -0700115 def test_output_file_when_changing_directory(self):
116 with temp_dir() as tmpdir, change_cwd(tmpdir):
117 os.mkdir('dest')
118 with open('demo.py', 'w') as f:
119 f.write('import os; os.chdir("dest")')
120
121 assert_python_ok(
122 '-m', self.profilermodule.__name__,
123 '-o', 'out.pstats',
124 'demo.py',
125 )
126
127 self.assertTrue(os.path.exists('out.pstats'))
128
Christian Heimes2202f872008-02-06 14:31:34 +0000129
130def regenerate_expected_output(filename, cls):
131 filename = filename.rstrip('co')
132 print('Regenerating %s...' % filename)
133 results = cls.do_profiling()
134
135 newfile = []
136 with open(filename, 'r') as f:
137 for line in f:
138 newfile.append(line)
Brett Cannonc17b35c2008-03-01 04:28:23 +0000139 if line.startswith('#--cut'):
Christian Heimes2202f872008-02-06 14:31:34 +0000140 break
141
142 with open(filename, 'w') as f:
143 f.writelines(newfile)
Benjamin Peterson7d766532008-10-06 22:05:00 +0000144 f.write("_ProfileOutput = {}\n")
Christian Heimes2202f872008-02-06 14:31:34 +0000145 for i, method in enumerate(cls.methodnames):
Benjamin Peterson7d766532008-10-06 22:05:00 +0000146 f.write('_ProfileOutput[%r] = """\\\n%s"""\n' % (
147 method, results[i+1]))
Christian Heimes2202f872008-02-06 14:31:34 +0000148 f.write('\nif __name__ == "__main__":\n main()\n')
149
Giampaolo Rodola'b071d4f2013-02-12 14:31:06 +0100150@contextmanager
151def silent():
152 stdout = sys.stdout
153 try:
154 sys.stdout = StringIO()
155 yield
156 finally:
157 sys.stdout = stdout
Armin Rigoa871ef22006-02-08 12:53:56 +0000158
159def test_main():
Christian Heimes2202f872008-02-06 14:31:34 +0000160 run_unittest(ProfileTest)
Guido van Rossumf137f752001-10-04 00:58:24 +0000161
Christian Heimes2202f872008-02-06 14:31:34 +0000162def main():
163 if '-r' not in sys.argv:
164 test_main()
Armin Rigoa871ef22006-02-08 12:53:56 +0000165 else:
Christian Heimes2202f872008-02-06 14:31:34 +0000166 regenerate_expected_output(__file__, ProfileTest)
Armin Rigoa871ef22006-02-08 12:53:56 +0000167
Guido van Rossumf137f752001-10-04 00:58:24 +0000168
Christian Heimes2202f872008-02-06 14:31:34 +0000169# Don't remove this comment. Everything below it is auto-generated.
170#--cut--------------------------------------------------------------------------
Benjamin Peterson7d766532008-10-06 22:05:00 +0000171_ProfileOutput = {}
172_ProfileOutput['print_stats'] = """\
Christian Heimes2202f872008-02-06 14:31:34 +0000173 28 27.972 0.999 27.972 0.999 profilee.py:110(__getattr__)
174 1 269.996 269.996 999.769 999.769 profilee.py:25(testfunc)
175 23/3 149.937 6.519 169.917 56.639 profilee.py:35(factorial)
176 20 19.980 0.999 19.980 0.999 profilee.py:48(mul)
177 2 39.986 19.993 599.830 299.915 profilee.py:55(helper)
178 4 115.984 28.996 119.964 29.991 profilee.py:73(helper1)
179 2 -0.006 -0.003 139.946 69.973 profilee.py:84(helper2_indirect)
180 8 311.976 38.997 399.912 49.989 profilee.py:88(helper2)
Brett Cannonc17b35c2008-03-01 04:28:23 +0000181 8 63.976 7.997 79.960 9.995 profilee.py:98(subhelper)"""
Benjamin Peterson7d766532008-10-06 22:05:00 +0000182_ProfileOutput['print_callers'] = """\
Christian Heimes2202f872008-02-06 14:31:34 +0000183:0(append) <- profilee.py:73(helper1)(4) 119.964
184:0(exc_info) <- profilee.py:73(helper1)(4) 119.964
Christian Heimes2202f872008-02-06 14:31:34 +0000185:0(hasattr) <- profilee.py:73(helper1)(4) 119.964
186 profilee.py:88(helper2)(8) 399.912
Christian Heimes2202f872008-02-06 14:31:34 +0000187profilee.py:110(__getattr__) <- :0(hasattr)(12) 11.964
188 profilee.py:98(subhelper)(16) 79.960
189profilee.py:25(testfunc) <- <string>:1(<module>)(1) 999.767
190profilee.py:35(factorial) <- profilee.py:25(testfunc)(1) 999.769
191 profilee.py:35(factorial)(20) 169.917
192 profilee.py:84(helper2_indirect)(2) 139.946
193profilee.py:48(mul) <- profilee.py:35(factorial)(20) 169.917
194profilee.py:55(helper) <- profilee.py:25(testfunc)(2) 999.769
195profilee.py:73(helper1) <- profilee.py:55(helper)(4) 599.830
196profilee.py:84(helper2_indirect) <- profilee.py:55(helper)(2) 599.830
197profilee.py:88(helper2) <- profilee.py:55(helper)(6) 599.830
198 profilee.py:84(helper2_indirect)(2) 139.946
Brett Cannonc17b35c2008-03-01 04:28:23 +0000199profilee.py:98(subhelper) <- profilee.py:88(helper2)(8) 399.912"""
Benjamin Peterson7d766532008-10-06 22:05:00 +0000200_ProfileOutput['print_callees'] = """\
Christian Heimes2202f872008-02-06 14:31:34 +0000201:0(hasattr) -> profilee.py:110(__getattr__)(12) 27.972
Christian Heimes2202f872008-02-06 14:31:34 +0000202<string>:1(<module>) -> profilee.py:25(testfunc)(1) 999.769
Christian Heimes2202f872008-02-06 14:31:34 +0000203profilee.py:110(__getattr__) ->
204profilee.py:25(testfunc) -> profilee.py:35(factorial)(1) 169.917
205 profilee.py:55(helper)(2) 599.830
206profilee.py:35(factorial) -> profilee.py:35(factorial)(20) 169.917
207 profilee.py:48(mul)(20) 19.980
208profilee.py:48(mul) ->
209profilee.py:55(helper) -> profilee.py:73(helper1)(4) 119.964
210 profilee.py:84(helper2_indirect)(2) 139.946
211 profilee.py:88(helper2)(6) 399.912
212profilee.py:73(helper1) -> :0(append)(4) -0.004
Christian Heimes2202f872008-02-06 14:31:34 +0000213profilee.py:84(helper2_indirect) -> profilee.py:35(factorial)(2) 169.917
214 profilee.py:88(helper2)(2) 399.912
215profilee.py:88(helper2) -> :0(hasattr)(8) 11.964
216 profilee.py:98(subhelper)(8) 79.960
Brett Cannonc17b35c2008-03-01 04:28:23 +0000217profilee.py:98(subhelper) -> profilee.py:110(__getattr__)(16) 27.972"""
Guido van Rossumf137f752001-10-04 00:58:24 +0000218
219if __name__ == "__main__":
Christian Heimes2202f872008-02-06 14:31:34 +0000220 main()