blob: b694c150212f3a0414845a2c0c2eb07ab39040d3 [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
186 base = base.replace("/", ".")
Jeremy Hyltondfbfe732003-04-21 22:49:17 +0000187 filename, ext = os.path.splitext(base)
188 return filename
189
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000190class CoverageResults:
191 def __init__(self, counts=None, calledfuncs=None, infile=None,
Tim Petersf2715e02003-02-19 02:35:07 +0000192 outfile=None):
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000193 self.counts = counts
194 if self.counts is None:
195 self.counts = {}
196 self.counter = self.counts.copy() # map (filename, lineno) to count
197 self.calledfuncs = calledfuncs
198 if self.calledfuncs is None:
199 self.calledfuncs = {}
200 self.calledfuncs = self.calledfuncs.copy()
201 self.infile = infile
202 self.outfile = outfile
203 if self.infile:
Jeremy Hyltond7ce86d2003-07-07 16:08:47 +0000204 # Try to merge existing counts file.
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000205 try:
Jeremy Hyltond0e27052003-10-14 20:12:06 +0000206 counts, calledfuncs = pickle.load(open(self.infile, 'rb'))
Jeremy Hyltond7ce86d2003-07-07 16:08:47 +0000207 self.update(self.__class__(counts, calledfuncs))
208 except (IOError, EOFError, ValueError), err:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000209 print >> sys.stderr, ("Skipping counts file %r: %s"
210 % (self.infile, err))
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000211
212 def update(self, other):
213 """Merge in the data from another CoverageResults"""
214 counts = self.counts
215 calledfuncs = self.calledfuncs
216 other_counts = other.counts
217 other_calledfuncs = other.calledfuncs
218
219 for key in other_counts.keys():
Jeremy Hylton38732e12003-04-21 22:04:46 +0000220 counts[key] = counts.get(key, 0) + other_counts[key]
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000221
222 for key in other_calledfuncs.keys():
223 calledfuncs[key] = 1
224
Jeremy Hylton38732e12003-04-21 22:04:46 +0000225 def write_results(self, show_missing=True, summary=False, coverdir=None):
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000226 """
227 @param coverdir
228 """
229 for filename, modulename, funcname in self.calledfuncs.keys():
230 print ("filename: %s, modulename: %s, funcname: %s"
231 % (filename, modulename, funcname))
232
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000233 # turn the counts data ("(filename, lineno) = count") into something
234 # accessible on a per-file basis
235 per_file = {}
Jeremy Hylton38732e12003-04-21 22:04:46 +0000236 for filename, lineno in self.counts.keys():
237 lines_hit = per_file[filename] = per_file.get(filename, {})
238 lines_hit[lineno] = self.counts[(filename, lineno)]
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000239
240 # accumulate summary info, if needed
241 sums = {}
242
Jeremy Hylton38732e12003-04-21 22:04:46 +0000243 for filename, count in per_file.iteritems():
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000244 # skip some "files" we don't care about...
245 if filename == "<string>":
246 continue
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000247
248 if filename.endswith(".pyc") or filename.endswith(".pyo"):
249 filename = filename[:-1]
250
Jeremy Hylton38732e12003-04-21 22:04:46 +0000251 if coverdir is None:
252 dir = os.path.dirname(os.path.abspath(filename))
Jeremy Hyltonc8c8b942003-04-22 15:35:51 +0000253 modulename = modname(filename)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000254 else:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000255 dir = coverdir
256 if not os.path.exists(dir):
257 os.makedirs(dir)
Jeremy Hyltonc8c8b942003-04-22 15:35:51 +0000258 modulename = fullmodname(filename)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000259
260 # If desired, get a list of the line numbers which represent
261 # executable content (returned as a dict for better lookup speed)
262 if show_missing:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000263 lnotab = find_executable_linenos(filename)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000264 else:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000265 lnotab = {}
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000266
Jeremy Hylton38732e12003-04-21 22:04:46 +0000267 source = linecache.getlines(filename)
268 coverpath = os.path.join(dir, modulename + ".cover")
269 n_hits, n_lines = self.write_results_file(coverpath, source,
270 lnotab, count)
Tim Peters0eadaac2003-04-24 16:02:54 +0000271
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000272 if summary and n_lines:
273 percent = int(100 * n_hits / n_lines)
274 sums[modulename] = n_lines, percent, modulename, filename
275
276 if summary and sums:
277 mods = sums.keys()
278 mods.sort()
279 print "lines cov% module (path)"
280 for m in mods:
281 n_lines, percent, modulename, filename = sums[m]
282 print "%5d %3d%% %s (%s)" % sums[m]
283
284 if self.outfile:
285 # try and store counts and module info into self.outfile
286 try:
287 pickle.dump((self.counts, self.calledfuncs),
Jeremy Hyltond0e27052003-10-14 20:12:06 +0000288 open(self.outfile, 'wb'), 1)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000289 except IOError, err:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000290 print >> sys.stderr, "Can't save counts files because %s" % err
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000291
Jeremy Hylton38732e12003-04-21 22:04:46 +0000292 def write_results_file(self, path, lines, lnotab, lines_hit):
293 """Return a coverage results file in path."""
294
295 try:
296 outfile = open(path, "w")
297 except IOError, err:
298 print >> sys.stderr, ("trace: Could not open %r for writing: %s"
299 "- skipping" % (path, err))
300 return
301
302 n_lines = 0
303 n_hits = 0
304 for i, line in enumerate(lines):
305 lineno = i + 1
306 # do the blank/comment match to try to mark more lines
307 # (help the reader find stuff that hasn't been covered)
308 if lineno in lines_hit:
309 outfile.write("%5d: " % lines_hit[lineno])
310 n_hits += 1
311 n_lines += 1
312 elif rx_blank.match(line):
Walter Dörwaldc1711722003-07-15 10:34:02 +0000313 outfile.write(" ")
Jeremy Hylton38732e12003-04-21 22:04:46 +0000314 else:
315 # lines preceded by no marks weren't hit
316 # Highlight them if so indicated, unless the line contains
317 # #pragma: NO COVER
318 if lineno in lnotab and not PRAGMA_NOCOVER in lines[i]:
319 outfile.write(">>>>>> ")
Jeremy Hylton546e34b2003-06-26 14:56:17 +0000320 n_lines += 1
Jeremy Hylton38732e12003-04-21 22:04:46 +0000321 else:
322 outfile.write(" ")
Jeremy Hylton38732e12003-04-21 22:04:46 +0000323 outfile.write(lines[i].expandtabs(8))
324 outfile.close()
325
326 return n_hits, n_lines
327
328def find_lines_from_code(code, strs):
329 """Return dict where keys are lines in the line number table."""
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000330 linenos = {}
331
332 line_increments = [ord(c) for c in code.co_lnotab[1::2]]
333 table_length = len(line_increments)
Jeremy Hylton38732e12003-04-21 22:04:46 +0000334 docstring = False
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000335
336 lineno = code.co_firstlineno
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000337 for li in line_increments:
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000338 lineno += li
Jeremy Hylton38732e12003-04-21 22:04:46 +0000339 if lineno not in strs:
340 linenos[lineno] = 1
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000341
342 return linenos
343
Jeremy Hylton38732e12003-04-21 22:04:46 +0000344def find_lines(code, strs):
345 """Return lineno dict for all code objects reachable from code."""
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000346 # get all of the lineno information from the code of this scope level
Jeremy Hylton38732e12003-04-21 22:04:46 +0000347 linenos = find_lines_from_code(code, strs)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000348
349 # and check the constants for references to other code objects
350 for c in code.co_consts:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000351 if isinstance(c, types.CodeType):
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000352 # find another code object, so recurse into it
Jeremy Hylton38732e12003-04-21 22:04:46 +0000353 linenos.update(find_lines(c, strs))
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000354 return linenos
355
Jeremy Hylton38732e12003-04-21 22:04:46 +0000356def find_strings(filename):
357 """Return a dict of possible docstring positions.
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000358
Jeremy Hylton38732e12003-04-21 22:04:46 +0000359 The dict maps line numbers to strings. There is an entry for
360 line that contains only a string or a part of a triple-quoted
361 string.
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000362 """
Jeremy Hylton38732e12003-04-21 22:04:46 +0000363 d = {}
364 # If the first token is a string, then it's the module docstring.
365 # Add this special case so that the test in the loop passes.
366 prev_ttype = token.INDENT
367 f = open(filename)
368 for ttype, tstr, start, end, line in tokenize.generate_tokens(f.readline):
369 if ttype == token.STRING:
370 if prev_ttype == token.INDENT:
371 sline, scol = start
372 eline, ecol = end
373 for i in range(sline, eline + 1):
374 d[i] = 1
375 prev_ttype = ttype
376 f.close()
377 return d
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000378
Jeremy Hylton38732e12003-04-21 22:04:46 +0000379def find_executable_linenos(filename):
380 """Return dict where keys are line numbers in the line number table."""
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000381 assert filename.endswith('.py')
Jeremy Hylton38732e12003-04-21 22:04:46 +0000382 try:
383 prog = open(filename).read()
384 except IOError, err:
385 print >> sys.stderr, ("Not printing coverage data for %r: %s"
386 % (filename, err))
387 return {}
388 code = compile(prog, filename, "exec")
389 strs = find_strings(filename)
390 return find_lines(code, strs)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000391
392class Trace:
393 def __init__(self, count=1, trace=1, countfuncs=0, ignoremods=(),
394 ignoredirs=(), infile=None, outfile=None):
395 """
396 @param count true iff it should count number of times each
Tim Petersf2715e02003-02-19 02:35:07 +0000397 line is executed
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000398 @param trace true iff it should print out each line that is
Tim Petersf2715e02003-02-19 02:35:07 +0000399 being counted
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000400 @param countfuncs true iff it should just output a list of
401 (filename, modulename, funcname,) for functions
402 that were called at least once; This overrides
Tim Petersf2715e02003-02-19 02:35:07 +0000403 `count' and `trace'
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000404 @param ignoremods a list of the names of modules to ignore
405 @param ignoredirs a list of the names of directories to ignore
Tim Petersf2715e02003-02-19 02:35:07 +0000406 all of the (recursive) contents of
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000407 @param infile file from which to read stored counts to be
Tim Petersf2715e02003-02-19 02:35:07 +0000408 added into the results
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000409 @param outfile file in which to write the results
410 """
411 self.infile = infile
412 self.outfile = outfile
413 self.ignore = Ignore(ignoremods, ignoredirs)
414 self.counts = {} # keys are (filename, linenumber)
415 self.blabbed = {} # for debugging
416 self.pathtobasename = {} # for memoizing os.path.basename
417 self.donothing = 0
418 self.trace = trace
419 self._calledfuncs = {}
420 if countfuncs:
421 self.globaltrace = self.globaltrace_countfuncs
422 elif trace and count:
423 self.globaltrace = self.globaltrace_lt
424 self.localtrace = self.localtrace_trace_and_count
425 elif trace:
426 self.globaltrace = self.globaltrace_lt
427 self.localtrace = self.localtrace_trace
428 elif count:
429 self.globaltrace = self.globaltrace_lt
430 self.localtrace = self.localtrace_count
431 else:
432 # Ahem -- do nothing? Okay.
433 self.donothing = 1
434
435 def run(self, cmd):
436 import __main__
437 dict = __main__.__dict__
438 if not self.donothing:
439 sys.settrace(self.globaltrace)
Jeremy Hylton546e34b2003-06-26 14:56:17 +0000440 threading.settrace(self.globaltrace)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000441 try:
442 exec cmd in dict, dict
443 finally:
444 if not self.donothing:
445 sys.settrace(None)
Jeremy Hylton546e34b2003-06-26 14:56:17 +0000446 threading.settrace(None)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000447
448 def runctx(self, cmd, globals=None, locals=None):
449 if globals is None: globals = {}
450 if locals is None: locals = {}
451 if not self.donothing:
452 sys.settrace(self.globaltrace)
Jeremy Hylton546e34b2003-06-26 14:56:17 +0000453 threading.settrace(self.globaltrace)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000454 try:
455 exec cmd in globals, locals
456 finally:
457 if not self.donothing:
458 sys.settrace(None)
Jeremy Hylton546e34b2003-06-26 14:56:17 +0000459 threading.settrace(None)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000460
461 def runfunc(self, func, *args, **kw):
462 result = None
463 if not self.donothing:
464 sys.settrace(self.globaltrace)
465 try:
Guido van Rossum68468eb2003-02-27 20:14:51 +0000466 result = func(*args, **kw)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000467 finally:
468 if not self.donothing:
469 sys.settrace(None)
470 return result
471
472 def globaltrace_countfuncs(self, frame, why, arg):
Jeremy Hylton38732e12003-04-21 22:04:46 +0000473 """Handler for call events.
Tim Peters0eadaac2003-04-24 16:02:54 +0000474
Jeremy Hylton38732e12003-04-21 22:04:46 +0000475 Adds (filename, modulename, funcname) to the self._calledfuncs dict.
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000476 """
477 if why == 'call':
Jeremy Hylton38732e12003-04-21 22:04:46 +0000478 code = frame.f_code
479 filename = code.co_filename
480 funcname = code.co_name
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000481 if filename:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000482 modulename = modname(filename)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000483 else:
484 modulename = None
Jeremy Hylton38732e12003-04-21 22:04:46 +0000485 self._calledfuncs[(filename, modulename, funcname)] = 1
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000486
487 def globaltrace_lt(self, frame, why, arg):
Jeremy Hylton38732e12003-04-21 22:04:46 +0000488 """Handler for call events.
489
490 If the code block being entered is to be ignored, returns `None',
491 else returns self.localtrace.
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000492 """
493 if why == 'call':
Jeremy Hylton38732e12003-04-21 22:04:46 +0000494 code = frame.f_code
495 filename = code.co_filename
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000496 if filename:
Jeremy Hyltondfbfe732003-04-21 22:49:17 +0000497 # XXX modname() doesn't work right for packages, so
498 # the ignore support won't work right for packages
Jeremy Hylton38732e12003-04-21 22:04:46 +0000499 modulename = modname(filename)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000500 if modulename is not None:
501 ignore_it = self.ignore.names(filename, modulename)
502 if not ignore_it:
503 if self.trace:
504 print (" --- modulename: %s, funcname: %s"
Jeremy Hylton38732e12003-04-21 22:04:46 +0000505 % (modulename, code.co_name))
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000506 return self.localtrace
507 else:
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000508 return None
509
510 def localtrace_trace_and_count(self, frame, why, arg):
Jeremy Hylton38732e12003-04-21 22:04:46 +0000511 if why == "line":
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000512 # record the file name and line number of every trace
Jeremy Hylton38732e12003-04-21 22:04:46 +0000513 filename = frame.f_code.co_filename
514 lineno = frame.f_lineno
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000515 key = filename, lineno
516 self.counts[key] = self.counts.get(key, 0) + 1
Tim Petersf2715e02003-02-19 02:35:07 +0000517
Jeremy Hylton38732e12003-04-21 22:04:46 +0000518 bname = os.path.basename(filename)
519 print "%s(%d): %s" % (bname, lineno,
520 linecache.getline(filename, lineno)),
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000521 return self.localtrace
522
523 def localtrace_trace(self, frame, why, arg):
Jeremy Hylton38732e12003-04-21 22:04:46 +0000524 if why == "line":
525 # record the file name and line number of every trace
526 filename = frame.f_code.co_filename
527 lineno = frame.f_lineno
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000528
Jeremy Hylton38732e12003-04-21 22:04:46 +0000529 bname = os.path.basename(filename)
530 print "%s(%d): %s" % (bname, lineno,
531 linecache.getline(filename, lineno)),
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000532 return self.localtrace
533
534 def localtrace_count(self, frame, why, arg):
Jeremy Hylton38732e12003-04-21 22:04:46 +0000535 if why == "line":
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000536 filename = frame.f_code.co_filename
537 lineno = frame.f_lineno
538 key = filename, lineno
539 self.counts[key] = self.counts.get(key, 0) + 1
540 return self.localtrace
541
542 def results(self):
543 return CoverageResults(self.counts, infile=self.infile,
544 outfile=self.outfile,
545 calledfuncs=self._calledfuncs)
546
547def _err_exit(msg):
548 sys.stderr.write("%s: %s\n" % (sys.argv[0], msg))
549 sys.exit(1)
550
551def main(argv=None):
552 import getopt
553
554 if argv is None:
555 argv = sys.argv
556 try:
557 opts, prog_argv = getopt.getopt(argv[1:], "tcrRf:d:msC:l",
558 ["help", "version", "trace", "count",
559 "report", "no-report", "summary",
560 "file=", "missing",
561 "ignore-module=", "ignore-dir=",
562 "coverdir=", "listfuncs",])
563
564 except getopt.error, msg:
565 sys.stderr.write("%s: %s\n" % (sys.argv[0], msg))
566 sys.stderr.write("Try `%s --help' for more information\n"
567 % sys.argv[0])
568 sys.exit(1)
569
570 trace = 0
571 count = 0
572 report = 0
573 no_report = 0
574 counts_file = None
575 missing = 0
576 ignore_modules = []
577 ignore_dirs = []
578 coverdir = None
579 summary = 0
580 listfuncs = False
581
582 for opt, val in opts:
583 if opt == "--help":
584 usage(sys.stdout)
585 sys.exit(0)
586
587 if opt == "--version":
588 sys.stdout.write("trace 2.0\n")
589 sys.exit(0)
590
591 if opt == "-l" or opt == "--listfuncs":
592 listfuncs = True
593 continue
594
595 if opt == "-t" or opt == "--trace":
596 trace = 1
597 continue
598
599 if opt == "-c" or opt == "--count":
600 count = 1
601 continue
602
603 if opt == "-r" or opt == "--report":
604 report = 1
605 continue
606
607 if opt == "-R" or opt == "--no-report":
608 no_report = 1
609 continue
610
611 if opt == "-f" or opt == "--file":
612 counts_file = val
613 continue
614
615 if opt == "-m" or opt == "--missing":
616 missing = 1
617 continue
618
619 if opt == "-C" or opt == "--coverdir":
620 coverdir = val
621 continue
622
623 if opt == "-s" or opt == "--summary":
624 summary = 1
625 continue
626
627 if opt == "--ignore-module":
628 ignore_modules.append(val)
629 continue
630
631 if opt == "--ignore-dir":
632 for s in val.split(os.pathsep):
633 s = os.path.expandvars(s)
634 # should I also call expanduser? (after all, could use $HOME)
635
636 s = s.replace("$prefix",
637 os.path.join(sys.prefix, "lib",
638 "python" + sys.version[:3]))
639 s = s.replace("$exec_prefix",
640 os.path.join(sys.exec_prefix, "lib",
641 "python" + sys.version[:3]))
642 s = os.path.normpath(s)
643 ignore_dirs.append(s)
644 continue
645
646 assert 0, "Should never get here"
647
648 if listfuncs and (count or trace):
649 _err_exit("cannot specify both --listfuncs and (--trace or --count)")
650
651 if not count and not trace and not report and not listfuncs:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000652 _err_exit("must specify one of --trace, --count, --report or "
653 "--listfuncs")
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000654
655 if report and no_report:
656 _err_exit("cannot specify both --report and --no-report")
657
658 if report and not counts_file:
659 _err_exit("--report requires a --file")
660
661 if no_report and len(prog_argv) == 0:
662 _err_exit("missing name of file to run")
663
664 # everything is ready
665 if report:
666 results = CoverageResults(infile=counts_file, outfile=counts_file)
667 results.write_results(missing, summary=summary, coverdir=coverdir)
668 else:
669 sys.argv = prog_argv
670 progname = prog_argv[0]
671 sys.path[0] = os.path.split(progname)[0]
672
673 t = Trace(count, trace, countfuncs=listfuncs,
674 ignoremods=ignore_modules, ignoredirs=ignore_dirs,
675 infile=counts_file, outfile=counts_file)
676 try:
677 t.run('execfile(' + `progname` + ')')
678 except IOError, err:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000679 _err_exit("Cannot run file %r because: %s" % (sys.argv[0], err))
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000680 except SystemExit:
681 pass
682
683 results = t.results()
684
685 if not no_report:
686 results.write_results(missing, summary=summary, coverdir=coverdir)
687
688if __name__=='__main__':
689 main()