blob: cb6a943a60b5def0fde00a68afc2cd1cc36602b4 [file] [log] [blame]
Jeremy Hyltonda1ec462000-08-03 19:26:21 +00001#!/usr/bin/env python
2
Guido van Rossuma30eacf2001-11-28 19:41:45 +00003# 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#
Jeremy Hyltonda1ec462000-08-03 19:26:21 +000010# 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#
Jeremy Hyltonda1ec462000-08-03 19:26:21 +000030
31"""
32program/module to trace Python program or function execution
33
34Sample use, command line:
35 trace.py -c -f counts --ignore-dir '$prefix' spam.py eggs
36 trace.py -t --ignore-dir '$prefix' spam.py eggs
37
Guido van Rossuma30eacf2001-11-28 19:41:45 +000038Sample use, programmatically
39 # create a Trace object, telling it what to ignore, and whether to do tracing
40 # or line-counting or both.
41 trace = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,], trace=0, count=1)
Jeremy Hyltonda1ec462000-08-03 19:26:21 +000042 # run the new command using the given trace
Guido van Rossuma30eacf2001-11-28 19:41:45 +000043 trace.run(coverage.globaltrace, 'main()')
Jeremy Hyltonda1ec462000-08-03 19:26:21 +000044 # make a report, telling it where you want output
Guido van Rossuma30eacf2001-11-28 19:41:45 +000045 trace.print_results(show_missing=1)
Jeremy Hyltonda1ec462000-08-03 19:26:21 +000046"""
47
Walter Dörwaldaaab30e2002-09-11 20:36:02 +000048import sys, os, tempfile, types, copy, operator, inspect, exceptions, marshal
Guido van Rossuma30eacf2001-11-28 19:41:45 +000049try:
50 import cPickle
51 pickle = cPickle
52except ImportError:
53 import pickle
54
55true = 1
56false = None
57
58# DEBUG_MODE=1 # make this true to get printouts which help you understand what's going on
Jeremy Hyltonda1ec462000-08-03 19:26:21 +000059
60def usage(outfile):
61 outfile.write("""Usage: %s [OPTIONS] <file> [ARGS]
62
Guido van Rossuma30eacf2001-11-28 19:41:45 +000063Meta-options:
64--help Display this help then exit.
65--version Output version information then exit.
Jeremy Hyltonda1ec462000-08-03 19:26:21 +000066
Guido van Rossuma30eacf2001-11-28 19:41:45 +000067Otherwise, exactly one of the following three options must be given:
68-t, --trace Print each line to sys.stdout before it is executed.
69-c, --count Count the number of times each line is executed
70 and write the counts to <module>.cover for each
71 module executed, in the module's directory.
72 See also `--coverdir', `--file', `--no-report' below.
73-r, --report Generate a report from a counts file; do not execute
74 any code. `--file' must specify the results file to
75 read, which must have been created in a previous run
76 with `--count --file=FILE'.
Jeremy Hyltonda1ec462000-08-03 19:26:21 +000077
Guido van Rossuma30eacf2001-11-28 19:41:45 +000078Modifiers:
79-f, --file=<file> File to accumulate counts over several runs.
80-R, --no-report Do not generate the coverage report files.
81 Useful if you want to accumulate over several runs.
82-C, --coverdir=<dir> Directory where the report files. The coverage
83 report for <package>.<module> is written to file
84 <dir>/<package>/<module>.cover.
85-m, --missing Annotate executable lines that were not executed
86 with '>>>>>> '.
87-s, --summary Write a brief summary on stdout for each file.
88 (Can only be used with --count or --report.)
Jeremy Hyltonda1ec462000-08-03 19:26:21 +000089
Guido van Rossuma30eacf2001-11-28 19:41:45 +000090Filters, may be repeated multiple times:
91--ignore-module=<mod> Ignore the given module and its submodules
92 (if it is a package).
93--ignore-dir=<dir> Ignore files in the given directory (multiple
94 directories can be joined by os.pathsep).
Jeremy Hyltonda1ec462000-08-03 19:26:21 +000095""" % sys.argv[0])
96
Jeremy Hyltonda1ec462000-08-03 19:26:21 +000097class Ignore:
98 def __init__(self, modules = None, dirs = None):
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +000099 self._mods = modules or []
100 self._dirs = dirs or []
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000101
Guido van Rossuma30eacf2001-11-28 19:41:45 +0000102 self._dirs = map(os.path.normpath, self._dirs)
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +0000103 self._ignore = { '<string>': 1 }
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000104
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000105 def names(self, filename, modulename):
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +0000106 if self._ignore.has_key(modulename):
107 return self._ignore[modulename]
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000108
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +0000109 # haven't seen this one before, so see if the module name is
110 # on the ignore list. Need to take some care since ignoring
111 # "cmp" musn't mean ignoring "cmpcache" but ignoring
112 # "Spam" must also mean ignoring "Spam.Eggs".
113 for mod in self._mods:
114 if mod == modulename: # Identical names, so ignore
115 self._ignore[modulename] = 1
116 return 1
117 # check if the module is a proper submodule of something on
118 # the ignore list
119 n = len(mod)
120 # (will not overflow since if the first n characters are the
121 # same and the name has not already occured, then the size
122 # of "name" is greater than that of "mod")
123 if mod == modulename[:n] and modulename[n] == '.':
124 self._ignore[modulename] = 1
125 return 1
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000126
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +0000127 # Now check that __file__ isn't in one of the directories
128 if filename is None:
129 # must be a built-in, so we must ignore
130 self._ignore[modulename] = 1
131 return 1
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000132
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +0000133 # Ignore a file when it contains one of the ignorable paths
134 for d in self._dirs:
135 # The '+ os.sep' is to ensure that d is a parent directory,
136 # as compared to cases like:
137 # d = "/usr/local"
138 # filename = "/usr/local.py"
139 # or
140 # d = "/usr/local.py"
141 # filename = "/usr/local.py"
Walter Dörwaldaaab30e2002-09-11 20:36:02 +0000142 if filename.startswith(d + os.sep):
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +0000143 self._ignore[modulename] = 1
144 return 1
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000145
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +0000146 # Tried the different ways, so we don't ignore this module
147 self._ignore[modulename] = 0
148 return 0
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000149
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000150class CoverageResults:
Guido van Rossuma30eacf2001-11-28 19:41:45 +0000151 def __init__(self, counts=None, calledfuncs=None, infile=None, outfile=None):
152 self.counts = counts
153 if self.counts is None:
154 self.counts = {}
155 self.counter = self.counts.copy() # map (filename, lineno) to count
156 self.calledfuncs = calledfuncs
157 if self.calledfuncs is None:
158 self.calledfuncs = {}
159 self.calledfuncs = self.calledfuncs.copy()
160 self.infile = infile
161 self.outfile = outfile
162 if self.infile:
163 # try and merge existing counts file
164 try:
165 thingie = pickle.load(open(self.infile, 'r'))
166 if type(thingie) is types.DictType:
167 # backwards compatibility for old trace.py after Zooko touched it but before calledfuncs --Zooko 2001-10-24
168 self.update(self.__class__(thingie))
169 elif type(thingie) is types.TupleType and len(thingie) == 2:
170 (counts, calledfuncs,) = thingie
171 self.update(self.__class__(counts, calledfuncs))
172 except (IOError, EOFError,):
173 pass
174 except pickle.UnpicklingError:
175 # backwards compatibility for old trace.py before Zooko touched it --Zooko 2001-10-24
176 self.update(self.__class__(marshal.load(open(self.infile))))
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000177
178 def update(self, other):
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +0000179 """Merge in the data from another CoverageResults"""
180 counts = self.counts
Guido van Rossuma30eacf2001-11-28 19:41:45 +0000181 calledfuncs = self.calledfuncs
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +0000182 other_counts = other.counts
Guido van Rossuma30eacf2001-11-28 19:41:45 +0000183 other_calledfuncs = other.calledfuncs
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000184
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +0000185 for key in other_counts.keys():
Guido van Rossuma30eacf2001-11-28 19:41:45 +0000186 if key != 'calledfuncs': # backwards compatibility for abortive attempt to stuff calledfuncs into self.counts, by Zooko --Zooko 2001-10-24
187 counts[key] = counts.get(key, 0) + other_counts[key]
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000188
Guido van Rossuma30eacf2001-11-28 19:41:45 +0000189 for key in other_calledfuncs.keys():
190 calledfuncs[key] = 1
191
192 def write_results(self, show_missing = 1, summary = 0, coverdir = None):
193 """
194 @param coverdir
195 """
196 for (filename, modulename, funcname,) in self.calledfuncs.keys():
197 print "filename: %s, modulename: %s, funcname: %s" % (filename, modulename, funcname,)
198
199 import re
200 # turn the counts data ("(filename, lineno) = count") into something
201 # accessible on a per-file basis
202 per_file = {}
203 for thingie in self.counts.keys():
204 if thingie != "calledfuncs": # backwards compatibility for abortive attempt to stuff calledfuncs into self.counts, by Zooko --Zooko 2001-10-24
205 (filename, lineno,) = thingie
206 lines_hit = per_file[filename] = per_file.get(filename, {})
207 lines_hit[lineno] = self.counts[(filename, lineno)]
208
209 # there are many places where this is insufficient, like a blank
210 # line embedded in a multiline string.
211 blank = re.compile(r'^\s*(#.*)?$')
212
213 # accumulate summary info, if needed
214 sums = {}
215
216 # generate file paths for the coverage files we are going to write...
217 fnlist = []
218 tfdir = tempfile.gettempdir()
219 for key in per_file.keys():
220 filename = key
221
222 # skip some "files" we don't care about...
223 if filename == "<string>":
224 continue
225 # are these caused by code compiled using exec or something?
226 if filename.startswith(tfdir):
227 continue
228
229 modulename = inspect.getmodulename(filename)
230
231 if filename.endswith(".pyc") or filename.endswith(".pyo"):
232 filename = filename[:-1]
233
234 if coverdir:
235 thiscoverdir = coverdir
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +0000236 else:
Guido van Rossuma30eacf2001-11-28 19:41:45 +0000237 thiscoverdir = os.path.dirname(os.path.abspath(filename))
238
239 # the code from here to "<<<" is the contents of the `fileutil.make_dirs()' function in the Mojo Nation project. --Zooko 2001-10-14
240 # http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/mojonation/evil/common/fileutil.py?rev=HEAD&content-type=text/vnd.viewcvs-markup
241 tx = None
242 try:
243 os.makedirs(thiscoverdir)
244 except OSError, x:
245 tx = x
246
247 if not os.path.isdir(thiscoverdir):
248 if tx:
249 raise tx
250 raise exceptions.IOError, "unknown error prevented creation of directory: %s" % thiscoverdir # careful not to construct an IOError with a 2-tuple, as that has a special meaning...
251 # <<<
252
253 # build list file name by appending a ".cover" to the module name
254 # and sticking it into the specified directory
255 if "." in modulename:
256 # A module in a package
257 finalname = modulename.split(".")[-1]
258 listfilename = os.path.join(thiscoverdir, finalname + ".cover")
259 else:
260 listfilename = os.path.join(thiscoverdir, modulename + ".cover")
261
262 # Get the original lines from the .py file
263 try:
264 lines = open(filename, 'r').readlines()
265 except IOError, err:
266 sys.stderr.write("trace: Could not open %s for reading because: %s - skipping\n" % (`filename`, err))
267 continue
268
269 try:
270 outfile = open(listfilename, 'w')
271 except IOError, err:
272 sys.stderr.write(
273 '%s: Could not open %s for writing because: %s" \
274 "- skipping\n' % ("trace", `listfilename`, err))
275 continue
276
277 # If desired, get a list of the line numbers which represent
278 # executable content (returned as a dict for better lookup speed)
279 if show_missing:
280 executable_linenos = find_executable_linenos(filename)
281 else:
282 executable_linenos = {}
283
284 n_lines = 0
285 n_hits = 0
286 lines_hit = per_file[key]
287 for i in range(len(lines)):
288 line = lines[i]
289
290 # do the blank/comment match to try to mark more lines
291 # (help the reader find stuff that hasn't been covered)
292 if lines_hit.has_key(i+1):
293 # count precedes the lines that we captured
294 outfile.write('%5d: ' % lines_hit[i+1])
295 n_hits = n_hits + 1
296 n_lines = n_lines + 1
297 elif blank.match(line):
298 # blank lines and comments are preceded by dots
299 outfile.write(' . ')
300 else:
301 # lines preceded by no marks weren't hit
302 # Highlight them if so indicated, unless the line contains
303 # '#pragma: NO COVER' (it is possible to embed this into
304 # the text as a non-comment; no easy fix)
305 if executable_linenos.has_key(i+1) and \
Walter Dörwaldaaab30e2002-09-11 20:36:02 +0000306 lines[i].find(' '.join(['#pragma', 'NO COVER'])) == -1:
Guido van Rossuma30eacf2001-11-28 19:41:45 +0000307 outfile.write('>>>>>> ')
308 else:
309 outfile.write(' '*7)
310 n_lines = n_lines + 1
Walter Dörwaldaaab30e2002-09-11 20:36:02 +0000311 outfile.write(lines[i].expandtabs(8))
Guido van Rossuma30eacf2001-11-28 19:41:45 +0000312
313 outfile.close()
314
315 if summary and n_lines:
316 percent = int(100 * n_hits / n_lines)
317 sums[modulename] = n_lines, percent, modulename, filename
318
319 if summary and sums:
320 mods = sums.keys()
321 mods.sort()
322 print "lines cov% module (path)"
323 for m in mods:
324 n_lines, percent, modulename, filename = sums[m]
325 print "%5d %3d%% %s (%s)" % sums[m]
326
327 if self.outfile:
328 # try and store counts and module info into self.outfile
329 try:
330 pickle.dump((self.counts, self.calledfuncs,), open(self.outfile, 'w'), 1)
331 except IOError, err:
332 sys.stderr.write("cannot save counts files because %s" % err)
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000333
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000334def _find_LINENO_from_code(code):
335 """return the numbers of the lines containing the source code that
336 was compiled into code"""
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000337 linenos = {}
338
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000339 line_increments = [ord(c) for c in code.co_lnotab[1::2]]
340 table_length = len(line_increments)
341
342 lineno = code.co_first_lineno
343
344 for li in line_increments:
345 linenos[lineno] = 1
346 lineno += li
347 linenos[lineno] = 1
348
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000349 return linenos
350
351def _find_LINENO(code):
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000352 """return all of the lineno information from a code object"""
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000353 import types
354
355 # get all of the lineno information from the code of this scope level
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000356 linenos = _find_LINENO_from_code(code)
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000357
358 # and check the constants for references to other code objects
359 for c in code.co_consts:
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +0000360 if type(c) == types.CodeType:
361 # find another code object, so recurse into it
362 linenos.update(_find_LINENO(c))
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000363 return linenos
364
365def find_executable_linenos(filename):
366 """return a dict of the line numbers from executable statements in a file
367
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000368 """
369 import parser
370
Jeremy Hylton66a7e572001-05-08 04:20:52 +0000371 assert filename.endswith('.py')
372
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000373 prog = open(filename).read()
374 ast = parser.suite(prog)
375 code = parser.compileast(ast, filename)
376
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000377 return _find_LINENO(code)
378
379### XXX because os.path.commonprefix seems broken by my way of thinking...
380def commonprefix(dirs):
381 "Given a list of pathnames, returns the longest common leading component"
382 if not dirs: return ''
383 n = copy.copy(dirs)
384 for i in range(len(n)):
385 n[i] = n[i].split(os.sep)
386 prefix = n[0]
387 for item in n:
388 for i in range(len(prefix)):
389 if prefix[:i+1] <> item[:i+1]:
390 prefix = prefix[:i]
391 if i == 0: return ''
392 break
393 return os.sep.join(prefix)
Tim Peters70c43782001-01-17 08:48:39 +0000394
Guido van Rossuma30eacf2001-11-28 19:41:45 +0000395class Trace:
396 def __init__(self, count=1, trace=1, countfuncs=0, ignoremods=(), ignoredirs=(), infile=None, outfile=None):
397 """
398 @param count true iff it should count number of times each line is executed
399 @param trace true iff it should print out each line that is being counted
400 @param countfuncs true iff it should just output a list of (filename, modulename, funcname,) for functions that were called at least once; This overrides `count' and `trace'
401 @param ignoremods a list of the names of modules to ignore
402 @param ignoredirs a list of the names of directories to ignore all of the (recursive) contents of
403 @param infile file from which to read stored counts to be added into the results
404 @param outfile file in which to write the results
405 """
406 self.infile = infile
407 self.outfile = outfile
408 self.ignore = Ignore(ignoremods, ignoredirs)
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +0000409 self.counts = {} # keys are (filename, linenumber)
Guido van Rossuma30eacf2001-11-28 19:41:45 +0000410 self.blabbed = {} # for debugging
411 self.pathtobasename = {} # for memoizing os.path.basename
412 self.donothing = 0
413 self.trace = trace
414 self._calledfuncs = {}
415 if countfuncs:
416 self.globaltrace = self.globaltrace_countfuncs
417 elif trace and count:
418 self.globaltrace = self.globaltrace_lt
419 self.localtrace = self.localtrace_trace_and_count
420 elif trace:
421 self.globaltrace = self.globaltrace_lt
422 self.localtrace = self.localtrace_trace
423 elif count:
424 self.globaltrace = self.globaltrace_lt
425 self.localtrace = self.localtrace_count
426 else:
427 # Ahem -- do nothing? Okay.
428 self.donothing = 1
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000429
Guido van Rossuma30eacf2001-11-28 19:41:45 +0000430 def run(self, cmd):
431 import __main__
432 dict = __main__.__dict__
433 if not self.donothing:
434 sys.settrace(self.globaltrace)
435 try:
436 exec cmd in dict, dict
437 finally:
438 if not self.donothing:
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +0000439 sys.settrace(None)
Guido van Rossuma30eacf2001-11-28 19:41:45 +0000440
441 def runctx(self, cmd, globals=None, locals=None):
442 if globals is None: globals = {}
443 if locals is None: locals = {}
444 if not self.donothing:
Skip Montanaro3a48ed92002-07-25 16:09:35 +0000445 sys.settrace(self.globaltrace)
Guido van Rossuma30eacf2001-11-28 19:41:45 +0000446 try:
Skip Montanaro3a48ed92002-07-25 16:09:35 +0000447 exec cmd in globals, locals
Guido van Rossuma30eacf2001-11-28 19:41:45 +0000448 finally:
449 if not self.donothing:
450 sys.settrace(None)
451
452 def runfunc(self, func, *args, **kw):
453 result = None
454 if not self.donothing:
455 sys.settrace(self.globaltrace)
456 try:
457 result = apply(func, args, kw)
458 finally:
459 if not self.donothing:
460 sys.settrace(None)
461 return result
462
463 def globaltrace_countfuncs(self, frame, why, arg):
464 """
465 Handles `call' events (why == 'call') and adds the (filename, modulename, funcname,) to the self._calledfuncs dict.
466 """
467 if why == 'call':
468 (filename, lineno, funcname, context, lineindex,) = inspect.getframeinfo(frame, 0)
469 if filename:
470 modulename = inspect.getmodulename(filename)
471 else:
472 modulename = None
473 self._calledfuncs[(filename, modulename, funcname,)] = 1
474
475 def globaltrace_lt(self, frame, why, arg):
476 """
477 Handles `call' events (why == 'call') and if the code block being entered is to be ignored then it returns `None', else it returns `self.localtrace'.
478 """
479 if why == 'call':
480 (filename, lineno, funcname, context, lineindex,) = inspect.getframeinfo(frame, 0)
481 # if DEBUG_MODE and not filename:
482 # print "%s.globaltrace(frame: %s, why: %s, arg: %s): filename: %s, lineno: %s, funcname: %s, context: %s, lineindex: %s\n" % (self, frame, why, arg, filename, lineno, funcname, context, lineindex,)
483 if filename:
484 modulename = inspect.getmodulename(filename)
Skip Montanaro3a48ed92002-07-25 16:09:35 +0000485 if modulename is not None:
486 ignore_it = self.ignore.names(filename, modulename)
487 # if DEBUG_MODE and not self.blabbed.has_key((filename, modulename,)):
488 # self.blabbed[(filename, modulename,)] = None
489 # print "%s.globaltrace(frame: %s, why: %s, arg: %s, filename: %s, modulename: %s, ignore_it: %s\n" % (self, frame, why, arg, filename, modulename, ignore_it,)
490 if not ignore_it:
491 if self.trace:
492 print " --- modulename: %s, funcname: %s" % (modulename, funcname,)
493 # if DEBUG_MODE:
494 # print "%s.globaltrace(frame: %s, why: %s, arg: %s, filename: %s, modulename: %s, ignore_it: %s -- about to localtrace\n" % (self, frame, why, arg, filename, modulename, ignore_it,)
495 return self.localtrace
Guido van Rossuma30eacf2001-11-28 19:41:45 +0000496 else:
497 # XXX why no filename?
498 return None
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000499
Guido van Rossuma30eacf2001-11-28 19:41:45 +0000500 def localtrace_trace_and_count(self, frame, why, arg):
501 if why == 'line':
502 # record the file name and line number of every trace
503 # XXX I wish inspect offered me an optimized `getfilename(frame)' to use in place of the presumably heavier `getframeinfo()'. --Zooko 2001-10-14
504 (filename, lineno, funcname, context, lineindex,) = inspect.getframeinfo(frame, 1)
505 key = (filename, lineno,)
506 self.counts[key] = self.counts.get(key, 0) + 1
507 # XXX not convinced that this memoizing is a performance win -- I don't know enough about Python guts to tell. --Zooko 2001-10-14
508 bname = self.pathtobasename.get(filename)
509 if bname is None:
510 # Using setdefault faster than two separate lines? --Zooko 2001-10-14
511 bname = self.pathtobasename.setdefault(filename, os.path.basename(filename))
512 try:
513 print "%s(%d): %s" % (bname, lineno, context[lineindex],),
514 except IndexError:
515 # Uh.. sometimes getframeinfo gives me a context of length 1 and a lineindex of -2. Oh well.
516 pass
517 return self.localtrace
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000518
Guido van Rossuma30eacf2001-11-28 19:41:45 +0000519 def localtrace_trace(self, frame, why, arg):
520 if why == 'line':
521 # XXX shouldn't do the count increment when arg is exception? But be careful to return self.localtrace when arg is exception! ? --Zooko 2001-10-14
522 # record the file name and line number of every trace
523 # XXX I wish inspect offered me an optimized `getfilename(frame)' to use in place of the presumably heavier `getframeinfo()'. --Zooko 2001-10-14
524 (filename, lineno, funcname, context, lineindex,) = inspect.getframeinfo(frame)
525 # if DEBUG_MODE:
526 # print "%s.localtrace_trace(frame: %s, why: %s, arg: %s); filename: %s, lineno: %s, funcname: %s, context: %s, lineindex: %s\n" % (self, frame, why, arg, filename, lineno, funcname, context, lineindex,)
527 # XXX not convinced that this memoizing is a performance win -- I don't know enough about Python guts to tell. --Zooko 2001-10-14
528 bname = self.pathtobasename.get(filename)
529 if bname is None:
530 # Using setdefault faster than two separate lines? --Zooko 2001-10-14
531 bname = self.pathtobasename.setdefault(filename, os.path.basename(filename))
Skip Montanaro3a48ed92002-07-25 16:09:35 +0000532 if context is not None:
533 try:
534 print "%s(%d): %s" % (bname, lineno, context[lineindex],),
535 except IndexError:
536 # Uh.. sometimes getframeinfo gives me a context of length 1 and a lineindex of -2. Oh well.
537 pass
538 else:
539 print "%s(???): ???" % bname
Guido van Rossuma30eacf2001-11-28 19:41:45 +0000540 return self.localtrace
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000541
Guido van Rossuma30eacf2001-11-28 19:41:45 +0000542 def localtrace_count(self, frame, why, arg):
543 if why == 'line':
544 # XXX shouldn't do the count increment when arg is exception? But be careful to return self.localtrace when arg is exception! ? --Zooko 2001-10-14
545 # record the file name and line number of every trace
546 # XXX I wish inspect offered me an optimized `getfilename(frame)' to use in place of the presumably heavier `getframeinfo()'. --Zooko 2001-10-14
547 (filename, lineno, funcname, context, lineindex,) = inspect.getframeinfo(frame)
548 key = (filename, lineno,)
549 self.counts[key] = self.counts.get(key, 0) + 1
550 return self.localtrace
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000551
552 def results(self):
Guido van Rossuma30eacf2001-11-28 19:41:45 +0000553 return CoverageResults(self.counts, infile=self.infile, outfile=self.outfile, calledfuncs=self._calledfuncs)
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000554
555def _err_exit(msg):
Guido van Rossuma30eacf2001-11-28 19:41:45 +0000556 sys.stderr.write("%s: %s\n" % (sys.argv[0], msg))
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +0000557 sys.exit(1)
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000558
Guido van Rossuma30eacf2001-11-28 19:41:45 +0000559def main(argv=None):
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000560 import getopt
561
562 if argv is None:
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +0000563 argv = sys.argv
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000564 try:
Guido van Rossuma30eacf2001-11-28 19:41:45 +0000565 opts, prog_argv = getopt.getopt(argv[1:], "tcrRf:d:msC:l",
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +0000566 ["help", "version", "trace", "count",
567 "report", "no-report",
Guido van Rossuma30eacf2001-11-28 19:41:45 +0000568 "file=", "missing",
Jeremy Hylton66a7e572001-05-08 04:20:52 +0000569 "ignore-module=", "ignore-dir=",
Guido van Rossuma30eacf2001-11-28 19:41:45 +0000570 "coverdir=", "listfuncs",])
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000571
572 except getopt.error, msg:
Guido van Rossuma30eacf2001-11-28 19:41:45 +0000573 sys.stderr.write("%s: %s\n" % (sys.argv[0], msg))
574 sys.stderr.write("Try `%s --help' for more information\n" % sys.argv[0])
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +0000575 sys.exit(1)
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000576
577 trace = 0
578 count = 0
579 report = 0
580 no_report = 0
581 counts_file = None
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000582 missing = 0
583 ignore_modules = []
584 ignore_dirs = []
Jeremy Hylton66a7e572001-05-08 04:20:52 +0000585 coverdir = None
586 summary = 0
Guido van Rossuma30eacf2001-11-28 19:41:45 +0000587 listfuncs = false
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000588
589 for opt, val in opts:
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +0000590 if opt == "--help":
591 usage(sys.stdout)
592 sys.exit(0)
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000593
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +0000594 if opt == "--version":
595 sys.stdout.write("trace 2.0\n")
596 sys.exit(0)
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000597
Guido van Rossuma30eacf2001-11-28 19:41:45 +0000598 if opt == "-l" or opt == "--listfuncs":
599 listfuncs = true
600 continue
601
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +0000602 if opt == "-t" or opt == "--trace":
603 trace = 1
604 continue
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000605
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +0000606 if opt == "-c" or opt == "--count":
607 count = 1
608 continue
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000609
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +0000610 if opt == "-r" or opt == "--report":
611 report = 1
612 continue
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000613
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +0000614 if opt == "-R" or opt == "--no-report":
615 no_report = 1
616 continue
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000617
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +0000618 if opt == "-f" or opt == "--file":
619 counts_file = val
620 continue
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000621
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +0000622 if opt == "-m" or opt == "--missing":
623 missing = 1
624 continue
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000625
Jeremy Hylton66a7e572001-05-08 04:20:52 +0000626 if opt == "-C" or opt == "--coverdir":
627 coverdir = val
628 continue
629
630 if opt == "-s" or opt == "--summary":
631 summary = 1
632 continue
633
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +0000634 if opt == "--ignore-module":
635 ignore_modules.append(val)
636 continue
637
638 if opt == "--ignore-dir":
Walter Dörwaldaaab30e2002-09-11 20:36:02 +0000639 for s in val.split(os.pathsep):
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +0000640 s = os.path.expandvars(s)
641 # should I also call expanduser? (after all, could use $HOME)
642
Walter Dörwaldaaab30e2002-09-11 20:36:02 +0000643 s = s.replace("$prefix",
644 os.path.join(sys.prefix, "lib",
645 "python" + sys.version[:3]))
646 s = s.replace("$exec_prefix",
647 os.path.join(sys.exec_prefix, "lib",
648 "python" + sys.version[:3]))
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +0000649 s = os.path.normpath(s)
650 ignore_dirs.append(s)
651 continue
652
653 assert 0, "Should never get here"
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000654
Guido van Rossuma30eacf2001-11-28 19:41:45 +0000655 if listfuncs and (count or trace):
656 _err_exit("cannot specify both --listfuncs and (--trace or --count)")
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000657
Guido van Rossuma30eacf2001-11-28 19:41:45 +0000658 if not count and not trace and not report and not listfuncs:
659 _err_exit("must specify one of --trace, --count, --report or --listfuncs")
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000660
661 if report and no_report:
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +0000662 _err_exit("cannot specify both --report and --no-report")
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000663
Guido van Rossuma30eacf2001-11-28 19:41:45 +0000664 if report and not counts_file:
665 _err_exit("--report requires a --file")
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000666
Guido van Rossuma30eacf2001-11-28 19:41:45 +0000667 if no_report and len(prog_argv) == 0:
668 _err_exit("missing name of file to run")
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000669
670 # everything is ready
Guido van Rossuma30eacf2001-11-28 19:41:45 +0000671 if report:
672 results = CoverageResults(infile=counts_file, outfile=counts_file)
673 results.write_results(missing, summary=summary, coverdir=coverdir)
674 else:
675 sys.argv = prog_argv
676 progname = prog_argv[0]
677 if eval(sys.version[:3])>1.3:
678 sys.path[0] = os.path.split(progname)[0] # ???
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000679
Guido van Rossuma30eacf2001-11-28 19:41:45 +0000680 t = Trace(count, trace, countfuncs=listfuncs, ignoremods=ignore_modules, ignoredirs=ignore_dirs, infile=counts_file, outfile=counts_file)
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +0000681 try:
Guido van Rossuma30eacf2001-11-28 19:41:45 +0000682 t.run('execfile(' + `progname` + ')')
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +0000683 except IOError, err:
Guido van Rossuma30eacf2001-11-28 19:41:45 +0000684 _err_exit("Cannot run file %s because: %s" % (`sys.argv[0]`, err))
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +0000685 except SystemExit:
686 pass
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000687
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +0000688 results = t.results()
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000689
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +0000690 if not no_report:
Guido van Rossuma30eacf2001-11-28 19:41:45 +0000691 results.write_results(missing, summary=summary, coverdir=coverdir)
Jeremy Hyltonda1ec462000-08-03 19:26:21 +0000692
693if __name__=='__main__':
694 main()