blob: c52c8a8667bf807e0bb9c2fd0d07fd166b3ea448 [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
Thomas Wouters477c8d52006-05-27 19:21:47 +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,
43 count=1)
44 # 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
Guido van Rossum99603b02007-07-20 00:22:32 +000061import pickle
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +000062
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +000063def usage(outfile):
64 outfile.write("""Usage: %s [OPTIONS] <file> [ARGS]
65
66Meta-options:
67--help Display this help then exit.
68--version Output version information then exit.
69
70Otherwise, exactly one of the following three options must be given:
71-t, --trace Print each line to sys.stdout before it is executed.
72-c, --count Count the number of times each line is executed
73 and write the counts to <module>.cover for each
74 module executed, in the module's directory.
75 See also `--coverdir', `--file', `--no-report' below.
Skip Montanaroa7b8ac62003-06-27 19:09:33 +000076-l, --listfuncs Keep track of which functions are executed at least
Fred Drake01c623b2003-06-27 19:22:11 +000077 once and write the results to sys.stdout after the
Skip Montanaroa7b8ac62003-06-27 19:09:33 +000078 program exits.
Skip Montanarocafc8112004-04-07 15:46:05 +000079-T, --trackcalls Keep track of caller/called pairs and write the
80 results to sys.stdout after the program exits.
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +000081-r, --report Generate a report from a counts file; do not execute
82 any code. `--file' must specify the results file to
83 read, which must have been created in a previous run
84 with `--count --file=FILE'.
85
86Modifiers:
87-f, --file=<file> File to accumulate counts over several runs.
88-R, --no-report Do not generate the coverage report files.
89 Useful if you want to accumulate over several runs.
90-C, --coverdir=<dir> Directory where the report files. The coverage
91 report for <package>.<module> is written to file
92 <dir>/<package>/<module>.cover.
93-m, --missing Annotate executable lines that were not executed
94 with '>>>>>> '.
95-s, --summary Write a brief summary on stdout for each file.
96 (Can only be used with --count or --report.)
97
98Filters, may be repeated multiple times:
Georg Brandlfceab5a2008-01-19 20:08:23 +000099--ignore-module=<mod> Ignore the given module(s) and its submodules
100 (if it is a package). Accepts comma separated
101 list of module names
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000102--ignore-dir=<dir> Ignore files in the given directory (multiple
103 directories can be joined by os.pathsep).
104""" % sys.argv[0])
105
Jeremy Hylton38732e12003-04-21 22:04:46 +0000106PRAGMA_NOCOVER = "#pragma NO COVER"
107
108# Simple rx to find lines with no code.
109rx_blank = re.compile(r'^\s*(#.*)?$')
110
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000111class Ignore:
112 def __init__(self, modules = None, dirs = None):
113 self._mods = modules or []
114 self._dirs = dirs or []
115
116 self._dirs = map(os.path.normpath, self._dirs)
117 self._ignore = { '<string>': 1 }
118
119 def names(self, filename, modulename):
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000120 if modulename in self._ignore:
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000121 return self._ignore[modulename]
122
123 # haven't seen this one before, so see if the module name is
124 # on the ignore list. Need to take some care since ignoring
125 # "cmp" musn't mean ignoring "cmpcache" but ignoring
126 # "Spam" must also mean ignoring "Spam.Eggs".
127 for mod in self._mods:
128 if mod == modulename: # Identical names, so ignore
129 self._ignore[modulename] = 1
130 return 1
131 # check if the module is a proper submodule of something on
132 # the ignore list
133 n = len(mod)
134 # (will not overflow since if the first n characters are the
Fred Drakedb390c12005-10-28 14:39:47 +0000135 # same and the name has not already occurred, then the size
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000136 # of "name" is greater than that of "mod")
137 if mod == modulename[:n] and modulename[n] == '.':
138 self._ignore[modulename] = 1
139 return 1
140
141 # Now check that __file__ isn't in one of the directories
142 if filename is None:
143 # must be a built-in, so we must ignore
144 self._ignore[modulename] = 1
145 return 1
146
147 # Ignore a file when it contains one of the ignorable paths
148 for d in self._dirs:
149 # The '+ os.sep' is to ensure that d is a parent directory,
150 # as compared to cases like:
151 # d = "/usr/local"
152 # filename = "/usr/local.py"
153 # or
154 # d = "/usr/local.py"
155 # filename = "/usr/local.py"
156 if filename.startswith(d + os.sep):
157 self._ignore[modulename] = 1
158 return 1
159
160 # Tried the different ways, so we don't ignore this module
161 self._ignore[modulename] = 0
162 return 0
163
Jeremy Hylton38732e12003-04-21 22:04:46 +0000164def modname(path):
165 """Return a plausible module name for the patch."""
Jeremy Hyltondfbfe732003-04-21 22:49:17 +0000166
Jeremy Hylton38732e12003-04-21 22:04:46 +0000167 base = os.path.basename(path)
168 filename, ext = os.path.splitext(base)
169 return filename
170
Jeremy Hyltondfbfe732003-04-21 22:49:17 +0000171def fullmodname(path):
Jeremy Hyltonc8c8b942003-04-22 15:35:51 +0000172 """Return a plausible module name for the path."""
Jeremy Hyltondfbfe732003-04-21 22:49:17 +0000173
174 # If the file 'path' is part of a package, then the filename isn't
175 # enough to uniquely identify it. Try to do the right thing by
176 # looking in sys.path for the longest matching prefix. We'll
177 # assume that the rest is the package name.
178
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000179 comparepath = os.path.normcase(path)
Jeremy Hyltondfbfe732003-04-21 22:49:17 +0000180 longest = ""
181 for dir in sys.path:
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000182 dir = os.path.normcase(dir)
183 if comparepath.startswith(dir) and comparepath[len(dir)] == os.sep:
Jeremy Hyltondfbfe732003-04-21 22:49:17 +0000184 if len(dir) > len(longest):
185 longest = dir
186
Guido van Rossumb427c002003-10-10 23:02:01 +0000187 if longest:
188 base = path[len(longest) + 1:]
189 else:
190 base = path
Guido van Rossumbbca8da2004-02-19 19:16:50 +0000191 base = base.replace(os.sep, ".")
192 if os.altsep:
193 base = base.replace(os.altsep, ".")
Jeremy Hyltondfbfe732003-04-21 22:49:17 +0000194 filename, ext = os.path.splitext(base)
195 return filename
196
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000197class CoverageResults:
198 def __init__(self, counts=None, calledfuncs=None, infile=None,
Skip Montanarocafc8112004-04-07 15:46:05 +0000199 callers=None, outfile=None):
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000200 self.counts = counts
201 if self.counts is None:
202 self.counts = {}
203 self.counter = self.counts.copy() # map (filename, lineno) to count
204 self.calledfuncs = calledfuncs
205 if self.calledfuncs is None:
206 self.calledfuncs = {}
207 self.calledfuncs = self.calledfuncs.copy()
Skip Montanarocafc8112004-04-07 15:46:05 +0000208 self.callers = callers
209 if self.callers is None:
210 self.callers = {}
211 self.callers = self.callers.copy()
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000212 self.infile = infile
213 self.outfile = outfile
214 if self.infile:
Jeremy Hyltond7ce86d2003-07-07 16:08:47 +0000215 # Try to merge existing counts file.
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000216 try:
Skip Montanarocafc8112004-04-07 15:46:05 +0000217 counts, calledfuncs, callers = \
218 pickle.load(open(self.infile, 'rb'))
219 self.update(self.__class__(counts, calledfuncs, callers))
Guido van Rossumb940e112007-01-10 16:19:56 +0000220 except (IOError, EOFError, ValueError) as err:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000221 print(("Skipping counts file %r: %s"
222 % (self.infile, err)), file=sys.stderr)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000223
224 def update(self, other):
225 """Merge in the data from another CoverageResults"""
226 counts = self.counts
227 calledfuncs = self.calledfuncs
Skip Montanarocafc8112004-04-07 15:46:05 +0000228 callers = self.callers
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000229 other_counts = other.counts
230 other_calledfuncs = other.calledfuncs
Skip Montanarocafc8112004-04-07 15:46:05 +0000231 other_callers = other.callers
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000232
233 for key in other_counts.keys():
Jeremy Hylton38732e12003-04-21 22:04:46 +0000234 counts[key] = counts.get(key, 0) + other_counts[key]
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000235
236 for key in other_calledfuncs.keys():
237 calledfuncs[key] = 1
238
Skip Montanarocafc8112004-04-07 15:46:05 +0000239 for key in other_callers.keys():
240 callers[key] = 1
241
Jeremy Hylton38732e12003-04-21 22:04:46 +0000242 def write_results(self, show_missing=True, summary=False, coverdir=None):
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000243 """
244 @param coverdir
245 """
Skip Montanarocafc8112004-04-07 15:46:05 +0000246 if self.calledfuncs:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000247 print()
248 print("functions called:")
Skip Montanarocafc8112004-04-07 15:46:05 +0000249 calls = self.calledfuncs.keys()
250 calls.sort()
251 for filename, modulename, funcname in calls:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000252 print(("filename: %s, modulename: %s, funcname: %s"
253 % (filename, modulename, funcname)))
Skip Montanarocafc8112004-04-07 15:46:05 +0000254
255 if self.callers:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000256 print()
257 print("calling relationships:")
Skip Montanarocafc8112004-04-07 15:46:05 +0000258 calls = self.callers.keys()
259 calls.sort()
260 lastfile = lastcfile = ""
261 for ((pfile, pmod, pfunc), (cfile, cmod, cfunc)) in calls:
262 if pfile != lastfile:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000263 print()
264 print("***", pfile, "***")
Skip Montanarocafc8112004-04-07 15:46:05 +0000265 lastfile = pfile
266 lastcfile = ""
267 if cfile != pfile and lastcfile != cfile:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000268 print(" -->", cfile)
Skip Montanarocafc8112004-04-07 15:46:05 +0000269 lastcfile = cfile
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000270 print(" %s.%s -> %s.%s" % (pmod, pfunc, cmod, cfunc))
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000271
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000272 # turn the counts data ("(filename, lineno) = count") into something
273 # accessible on a per-file basis
274 per_file = {}
Jeremy Hylton38732e12003-04-21 22:04:46 +0000275 for filename, lineno in self.counts.keys():
276 lines_hit = per_file[filename] = per_file.get(filename, {})
277 lines_hit[lineno] = self.counts[(filename, lineno)]
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000278
279 # accumulate summary info, if needed
280 sums = {}
281
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000282 for filename, count in per_file.items():
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000283 # skip some "files" we don't care about...
284 if filename == "<string>":
285 continue
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000286 if filename.startswith("<doctest "):
287 continue
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000288
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000289 if filename.endswith((".pyc", ".pyo")):
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000290 filename = filename[:-1]
291
Jeremy Hylton38732e12003-04-21 22:04:46 +0000292 if coverdir is None:
293 dir = os.path.dirname(os.path.abspath(filename))
Jeremy Hyltonc8c8b942003-04-22 15:35:51 +0000294 modulename = modname(filename)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000295 else:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000296 dir = coverdir
297 if not os.path.exists(dir):
298 os.makedirs(dir)
Jeremy Hyltonc8c8b942003-04-22 15:35:51 +0000299 modulename = fullmodname(filename)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000300
301 # If desired, get a list of the line numbers which represent
302 # executable content (returned as a dict for better lookup speed)
303 if show_missing:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000304 lnotab = find_executable_linenos(filename)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000305 else:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000306 lnotab = {}
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000307
Jeremy Hylton38732e12003-04-21 22:04:46 +0000308 source = linecache.getlines(filename)
309 coverpath = os.path.join(dir, modulename + ".cover")
310 n_hits, n_lines = self.write_results_file(coverpath, source,
311 lnotab, count)
Tim Peters0eadaac2003-04-24 16:02:54 +0000312
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000313 if summary and n_lines:
314 percent = int(100 * n_hits / n_lines)
315 sums[modulename] = n_lines, percent, modulename, filename
316
317 if summary and sums:
318 mods = sums.keys()
319 mods.sort()
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000320 print("lines cov% module (path)")
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000321 for m in mods:
322 n_lines, percent, modulename, filename = sums[m]
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000323 print("%5d %3d%% %s (%s)" % sums[m])
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000324
325 if self.outfile:
326 # try and store counts and module info into self.outfile
327 try:
Skip Montanarocafc8112004-04-07 15:46:05 +0000328 pickle.dump((self.counts, self.calledfuncs, self.callers),
Jeremy Hyltond0e27052003-10-14 20:12:06 +0000329 open(self.outfile, 'wb'), 1)
Guido van Rossumb940e112007-01-10 16:19:56 +0000330 except IOError as err:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000331 print("Can't save counts files because %s" % err, file=sys.stderr)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000332
Jeremy Hylton38732e12003-04-21 22:04:46 +0000333 def write_results_file(self, path, lines, lnotab, lines_hit):
334 """Return a coverage results file in path."""
335
336 try:
337 outfile = open(path, "w")
Guido van Rossumb940e112007-01-10 16:19:56 +0000338 except IOError as err:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000339 print(("trace: Could not open %r for writing: %s"
340 "- skipping" % (path, err)), file=sys.stderr)
Guido van Rossumbbca8da2004-02-19 19:16:50 +0000341 return 0, 0
Jeremy Hylton38732e12003-04-21 22:04:46 +0000342
343 n_lines = 0
344 n_hits = 0
345 for i, line in enumerate(lines):
346 lineno = i + 1
347 # do the blank/comment match to try to mark more lines
348 # (help the reader find stuff that hasn't been covered)
349 if lineno in lines_hit:
350 outfile.write("%5d: " % lines_hit[lineno])
351 n_hits += 1
352 n_lines += 1
353 elif rx_blank.match(line):
Walter Dörwaldc1711722003-07-15 10:34:02 +0000354 outfile.write(" ")
Jeremy Hylton38732e12003-04-21 22:04:46 +0000355 else:
356 # lines preceded by no marks weren't hit
357 # Highlight them if so indicated, unless the line contains
358 # #pragma: NO COVER
359 if lineno in lnotab and not PRAGMA_NOCOVER in lines[i]:
360 outfile.write(">>>>>> ")
Jeremy Hylton546e34b2003-06-26 14:56:17 +0000361 n_lines += 1
Jeremy Hylton38732e12003-04-21 22:04:46 +0000362 else:
363 outfile.write(" ")
Jeremy Hylton38732e12003-04-21 22:04:46 +0000364 outfile.write(lines[i].expandtabs(8))
365 outfile.close()
366
367 return n_hits, n_lines
368
369def find_lines_from_code(code, strs):
370 """Return dict where keys are lines in the line number table."""
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000371 linenos = {}
372
373 line_increments = [ord(c) for c in code.co_lnotab[1::2]]
374 table_length = len(line_increments)
Jeremy Hylton38732e12003-04-21 22:04:46 +0000375 docstring = False
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000376
377 lineno = code.co_firstlineno
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000378 for li in line_increments:
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000379 lineno += li
Jeremy Hylton38732e12003-04-21 22:04:46 +0000380 if lineno not in strs:
381 linenos[lineno] = 1
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000382
383 return linenos
384
Jeremy Hylton38732e12003-04-21 22:04:46 +0000385def find_lines(code, strs):
386 """Return lineno dict for all code objects reachable from code."""
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000387 # get all of the lineno information from the code of this scope level
Jeremy Hylton38732e12003-04-21 22:04:46 +0000388 linenos = find_lines_from_code(code, strs)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000389
390 # and check the constants for references to other code objects
391 for c in code.co_consts:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000392 if isinstance(c, types.CodeType):
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000393 # find another code object, so recurse into it
Jeremy Hylton38732e12003-04-21 22:04:46 +0000394 linenos.update(find_lines(c, strs))
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000395 return linenos
396
Jeremy Hylton38732e12003-04-21 22:04:46 +0000397def find_strings(filename):
398 """Return a dict of possible docstring positions.
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000399
Jeremy Hylton38732e12003-04-21 22:04:46 +0000400 The dict maps line numbers to strings. There is an entry for
401 line that contains only a string or a part of a triple-quoted
402 string.
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000403 """
Jeremy Hylton38732e12003-04-21 22:04:46 +0000404 d = {}
405 # If the first token is a string, then it's the module docstring.
406 # Add this special case so that the test in the loop passes.
407 prev_ttype = token.INDENT
408 f = open(filename)
409 for ttype, tstr, start, end, line in tokenize.generate_tokens(f.readline):
410 if ttype == token.STRING:
411 if prev_ttype == token.INDENT:
412 sline, scol = start
413 eline, ecol = end
414 for i in range(sline, eline + 1):
415 d[i] = 1
416 prev_ttype = ttype
417 f.close()
418 return d
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000419
Jeremy Hylton38732e12003-04-21 22:04:46 +0000420def find_executable_linenos(filename):
421 """Return dict where keys are line numbers in the line number table."""
Jeremy Hylton38732e12003-04-21 22:04:46 +0000422 try:
Skip Montanaroc00fc842004-04-16 03:28:19 +0000423 prog = open(filename, "rU").read()
Guido van Rossumb940e112007-01-10 16:19:56 +0000424 except IOError as err:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000425 print(("Not printing coverage data for %r: %s"
426 % (filename, err)), file=sys.stderr)
Jeremy Hylton38732e12003-04-21 22:04:46 +0000427 return {}
428 code = compile(prog, filename, "exec")
429 strs = find_strings(filename)
430 return find_lines(code, strs)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000431
432class Trace:
Skip Montanarocafc8112004-04-07 15:46:05 +0000433 def __init__(self, count=1, trace=1, countfuncs=0, countcallers=0,
434 ignoremods=(), ignoredirs=(), infile=None, outfile=None):
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000435 """
436 @param count true iff it should count number of times each
Tim Petersf2715e02003-02-19 02:35:07 +0000437 line is executed
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000438 @param trace true iff it should print out each line that is
Tim Petersf2715e02003-02-19 02:35:07 +0000439 being counted
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000440 @param countfuncs true iff it should just output a list of
441 (filename, modulename, funcname,) for functions
442 that were called at least once; This overrides
Tim Petersf2715e02003-02-19 02:35:07 +0000443 `count' and `trace'
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000444 @param ignoremods a list of the names of modules to ignore
445 @param ignoredirs a list of the names of directories to ignore
Tim Petersf2715e02003-02-19 02:35:07 +0000446 all of the (recursive) contents of
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000447 @param infile file from which to read stored counts to be
Tim Petersf2715e02003-02-19 02:35:07 +0000448 added into the results
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000449 @param outfile file in which to write the results
450 """
451 self.infile = infile
452 self.outfile = outfile
453 self.ignore = Ignore(ignoremods, ignoredirs)
454 self.counts = {} # keys are (filename, linenumber)
455 self.blabbed = {} # for debugging
456 self.pathtobasename = {} # for memoizing os.path.basename
457 self.donothing = 0
458 self.trace = trace
459 self._calledfuncs = {}
Skip Montanarocafc8112004-04-07 15:46:05 +0000460 self._callers = {}
Skip Montanaro5bfd9842004-04-10 16:29:58 +0000461 self._caller_cache = {}
Skip Montanarocafc8112004-04-07 15:46:05 +0000462 if countcallers:
463 self.globaltrace = self.globaltrace_trackcallers
464 elif countfuncs:
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000465 self.globaltrace = self.globaltrace_countfuncs
466 elif trace and count:
467 self.globaltrace = self.globaltrace_lt
468 self.localtrace = self.localtrace_trace_and_count
469 elif trace:
470 self.globaltrace = self.globaltrace_lt
471 self.localtrace = self.localtrace_trace
472 elif count:
473 self.globaltrace = self.globaltrace_lt
474 self.localtrace = self.localtrace_count
475 else:
476 # Ahem -- do nothing? Okay.
477 self.donothing = 1
478
479 def run(self, cmd):
480 import __main__
481 dict = __main__.__dict__
482 if not self.donothing:
483 sys.settrace(self.globaltrace)
Jeremy Hylton546e34b2003-06-26 14:56:17 +0000484 threading.settrace(self.globaltrace)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000485 try:
Georg Brandl7cae87c2006-09-06 06:51:57 +0000486 exec(cmd, dict, dict)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000487 finally:
488 if not self.donothing:
489 sys.settrace(None)
Jeremy Hylton546e34b2003-06-26 14:56:17 +0000490 threading.settrace(None)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000491
492 def runctx(self, cmd, globals=None, locals=None):
493 if globals is None: globals = {}
494 if locals is None: locals = {}
495 if not self.donothing:
496 sys.settrace(self.globaltrace)
Jeremy Hylton546e34b2003-06-26 14:56:17 +0000497 threading.settrace(self.globaltrace)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000498 try:
Georg Brandl7cae87c2006-09-06 06:51:57 +0000499 exec(cmd, globals, locals)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000500 finally:
501 if not self.donothing:
502 sys.settrace(None)
Jeremy Hylton546e34b2003-06-26 14:56:17 +0000503 threading.settrace(None)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000504
505 def runfunc(self, func, *args, **kw):
506 result = None
507 if not self.donothing:
508 sys.settrace(self.globaltrace)
509 try:
Guido van Rossum68468eb2003-02-27 20:14:51 +0000510 result = func(*args, **kw)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000511 finally:
512 if not self.donothing:
513 sys.settrace(None)
514 return result
515
Skip Montanaro5bfd9842004-04-10 16:29:58 +0000516 def file_module_function_of(self, frame):
517 code = frame.f_code
518 filename = code.co_filename
519 if filename:
520 modulename = modname(filename)
521 else:
522 modulename = None
523
524 funcname = code.co_name
525 clsname = None
526 if code in self._caller_cache:
527 if self._caller_cache[code] is not None:
528 clsname = self._caller_cache[code]
529 else:
530 self._caller_cache[code] = None
531 ## use of gc.get_referrers() was suggested by Michael Hudson
532 # all functions which refer to this code object
533 funcs = [f for f in gc.get_referrers(code)
Neal Norwitz221085d2007-02-25 20:55:47 +0000534 if hasattr(f, "__doc__")]
Skip Montanaro5bfd9842004-04-10 16:29:58 +0000535 # require len(func) == 1 to avoid ambiguity caused by calls to
536 # new.function(): "In the face of ambiguity, refuse the
537 # temptation to guess."
538 if len(funcs) == 1:
539 dicts = [d for d in gc.get_referrers(funcs[0])
540 if isinstance(d, dict)]
541 if len(dicts) == 1:
542 classes = [c for c in gc.get_referrers(dicts[0])
543 if hasattr(c, "__bases__")]
544 if len(classes) == 1:
545 # ditto for new.classobj()
546 clsname = str(classes[0])
547 # cache the result - assumption is that new.* is
548 # not called later to disturb this relationship
549 # _caller_cache could be flushed if functions in
550 # the new module get called.
551 self._caller_cache[code] = clsname
552 if clsname is not None:
553 # final hack - module name shows up in str(cls), but we've already
554 # computed module name, so remove it
555 clsname = clsname.split(".")[1:]
556 clsname = ".".join(clsname)
557 funcname = "%s.%s" % (clsname, funcname)
558
559 return filename, modulename, funcname
560
Skip Montanarocafc8112004-04-07 15:46:05 +0000561 def globaltrace_trackcallers(self, frame, why, arg):
562 """Handler for call events.
563
564 Adds information about who called who to the self._callers dict.
565 """
566 if why == 'call':
567 # XXX Should do a better job of identifying methods
Skip Montanaro5bfd9842004-04-10 16:29:58 +0000568 this_func = self.file_module_function_of(frame)
569 parent_func = self.file_module_function_of(frame.f_back)
Skip Montanarocafc8112004-04-07 15:46:05 +0000570 self._callers[(parent_func, this_func)] = 1
571
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000572 def globaltrace_countfuncs(self, frame, why, arg):
Jeremy Hylton38732e12003-04-21 22:04:46 +0000573 """Handler for call events.
Tim Peters0eadaac2003-04-24 16:02:54 +0000574
Jeremy Hylton38732e12003-04-21 22:04:46 +0000575 Adds (filename, modulename, funcname) to the self._calledfuncs dict.
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000576 """
577 if why == 'call':
Skip Montanaro5bfd9842004-04-10 16:29:58 +0000578 this_func = self.file_module_function_of(frame)
579 self._calledfuncs[this_func] = 1
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000580
581 def globaltrace_lt(self, frame, why, arg):
Jeremy Hylton38732e12003-04-21 22:04:46 +0000582 """Handler for call events.
583
584 If the code block being entered is to be ignored, returns `None',
585 else returns self.localtrace.
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000586 """
587 if why == 'call':
Jeremy Hylton38732e12003-04-21 22:04:46 +0000588 code = frame.f_code
Thomas Wouterscf297e42007-02-23 15:07:44 +0000589 filename = frame.f_globals.get('__file__', None)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000590 if filename:
Jeremy Hyltondfbfe732003-04-21 22:49:17 +0000591 # XXX modname() doesn't work right for packages, so
592 # the ignore support won't work right for packages
Jeremy Hylton38732e12003-04-21 22:04:46 +0000593 modulename = modname(filename)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000594 if modulename is not None:
595 ignore_it = self.ignore.names(filename, modulename)
596 if not ignore_it:
597 if self.trace:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000598 print((" --- modulename: %s, funcname: %s"
599 % (modulename, code.co_name)))
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000600 return self.localtrace
601 else:
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000602 return None
603
604 def localtrace_trace_and_count(self, frame, why, arg):
Jeremy Hylton38732e12003-04-21 22:04:46 +0000605 if why == "line":
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000606 # record the file name and line number of every trace
Jeremy Hylton38732e12003-04-21 22:04:46 +0000607 filename = frame.f_code.co_filename
608 lineno = frame.f_lineno
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000609 key = filename, lineno
610 self.counts[key] = self.counts.get(key, 0) + 1
Tim Petersf2715e02003-02-19 02:35:07 +0000611
Jeremy Hylton38732e12003-04-21 22:04:46 +0000612 bname = os.path.basename(filename)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000613 print("%s(%d): %s" % (bname, lineno,
614 linecache.getline(filename, lineno)), end=' ')
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000615 return self.localtrace
616
617 def localtrace_trace(self, frame, why, arg):
Jeremy Hylton38732e12003-04-21 22:04:46 +0000618 if why == "line":
619 # record the file name and line number of every trace
620 filename = frame.f_code.co_filename
621 lineno = frame.f_lineno
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000622
Jeremy Hylton38732e12003-04-21 22:04:46 +0000623 bname = os.path.basename(filename)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000624 print("%s(%d): %s" % (bname, lineno,
625 linecache.getline(filename, lineno)), end=' ')
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000626 return self.localtrace
627
628 def localtrace_count(self, frame, why, arg):
Jeremy Hylton38732e12003-04-21 22:04:46 +0000629 if why == "line":
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000630 filename = frame.f_code.co_filename
631 lineno = frame.f_lineno
632 key = filename, lineno
633 self.counts[key] = self.counts.get(key, 0) + 1
634 return self.localtrace
635
636 def results(self):
637 return CoverageResults(self.counts, infile=self.infile,
638 outfile=self.outfile,
Skip Montanarocafc8112004-04-07 15:46:05 +0000639 calledfuncs=self._calledfuncs,
640 callers=self._callers)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000641
642def _err_exit(msg):
643 sys.stderr.write("%s: %s\n" % (sys.argv[0], msg))
644 sys.exit(1)
645
646def main(argv=None):
647 import getopt
648
649 if argv is None:
650 argv = sys.argv
651 try:
Skip Montanarocafc8112004-04-07 15:46:05 +0000652 opts, prog_argv = getopt.getopt(argv[1:], "tcrRf:d:msC:lT",
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000653 ["help", "version", "trace", "count",
654 "report", "no-report", "summary",
655 "file=", "missing",
656 "ignore-module=", "ignore-dir=",
Skip Montanarocafc8112004-04-07 15:46:05 +0000657 "coverdir=", "listfuncs",
658 "trackcalls"])
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000659
Guido van Rossumb940e112007-01-10 16:19:56 +0000660 except getopt.error as msg:
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000661 sys.stderr.write("%s: %s\n" % (sys.argv[0], msg))
662 sys.stderr.write("Try `%s --help' for more information\n"
663 % sys.argv[0])
664 sys.exit(1)
665
666 trace = 0
667 count = 0
668 report = 0
669 no_report = 0
670 counts_file = None
671 missing = 0
672 ignore_modules = []
673 ignore_dirs = []
674 coverdir = None
675 summary = 0
676 listfuncs = False
Skip Montanarocafc8112004-04-07 15:46:05 +0000677 countcallers = False
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000678
679 for opt, val in opts:
680 if opt == "--help":
681 usage(sys.stdout)
682 sys.exit(0)
683
684 if opt == "--version":
685 sys.stdout.write("trace 2.0\n")
686 sys.exit(0)
687
Skip Montanarocafc8112004-04-07 15:46:05 +0000688 if opt == "-T" or opt == "--trackcalls":
689 countcallers = True
690 continue
691
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000692 if opt == "-l" or opt == "--listfuncs":
693 listfuncs = True
694 continue
695
696 if opt == "-t" or opt == "--trace":
697 trace = 1
698 continue
699
700 if opt == "-c" or opt == "--count":
701 count = 1
702 continue
703
704 if opt == "-r" or opt == "--report":
705 report = 1
706 continue
707
708 if opt == "-R" or opt == "--no-report":
709 no_report = 1
710 continue
711
712 if opt == "-f" or opt == "--file":
713 counts_file = val
714 continue
715
716 if opt == "-m" or opt == "--missing":
717 missing = 1
718 continue
719
720 if opt == "-C" or opt == "--coverdir":
721 coverdir = val
722 continue
723
724 if opt == "-s" or opt == "--summary":
725 summary = 1
726 continue
727
728 if opt == "--ignore-module":
Georg Brandlfceab5a2008-01-19 20:08:23 +0000729 for mod in val.split(","):
730 ignore_modules.append(mod.strip())
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000731 continue
732
733 if opt == "--ignore-dir":
734 for s in val.split(os.pathsep):
735 s = os.path.expandvars(s)
736 # should I also call expanduser? (after all, could use $HOME)
737
738 s = s.replace("$prefix",
739 os.path.join(sys.prefix, "lib",
740 "python" + sys.version[:3]))
741 s = s.replace("$exec_prefix",
742 os.path.join(sys.exec_prefix, "lib",
743 "python" + sys.version[:3]))
744 s = os.path.normpath(s)
745 ignore_dirs.append(s)
746 continue
747
748 assert 0, "Should never get here"
749
750 if listfuncs and (count or trace):
751 _err_exit("cannot specify both --listfuncs and (--trace or --count)")
752
Skip Montanarocafc8112004-04-07 15:46:05 +0000753 if not (count or trace or report or listfuncs or countcallers):
754 _err_exit("must specify one of --trace, --count, --report, "
755 "--listfuncs, or --trackcalls")
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000756
757 if report and no_report:
758 _err_exit("cannot specify both --report and --no-report")
759
760 if report and not counts_file:
761 _err_exit("--report requires a --file")
762
763 if no_report and len(prog_argv) == 0:
764 _err_exit("missing name of file to run")
765
766 # everything is ready
767 if report:
768 results = CoverageResults(infile=counts_file, outfile=counts_file)
769 results.write_results(missing, summary=summary, coverdir=coverdir)
770 else:
771 sys.argv = prog_argv
772 progname = prog_argv[0]
773 sys.path[0] = os.path.split(progname)[0]
774
775 t = Trace(count, trace, countfuncs=listfuncs,
Skip Montanarocafc8112004-04-07 15:46:05 +0000776 countcallers=countcallers, ignoremods=ignore_modules,
777 ignoredirs=ignore_dirs, infile=counts_file,
778 outfile=counts_file)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000779 try:
Neal Norwitz01688022007-08-12 00:43:29 +0000780 fp = open(progname)
781 try:
782 script = fp.read()
783 finally:
784 fp.close()
785 t.run('exec(%r)' % (script,))
Guido van Rossumb940e112007-01-10 16:19:56 +0000786 except IOError as err:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000787 _err_exit("Cannot run file %r because: %s" % (sys.argv[0], err))
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000788 except SystemExit:
789 pass
790
791 results = t.results()
792
793 if not no_report:
794 results.write_results(missing, summary=summary, coverdir=coverdir)
795
796if __name__=='__main__':
797 main()