Fred Drake | de3cdca | 2001-10-12 20:53:59 +0000 | [diff] [blame] | 1 | import hotshot |
| 2 | import hotshot.log |
| 3 | import os |
| 4 | import pprint |
| 5 | import sys |
| 6 | import unittest |
| 7 | import warnings |
| 8 | |
| 9 | import test_support |
| 10 | |
| 11 | from hotshot.log import ENTER, EXIT, LINE |
| 12 | |
| 13 | |
| 14 | def 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 | |
| 24 | class 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) |
Tim Peters | 10603b8 | 2001-10-13 00:19:39 +0000 | [diff] [blame^] | 31 | #XXX os.unlink(self.logfn) |
Fred Drake | de3cdca | 2001-10-12 20:53:59 +0000 | [diff] [blame] | 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 | |
| 76 | def test_main(): |
| 77 | test_support.run_unittest(HotShotTestCase) |
| 78 | |
| 79 | |
| 80 | if __name__ == "__main__": |
| 81 | test_main() |