Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 1 | #!/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 | |
| 32 | Sample 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 |
| 35 | |
| 36 | Sample use, programmatically |
| 37 | # create a Trace object, telling it what to ignore, and whether to |
| 38 | # do tracing or line-counting or both. |
| 39 | trace = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,], trace=0, |
| 40 | count=1) |
| 41 | # run the new command using the given trace |
| 42 | trace.run(coverage.globaltrace, 'main()') |
| 43 | # make a report, telling it where you want output |
| 44 | r = trace.results() |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 45 | r.write_results(show_missing=True) |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 46 | """ |
| 47 | |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 48 | import linecache |
| 49 | import marshal |
| 50 | import os |
| 51 | import re |
| 52 | import sys |
| 53 | import token |
| 54 | import tokenize |
| 55 | import types |
| 56 | |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 57 | try: |
| 58 | import cPickle |
| 59 | pickle = cPickle |
| 60 | except ImportError: |
| 61 | import pickle |
| 62 | |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 63 | def usage(outfile): |
| 64 | outfile.write("""Usage: %s [OPTIONS] <file> [ARGS] |
| 65 | |
| 66 | Meta-options: |
| 67 | --help Display this help then exit. |
| 68 | --version Output version information then exit. |
| 69 | |
| 70 | Otherwise, 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. |
| 76 | -r, --report Generate a report from a counts file; do not execute |
| 77 | any code. `--file' must specify the results file to |
| 78 | read, which must have been created in a previous run |
| 79 | with `--count --file=FILE'. |
| 80 | |
| 81 | Modifiers: |
| 82 | -f, --file=<file> File to accumulate counts over several runs. |
| 83 | -R, --no-report Do not generate the coverage report files. |
| 84 | Useful if you want to accumulate over several runs. |
| 85 | -C, --coverdir=<dir> Directory where the report files. The coverage |
| 86 | report for <package>.<module> is written to file |
| 87 | <dir>/<package>/<module>.cover. |
| 88 | -m, --missing Annotate executable lines that were not executed |
| 89 | with '>>>>>> '. |
| 90 | -s, --summary Write a brief summary on stdout for each file. |
| 91 | (Can only be used with --count or --report.) |
| 92 | |
| 93 | Filters, may be repeated multiple times: |
| 94 | --ignore-module=<mod> Ignore the given module and its submodules |
| 95 | (if it is a package). |
| 96 | --ignore-dir=<dir> Ignore files in the given directory (multiple |
| 97 | directories can be joined by os.pathsep). |
| 98 | """ % sys.argv[0]) |
| 99 | |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 100 | PRAGMA_NOCOVER = "#pragma NO COVER" |
| 101 | |
| 102 | # Simple rx to find lines with no code. |
| 103 | rx_blank = re.compile(r'^\s*(#.*)?$') |
| 104 | |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 105 | class Ignore: |
| 106 | def __init__(self, modules = None, dirs = None): |
| 107 | self._mods = modules or [] |
| 108 | self._dirs = dirs or [] |
| 109 | |
| 110 | self._dirs = map(os.path.normpath, self._dirs) |
| 111 | self._ignore = { '<string>': 1 } |
| 112 | |
| 113 | def names(self, filename, modulename): |
| 114 | if self._ignore.has_key(modulename): |
| 115 | return self._ignore[modulename] |
| 116 | |
| 117 | # haven't seen this one before, so see if the module name is |
| 118 | # on the ignore list. Need to take some care since ignoring |
| 119 | # "cmp" musn't mean ignoring "cmpcache" but ignoring |
| 120 | # "Spam" must also mean ignoring "Spam.Eggs". |
| 121 | for mod in self._mods: |
| 122 | if mod == modulename: # Identical names, so ignore |
| 123 | self._ignore[modulename] = 1 |
| 124 | return 1 |
| 125 | # check if the module is a proper submodule of something on |
| 126 | # the ignore list |
| 127 | n = len(mod) |
| 128 | # (will not overflow since if the first n characters are the |
| 129 | # same and the name has not already occured, then the size |
| 130 | # of "name" is greater than that of "mod") |
| 131 | if mod == modulename[:n] and modulename[n] == '.': |
| 132 | self._ignore[modulename] = 1 |
| 133 | return 1 |
| 134 | |
| 135 | # Now check that __file__ isn't in one of the directories |
| 136 | if filename is None: |
| 137 | # must be a built-in, so we must ignore |
| 138 | self._ignore[modulename] = 1 |
| 139 | return 1 |
| 140 | |
| 141 | # Ignore a file when it contains one of the ignorable paths |
| 142 | for d in self._dirs: |
| 143 | # The '+ os.sep' is to ensure that d is a parent directory, |
| 144 | # as compared to cases like: |
| 145 | # d = "/usr/local" |
| 146 | # filename = "/usr/local.py" |
| 147 | # or |
| 148 | # d = "/usr/local.py" |
| 149 | # filename = "/usr/local.py" |
| 150 | if filename.startswith(d + os.sep): |
| 151 | self._ignore[modulename] = 1 |
| 152 | return 1 |
| 153 | |
| 154 | # Tried the different ways, so we don't ignore this module |
| 155 | self._ignore[modulename] = 0 |
| 156 | return 0 |
| 157 | |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 158 | def modname(path): |
| 159 | """Return a plausible module name for the patch.""" |
| 160 | base = os.path.basename(path) |
| 161 | filename, ext = os.path.splitext(base) |
| 162 | return filename |
| 163 | |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 164 | class CoverageResults: |
| 165 | def __init__(self, counts=None, calledfuncs=None, infile=None, |
Tim Peters | f2715e0 | 2003-02-19 02:35:07 +0000 | [diff] [blame] | 166 | outfile=None): |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 167 | self.counts = counts |
| 168 | if self.counts is None: |
| 169 | self.counts = {} |
| 170 | self.counter = self.counts.copy() # map (filename, lineno) to count |
| 171 | self.calledfuncs = calledfuncs |
| 172 | if self.calledfuncs is None: |
| 173 | self.calledfuncs = {} |
| 174 | self.calledfuncs = self.calledfuncs.copy() |
| 175 | self.infile = infile |
| 176 | self.outfile = outfile |
| 177 | if self.infile: |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 178 | # Try and merge existing counts file. |
| 179 | # This code understand a couple of old trace.py formats. |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 180 | try: |
| 181 | thingie = pickle.load(open(self.infile, 'r')) |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 182 | if isinstance(thingie, dict): |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 183 | self.update(self.__class__(thingie)) |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 184 | elif isinstance(thingie, tuple) and len(thingie) == 2: |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 185 | counts, calledfuncs = thingie |
| 186 | self.update(self.__class__(counts, calledfuncs)) |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 187 | except (IOError, EOFError), err: |
| 188 | print >> sys.stderr, ("Skipping counts file %r: %s" |
| 189 | % (self.infile, err)) |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 190 | except pickle.UnpicklingError: |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 191 | self.update(self.__class__(marshal.load(open(self.infile)))) |
| 192 | |
| 193 | def update(self, other): |
| 194 | """Merge in the data from another CoverageResults""" |
| 195 | counts = self.counts |
| 196 | calledfuncs = self.calledfuncs |
| 197 | other_counts = other.counts |
| 198 | other_calledfuncs = other.calledfuncs |
| 199 | |
| 200 | for key in other_counts.keys(): |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 201 | counts[key] = counts.get(key, 0) + other_counts[key] |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 202 | |
| 203 | for key in other_calledfuncs.keys(): |
| 204 | calledfuncs[key] = 1 |
| 205 | |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 206 | def write_results(self, show_missing=True, summary=False, coverdir=None): |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 207 | """ |
| 208 | @param coverdir |
| 209 | """ |
| 210 | for filename, modulename, funcname in self.calledfuncs.keys(): |
| 211 | print ("filename: %s, modulename: %s, funcname: %s" |
| 212 | % (filename, modulename, funcname)) |
| 213 | |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 214 | # turn the counts data ("(filename, lineno) = count") into something |
| 215 | # accessible on a per-file basis |
| 216 | per_file = {} |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 217 | for filename, lineno in self.counts.keys(): |
| 218 | lines_hit = per_file[filename] = per_file.get(filename, {}) |
| 219 | lines_hit[lineno] = self.counts[(filename, lineno)] |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 220 | |
| 221 | # accumulate summary info, if needed |
| 222 | sums = {} |
| 223 | |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 224 | for filename, count in per_file.iteritems(): |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 225 | # skip some "files" we don't care about... |
| 226 | if filename == "<string>": |
| 227 | continue |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 228 | modulename = modname(filename) |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 229 | |
| 230 | if filename.endswith(".pyc") or filename.endswith(".pyo"): |
| 231 | filename = filename[:-1] |
| 232 | |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 233 | if coverdir is None: |
| 234 | dir = os.path.dirname(os.path.abspath(filename)) |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 235 | else: |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 236 | dir = coverdir |
| 237 | if not os.path.exists(dir): |
| 238 | os.makedirs(dir) |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 239 | |
| 240 | # If desired, get a list of the line numbers which represent |
| 241 | # executable content (returned as a dict for better lookup speed) |
| 242 | if show_missing: |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 243 | lnotab = find_executable_linenos(filename) |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 244 | else: |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 245 | lnotab = {} |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 246 | |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 247 | source = linecache.getlines(filename) |
| 248 | coverpath = os.path.join(dir, modulename + ".cover") |
| 249 | n_hits, n_lines = self.write_results_file(coverpath, source, |
| 250 | lnotab, count) |
| 251 | |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 252 | if summary and n_lines: |
| 253 | percent = int(100 * n_hits / n_lines) |
| 254 | sums[modulename] = n_lines, percent, modulename, filename |
| 255 | |
| 256 | if summary and sums: |
| 257 | mods = sums.keys() |
| 258 | mods.sort() |
| 259 | print "lines cov% module (path)" |
| 260 | for m in mods: |
| 261 | n_lines, percent, modulename, filename = sums[m] |
| 262 | print "%5d %3d%% %s (%s)" % sums[m] |
| 263 | |
| 264 | if self.outfile: |
| 265 | # try and store counts and module info into self.outfile |
| 266 | try: |
| 267 | pickle.dump((self.counts, self.calledfuncs), |
| 268 | open(self.outfile, 'w'), 1) |
| 269 | except IOError, err: |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 270 | print >> sys.stderr, "Can't save counts files because %s" % err |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 271 | |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 272 | def write_results_file(self, path, lines, lnotab, lines_hit): |
| 273 | """Return a coverage results file in path.""" |
| 274 | |
| 275 | try: |
| 276 | outfile = open(path, "w") |
| 277 | except IOError, err: |
| 278 | print >> sys.stderr, ("trace: Could not open %r for writing: %s" |
| 279 | "- skipping" % (path, err)) |
| 280 | return |
| 281 | |
| 282 | n_lines = 0 |
| 283 | n_hits = 0 |
| 284 | for i, line in enumerate(lines): |
| 285 | lineno = i + 1 |
| 286 | # do the blank/comment match to try to mark more lines |
| 287 | # (help the reader find stuff that hasn't been covered) |
| 288 | if lineno in lines_hit: |
| 289 | outfile.write("%5d: " % lines_hit[lineno]) |
| 290 | n_hits += 1 |
| 291 | n_lines += 1 |
| 292 | elif rx_blank.match(line): |
| 293 | outfile.write(" ") |
| 294 | else: |
| 295 | # lines preceded by no marks weren't hit |
| 296 | # Highlight them if so indicated, unless the line contains |
| 297 | # #pragma: NO COVER |
| 298 | if lineno in lnotab and not PRAGMA_NOCOVER in lines[i]: |
| 299 | outfile.write(">>>>>> ") |
| 300 | else: |
| 301 | outfile.write(" ") |
| 302 | n_lines += 1 |
| 303 | outfile.write(lines[i].expandtabs(8)) |
| 304 | outfile.close() |
| 305 | |
| 306 | return n_hits, n_lines |
| 307 | |
| 308 | def find_lines_from_code(code, strs): |
| 309 | """Return dict where keys are lines in the line number table.""" |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 310 | linenos = {} |
| 311 | |
| 312 | line_increments = [ord(c) for c in code.co_lnotab[1::2]] |
| 313 | table_length = len(line_increments) |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 314 | docstring = False |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 315 | |
| 316 | lineno = code.co_firstlineno |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 317 | for li in line_increments: |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 318 | lineno += li |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 319 | if lineno not in strs: |
| 320 | linenos[lineno] = 1 |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 321 | |
| 322 | return linenos |
| 323 | |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 324 | def find_lines(code, strs): |
| 325 | """Return lineno dict for all code objects reachable from code.""" |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 326 | # get all of the lineno information from the code of this scope level |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 327 | linenos = find_lines_from_code(code, strs) |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 328 | |
| 329 | # and check the constants for references to other code objects |
| 330 | for c in code.co_consts: |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 331 | if isinstance(c, types.CodeType): |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 332 | # find another code object, so recurse into it |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 333 | linenos.update(find_lines(c, strs)) |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 334 | return linenos |
| 335 | |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 336 | def find_strings(filename): |
| 337 | """Return a dict of possible docstring positions. |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 338 | |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 339 | The dict maps line numbers to strings. There is an entry for |
| 340 | line that contains only a string or a part of a triple-quoted |
| 341 | string. |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 342 | """ |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 343 | d = {} |
| 344 | # If the first token is a string, then it's the module docstring. |
| 345 | # Add this special case so that the test in the loop passes. |
| 346 | prev_ttype = token.INDENT |
| 347 | f = open(filename) |
| 348 | for ttype, tstr, start, end, line in tokenize.generate_tokens(f.readline): |
| 349 | if ttype == token.STRING: |
| 350 | if prev_ttype == token.INDENT: |
| 351 | sline, scol = start |
| 352 | eline, ecol = end |
| 353 | for i in range(sline, eline + 1): |
| 354 | d[i] = 1 |
| 355 | prev_ttype = ttype |
| 356 | f.close() |
| 357 | return d |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 358 | |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 359 | def find_executable_linenos(filename): |
| 360 | """Return dict where keys are line numbers in the line number table.""" |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 361 | assert filename.endswith('.py') |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 362 | try: |
| 363 | prog = open(filename).read() |
| 364 | except IOError, err: |
| 365 | print >> sys.stderr, ("Not printing coverage data for %r: %s" |
| 366 | % (filename, err)) |
| 367 | return {} |
| 368 | code = compile(prog, filename, "exec") |
| 369 | strs = find_strings(filename) |
| 370 | return find_lines(code, strs) |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 371 | |
| 372 | class Trace: |
| 373 | def __init__(self, count=1, trace=1, countfuncs=0, ignoremods=(), |
| 374 | ignoredirs=(), infile=None, outfile=None): |
| 375 | """ |
| 376 | @param count true iff it should count number of times each |
Tim Peters | f2715e0 | 2003-02-19 02:35:07 +0000 | [diff] [blame] | 377 | line is executed |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 378 | @param trace true iff it should print out each line that is |
Tim Peters | f2715e0 | 2003-02-19 02:35:07 +0000 | [diff] [blame] | 379 | being counted |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 380 | @param countfuncs true iff it should just output a list of |
| 381 | (filename, modulename, funcname,) for functions |
| 382 | that were called at least once; This overrides |
Tim Peters | f2715e0 | 2003-02-19 02:35:07 +0000 | [diff] [blame] | 383 | `count' and `trace' |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 384 | @param ignoremods a list of the names of modules to ignore |
| 385 | @param ignoredirs a list of the names of directories to ignore |
Tim Peters | f2715e0 | 2003-02-19 02:35:07 +0000 | [diff] [blame] | 386 | all of the (recursive) contents of |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 387 | @param infile file from which to read stored counts to be |
Tim Peters | f2715e0 | 2003-02-19 02:35:07 +0000 | [diff] [blame] | 388 | added into the results |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 389 | @param outfile file in which to write the results |
| 390 | """ |
| 391 | self.infile = infile |
| 392 | self.outfile = outfile |
| 393 | self.ignore = Ignore(ignoremods, ignoredirs) |
| 394 | self.counts = {} # keys are (filename, linenumber) |
| 395 | self.blabbed = {} # for debugging |
| 396 | self.pathtobasename = {} # for memoizing os.path.basename |
| 397 | self.donothing = 0 |
| 398 | self.trace = trace |
| 399 | self._calledfuncs = {} |
| 400 | if countfuncs: |
| 401 | self.globaltrace = self.globaltrace_countfuncs |
| 402 | elif trace and count: |
| 403 | self.globaltrace = self.globaltrace_lt |
| 404 | self.localtrace = self.localtrace_trace_and_count |
| 405 | elif trace: |
| 406 | self.globaltrace = self.globaltrace_lt |
| 407 | self.localtrace = self.localtrace_trace |
| 408 | elif count: |
| 409 | self.globaltrace = self.globaltrace_lt |
| 410 | self.localtrace = self.localtrace_count |
| 411 | else: |
| 412 | # Ahem -- do nothing? Okay. |
| 413 | self.donothing = 1 |
| 414 | |
| 415 | def run(self, cmd): |
| 416 | import __main__ |
| 417 | dict = __main__.__dict__ |
| 418 | if not self.donothing: |
| 419 | sys.settrace(self.globaltrace) |
| 420 | try: |
| 421 | exec cmd in dict, dict |
| 422 | finally: |
| 423 | if not self.donothing: |
| 424 | sys.settrace(None) |
| 425 | |
| 426 | def runctx(self, cmd, globals=None, locals=None): |
| 427 | if globals is None: globals = {} |
| 428 | if locals is None: locals = {} |
| 429 | if not self.donothing: |
| 430 | sys.settrace(self.globaltrace) |
| 431 | try: |
| 432 | exec cmd in globals, locals |
| 433 | finally: |
| 434 | if not self.donothing: |
| 435 | sys.settrace(None) |
| 436 | |
| 437 | def runfunc(self, func, *args, **kw): |
| 438 | result = None |
| 439 | if not self.donothing: |
| 440 | sys.settrace(self.globaltrace) |
| 441 | try: |
Guido van Rossum | 68468eb | 2003-02-27 20:14:51 +0000 | [diff] [blame] | 442 | result = func(*args, **kw) |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 443 | finally: |
| 444 | if not self.donothing: |
| 445 | sys.settrace(None) |
| 446 | return result |
| 447 | |
| 448 | def globaltrace_countfuncs(self, frame, why, arg): |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 449 | """Handler for call events. |
| 450 | |
| 451 | Adds (filename, modulename, funcname) to the self._calledfuncs dict. |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 452 | """ |
| 453 | if why == 'call': |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 454 | code = frame.f_code |
| 455 | filename = code.co_filename |
| 456 | funcname = code.co_name |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 457 | if filename: |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 458 | modulename = modname(filename) |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 459 | else: |
| 460 | modulename = None |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 461 | self._calledfuncs[(filename, modulename, funcname)] = 1 |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 462 | |
| 463 | def globaltrace_lt(self, frame, why, arg): |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 464 | """Handler for call events. |
| 465 | |
| 466 | If the code block being entered is to be ignored, returns `None', |
| 467 | else returns self.localtrace. |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 468 | """ |
| 469 | if why == 'call': |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 470 | code = frame.f_code |
| 471 | filename = code.co_filename |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 472 | if filename: |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 473 | modulename = modname(filename) |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 474 | if modulename is not None: |
| 475 | ignore_it = self.ignore.names(filename, modulename) |
| 476 | if not ignore_it: |
| 477 | if self.trace: |
| 478 | print (" --- modulename: %s, funcname: %s" |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 479 | % (modulename, code.co_name)) |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 480 | return self.localtrace |
| 481 | else: |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 482 | return None |
| 483 | |
| 484 | def localtrace_trace_and_count(self, frame, why, arg): |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 485 | if why == "line": |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 486 | # record the file name and line number of every trace |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 487 | filename = frame.f_code.co_filename |
| 488 | lineno = frame.f_lineno |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 489 | key = filename, lineno |
| 490 | self.counts[key] = self.counts.get(key, 0) + 1 |
Tim Peters | f2715e0 | 2003-02-19 02:35:07 +0000 | [diff] [blame] | 491 | |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 492 | bname = os.path.basename(filename) |
| 493 | print "%s(%d): %s" % (bname, lineno, |
| 494 | linecache.getline(filename, lineno)), |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 495 | return self.localtrace |
| 496 | |
| 497 | def localtrace_trace(self, frame, why, arg): |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 498 | if why == "line": |
| 499 | # record the file name and line number of every trace |
| 500 | filename = frame.f_code.co_filename |
| 501 | lineno = frame.f_lineno |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 502 | |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 503 | bname = os.path.basename(filename) |
| 504 | print "%s(%d): %s" % (bname, lineno, |
| 505 | linecache.getline(filename, lineno)), |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 506 | return self.localtrace |
| 507 | |
| 508 | def localtrace_count(self, frame, why, arg): |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 509 | if why == "line": |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 510 | filename = frame.f_code.co_filename |
| 511 | lineno = frame.f_lineno |
| 512 | key = filename, lineno |
| 513 | self.counts[key] = self.counts.get(key, 0) + 1 |
| 514 | return self.localtrace |
| 515 | |
| 516 | def results(self): |
| 517 | return CoverageResults(self.counts, infile=self.infile, |
| 518 | outfile=self.outfile, |
| 519 | calledfuncs=self._calledfuncs) |
| 520 | |
| 521 | def _err_exit(msg): |
| 522 | sys.stderr.write("%s: %s\n" % (sys.argv[0], msg)) |
| 523 | sys.exit(1) |
| 524 | |
| 525 | def main(argv=None): |
| 526 | import getopt |
| 527 | |
| 528 | if argv is None: |
| 529 | argv = sys.argv |
| 530 | try: |
| 531 | opts, prog_argv = getopt.getopt(argv[1:], "tcrRf:d:msC:l", |
| 532 | ["help", "version", "trace", "count", |
| 533 | "report", "no-report", "summary", |
| 534 | "file=", "missing", |
| 535 | "ignore-module=", "ignore-dir=", |
| 536 | "coverdir=", "listfuncs",]) |
| 537 | |
| 538 | except getopt.error, msg: |
| 539 | sys.stderr.write("%s: %s\n" % (sys.argv[0], msg)) |
| 540 | sys.stderr.write("Try `%s --help' for more information\n" |
| 541 | % sys.argv[0]) |
| 542 | sys.exit(1) |
| 543 | |
| 544 | trace = 0 |
| 545 | count = 0 |
| 546 | report = 0 |
| 547 | no_report = 0 |
| 548 | counts_file = None |
| 549 | missing = 0 |
| 550 | ignore_modules = [] |
| 551 | ignore_dirs = [] |
| 552 | coverdir = None |
| 553 | summary = 0 |
| 554 | listfuncs = False |
| 555 | |
| 556 | for opt, val in opts: |
| 557 | if opt == "--help": |
| 558 | usage(sys.stdout) |
| 559 | sys.exit(0) |
| 560 | |
| 561 | if opt == "--version": |
| 562 | sys.stdout.write("trace 2.0\n") |
| 563 | sys.exit(0) |
| 564 | |
| 565 | if opt == "-l" or opt == "--listfuncs": |
| 566 | listfuncs = True |
| 567 | continue |
| 568 | |
| 569 | if opt == "-t" or opt == "--trace": |
| 570 | trace = 1 |
| 571 | continue |
| 572 | |
| 573 | if opt == "-c" or opt == "--count": |
| 574 | count = 1 |
| 575 | continue |
| 576 | |
| 577 | if opt == "-r" or opt == "--report": |
| 578 | report = 1 |
| 579 | continue |
| 580 | |
| 581 | if opt == "-R" or opt == "--no-report": |
| 582 | no_report = 1 |
| 583 | continue |
| 584 | |
| 585 | if opt == "-f" or opt == "--file": |
| 586 | counts_file = val |
| 587 | continue |
| 588 | |
| 589 | if opt == "-m" or opt == "--missing": |
| 590 | missing = 1 |
| 591 | continue |
| 592 | |
| 593 | if opt == "-C" or opt == "--coverdir": |
| 594 | coverdir = val |
| 595 | continue |
| 596 | |
| 597 | if opt == "-s" or opt == "--summary": |
| 598 | summary = 1 |
| 599 | continue |
| 600 | |
| 601 | if opt == "--ignore-module": |
| 602 | ignore_modules.append(val) |
| 603 | continue |
| 604 | |
| 605 | if opt == "--ignore-dir": |
| 606 | for s in val.split(os.pathsep): |
| 607 | s = os.path.expandvars(s) |
| 608 | # should I also call expanduser? (after all, could use $HOME) |
| 609 | |
| 610 | s = s.replace("$prefix", |
| 611 | os.path.join(sys.prefix, "lib", |
| 612 | "python" + sys.version[:3])) |
| 613 | s = s.replace("$exec_prefix", |
| 614 | os.path.join(sys.exec_prefix, "lib", |
| 615 | "python" + sys.version[:3])) |
| 616 | s = os.path.normpath(s) |
| 617 | ignore_dirs.append(s) |
| 618 | continue |
| 619 | |
| 620 | assert 0, "Should never get here" |
| 621 | |
| 622 | if listfuncs and (count or trace): |
| 623 | _err_exit("cannot specify both --listfuncs and (--trace or --count)") |
| 624 | |
| 625 | if not count and not trace and not report and not listfuncs: |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 626 | _err_exit("must specify one of --trace, --count, --report or " |
| 627 | "--listfuncs") |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 628 | |
| 629 | if report and no_report: |
| 630 | _err_exit("cannot specify both --report and --no-report") |
| 631 | |
| 632 | if report and not counts_file: |
| 633 | _err_exit("--report requires a --file") |
| 634 | |
| 635 | if no_report and len(prog_argv) == 0: |
| 636 | _err_exit("missing name of file to run") |
| 637 | |
| 638 | # everything is ready |
| 639 | if report: |
| 640 | results = CoverageResults(infile=counts_file, outfile=counts_file) |
| 641 | results.write_results(missing, summary=summary, coverdir=coverdir) |
| 642 | else: |
| 643 | sys.argv = prog_argv |
| 644 | progname = prog_argv[0] |
| 645 | sys.path[0] = os.path.split(progname)[0] |
| 646 | |
| 647 | t = Trace(count, trace, countfuncs=listfuncs, |
| 648 | ignoremods=ignore_modules, ignoredirs=ignore_dirs, |
| 649 | infile=counts_file, outfile=counts_file) |
| 650 | try: |
| 651 | t.run('execfile(' + `progname` + ')') |
| 652 | except IOError, err: |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame^] | 653 | _err_exit("Cannot run file %r because: %s" % (sys.argv[0], err)) |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 654 | except SystemExit: |
| 655 | pass |
| 656 | |
| 657 | results = t.results() |
| 658 | |
| 659 | if not no_report: |
| 660 | results.write_results(missing, summary=summary, coverdir=coverdir) |
| 661 | |
| 662 | if __name__=='__main__': |
| 663 | main() |