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