| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 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 |
trace.py --trackcalls spam.py eggs |
| 36 |
|
| 37 |
Sample use, programmatically |
| 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.base_prefix, sys.base_exec_prefix,], |
| 43 |
trace=0, 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") |
| 49 |
""" |
| 50 |
__all__ = ['Trace', 'CoverageResults'] |
| 51 |
|
| 52 |
import io |
| 53 |
import linecache |
| 54 |
import os |
| 55 |
import sys |
| 56 |
import sysconfig |
| 57 |
import token |
| 58 |
import tokenize |
| 59 |
import inspect |
| 60 |
import gc |
| 61 |
import dis |
| 62 |
import pickle |
| 63 |
from time import monotonic as _time |
| 64 |
|
| 65 |
import threading |
| 66 |
|
| 67 |
PRAGMA_NOCOVER = "#pragma NO COVER" |
| 68 |
|
| 69 |
class _Ignore: |
| 70 |
def __init__(self, modules=None, dirs=None): |
| 71 |
self._mods = set() if not modules else set(modules) |
| 72 |
self._dirs = [] if not dirs else [os.path.normpath(d) |
| 73 |
for d in dirs] |
| 74 |
self._ignore = { '<string>': 1 } |
| 75 |
|
| 76 |
def names(self, filename, modulename): |
| 77 |
if modulename in self._ignore: |
| 78 |
return self._ignore[modulename] |
| 79 |
|
| 80 |
|
| 81 |
|
| 82 |
if modulename in self._mods: |
| 83 |
self._ignore[modulename] = 1 |
| 84 |
return 1 |
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
for mod in self._mods: |
| 89 |
|
| 90 |
|
| 91 |
|
| 92 |
if modulename.startswith(mod + '.'): |
| 93 |
self._ignore[modulename] = 1 |
| 94 |
return 1 |
| 95 |
|
| 96 |
|
| 97 |
if filename is None: |
| 98 |
|
| 99 |
self._ignore[modulename] = 1 |
| 100 |
return 1 |
| 101 |
|
| 102 |
|
| 103 |
for d in self._dirs: |
| 104 |
|
| 105 |
|
| 106 |
|
| 107 |
|
| 108 |
|
| 109 |
|
| 110 |
|
| 111 |
if filename.startswith(d + os.sep): |
| 112 |
self._ignore[modulename] = 1 |
| 113 |
return 1 |
| 114 |
|
| 115 |
|
| 116 |
self._ignore[modulename] = 0 |
| 117 |
return 0 |
| 118 |
|
| 119 |
def _modname(path): |
| 120 |
"""Return a plausible module name for the path.""" |
| 121 |
|
| 122 |
base = os.path.basename(path) |
| 123 |
filename, ext = os.path.splitext(base) |
| 124 |
return filename |
| 125 |
|
| 126 |
def _fullmodname(path): |
| 127 |
"""Return a plausible module name for the path.""" |
| 128 |
|
| 129 |
|
| 130 |
|
| 131 |
|
| 132 |
|
| 133 |
|
| 134 |
comparepath = os.path.normcase(path) |
| 135 |
longest = "" |
| 136 |
for dir in sys.path: |
| 137 |
dir = os.path.normcase(dir) |
| 138 |
if comparepath.startswith(dir) and comparepath[len(dir)] == os.sep: |
| 139 |
if len(dir) > len(longest): |
| 140 |
longest = dir |
| 141 |
|
| 142 |
if longest: |
| 143 |
base = path[len(longest) + 1:] |
| 144 |
else: |
| 145 |
base = path |
| 146 |
|
| 147 |
drive, base = os.path.splitdrive(base) |
| 148 |
base = base.replace(os.sep, ".") |
| 149 |
if os.altsep: |
| 150 |
base = base.replace(os.altsep, ".") |
| 151 |
filename, ext = os.path.splitext(base) |
| 152 |
return filename.lstrip(".") |
| 153 |
|
| 154 |
class CoverageResults: |
| 155 |
def __init__(self, counts=None, calledfuncs=None, infile=None, |
| 156 |
callers=None, outfile=None): |
| 157 |
self.counts = counts |
| 158 |
if self.counts is None: |
| 159 |
self.counts = {} |
| 160 |
self.counter = self.counts.copy() |
| 161 |
self.calledfuncs = calledfuncs |
| 162 |
if self.calledfuncs is None: |
| 163 |
self.calledfuncs = {} |
| 164 |
self.calledfuncs = self.calledfuncs.copy() |
| 165 |
self.callers = callers |
| 166 |
if self.callers is None: |
| 167 |
self.callers = {} |
| 168 |
self.callers = self.callers.copy() |
| 169 |
self.infile = infile |
| 170 |
self.outfile = outfile |
| 171 |
if self.infile: |
| 172 |
|
| 173 |
try: |
| 174 |
with open(self.infile, 'rb') as f: |
| 175 |
counts, calledfuncs, callers = pickle.load(f) |
| 176 |
self.update(self.__class__(counts, calledfuncs, callers=callers)) |
| 177 |
except (OSError, EOFError, ValueError) as err: |
| 178 |
print(("Skipping counts file %r: %s" |
| 179 |
% (self.infile, err)), file=sys.stderr) |
| 180 |
|
| 181 |
def is_ignored_filename(self, filename): |
| 182 |
"""Return True if the filename does not refer to a file |
| 183 |
we want to have reported. |
| 184 |
""" |
| 185 |
return ((filename.startswith('<') and filename.endswith('>')) or |
| 186 |
|
| 187 |
|
| 188 |
|
| 189 |
|
| 190 |
filename.startswith("<builtin>/")) |
| 191 |
|
| 192 |
def update(self, other): |
| 193 |
"""Merge in the data from another CoverageResults""" |
| 194 |
counts = self.counts |
| 195 |
calledfuncs = self.calledfuncs |
| 196 |
callers = self.callers |
| 197 |
other_counts = other.counts |
| 198 |
other_calledfuncs = other.calledfuncs |
| 199 |
other_callers = other.callers |
| 200 |
|
| 201 |
for key in other_counts: |
| 202 |
counts[key] = counts.get(key, 0) + other_counts[key] |
| 203 |
|
| 204 |
for key in other_calledfuncs: |
| 205 |
calledfuncs[key] = 1 |
| 206 |
|
| 207 |
for key in other_callers: |
| 208 |
callers[key] = 1 |
| 209 |
|
| 210 |
def write_results(self, show_missing=True, summary=False, coverdir=None): |
| 211 |
""" |
| 212 |
Write the coverage results. |
| 213 |
|
| 214 |
:param show_missing: Show lines that had no hits. |
| 215 |
:param summary: Include coverage summary per module. |
| 216 |
:param coverdir: If None, the results of each module are placed in its |
| 217 |
directory, otherwise it is included in the directory |
| 218 |
specified. |
| 219 |
""" |
| 220 |
if self.calledfuncs: |
| 221 |
print() |
| 222 |
print("functions called:") |
| 223 |
calls = self.calledfuncs |
| 224 |
for filename, modulename, funcname in sorted(calls): |
| 225 |
print(("filename: %s, modulename: %s, funcname: %s" |
| 226 |
% (filename, modulename, funcname))) |
| 227 |
|
| 228 |
if self.callers: |
| 229 |
print() |
| 230 |
print("calling relationships:") |
| 231 |
lastfile = lastcfile = "" |
| 232 |
for ((pfile, pmod, pfunc), (cfile, cmod, cfunc)) \ |
| 233 |
in sorted(self.callers): |
| 234 |
if pfile != lastfile: |
| 235 |
print() |
| 236 |
print("***", pfile, "***") |
| 237 |
lastfile = pfile |
| 238 |
lastcfile = "" |
| 239 |
if cfile != pfile and lastcfile != cfile: |
| 240 |
print(" -->", cfile) |
| 241 |
lastcfile = cfile |
| 242 |
print(" %s.%s -> %s.%s" % (pmod, pfunc, cmod, cfunc)) |
| 243 |
|
| 244 |
|
| 245 |
|
| 246 |
per_file = {} |
| 247 |
for filename, lineno in self.counts: |
| 248 |
lines_hit = per_file[filename] = per_file.get(filename, {}) |
| 249 |
lines_hit[lineno] = self.counts[(filename, lineno)] |
| 250 |
|
| 251 |
|
| 252 |
sums = {} |
| 253 |
|
| 254 |
for filename, count in per_file.items(): |
| 255 |
if self.is_ignored_filename(filename): |
| 256 |
continue |
| 257 |
|
| 258 |
if filename.endswith(".pyc"): |
| 259 |
filename = filename[:-1] |
| 260 |
|
| 261 |
if coverdir is None: |
| 262 |
dir = os.path.dirname(os.path.abspath(filename)) |
| 263 |
modulename = _modname(filename) |
| 264 |
else: |
| 265 |
dir = coverdir |
| 266 |
os.makedirs(dir, exist_ok=True) |
| 267 |
modulename = _fullmodname(filename) |
| 268 |
|
| 269 |
|
| 270 |
|
| 271 |
if show_missing: |
| 272 |
lnotab = _find_executable_linenos(filename) |
| 273 |
else: |
| 274 |
lnotab = {} |
| 275 |
source = linecache.getlines(filename) |
| 276 |
coverpath = os.path.join(dir, modulename + ".cover") |
| 277 |
with open(filename, 'rb') as fp: |
| 278 |
encoding, _ = tokenize.detect_encoding(fp.readline) |
| 279 |
n_hits, n_lines = self.write_results_file(coverpath, source, |
| 280 |
lnotab, count, encoding) |
| 281 |
if summary and n_lines: |
| 282 |
percent = int(100 * n_hits / n_lines) |
| 283 |
sums[modulename] = n_lines, percent, modulename, filename |
| 284 |
|
| 285 |
|
| 286 |
if summary and sums: |
| 287 |
print("lines cov% module (path)") |
| 288 |
for m in sorted(sums): |
| 289 |
n_lines, percent, modulename, filename = sums[m] |
| 290 |
print("%5d %3d%% %s (%s)" % sums[m]) |
| 291 |
|
| 292 |
if self.outfile: |
| 293 |
|
| 294 |
try: |
| 295 |
with open(self.outfile, 'wb') as f: |
| 296 |
pickle.dump((self.counts, self.calledfuncs, self.callers), |
| 297 |
f, 1) |
| 298 |
except OSError as err: |
| 299 |
print("Can't save counts files because %s" % err, file=sys.stderr) |
| 300 |
|
| 301 |
def write_results_file(self, path, lines, lnotab, lines_hit, encoding=None): |
| 302 |
"""Return a coverage results file in path.""" |
| 303 |
|
| 304 |
|
| 305 |
try: |
| 306 |
outfile = open(path, "w", encoding=encoding) |
| 307 |
except OSError as err: |
| 308 |
print(("trace: Could not open %r for writing: %s " |
| 309 |
"- skipping" % (path, err)), file=sys.stderr) |
| 310 |
return 0, 0 |
| 311 |
|
| 312 |
n_lines = 0 |
| 313 |
n_hits = 0 |
| 314 |
with outfile: |
| 315 |
for lineno, line in enumerate(lines, 1): |
| 316 |
|
| 317 |
|
| 318 |
if lineno in lines_hit: |
| 319 |
outfile.write("%5d: " % lines_hit[lineno]) |
| 320 |
n_hits += 1 |
| 321 |
n_lines += 1 |
| 322 |
elif lineno in lnotab and not PRAGMA_NOCOVER in line: |
| 323 |
|
| 324 |
|
| 325 |
outfile.write(">>>>>> ") |
| 326 |
n_lines += 1 |
| 327 |
else: |
| 328 |
outfile.write(" ") |
| 329 |
outfile.write(line.expandtabs(8)) |
| 330 |
|
| 331 |
return n_hits, n_lines |
| 332 |
|
| 333 |
def _find_lines_from_code(code, strs): |
| 334 |
"""Return dict where keys are lines in the line number table.""" |
| 335 |
linenos = {} |
| 336 |
|
| 337 |
for _, lineno in dis.findlinestarts(code): |
| 338 |
if lineno not in strs: |
| 339 |
linenos[lineno] = 1 |
| 340 |
|
| 341 |
return linenos |
| 342 |
|
| 343 |
def _find_lines(code, strs): |
| 344 |
"""Return lineno dict for all code objects reachable from code.""" |
| 345 |
|
| 346 |
linenos = _find_lines_from_code(code, strs) |
| 347 |
|
| 348 |
|
| 349 |
for c in code.co_consts: |
| 350 |
if inspect.iscode(c): |
| 351 |
|
| 352 |
linenos.update(_find_lines(c, strs)) |
| 353 |
return linenos |
| 354 |
|
| 355 |
def _find_strings(filename, encoding=None): |
| 356 |
"""Return a dict of possible docstring positions. |
| 357 |
|
| 358 |
The dict maps line numbers to strings. There is an entry for |
| 359 |
line that contains only a string or a part of a triple-quoted |
| 360 |
string. |
| 361 |
""" |
| 362 |
d = {} |
| 363 |
|
| 364 |
|
| 365 |
prev_ttype = token.INDENT |
| 366 |
with open(filename, encoding=encoding) as f: |
| 367 |
tok = tokenize.generate_tokens(f.readline) |
| 368 |
for ttype, tstr, start, end, line in tok: |
| 369 |
if ttype == token.STRING: |
| 370 |
if prev_ttype == token.INDENT: |
| 371 |
sline, scol = start |
| 372 |
eline, ecol = end |
| 373 |
for i in range(sline, eline + 1): |
| 374 |
d[i] = 1 |
| 375 |
prev_ttype = ttype |
| 376 |
return d |
| 377 |
|
| 378 |
def _find_executable_linenos(filename): |
| 379 |
"""Return dict where keys are line numbers in the line number table.""" |
| 380 |
try: |
| 381 |
with tokenize.open(filename) as f: |
| 382 |
prog = f.read() |
| 383 |
encoding = f.encoding |
| 384 |
except OSError as err: |
| 385 |
print(("Not printing coverage data for %r: %s" |
| 386 |
% (filename, err)), file=sys.stderr) |
| 387 |
return {} |
| 388 |
code = compile(prog, filename, "exec") |
| 389 |
strs = _find_strings(filename, encoding) |
| 390 |
return _find_lines(code, strs) |
| 391 |
|
| 392 |
class Trace: |
| 393 |
def __init__(self, count=1, trace=1, countfuncs=0, countcallers=0, |
| 394 |
ignoremods=(), ignoredirs=(), infile=None, outfile=None, |
| 395 |
timing=False): |
| 396 |
""" |
| 397 |
@param count true iff it should count number of times each |
| 398 |
line is executed |
| 399 |
@param trace true iff it should print out each line that is |
| 400 |
being counted |
| 401 |
@param countfuncs true iff it should just output a list of |
| 402 |
(filename, modulename, funcname,) for functions |
| 403 |
that were called at least once; This overrides |
| 404 |
`count' and `trace' |
| 405 |
@param ignoremods a list of the names of modules to ignore |
| 406 |
@param ignoredirs a list of the names of directories to ignore |
| 407 |
all of the (recursive) contents of |
| 408 |
@param infile file from which to read stored counts to be |
| 409 |
added into the results |
| 410 |
@param outfile file in which to write the results |
| 411 |
@param timing true iff timing information be displayed |
| 412 |
""" |
| 413 |
self.infile = infile |
| 414 |
self.outfile = outfile |
| 415 |
self.ignore = _Ignore(ignoremods, ignoredirs) |
| 416 |
self.counts = {} |
| 417 |
self.pathtobasename = {} |
| 418 |
self.donothing = 0 |
| 419 |
self.trace = trace |
| 420 |
self._calledfuncs = {} |
| 421 |
self._callers = {} |
| 422 |
self._caller_cache = {} |
| 423 |
self.start_time = None |
| 424 |
if timing: |
| 425 |
self.start_time = _time() |
| 426 |
if countcallers: |
| 427 |
self.globaltrace = self.globaltrace_trackcallers |
| 428 |
elif countfuncs: |
| 429 |
self.globaltrace = self.globaltrace_countfuncs |
| 430 |
elif trace and count: |
| 431 |
self.globaltrace = self.globaltrace_lt |
| 432 |
self.localtrace = self.localtrace_trace_and_count |
| 433 |
elif trace: |
| 434 |
self.globaltrace = self.globaltrace_lt |
| 435 |
self.localtrace = self.localtrace_trace |
| 436 |
elif count: |
| 437 |
self.globaltrace = self.globaltrace_lt |
| 438 |
self.localtrace = self.localtrace_count |
| 439 |
else: |
| 440 |
|
| 441 |
self.donothing = 1 |
| 442 |
|
| 443 |
def run(self, cmd): |
| 444 |
import __main__ |
| 445 |
dict = __main__.__dict__ |
| 446 |
self.runctx(cmd, dict, dict) |
| 447 |
|
| 448 |
def runctx(self, cmd, globals=None, locals=None): |
| 449 |
if globals is None: globals = {} |
| 450 |
if locals is None: locals = {} |
| 451 |
if not self.donothing: |
| 452 |
threading.settrace(self.globaltrace) |
| 453 |
sys.settrace(self.globaltrace) |
| 454 |
try: |
| 455 |
exec(cmd, globals, locals) |
| 456 |
finally: |
| 457 |
if not self.donothing: |
| 458 |
sys.settrace(None) |
| 459 |
threading.settrace(None) |
| 460 |
|
| 461 |
def runfunc(self, func, /, *args, **kw): |
| 462 |
result = None |
| 463 |
if not self.donothing: |
| 464 |
sys.settrace(self.globaltrace) |
| 465 |
try: |
| 466 |
result = func(*args, **kw) |
| 467 |
finally: |
| 468 |
if not self.donothing: |
| 469 |
sys.settrace(None) |
| 470 |
return result |
| 471 |
|
| 472 |
def file_module_function_of(self, frame): |
| 473 |
code = frame.f_code |
| 474 |
filename = code.co_filename |
| 475 |
if filename: |
| 476 |
modulename = _modname(filename) |
| 477 |
else: |
| 478 |
modulename = None |
| 479 |
|
| 480 |
funcname = code.co_name |
| 481 |
clsname = None |
| 482 |
if code in self._caller_cache: |
| 483 |
if self._caller_cache[code] is not None: |
| 484 |
clsname = self._caller_cache[code] |
| 485 |
else: |
| 486 |
self._caller_cache[code] = None |
| 487 |
|
| 488 |
|
| 489 |
funcs = [f for f in gc.get_referrers(code) |
| 490 |
if inspect.isfunction(f)] |
| 491 |
|
| 492 |
|
| 493 |
|
| 494 |
if len(funcs) == 1: |
| 495 |
dicts = [d for d in gc.get_referrers(funcs[0]) |
| 496 |
if isinstance(d, dict)] |
| 497 |
if len(dicts) == 0: |
| 498 |
|
| 499 |
|
| 500 |
dicts = funcs |
| 501 |
if len(dicts) == 1: |
| 502 |
classes = [c for c in gc.get_referrers(dicts[0]) |
| 503 |
if hasattr(c, "__bases__")] |
| 504 |
if len(classes) == 1: |
| 505 |
|
| 506 |
clsname = classes[0].__name__ |
| 507 |
|
| 508 |
|
| 509 |
|
| 510 |
|
| 511 |
self._caller_cache[code] = clsname |
| 512 |
if clsname is not None: |
| 513 |
funcname = "%s.%s" % (clsname, funcname) |
| 514 |
|
| 515 |
return filename, modulename, funcname |
| 516 |
|
| 517 |
def globaltrace_trackcallers(self, frame, why, arg): |
| 518 |
"""Handler for call events. |
| 519 |
|
| 520 |
Adds information about who called who to the self._callers dict. |
| 521 |
""" |
| 522 |
if why == 'call': |
| 523 |
|
| 524 |
this_func = self.file_module_function_of(frame) |
| 525 |
parent_func = self.file_module_function_of(frame.f_back) |
| 526 |
self._callers[(parent_func, this_func)] = 1 |
| 527 |
|
| 528 |
def globaltrace_countfuncs(self, frame, why, arg): |
| 529 |
"""Handler for call events. |
| 530 |
|
| 531 |
Adds (filename, modulename, funcname) to the self._calledfuncs dict. |
| 532 |
""" |
| 533 |
if why == 'call': |
| 534 |
this_func = self.file_module_function_of(frame) |
| 535 |
self._calledfuncs[this_func] = 1 |
| 536 |
|
| 537 |
def globaltrace_lt(self, frame, why, arg): |
| 538 |
"""Handler for call events. |
| 539 |
|
| 540 |
If the code block being entered is to be ignored, returns `None', |
| 541 |
else returns self.localtrace. |
| 542 |
""" |
| 543 |
if why == 'call': |
| 544 |
code = frame.f_code |
| 545 |
filename = frame.f_globals.get('__file__', None) |
| 546 |
if filename: |
| 547 |
|
| 548 |
|
| 549 |
modulename = _modname(filename) |
| 550 |
if modulename is not None: |
| 551 |
ignore_it = self.ignore.names(filename, modulename) |
| 552 |
if not ignore_it: |
| 553 |
if self.trace: |
| 554 |
print((" --- modulename: %s, funcname: %s" |
| 555 |
% (modulename, code.co_name))) |
| 556 |
return self.localtrace |
| 557 |
else: |
| 558 |
return None |
| 559 |
|
| 560 |
def localtrace_trace_and_count(self, frame, why, arg): |
| 561 |
if why == "line": |
| 562 |
|
| 563 |
filename = frame.f_code.co_filename |
| 564 |
lineno = frame.f_lineno |
| 565 |
key = filename, lineno |
| 566 |
self.counts[key] = self.counts.get(key, 0) + 1 |
| 567 |
|
| 568 |
if self.start_time: |
| 569 |
print('%.2f' % (_time() - self.start_time), end=' ') |
| 570 |
bname = os.path.basename(filename) |
| 571 |
print("%s(%d): %s" % (bname, lineno, |
| 572 |
linecache.getline(filename, lineno)), end='') |
| 573 |
return self.localtrace |
| 574 |
|
| 575 |
def localtrace_trace(self, frame, why, arg): |
| 576 |
if why == "line": |
| 577 |
|
| 578 |
filename = frame.f_code.co_filename |
| 579 |
lineno = frame.f_lineno |
| 580 |
|
| 581 |
if self.start_time: |
| 582 |
print('%.2f' % (_time() - self.start_time), end=' ') |
| 583 |
bname = os.path.basename(filename) |
| 584 |
print("%s(%d): %s" % (bname, lineno, |
| 585 |
linecache.getline(filename, lineno)), end='') |
| 586 |
return self.localtrace |
| 587 |
|
| 588 |
def localtrace_count(self, frame, why, arg): |
| 589 |
if why == "line": |
| 590 |
filename = frame.f_code.co_filename |
| 591 |
lineno = frame.f_lineno |
| 592 |
key = filename, lineno |
| 593 |
self.counts[key] = self.counts.get(key, 0) + 1 |
| 594 |
return self.localtrace |
| 595 |
|
| 596 |
def results(self): |
| 597 |
return CoverageResults(self.counts, infile=self.infile, |
| 598 |
outfile=self.outfile, |
| 599 |
calledfuncs=self._calledfuncs, |
| 600 |
callers=self._callers) |
| 601 |
|
| 602 |
def main(): |
| 603 |
import argparse |
| 604 |
|
| 605 |
parser = argparse.ArgumentParser() |
| 606 |
parser.add_argument('--version', action='version', version='trace 2.0') |
| 607 |
|
| 608 |
grp = parser.add_argument_group('Main options', |
| 609 |
'One of these (or --report) must be given') |
| 610 |
|
| 611 |
grp.add_argument('-c', '--count', action='store_true', |
| 612 |
help='Count the number of times each line is executed and write ' |
| 613 |
'the counts to <module>.cover for each module executed, in ' |
| 614 |
'the module\'s directory. See also --coverdir, --file, ' |
| 615 |
'--no-report below.') |
| 616 |
grp.add_argument('-t', '--trace', action='store_true', |
| 617 |
help='Print each line to sys.stdout before it is executed') |
| 618 |
grp.add_argument('-l', '--listfuncs', action='store_true', |
| 619 |
help='Keep track of which functions are executed at least once ' |
| 620 |
'and write the results to sys.stdout after the program exits. ' |
| 621 |
'Cannot be specified alongside --trace or --count.') |
| 622 |
grp.add_argument('-T', '--trackcalls', action='store_true', |
| 623 |
help='Keep track of caller/called pairs and write the results to ' |
| 624 |
'sys.stdout after the program exits.') |
| 625 |
|
| 626 |
grp = parser.add_argument_group('Modifiers') |
| 627 |
|
| 628 |
_grp = grp.add_mutually_exclusive_group() |
| 629 |
_grp.add_argument('-r', '--report', action='store_true', |
| 630 |
help='Generate a report from a counts file; does not execute any ' |
| 631 |
'code. --file must specify the results file to read, which ' |
| 632 |
'must have been created in a previous run with --count ' |
| 633 |
'--file=FILE') |
| 634 |
_grp.add_argument('-R', '--no-report', action='store_true', |
| 635 |
help='Do not generate the coverage report files. ' |
| 636 |
'Useful if you want to accumulate over several runs.') |
| 637 |
|
| 638 |
grp.add_argument('-f', '--file', |
| 639 |
help='File to accumulate counts over several runs') |
| 640 |
grp.add_argument('-C', '--coverdir', |
| 641 |
help='Directory where the report files go. The coverage report ' |
| 642 |
'for <package>.<module> will be written to file ' |
| 643 |
'<dir>/<package>/<module>.cover') |
| 644 |
grp.add_argument('-m', '--missing', action='store_true', |
| 645 |
help='Annotate executable lines that were not executed with ' |
| 646 |
'">>>>>> "') |
| 647 |
grp.add_argument('-s', '--summary', action='store_true', |
| 648 |
help='Write a brief summary for each file to sys.stdout. ' |
| 649 |
'Can only be used with --count or --report') |
| 650 |
grp.add_argument('-g', '--timing', action='store_true', |
| 651 |
help='Prefix each line with the time since the program started. ' |
| 652 |
'Only used while tracing') |
| 653 |
|
| 654 |
grp = parser.add_argument_group('Filters', |
| 655 |
'Can be specified multiple times') |
| 656 |
grp.add_argument('--ignore-module', action='append', default=[], |
| 657 |
help='Ignore the given module(s) and its submodules ' |
| 658 |
'(if it is a package). Accepts comma separated list of ' |
| 659 |
'module names.') |
| 660 |
grp.add_argument('--ignore-dir', action='append', default=[], |
| 661 |
help='Ignore files in the given directory ' |
| 662 |
'(multiple directories can be joined by os.pathsep).') |
| 663 |
|
| 664 |
parser.add_argument('--module', action='store_true', default=False, |
| 665 |
help='Trace a module. ') |
| 666 |
parser.add_argument('progname', nargs='?', |
| 667 |
help='file to run as main program') |
| 668 |
parser.add_argument('arguments', nargs=argparse.REMAINDER, |
| 669 |
help='arguments to the program') |
| 670 |
|
| 671 |
opts = parser.parse_args() |
| 672 |
|
| 673 |
if opts.ignore_dir: |
| 674 |
_prefix = sysconfig.get_path("stdlib") |
| 675 |
_exec_prefix = sysconfig.get_path("platstdlib") |
| 676 |
|
| 677 |
def parse_ignore_dir(s): |
| 678 |
s = os.path.expanduser(os.path.expandvars(s)) |
| 679 |
s = s.replace('$prefix', _prefix).replace('$exec_prefix', _exec_prefix) |
| 680 |
return os.path.normpath(s) |
| 681 |
|
| 682 |
opts.ignore_module = [mod.strip() |
| 683 |
for i in opts.ignore_module for mod in i.split(',')] |
| 684 |
opts.ignore_dir = [parse_ignore_dir(s) |
| 685 |
for i in opts.ignore_dir for s in i.split(os.pathsep)] |
| 686 |
|
| 687 |
if opts.report: |
| 688 |
if not opts.file: |
| 689 |
parser.error('-r/--report requires -f/--file') |
| 690 |
results = CoverageResults(infile=opts.file, outfile=opts.file) |
| 691 |
return results.write_results(opts.missing, opts.summary, opts.coverdir) |
| 692 |
|
| 693 |
if not any([opts.trace, opts.count, opts.listfuncs, opts.trackcalls]): |
| 694 |
parser.error('must specify one of --trace, --count, --report, ' |
| 695 |
'--listfuncs, or --trackcalls') |
| 696 |
|
| 697 |
if opts.listfuncs and (opts.count or opts.trace): |
| 698 |
parser.error('cannot specify both --listfuncs and (--trace or --count)') |
| 699 |
|
| 700 |
if opts.summary and not opts.count: |
| 701 |
parser.error('--summary can only be used with --count or --report') |
| 702 |
|
| 703 |
if opts.progname is None: |
| 704 |
parser.error('progname is missing: required with the main options') |
| 705 |
|
| 706 |
t = Trace(opts.count, opts.trace, countfuncs=opts.listfuncs, |
| 707 |
countcallers=opts.trackcalls, ignoremods=opts.ignore_module, |
| 708 |
ignoredirs=opts.ignore_dir, infile=opts.file, |
| 709 |
outfile=opts.file, timing=opts.timing) |
| 710 |
try: |
| 711 |
if opts.module: |
| 712 |
import runpy |
| 713 |
module_name = opts.progname |
| 714 |
mod_name, mod_spec, code = runpy._get_module_details(module_name) |
| 715 |
sys.argv = [code.co_filename, *opts.arguments] |
| 716 |
globs = { |
| 717 |
'__name__': '__main__', |
| 718 |
'__file__': code.co_filename, |
| 719 |
'__package__': mod_spec.parent, |
| 720 |
'__loader__': mod_spec.loader, |
| 721 |
'__spec__': mod_spec, |
| 722 |
'__cached__': None, |
| 723 |
} |
| 724 |
else: |
| 725 |
sys.argv = [opts.progname, *opts.arguments] |
| 726 |
sys.path[0] = os.path.dirname(opts.progname) |
| 727 |
|
| 728 |
with io.open_code(opts.progname) as fp: |
| 729 |
code = compile(fp.read(), opts.progname, 'exec') |
| 730 |
|
| 731 |
globs = { |
| 732 |
'__file__': opts.progname, |
| 733 |
'__name__': '__main__', |
| 734 |
'__package__': None, |
| 735 |
'__cached__': None, |
| 736 |
} |
| 737 |
t.runctx(code, globs, globs) |
| 738 |
except OSError as err: |
| 739 |
sys.exit("Cannot run file %r because: %s" % (sys.argv[0], err)) |
| 740 |
except SystemExit: |
| 741 |
pass |
| 742 |
|
| 743 |
results = t.results() |
| 744 |
|
| 745 |
if not opts.no_report: |
| 746 |
results.write_results(opts.missing, opts.summary, opts.coverdir) |
| 747 |
|
| 748 |
if __name__=='__main__': |
| 749 |
main() |