blob: a9982663175a760cb14752c8c5d5110b3244acc3 [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
Tim Peters527e64f2001-10-04 05:36:56 +000014
Christian Heimes2202f872008-02-06 14:31:34 +000015
16class ProfileTest(unittest.TestCase):
17
18 profilerclass = profile.Profile
Giampaolo Rodola'b071d4f2013-02-12 14:31:06 +010019 profilermodule = profile
Christian Heimes2202f872008-02-06 14:31:34 +000020 methodnames = ['print_stats', 'print_callers', 'print_callees']
Antoine Pitrou8e124f32009-05-30 21:41:10 +000021 expected_max_output = ':0(max)'
Benjamin Peterson7d766532008-10-06 22:05:00 +000022
Giampaolo Rodola'b071d4f2013-02-12 14:31:06 +010023 def tearDown(self):
24 unlink(TESTFN)
25
Benjamin Peterson7d766532008-10-06 22:05:00 +000026 def get_expected_output(self):
27 return _ProfileOutput
Christian Heimes2202f872008-02-06 14:31:34 +000028
29 @classmethod
30 def do_profiling(cls):
31 results = []
32 prof = cls.profilerclass(timer, 0.001)
Christian Heimesdae2a892008-04-19 00:55:37 +000033 start_timer = timer()
Christian Heimes2202f872008-02-06 14:31:34 +000034 prof.runctx("testfunc()", globals(), locals())
Christian Heimesdae2a892008-04-19 00:55:37 +000035 results.append(timer() - start_timer)
Christian Heimes2202f872008-02-06 14:31:34 +000036 for methodname in cls.methodnames:
37 s = StringIO()
38 stats = pstats.Stats(prof, stream=s)
39 stats.strip_dirs().sort_stats("stdname")
40 getattr(stats, methodname)()
Brett Cannonc17b35c2008-03-01 04:28:23 +000041 output = s.getvalue().splitlines()
42 mod_name = testfunc.__module__.rsplit('.', 1)[1]
43 # Only compare against stats originating from the test file.
44 # Prevents outside code (e.g., the io module) from causing
45 # unexpected output.
46 output = [line.rstrip() for line in output if mod_name in line]
47 results.append('\n'.join(output))
Christian Heimes2202f872008-02-06 14:31:34 +000048 return results
49
50 def test_cprofile(self):
51 results = self.do_profiling()
Benjamin Peterson7d766532008-10-06 22:05:00 +000052 expected = self.get_expected_output()
Christian Heimesdae2a892008-04-19 00:55:37 +000053 self.assertEqual(results[0], 1000)
jdemeyerac9240b2018-05-09 06:16:35 +020054 fail = []
Christian Heimes2202f872008-02-06 14:31:34 +000055 for i, method in enumerate(self.methodnames):
jdemeyerac9240b2018-05-09 06:16:35 +020056 a = expected[method]
57 b = results[i+1]
58 if a != b:
59 fail.append(f"\nStats.{method} output for "
60 f"{self.profilerclass.__name__} "
61 "does not fit expectation:")
62 fail.extend(unified_diff(a.split('\n'), b.split('\n'),
63 lineterm=""))
64 if fail:
65 self.fail("\n".join(fail))
Christian Heimes2202f872008-02-06 14:31:34 +000066
Antoine Pitrou8e124f32009-05-30 21:41:10 +000067 def test_calling_conventions(self):
68 # Issue #5330: profile and cProfile wouldn't report C functions called
69 # with keyword arguments. We test all calling conventions.
70 stmts = [
71 "max([0])",
72 "max([0], key=int)",
73 "max([0], **dict(key=int))",
74 "max(*([0],))",
75 "max(*([0],), key=int)",
76 "max(*([0],), **dict(key=int))",
77 ]
78 for stmt in stmts:
79 s = StringIO()
80 prof = self.profilerclass(timer, 0.001)
81 prof.runctx(stmt, globals(), locals())
82 stats = pstats.Stats(prof, stream=s)
83 stats.print_stats()
84 res = s.getvalue()
Ezio Melottib58e0bd2010-01-23 15:40:09 +000085 self.assertIn(self.expected_max_output, res,
Antoine Pitrou8e124f32009-05-30 21:41:10 +000086 "Profiling {0!r} didn't report max:\n{1}".format(stmt, res))
87
Giampaolo Rodola'b071d4f2013-02-12 14:31:06 +010088 def test_run(self):
89 with silent():
Giampaolo Rodola'58cf4532013-02-12 15:23:21 +010090 self.profilermodule.run("int('1')")
91 self.profilermodule.run("int('1')", filename=TESTFN)
Giampaolo Rodola'b071d4f2013-02-12 14:31:06 +010092 self.assertTrue(os.path.exists(TESTFN))
93
94 def test_runctx(self):
95 with silent():
96 self.profilermodule.runctx("testfunc()", globals(), locals())
97 self.profilermodule.runctx("testfunc()", globals(), locals(),
98 filename=TESTFN)
99 self.assertTrue(os.path.exists(TESTFN))
100
Christian Heimes2202f872008-02-06 14:31:34 +0000101
102def regenerate_expected_output(filename, cls):
103 filename = filename.rstrip('co')
104 print('Regenerating %s...' % filename)
105 results = cls.do_profiling()
106
107 newfile = []
108 with open(filename, 'r') as f:
109 for line in f:
110 newfile.append(line)
Brett Cannonc17b35c2008-03-01 04:28:23 +0000111 if line.startswith('#--cut'):
Christian Heimes2202f872008-02-06 14:31:34 +0000112 break
113
114 with open(filename, 'w') as f:
115 f.writelines(newfile)
Benjamin Peterson7d766532008-10-06 22:05:00 +0000116 f.write("_ProfileOutput = {}\n")
Christian Heimes2202f872008-02-06 14:31:34 +0000117 for i, method in enumerate(cls.methodnames):
Benjamin Peterson7d766532008-10-06 22:05:00 +0000118 f.write('_ProfileOutput[%r] = """\\\n%s"""\n' % (
119 method, results[i+1]))
Christian Heimes2202f872008-02-06 14:31:34 +0000120 f.write('\nif __name__ == "__main__":\n main()\n')
121
Giampaolo Rodola'b071d4f2013-02-12 14:31:06 +0100122@contextmanager
123def silent():
124 stdout = sys.stdout
125 try:
126 sys.stdout = StringIO()
127 yield
128 finally:
129 sys.stdout = stdout
Armin Rigoa871ef22006-02-08 12:53:56 +0000130
131def test_main():
Christian Heimes2202f872008-02-06 14:31:34 +0000132 run_unittest(ProfileTest)
Guido van Rossumf137f752001-10-04 00:58:24 +0000133
Christian Heimes2202f872008-02-06 14:31:34 +0000134def main():
135 if '-r' not in sys.argv:
136 test_main()
Armin Rigoa871ef22006-02-08 12:53:56 +0000137 else:
Christian Heimes2202f872008-02-06 14:31:34 +0000138 regenerate_expected_output(__file__, ProfileTest)
Armin Rigoa871ef22006-02-08 12:53:56 +0000139
Guido van Rossumf137f752001-10-04 00:58:24 +0000140
Christian Heimes2202f872008-02-06 14:31:34 +0000141# Don't remove this comment. Everything below it is auto-generated.
142#--cut--------------------------------------------------------------------------
Benjamin Peterson7d766532008-10-06 22:05:00 +0000143_ProfileOutput = {}
144_ProfileOutput['print_stats'] = """\
Christian Heimes2202f872008-02-06 14:31:34 +0000145 28 27.972 0.999 27.972 0.999 profilee.py:110(__getattr__)
146 1 269.996 269.996 999.769 999.769 profilee.py:25(testfunc)
147 23/3 149.937 6.519 169.917 56.639 profilee.py:35(factorial)
148 20 19.980 0.999 19.980 0.999 profilee.py:48(mul)
149 2 39.986 19.993 599.830 299.915 profilee.py:55(helper)
150 4 115.984 28.996 119.964 29.991 profilee.py:73(helper1)
151 2 -0.006 -0.003 139.946 69.973 profilee.py:84(helper2_indirect)
152 8 311.976 38.997 399.912 49.989 profilee.py:88(helper2)
Brett Cannonc17b35c2008-03-01 04:28:23 +0000153 8 63.976 7.997 79.960 9.995 profilee.py:98(subhelper)"""
Benjamin Peterson7d766532008-10-06 22:05:00 +0000154_ProfileOutput['print_callers'] = """\
Christian Heimes2202f872008-02-06 14:31:34 +0000155:0(append) <- profilee.py:73(helper1)(4) 119.964
156:0(exc_info) <- profilee.py:73(helper1)(4) 119.964
Christian Heimes2202f872008-02-06 14:31:34 +0000157:0(hasattr) <- profilee.py:73(helper1)(4) 119.964
158 profilee.py:88(helper2)(8) 399.912
Christian Heimes2202f872008-02-06 14:31:34 +0000159profilee.py:110(__getattr__) <- :0(hasattr)(12) 11.964
160 profilee.py:98(subhelper)(16) 79.960
161profilee.py:25(testfunc) <- <string>:1(<module>)(1) 999.767
162profilee.py:35(factorial) <- profilee.py:25(testfunc)(1) 999.769
163 profilee.py:35(factorial)(20) 169.917
164 profilee.py:84(helper2_indirect)(2) 139.946
165profilee.py:48(mul) <- profilee.py:35(factorial)(20) 169.917
166profilee.py:55(helper) <- profilee.py:25(testfunc)(2) 999.769
167profilee.py:73(helper1) <- profilee.py:55(helper)(4) 599.830
168profilee.py:84(helper2_indirect) <- profilee.py:55(helper)(2) 599.830
169profilee.py:88(helper2) <- profilee.py:55(helper)(6) 599.830
170 profilee.py:84(helper2_indirect)(2) 139.946
Brett Cannonc17b35c2008-03-01 04:28:23 +0000171profilee.py:98(subhelper) <- profilee.py:88(helper2)(8) 399.912"""
Benjamin Peterson7d766532008-10-06 22:05:00 +0000172_ProfileOutput['print_callees'] = """\
Christian Heimes2202f872008-02-06 14:31:34 +0000173:0(hasattr) -> profilee.py:110(__getattr__)(12) 27.972
Christian Heimes2202f872008-02-06 14:31:34 +0000174<string>:1(<module>) -> profilee.py:25(testfunc)(1) 999.769
Christian Heimes2202f872008-02-06 14:31:34 +0000175profilee.py:110(__getattr__) ->
176profilee.py:25(testfunc) -> profilee.py:35(factorial)(1) 169.917
177 profilee.py:55(helper)(2) 599.830
178profilee.py:35(factorial) -> profilee.py:35(factorial)(20) 169.917
179 profilee.py:48(mul)(20) 19.980
180profilee.py:48(mul) ->
181profilee.py:55(helper) -> profilee.py:73(helper1)(4) 119.964
182 profilee.py:84(helper2_indirect)(2) 139.946
183 profilee.py:88(helper2)(6) 399.912
184profilee.py:73(helper1) -> :0(append)(4) -0.004
Christian Heimes2202f872008-02-06 14:31:34 +0000185profilee.py:84(helper2_indirect) -> profilee.py:35(factorial)(2) 169.917
186 profilee.py:88(helper2)(2) 399.912
187profilee.py:88(helper2) -> :0(hasattr)(8) 11.964
188 profilee.py:98(subhelper)(8) 79.960
Brett Cannonc17b35c2008-03-01 04:28:23 +0000189profilee.py:98(subhelper) -> profilee.py:110(__getattr__)(16) 27.972"""
Guido van Rossumf137f752001-10-04 00:58:24 +0000190
191if __name__ == "__main__":
Christian Heimes2202f872008-02-06 14:31:34 +0000192 main()