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