blob: 12e1b492072729c052b336354ede258b086769b7 [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
Alexander Belopolsky9d17da32010-09-13 16:45:02 +000059import inspect
Skip Montanaro5bfd9842004-04-10 16:29:58 +000060import gc
Alexander Belopolsky517185e2010-09-24 18:14:18 +000061import dis
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
Georg Brandl78e69572010-08-01 18:52:52 +0000198 # the drive letter is never part of the module name
199 drive, base = os.path.splitdrive(base)
Guido van Rossumbbca8da2004-02-19 19:16:50 +0000200 base = base.replace(os.sep, ".")
201 if os.altsep:
202 base = base.replace(os.altsep, ".")
Jeremy Hyltondfbfe732003-04-21 22:49:17 +0000203 filename, ext = os.path.splitext(base)
Georg Brandl78e69572010-08-01 18:52:52 +0000204 return filename.lstrip(".")
Jeremy Hyltondfbfe732003-04-21 22:49:17 +0000205
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000206class CoverageResults:
207 def __init__(self, counts=None, calledfuncs=None, infile=None,
Skip Montanarocafc8112004-04-07 15:46:05 +0000208 callers=None, outfile=None):
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000209 self.counts = counts
210 if self.counts is None:
211 self.counts = {}
212 self.counter = self.counts.copy() # map (filename, lineno) to count
213 self.calledfuncs = calledfuncs
214 if self.calledfuncs is None:
215 self.calledfuncs = {}
216 self.calledfuncs = self.calledfuncs.copy()
Skip Montanarocafc8112004-04-07 15:46:05 +0000217 self.callers = callers
218 if self.callers is None:
219 self.callers = {}
220 self.callers = self.callers.copy()
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000221 self.infile = infile
222 self.outfile = outfile
223 if self.infile:
Jeremy Hyltond7ce86d2003-07-07 16:08:47 +0000224 # Try to merge existing counts file.
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000225 try:
Skip Montanarocafc8112004-04-07 15:46:05 +0000226 counts, calledfuncs, callers = \
227 pickle.load(open(self.infile, 'rb'))
228 self.update(self.__class__(counts, calledfuncs, callers))
Jeremy Hyltond7ce86d2003-07-07 16:08:47 +0000229 except (IOError, EOFError, ValueError), err:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000230 print >> sys.stderr, ("Skipping counts file %r: %s"
231 % (self.infile, err))
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000232
233 def update(self, other):
234 """Merge in the data from another CoverageResults"""
235 counts = self.counts
236 calledfuncs = self.calledfuncs
Skip Montanarocafc8112004-04-07 15:46:05 +0000237 callers = self.callers
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000238 other_counts = other.counts
239 other_calledfuncs = other.calledfuncs
Skip Montanarocafc8112004-04-07 15:46:05 +0000240 other_callers = other.callers
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000241
242 for key in other_counts.keys():
Jeremy Hylton38732e12003-04-21 22:04:46 +0000243 counts[key] = counts.get(key, 0) + other_counts[key]
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000244
245 for key in other_calledfuncs.keys():
246 calledfuncs[key] = 1
247
Skip Montanarocafc8112004-04-07 15:46:05 +0000248 for key in other_callers.keys():
249 callers[key] = 1
250
Jeremy Hylton38732e12003-04-21 22:04:46 +0000251 def write_results(self, show_missing=True, summary=False, coverdir=None):
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000252 """
253 @param coverdir
254 """
Skip Montanarocafc8112004-04-07 15:46:05 +0000255 if self.calledfuncs:
Skip Montanaro5bfd9842004-04-10 16:29:58 +0000256 print
Skip Montanarocafc8112004-04-07 15:46:05 +0000257 print "functions called:"
258 calls = self.calledfuncs.keys()
259 calls.sort()
260 for filename, modulename, funcname in calls:
261 print ("filename: %s, modulename: %s, funcname: %s"
262 % (filename, modulename, funcname))
263
264 if self.callers:
Skip Montanaro5bfd9842004-04-10 16:29:58 +0000265 print
Skip Montanarocafc8112004-04-07 15:46:05 +0000266 print "calling relationships:"
267 calls = self.callers.keys()
268 calls.sort()
269 lastfile = lastcfile = ""
270 for ((pfile, pmod, pfunc), (cfile, cmod, cfunc)) in calls:
271 if pfile != lastfile:
Skip Montanaro5bfd9842004-04-10 16:29:58 +0000272 print
Skip Montanarocafc8112004-04-07 15:46:05 +0000273 print "***", pfile, "***"
274 lastfile = pfile
275 lastcfile = ""
276 if cfile != pfile and lastcfile != cfile:
277 print " -->", cfile
278 lastcfile = cfile
279 print " %s.%s -> %s.%s" % (pmod, pfunc, cmod, cfunc)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000280
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000281 # turn the counts data ("(filename, lineno) = count") into something
282 # accessible on a per-file basis
283 per_file = {}
Jeremy Hylton38732e12003-04-21 22:04:46 +0000284 for filename, lineno in self.counts.keys():
285 lines_hit = per_file[filename] = per_file.get(filename, {})
286 lines_hit[lineno] = self.counts[(filename, lineno)]
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000287
288 # accumulate summary info, if needed
289 sums = {}
290
Jeremy Hylton38732e12003-04-21 22:04:46 +0000291 for filename, count in per_file.iteritems():
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000292 # skip some "files" we don't care about...
293 if filename == "<string>":
294 continue
Skip Montanaro58a6f442007-11-24 14:30:47 +0000295 if filename.startswith("<doctest "):
296 continue
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000297
Georg Brandlb2afe852006-06-09 20:43:48 +0000298 if filename.endswith((".pyc", ".pyo")):
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000299 filename = filename[:-1]
300
Jeremy Hylton38732e12003-04-21 22:04:46 +0000301 if coverdir is None:
302 dir = os.path.dirname(os.path.abspath(filename))
Jeremy Hyltonc8c8b942003-04-22 15:35:51 +0000303 modulename = modname(filename)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000304 else:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000305 dir = coverdir
306 if not os.path.exists(dir):
307 os.makedirs(dir)
Jeremy Hyltonc8c8b942003-04-22 15:35:51 +0000308 modulename = fullmodname(filename)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000309
310 # If desired, get a list of the line numbers which represent
311 # executable content (returned as a dict for better lookup speed)
312 if show_missing:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000313 lnotab = find_executable_linenos(filename)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000314 else:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000315 lnotab = {}
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000316
Jeremy Hylton38732e12003-04-21 22:04:46 +0000317 source = linecache.getlines(filename)
318 coverpath = os.path.join(dir, modulename + ".cover")
319 n_hits, n_lines = self.write_results_file(coverpath, source,
320 lnotab, count)
Tim Peters0eadaac2003-04-24 16:02:54 +0000321
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000322 if summary and n_lines:
323 percent = int(100 * n_hits / n_lines)
324 sums[modulename] = n_lines, percent, modulename, filename
325
326 if summary and sums:
327 mods = sums.keys()
328 mods.sort()
329 print "lines cov% module (path)"
330 for m in mods:
331 n_lines, percent, modulename, filename = sums[m]
332 print "%5d %3d%% %s (%s)" % sums[m]
333
334 if self.outfile:
335 # try and store counts and module info into self.outfile
336 try:
Skip Montanarocafc8112004-04-07 15:46:05 +0000337 pickle.dump((self.counts, self.calledfuncs, self.callers),
Jeremy Hyltond0e27052003-10-14 20:12:06 +0000338 open(self.outfile, 'wb'), 1)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000339 except IOError, err:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000340 print >> sys.stderr, "Can't save counts files because %s" % err
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000341
Jeremy Hylton38732e12003-04-21 22:04:46 +0000342 def write_results_file(self, path, lines, lnotab, lines_hit):
343 """Return a coverage results file in path."""
344
345 try:
346 outfile = open(path, "w")
347 except IOError, err:
348 print >> sys.stderr, ("trace: Could not open %r for writing: %s"
349 "- skipping" % (path, err))
Guido van Rossumbbca8da2004-02-19 19:16:50 +0000350 return 0, 0
Jeremy Hylton38732e12003-04-21 22:04:46 +0000351
352 n_lines = 0
353 n_hits = 0
354 for i, line in enumerate(lines):
355 lineno = i + 1
356 # do the blank/comment match to try to mark more lines
357 # (help the reader find stuff that hasn't been covered)
358 if lineno in lines_hit:
359 outfile.write("%5d: " % lines_hit[lineno])
360 n_hits += 1
361 n_lines += 1
362 elif rx_blank.match(line):
Walter Dörwaldc1711722003-07-15 10:34:02 +0000363 outfile.write(" ")
Jeremy Hylton38732e12003-04-21 22:04:46 +0000364 else:
365 # lines preceded by no marks weren't hit
366 # Highlight them if so indicated, unless the line contains
367 # #pragma: NO COVER
368 if lineno in lnotab and not PRAGMA_NOCOVER in lines[i]:
369 outfile.write(">>>>>> ")
Jeremy Hylton546e34b2003-06-26 14:56:17 +0000370 n_lines += 1
Jeremy Hylton38732e12003-04-21 22:04:46 +0000371 else:
372 outfile.write(" ")
Jeremy Hylton38732e12003-04-21 22:04:46 +0000373 outfile.write(lines[i].expandtabs(8))
374 outfile.close()
375
376 return n_hits, n_lines
377
378def find_lines_from_code(code, strs):
379 """Return dict where keys are lines in the line number table."""
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000380 linenos = {}
381
Alexander Belopolsky517185e2010-09-24 18:14:18 +0000382 for _, lineno in dis.findlinestarts(code):
Jeremy Hylton38732e12003-04-21 22:04:46 +0000383 if lineno not in strs:
384 linenos[lineno] = 1
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000385
386 return linenos
387
Jeremy Hylton38732e12003-04-21 22:04:46 +0000388def find_lines(code, strs):
389 """Return lineno dict for all code objects reachable from code."""
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000390 # get all of the lineno information from the code of this scope level
Jeremy Hylton38732e12003-04-21 22:04:46 +0000391 linenos = find_lines_from_code(code, strs)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000392
393 # and check the constants for references to other code objects
394 for c in code.co_consts:
Alexander Belopolsky9d17da32010-09-13 16:45:02 +0000395 if inspect.iscode(c):
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000396 # find another code object, so recurse into it
Jeremy Hylton38732e12003-04-21 22:04:46 +0000397 linenos.update(find_lines(c, strs))
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000398 return linenos
399
Jeremy Hylton38732e12003-04-21 22:04:46 +0000400def find_strings(filename):
401 """Return a dict of possible docstring positions.
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000402
Jeremy Hylton38732e12003-04-21 22:04:46 +0000403 The dict maps line numbers to strings. There is an entry for
404 line that contains only a string or a part of a triple-quoted
405 string.
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000406 """
Jeremy Hylton38732e12003-04-21 22:04:46 +0000407 d = {}
408 # If the first token is a string, then it's the module docstring.
409 # Add this special case so that the test in the loop passes.
410 prev_ttype = token.INDENT
411 f = open(filename)
412 for ttype, tstr, start, end, line in tokenize.generate_tokens(f.readline):
413 if ttype == token.STRING:
414 if prev_ttype == token.INDENT:
415 sline, scol = start
416 eline, ecol = end
417 for i in range(sline, eline + 1):
418 d[i] = 1
419 prev_ttype = ttype
420 f.close()
421 return d
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000422
Jeremy Hylton38732e12003-04-21 22:04:46 +0000423def find_executable_linenos(filename):
424 """Return dict where keys are line numbers in the line number table."""
Jeremy Hylton38732e12003-04-21 22:04:46 +0000425 try:
Skip Montanaroc00fc842004-04-16 03:28:19 +0000426 prog = open(filename, "rU").read()
Jeremy Hylton38732e12003-04-21 22:04:46 +0000427 except IOError, err:
428 print >> sys.stderr, ("Not printing coverage data for %r: %s"
429 % (filename, err))
430 return {}
431 code = compile(prog, filename, "exec")
432 strs = find_strings(filename)
433 return find_lines(code, strs)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000434
435class Trace:
Skip Montanarocafc8112004-04-07 15:46:05 +0000436 def __init__(self, count=1, trace=1, countfuncs=0, countcallers=0,
Neal Norwitzca376612008-02-26 08:21:28 +0000437 ignoremods=(), ignoredirs=(), infile=None, outfile=None,
438 timing=False):
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000439 """
440 @param count true iff it should count number of times each
Tim Petersf2715e02003-02-19 02:35:07 +0000441 line is executed
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000442 @param trace true iff it should print out each line that is
Tim Petersf2715e02003-02-19 02:35:07 +0000443 being counted
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000444 @param countfuncs true iff it should just output a list of
445 (filename, modulename, funcname,) for functions
446 that were called at least once; This overrides
Tim Petersf2715e02003-02-19 02:35:07 +0000447 `count' and `trace'
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000448 @param ignoremods a list of the names of modules to ignore
449 @param ignoredirs a list of the names of directories to ignore
Tim Petersf2715e02003-02-19 02:35:07 +0000450 all of the (recursive) contents of
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000451 @param infile file from which to read stored counts to be
Tim Petersf2715e02003-02-19 02:35:07 +0000452 added into the results
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000453 @param outfile file in which to write the results
Neal Norwitzca376612008-02-26 08:21:28 +0000454 @param timing true iff timing information be displayed
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000455 """
456 self.infile = infile
457 self.outfile = outfile
458 self.ignore = Ignore(ignoremods, ignoredirs)
459 self.counts = {} # keys are (filename, linenumber)
460 self.blabbed = {} # for debugging
461 self.pathtobasename = {} # for memoizing os.path.basename
462 self.donothing = 0
463 self.trace = trace
464 self._calledfuncs = {}
Skip Montanarocafc8112004-04-07 15:46:05 +0000465 self._callers = {}
Skip Montanaro5bfd9842004-04-10 16:29:58 +0000466 self._caller_cache = {}
Neal Norwitzca376612008-02-26 08:21:28 +0000467 self.start_time = None
468 if timing:
469 self.start_time = time.time()
Skip Montanarocafc8112004-04-07 15:46:05 +0000470 if countcallers:
471 self.globaltrace = self.globaltrace_trackcallers
472 elif countfuncs:
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000473 self.globaltrace = self.globaltrace_countfuncs
474 elif trace and count:
475 self.globaltrace = self.globaltrace_lt
476 self.localtrace = self.localtrace_trace_and_count
477 elif trace:
478 self.globaltrace = self.globaltrace_lt
479 self.localtrace = self.localtrace_trace
480 elif count:
481 self.globaltrace = self.globaltrace_lt
482 self.localtrace = self.localtrace_count
483 else:
484 # Ahem -- do nothing? Okay.
485 self.donothing = 1
486
487 def run(self, cmd):
488 import __main__
489 dict = __main__.__dict__
490 if not self.donothing:
Jeremy Hylton546e34b2003-06-26 14:56:17 +0000491 threading.settrace(self.globaltrace)
Georg Brandl11ce4d92010-08-02 21:38:08 +0000492 sys.settrace(self.globaltrace)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000493 try:
494 exec cmd in dict, dict
495 finally:
496 if not self.donothing:
497 sys.settrace(None)
Jeremy Hylton546e34b2003-06-26 14:56:17 +0000498 threading.settrace(None)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000499
500 def runctx(self, cmd, globals=None, locals=None):
501 if globals is None: globals = {}
502 if locals is None: locals = {}
503 if not self.donothing:
Jeremy Hylton546e34b2003-06-26 14:56:17 +0000504 threading.settrace(self.globaltrace)
Georg Brandl11ce4d92010-08-02 21:38:08 +0000505 sys.settrace(self.globaltrace)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000506 try:
507 exec cmd in globals, locals
508 finally:
509 if not self.donothing:
510 sys.settrace(None)
Jeremy Hylton546e34b2003-06-26 14:56:17 +0000511 threading.settrace(None)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000512
513 def runfunc(self, func, *args, **kw):
514 result = None
515 if not self.donothing:
516 sys.settrace(self.globaltrace)
517 try:
Guido van Rossum68468eb2003-02-27 20:14:51 +0000518 result = func(*args, **kw)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000519 finally:
520 if not self.donothing:
521 sys.settrace(None)
522 return result
523
Skip Montanaro5bfd9842004-04-10 16:29:58 +0000524 def file_module_function_of(self, frame):
525 code = frame.f_code
526 filename = code.co_filename
527 if filename:
528 modulename = modname(filename)
529 else:
530 modulename = None
531
532 funcname = code.co_name
533 clsname = None
534 if code in self._caller_cache:
535 if self._caller_cache[code] is not None:
536 clsname = self._caller_cache[code]
537 else:
538 self._caller_cache[code] = None
539 ## use of gc.get_referrers() was suggested by Michael Hudson
540 # all functions which refer to this code object
541 funcs = [f for f in gc.get_referrers(code)
Alexander Belopolsky9d17da32010-09-13 16:45:02 +0000542 if inspect.isfunction(f)]
Skip Montanaro5bfd9842004-04-10 16:29:58 +0000543 # require len(func) == 1 to avoid ambiguity caused by calls to
544 # new.function(): "In the face of ambiguity, refuse the
545 # temptation to guess."
546 if len(funcs) == 1:
547 dicts = [d for d in gc.get_referrers(funcs[0])
548 if isinstance(d, dict)]
549 if len(dicts) == 1:
550 classes = [c for c in gc.get_referrers(dicts[0])
551 if hasattr(c, "__bases__")]
552 if len(classes) == 1:
553 # ditto for new.classobj()
Alexander Belopolsky9d17da32010-09-13 16:45:02 +0000554 clsname = classes[0].__name__
Skip Montanaro5bfd9842004-04-10 16:29:58 +0000555 # cache the result - assumption is that new.* is
556 # not called later to disturb this relationship
557 # _caller_cache could be flushed if functions in
558 # the new module get called.
559 self._caller_cache[code] = clsname
560 if clsname is not None:
Skip Montanaro5bfd9842004-04-10 16:29:58 +0000561 funcname = "%s.%s" % (clsname, funcname)
562
563 return filename, modulename, funcname
564
Skip Montanarocafc8112004-04-07 15:46:05 +0000565 def globaltrace_trackcallers(self, frame, why, arg):
566 """Handler for call events.
567
568 Adds information about who called who to the self._callers dict.
569 """
570 if why == 'call':
571 # XXX Should do a better job of identifying methods
Skip Montanaro5bfd9842004-04-10 16:29:58 +0000572 this_func = self.file_module_function_of(frame)
573 parent_func = self.file_module_function_of(frame.f_back)
Skip Montanarocafc8112004-04-07 15:46:05 +0000574 self._callers[(parent_func, this_func)] = 1
575
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000576 def globaltrace_countfuncs(self, frame, why, arg):
Jeremy Hylton38732e12003-04-21 22:04:46 +0000577 """Handler for call events.
Tim Peters0eadaac2003-04-24 16:02:54 +0000578
Jeremy Hylton38732e12003-04-21 22:04:46 +0000579 Adds (filename, modulename, funcname) to the self._calledfuncs dict.
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000580 """
581 if why == 'call':
Skip Montanaro5bfd9842004-04-10 16:29:58 +0000582 this_func = self.file_module_function_of(frame)
583 self._calledfuncs[this_func] = 1
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000584
585 def globaltrace_lt(self, frame, why, arg):
Jeremy Hylton38732e12003-04-21 22:04:46 +0000586 """Handler for call events.
587
588 If the code block being entered is to be ignored, returns `None',
589 else returns self.localtrace.
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000590 """
591 if why == 'call':
Jeremy Hylton38732e12003-04-21 22:04:46 +0000592 code = frame.f_code
Skip Montanaro691acf22007-02-11 18:24:37 +0000593 filename = frame.f_globals.get('__file__', None)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000594 if filename:
Jeremy Hyltondfbfe732003-04-21 22:49:17 +0000595 # XXX modname() doesn't work right for packages, so
596 # the ignore support won't work right for packages
Jeremy Hylton38732e12003-04-21 22:04:46 +0000597 modulename = modname(filename)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000598 if modulename is not None:
599 ignore_it = self.ignore.names(filename, modulename)
600 if not ignore_it:
601 if self.trace:
602 print (" --- modulename: %s, funcname: %s"
Jeremy Hylton38732e12003-04-21 22:04:46 +0000603 % (modulename, code.co_name))
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000604 return self.localtrace
605 else:
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000606 return None
607
608 def localtrace_trace_and_count(self, frame, why, arg):
Jeremy Hylton38732e12003-04-21 22:04:46 +0000609 if why == "line":
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000610 # record the file name and line number of every trace
Jeremy Hylton38732e12003-04-21 22:04:46 +0000611 filename = frame.f_code.co_filename
612 lineno = frame.f_lineno
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000613 key = filename, lineno
614 self.counts[key] = self.counts.get(key, 0) + 1
Tim Petersf2715e02003-02-19 02:35:07 +0000615
Neal Norwitzca376612008-02-26 08:21:28 +0000616 if self.start_time:
617 print '%.2f' % (time.time() - self.start_time),
Jeremy Hylton38732e12003-04-21 22:04:46 +0000618 bname = os.path.basename(filename)
619 print "%s(%d): %s" % (bname, lineno,
620 linecache.getline(filename, lineno)),
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000621 return self.localtrace
622
623 def localtrace_trace(self, frame, why, arg):
Jeremy Hylton38732e12003-04-21 22:04:46 +0000624 if why == "line":
625 # record the file name and line number of every trace
626 filename = frame.f_code.co_filename
627 lineno = frame.f_lineno
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000628
Neal Norwitzca376612008-02-26 08:21:28 +0000629 if self.start_time:
630 print '%.2f' % (time.time() - self.start_time),
Jeremy Hylton38732e12003-04-21 22:04:46 +0000631 bname = os.path.basename(filename)
632 print "%s(%d): %s" % (bname, lineno,
633 linecache.getline(filename, lineno)),
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000634 return self.localtrace
635
636 def localtrace_count(self, frame, why, arg):
Jeremy Hylton38732e12003-04-21 22:04:46 +0000637 if why == "line":
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000638 filename = frame.f_code.co_filename
639 lineno = frame.f_lineno
640 key = filename, lineno
641 self.counts[key] = self.counts.get(key, 0) + 1
642 return self.localtrace
643
644 def results(self):
645 return CoverageResults(self.counts, infile=self.infile,
646 outfile=self.outfile,
Skip Montanarocafc8112004-04-07 15:46:05 +0000647 calledfuncs=self._calledfuncs,
648 callers=self._callers)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000649
650def _err_exit(msg):
651 sys.stderr.write("%s: %s\n" % (sys.argv[0], msg))
652 sys.exit(1)
653
654def main(argv=None):
655 import getopt
656
657 if argv is None:
658 argv = sys.argv
659 try:
Neal Norwitzca376612008-02-26 08:21:28 +0000660 opts, prog_argv = getopt.getopt(argv[1:], "tcrRf:d:msC:lTg",
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000661 ["help", "version", "trace", "count",
662 "report", "no-report", "summary",
663 "file=", "missing",
664 "ignore-module=", "ignore-dir=",
Skip Montanarocafc8112004-04-07 15:46:05 +0000665 "coverdir=", "listfuncs",
Neal Norwitzca376612008-02-26 08:21:28 +0000666 "trackcalls", "timing"])
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000667
668 except getopt.error, msg:
669 sys.stderr.write("%s: %s\n" % (sys.argv[0], msg))
670 sys.stderr.write("Try `%s --help' for more information\n"
671 % sys.argv[0])
672 sys.exit(1)
673
674 trace = 0
675 count = 0
676 report = 0
677 no_report = 0
678 counts_file = None
679 missing = 0
680 ignore_modules = []
681 ignore_dirs = []
682 coverdir = None
683 summary = 0
684 listfuncs = False
Skip Montanarocafc8112004-04-07 15:46:05 +0000685 countcallers = False
Neal Norwitzca376612008-02-26 08:21:28 +0000686 timing = False
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000687
688 for opt, val in opts:
689 if opt == "--help":
690 usage(sys.stdout)
691 sys.exit(0)
692
693 if opt == "--version":
694 sys.stdout.write("trace 2.0\n")
695 sys.exit(0)
696
Skip Montanarocafc8112004-04-07 15:46:05 +0000697 if opt == "-T" or opt == "--trackcalls":
698 countcallers = True
699 continue
700
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000701 if opt == "-l" or opt == "--listfuncs":
702 listfuncs = True
703 continue
704
Neal Norwitzca376612008-02-26 08:21:28 +0000705 if opt == "-g" or opt == "--timing":
706 timing = True
707 continue
708
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000709 if opt == "-t" or opt == "--trace":
710 trace = 1
711 continue
712
713 if opt == "-c" or opt == "--count":
714 count = 1
715 continue
716
717 if opt == "-r" or opt == "--report":
718 report = 1
719 continue
720
721 if opt == "-R" or opt == "--no-report":
722 no_report = 1
723 continue
724
725 if opt == "-f" or opt == "--file":
726 counts_file = val
727 continue
728
729 if opt == "-m" or opt == "--missing":
730 missing = 1
731 continue
732
733 if opt == "-C" or opt == "--coverdir":
734 coverdir = val
735 continue
736
737 if opt == "-s" or opt == "--summary":
738 summary = 1
739 continue
740
741 if opt == "--ignore-module":
Facundo Batista873c9852008-01-19 18:38:19 +0000742 for mod in val.split(","):
743 ignore_modules.append(mod.strip())
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000744 continue
745
746 if opt == "--ignore-dir":
747 for s in val.split(os.pathsep):
748 s = os.path.expandvars(s)
749 # should I also call expanduser? (after all, could use $HOME)
750
751 s = s.replace("$prefix",
752 os.path.join(sys.prefix, "lib",
753 "python" + sys.version[:3]))
754 s = s.replace("$exec_prefix",
755 os.path.join(sys.exec_prefix, "lib",
756 "python" + sys.version[:3]))
757 s = os.path.normpath(s)
758 ignore_dirs.append(s)
759 continue
760
761 assert 0, "Should never get here"
762
763 if listfuncs and (count or trace):
764 _err_exit("cannot specify both --listfuncs and (--trace or --count)")
765
Skip Montanarocafc8112004-04-07 15:46:05 +0000766 if not (count or trace or report or listfuncs or countcallers):
767 _err_exit("must specify one of --trace, --count, --report, "
768 "--listfuncs, or --trackcalls")
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000769
770 if report and no_report:
771 _err_exit("cannot specify both --report and --no-report")
772
773 if report and not counts_file:
774 _err_exit("--report requires a --file")
775
776 if no_report and len(prog_argv) == 0:
777 _err_exit("missing name of file to run")
778
779 # everything is ready
780 if report:
781 results = CoverageResults(infile=counts_file, outfile=counts_file)
782 results.write_results(missing, summary=summary, coverdir=coverdir)
783 else:
784 sys.argv = prog_argv
785 progname = prog_argv[0]
786 sys.path[0] = os.path.split(progname)[0]
787
788 t = Trace(count, trace, countfuncs=listfuncs,
Skip Montanarocafc8112004-04-07 15:46:05 +0000789 countcallers=countcallers, ignoremods=ignore_modules,
790 ignoredirs=ignore_dirs, infile=counts_file,
Neal Norwitzca376612008-02-26 08:21:28 +0000791 outfile=counts_file, timing=timing)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000792 try:
Georg Brandl78e69572010-08-01 18:52:52 +0000793 with open(progname) as fp:
794 code = compile(fp.read(), progname, 'exec')
795 # try to emulate __main__ namespace as much as possible
796 globs = {
797 '__file__': progname,
798 '__name__': '__main__',
799 '__package__': None,
800 '__cached__': None,
801 }
802 t.runctx(code, globs, globs)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000803 except IOError, err:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000804 _err_exit("Cannot run file %r because: %s" % (sys.argv[0], err))
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000805 except SystemExit:
806 pass
807
808 results = t.results()
809
810 if not no_report:
811 results.write_results(missing, summary=summary, coverdir=coverdir)
812
813if __name__=='__main__':
814 main()