9 from hotshot
.log
import ENTER
, EXIT
, LINE
12 def shortfilename(fn
):
13 # We use a really shortened filename since an exact match is made,
14 # and the source may be either a Python source file or a
15 # pre-compiled bytecode file.
17 return os
.path
.splitext(os
.path
.basename(fn
))[0]
22 class UnlinkingLogReader(hotshot
.log
.LogReader
):
23 """Extend the LogReader so the log file is unlinked when we're
26 def __init__(self
, logfn
):
28 hotshot
.log
.LogReader
.__init
__(self
, logfn
)
30 def next(self
, index
=None):
32 return hotshot
.log
.LogReader
.next(self
)
33 except (IndexError, StopIteration):
34 os
.unlink(self
.__logfn
)
38 class HotShotTestCase(unittest
.TestCase
):
39 def new_profiler(self
, lineevents
=0, linetimings
=1):
40 self
.logfn
= test_support
.TESTFN
41 return hotshot
.Profile(self
.logfn
, lineevents
, linetimings
)
43 def get_logreader(self
):
44 return UnlinkingLogReader(self
.logfn
)
46 def get_events_wotime(self
):
48 for event
in self
.get_logreader():
49 what
, (filename
, lineno
, funcname
), tdelta
= event
50 L
.append((what
, (shortfilename(filename
), lineno
, funcname
)))
53 def check_events(self
, expected
):
54 events
= self
.get_events_wotime()
56 # Running under -O, so we don't get LINE events
57 expected
= [ev
for ev
in expected
if ev
[0] != LINE
]
58 if events
!= expected
:
60 "events did not match expectation; got:\n%s\nexpected:\n%s"
61 % (pprint
.pformat(events
), pprint
.pformat(expected
)))
63 def run_test(self
, callable, events
, profiler
=None):
65 profiler
= self
.new_profiler()
66 profiler
.runcall(callable)
68 self
.check_events(events
)
70 def test_addinfo(self
):
72 p
.addinfo("test-key", "test-value")
73 profiler
= self
.new_profiler()
74 profiler
.runcall(f
, profiler
)
76 log
= self
.get_logreader()
79 self
.failUnless(info
["test-key"] == ["test-value"])
81 def test_line_numbers(self
):
87 f_lineno
= f
.func_code
.co_firstlineno
88 g_lineno
= g
.func_code
.co_firstlineno
89 events
= [(ENTER
, ("test_hotshot", g_lineno
, "g")),
90 (LINE
, ("test_hotshot", g_lineno
, "g")),
91 (LINE
, ("test_hotshot", g_lineno
+1, "g")),
92 (ENTER
, ("test_hotshot", f_lineno
, "f")),
93 (LINE
, ("test_hotshot", f_lineno
, "f")),
94 (LINE
, ("test_hotshot", f_lineno
+1, "f")),
95 (LINE
, ("test_hotshot", f_lineno
+2, "f")),
96 (EXIT
, ("test_hotshot", f_lineno
, "f")),
97 (EXIT
, ("test_hotshot", g_lineno
, "g")),
99 self
.run_test(g
, events
, self
.new_profiler(lineevents
=1))
101 def test_start_stop(self
):
102 # Make sure we don't return NULL in the start() and stop()
103 # methods when there isn't an error. Bug in 2.2 noted by
105 profiler
= self
.new_profiler()
109 os
.unlink(self
.logfn
)
113 test_support
.run_unittest(HotShotTestCase
)
116 if __name__
== "__main__":