blob: 7d504c1e3d6d87dc921b284550845b63f7c01cdc [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
Skip Montanaro5bfd9842004-04-10 16:29:58 +000035 trace.py --trackcalls spam.py eggs
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +000036
37Sample use, programmatically
Skip Montanaro7b1559a2006-04-23 19:32:14 +000038 import sys
39
40 # create a Trace object, telling it what to ignore, and whether to
41 # do tracing or line-counting or both.
42 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,], trace=0,
Tim Petersbe635cd2006-04-24 22:45:13 +000043 count=1)
Skip Montanaro7b1559a2006-04-23 19:32:14 +000044 # run the new command using the given tracer
45 tracer.run('main()')
46 # make a report, placing output in /tmp
47 r = tracer.results()
48 r.write_results(show_missing=True, coverdir="/tmp")
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +000049"""
50
Jeremy Hylton38732e12003-04-21 22:04:46 +000051import linecache
Jeremy Hylton38732e12003-04-21 22:04:46 +000052import os
53import re
54import sys
Jeremy Hylton546e34b2003-06-26 14:56:17 +000055import threading
Neal Norwitzca376612008-02-26 08:21:28 +000056import time
Jeremy Hylton38732e12003-04-21 22:04:46 +000057import token
58import tokenize
59import types
Skip Montanaro5bfd9842004-04-10 16:29:58 +000060import gc
Jeremy Hylton38732e12003-04-21 22:04:46 +000061
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +000062try:
63 import cPickle
64 pickle = cPickle
65except ImportError:
66 import pickle
67
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +000068def usage(outfile):
69 outfile.write("""Usage: %s [OPTIONS] <file> [ARGS]
70
71Meta-options:
72--help Display this help then exit.
73--version Output version information then exit.
74
75Otherwise, exactly one of the following three options must be given:
76-t, --trace Print each line to sys.stdout before it is executed.
77-c, --count Count the number of times each line is executed
78 and write the counts to <module>.cover for each
79 module executed, in the module's directory.
80 See also `--coverdir', `--file', `--no-report' below.
Skip Montanaroa7b8ac62003-06-27 19:09:33 +000081-l, --listfuncs Keep track of which functions are executed at least
Fred Drake01c623b2003-06-27 19:22:11 +000082 once and write the results to sys.stdout after the
Skip Montanaroa7b8ac62003-06-27 19:09:33 +000083 program exits.
Skip Montanarocafc8112004-04-07 15:46:05 +000084-T, --trackcalls Keep track of caller/called pairs and write the
85 results to sys.stdout after the program exits.
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +000086-r, --report Generate a report from a counts file; do not execute
87 any code. `--file' must specify the results file to
88 read, which must have been created in a previous run
89 with `--count --file=FILE'.
90
91Modifiers:
92-f, --file=<file> File to accumulate counts over several runs.
93-R, --no-report Do not generate the coverage report files.
94 Useful if you want to accumulate over several runs.
95-C, --coverdir=<dir> Directory where the report files. The coverage
96 report for <package>.<module> is written to file
97 <dir>/<package>/<module>.cover.
98-m, --missing Annotate executable lines that were not executed
99 with '>>>>>> '.
100-s, --summary Write a brief summary on stdout for each file.
101 (Can only be used with --count or --report.)
Neal Norwitzca376612008-02-26 08:21:28 +0000102-g, --timing Prefix each line with the time since the program started.
103 Only used while tracing.
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000104
105Filters, may be repeated multiple times:
Facundo Batista873c9852008-01-19 18:38:19 +0000106--ignore-module=<mod> Ignore the given module(s) and its submodules
107 (if it is a package). Accepts comma separated
108 list of module names
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000109--ignore-dir=<dir> Ignore files in the given directory (multiple
110 directories can be joined by os.pathsep).
111""" % sys.argv[0])
112
Jeremy Hylton38732e12003-04-21 22:04:46 +0000113PRAGMA_NOCOVER = "#pragma NO COVER"
114
115# Simple rx to find lines with no code.
116rx_blank = re.compile(r'^\s*(#.*)?$')
117
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000118class Ignore:
119 def __init__(self, modules = None, dirs = None):
120 self._mods = modules or []
121 self._dirs = dirs or []
122
123 self._dirs = map(os.path.normpath, self._dirs)
124 self._ignore = { '<string>': 1 }
125
126 def names(self, filename, modulename):
Benjamin Peterson6e3dbbd2009-10-09 22:15:50 +0000127 if modulename in self._ignore:
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000128 return self._ignore[modulename]
129
130 # haven't seen this one before, so see if the module name is
131 # on the ignore list. Need to take some care since ignoring
132 # "cmp" musn't mean ignoring "cmpcache" but ignoring
133 # "Spam" must also mean ignoring "Spam.Eggs".
134 for mod in self._mods:
135 if mod == modulename: # Identical names, so ignore
136 self._ignore[modulename] = 1
137 return 1
138 # check if the module is a proper submodule of something on
139 # the ignore list
140 n = len(mod)
141 # (will not overflow since if the first n characters are the
Fred Drakedb390c12005-10-28 14:39:47 +0000142 # same and the name has not already occurred, then the size
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000143 # of "name" is greater than that of "mod")
144 if mod == modulename[:n] and modulename[n] == '.':
145 self._ignore[modulename] = 1
146 return 1
147
148 # Now check that __file__ isn't in one of the directories
149 if filename is None:
150 # must be a built-in, so we must ignore
151 self._ignore[modulename] = 1
152 return 1
153
154 # Ignore a file when it contains one of the ignorable paths
155 for d in self._dirs:
156 # The '+ os.sep' is to ensure that d is a parent directory,
157 # as compared to cases like:
158 # d = "/usr/local"
159 # filename = "/usr/local.py"
160 # or
161 # d = "/usr/local.py"
162 # filename = "/usr/local.py"
163 if filename.startswith(d + os.sep):
164 self._ignore[modulename] = 1
165 return 1
166
167 # Tried the different ways, so we don't ignore this module
168 self._ignore[modulename] = 0
169 return 0
170
Jeremy Hylton38732e12003-04-21 22:04:46 +0000171def modname(path):
172 """Return a plausible module name for the patch."""
Jeremy Hyltondfbfe732003-04-21 22:49:17 +0000173
Jeremy Hylton38732e12003-04-21 22:04:46 +0000174 base = os.path.basename(path)
175 filename, ext = os.path.splitext(base)
176 return filename
177
Jeremy Hyltondfbfe732003-04-21 22:49:17 +0000178def fullmodname(path):
Jeremy Hyltonc8c8b942003-04-22 15:35:51 +0000179 """Return a plausible module name for the path."""
Jeremy Hyltondfbfe732003-04-21 22:49:17 +0000180
181 # If the file 'path' is part of a package, then the filename isn't
182 # enough to uniquely identify it. Try to do the right thing by
183 # looking in sys.path for the longest matching prefix. We'll
184 # assume that the rest is the package name.
185
Georg Brandl7a1af772006-08-14 21:55:28 +0000186 comparepath = os.path.normcase(path)
Jeremy Hyltondfbfe732003-04-21 22:49:17 +0000187 longest = ""
188 for dir in sys.path:
Georg Brandl7a1af772006-08-14 21:55:28 +0000189 dir = os.path.normcase(dir)
190 if comparepath.startswith(dir) and comparepath[len(dir)] == os.sep:
Jeremy Hyltondfbfe732003-04-21 22:49:17 +0000191 if len(dir) > len(longest):
192 longest = dir
193
Guido van Rossumb427c002003-10-10 23:02:01 +0000194 if longest:
195 base = path[len(longest) + 1:]
196 else:
197 base = path
Guido van Rossumbbca8da2004-02-19 19:16:50 +0000198 base = base.replace(os.sep, ".")
199 if os.altsep:
200 base = base.replace(os.altsep, ".")
Jeremy Hyltondfbfe732003-04-21 22:49:17 +0000201 filename, ext = os.path.splitext(base)
202 return filename
203
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000204class CoverageResults:
205 def __init__(self, counts=None, calledfuncs=None, infile=None,
Skip Montanarocafc8112004-04-07 15:46:05 +0000206 callers=None, outfile=None):
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000207 self.counts = counts
208 if self.counts is None:
209 self.counts = {}
210 self.counter = self.counts.copy() # map (filename, lineno) to count
211 self.calledfuncs = calledfuncs
212 if self.calledfuncs is None:
213 self.calledfuncs = {}
214 self.calledfuncs = self.calledfuncs.copy()
Skip Montanarocafc8112004-04-07 15:46:05 +0000215 self.callers = callers
216 if self.callers is None:
217 self.callers = {}
218 self.callers = self.callers.copy()
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000219 self.infile = infile
220 self.outfile = outfile
221 if self.infile:
Jeremy Hyltond7ce86d2003-07-07 16:08:47 +0000222 # Try to merge existing counts file.
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000223 try:
Skip Montanarocafc8112004-04-07 15:46:05 +0000224 counts, calledfuncs, callers = \
225 pickle.load(open(self.infile, 'rb'))
226 self.update(self.__class__(counts, calledfuncs, callers))
Jeremy Hyltond7ce86d2003-07-07 16:08:47 +0000227 except (IOError, EOFError, ValueError), err:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000228 print >> sys.stderr, ("Skipping counts file %r: %s"
229 % (self.infile, err))
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000230
231 def update(self, other):
232 """Merge in the data from another CoverageResults"""
233 counts = self.counts
234 calledfuncs = self.calledfuncs
Skip Montanarocafc8112004-04-07 15:46:05 +0000235 callers = self.callers
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000236 other_counts = other.counts
237 other_calledfuncs = other.calledfuncs
Skip Montanarocafc8112004-04-07 15:46:05 +0000238 other_callers = other.callers
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000239
240 for key in other_counts.keys():
Jeremy Hylton38732e12003-04-21 22:04:46 +0000241 counts[key] = counts.get(key, 0) + other_counts[key]
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000242
243 for key in other_calledfuncs.keys():
244 calledfuncs[key] = 1
245
Skip Montanarocafc8112004-04-07 15:46:05 +0000246 for key in other_callers.keys():
247 callers[key] = 1
248
Jeremy Hylton38732e12003-04-21 22:04:46 +0000249 def write_results(self, show_missing=True, summary=False, coverdir=None):
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000250 """
251 @param coverdir
252 """
Skip Montanarocafc8112004-04-07 15:46:05 +0000253 if self.calledfuncs:
Skip Montanaro5bfd9842004-04-10 16:29:58 +0000254 print
Skip Montanarocafc8112004-04-07 15:46:05 +0000255 print "functions called:"
256 calls = self.calledfuncs.keys()
257 calls.sort()
258 for filename, modulename, funcname in calls:
259 print ("filename: %s, modulename: %s, funcname: %s"
260 % (filename, modulename, funcname))
261
262 if self.callers:
Skip Montanaro5bfd9842004-04-10 16:29:58 +0000263 print
Skip Montanarocafc8112004-04-07 15:46:05 +0000264 print "calling relationships:"
265 calls = self.callers.keys()
266 calls.sort()
267 lastfile = lastcfile = ""
268 for ((pfile, pmod, pfunc), (cfile, cmod, cfunc)) in calls:
269 if pfile != lastfile:
Skip Montanaro5bfd9842004-04-10 16:29:58 +0000270 print
Skip Montanarocafc8112004-04-07 15:46:05 +0000271 print "***", pfile, "***"
272 lastfile = pfile
273 lastcfile = ""
274 if cfile != pfile and lastcfile != cfile:
275 print " -->", cfile
276 lastcfile = cfile
277 print " %s.%s -> %s.%s" % (pmod, pfunc, cmod, cfunc)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000278
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000279 # turn the counts data ("(filename, lineno) = count") into something
280 # accessible on a per-file basis
281 per_file = {}
Jeremy Hylton38732e12003-04-21 22:04:46 +0000282 for filename, lineno in self.counts.keys():
283 lines_hit = per_file[filename] = per_file.get(filename, {})
284 lines_hit[lineno] = self.counts[(filename, lineno)]
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000285
286 # accumulate summary info, if needed
287 sums = {}
288
Jeremy Hylton38732e12003-04-21 22:04:46 +0000289 for filename, count in per_file.iteritems():
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000290 # skip some "files" we don't care about...
291 if filename == "<string>":
292 continue
Skip Montanaro58a6f442007-11-24 14:30:47 +0000293 if filename.startswith("<doctest "):
294 continue
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000295
Georg Brandlb2afe852006-06-09 20:43:48 +0000296 if filename.endswith((".pyc", ".pyo")):
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000297 filename = filename[:-1]
298
Jeremy Hylton38732e12003-04-21 22:04:46 +0000299 if coverdir is None:
300 dir = os.path.dirname(os.path.abspath(filename))
Jeremy Hyltonc8c8b942003-04-22 15:35:51 +0000301 modulename = modname(filename)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000302 else:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000303 dir = coverdir
304 if not os.path.exists(dir):
305 os.makedirs(dir)
Jeremy Hyltonc8c8b942003-04-22 15:35:51 +0000306 modulename = fullmodname(filename)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000307
308 # If desired, get a list of the line numbers which represent
309 # executable content (returned as a dict for better lookup speed)
310 if show_missing:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000311 lnotab = find_executable_linenos(filename)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000312 else:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000313 lnotab = {}
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000314
Jeremy Hylton38732e12003-04-21 22:04:46 +0000315 source = linecache.getlines(filename)
316 coverpath = os.path.join(dir, modulename + ".cover")
317 n_hits, n_lines = self.write_results_file(coverpath, source,
318 lnotab, count)
Tim Peters0eadaac2003-04-24 16:02:54 +0000319
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000320 if summary and n_lines:
321 percent = int(100 * n_hits / n_lines)
322 sums[modulename] = n_lines, percent, modulename, filename
323
324 if summary and sums:
325 mods = sums.keys()
326 mods.sort()
327 print "lines cov% module (path)"
328 for m in mods:
329 n_lines, percent, modulename, filename = sums[m]
330 print "%5d %3d%% %s (%s)" % sums[m]
331
332 if self.outfile:
333 # try and store counts and module info into self.outfile
334 try:
Skip Montanarocafc8112004-04-07 15:46:05 +0000335 pickle.dump((self.counts, self.calledfuncs, self.callers),
Jeremy Hyltond0e27052003-10-14 20:12:06 +0000336 open(self.outfile, 'wb'), 1)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000337 except IOError, err:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000338 print >> sys.stderr, "Can't save counts files because %s" % err
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000339
Jeremy Hylton38732e12003-04-21 22:04:46 +0000340 def write_results_file(self, path, lines, lnotab, lines_hit):
341 """Return a coverage results file in path."""
342
343 try:
344 outfile = open(path, "w")
345 except IOError, err:
346 print >> sys.stderr, ("trace: Could not open %r for writing: %s"
347 "- skipping" % (path, err))
Guido van Rossumbbca8da2004-02-19 19:16:50 +0000348 return 0, 0
Jeremy Hylton38732e12003-04-21 22:04:46 +0000349
350 n_lines = 0
351 n_hits = 0
352 for i, line in enumerate(lines):
353 lineno = i + 1
354 # do the blank/comment match to try to mark more lines
355 # (help the reader find stuff that hasn't been covered)
356 if lineno in lines_hit:
357 outfile.write("%5d: " % lines_hit[lineno])
358 n_hits += 1
359 n_lines += 1
360 elif rx_blank.match(line):
Walter Dörwaldc1711722003-07-15 10:34:02 +0000361 outfile.write(" ")
Jeremy Hylton38732e12003-04-21 22:04:46 +0000362 else:
363 # lines preceded by no marks weren't hit
364 # Highlight them if so indicated, unless the line contains
365 # #pragma: NO COVER
366 if lineno in lnotab and not PRAGMA_NOCOVER in lines[i]:
367 outfile.write(">>>>>> ")
Jeremy Hylton546e34b2003-06-26 14:56:17 +0000368 n_lines += 1
Jeremy Hylton38732e12003-04-21 22:04:46 +0000369 else:
370 outfile.write(" ")
Jeremy Hylton38732e12003-04-21 22:04:46 +0000371 outfile.write(lines[i].expandtabs(8))
372 outfile.close()
373
374 return n_hits, n_lines
375
376def find_lines_from_code(code, strs):
377 """Return dict where keys are lines in the line number table."""
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000378 linenos = {}
379
380 line_increments = [ord(c) for c in code.co_lnotab[1::2]]
381 table_length = len(line_increments)
Jeremy Hylton38732e12003-04-21 22:04:46 +0000382 docstring = False
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000383
384 lineno = code.co_firstlineno
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000385 for li in line_increments:
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000386 lineno += li
Jeremy Hylton38732e12003-04-21 22:04:46 +0000387 if lineno not in strs:
388 linenos[lineno] = 1
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000389
390 return linenos
391
Jeremy Hylton38732e12003-04-21 22:04:46 +0000392def find_lines(code, strs):
393 """Return lineno dict for all code objects reachable from code."""
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000394 # get all of the lineno information from the code of this scope level
Jeremy Hylton38732e12003-04-21 22:04:46 +0000395 linenos = find_lines_from_code(code, strs)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000396
397 # and check the constants for references to other code objects
398 for c in code.co_consts:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000399 if isinstance(c, types.CodeType):
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000400 # find another code object, so recurse into it
Jeremy Hylton38732e12003-04-21 22:04:46 +0000401 linenos.update(find_lines(c, strs))
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000402 return linenos
403
Jeremy Hylton38732e12003-04-21 22:04:46 +0000404def find_strings(filename):
405 """Return a dict of possible docstring positions.
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000406
Jeremy Hylton38732e12003-04-21 22:04:46 +0000407 The dict maps line numbers to strings. There is an entry for
408 line that contains only a string or a part of a triple-quoted
409 string.
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000410 """
Jeremy Hylton38732e12003-04-21 22:04:46 +0000411 d = {}
412 # If the first token is a string, then it's the module docstring.
413 # Add this special case so that the test in the loop passes.
414 prev_ttype = token.INDENT
415 f = open(filename)
416 for ttype, tstr, start, end, line in tokenize.generate_tokens(f.readline):
417 if ttype == token.STRING:
418 if prev_ttype == token.INDENT:
419 sline, scol = start
420 eline, ecol = end
421 for i in range(sline, eline + 1):
422 d[i] = 1
423 prev_ttype = ttype
424 f.close()
425 return d
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000426
Jeremy Hylton38732e12003-04-21 22:04:46 +0000427def find_executable_linenos(filename):
428 """Return dict where keys are line numbers in the line number table."""
Jeremy Hylton38732e12003-04-21 22:04:46 +0000429 try:
Skip Montanaroc00fc842004-04-16 03:28:19 +0000430 prog = open(filename, "rU").read()
Jeremy Hylton38732e12003-04-21 22:04:46 +0000431 except IOError, err:
432 print >> sys.stderr, ("Not printing coverage data for %r: %s"
433 % (filename, err))
434 return {}
435 code = compile(prog, filename, "exec")
436 strs = find_strings(filename)
437 return find_lines(code, strs)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000438
439class Trace:
Skip Montanarocafc8112004-04-07 15:46:05 +0000440 def __init__(self, count=1, trace=1, countfuncs=0, countcallers=0,
Neal Norwitzca376612008-02-26 08:21:28 +0000441 ignoremods=(), ignoredirs=(), infile=None, outfile=None,
442 timing=False):
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000443 """
444 @param count true iff it should count number of times each
Tim Petersf2715e02003-02-19 02:35:07 +0000445 line is executed
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000446 @param trace true iff it should print out each line that is
Tim Petersf2715e02003-02-19 02:35:07 +0000447 being counted
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000448 @param countfuncs true iff it should just output a list of
449 (filename, modulename, funcname,) for functions
450 that were called at least once; This overrides
Tim Petersf2715e02003-02-19 02:35:07 +0000451 `count' and `trace'
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000452 @param ignoremods a list of the names of modules to ignore
453 @param ignoredirs a list of the names of directories to ignore
Tim Petersf2715e02003-02-19 02:35:07 +0000454 all of the (recursive) contents of
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000455 @param infile file from which to read stored counts to be
Tim Petersf2715e02003-02-19 02:35:07 +0000456 added into the results
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000457 @param outfile file in which to write the results
Neal Norwitzca376612008-02-26 08:21:28 +0000458 @param timing true iff timing information be displayed
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000459 """
460 self.infile = infile
461 self.outfile = outfile
462 self.ignore = Ignore(ignoremods, ignoredirs)
463 self.counts = {} # keys are (filename, linenumber)
464 self.blabbed = {} # for debugging
465 self.pathtobasename = {} # for memoizing os.path.basename
466 self.donothing = 0
467 self.trace = trace
468 self._calledfuncs = {}
Skip Montanarocafc8112004-04-07 15:46:05 +0000469 self._callers = {}
Skip Montanaro5bfd9842004-04-10 16:29:58 +0000470 self._caller_cache = {}
Neal Norwitzca376612008-02-26 08:21:28 +0000471 self.start_time = None
472 if timing:
473 self.start_time = time.time()
Skip Montanarocafc8112004-04-07 15:46:05 +0000474 if countcallers:
475 self.globaltrace = self.globaltrace_trackcallers
476 elif countfuncs:
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000477 self.globaltrace = self.globaltrace_countfuncs
478 elif trace and count:
479 self.globaltrace = self.globaltrace_lt
480 self.localtrace = self.localtrace_trace_and_count
481 elif trace:
482 self.globaltrace = self.globaltrace_lt
483 self.localtrace = self.localtrace_trace
484 elif count:
485 self.globaltrace = self.globaltrace_lt
486 self.localtrace = self.localtrace_count
487 else:
488 # Ahem -- do nothing? Okay.
489 self.donothing = 1
490
491 def run(self, cmd):
492 import __main__
493 dict = __main__.__dict__
494 if not self.donothing:
495 sys.settrace(self.globaltrace)
Jeremy Hylton546e34b2003-06-26 14:56:17 +0000496 threading.settrace(self.globaltrace)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000497 try:
498 exec cmd in dict, dict
499 finally:
500 if not self.donothing:
501 sys.settrace(None)
Jeremy Hylton546e34b2003-06-26 14:56:17 +0000502 threading.settrace(None)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000503
504 def runctx(self, cmd, globals=None, locals=None):
505 if globals is None: globals = {}
506 if locals is None: locals = {}
507 if not self.donothing:
508 sys.settrace(self.globaltrace)
Jeremy Hylton546e34b2003-06-26 14:56:17 +0000509 threading.settrace(self.globaltrace)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000510 try:
511 exec cmd in globals, locals
512 finally:
513 if not self.donothing:
514 sys.settrace(None)
Jeremy Hylton546e34b2003-06-26 14:56:17 +0000515 threading.settrace(None)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000516
517 def runfunc(self, func, *args, **kw):
518 result = None
519 if not self.donothing:
520 sys.settrace(self.globaltrace)
521 try:
Guido van Rossum68468eb2003-02-27 20:14:51 +0000522 result = func(*args, **kw)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000523 finally:
524 if not self.donothing:
525 sys.settrace(None)
526 return result
527
Skip Montanaro5bfd9842004-04-10 16:29:58 +0000528 def file_module_function_of(self, frame):
529 code = frame.f_code
530 filename = code.co_filename
531 if filename:
532 modulename = modname(filename)
533 else:
534 modulename = None
535
536 funcname = code.co_name
537 clsname = None
538 if code in self._caller_cache:
539 if self._caller_cache[code] is not None:
540 clsname = self._caller_cache[code]
541 else:
542 self._caller_cache[code] = None
543 ## use of gc.get_referrers() was suggested by Michael Hudson
544 # all functions which refer to this code object
545 funcs = [f for f in gc.get_referrers(code)
546 if hasattr(f, "func_doc")]
547 # require len(func) == 1 to avoid ambiguity caused by calls to
548 # new.function(): "In the face of ambiguity, refuse the
549 # temptation to guess."
550 if len(funcs) == 1:
551 dicts = [d for d in gc.get_referrers(funcs[0])
552 if isinstance(d, dict)]
553 if len(dicts) == 1:
554 classes = [c for c in gc.get_referrers(dicts[0])
555 if hasattr(c, "__bases__")]
556 if len(classes) == 1:
557 # ditto for new.classobj()
558 clsname = str(classes[0])
559 # cache the result - assumption is that new.* is
560 # not called later to disturb this relationship
561 # _caller_cache could be flushed if functions in
562 # the new module get called.
563 self._caller_cache[code] = clsname
564 if clsname is not None:
565 # final hack - module name shows up in str(cls), but we've already
566 # computed module name, so remove it
567 clsname = clsname.split(".")[1:]
568 clsname = ".".join(clsname)
569 funcname = "%s.%s" % (clsname, funcname)
570
571 return filename, modulename, funcname
572
Skip Montanarocafc8112004-04-07 15:46:05 +0000573 def globaltrace_trackcallers(self, frame, why, arg):
574 """Handler for call events.
575
576 Adds information about who called who to the self._callers dict.
577 """
578 if why == 'call':
579 # XXX Should do a better job of identifying methods
Skip Montanaro5bfd9842004-04-10 16:29:58 +0000580 this_func = self.file_module_function_of(frame)
581 parent_func = self.file_module_function_of(frame.f_back)
Skip Montanarocafc8112004-04-07 15:46:05 +0000582 self._callers[(parent_func, this_func)] = 1
583
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000584 def globaltrace_countfuncs(self, frame, why, arg):
Jeremy Hylton38732e12003-04-21 22:04:46 +0000585 """Handler for call events.
Tim Peters0eadaac2003-04-24 16:02:54 +0000586
Jeremy Hylton38732e12003-04-21 22:04:46 +0000587 Adds (filename, modulename, funcname) to the self._calledfuncs dict.
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000588 """
589 if why == 'call':
Skip Montanaro5bfd9842004-04-10 16:29:58 +0000590 this_func = self.file_module_function_of(frame)
591 self._calledfuncs[this_func] = 1
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000592
593 def globaltrace_lt(self, frame, why, arg):
Jeremy Hylton38732e12003-04-21 22:04:46 +0000594 """Handler for call events.
595
596 If the code block being entered is to be ignored, returns `None',
597 else returns self.localtrace.
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000598 """
599 if why == 'call':
Jeremy Hylton38732e12003-04-21 22:04:46 +0000600 code = frame.f_code
Skip Montanaro691acf22007-02-11 18:24:37 +0000601 filename = frame.f_globals.get('__file__', None)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000602 if filename:
Jeremy Hyltondfbfe732003-04-21 22:49:17 +0000603 # XXX modname() doesn't work right for packages, so
604 # the ignore support won't work right for packages
Jeremy Hylton38732e12003-04-21 22:04:46 +0000605 modulename = modname(filename)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000606 if modulename is not None:
607 ignore_it = self.ignore.names(filename, modulename)
608 if not ignore_it:
609 if self.trace:
610 print (" --- modulename: %s, funcname: %s"
Jeremy Hylton38732e12003-04-21 22:04:46 +0000611 % (modulename, code.co_name))
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000612 return self.localtrace
613 else:
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000614 return None
615
616 def localtrace_trace_and_count(self, frame, why, arg):
Jeremy Hylton38732e12003-04-21 22:04:46 +0000617 if why == "line":
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000618 # record the file name and line number of every trace
Jeremy Hylton38732e12003-04-21 22:04:46 +0000619 filename = frame.f_code.co_filename
620 lineno = frame.f_lineno
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000621 key = filename, lineno
622 self.counts[key] = self.counts.get(key, 0) + 1
Tim Petersf2715e02003-02-19 02:35:07 +0000623
Neal Norwitzca376612008-02-26 08:21:28 +0000624 if self.start_time:
625 print '%.2f' % (time.time() - self.start_time),
Jeremy Hylton38732e12003-04-21 22:04:46 +0000626 bname = os.path.basename(filename)
627 print "%s(%d): %s" % (bname, lineno,
628 linecache.getline(filename, lineno)),
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000629 return self.localtrace
630
631 def localtrace_trace(self, frame, why, arg):
Jeremy Hylton38732e12003-04-21 22:04:46 +0000632 if why == "line":
633 # record the file name and line number of every trace
634 filename = frame.f_code.co_filename
635 lineno = frame.f_lineno
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000636
Neal Norwitzca376612008-02-26 08:21:28 +0000637 if self.start_time:
638 print '%.2f' % (time.time() - self.start_time),
Jeremy Hylton38732e12003-04-21 22:04:46 +0000639 bname = os.path.basename(filename)
640 print "%s(%d): %s" % (bname, lineno,
641 linecache.getline(filename, lineno)),
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000642 return self.localtrace
643
644 def localtrace_count(self, frame, why, arg):
Jeremy Hylton38732e12003-04-21 22:04:46 +0000645 if why == "line":
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000646 filename = frame.f_code.co_filename
647 lineno = frame.f_lineno
648 key = filename, lineno
649 self.counts[key] = self.counts.get(key, 0) + 1
650 return self.localtrace
651
652 def results(self):
653 return CoverageResults(self.counts, infile=self.infile,
654 outfile=self.outfile,
Skip Montanarocafc8112004-04-07 15:46:05 +0000655 calledfuncs=self._calledfuncs,
656 callers=self._callers)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000657
658def _err_exit(msg):
659 sys.stderr.write("%s: %s\n" % (sys.argv[0], msg))
660 sys.exit(1)
661
662def main(argv=None):
663 import getopt
664
665 if argv is None:
666 argv = sys.argv
667 try:
Neal Norwitzca376612008-02-26 08:21:28 +0000668 opts, prog_argv = getopt.getopt(argv[1:], "tcrRf:d:msC:lTg",
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000669 ["help", "version", "trace", "count",
670 "report", "no-report", "summary",
671 "file=", "missing",
672 "ignore-module=", "ignore-dir=",
Skip Montanarocafc8112004-04-07 15:46:05 +0000673 "coverdir=", "listfuncs",
Neal Norwitzca376612008-02-26 08:21:28 +0000674 "trackcalls", "timing"])
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000675
676 except getopt.error, msg:
677 sys.stderr.write("%s: %s\n" % (sys.argv[0], msg))
678 sys.stderr.write("Try `%s --help' for more information\n"
679 % sys.argv[0])
680 sys.exit(1)
681
682 trace = 0
683 count = 0
684 report = 0
685 no_report = 0
686 counts_file = None
687 missing = 0
688 ignore_modules = []
689 ignore_dirs = []
690 coverdir = None
691 summary = 0
692 listfuncs = False
Skip Montanarocafc8112004-04-07 15:46:05 +0000693 countcallers = False
Neal Norwitzca376612008-02-26 08:21:28 +0000694 timing = False
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000695
696 for opt, val in opts:
697 if opt == "--help":
698 usage(sys.stdout)
699 sys.exit(0)
700
701 if opt == "--version":
702 sys.stdout.write("trace 2.0\n")
703 sys.exit(0)
704
Skip Montanarocafc8112004-04-07 15:46:05 +0000705 if opt == "-T" or opt == "--trackcalls":
706 countcallers = True
707 continue
708
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000709 if opt == "-l" or opt == "--listfuncs":
710 listfuncs = True
711 continue
712
Neal Norwitzca376612008-02-26 08:21:28 +0000713 if opt == "-g" or opt == "--timing":
714 timing = True
715 continue
716
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000717 if opt == "-t" or opt == "--trace":
718 trace = 1
719 continue
720
721 if opt == "-c" or opt == "--count":
722 count = 1
723 continue
724
725 if opt == "-r" or opt == "--report":
726 report = 1
727 continue
728
729 if opt == "-R" or opt == "--no-report":
730 no_report = 1
731 continue
732
733 if opt == "-f" or opt == "--file":
734 counts_file = val
735 continue
736
737 if opt == "-m" or opt == "--missing":
738 missing = 1
739 continue
740
741 if opt == "-C" or opt == "--coverdir":
742 coverdir = val
743 continue
744
745 if opt == "-s" or opt == "--summary":
746 summary = 1
747 continue
748
749 if opt == "--ignore-module":
Facundo Batista873c9852008-01-19 18:38:19 +0000750 for mod in val.split(","):
751 ignore_modules.append(mod.strip())
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000752 continue
753
754 if opt == "--ignore-dir":
755 for s in val.split(os.pathsep):
756 s = os.path.expandvars(s)
757 # should I also call expanduser? (after all, could use $HOME)
758
759 s = s.replace("$prefix",
760 os.path.join(sys.prefix, "lib",
761 "python" + sys.version[:3]))
762 s = s.replace("$exec_prefix",
763 os.path.join(sys.exec_prefix, "lib",
764 "python" + sys.version[:3]))
765 s = os.path.normpath(s)
766 ignore_dirs.append(s)
767 continue
768
769 assert 0, "Should never get here"
770
771 if listfuncs and (count or trace):
772 _err_exit("cannot specify both --listfuncs and (--trace or --count)")
773
Skip Montanarocafc8112004-04-07 15:46:05 +0000774 if not (count or trace or report or listfuncs or countcallers):
775 _err_exit("must specify one of --trace, --count, --report, "
776 "--listfuncs, or --trackcalls")
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000777
778 if report and no_report:
779 _err_exit("cannot specify both --report and --no-report")
780
781 if report and not counts_file:
782 _err_exit("--report requires a --file")
783
784 if no_report and len(prog_argv) == 0:
785 _err_exit("missing name of file to run")
786
787 # everything is ready
788 if report:
789 results = CoverageResults(infile=counts_file, outfile=counts_file)
790 results.write_results(missing, summary=summary, coverdir=coverdir)
791 else:
792 sys.argv = prog_argv
793 progname = prog_argv[0]
794 sys.path[0] = os.path.split(progname)[0]
795
796 t = Trace(count, trace, countfuncs=listfuncs,
Skip Montanarocafc8112004-04-07 15:46:05 +0000797 countcallers=countcallers, ignoremods=ignore_modules,
798 ignoredirs=ignore_dirs, infile=counts_file,
Neal Norwitzca376612008-02-26 08:21:28 +0000799 outfile=counts_file, timing=timing)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000800 try:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000801 t.run('execfile(%r)' % (progname,))
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000802 except IOError, err:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000803 _err_exit("Cannot run file %r because: %s" % (sys.argv[0], err))
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000804 except SystemExit:
805 pass
806
807 results = t.results()
808
809 if not no_report:
810 results.write_results(missing, summary=summary, coverdir=coverdir)
811
812if __name__=='__main__':
813 main()