blob: 8be4f240841448ada4802ca6f57ca45428b37e1e [file] [log] [blame]
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +00001#!/usr/bin/env python
2
3# portions copyright 2001, Autonomous Zones Industries, Inc., all rights...
4# err... reserved and offered to the public under the terms of the
5# Python 2.2 license.
6# Author: Zooko O'Whielacronx
7# http://zooko.com/
8# mailto:zooko@zooko.com
9#
10# Copyright 2000, Mojam Media, Inc., all rights reserved.
11# Author: Skip Montanaro
12#
13# Copyright 1999, Bioreason, Inc., all rights reserved.
14# Author: Andrew Dalke
15#
16# Copyright 1995-1997, Automatrix, Inc., all rights reserved.
17# Author: Skip Montanaro
18#
19# Copyright 1991-1995, Stichting Mathematisch Centrum, all rights reserved.
20#
21#
22# Permission to use, copy, modify, and distribute this Python software and
23# its associated documentation for any purpose without fee is hereby
24# granted, provided that the above copyright notice appears in all copies,
25# and that both that copyright notice and this permission notice appear in
26# supporting documentation, and that the name of neither Automatrix,
27# Bioreason or Mojam Media be used in advertising or publicity pertaining to
28# distribution of the software without specific, written prior permission.
29#
30"""program/module to trace Python program or function execution
31
32Sample use, command line:
33 trace.py -c -f counts --ignore-dir '$prefix' spam.py eggs
34 trace.py -t --ignore-dir '$prefix' spam.py eggs
35
36Sample use, programmatically
37 # create a Trace object, telling it what to ignore, and whether to
38 # do tracing or line-counting or both.
39 trace = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,], trace=0,
40 count=1)
41 # run the new command using the given trace
42 trace.run(coverage.globaltrace, 'main()')
43 # make a report, telling it where you want output
44 r = trace.results()
Jeremy Hylton38732e12003-04-21 22:04:46 +000045 r.write_results(show_missing=True)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +000046"""
47
Jeremy Hylton38732e12003-04-21 22:04:46 +000048import linecache
Jeremy Hylton38732e12003-04-21 22:04:46 +000049import os
50import re
51import sys
Jeremy Hylton546e34b2003-06-26 14:56:17 +000052import threading
Jeremy Hylton38732e12003-04-21 22:04:46 +000053import token
54import tokenize
55import types
56
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +000057try:
58 import cPickle
59 pickle = cPickle
60except ImportError:
61 import pickle
62
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +000063def usage(outfile):
64 outfile.write("""Usage: %s [OPTIONS] <file> [ARGS]
65
66Meta-options:
67--help Display this help then exit.
68--version Output version information then exit.
69
70Otherwise, exactly one of the following three options must be given:
71-t, --trace Print each line to sys.stdout before it is executed.
72-c, --count Count the number of times each line is executed
73 and write the counts to <module>.cover for each
74 module executed, in the module's directory.
75 See also `--coverdir', `--file', `--no-report' below.
Skip Montanaroa7b8ac62003-06-27 19:09:33 +000076-l, --listfuncs Keep track of which functions are executed at least
Fred Drake01c623b2003-06-27 19:22:11 +000077 once and write the results to sys.stdout after the
Skip Montanaroa7b8ac62003-06-27 19:09:33 +000078 program exits.
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +000079-r, --report Generate a report from a counts file; do not execute
80 any code. `--file' must specify the results file to
81 read, which must have been created in a previous run
82 with `--count --file=FILE'.
83
84Modifiers:
85-f, --file=<file> File to accumulate counts over several runs.
86-R, --no-report Do not generate the coverage report files.
87 Useful if you want to accumulate over several runs.
88-C, --coverdir=<dir> Directory where the report files. The coverage
89 report for <package>.<module> is written to file
90 <dir>/<package>/<module>.cover.
91-m, --missing Annotate executable lines that were not executed
92 with '>>>>>> '.
93-s, --summary Write a brief summary on stdout for each file.
94 (Can only be used with --count or --report.)
95
96Filters, may be repeated multiple times:
97--ignore-module=<mod> Ignore the given module and its submodules
98 (if it is a package).
99--ignore-dir=<dir> Ignore files in the given directory (multiple
100 directories can be joined by os.pathsep).
101""" % sys.argv[0])
102
Jeremy Hylton38732e12003-04-21 22:04:46 +0000103PRAGMA_NOCOVER = "#pragma NO COVER"
104
105# Simple rx to find lines with no code.
106rx_blank = re.compile(r'^\s*(#.*)?$')
107
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000108class Ignore:
109 def __init__(self, modules = None, dirs = None):
110 self._mods = modules or []
111 self._dirs = dirs or []
112
113 self._dirs = map(os.path.normpath, self._dirs)
114 self._ignore = { '<string>': 1 }
115
116 def names(self, filename, modulename):
117 if self._ignore.has_key(modulename):
118 return self._ignore[modulename]
119
120 # haven't seen this one before, so see if the module name is
121 # on the ignore list. Need to take some care since ignoring
122 # "cmp" musn't mean ignoring "cmpcache" but ignoring
123 # "Spam" must also mean ignoring "Spam.Eggs".
124 for mod in self._mods:
125 if mod == modulename: # Identical names, so ignore
126 self._ignore[modulename] = 1
127 return 1
128 # check if the module is a proper submodule of something on
129 # the ignore list
130 n = len(mod)
131 # (will not overflow since if the first n characters are the
132 # same and the name has not already occured, then the size
133 # of "name" is greater than that of "mod")
134 if mod == modulename[:n] and modulename[n] == '.':
135 self._ignore[modulename] = 1
136 return 1
137
138 # Now check that __file__ isn't in one of the directories
139 if filename is None:
140 # must be a built-in, so we must ignore
141 self._ignore[modulename] = 1
142 return 1
143
144 # Ignore a file when it contains one of the ignorable paths
145 for d in self._dirs:
146 # The '+ os.sep' is to ensure that d is a parent directory,
147 # as compared to cases like:
148 # d = "/usr/local"
149 # filename = "/usr/local.py"
150 # or
151 # d = "/usr/local.py"
152 # filename = "/usr/local.py"
153 if filename.startswith(d + os.sep):
154 self._ignore[modulename] = 1
155 return 1
156
157 # Tried the different ways, so we don't ignore this module
158 self._ignore[modulename] = 0
159 return 0
160
Jeremy Hylton38732e12003-04-21 22:04:46 +0000161def modname(path):
162 """Return a plausible module name for the patch."""
Jeremy Hyltondfbfe732003-04-21 22:49:17 +0000163
Jeremy Hylton38732e12003-04-21 22:04:46 +0000164 base = os.path.basename(path)
165 filename, ext = os.path.splitext(base)
166 return filename
167
Jeremy Hyltondfbfe732003-04-21 22:49:17 +0000168def fullmodname(path):
Jeremy Hyltonc8c8b942003-04-22 15:35:51 +0000169 """Return a plausible module name for the path."""
Jeremy Hyltondfbfe732003-04-21 22:49:17 +0000170
171 # If the file 'path' is part of a package, then the filename isn't
172 # enough to uniquely identify it. Try to do the right thing by
173 # looking in sys.path for the longest matching prefix. We'll
174 # assume that the rest is the package name.
175
176 longest = ""
177 for dir in sys.path:
178 if path.startswith(dir) and path[len(dir)] == os.path.sep:
179 if len(dir) > len(longest):
180 longest = dir
181
Guido van Rossumb427c002003-10-10 23:02:01 +0000182 if longest:
183 base = path[len(longest) + 1:]
184 else:
185 base = path
Guido van Rossumbbca8da2004-02-19 19:16:50 +0000186 base = base.replace(os.sep, ".")
187 if os.altsep:
188 base = base.replace(os.altsep, ".")
Jeremy Hyltondfbfe732003-04-21 22:49:17 +0000189 filename, ext = os.path.splitext(base)
190 return filename
191
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000192class CoverageResults:
193 def __init__(self, counts=None, calledfuncs=None, infile=None,
Tim Petersf2715e02003-02-19 02:35:07 +0000194 outfile=None):
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000195 self.counts = counts
196 if self.counts is None:
197 self.counts = {}
198 self.counter = self.counts.copy() # map (filename, lineno) to count
199 self.calledfuncs = calledfuncs
200 if self.calledfuncs is None:
201 self.calledfuncs = {}
202 self.calledfuncs = self.calledfuncs.copy()
203 self.infile = infile
204 self.outfile = outfile
205 if self.infile:
Jeremy Hyltond7ce86d2003-07-07 16:08:47 +0000206 # Try to merge existing counts file.
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000207 try:
Jeremy Hyltond0e27052003-10-14 20:12:06 +0000208 counts, calledfuncs = pickle.load(open(self.infile, 'rb'))
Jeremy Hyltond7ce86d2003-07-07 16:08:47 +0000209 self.update(self.__class__(counts, calledfuncs))
210 except (IOError, EOFError, ValueError), err:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000211 print >> sys.stderr, ("Skipping counts file %r: %s"
212 % (self.infile, err))
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000213
214 def update(self, other):
215 """Merge in the data from another CoverageResults"""
216 counts = self.counts
217 calledfuncs = self.calledfuncs
218 other_counts = other.counts
219 other_calledfuncs = other.calledfuncs
220
221 for key in other_counts.keys():
Jeremy Hylton38732e12003-04-21 22:04:46 +0000222 counts[key] = counts.get(key, 0) + other_counts[key]
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000223
224 for key in other_calledfuncs.keys():
225 calledfuncs[key] = 1
226
Jeremy Hylton38732e12003-04-21 22:04:46 +0000227 def write_results(self, show_missing=True, summary=False, coverdir=None):
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000228 """
229 @param coverdir
230 """
231 for filename, modulename, funcname in self.calledfuncs.keys():
232 print ("filename: %s, modulename: %s, funcname: %s"
233 % (filename, modulename, funcname))
234
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000235 # turn the counts data ("(filename, lineno) = count") into something
236 # accessible on a per-file basis
237 per_file = {}
Jeremy Hylton38732e12003-04-21 22:04:46 +0000238 for filename, lineno in self.counts.keys():
239 lines_hit = per_file[filename] = per_file.get(filename, {})
240 lines_hit[lineno] = self.counts[(filename, lineno)]
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000241
242 # accumulate summary info, if needed
243 sums = {}
244
Jeremy Hylton38732e12003-04-21 22:04:46 +0000245 for filename, count in per_file.iteritems():
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000246 # skip some "files" we don't care about...
247 if filename == "<string>":
248 continue
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000249
250 if filename.endswith(".pyc") or filename.endswith(".pyo"):
251 filename = filename[:-1]
252
Jeremy Hylton38732e12003-04-21 22:04:46 +0000253 if coverdir is None:
254 dir = os.path.dirname(os.path.abspath(filename))
Jeremy Hyltonc8c8b942003-04-22 15:35:51 +0000255 modulename = modname(filename)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000256 else:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000257 dir = coverdir
258 if not os.path.exists(dir):
259 os.makedirs(dir)
Jeremy Hyltonc8c8b942003-04-22 15:35:51 +0000260 modulename = fullmodname(filename)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000261
262 # If desired, get a list of the line numbers which represent
263 # executable content (returned as a dict for better lookup speed)
264 if show_missing:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000265 lnotab = find_executable_linenos(filename)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000266 else:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000267 lnotab = {}
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000268
Jeremy Hylton38732e12003-04-21 22:04:46 +0000269 source = linecache.getlines(filename)
270 coverpath = os.path.join(dir, modulename + ".cover")
271 n_hits, n_lines = self.write_results_file(coverpath, source,
272 lnotab, count)
Tim Peters0eadaac2003-04-24 16:02:54 +0000273
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000274 if summary and n_lines:
275 percent = int(100 * n_hits / n_lines)
276 sums[modulename] = n_lines, percent, modulename, filename
277
278 if summary and sums:
279 mods = sums.keys()
280 mods.sort()
281 print "lines cov% module (path)"
282 for m in mods:
283 n_lines, percent, modulename, filename = sums[m]
284 print "%5d %3d%% %s (%s)" % sums[m]
285
286 if self.outfile:
287 # try and store counts and module info into self.outfile
288 try:
289 pickle.dump((self.counts, self.calledfuncs),
Jeremy Hyltond0e27052003-10-14 20:12:06 +0000290 open(self.outfile, 'wb'), 1)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000291 except IOError, err:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000292 print >> sys.stderr, "Can't save counts files because %s" % err
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000293
Jeremy Hylton38732e12003-04-21 22:04:46 +0000294 def write_results_file(self, path, lines, lnotab, lines_hit):
295 """Return a coverage results file in path."""
296
297 try:
298 outfile = open(path, "w")
299 except IOError, err:
300 print >> sys.stderr, ("trace: Could not open %r for writing: %s"
301 "- skipping" % (path, err))
Guido van Rossumbbca8da2004-02-19 19:16:50 +0000302 return 0, 0
Jeremy Hylton38732e12003-04-21 22:04:46 +0000303
304 n_lines = 0
305 n_hits = 0
306 for i, line in enumerate(lines):
307 lineno = i + 1
308 # do the blank/comment match to try to mark more lines
309 # (help the reader find stuff that hasn't been covered)
310 if lineno in lines_hit:
311 outfile.write("%5d: " % lines_hit[lineno])
312 n_hits += 1
313 n_lines += 1
314 elif rx_blank.match(line):
Walter Dörwaldc1711722003-07-15 10:34:02 +0000315 outfile.write(" ")
Jeremy Hylton38732e12003-04-21 22:04:46 +0000316 else:
317 # lines preceded by no marks weren't hit
318 # Highlight them if so indicated, unless the line contains
319 # #pragma: NO COVER
320 if lineno in lnotab and not PRAGMA_NOCOVER in lines[i]:
321 outfile.write(">>>>>> ")
Jeremy Hylton546e34b2003-06-26 14:56:17 +0000322 n_lines += 1
Jeremy Hylton38732e12003-04-21 22:04:46 +0000323 else:
324 outfile.write(" ")
Jeremy Hylton38732e12003-04-21 22:04:46 +0000325 outfile.write(lines[i].expandtabs(8))
326 outfile.close()
327
328 return n_hits, n_lines
329
330def find_lines_from_code(code, strs):
331 """Return dict where keys are lines in the line number table."""
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000332 linenos = {}
333
334 line_increments = [ord(c) for c in code.co_lnotab[1::2]]
335 table_length = len(line_increments)
Jeremy Hylton38732e12003-04-21 22:04:46 +0000336 docstring = False
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000337
338 lineno = code.co_firstlineno
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000339 for li in line_increments:
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000340 lineno += li
Jeremy Hylton38732e12003-04-21 22:04:46 +0000341 if lineno not in strs:
342 linenos[lineno] = 1
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000343
344 return linenos
345
Jeremy Hylton38732e12003-04-21 22:04:46 +0000346def find_lines(code, strs):
347 """Return lineno dict for all code objects reachable from code."""
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000348 # get all of the lineno information from the code of this scope level
Jeremy Hylton38732e12003-04-21 22:04:46 +0000349 linenos = find_lines_from_code(code, strs)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000350
351 # and check the constants for references to other code objects
352 for c in code.co_consts:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000353 if isinstance(c, types.CodeType):
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000354 # find another code object, so recurse into it
Jeremy Hylton38732e12003-04-21 22:04:46 +0000355 linenos.update(find_lines(c, strs))
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000356 return linenos
357
Jeremy Hylton38732e12003-04-21 22:04:46 +0000358def find_strings(filename):
359 """Return a dict of possible docstring positions.
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000360
Jeremy Hylton38732e12003-04-21 22:04:46 +0000361 The dict maps line numbers to strings. There is an entry for
362 line that contains only a string or a part of a triple-quoted
363 string.
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000364 """
Jeremy Hylton38732e12003-04-21 22:04:46 +0000365 d = {}
366 # If the first token is a string, then it's the module docstring.
367 # Add this special case so that the test in the loop passes.
368 prev_ttype = token.INDENT
369 f = open(filename)
370 for ttype, tstr, start, end, line in tokenize.generate_tokens(f.readline):
371 if ttype == token.STRING:
372 if prev_ttype == token.INDENT:
373 sline, scol = start
374 eline, ecol = end
375 for i in range(sline, eline + 1):
376 d[i] = 1
377 prev_ttype = ttype
378 f.close()
379 return d
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000380
Jeremy Hylton38732e12003-04-21 22:04:46 +0000381def find_executable_linenos(filename):
382 """Return dict where keys are line numbers in the line number table."""
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000383 assert filename.endswith('.py')
Jeremy Hylton38732e12003-04-21 22:04:46 +0000384 try:
385 prog = open(filename).read()
386 except IOError, err:
387 print >> sys.stderr, ("Not printing coverage data for %r: %s"
388 % (filename, err))
389 return {}
390 code = compile(prog, filename, "exec")
391 strs = find_strings(filename)
392 return find_lines(code, strs)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000393
394class Trace:
395 def __init__(self, count=1, trace=1, countfuncs=0, ignoremods=(),
396 ignoredirs=(), infile=None, outfile=None):
397 """
398 @param count true iff it should count number of times each
Tim Petersf2715e02003-02-19 02:35:07 +0000399 line is executed
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000400 @param trace true iff it should print out each line that is
Tim Petersf2715e02003-02-19 02:35:07 +0000401 being counted
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000402 @param countfuncs true iff it should just output a list of
403 (filename, modulename, funcname,) for functions
404 that were called at least once; This overrides
Tim Petersf2715e02003-02-19 02:35:07 +0000405 `count' and `trace'
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000406 @param ignoremods a list of the names of modules to ignore
407 @param ignoredirs a list of the names of directories to ignore
Tim Petersf2715e02003-02-19 02:35:07 +0000408 all of the (recursive) contents of
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000409 @param infile file from which to read stored counts to be
Tim Petersf2715e02003-02-19 02:35:07 +0000410 added into the results
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000411 @param outfile file in which to write the results
412 """
413 self.infile = infile
414 self.outfile = outfile
415 self.ignore = Ignore(ignoremods, ignoredirs)
416 self.counts = {} # keys are (filename, linenumber)
417 self.blabbed = {} # for debugging
418 self.pathtobasename = {} # for memoizing os.path.basename
419 self.donothing = 0
420 self.trace = trace
421 self._calledfuncs = {}
422 if countfuncs:
423 self.globaltrace = self.globaltrace_countfuncs
424 elif trace and count:
425 self.globaltrace = self.globaltrace_lt
426 self.localtrace = self.localtrace_trace_and_count
427 elif trace:
428 self.globaltrace = self.globaltrace_lt
429 self.localtrace = self.localtrace_trace
430 elif count:
431 self.globaltrace = self.globaltrace_lt
432 self.localtrace = self.localtrace_count
433 else:
434 # Ahem -- do nothing? Okay.
435 self.donothing = 1
436
437 def run(self, cmd):
438 import __main__
439 dict = __main__.__dict__
440 if not self.donothing:
441 sys.settrace(self.globaltrace)
Jeremy Hylton546e34b2003-06-26 14:56:17 +0000442 threading.settrace(self.globaltrace)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000443 try:
444 exec cmd in dict, dict
445 finally:
446 if not self.donothing:
447 sys.settrace(None)
Jeremy Hylton546e34b2003-06-26 14:56:17 +0000448 threading.settrace(None)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000449
450 def runctx(self, cmd, globals=None, locals=None):
451 if globals is None: globals = {}
452 if locals is None: locals = {}
453 if not self.donothing:
454 sys.settrace(self.globaltrace)
Jeremy Hylton546e34b2003-06-26 14:56:17 +0000455 threading.settrace(self.globaltrace)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000456 try:
457 exec cmd in globals, locals
458 finally:
459 if not self.donothing:
460 sys.settrace(None)
Jeremy Hylton546e34b2003-06-26 14:56:17 +0000461 threading.settrace(None)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000462
463 def runfunc(self, func, *args, **kw):
464 result = None
465 if not self.donothing:
466 sys.settrace(self.globaltrace)
467 try:
Guido van Rossum68468eb2003-02-27 20:14:51 +0000468 result = func(*args, **kw)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000469 finally:
470 if not self.donothing:
471 sys.settrace(None)
472 return result
473
474 def globaltrace_countfuncs(self, frame, why, arg):
Jeremy Hylton38732e12003-04-21 22:04:46 +0000475 """Handler for call events.
Tim Peters0eadaac2003-04-24 16:02:54 +0000476
Jeremy Hylton38732e12003-04-21 22:04:46 +0000477 Adds (filename, modulename, funcname) to the self._calledfuncs dict.
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000478 """
479 if why == 'call':
Jeremy Hylton38732e12003-04-21 22:04:46 +0000480 code = frame.f_code
481 filename = code.co_filename
482 funcname = code.co_name
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000483 if filename:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000484 modulename = modname(filename)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000485 else:
486 modulename = None
Jeremy Hylton38732e12003-04-21 22:04:46 +0000487 self._calledfuncs[(filename, modulename, funcname)] = 1
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000488
489 def globaltrace_lt(self, frame, why, arg):
Jeremy Hylton38732e12003-04-21 22:04:46 +0000490 """Handler for call events.
491
492 If the code block being entered is to be ignored, returns `None',
493 else returns self.localtrace.
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000494 """
495 if why == 'call':
Jeremy Hylton38732e12003-04-21 22:04:46 +0000496 code = frame.f_code
497 filename = code.co_filename
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000498 if filename:
Jeremy Hyltondfbfe732003-04-21 22:49:17 +0000499 # XXX modname() doesn't work right for packages, so
500 # the ignore support won't work right for packages
Jeremy Hylton38732e12003-04-21 22:04:46 +0000501 modulename = modname(filename)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000502 if modulename is not None:
503 ignore_it = self.ignore.names(filename, modulename)
504 if not ignore_it:
505 if self.trace:
506 print (" --- modulename: %s, funcname: %s"
Jeremy Hylton38732e12003-04-21 22:04:46 +0000507 % (modulename, code.co_name))
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000508 return self.localtrace
509 else:
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000510 return None
511
512 def localtrace_trace_and_count(self, frame, why, arg):
Jeremy Hylton38732e12003-04-21 22:04:46 +0000513 if why == "line":
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000514 # record the file name and line number of every trace
Jeremy Hylton38732e12003-04-21 22:04:46 +0000515 filename = frame.f_code.co_filename
516 lineno = frame.f_lineno
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000517 key = filename, lineno
518 self.counts[key] = self.counts.get(key, 0) + 1
Tim Petersf2715e02003-02-19 02:35:07 +0000519
Jeremy Hylton38732e12003-04-21 22:04:46 +0000520 bname = os.path.basename(filename)
521 print "%s(%d): %s" % (bname, lineno,
522 linecache.getline(filename, lineno)),
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000523 return self.localtrace
524
525 def localtrace_trace(self, frame, why, arg):
Jeremy Hylton38732e12003-04-21 22:04:46 +0000526 if why == "line":
527 # record the file name and line number of every trace
528 filename = frame.f_code.co_filename
529 lineno = frame.f_lineno
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000530
Jeremy Hylton38732e12003-04-21 22:04:46 +0000531 bname = os.path.basename(filename)
532 print "%s(%d): %s" % (bname, lineno,
533 linecache.getline(filename, lineno)),
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000534 return self.localtrace
535
536 def localtrace_count(self, frame, why, arg):
Jeremy Hylton38732e12003-04-21 22:04:46 +0000537 if why == "line":
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000538 filename = frame.f_code.co_filename
539 lineno = frame.f_lineno
540 key = filename, lineno
541 self.counts[key] = self.counts.get(key, 0) + 1
542 return self.localtrace
543
544 def results(self):
545 return CoverageResults(self.counts, infile=self.infile,
546 outfile=self.outfile,
547 calledfuncs=self._calledfuncs)
548
549def _err_exit(msg):
550 sys.stderr.write("%s: %s\n" % (sys.argv[0], msg))
551 sys.exit(1)
552
553def main(argv=None):
554 import getopt
555
556 if argv is None:
557 argv = sys.argv
558 try:
559 opts, prog_argv = getopt.getopt(argv[1:], "tcrRf:d:msC:l",
560 ["help", "version", "trace", "count",
561 "report", "no-report", "summary",
562 "file=", "missing",
563 "ignore-module=", "ignore-dir=",
564 "coverdir=", "listfuncs",])
565
566 except getopt.error, msg:
567 sys.stderr.write("%s: %s\n" % (sys.argv[0], msg))
568 sys.stderr.write("Try `%s --help' for more information\n"
569 % sys.argv[0])
570 sys.exit(1)
571
572 trace = 0
573 count = 0
574 report = 0
575 no_report = 0
576 counts_file = None
577 missing = 0
578 ignore_modules = []
579 ignore_dirs = []
580 coverdir = None
581 summary = 0
582 listfuncs = False
583
584 for opt, val in opts:
585 if opt == "--help":
586 usage(sys.stdout)
587 sys.exit(0)
588
589 if opt == "--version":
590 sys.stdout.write("trace 2.0\n")
591 sys.exit(0)
592
593 if opt == "-l" or opt == "--listfuncs":
594 listfuncs = True
595 continue
596
597 if opt == "-t" or opt == "--trace":
598 trace = 1
599 continue
600
601 if opt == "-c" or opt == "--count":
602 count = 1
603 continue
604
605 if opt == "-r" or opt == "--report":
606 report = 1
607 continue
608
609 if opt == "-R" or opt == "--no-report":
610 no_report = 1
611 continue
612
613 if opt == "-f" or opt == "--file":
614 counts_file = val
615 continue
616
617 if opt == "-m" or opt == "--missing":
618 missing = 1
619 continue
620
621 if opt == "-C" or opt == "--coverdir":
622 coverdir = val
623 continue
624
625 if opt == "-s" or opt == "--summary":
626 summary = 1
627 continue
628
629 if opt == "--ignore-module":
630 ignore_modules.append(val)
631 continue
632
633 if opt == "--ignore-dir":
634 for s in val.split(os.pathsep):
635 s = os.path.expandvars(s)
636 # should I also call expanduser? (after all, could use $HOME)
637
638 s = s.replace("$prefix",
639 os.path.join(sys.prefix, "lib",
640 "python" + sys.version[:3]))
641 s = s.replace("$exec_prefix",
642 os.path.join(sys.exec_prefix, "lib",
643 "python" + sys.version[:3]))
644 s = os.path.normpath(s)
645 ignore_dirs.append(s)
646 continue
647
648 assert 0, "Should never get here"
649
650 if listfuncs and (count or trace):
651 _err_exit("cannot specify both --listfuncs and (--trace or --count)")
652
653 if not count and not trace and not report and not listfuncs:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000654 _err_exit("must specify one of --trace, --count, --report or "
655 "--listfuncs")
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000656
657 if report and no_report:
658 _err_exit("cannot specify both --report and --no-report")
659
660 if report and not counts_file:
661 _err_exit("--report requires a --file")
662
663 if no_report and len(prog_argv) == 0:
664 _err_exit("missing name of file to run")
665
666 # everything is ready
667 if report:
668 results = CoverageResults(infile=counts_file, outfile=counts_file)
669 results.write_results(missing, summary=summary, coverdir=coverdir)
670 else:
671 sys.argv = prog_argv
672 progname = prog_argv[0]
673 sys.path[0] = os.path.split(progname)[0]
674
675 t = Trace(count, trace, countfuncs=listfuncs,
676 ignoremods=ignore_modules, ignoredirs=ignore_dirs,
677 infile=counts_file, outfile=counts_file)
678 try:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000679 t.run('execfile(%r)' % (progname,))
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000680 except IOError, err:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000681 _err_exit("Cannot run file %r because: %s" % (sys.argv[0], err))
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000682 except SystemExit:
683 pass
684
685 results = t.results()
686
687 if not no_report:
688 results.write_results(missing, summary=summary, coverdir=coverdir)
689
690if __name__=='__main__':
691 main()