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 |
Skip Montanaro | 5bfd984 | 2004-04-10 16:29:58 +0000 | [diff] [blame] | 35 | trace.py --trackcalls spam.py eggs |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 36 | |
| 37 | Sample use, programmatically |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 38 | import sys |
| 39 | |
| 40 | # create a Trace object, telling it what to ignore, and whether to |
| 41 | # do tracing or line-counting or both. |
| 42 | tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,], trace=0, |
| 43 | count=1) |
| 44 | # run the new command using the given tracer |
| 45 | tracer.run('main()') |
| 46 | # make a report, placing output in /tmp |
| 47 | r = tracer.results() |
| 48 | r.write_results(show_missing=True, coverdir="/tmp") |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 49 | """ |
| 50 | |
Georg Brandl | 33c2881 | 2009-04-01 23:07:29 +0000 | [diff] [blame] | 51 | import io |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 52 | import linecache |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 53 | import os |
| 54 | import re |
| 55 | import sys |
Jeremy Hylton | 546e34b | 2003-06-26 14:56:17 +0000 | [diff] [blame] | 56 | import threading |
Christian Heimes | 380f7f2 | 2008-02-28 11:19:05 +0000 | [diff] [blame] | 57 | import time |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 58 | import token |
| 59 | import tokenize |
| 60 | import types |
Skip Montanaro | 5bfd984 | 2004-04-10 16:29:58 +0000 | [diff] [blame] | 61 | import gc |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 62 | |
Guido van Rossum | 99603b0 | 2007-07-20 00:22:32 +0000 | [diff] [blame] | 63 | import pickle |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 64 | |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 65 | def usage(outfile): |
| 66 | outfile.write("""Usage: %s [OPTIONS] <file> [ARGS] |
| 67 | |
| 68 | Meta-options: |
| 69 | --help Display this help then exit. |
| 70 | --version Output version information then exit. |
| 71 | |
| 72 | Otherwise, exactly one of the following three options must be given: |
| 73 | -t, --trace Print each line to sys.stdout before it is executed. |
| 74 | -c, --count Count the number of times each line is executed |
| 75 | and write the counts to <module>.cover for each |
| 76 | module executed, in the module's directory. |
| 77 | See also `--coverdir', `--file', `--no-report' below. |
Skip Montanaro | a7b8ac6 | 2003-06-27 19:09:33 +0000 | [diff] [blame] | 78 | -l, --listfuncs Keep track of which functions are executed at least |
Fred Drake | 01c623b | 2003-06-27 19:22:11 +0000 | [diff] [blame] | 79 | once and write the results to sys.stdout after the |
Skip Montanaro | a7b8ac6 | 2003-06-27 19:09:33 +0000 | [diff] [blame] | 80 | program exits. |
Skip Montanaro | cafc811 | 2004-04-07 15:46:05 +0000 | [diff] [blame] | 81 | -T, --trackcalls Keep track of caller/called pairs and write the |
| 82 | results to sys.stdout after the program exits. |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 83 | -r, --report Generate a report from a counts file; do not execute |
| 84 | any code. `--file' must specify the results file to |
| 85 | read, which must have been created in a previous run |
| 86 | with `--count --file=FILE'. |
| 87 | |
| 88 | Modifiers: |
| 89 | -f, --file=<file> File to accumulate counts over several runs. |
| 90 | -R, --no-report Do not generate the coverage report files. |
| 91 | Useful if you want to accumulate over several runs. |
| 92 | -C, --coverdir=<dir> Directory where the report files. The coverage |
| 93 | report for <package>.<module> is written to file |
| 94 | <dir>/<package>/<module>.cover. |
| 95 | -m, --missing Annotate executable lines that were not executed |
| 96 | with '>>>>>> '. |
| 97 | -s, --summary Write a brief summary on stdout for each file. |
| 98 | (Can only be used with --count or --report.) |
Christian Heimes | 380f7f2 | 2008-02-28 11:19:05 +0000 | [diff] [blame] | 99 | -g, --timing Prefix each line with the time since the program started. |
| 100 | Only used while tracing. |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 101 | |
| 102 | Filters, may be repeated multiple times: |
Georg Brandl | fceab5a | 2008-01-19 20:08:23 +0000 | [diff] [blame] | 103 | --ignore-module=<mod> Ignore the given module(s) and its submodules |
| 104 | (if it is a package). Accepts comma separated |
| 105 | list of module names |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 106 | --ignore-dir=<dir> Ignore files in the given directory (multiple |
| 107 | directories can be joined by os.pathsep). |
| 108 | """ % sys.argv[0]) |
| 109 | |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 110 | PRAGMA_NOCOVER = "#pragma NO COVER" |
| 111 | |
| 112 | # Simple rx to find lines with no code. |
| 113 | rx_blank = re.compile(r'^\s*(#.*)?$') |
| 114 | |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 115 | class Ignore: |
| 116 | def __init__(self, modules = None, dirs = None): |
| 117 | self._mods = modules or [] |
| 118 | self._dirs = dirs or [] |
| 119 | |
Andrew M. Kuchling | 54e14f2 | 2010-02-22 22:21:05 +0000 | [diff] [blame] | 120 | self._dirs = list(map(os.path.normpath, self._dirs)) |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 121 | self._ignore = { '<string>': 1 } |
| 122 | |
| 123 | def names(self, filename, modulename): |
Guido van Rossum | e2b70bc | 2006-08-18 22:13:04 +0000 | [diff] [blame] | 124 | if modulename in self._ignore: |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 125 | return self._ignore[modulename] |
| 126 | |
| 127 | # haven't seen this one before, so see if the module name is |
| 128 | # on the ignore list. Need to take some care since ignoring |
| 129 | # "cmp" musn't mean ignoring "cmpcache" but ignoring |
| 130 | # "Spam" must also mean ignoring "Spam.Eggs". |
| 131 | for mod in self._mods: |
| 132 | if mod == modulename: # Identical names, so ignore |
| 133 | self._ignore[modulename] = 1 |
| 134 | return 1 |
| 135 | # check if the module is a proper submodule of something on |
| 136 | # the ignore list |
| 137 | n = len(mod) |
| 138 | # (will not overflow since if the first n characters are the |
Fred Drake | db390c1 | 2005-10-28 14:39:47 +0000 | [diff] [blame] | 139 | # same and the name has not already occurred, then the size |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 140 | # of "name" is greater than that of "mod") |
| 141 | if mod == modulename[:n] and modulename[n] == '.': |
| 142 | self._ignore[modulename] = 1 |
| 143 | return 1 |
| 144 | |
| 145 | # Now check that __file__ isn't in one of the directories |
| 146 | if filename is None: |
| 147 | # must be a built-in, so we must ignore |
| 148 | self._ignore[modulename] = 1 |
| 149 | return 1 |
| 150 | |
| 151 | # Ignore a file when it contains one of the ignorable paths |
| 152 | for d in self._dirs: |
| 153 | # The '+ os.sep' is to ensure that d is a parent directory, |
| 154 | # as compared to cases like: |
| 155 | # d = "/usr/local" |
| 156 | # filename = "/usr/local.py" |
| 157 | # or |
| 158 | # d = "/usr/local.py" |
| 159 | # filename = "/usr/local.py" |
| 160 | if filename.startswith(d + os.sep): |
| 161 | self._ignore[modulename] = 1 |
| 162 | return 1 |
| 163 | |
| 164 | # Tried the different ways, so we don't ignore this module |
| 165 | self._ignore[modulename] = 0 |
| 166 | return 0 |
| 167 | |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 168 | def modname(path): |
| 169 | """Return a plausible module name for the patch.""" |
Jeremy Hylton | dfbfe73 | 2003-04-21 22:49:17 +0000 | [diff] [blame] | 170 | |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 171 | base = os.path.basename(path) |
| 172 | filename, ext = os.path.splitext(base) |
| 173 | return filename |
| 174 | |
Jeremy Hylton | dfbfe73 | 2003-04-21 22:49:17 +0000 | [diff] [blame] | 175 | def fullmodname(path): |
Jeremy Hylton | c8c8b94 | 2003-04-22 15:35:51 +0000 | [diff] [blame] | 176 | """Return a plausible module name for the path.""" |
Jeremy Hylton | dfbfe73 | 2003-04-21 22:49:17 +0000 | [diff] [blame] | 177 | |
| 178 | # If the file 'path' is part of a package, then the filename isn't |
| 179 | # enough to uniquely identify it. Try to do the right thing by |
| 180 | # looking in sys.path for the longest matching prefix. We'll |
| 181 | # assume that the rest is the package name. |
| 182 | |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 183 | comparepath = os.path.normcase(path) |
Jeremy Hylton | dfbfe73 | 2003-04-21 22:49:17 +0000 | [diff] [blame] | 184 | longest = "" |
| 185 | for dir in sys.path: |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 186 | dir = os.path.normcase(dir) |
| 187 | if comparepath.startswith(dir) and comparepath[len(dir)] == os.sep: |
Jeremy Hylton | dfbfe73 | 2003-04-21 22:49:17 +0000 | [diff] [blame] | 188 | if len(dir) > len(longest): |
| 189 | longest = dir |
| 190 | |
Guido van Rossum | b427c00 | 2003-10-10 23:02:01 +0000 | [diff] [blame] | 191 | if longest: |
| 192 | base = path[len(longest) + 1:] |
| 193 | else: |
| 194 | base = path |
Guido van Rossum | bbca8da | 2004-02-19 19:16:50 +0000 | [diff] [blame] | 195 | base = base.replace(os.sep, ".") |
| 196 | if os.altsep: |
| 197 | base = base.replace(os.altsep, ".") |
Jeremy Hylton | dfbfe73 | 2003-04-21 22:49:17 +0000 | [diff] [blame] | 198 | filename, ext = os.path.splitext(base) |
| 199 | return filename |
| 200 | |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 201 | class CoverageResults: |
| 202 | def __init__(self, counts=None, calledfuncs=None, infile=None, |
Skip Montanaro | cafc811 | 2004-04-07 15:46:05 +0000 | [diff] [blame] | 203 | callers=None, outfile=None): |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 204 | self.counts = counts |
| 205 | if self.counts is None: |
| 206 | self.counts = {} |
| 207 | self.counter = self.counts.copy() # map (filename, lineno) to count |
| 208 | self.calledfuncs = calledfuncs |
| 209 | if self.calledfuncs is None: |
| 210 | self.calledfuncs = {} |
| 211 | self.calledfuncs = self.calledfuncs.copy() |
Skip Montanaro | cafc811 | 2004-04-07 15:46:05 +0000 | [diff] [blame] | 212 | self.callers = callers |
| 213 | if self.callers is None: |
| 214 | self.callers = {} |
| 215 | self.callers = self.callers.copy() |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 216 | self.infile = infile |
| 217 | self.outfile = outfile |
| 218 | if self.infile: |
Jeremy Hylton | d7ce86d | 2003-07-07 16:08:47 +0000 | [diff] [blame] | 219 | # Try to merge existing counts file. |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 220 | try: |
Skip Montanaro | cafc811 | 2004-04-07 15:46:05 +0000 | [diff] [blame] | 221 | counts, calledfuncs, callers = \ |
| 222 | pickle.load(open(self.infile, 'rb')) |
| 223 | self.update(self.__class__(counts, calledfuncs, callers)) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 224 | except (IOError, EOFError, ValueError) as err: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 225 | print(("Skipping counts file %r: %s" |
| 226 | % (self.infile, err)), file=sys.stderr) |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 227 | |
Georg Brandl | 33c2881 | 2009-04-01 23:07:29 +0000 | [diff] [blame] | 228 | def is_ignored_filename(self, filename): |
| 229 | """Return True if the filename does not refer to a file |
| 230 | we want to have reported. |
| 231 | """ |
| 232 | return (filename == "<string>" or |
| 233 | filename.startswith("<doctest ")) |
| 234 | |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 235 | def update(self, other): |
| 236 | """Merge in the data from another CoverageResults""" |
| 237 | counts = self.counts |
| 238 | calledfuncs = self.calledfuncs |
Skip Montanaro | cafc811 | 2004-04-07 15:46:05 +0000 | [diff] [blame] | 239 | callers = self.callers |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 240 | other_counts = other.counts |
| 241 | other_calledfuncs = other.calledfuncs |
Skip Montanaro | cafc811 | 2004-04-07 15:46:05 +0000 | [diff] [blame] | 242 | other_callers = other.callers |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 243 | |
| 244 | for key in other_counts.keys(): |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 245 | counts[key] = counts.get(key, 0) + other_counts[key] |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 246 | |
| 247 | for key in other_calledfuncs.keys(): |
| 248 | calledfuncs[key] = 1 |
| 249 | |
Skip Montanaro | cafc811 | 2004-04-07 15:46:05 +0000 | [diff] [blame] | 250 | for key in other_callers.keys(): |
| 251 | callers[key] = 1 |
| 252 | |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 253 | def write_results(self, show_missing=True, summary=False, coverdir=None): |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 254 | """ |
| 255 | @param coverdir |
| 256 | """ |
Skip Montanaro | cafc811 | 2004-04-07 15:46:05 +0000 | [diff] [blame] | 257 | if self.calledfuncs: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 258 | print() |
| 259 | print("functions called:") |
Alexander Belopolsky | 13aeb36 | 2010-07-20 20:13:45 +0000 | [diff] [blame] | 260 | calls = self.calledfuncs.keys() |
| 261 | for filename, modulename, funcname in sorted(calls): |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 262 | print(("filename: %s, modulename: %s, funcname: %s" |
| 263 | % (filename, modulename, funcname))) |
Skip Montanaro | cafc811 | 2004-04-07 15:46:05 +0000 | [diff] [blame] | 264 | |
| 265 | if self.callers: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 266 | print() |
| 267 | print("calling relationships:") |
Skip Montanaro | cafc811 | 2004-04-07 15:46:05 +0000 | [diff] [blame] | 268 | lastfile = lastcfile = "" |
Georg Brandl | 33c2881 | 2009-04-01 23:07:29 +0000 | [diff] [blame] | 269 | for ((pfile, pmod, pfunc), (cfile, cmod, cfunc)) \ |
| 270 | in sorted(self.callers.keys()): |
Skip Montanaro | cafc811 | 2004-04-07 15:46:05 +0000 | [diff] [blame] | 271 | if pfile != lastfile: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 272 | print() |
| 273 | print("***", pfile, "***") |
Skip Montanaro | cafc811 | 2004-04-07 15:46:05 +0000 | [diff] [blame] | 274 | lastfile = pfile |
| 275 | lastcfile = "" |
| 276 | if cfile != pfile and lastcfile != cfile: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 277 | print(" -->", cfile) |
Skip Montanaro | cafc811 | 2004-04-07 15:46:05 +0000 | [diff] [blame] | 278 | lastcfile = cfile |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 279 | print(" %s.%s -> %s.%s" % (pmod, pfunc, cmod, cfunc)) |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 280 | |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 281 | # turn the counts data ("(filename, lineno) = count") into something |
| 282 | # accessible on a per-file basis |
| 283 | per_file = {} |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 284 | for filename, lineno in self.counts.keys(): |
| 285 | lines_hit = per_file[filename] = per_file.get(filename, {}) |
| 286 | lines_hit[lineno] = self.counts[(filename, lineno)] |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 287 | |
| 288 | # accumulate summary info, if needed |
| 289 | sums = {} |
| 290 | |
Guido van Rossum | cc2b016 | 2007-02-11 06:12:03 +0000 | [diff] [blame] | 291 | for filename, count in per_file.items(): |
Georg Brandl | 33c2881 | 2009-04-01 23:07:29 +0000 | [diff] [blame] | 292 | if self.is_ignored_filename(filename): |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 293 | continue |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 294 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 295 | if filename.endswith((".pyc", ".pyo")): |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 296 | filename = filename[:-1] |
| 297 | |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 298 | if coverdir is None: |
| 299 | dir = os.path.dirname(os.path.abspath(filename)) |
Jeremy Hylton | c8c8b94 | 2003-04-22 15:35:51 +0000 | [diff] [blame] | 300 | modulename = modname(filename) |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 301 | else: |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 302 | dir = coverdir |
| 303 | if not os.path.exists(dir): |
| 304 | os.makedirs(dir) |
Jeremy Hylton | c8c8b94 | 2003-04-22 15:35:51 +0000 | [diff] [blame] | 305 | modulename = fullmodname(filename) |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 306 | |
| 307 | # If desired, get a list of the line numbers which represent |
| 308 | # executable content (returned as a dict for better lookup speed) |
| 309 | if show_missing: |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 310 | lnotab = find_executable_linenos(filename) |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 311 | else: |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 312 | lnotab = {} |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 313 | |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 314 | source = linecache.getlines(filename) |
| 315 | coverpath = os.path.join(dir, modulename + ".cover") |
| 316 | n_hits, n_lines = self.write_results_file(coverpath, source, |
| 317 | lnotab, count) |
Tim Peters | 0eadaac | 2003-04-24 16:02:54 +0000 | [diff] [blame] | 318 | |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 319 | if summary and n_lines: |
| 320 | percent = int(100 * n_hits / n_lines) |
| 321 | sums[modulename] = n_lines, percent, modulename, filename |
| 322 | |
| 323 | if summary and sums: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 324 | print("lines cov% module (path)") |
Martin v. Löwis | 8efc62c | 2008-04-10 19:02:25 +0000 | [diff] [blame] | 325 | for m in sorted(sums.keys()): |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 326 | n_lines, percent, modulename, filename = sums[m] |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 327 | print("%5d %3d%% %s (%s)" % sums[m]) |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 328 | |
| 329 | if self.outfile: |
| 330 | # try and store counts and module info into self.outfile |
| 331 | try: |
Skip Montanaro | cafc811 | 2004-04-07 15:46:05 +0000 | [diff] [blame] | 332 | pickle.dump((self.counts, self.calledfuncs, self.callers), |
Jeremy Hylton | d0e2705 | 2003-10-14 20:12:06 +0000 | [diff] [blame] | 333 | open(self.outfile, 'wb'), 1) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 334 | except IOError as err: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 335 | print("Can't save counts files because %s" % err, file=sys.stderr) |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 336 | |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 337 | def write_results_file(self, path, lines, lnotab, lines_hit): |
| 338 | """Return a coverage results file in path.""" |
| 339 | |
| 340 | try: |
| 341 | outfile = open(path, "w") |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 342 | except IOError as err: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 343 | print(("trace: Could not open %r for writing: %s" |
| 344 | "- skipping" % (path, err)), file=sys.stderr) |
Guido van Rossum | bbca8da | 2004-02-19 19:16:50 +0000 | [diff] [blame] | 345 | return 0, 0 |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 346 | |
| 347 | n_lines = 0 |
| 348 | n_hits = 0 |
| 349 | for i, line in enumerate(lines): |
| 350 | lineno = i + 1 |
| 351 | # do the blank/comment match to try to mark more lines |
| 352 | # (help the reader find stuff that hasn't been covered) |
| 353 | if lineno in lines_hit: |
| 354 | outfile.write("%5d: " % lines_hit[lineno]) |
| 355 | n_hits += 1 |
| 356 | n_lines += 1 |
| 357 | elif rx_blank.match(line): |
Walter Dörwald | c171172 | 2003-07-15 10:34:02 +0000 | [diff] [blame] | 358 | outfile.write(" ") |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 359 | else: |
| 360 | # lines preceded by no marks weren't hit |
| 361 | # Highlight them if so indicated, unless the line contains |
| 362 | # #pragma: NO COVER |
| 363 | if lineno in lnotab and not PRAGMA_NOCOVER in lines[i]: |
| 364 | outfile.write(">>>>>> ") |
Jeremy Hylton | 546e34b | 2003-06-26 14:56:17 +0000 | [diff] [blame] | 365 | n_lines += 1 |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 366 | else: |
| 367 | outfile.write(" ") |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 368 | outfile.write(lines[i].expandtabs(8)) |
| 369 | outfile.close() |
| 370 | |
| 371 | return n_hits, n_lines |
| 372 | |
| 373 | def find_lines_from_code(code, strs): |
| 374 | """Return dict where keys are lines in the line number table.""" |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 375 | linenos = {} |
| 376 | |
Brett Cannon | e61426e | 2009-01-30 01:31:34 +0000 | [diff] [blame] | 377 | line_increments = code.co_lnotab[1::2] |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 378 | table_length = len(line_increments) |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 379 | docstring = False |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 380 | |
| 381 | lineno = code.co_firstlineno |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 382 | for li in line_increments: |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 383 | lineno += li |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 384 | if lineno not in strs: |
| 385 | linenos[lineno] = 1 |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 386 | |
| 387 | return linenos |
| 388 | |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 389 | def find_lines(code, strs): |
| 390 | """Return lineno dict for all code objects reachable from code.""" |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 391 | # 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] | 392 | linenos = find_lines_from_code(code, strs) |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 393 | |
| 394 | # and check the constants for references to other code objects |
| 395 | for c in code.co_consts: |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 396 | if isinstance(c, types.CodeType): |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 397 | # find another code object, so recurse into it |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 398 | linenos.update(find_lines(c, strs)) |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 399 | return linenos |
| 400 | |
Georg Brandl | 33c2881 | 2009-04-01 23:07:29 +0000 | [diff] [blame] | 401 | def find_strings(filename, encoding=None): |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 402 | """Return a dict of possible docstring positions. |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 403 | |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 404 | The dict maps line numbers to strings. There is an entry for |
| 405 | line that contains only a string or a part of a triple-quoted |
| 406 | string. |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 407 | """ |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 408 | d = {} |
| 409 | # If the first token is a string, then it's the module docstring. |
| 410 | # Add this special case so that the test in the loop passes. |
| 411 | prev_ttype = token.INDENT |
Georg Brandl | 33c2881 | 2009-04-01 23:07:29 +0000 | [diff] [blame] | 412 | f = open(filename, encoding=encoding) |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 413 | for ttype, tstr, start, end, line in tokenize.generate_tokens(f.readline): |
| 414 | if ttype == token.STRING: |
| 415 | if prev_ttype == token.INDENT: |
| 416 | sline, scol = start |
| 417 | eline, ecol = end |
| 418 | for i in range(sline, eline + 1): |
| 419 | d[i] = 1 |
| 420 | prev_ttype = ttype |
| 421 | f.close() |
| 422 | return d |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 423 | |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 424 | def find_executable_linenos(filename): |
| 425 | """Return dict where keys are line numbers in the line number table.""" |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 426 | try: |
Georg Brandl | 33c2881 | 2009-04-01 23:07:29 +0000 | [diff] [blame] | 427 | with io.FileIO(filename, 'r') as file: |
| 428 | encoding, lines = tokenize.detect_encoding(file.readline) |
| 429 | prog = open(filename, "r", encoding=encoding).read() |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 430 | except IOError as err: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 431 | print(("Not printing coverage data for %r: %s" |
| 432 | % (filename, err)), file=sys.stderr) |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 433 | return {} |
| 434 | code = compile(prog, filename, "exec") |
Georg Brandl | 33c2881 | 2009-04-01 23:07:29 +0000 | [diff] [blame] | 435 | strs = find_strings(filename, encoding) |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 436 | return find_lines(code, strs) |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 437 | |
| 438 | class Trace: |
Skip Montanaro | cafc811 | 2004-04-07 15:46:05 +0000 | [diff] [blame] | 439 | def __init__(self, count=1, trace=1, countfuncs=0, countcallers=0, |
Christian Heimes | 380f7f2 | 2008-02-28 11:19:05 +0000 | [diff] [blame] | 440 | ignoremods=(), ignoredirs=(), infile=None, outfile=None, |
| 441 | timing=False): |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 442 | """ |
| 443 | @param count true iff it should count number of times each |
Tim Peters | f2715e0 | 2003-02-19 02:35:07 +0000 | [diff] [blame] | 444 | line is executed |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 445 | @param trace true iff it should print out each line that is |
Tim Peters | f2715e0 | 2003-02-19 02:35:07 +0000 | [diff] [blame] | 446 | being counted |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 447 | @param countfuncs true iff it should just output a list of |
| 448 | (filename, modulename, funcname,) for functions |
| 449 | that were called at least once; This overrides |
Tim Peters | f2715e0 | 2003-02-19 02:35:07 +0000 | [diff] [blame] | 450 | `count' and `trace' |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 451 | @param ignoremods a list of the names of modules to ignore |
| 452 | @param ignoredirs a list of the names of directories to ignore |
Tim Peters | f2715e0 | 2003-02-19 02:35:07 +0000 | [diff] [blame] | 453 | all of the (recursive) contents of |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 454 | @param infile file from which to read stored counts to be |
Tim Peters | f2715e0 | 2003-02-19 02:35:07 +0000 | [diff] [blame] | 455 | added into the results |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 456 | @param outfile file in which to write the results |
Christian Heimes | 380f7f2 | 2008-02-28 11:19:05 +0000 | [diff] [blame] | 457 | @param timing true iff timing information be displayed |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 458 | """ |
| 459 | self.infile = infile |
| 460 | self.outfile = outfile |
| 461 | self.ignore = Ignore(ignoremods, ignoredirs) |
| 462 | self.counts = {} # keys are (filename, linenumber) |
| 463 | self.blabbed = {} # for debugging |
| 464 | self.pathtobasename = {} # for memoizing os.path.basename |
| 465 | self.donothing = 0 |
| 466 | self.trace = trace |
| 467 | self._calledfuncs = {} |
Skip Montanaro | cafc811 | 2004-04-07 15:46:05 +0000 | [diff] [blame] | 468 | self._callers = {} |
Skip Montanaro | 5bfd984 | 2004-04-10 16:29:58 +0000 | [diff] [blame] | 469 | self._caller_cache = {} |
Christian Heimes | 380f7f2 | 2008-02-28 11:19:05 +0000 | [diff] [blame] | 470 | self.start_time = None |
| 471 | if timing: |
| 472 | self.start_time = time.time() |
Skip Montanaro | cafc811 | 2004-04-07 15:46:05 +0000 | [diff] [blame] | 473 | if countcallers: |
| 474 | self.globaltrace = self.globaltrace_trackcallers |
| 475 | elif countfuncs: |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 476 | self.globaltrace = self.globaltrace_countfuncs |
| 477 | elif trace and count: |
| 478 | self.globaltrace = self.globaltrace_lt |
| 479 | self.localtrace = self.localtrace_trace_and_count |
| 480 | elif trace: |
| 481 | self.globaltrace = self.globaltrace_lt |
| 482 | self.localtrace = self.localtrace_trace |
| 483 | elif count: |
| 484 | self.globaltrace = self.globaltrace_lt |
| 485 | self.localtrace = self.localtrace_count |
| 486 | else: |
| 487 | # Ahem -- do nothing? Okay. |
| 488 | self.donothing = 1 |
| 489 | |
| 490 | def run(self, cmd): |
| 491 | import __main__ |
| 492 | dict = __main__.__dict__ |
| 493 | if not self.donothing: |
| 494 | sys.settrace(self.globaltrace) |
Jeremy Hylton | 546e34b | 2003-06-26 14:56:17 +0000 | [diff] [blame] | 495 | threading.settrace(self.globaltrace) |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 496 | try: |
Georg Brandl | 7cae87c | 2006-09-06 06:51:57 +0000 | [diff] [blame] | 497 | exec(cmd, dict, dict) |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 498 | finally: |
| 499 | if not self.donothing: |
| 500 | sys.settrace(None) |
Jeremy Hylton | 546e34b | 2003-06-26 14:56:17 +0000 | [diff] [blame] | 501 | threading.settrace(None) |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 502 | |
| 503 | def runctx(self, cmd, globals=None, locals=None): |
| 504 | if globals is None: globals = {} |
| 505 | if locals is None: locals = {} |
| 506 | if not self.donothing: |
| 507 | sys.settrace(self.globaltrace) |
Jeremy Hylton | 546e34b | 2003-06-26 14:56:17 +0000 | [diff] [blame] | 508 | threading.settrace(self.globaltrace) |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 509 | try: |
Georg Brandl | 7cae87c | 2006-09-06 06:51:57 +0000 | [diff] [blame] | 510 | exec(cmd, globals, locals) |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 511 | finally: |
| 512 | if not self.donothing: |
| 513 | sys.settrace(None) |
Jeremy Hylton | 546e34b | 2003-06-26 14:56:17 +0000 | [diff] [blame] | 514 | threading.settrace(None) |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 515 | |
| 516 | def runfunc(self, func, *args, **kw): |
| 517 | result = None |
| 518 | if not self.donothing: |
| 519 | sys.settrace(self.globaltrace) |
| 520 | try: |
Guido van Rossum | 68468eb | 2003-02-27 20:14:51 +0000 | [diff] [blame] | 521 | result = func(*args, **kw) |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 522 | finally: |
| 523 | if not self.donothing: |
| 524 | sys.settrace(None) |
| 525 | return result |
| 526 | |
Skip Montanaro | 5bfd984 | 2004-04-10 16:29:58 +0000 | [diff] [blame] | 527 | def file_module_function_of(self, frame): |
| 528 | code = frame.f_code |
| 529 | filename = code.co_filename |
| 530 | if filename: |
| 531 | modulename = modname(filename) |
| 532 | else: |
| 533 | modulename = None |
| 534 | |
| 535 | funcname = code.co_name |
| 536 | clsname = None |
| 537 | if code in self._caller_cache: |
| 538 | if self._caller_cache[code] is not None: |
| 539 | clsname = self._caller_cache[code] |
| 540 | else: |
| 541 | self._caller_cache[code] = None |
| 542 | ## use of gc.get_referrers() was suggested by Michael Hudson |
| 543 | # all functions which refer to this code object |
| 544 | funcs = [f for f in gc.get_referrers(code) |
Neal Norwitz | 221085d | 2007-02-25 20:55:47 +0000 | [diff] [blame] | 545 | if hasattr(f, "__doc__")] |
Skip Montanaro | 5bfd984 | 2004-04-10 16:29:58 +0000 | [diff] [blame] | 546 | # require len(func) == 1 to avoid ambiguity caused by calls to |
| 547 | # new.function(): "In the face of ambiguity, refuse the |
| 548 | # temptation to guess." |
| 549 | if len(funcs) == 1: |
| 550 | dicts = [d for d in gc.get_referrers(funcs[0]) |
| 551 | if isinstance(d, dict)] |
| 552 | if len(dicts) == 1: |
| 553 | classes = [c for c in gc.get_referrers(dicts[0]) |
| 554 | if hasattr(c, "__bases__")] |
| 555 | if len(classes) == 1: |
| 556 | # ditto for new.classobj() |
| 557 | clsname = str(classes[0]) |
| 558 | # cache the result - assumption is that new.* is |
| 559 | # not called later to disturb this relationship |
| 560 | # _caller_cache could be flushed if functions in |
| 561 | # the new module get called. |
| 562 | self._caller_cache[code] = clsname |
| 563 | if clsname is not None: |
| 564 | # final hack - module name shows up in str(cls), but we've already |
| 565 | # computed module name, so remove it |
| 566 | clsname = clsname.split(".")[1:] |
| 567 | clsname = ".".join(clsname) |
| 568 | funcname = "%s.%s" % (clsname, funcname) |
| 569 | |
| 570 | return filename, modulename, funcname |
| 571 | |
Skip Montanaro | cafc811 | 2004-04-07 15:46:05 +0000 | [diff] [blame] | 572 | def globaltrace_trackcallers(self, frame, why, arg): |
| 573 | """Handler for call events. |
| 574 | |
| 575 | Adds information about who called who to the self._callers dict. |
| 576 | """ |
| 577 | if why == 'call': |
| 578 | # XXX Should do a better job of identifying methods |
Skip Montanaro | 5bfd984 | 2004-04-10 16:29:58 +0000 | [diff] [blame] | 579 | this_func = self.file_module_function_of(frame) |
| 580 | parent_func = self.file_module_function_of(frame.f_back) |
Skip Montanaro | cafc811 | 2004-04-07 15:46:05 +0000 | [diff] [blame] | 581 | self._callers[(parent_func, this_func)] = 1 |
| 582 | |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 583 | def globaltrace_countfuncs(self, frame, why, arg): |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 584 | """Handler for call events. |
Tim Peters | 0eadaac | 2003-04-24 16:02:54 +0000 | [diff] [blame] | 585 | |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 586 | Adds (filename, modulename, funcname) to the self._calledfuncs dict. |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 587 | """ |
| 588 | if why == 'call': |
Skip Montanaro | 5bfd984 | 2004-04-10 16:29:58 +0000 | [diff] [blame] | 589 | this_func = self.file_module_function_of(frame) |
| 590 | self._calledfuncs[this_func] = 1 |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 591 | |
| 592 | def globaltrace_lt(self, frame, why, arg): |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 593 | """Handler for call events. |
| 594 | |
| 595 | If the code block being entered is to be ignored, returns `None', |
| 596 | else returns self.localtrace. |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 597 | """ |
| 598 | if why == 'call': |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 599 | code = frame.f_code |
Thomas Wouters | cf297e4 | 2007-02-23 15:07:44 +0000 | [diff] [blame] | 600 | filename = frame.f_globals.get('__file__', None) |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 601 | if filename: |
Jeremy Hylton | dfbfe73 | 2003-04-21 22:49:17 +0000 | [diff] [blame] | 602 | # XXX modname() doesn't work right for packages, so |
| 603 | # the ignore support won't work right for packages |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 604 | modulename = modname(filename) |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 605 | if modulename is not None: |
| 606 | ignore_it = self.ignore.names(filename, modulename) |
| 607 | if not ignore_it: |
| 608 | if self.trace: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 609 | print((" --- modulename: %s, funcname: %s" |
| 610 | % (modulename, code.co_name))) |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 611 | return self.localtrace |
| 612 | else: |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 613 | return None |
| 614 | |
| 615 | def localtrace_trace_and_count(self, frame, why, arg): |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 616 | if why == "line": |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 617 | # record the file name and line number of every trace |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 618 | filename = frame.f_code.co_filename |
| 619 | lineno = frame.f_lineno |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 620 | key = filename, lineno |
| 621 | self.counts[key] = self.counts.get(key, 0) + 1 |
Tim Peters | f2715e0 | 2003-02-19 02:35:07 +0000 | [diff] [blame] | 622 | |
Christian Heimes | 380f7f2 | 2008-02-28 11:19:05 +0000 | [diff] [blame] | 623 | if self.start_time: |
| 624 | print('%.2f' % (time.time() - self.start_time), end=' ') |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 625 | bname = os.path.basename(filename) |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 626 | print("%s(%d): %s" % (bname, lineno, |
| 627 | linecache.getline(filename, lineno)), end=' ') |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 628 | return self.localtrace |
| 629 | |
| 630 | def localtrace_trace(self, frame, why, arg): |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 631 | if why == "line": |
| 632 | # record the file name and line number of every trace |
| 633 | filename = frame.f_code.co_filename |
| 634 | lineno = frame.f_lineno |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 635 | |
Christian Heimes | 380f7f2 | 2008-02-28 11:19:05 +0000 | [diff] [blame] | 636 | if self.start_time: |
| 637 | print('%.2f' % (time.time() - self.start_time), end=' ') |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 638 | bname = os.path.basename(filename) |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 639 | print("%s(%d): %s" % (bname, lineno, |
| 640 | linecache.getline(filename, lineno)), end=' ') |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 641 | return self.localtrace |
| 642 | |
| 643 | def localtrace_count(self, frame, why, arg): |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 644 | if why == "line": |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 645 | filename = frame.f_code.co_filename |
| 646 | lineno = frame.f_lineno |
| 647 | key = filename, lineno |
| 648 | self.counts[key] = self.counts.get(key, 0) + 1 |
| 649 | return self.localtrace |
| 650 | |
| 651 | def results(self): |
| 652 | return CoverageResults(self.counts, infile=self.infile, |
| 653 | outfile=self.outfile, |
Skip Montanaro | cafc811 | 2004-04-07 15:46:05 +0000 | [diff] [blame] | 654 | calledfuncs=self._calledfuncs, |
| 655 | callers=self._callers) |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 656 | |
| 657 | def _err_exit(msg): |
| 658 | sys.stderr.write("%s: %s\n" % (sys.argv[0], msg)) |
| 659 | sys.exit(1) |
| 660 | |
| 661 | def main(argv=None): |
| 662 | import getopt |
| 663 | |
| 664 | if argv is None: |
| 665 | argv = sys.argv |
| 666 | try: |
Christian Heimes | 380f7f2 | 2008-02-28 11:19:05 +0000 | [diff] [blame] | 667 | opts, prog_argv = getopt.getopt(argv[1:], "tcrRf:d:msC:lTg", |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 668 | ["help", "version", "trace", "count", |
| 669 | "report", "no-report", "summary", |
| 670 | "file=", "missing", |
| 671 | "ignore-module=", "ignore-dir=", |
Skip Montanaro | cafc811 | 2004-04-07 15:46:05 +0000 | [diff] [blame] | 672 | "coverdir=", "listfuncs", |
Christian Heimes | 380f7f2 | 2008-02-28 11:19:05 +0000 | [diff] [blame] | 673 | "trackcalls", "timing"]) |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 674 | |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 675 | except getopt.error as msg: |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 676 | sys.stderr.write("%s: %s\n" % (sys.argv[0], msg)) |
| 677 | sys.stderr.write("Try `%s --help' for more information\n" |
| 678 | % sys.argv[0]) |
| 679 | sys.exit(1) |
| 680 | |
| 681 | trace = 0 |
| 682 | count = 0 |
| 683 | report = 0 |
| 684 | no_report = 0 |
| 685 | counts_file = None |
| 686 | missing = 0 |
| 687 | ignore_modules = [] |
| 688 | ignore_dirs = [] |
| 689 | coverdir = None |
| 690 | summary = 0 |
| 691 | listfuncs = False |
Skip Montanaro | cafc811 | 2004-04-07 15:46:05 +0000 | [diff] [blame] | 692 | countcallers = False |
Christian Heimes | 380f7f2 | 2008-02-28 11:19:05 +0000 | [diff] [blame] | 693 | timing = False |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 694 | |
| 695 | for opt, val in opts: |
| 696 | if opt == "--help": |
| 697 | usage(sys.stdout) |
| 698 | sys.exit(0) |
| 699 | |
| 700 | if opt == "--version": |
| 701 | sys.stdout.write("trace 2.0\n") |
| 702 | sys.exit(0) |
| 703 | |
Skip Montanaro | cafc811 | 2004-04-07 15:46:05 +0000 | [diff] [blame] | 704 | if opt == "-T" or opt == "--trackcalls": |
| 705 | countcallers = True |
| 706 | continue |
| 707 | |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 708 | if opt == "-l" or opt == "--listfuncs": |
| 709 | listfuncs = True |
| 710 | continue |
| 711 | |
Christian Heimes | 380f7f2 | 2008-02-28 11:19:05 +0000 | [diff] [blame] | 712 | if opt == "-g" or opt == "--timing": |
| 713 | timing = True |
| 714 | continue |
| 715 | |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 716 | if opt == "-t" or opt == "--trace": |
| 717 | trace = 1 |
| 718 | continue |
| 719 | |
| 720 | if opt == "-c" or opt == "--count": |
| 721 | count = 1 |
| 722 | continue |
| 723 | |
| 724 | if opt == "-r" or opt == "--report": |
| 725 | report = 1 |
| 726 | continue |
| 727 | |
| 728 | if opt == "-R" or opt == "--no-report": |
| 729 | no_report = 1 |
| 730 | continue |
| 731 | |
| 732 | if opt == "-f" or opt == "--file": |
| 733 | counts_file = val |
| 734 | continue |
| 735 | |
| 736 | if opt == "-m" or opt == "--missing": |
| 737 | missing = 1 |
| 738 | continue |
| 739 | |
| 740 | if opt == "-C" or opt == "--coverdir": |
| 741 | coverdir = val |
| 742 | continue |
| 743 | |
| 744 | if opt == "-s" or opt == "--summary": |
| 745 | summary = 1 |
| 746 | continue |
| 747 | |
| 748 | if opt == "--ignore-module": |
Georg Brandl | fceab5a | 2008-01-19 20:08:23 +0000 | [diff] [blame] | 749 | for mod in val.split(","): |
| 750 | ignore_modules.append(mod.strip()) |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 751 | continue |
| 752 | |
| 753 | if opt == "--ignore-dir": |
| 754 | for s in val.split(os.pathsep): |
| 755 | s = os.path.expandvars(s) |
| 756 | # should I also call expanduser? (after all, could use $HOME) |
| 757 | |
| 758 | s = s.replace("$prefix", |
| 759 | os.path.join(sys.prefix, "lib", |
| 760 | "python" + sys.version[:3])) |
| 761 | s = s.replace("$exec_prefix", |
| 762 | os.path.join(sys.exec_prefix, "lib", |
| 763 | "python" + sys.version[:3])) |
| 764 | s = os.path.normpath(s) |
| 765 | ignore_dirs.append(s) |
| 766 | continue |
| 767 | |
| 768 | assert 0, "Should never get here" |
| 769 | |
| 770 | if listfuncs and (count or trace): |
| 771 | _err_exit("cannot specify both --listfuncs and (--trace or --count)") |
| 772 | |
Skip Montanaro | cafc811 | 2004-04-07 15:46:05 +0000 | [diff] [blame] | 773 | if not (count or trace or report or listfuncs or countcallers): |
| 774 | _err_exit("must specify one of --trace, --count, --report, " |
| 775 | "--listfuncs, or --trackcalls") |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 776 | |
| 777 | if report and no_report: |
| 778 | _err_exit("cannot specify both --report and --no-report") |
| 779 | |
| 780 | if report and not counts_file: |
| 781 | _err_exit("--report requires a --file") |
| 782 | |
| 783 | if no_report and len(prog_argv) == 0: |
| 784 | _err_exit("missing name of file to run") |
| 785 | |
| 786 | # everything is ready |
| 787 | if report: |
| 788 | results = CoverageResults(infile=counts_file, outfile=counts_file) |
| 789 | results.write_results(missing, summary=summary, coverdir=coverdir) |
| 790 | else: |
| 791 | sys.argv = prog_argv |
| 792 | progname = prog_argv[0] |
| 793 | sys.path[0] = os.path.split(progname)[0] |
| 794 | |
| 795 | t = Trace(count, trace, countfuncs=listfuncs, |
Skip Montanaro | cafc811 | 2004-04-07 15:46:05 +0000 | [diff] [blame] | 796 | countcallers=countcallers, ignoremods=ignore_modules, |
| 797 | ignoredirs=ignore_dirs, infile=counts_file, |
Christian Heimes | 380f7f2 | 2008-02-28 11:19:05 +0000 | [diff] [blame] | 798 | outfile=counts_file, timing=timing) |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 799 | try: |
Alexander Belopolsky | eeec92f | 2010-07-21 17:50:34 +0000 | [diff] [blame] | 800 | with open(progname) as fp: |
| 801 | code = compile(fp.read(), progname, 'exec') |
| 802 | t.run(code) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 803 | except IOError as err: |
Jeremy Hylton | 38732e1 | 2003-04-21 22:04:46 +0000 | [diff] [blame] | 804 | _err_exit("Cannot run file %r because: %s" % (sys.argv[0], err)) |
Jeremy Hylton | 4edaa0d | 2003-02-18 15:06:17 +0000 | [diff] [blame] | 805 | except SystemExit: |
| 806 | pass |
| 807 | |
| 808 | results = t.results() |
| 809 | |
| 810 | if not no_report: |
| 811 | results.write_results(missing, summary=summary, coverdir=coverdir) |
| 812 | |
| 813 | if __name__=='__main__': |
| 814 | main() |