blob: d406290d1c84f45f1b328e0f46d4f92770ea094d [file] [log] [blame]
Fred Drakede3cdca2001-10-12 20:53:59 +00001import hotshot
2import hotshot.log
3import os
4import pprint
5import sys
6import unittest
7import warnings
8
9import test_support
10
11from hotshot.log import ENTER, EXIT, LINE
12
13
14def shortfilename(fn):
15 # We use a really shortened filename since an exact match is made,
16 # and the source may be either a Python source file or a
17 # pre-compiled bytecode file.
18 if fn:
19 return os.path.splitext(os.path.basename(fn))[0]
20 else:
21 return fn
22
23
24class HotShotTestCase(unittest.TestCase):
25 def new_profiler(self, lineevents=0, linetimings=1):
26 self.logfn = test_support.TESTFN
27 return hotshot.Profile(self.logfn, lineevents, linetimings)
28
29 def get_logreader(self):
30 log = hotshot.log.LogReader(self.logfn)
31 os.unlink(self.logfn)
32 return log
33
34 def get_events_wotime(self):
35 L = []
36 for event in self.get_logreader():
37 what, (filename, lineno, funcname), tdelta = event
38 L.append((what, (shortfilename(filename), lineno, funcname)))
39 return L
40
41 def check_events(self, expected):
42 events = self.get_events_wotime()
43 if events != expected:
44 self.fail(
45 "events did not match expectation; got:\n%s\nexpected:\n%s"
46 % (pprint.pformat(events), pprint.pformat(expected)))
47
48 def run_test(self, callable, events, profiler=None):
49 if profiler is None:
50 profiler = self.new_profiler()
51 profiler.runcall(callable)
52 profiler.close()
53 self.check_events(events)
54
55 def test_line_numbers(self):
56 def f():
57 y = 2
58 x = 1
59 def g():
60 f()
61 f_lineno = f.func_code.co_firstlineno
62 g_lineno = g.func_code.co_firstlineno
63 events = [(ENTER, ("test_hotshot", g_lineno, "g")),
64 (LINE, ("test_hotshot", g_lineno, "g")),
65 (LINE, ("test_hotshot", g_lineno+1, "g")),
66 (ENTER, ("test_hotshot", f_lineno, "f")),
67 (LINE, ("test_hotshot", f_lineno, "f")),
68 (LINE, ("test_hotshot", f_lineno+1, "f")),
69 (LINE, ("test_hotshot", f_lineno+2, "f")),
70 (EXIT, ("test_hotshot", f_lineno, "f")),
71 (EXIT, ("test_hotshot", g_lineno, "g")),
72 ]
73 self.run_test(g, events, self.new_profiler(lineevents=1))
74
75
76def test_main():
77 test_support.run_unittest(HotShotTestCase)
78
79
80if __name__ == "__main__":
81 test_main()