blob: 2e403c8b3eb523c33855018824a84f42209f1e14 [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
Jeremy Hylton38732e12003-04-21 22:04:46 +000056import token
57import tokenize
58import types
Skip Montanaro5bfd9842004-04-10 16:29:58 +000059import gc
Jeremy Hylton38732e12003-04-21 22:04:46 +000060
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +000061try:
62 import cPickle
63 pickle = cPickle
64except ImportError:
65 import pickle
66
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +000067def usage(outfile):
68 outfile.write("""Usage: %s [OPTIONS] <file> [ARGS]
69
70Meta-options:
71--help Display this help then exit.
72--version Output version information then exit.
73
74Otherwise, exactly one of the following three options must be given:
75-t, --trace Print each line to sys.stdout before it is executed.
76-c, --count Count the number of times each line is executed
77 and write the counts to <module>.cover for each
78 module executed, in the module's directory.
79 See also `--coverdir', `--file', `--no-report' below.
Skip Montanaroa7b8ac62003-06-27 19:09:33 +000080-l, --listfuncs Keep track of which functions are executed at least
Fred Drake01c623b2003-06-27 19:22:11 +000081 once and write the results to sys.stdout after the
Skip Montanaroa7b8ac62003-06-27 19:09:33 +000082 program exits.
Skip Montanarocafc8112004-04-07 15:46:05 +000083-T, --trackcalls Keep track of caller/called pairs and write the
84 results to sys.stdout after the program exits.
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +000085-r, --report Generate a report from a counts file; do not execute
86 any code. `--file' must specify the results file to
87 read, which must have been created in a previous run
88 with `--count --file=FILE'.
89
90Modifiers:
91-f, --file=<file> File to accumulate counts over several runs.
92-R, --no-report Do not generate the coverage report files.
93 Useful if you want to accumulate over several runs.
94-C, --coverdir=<dir> Directory where the report files. The coverage
95 report for <package>.<module> is written to file
96 <dir>/<package>/<module>.cover.
97-m, --missing Annotate executable lines that were not executed
98 with '>>>>>> '.
99-s, --summary Write a brief summary on stdout for each file.
100 (Can only be used with --count or --report.)
101
102Filters, may be repeated multiple times:
Facundo Batista873c9852008-01-19 18:38:19 +0000103--ignore-module=<mod> Ignore the given module(s) and its submodules
104 (if it is a package). Accepts comma separated
105 list of module names
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000106--ignore-dir=<dir> Ignore files in the given directory (multiple
107 directories can be joined by os.pathsep).
108""" % sys.argv[0])
109
Jeremy Hylton38732e12003-04-21 22:04:46 +0000110PRAGMA_NOCOVER = "#pragma NO COVER"
111
112# Simple rx to find lines with no code.
113rx_blank = re.compile(r'^\s*(#.*)?$')
114
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000115class Ignore:
116 def __init__(self, modules = None, dirs = None):
117 self._mods = modules or []
118 self._dirs = dirs or []
119
120 self._dirs = map(os.path.normpath, self._dirs)
121 self._ignore = { '<string>': 1 }
122
123 def names(self, filename, modulename):
124 if self._ignore.has_key(modulename):
125 return self._ignore[modulename]
126
127 # haven't seen this one before, so see if the module name is
128 # on the ignore list. Need to take some care since ignoring
129 # "cmp" musn't mean ignoring "cmpcache" but ignoring
130 # "Spam" must also mean ignoring "Spam.Eggs".
131 for mod in self._mods:
132 if mod == modulename: # Identical names, so ignore
133 self._ignore[modulename] = 1
134 return 1
135 # check if the module is a proper submodule of something on
136 # the ignore list
137 n = len(mod)
138 # (will not overflow since if the first n characters are the
Fred Drakedb390c12005-10-28 14:39:47 +0000139 # same and the name has not already occurred, then the size
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000140 # of "name" is greater than that of "mod")
141 if mod == modulename[:n] and modulename[n] == '.':
142 self._ignore[modulename] = 1
143 return 1
144
145 # Now check that __file__ isn't in one of the directories
146 if filename is None:
147 # must be a built-in, so we must ignore
148 self._ignore[modulename] = 1
149 return 1
150
151 # Ignore a file when it contains one of the ignorable paths
152 for d in self._dirs:
153 # The '+ os.sep' is to ensure that d is a parent directory,
154 # as compared to cases like:
155 # d = "/usr/local"
156 # filename = "/usr/local.py"
157 # or
158 # d = "/usr/local.py"
159 # filename = "/usr/local.py"
160 if filename.startswith(d + os.sep):
161 self._ignore[modulename] = 1
162 return 1
163
164 # Tried the different ways, so we don't ignore this module
165 self._ignore[modulename] = 0
166 return 0
167
Jeremy Hylton38732e12003-04-21 22:04:46 +0000168def modname(path):
169 """Return a plausible module name for the patch."""
Jeremy Hyltondfbfe732003-04-21 22:49:17 +0000170
Jeremy Hylton38732e12003-04-21 22:04:46 +0000171 base = os.path.basename(path)
172 filename, ext = os.path.splitext(base)
173 return filename
174
Jeremy Hyltondfbfe732003-04-21 22:49:17 +0000175def fullmodname(path):
Jeremy Hyltonc8c8b942003-04-22 15:35:51 +0000176 """Return a plausible module name for the path."""
Jeremy Hyltondfbfe732003-04-21 22:49:17 +0000177
178 # If the file 'path' is part of a package, then the filename isn't
179 # enough to uniquely identify it. Try to do the right thing by
180 # looking in sys.path for the longest matching prefix. We'll
181 # assume that the rest is the package name.
182
Georg Brandl7a1af772006-08-14 21:55:28 +0000183 comparepath = os.path.normcase(path)
Jeremy Hyltondfbfe732003-04-21 22:49:17 +0000184 longest = ""
185 for dir in sys.path:
Georg Brandl7a1af772006-08-14 21:55:28 +0000186 dir = os.path.normcase(dir)
187 if comparepath.startswith(dir) and comparepath[len(dir)] == os.sep:
Jeremy Hyltondfbfe732003-04-21 22:49:17 +0000188 if len(dir) > len(longest):
189 longest = dir
190
Guido van Rossumb427c002003-10-10 23:02:01 +0000191 if longest:
192 base = path[len(longest) + 1:]
193 else:
194 base = path
Guido van Rossumbbca8da2004-02-19 19:16:50 +0000195 base = base.replace(os.sep, ".")
196 if os.altsep:
197 base = base.replace(os.altsep, ".")
Jeremy Hyltondfbfe732003-04-21 22:49:17 +0000198 filename, ext = os.path.splitext(base)
199 return filename
200
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000201class CoverageResults:
202 def __init__(self, counts=None, calledfuncs=None, infile=None,
Skip Montanarocafc8112004-04-07 15:46:05 +0000203 callers=None, outfile=None):
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000204 self.counts = counts
205 if self.counts is None:
206 self.counts = {}
207 self.counter = self.counts.copy() # map (filename, lineno) to count
208 self.calledfuncs = calledfuncs
209 if self.calledfuncs is None:
210 self.calledfuncs = {}
211 self.calledfuncs = self.calledfuncs.copy()
Skip Montanarocafc8112004-04-07 15:46:05 +0000212 self.callers = callers
213 if self.callers is None:
214 self.callers = {}
215 self.callers = self.callers.copy()
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000216 self.infile = infile
217 self.outfile = outfile
218 if self.infile:
Jeremy Hyltond7ce86d2003-07-07 16:08:47 +0000219 # Try to merge existing counts file.
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000220 try:
Skip Montanarocafc8112004-04-07 15:46:05 +0000221 counts, calledfuncs, callers = \
222 pickle.load(open(self.infile, 'rb'))
223 self.update(self.__class__(counts, calledfuncs, callers))
Jeremy Hyltond7ce86d2003-07-07 16:08:47 +0000224 except (IOError, EOFError, ValueError), err:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000225 print >> sys.stderr, ("Skipping counts file %r: %s"
226 % (self.infile, err))
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000227
228 def update(self, other):
229 """Merge in the data from another CoverageResults"""
230 counts = self.counts
231 calledfuncs = self.calledfuncs
Skip Montanarocafc8112004-04-07 15:46:05 +0000232 callers = self.callers
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000233 other_counts = other.counts
234 other_calledfuncs = other.calledfuncs
Skip Montanarocafc8112004-04-07 15:46:05 +0000235 other_callers = other.callers
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000236
237 for key in other_counts.keys():
Jeremy Hylton38732e12003-04-21 22:04:46 +0000238 counts[key] = counts.get(key, 0) + other_counts[key]
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000239
240 for key in other_calledfuncs.keys():
241 calledfuncs[key] = 1
242
Skip Montanarocafc8112004-04-07 15:46:05 +0000243 for key in other_callers.keys():
244 callers[key] = 1
245
Jeremy Hylton38732e12003-04-21 22:04:46 +0000246 def write_results(self, show_missing=True, summary=False, coverdir=None):
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000247 """
248 @param coverdir
249 """
Skip Montanarocafc8112004-04-07 15:46:05 +0000250 if self.calledfuncs:
Skip Montanaro5bfd9842004-04-10 16:29:58 +0000251 print
Skip Montanarocafc8112004-04-07 15:46:05 +0000252 print "functions called:"
253 calls = self.calledfuncs.keys()
254 calls.sort()
255 for filename, modulename, funcname in calls:
256 print ("filename: %s, modulename: %s, funcname: %s"
257 % (filename, modulename, funcname))
258
259 if self.callers:
Skip Montanaro5bfd9842004-04-10 16:29:58 +0000260 print
Skip Montanarocafc8112004-04-07 15:46:05 +0000261 print "calling relationships:"
262 calls = self.callers.keys()
263 calls.sort()
264 lastfile = lastcfile = ""
265 for ((pfile, pmod, pfunc), (cfile, cmod, cfunc)) in calls:
266 if pfile != lastfile:
Skip Montanaro5bfd9842004-04-10 16:29:58 +0000267 print
Skip Montanarocafc8112004-04-07 15:46:05 +0000268 print "***", pfile, "***"
269 lastfile = pfile
270 lastcfile = ""
271 if cfile != pfile and lastcfile != cfile:
272 print " -->", cfile
273 lastcfile = cfile
274 print " %s.%s -> %s.%s" % (pmod, pfunc, cmod, cfunc)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000275
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000276 # turn the counts data ("(filename, lineno) = count") into something
277 # accessible on a per-file basis
278 per_file = {}
Jeremy Hylton38732e12003-04-21 22:04:46 +0000279 for filename, lineno in self.counts.keys():
280 lines_hit = per_file[filename] = per_file.get(filename, {})
281 lines_hit[lineno] = self.counts[(filename, lineno)]
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000282
283 # accumulate summary info, if needed
284 sums = {}
285
Jeremy Hylton38732e12003-04-21 22:04:46 +0000286 for filename, count in per_file.iteritems():
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000287 # skip some "files" we don't care about...
288 if filename == "<string>":
289 continue
Skip Montanaro58a6f442007-11-24 14:30:47 +0000290 if filename.startswith("<doctest "):
291 continue
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000292
Georg Brandlb2afe852006-06-09 20:43:48 +0000293 if filename.endswith((".pyc", ".pyo")):
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000294 filename = filename[:-1]
295
Jeremy Hylton38732e12003-04-21 22:04:46 +0000296 if coverdir is None:
297 dir = os.path.dirname(os.path.abspath(filename))
Jeremy Hyltonc8c8b942003-04-22 15:35:51 +0000298 modulename = modname(filename)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000299 else:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000300 dir = coverdir
301 if not os.path.exists(dir):
302 os.makedirs(dir)
Jeremy Hyltonc8c8b942003-04-22 15:35:51 +0000303 modulename = fullmodname(filename)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000304
305 # If desired, get a list of the line numbers which represent
306 # executable content (returned as a dict for better lookup speed)
307 if show_missing:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000308 lnotab = find_executable_linenos(filename)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000309 else:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000310 lnotab = {}
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000311
Jeremy Hylton38732e12003-04-21 22:04:46 +0000312 source = linecache.getlines(filename)
313 coverpath = os.path.join(dir, modulename + ".cover")
314 n_hits, n_lines = self.write_results_file(coverpath, source,
315 lnotab, count)
Tim Peters0eadaac2003-04-24 16:02:54 +0000316
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000317 if summary and n_lines:
318 percent = int(100 * n_hits / n_lines)
319 sums[modulename] = n_lines, percent, modulename, filename
320
321 if summary and sums:
322 mods = sums.keys()
323 mods.sort()
324 print "lines cov% module (path)"
325 for m in mods:
326 n_lines, percent, modulename, filename = sums[m]
327 print "%5d %3d%% %s (%s)" % sums[m]
328
329 if self.outfile:
330 # try and store counts and module info into self.outfile
331 try:
Skip Montanarocafc8112004-04-07 15:46:05 +0000332 pickle.dump((self.counts, self.calledfuncs, self.callers),
Jeremy Hyltond0e27052003-10-14 20:12:06 +0000333 open(self.outfile, 'wb'), 1)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000334 except IOError, err:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000335 print >> sys.stderr, "Can't save counts files because %s" % err
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000336
Jeremy Hylton38732e12003-04-21 22:04:46 +0000337 def write_results_file(self, path, lines, lnotab, lines_hit):
338 """Return a coverage results file in path."""
339
340 try:
341 outfile = open(path, "w")
342 except IOError, err:
343 print >> sys.stderr, ("trace: Could not open %r for writing: %s"
344 "- skipping" % (path, err))
Guido van Rossumbbca8da2004-02-19 19:16:50 +0000345 return 0, 0
Jeremy Hylton38732e12003-04-21 22:04:46 +0000346
347 n_lines = 0
348 n_hits = 0
349 for i, line in enumerate(lines):
350 lineno = i + 1
351 # do the blank/comment match to try to mark more lines
352 # (help the reader find stuff that hasn't been covered)
353 if lineno in lines_hit:
354 outfile.write("%5d: " % lines_hit[lineno])
355 n_hits += 1
356 n_lines += 1
357 elif rx_blank.match(line):
Walter Dörwaldc1711722003-07-15 10:34:02 +0000358 outfile.write(" ")
Jeremy Hylton38732e12003-04-21 22:04:46 +0000359 else:
360 # lines preceded by no marks weren't hit
361 # Highlight them if so indicated, unless the line contains
362 # #pragma: NO COVER
363 if lineno in lnotab and not PRAGMA_NOCOVER in lines[i]:
364 outfile.write(">>>>>> ")
Jeremy Hylton546e34b2003-06-26 14:56:17 +0000365 n_lines += 1
Jeremy Hylton38732e12003-04-21 22:04:46 +0000366 else:
367 outfile.write(" ")
Jeremy Hylton38732e12003-04-21 22:04:46 +0000368 outfile.write(lines[i].expandtabs(8))
369 outfile.close()
370
371 return n_hits, n_lines
372
373def find_lines_from_code(code, strs):
374 """Return dict where keys are lines in the line number table."""
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000375 linenos = {}
376
377 line_increments = [ord(c) for c in code.co_lnotab[1::2]]
378 table_length = len(line_increments)
Jeremy Hylton38732e12003-04-21 22:04:46 +0000379 docstring = False
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000380
381 lineno = code.co_firstlineno
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000382 for li in line_increments:
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000383 lineno += li
Jeremy Hylton38732e12003-04-21 22:04:46 +0000384 if lineno not in strs:
385 linenos[lineno] = 1
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000386
387 return linenos
388
Jeremy Hylton38732e12003-04-21 22:04:46 +0000389def find_lines(code, strs):
390 """Return lineno dict for all code objects reachable from code."""
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000391 # get all of the lineno information from the code of this scope level
Jeremy Hylton38732e12003-04-21 22:04:46 +0000392 linenos = find_lines_from_code(code, strs)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000393
394 # and check the constants for references to other code objects
395 for c in code.co_consts:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000396 if isinstance(c, types.CodeType):
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000397 # find another code object, so recurse into it
Jeremy Hylton38732e12003-04-21 22:04:46 +0000398 linenos.update(find_lines(c, strs))
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000399 return linenos
400
Jeremy Hylton38732e12003-04-21 22:04:46 +0000401def find_strings(filename):
402 """Return a dict of possible docstring positions.
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000403
Jeremy Hylton38732e12003-04-21 22:04:46 +0000404 The dict maps line numbers to strings. There is an entry for
405 line that contains only a string or a part of a triple-quoted
406 string.
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000407 """
Jeremy Hylton38732e12003-04-21 22:04:46 +0000408 d = {}
409 # If the first token is a string, then it's the module docstring.
410 # Add this special case so that the test in the loop passes.
411 prev_ttype = token.INDENT
412 f = open(filename)
413 for ttype, tstr, start, end, line in tokenize.generate_tokens(f.readline):
414 if ttype == token.STRING:
415 if prev_ttype == token.INDENT:
416 sline, scol = start
417 eline, ecol = end
418 for i in range(sline, eline + 1):
419 d[i] = 1
420 prev_ttype = ttype
421 f.close()
422 return d
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000423
Jeremy Hylton38732e12003-04-21 22:04:46 +0000424def find_executable_linenos(filename):
425 """Return dict where keys are line numbers in the line number table."""
Jeremy Hylton38732e12003-04-21 22:04:46 +0000426 try:
Skip Montanaroc00fc842004-04-16 03:28:19 +0000427 prog = open(filename, "rU").read()
Jeremy Hylton38732e12003-04-21 22:04:46 +0000428 except IOError, err:
429 print >> sys.stderr, ("Not printing coverage data for %r: %s"
430 % (filename, err))
431 return {}
432 code = compile(prog, filename, "exec")
433 strs = find_strings(filename)
434 return find_lines(code, strs)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000435
436class Trace:
Skip Montanarocafc8112004-04-07 15:46:05 +0000437 def __init__(self, count=1, trace=1, countfuncs=0, countcallers=0,
438 ignoremods=(), ignoredirs=(), infile=None, outfile=None):
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
454 """
455 self.infile = infile
456 self.outfile = outfile
457 self.ignore = Ignore(ignoremods, ignoredirs)
458 self.counts = {} # keys are (filename, linenumber)
459 self.blabbed = {} # for debugging
460 self.pathtobasename = {} # for memoizing os.path.basename
461 self.donothing = 0
462 self.trace = trace
463 self._calledfuncs = {}
Skip Montanarocafc8112004-04-07 15:46:05 +0000464 self._callers = {}
Skip Montanaro5bfd9842004-04-10 16:29:58 +0000465 self._caller_cache = {}
Skip Montanarocafc8112004-04-07 15:46:05 +0000466 if countcallers:
467 self.globaltrace = self.globaltrace_trackcallers
468 elif countfuncs:
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000469 self.globaltrace = self.globaltrace_countfuncs
470 elif trace and count:
471 self.globaltrace = self.globaltrace_lt
472 self.localtrace = self.localtrace_trace_and_count
473 elif trace:
474 self.globaltrace = self.globaltrace_lt
475 self.localtrace = self.localtrace_trace
476 elif count:
477 self.globaltrace = self.globaltrace_lt
478 self.localtrace = self.localtrace_count
479 else:
480 # Ahem -- do nothing? Okay.
481 self.donothing = 1
482
483 def run(self, cmd):
484 import __main__
485 dict = __main__.__dict__
486 if not self.donothing:
487 sys.settrace(self.globaltrace)
Jeremy Hylton546e34b2003-06-26 14:56:17 +0000488 threading.settrace(self.globaltrace)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000489 try:
490 exec cmd in dict, dict
491 finally:
492 if not self.donothing:
493 sys.settrace(None)
Jeremy Hylton546e34b2003-06-26 14:56:17 +0000494 threading.settrace(None)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000495
496 def runctx(self, cmd, globals=None, locals=None):
497 if globals is None: globals = {}
498 if locals is None: locals = {}
499 if not self.donothing:
500 sys.settrace(self.globaltrace)
Jeremy Hylton546e34b2003-06-26 14:56:17 +0000501 threading.settrace(self.globaltrace)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000502 try:
503 exec cmd in globals, locals
504 finally:
505 if not self.donothing:
506 sys.settrace(None)
Jeremy Hylton546e34b2003-06-26 14:56:17 +0000507 threading.settrace(None)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000508
509 def runfunc(self, func, *args, **kw):
510 result = None
511 if not self.donothing:
512 sys.settrace(self.globaltrace)
513 try:
Guido van Rossum68468eb2003-02-27 20:14:51 +0000514 result = func(*args, **kw)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000515 finally:
516 if not self.donothing:
517 sys.settrace(None)
518 return result
519
Skip Montanaro5bfd9842004-04-10 16:29:58 +0000520 def file_module_function_of(self, frame):
521 code = frame.f_code
522 filename = code.co_filename
523 if filename:
524 modulename = modname(filename)
525 else:
526 modulename = None
527
528 funcname = code.co_name
529 clsname = None
530 if code in self._caller_cache:
531 if self._caller_cache[code] is not None:
532 clsname = self._caller_cache[code]
533 else:
534 self._caller_cache[code] = None
535 ## use of gc.get_referrers() was suggested by Michael Hudson
536 # all functions which refer to this code object
537 funcs = [f for f in gc.get_referrers(code)
538 if hasattr(f, "func_doc")]
539 # require len(func) == 1 to avoid ambiguity caused by calls to
540 # new.function(): "In the face of ambiguity, refuse the
541 # temptation to guess."
542 if len(funcs) == 1:
543 dicts = [d for d in gc.get_referrers(funcs[0])
544 if isinstance(d, dict)]
545 if len(dicts) == 1:
546 classes = [c for c in gc.get_referrers(dicts[0])
547 if hasattr(c, "__bases__")]
548 if len(classes) == 1:
549 # ditto for new.classobj()
550 clsname = str(classes[0])
551 # cache the result - assumption is that new.* is
552 # not called later to disturb this relationship
553 # _caller_cache could be flushed if functions in
554 # the new module get called.
555 self._caller_cache[code] = clsname
556 if clsname is not None:
557 # final hack - module name shows up in str(cls), but we've already
558 # computed module name, so remove it
559 clsname = clsname.split(".")[1:]
560 clsname = ".".join(clsname)
561 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
Jeremy Hylton38732e12003-04-21 22:04:46 +0000616 bname = os.path.basename(filename)
617 print "%s(%d): %s" % (bname, lineno,
618 linecache.getline(filename, lineno)),
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000619 return self.localtrace
620
621 def localtrace_trace(self, frame, why, arg):
Jeremy Hylton38732e12003-04-21 22:04:46 +0000622 if why == "line":
623 # record the file name and line number of every trace
624 filename = frame.f_code.co_filename
625 lineno = frame.f_lineno
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000626
Jeremy Hylton38732e12003-04-21 22:04:46 +0000627 bname = os.path.basename(filename)
628 print "%s(%d): %s" % (bname, lineno,
629 linecache.getline(filename, lineno)),
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000630 return self.localtrace
631
632 def localtrace_count(self, frame, why, arg):
Jeremy Hylton38732e12003-04-21 22:04:46 +0000633 if why == "line":
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000634 filename = frame.f_code.co_filename
635 lineno = frame.f_lineno
636 key = filename, lineno
637 self.counts[key] = self.counts.get(key, 0) + 1
638 return self.localtrace
639
640 def results(self):
641 return CoverageResults(self.counts, infile=self.infile,
642 outfile=self.outfile,
Skip Montanarocafc8112004-04-07 15:46:05 +0000643 calledfuncs=self._calledfuncs,
644 callers=self._callers)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000645
646def _err_exit(msg):
647 sys.stderr.write("%s: %s\n" % (sys.argv[0], msg))
648 sys.exit(1)
649
650def main(argv=None):
651 import getopt
652
653 if argv is None:
654 argv = sys.argv
655 try:
Skip Montanarocafc8112004-04-07 15:46:05 +0000656 opts, prog_argv = getopt.getopt(argv[1:], "tcrRf:d:msC:lT",
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000657 ["help", "version", "trace", "count",
658 "report", "no-report", "summary",
659 "file=", "missing",
660 "ignore-module=", "ignore-dir=",
Skip Montanarocafc8112004-04-07 15:46:05 +0000661 "coverdir=", "listfuncs",
662 "trackcalls"])
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000663
664 except getopt.error, msg:
665 sys.stderr.write("%s: %s\n" % (sys.argv[0], msg))
666 sys.stderr.write("Try `%s --help' for more information\n"
667 % sys.argv[0])
668 sys.exit(1)
669
670 trace = 0
671 count = 0
672 report = 0
673 no_report = 0
674 counts_file = None
675 missing = 0
676 ignore_modules = []
677 ignore_dirs = []
678 coverdir = None
679 summary = 0
680 listfuncs = False
Skip Montanarocafc8112004-04-07 15:46:05 +0000681 countcallers = False
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000682
683 for opt, val in opts:
684 if opt == "--help":
685 usage(sys.stdout)
686 sys.exit(0)
687
688 if opt == "--version":
689 sys.stdout.write("trace 2.0\n")
690 sys.exit(0)
691
Skip Montanarocafc8112004-04-07 15:46:05 +0000692 if opt == "-T" or opt == "--trackcalls":
693 countcallers = True
694 continue
695
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000696 if opt == "-l" or opt == "--listfuncs":
697 listfuncs = True
698 continue
699
700 if opt == "-t" or opt == "--trace":
701 trace = 1
702 continue
703
704 if opt == "-c" or opt == "--count":
705 count = 1
706 continue
707
708 if opt == "-r" or opt == "--report":
709 report = 1
710 continue
711
712 if opt == "-R" or opt == "--no-report":
713 no_report = 1
714 continue
715
716 if opt == "-f" or opt == "--file":
717 counts_file = val
718 continue
719
720 if opt == "-m" or opt == "--missing":
721 missing = 1
722 continue
723
724 if opt == "-C" or opt == "--coverdir":
725 coverdir = val
726 continue
727
728 if opt == "-s" or opt == "--summary":
729 summary = 1
730 continue
731
732 if opt == "--ignore-module":
Facundo Batista873c9852008-01-19 18:38:19 +0000733 for mod in val.split(","):
734 ignore_modules.append(mod.strip())
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000735 continue
736
737 if opt == "--ignore-dir":
738 for s in val.split(os.pathsep):
739 s = os.path.expandvars(s)
740 # should I also call expanduser? (after all, could use $HOME)
741
742 s = s.replace("$prefix",
743 os.path.join(sys.prefix, "lib",
744 "python" + sys.version[:3]))
745 s = s.replace("$exec_prefix",
746 os.path.join(sys.exec_prefix, "lib",
747 "python" + sys.version[:3]))
748 s = os.path.normpath(s)
749 ignore_dirs.append(s)
750 continue
751
752 assert 0, "Should never get here"
753
754 if listfuncs and (count or trace):
755 _err_exit("cannot specify both --listfuncs and (--trace or --count)")
756
Skip Montanarocafc8112004-04-07 15:46:05 +0000757 if not (count or trace or report or listfuncs or countcallers):
758 _err_exit("must specify one of --trace, --count, --report, "
759 "--listfuncs, or --trackcalls")
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000760
761 if report and no_report:
762 _err_exit("cannot specify both --report and --no-report")
763
764 if report and not counts_file:
765 _err_exit("--report requires a --file")
766
767 if no_report and len(prog_argv) == 0:
768 _err_exit("missing name of file to run")
769
770 # everything is ready
771 if report:
772 results = CoverageResults(infile=counts_file, outfile=counts_file)
773 results.write_results(missing, summary=summary, coverdir=coverdir)
774 else:
775 sys.argv = prog_argv
776 progname = prog_argv[0]
777 sys.path[0] = os.path.split(progname)[0]
778
779 t = Trace(count, trace, countfuncs=listfuncs,
Skip Montanarocafc8112004-04-07 15:46:05 +0000780 countcallers=countcallers, ignoremods=ignore_modules,
781 ignoredirs=ignore_dirs, infile=counts_file,
782 outfile=counts_file)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000783 try:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000784 t.run('execfile(%r)' % (progname,))
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000785 except IOError, err:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000786 _err_exit("Cannot run file %r because: %s" % (sys.argv[0], err))
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000787 except SystemExit:
788 pass
789
790 results = t.results()
791
792 if not no_report:
793 results.write_results(missing, summary=summary, coverdir=coverdir)
794
795if __name__=='__main__':
796 main()