blob: b768829e9bff9e0a4236fd07c0c793bd795808af [file] [log] [blame]
Benjamin Peterson90f5ba52010-03-11 22:53:45 +00001#!/usr/bin/env python3
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +00002
3# portions copyright 2001, Autonomous Zones Industries, Inc., all rights...
4# err... reserved and offered to the public under the terms of the
5# Python 2.2 license.
6# Author: Zooko O'Whielacronx
7# http://zooko.com/
8# mailto:zooko@zooko.com
9#
10# Copyright 2000, Mojam Media, Inc., all rights reserved.
11# Author: Skip Montanaro
12#
13# Copyright 1999, Bioreason, Inc., all rights reserved.
14# Author: Andrew Dalke
15#
16# Copyright 1995-1997, Automatrix, Inc., all rights reserved.
17# Author: Skip Montanaro
18#
19# Copyright 1991-1995, Stichting Mathematisch Centrum, all rights reserved.
20#
21#
22# Permission to use, copy, modify, and distribute this Python software and
23# its associated documentation for any purpose without fee is hereby
24# granted, provided that the above copyright notice appears in all copies,
25# and that both that copyright notice and this permission notice appear in
26# supporting documentation, and that the name of neither Automatrix,
27# Bioreason or Mojam Media be used in advertising or publicity pertaining to
28# distribution of the software without specific, written prior permission.
29#
30"""program/module to trace Python program or function execution
31
32Sample use, command line:
33 trace.py -c -f counts --ignore-dir '$prefix' spam.py eggs
34 trace.py -t --ignore-dir '$prefix' spam.py eggs
Skip Montanaro5bfd9842004-04-10 16:29:58 +000035 trace.py --trackcalls spam.py eggs
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +000036
37Sample use, programmatically
Thomas Wouters477c8d52006-05-27 19:21:47 +000038 import sys
39
40 # create a Trace object, telling it what to ignore, and whether to
41 # do tracing or line-counting or both.
Vinay Sajip7ded1f02012-05-26 03:45:29 +010042 tracer = trace.Trace(ignoredirs=[sys.base_prefix, sys.base_exec_prefix,],
43 trace=0, count=1)
Thomas Wouters477c8d52006-05-27 19:21:47 +000044 # run the new command using the given tracer
45 tracer.run('main()')
46 # make a report, placing output in /tmp
47 r = tracer.results()
48 r.write_results(show_missing=True, coverdir="/tmp")
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +000049"""
Alexander Belopolsky44454af2010-11-20 18:21:07 +000050__all__ = ['Trace', 'CoverageResults']
Jeremy Hylton38732e12003-04-21 22:04:46 +000051import linecache
Jeremy Hylton38732e12003-04-21 22:04:46 +000052import os
53import re
54import sys
55import token
56import tokenize
Alexander Belopolsky4d770172010-09-13 18:14:34 +000057import inspect
Skip Montanaro5bfd9842004-04-10 16:29:58 +000058import gc
Alexander Belopolskyff09ce22010-09-24 18:03:12 +000059import dis
Guido van Rossum99603b02007-07-20 00:22:32 +000060import pickle
Victor Stinnerae586492014-09-02 23:18:25 +020061from time import monotonic as _time
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +000062
Alexander Belopolsky25b57412010-11-06 01:31:16 +000063try:
64 import threading
Brett Cannoncd171c82013-07-04 17:43:24 -040065except ImportError:
Alexander Belopolsky25b57412010-11-06 01:31:16 +000066 _settrace = sys.settrace
67
68 def _unsettrace():
69 sys.settrace(None)
70else:
71 def _settrace(func):
72 threading.settrace(func)
73 sys.settrace(func)
74
75 def _unsettrace():
76 sys.settrace(None)
77 threading.settrace(None)
78
Alexander Belopolsky44454af2010-11-20 18:21:07 +000079def _usage(outfile):
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +000080 outfile.write("""Usage: %s [OPTIONS] <file> [ARGS]
81
82Meta-options:
83--help Display this help then exit.
84--version Output version information then exit.
85
86Otherwise, exactly one of the following three options must be given:
87-t, --trace Print each line to sys.stdout before it is executed.
88-c, --count Count the number of times each line is executed
89 and write the counts to <module>.cover for each
90 module executed, in the module's directory.
91 See also `--coverdir', `--file', `--no-report' below.
Skip Montanaroa7b8ac62003-06-27 19:09:33 +000092-l, --listfuncs Keep track of which functions are executed at least
Fred Drake01c623b2003-06-27 19:22:11 +000093 once and write the results to sys.stdout after the
Skip Montanaroa7b8ac62003-06-27 19:09:33 +000094 program exits.
Skip Montanarocafc8112004-04-07 15:46:05 +000095-T, --trackcalls Keep track of caller/called pairs and write the
96 results to sys.stdout after the program exits.
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +000097-r, --report Generate a report from a counts file; do not execute
98 any code. `--file' must specify the results file to
99 read, which must have been created in a previous run
100 with `--count --file=FILE'.
101
102Modifiers:
103-f, --file=<file> File to accumulate counts over several runs.
104-R, --no-report Do not generate the coverage report files.
105 Useful if you want to accumulate over several runs.
106-C, --coverdir=<dir> Directory where the report files. The coverage
107 report for <package>.<module> is written to file
108 <dir>/<package>/<module>.cover.
109-m, --missing Annotate executable lines that were not executed
110 with '>>>>>> '.
111-s, --summary Write a brief summary on stdout for each file.
112 (Can only be used with --count or --report.)
Christian Heimes380f7f22008-02-28 11:19:05 +0000113-g, --timing Prefix each line with the time since the program started.
114 Only used while tracing.
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000115
116Filters, may be repeated multiple times:
Georg Brandlfceab5a2008-01-19 20:08:23 +0000117--ignore-module=<mod> Ignore the given module(s) and its submodules
118 (if it is a package). Accepts comma separated
119 list of module names
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000120--ignore-dir=<dir> Ignore files in the given directory (multiple
121 directories can be joined by os.pathsep).
122""" % sys.argv[0])
123
Jeremy Hylton38732e12003-04-21 22:04:46 +0000124PRAGMA_NOCOVER = "#pragma NO COVER"
125
126# Simple rx to find lines with no code.
127rx_blank = re.compile(r'^\s*(#.*)?$')
128
Alexander Belopolsky44454af2010-11-20 18:21:07 +0000129class _Ignore:
Alexander Belopolsky6672ea92010-11-08 18:32:40 +0000130 def __init__(self, modules=None, dirs=None):
131 self._mods = set() if not modules else set(modules)
132 self._dirs = [] if not dirs else [os.path.normpath(d)
133 for d in dirs]
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000134 self._ignore = { '<string>': 1 }
135
136 def names(self, filename, modulename):
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000137 if modulename in self._ignore:
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000138 return self._ignore[modulename]
139
140 # haven't seen this one before, so see if the module name is
Alexander Belopolsky6672ea92010-11-08 18:32:40 +0000141 # on the ignore list.
142 if modulename in self._mods: # Identical names, so ignore
143 self._ignore[modulename] = 1
144 return 1
145
146 # check if the module is a proper submodule of something on
147 # the ignore list
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000148 for mod in self._mods:
Alexander Belopolsky6672ea92010-11-08 18:32:40 +0000149 # Need to take some care since ignoring
150 # "cmp" mustn't mean ignoring "cmpcache" but ignoring
151 # "Spam" must also mean ignoring "Spam.Eggs".
152 if modulename.startswith(mod + '.'):
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000153 self._ignore[modulename] = 1
154 return 1
155
Alexander Belopolsky6672ea92010-11-08 18:32:40 +0000156 # Now check that filename isn't in one of the directories
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000157 if filename is None:
158 # must be a built-in, so we must ignore
159 self._ignore[modulename] = 1
160 return 1
161
162 # Ignore a file when it contains one of the ignorable paths
163 for d in self._dirs:
164 # The '+ os.sep' is to ensure that d is a parent directory,
165 # as compared to cases like:
166 # d = "/usr/local"
167 # filename = "/usr/local.py"
168 # or
169 # d = "/usr/local.py"
170 # filename = "/usr/local.py"
171 if filename.startswith(d + os.sep):
172 self._ignore[modulename] = 1
173 return 1
174
175 # Tried the different ways, so we don't ignore this module
176 self._ignore[modulename] = 0
177 return 0
178
Alexander Belopolsky44454af2010-11-20 18:21:07 +0000179def _modname(path):
Jeremy Hylton38732e12003-04-21 22:04:46 +0000180 """Return a plausible module name for the patch."""
Jeremy Hyltondfbfe732003-04-21 22:49:17 +0000181
Jeremy Hylton38732e12003-04-21 22:04:46 +0000182 base = os.path.basename(path)
183 filename, ext = os.path.splitext(base)
184 return filename
185
Alexander Belopolsky44454af2010-11-20 18:21:07 +0000186def _fullmodname(path):
Jeremy Hyltonc8c8b942003-04-22 15:35:51 +0000187 """Return a plausible module name for the path."""
Jeremy Hyltondfbfe732003-04-21 22:49:17 +0000188
189 # If the file 'path' is part of a package, then the filename isn't
190 # enough to uniquely identify it. Try to do the right thing by
191 # looking in sys.path for the longest matching prefix. We'll
192 # assume that the rest is the package name.
193
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000194 comparepath = os.path.normcase(path)
Jeremy Hyltondfbfe732003-04-21 22:49:17 +0000195 longest = ""
196 for dir in sys.path:
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000197 dir = os.path.normcase(dir)
198 if comparepath.startswith(dir) and comparepath[len(dir)] == os.sep:
Jeremy Hyltondfbfe732003-04-21 22:49:17 +0000199 if len(dir) > len(longest):
200 longest = dir
201
Guido van Rossumb427c002003-10-10 23:02:01 +0000202 if longest:
203 base = path[len(longest) + 1:]
204 else:
205 base = path
Georg Brandl120d6332010-08-01 14:38:17 +0000206 # the drive letter is never part of the module name
207 drive, base = os.path.splitdrive(base)
Guido van Rossumbbca8da2004-02-19 19:16:50 +0000208 base = base.replace(os.sep, ".")
209 if os.altsep:
210 base = base.replace(os.altsep, ".")
Jeremy Hyltondfbfe732003-04-21 22:49:17 +0000211 filename, ext = os.path.splitext(base)
Georg Brandl120d6332010-08-01 14:38:17 +0000212 return filename.lstrip(".")
Jeremy Hyltondfbfe732003-04-21 22:49:17 +0000213
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000214class CoverageResults:
215 def __init__(self, counts=None, calledfuncs=None, infile=None,
Skip Montanarocafc8112004-04-07 15:46:05 +0000216 callers=None, outfile=None):
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000217 self.counts = counts
218 if self.counts is None:
219 self.counts = {}
220 self.counter = self.counts.copy() # map (filename, lineno) to count
221 self.calledfuncs = calledfuncs
222 if self.calledfuncs is None:
223 self.calledfuncs = {}
224 self.calledfuncs = self.calledfuncs.copy()
Skip Montanarocafc8112004-04-07 15:46:05 +0000225 self.callers = callers
226 if self.callers is None:
227 self.callers = {}
228 self.callers = self.callers.copy()
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000229 self.infile = infile
230 self.outfile = outfile
231 if self.infile:
Jeremy Hyltond7ce86d2003-07-07 16:08:47 +0000232 # Try to merge existing counts file.
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000233 try:
Serhiy Storchaka46ba6c82015-04-04 11:01:02 +0300234 with open(self.infile, 'rb') as f:
235 counts, calledfuncs, callers = pickle.load(f)
Skip Montanarocafc8112004-04-07 15:46:05 +0000236 self.update(self.__class__(counts, calledfuncs, callers))
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200237 except (OSError, EOFError, ValueError) as err:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000238 print(("Skipping counts file %r: %s"
239 % (self.infile, err)), file=sys.stderr)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000240
Georg Brandl33c28812009-04-01 23:07:29 +0000241 def is_ignored_filename(self, filename):
242 """Return True if the filename does not refer to a file
243 we want to have reported.
244 """
Brett Cannon9fe92d12012-04-10 21:05:53 -0400245 return filename.startswith('<') and filename.endswith('>')
Georg Brandl33c28812009-04-01 23:07:29 +0000246
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000247 def update(self, other):
248 """Merge in the data from another CoverageResults"""
249 counts = self.counts
250 calledfuncs = self.calledfuncs
Skip Montanarocafc8112004-04-07 15:46:05 +0000251 callers = self.callers
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000252 other_counts = other.counts
253 other_calledfuncs = other.calledfuncs
Skip Montanarocafc8112004-04-07 15:46:05 +0000254 other_callers = other.callers
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000255
Alexander Belopolsky0ae33612010-09-27 15:49:20 +0000256 for key in other_counts:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000257 counts[key] = counts.get(key, 0) + other_counts[key]
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000258
Alexander Belopolsky0ae33612010-09-27 15:49:20 +0000259 for key in other_calledfuncs:
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000260 calledfuncs[key] = 1
261
Alexander Belopolsky0ae33612010-09-27 15:49:20 +0000262 for key in other_callers:
Skip Montanarocafc8112004-04-07 15:46:05 +0000263 callers[key] = 1
264
Jeremy Hylton38732e12003-04-21 22:04:46 +0000265 def write_results(self, show_missing=True, summary=False, coverdir=None):
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000266 """
267 @param coverdir
268 """
Skip Montanarocafc8112004-04-07 15:46:05 +0000269 if self.calledfuncs:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000270 print()
271 print("functions called:")
Alexander Belopolsky0ae33612010-09-27 15:49:20 +0000272 calls = self.calledfuncs
Alexander Belopolsky533a1672010-07-20 19:55:18 +0000273 for filename, modulename, funcname in sorted(calls):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000274 print(("filename: %s, modulename: %s, funcname: %s"
275 % (filename, modulename, funcname)))
Skip Montanarocafc8112004-04-07 15:46:05 +0000276
277 if self.callers:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000278 print()
279 print("calling relationships:")
Skip Montanarocafc8112004-04-07 15:46:05 +0000280 lastfile = lastcfile = ""
Georg Brandl33c28812009-04-01 23:07:29 +0000281 for ((pfile, pmod, pfunc), (cfile, cmod, cfunc)) \
Alexander Belopolsky0ae33612010-09-27 15:49:20 +0000282 in sorted(self.callers):
Skip Montanarocafc8112004-04-07 15:46:05 +0000283 if pfile != lastfile:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000284 print()
285 print("***", pfile, "***")
Skip Montanarocafc8112004-04-07 15:46:05 +0000286 lastfile = pfile
287 lastcfile = ""
288 if cfile != pfile and lastcfile != cfile:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000289 print(" -->", cfile)
Skip Montanarocafc8112004-04-07 15:46:05 +0000290 lastcfile = cfile
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000291 print(" %s.%s -> %s.%s" % (pmod, pfunc, cmod, cfunc))
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000292
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000293 # turn the counts data ("(filename, lineno) = count") into something
294 # accessible on a per-file basis
295 per_file = {}
Alexander Belopolsky0ae33612010-09-27 15:49:20 +0000296 for filename, lineno in self.counts:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000297 lines_hit = per_file[filename] = per_file.get(filename, {})
298 lines_hit[lineno] = self.counts[(filename, lineno)]
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000299
300 # accumulate summary info, if needed
301 sums = {}
302
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000303 for filename, count in per_file.items():
Georg Brandl33c28812009-04-01 23:07:29 +0000304 if self.is_ignored_filename(filename):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000305 continue
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000306
Brett Cannonf299abd2015-04-13 14:21:02 -0400307 if filename.endswith(".pyc"):
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000308 filename = filename[:-1]
309
Jeremy Hylton38732e12003-04-21 22:04:46 +0000310 if coverdir is None:
311 dir = os.path.dirname(os.path.abspath(filename))
Alexander Belopolsky44454af2010-11-20 18:21:07 +0000312 modulename = _modname(filename)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000313 else:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000314 dir = coverdir
315 if not os.path.exists(dir):
316 os.makedirs(dir)
Alexander Belopolsky44454af2010-11-20 18:21:07 +0000317 modulename = _fullmodname(filename)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000318
319 # If desired, get a list of the line numbers which represent
320 # executable content (returned as a dict for better lookup speed)
321 if show_missing:
Alexander Belopolsky44454af2010-11-20 18:21:07 +0000322 lnotab = _find_executable_linenos(filename)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000323 else:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000324 lnotab = {}
Alexander Belopolskyf026dae2014-06-29 17:44:05 -0400325 if lnotab:
326 source = linecache.getlines(filename)
327 coverpath = os.path.join(dir, modulename + ".cover")
328 with open(filename, 'rb') as fp:
329 encoding, _ = tokenize.detect_encoding(fp.readline)
330 n_hits, n_lines = self.write_results_file(coverpath, source,
331 lnotab, count, encoding)
332 if summary and n_lines:
333 percent = int(100 * n_hits / n_lines)
334 sums[modulename] = n_lines, percent, modulename, filename
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000335
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000336
337 if summary and sums:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000338 print("lines cov% module (path)")
Alexander Belopolsky0ae33612010-09-27 15:49:20 +0000339 for m in sorted(sums):
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000340 n_lines, percent, modulename, filename = sums[m]
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000341 print("%5d %3d%% %s (%s)" % sums[m])
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000342
343 if self.outfile:
344 # try and store counts and module info into self.outfile
345 try:
Skip Montanarocafc8112004-04-07 15:46:05 +0000346 pickle.dump((self.counts, self.calledfuncs, self.callers),
Jeremy Hyltond0e27052003-10-14 20:12:06 +0000347 open(self.outfile, 'wb'), 1)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200348 except OSError as err:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000349 print("Can't save counts files because %s" % err, file=sys.stderr)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000350
Victor Stinner64bc3b22010-11-07 15:47:36 +0000351 def write_results_file(self, path, lines, lnotab, lines_hit, encoding=None):
Jeremy Hylton38732e12003-04-21 22:04:46 +0000352 """Return a coverage results file in path."""
353
354 try:
Victor Stinner64bc3b22010-11-07 15:47:36 +0000355 outfile = open(path, "w", encoding=encoding)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200356 except OSError as err:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000357 print(("trace: Could not open %r for writing: %s"
358 "- skipping" % (path, err)), file=sys.stderr)
Guido van Rossumbbca8da2004-02-19 19:16:50 +0000359 return 0, 0
Jeremy Hylton38732e12003-04-21 22:04:46 +0000360
361 n_lines = 0
362 n_hits = 0
Serhiy Storchaka46ba6c82015-04-04 11:01:02 +0300363 with outfile:
364 for lineno, line in enumerate(lines, 1):
365 # do the blank/comment match to try to mark more lines
366 # (help the reader find stuff that hasn't been covered)
367 if lineno in lines_hit:
368 outfile.write("%5d: " % lines_hit[lineno])
369 n_hits += 1
Jeremy Hylton546e34b2003-06-26 14:56:17 +0000370 n_lines += 1
Serhiy Storchaka46ba6c82015-04-04 11:01:02 +0300371 elif rx_blank.match(line):
Jeremy Hylton38732e12003-04-21 22:04:46 +0000372 outfile.write(" ")
Serhiy Storchaka46ba6c82015-04-04 11:01:02 +0300373 else:
374 # lines preceded by no marks weren't hit
375 # Highlight them if so indicated, unless the line contains
376 # #pragma: NO COVER
377 if lineno in lnotab and not PRAGMA_NOCOVER in line:
378 outfile.write(">>>>>> ")
379 n_lines += 1
380 else:
381 outfile.write(" ")
382 outfile.write(line.expandtabs(8))
Jeremy Hylton38732e12003-04-21 22:04:46 +0000383
384 return n_hits, n_lines
385
Alexander Belopolsky44454af2010-11-20 18:21:07 +0000386def _find_lines_from_code(code, strs):
Jeremy Hylton38732e12003-04-21 22:04:46 +0000387 """Return dict where keys are lines in the line number table."""
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000388 linenos = {}
389
Alexander Belopolskyff09ce22010-09-24 18:03:12 +0000390 for _, lineno in dis.findlinestarts(code):
Jeremy Hylton38732e12003-04-21 22:04:46 +0000391 if lineno not in strs:
392 linenos[lineno] = 1
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000393
394 return linenos
395
Alexander Belopolsky44454af2010-11-20 18:21:07 +0000396def _find_lines(code, strs):
Jeremy Hylton38732e12003-04-21 22:04:46 +0000397 """Return lineno dict for all code objects reachable from code."""
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000398 # get all of the lineno information from the code of this scope level
Alexander Belopolsky44454af2010-11-20 18:21:07 +0000399 linenos = _find_lines_from_code(code, strs)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000400
401 # and check the constants for references to other code objects
402 for c in code.co_consts:
Alexander Belopolsky4d770172010-09-13 18:14:34 +0000403 if inspect.iscode(c):
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000404 # find another code object, so recurse into it
Alexander Belopolsky44454af2010-11-20 18:21:07 +0000405 linenos.update(_find_lines(c, strs))
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000406 return linenos
407
Alexander Belopolsky44454af2010-11-20 18:21:07 +0000408def _find_strings(filename, encoding=None):
Jeremy Hylton38732e12003-04-21 22:04:46 +0000409 """Return a dict of possible docstring positions.
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000410
Jeremy Hylton38732e12003-04-21 22:04:46 +0000411 The dict maps line numbers to strings. There is an entry for
412 line that contains only a string or a part of a triple-quoted
413 string.
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000414 """
Jeremy Hylton38732e12003-04-21 22:04:46 +0000415 d = {}
416 # If the first token is a string, then it's the module docstring.
417 # Add this special case so that the test in the loop passes.
418 prev_ttype = token.INDENT
Benjamin Petersonb2fda232010-10-30 23:51:34 +0000419 with open(filename, encoding=encoding) as f:
420 tok = tokenize.generate_tokens(f.readline)
421 for ttype, tstr, start, end, line in tok:
422 if ttype == token.STRING:
423 if prev_ttype == token.INDENT:
424 sline, scol = start
425 eline, ecol = end
426 for i in range(sline, eline + 1):
427 d[i] = 1
428 prev_ttype = ttype
Jeremy Hylton38732e12003-04-21 22:04:46 +0000429 return d
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000430
Alexander Belopolsky44454af2010-11-20 18:21:07 +0000431def _find_executable_linenos(filename):
Jeremy Hylton38732e12003-04-21 22:04:46 +0000432 """Return dict where keys are line numbers in the line number table."""
Jeremy Hylton38732e12003-04-21 22:04:46 +0000433 try:
Victor Stinner58c07522010-11-09 01:08:59 +0000434 with tokenize.open(filename) as f:
Benjamin Petersonb2fda232010-10-30 23:51:34 +0000435 prog = f.read()
Victor Stinner58c07522010-11-09 01:08:59 +0000436 encoding = f.encoding
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200437 except OSError as err:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000438 print(("Not printing coverage data for %r: %s"
439 % (filename, err)), file=sys.stderr)
Jeremy Hylton38732e12003-04-21 22:04:46 +0000440 return {}
441 code = compile(prog, filename, "exec")
Alexander Belopolsky44454af2010-11-20 18:21:07 +0000442 strs = _find_strings(filename, encoding)
443 return _find_lines(code, strs)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000444
445class Trace:
Skip Montanarocafc8112004-04-07 15:46:05 +0000446 def __init__(self, count=1, trace=1, countfuncs=0, countcallers=0,
Christian Heimes380f7f22008-02-28 11:19:05 +0000447 ignoremods=(), ignoredirs=(), infile=None, outfile=None,
448 timing=False):
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000449 """
450 @param count true iff it should count number of times each
Tim Petersf2715e02003-02-19 02:35:07 +0000451 line is executed
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000452 @param trace true iff it should print out each line that is
Tim Petersf2715e02003-02-19 02:35:07 +0000453 being counted
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000454 @param countfuncs true iff it should just output a list of
455 (filename, modulename, funcname,) for functions
456 that were called at least once; This overrides
Tim Petersf2715e02003-02-19 02:35:07 +0000457 `count' and `trace'
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000458 @param ignoremods a list of the names of modules to ignore
459 @param ignoredirs a list of the names of directories to ignore
Tim Petersf2715e02003-02-19 02:35:07 +0000460 all of the (recursive) contents of
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000461 @param infile file from which to read stored counts to be
Tim Petersf2715e02003-02-19 02:35:07 +0000462 added into the results
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000463 @param outfile file in which to write the results
Christian Heimes380f7f22008-02-28 11:19:05 +0000464 @param timing true iff timing information be displayed
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000465 """
466 self.infile = infile
467 self.outfile = outfile
Alexander Belopolsky44454af2010-11-20 18:21:07 +0000468 self.ignore = _Ignore(ignoremods, ignoredirs)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000469 self.counts = {} # keys are (filename, linenumber)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000470 self.pathtobasename = {} # for memoizing os.path.basename
471 self.donothing = 0
472 self.trace = trace
473 self._calledfuncs = {}
Skip Montanarocafc8112004-04-07 15:46:05 +0000474 self._callers = {}
Skip Montanaro5bfd9842004-04-10 16:29:58 +0000475 self._caller_cache = {}
Christian Heimes380f7f22008-02-28 11:19:05 +0000476 self.start_time = None
477 if timing:
Victor Stinner949d8c92012-05-30 13:30:32 +0200478 self.start_time = _time()
Skip Montanarocafc8112004-04-07 15:46:05 +0000479 if countcallers:
480 self.globaltrace = self.globaltrace_trackcallers
481 elif countfuncs:
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000482 self.globaltrace = self.globaltrace_countfuncs
483 elif trace and count:
484 self.globaltrace = self.globaltrace_lt
485 self.localtrace = self.localtrace_trace_and_count
486 elif trace:
487 self.globaltrace = self.globaltrace_lt
488 self.localtrace = self.localtrace_trace
489 elif count:
490 self.globaltrace = self.globaltrace_lt
491 self.localtrace = self.localtrace_count
492 else:
493 # Ahem -- do nothing? Okay.
494 self.donothing = 1
495
496 def run(self, cmd):
497 import __main__
498 dict = __main__.__dict__
Alexander Belopolsky0ae33612010-09-27 15:49:20 +0000499 self.runctx(cmd, dict, dict)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000500
501 def runctx(self, cmd, globals=None, locals=None):
502 if globals is None: globals = {}
503 if locals is None: locals = {}
504 if not self.donothing:
Alexander Belopolsky25b57412010-11-06 01:31:16 +0000505 _settrace(self.globaltrace)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000506 try:
Georg Brandl7cae87c2006-09-06 06:51:57 +0000507 exec(cmd, globals, locals)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000508 finally:
509 if not self.donothing:
Alexander Belopolsky25b57412010-11-06 01:31:16 +0000510 _unsettrace()
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000511
512 def runfunc(self, func, *args, **kw):
513 result = None
514 if not self.donothing:
515 sys.settrace(self.globaltrace)
516 try:
Guido van Rossum68468eb2003-02-27 20:14:51 +0000517 result = func(*args, **kw)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000518 finally:
519 if not self.donothing:
520 sys.settrace(None)
521 return result
522
Skip Montanaro5bfd9842004-04-10 16:29:58 +0000523 def file_module_function_of(self, frame):
524 code = frame.f_code
525 filename = code.co_filename
526 if filename:
Alexander Belopolsky44454af2010-11-20 18:21:07 +0000527 modulename = _modname(filename)
Skip Montanaro5bfd9842004-04-10 16:29:58 +0000528 else:
529 modulename = None
530
531 funcname = code.co_name
532 clsname = None
533 if code in self._caller_cache:
534 if self._caller_cache[code] is not None:
535 clsname = self._caller_cache[code]
536 else:
537 self._caller_cache[code] = None
538 ## use of gc.get_referrers() was suggested by Michael Hudson
539 # all functions which refer to this code object
540 funcs = [f for f in gc.get_referrers(code)
Alexander Belopolsky4d770172010-09-13 18:14:34 +0000541 if inspect.isfunction(f)]
Skip Montanaro5bfd9842004-04-10 16:29:58 +0000542 # require len(func) == 1 to avoid ambiguity caused by calls to
543 # new.function(): "In the face of ambiguity, refuse the
544 # temptation to guess."
545 if len(funcs) == 1:
546 dicts = [d for d in gc.get_referrers(funcs[0])
547 if isinstance(d, dict)]
548 if len(dicts) == 1:
549 classes = [c for c in gc.get_referrers(dicts[0])
550 if hasattr(c, "__bases__")]
551 if len(classes) == 1:
552 # ditto for new.classobj()
Alexander Belopolsky4d770172010-09-13 18:14:34 +0000553 clsname = classes[0].__name__
Skip Montanaro5bfd9842004-04-10 16:29:58 +0000554 # cache the result - assumption is that new.* is
555 # not called later to disturb this relationship
556 # _caller_cache could be flushed if functions in
557 # the new module get called.
558 self._caller_cache[code] = clsname
559 if clsname is not None:
Skip Montanaro5bfd9842004-04-10 16:29:58 +0000560 funcname = "%s.%s" % (clsname, funcname)
561
562 return filename, modulename, funcname
563
Skip Montanarocafc8112004-04-07 15:46:05 +0000564 def globaltrace_trackcallers(self, frame, why, arg):
565 """Handler for call events.
566
567 Adds information about who called who to the self._callers dict.
568 """
569 if why == 'call':
570 # XXX Should do a better job of identifying methods
Skip Montanaro5bfd9842004-04-10 16:29:58 +0000571 this_func = self.file_module_function_of(frame)
572 parent_func = self.file_module_function_of(frame.f_back)
Skip Montanarocafc8112004-04-07 15:46:05 +0000573 self._callers[(parent_func, this_func)] = 1
574
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000575 def globaltrace_countfuncs(self, frame, why, arg):
Jeremy Hylton38732e12003-04-21 22:04:46 +0000576 """Handler for call events.
Tim Peters0eadaac2003-04-24 16:02:54 +0000577
Jeremy Hylton38732e12003-04-21 22:04:46 +0000578 Adds (filename, modulename, funcname) to the self._calledfuncs dict.
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000579 """
580 if why == 'call':
Skip Montanaro5bfd9842004-04-10 16:29:58 +0000581 this_func = self.file_module_function_of(frame)
582 self._calledfuncs[this_func] = 1
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000583
584 def globaltrace_lt(self, frame, why, arg):
Jeremy Hylton38732e12003-04-21 22:04:46 +0000585 """Handler for call events.
586
587 If the code block being entered is to be ignored, returns `None',
588 else returns self.localtrace.
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000589 """
590 if why == 'call':
Jeremy Hylton38732e12003-04-21 22:04:46 +0000591 code = frame.f_code
Thomas Wouterscf297e42007-02-23 15:07:44 +0000592 filename = frame.f_globals.get('__file__', None)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000593 if filename:
Alexander Belopolsky44454af2010-11-20 18:21:07 +0000594 # XXX _modname() doesn't work right for packages, so
Jeremy Hyltondfbfe732003-04-21 22:49:17 +0000595 # the ignore support won't work right for packages
Alexander Belopolsky44454af2010-11-20 18:21:07 +0000596 modulename = _modname(filename)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000597 if modulename is not None:
598 ignore_it = self.ignore.names(filename, modulename)
599 if not ignore_it:
600 if self.trace:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000601 print((" --- modulename: %s, funcname: %s"
602 % (modulename, code.co_name)))
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000603 return self.localtrace
604 else:
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000605 return None
606
607 def localtrace_trace_and_count(self, frame, why, arg):
Jeremy Hylton38732e12003-04-21 22:04:46 +0000608 if why == "line":
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000609 # record the file name and line number of every trace
Jeremy Hylton38732e12003-04-21 22:04:46 +0000610 filename = frame.f_code.co_filename
611 lineno = frame.f_lineno
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000612 key = filename, lineno
613 self.counts[key] = self.counts.get(key, 0) + 1
Tim Petersf2715e02003-02-19 02:35:07 +0000614
Christian Heimes380f7f22008-02-28 11:19:05 +0000615 if self.start_time:
Victor Stinner949d8c92012-05-30 13:30:32 +0200616 print('%.2f' % (_time() - self.start_time), end=' ')
Jeremy Hylton38732e12003-04-21 22:04:46 +0000617 bname = os.path.basename(filename)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000618 print("%s(%d): %s" % (bname, lineno,
Georg Brandldc50c692010-08-02 12:40:22 +0000619 linecache.getline(filename, lineno)), end='')
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000620 return self.localtrace
621
622 def localtrace_trace(self, frame, why, arg):
Jeremy Hylton38732e12003-04-21 22:04:46 +0000623 if why == "line":
624 # record the file name and line number of every trace
625 filename = frame.f_code.co_filename
626 lineno = frame.f_lineno
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000627
Christian Heimes380f7f22008-02-28 11:19:05 +0000628 if self.start_time:
Victor Stinner949d8c92012-05-30 13:30:32 +0200629 print('%.2f' % (_time() - self.start_time), end=' ')
Jeremy Hylton38732e12003-04-21 22:04:46 +0000630 bname = os.path.basename(filename)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000631 print("%s(%d): %s" % (bname, lineno,
Georg Brandldc50c692010-08-02 12:40:22 +0000632 linecache.getline(filename, lineno)), end='')
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000633 return self.localtrace
634
635 def localtrace_count(self, frame, why, arg):
Jeremy Hylton38732e12003-04-21 22:04:46 +0000636 if why == "line":
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000637 filename = frame.f_code.co_filename
638 lineno = frame.f_lineno
639 key = filename, lineno
640 self.counts[key] = self.counts.get(key, 0) + 1
641 return self.localtrace
642
643 def results(self):
644 return CoverageResults(self.counts, infile=self.infile,
645 outfile=self.outfile,
Skip Montanarocafc8112004-04-07 15:46:05 +0000646 calledfuncs=self._calledfuncs,
647 callers=self._callers)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000648
649def _err_exit(msg):
650 sys.stderr.write("%s: %s\n" % (sys.argv[0], msg))
651 sys.exit(1)
652
653def main(argv=None):
654 import getopt
655
656 if argv is None:
657 argv = sys.argv
658 try:
Christian Heimes380f7f22008-02-28 11:19:05 +0000659 opts, prog_argv = getopt.getopt(argv[1:], "tcrRf:d:msC:lTg",
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000660 ["help", "version", "trace", "count",
661 "report", "no-report", "summary",
662 "file=", "missing",
663 "ignore-module=", "ignore-dir=",
Skip Montanarocafc8112004-04-07 15:46:05 +0000664 "coverdir=", "listfuncs",
Christian Heimes380f7f22008-02-28 11:19:05 +0000665 "trackcalls", "timing"])
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000666
Guido van Rossumb940e112007-01-10 16:19:56 +0000667 except getopt.error as msg:
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000668 sys.stderr.write("%s: %s\n" % (sys.argv[0], msg))
669 sys.stderr.write("Try `%s --help' for more information\n"
670 % sys.argv[0])
671 sys.exit(1)
672
673 trace = 0
674 count = 0
675 report = 0
676 no_report = 0
677 counts_file = None
678 missing = 0
679 ignore_modules = []
680 ignore_dirs = []
681 coverdir = None
682 summary = 0
683 listfuncs = False
Skip Montanarocafc8112004-04-07 15:46:05 +0000684 countcallers = False
Christian Heimes380f7f22008-02-28 11:19:05 +0000685 timing = False
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000686
687 for opt, val in opts:
688 if opt == "--help":
Éric Araujoe7d36fe2011-04-17 16:48:52 +0200689 _usage(sys.stdout)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000690 sys.exit(0)
691
692 if opt == "--version":
693 sys.stdout.write("trace 2.0\n")
694 sys.exit(0)
695
Skip Montanarocafc8112004-04-07 15:46:05 +0000696 if opt == "-T" or opt == "--trackcalls":
697 countcallers = True
698 continue
699
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000700 if opt == "-l" or opt == "--listfuncs":
701 listfuncs = True
702 continue
703
Christian Heimes380f7f22008-02-28 11:19:05 +0000704 if opt == "-g" or opt == "--timing":
705 timing = True
706 continue
707
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000708 if opt == "-t" or opt == "--trace":
709 trace = 1
710 continue
711
712 if opt == "-c" or opt == "--count":
713 count = 1
714 continue
715
716 if opt == "-r" or opt == "--report":
717 report = 1
718 continue
719
720 if opt == "-R" or opt == "--no-report":
721 no_report = 1
722 continue
723
724 if opt == "-f" or opt == "--file":
725 counts_file = val
726 continue
727
728 if opt == "-m" or opt == "--missing":
729 missing = 1
730 continue
731
732 if opt == "-C" or opt == "--coverdir":
733 coverdir = val
734 continue
735
736 if opt == "-s" or opt == "--summary":
737 summary = 1
738 continue
739
740 if opt == "--ignore-module":
Georg Brandlfceab5a2008-01-19 20:08:23 +0000741 for mod in val.split(","):
742 ignore_modules.append(mod.strip())
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000743 continue
744
745 if opt == "--ignore-dir":
746 for s in val.split(os.pathsep):
747 s = os.path.expandvars(s)
748 # should I also call expanduser? (after all, could use $HOME)
749
750 s = s.replace("$prefix",
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100751 os.path.join(sys.base_prefix, "lib",
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000752 "python" + sys.version[:3]))
753 s = s.replace("$exec_prefix",
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100754 os.path.join(sys.base_exec_prefix, "lib",
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000755 "python" + sys.version[:3]))
756 s = os.path.normpath(s)
757 ignore_dirs.append(s)
758 continue
759
760 assert 0, "Should never get here"
761
762 if listfuncs and (count or trace):
763 _err_exit("cannot specify both --listfuncs and (--trace or --count)")
764
Skip Montanarocafc8112004-04-07 15:46:05 +0000765 if not (count or trace or report or listfuncs or countcallers):
766 _err_exit("must specify one of --trace, --count, --report, "
767 "--listfuncs, or --trackcalls")
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000768
769 if report and no_report:
770 _err_exit("cannot specify both --report and --no-report")
771
772 if report and not counts_file:
773 _err_exit("--report requires a --file")
774
775 if no_report and len(prog_argv) == 0:
776 _err_exit("missing name of file to run")
777
778 # everything is ready
779 if report:
780 results = CoverageResults(infile=counts_file, outfile=counts_file)
781 results.write_results(missing, summary=summary, coverdir=coverdir)
782 else:
783 sys.argv = prog_argv
784 progname = prog_argv[0]
785 sys.path[0] = os.path.split(progname)[0]
786
787 t = Trace(count, trace, countfuncs=listfuncs,
Skip Montanarocafc8112004-04-07 15:46:05 +0000788 countcallers=countcallers, ignoremods=ignore_modules,
789 ignoredirs=ignore_dirs, infile=counts_file,
Christian Heimes380f7f22008-02-28 11:19:05 +0000790 outfile=counts_file, timing=timing)
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000791 try:
Alexander Belopolsky3f8ecab2010-07-21 17:43:42 +0000792 with open(progname) as fp:
793 code = compile(fp.read(), progname, 'exec')
Georg Brandl8f9f4662010-08-01 08:35:29 +0000794 # try to emulate __main__ namespace as much as possible
795 globs = {
796 '__file__': progname,
797 '__name__': '__main__',
798 '__package__': None,
799 '__cached__': None,
800 }
801 t.runctx(code, globs, globs)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200802 except OSError as err:
Jeremy Hylton38732e12003-04-21 22:04:46 +0000803 _err_exit("Cannot run file %r because: %s" % (sys.argv[0], err))
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000804 except SystemExit:
805 pass
806
807 results = t.results()
808
809 if not no_report:
810 results.write_results(missing, summary=summary, coverdir=coverdir)
811
Jeremy Hylton4edaa0d2003-02-18 15:06:17 +0000812if __name__=='__main__':
813 main()