Back to index

python3.2  3.2.2
Classes | Functions | Variables
trace Namespace Reference

Classes

class  _Ignore
class  CoverageResults
class  Trace
class  Ignore

Functions

def _unsettrace
def _settrace
def _usage
def _modname
def _fullmodname
def _find_lines_from_code
def _find_lines
def _find_strings
def _find_executable_linenos
def _err_exit
def main
def usage
def modname
def fullmodname
def find_lines_from_code
def find_lines
def find_strings
def find_executable_linenos

Variables

list __all__ = ['Trace', 'CoverageResults']
 _settrace = sys.settrace
string PRAGMA_NOCOVER = "#pragma NO COVER"
tuple rx_blank = re.compile(r'^\s*(#.*)?$')

Function Documentation

def trace._err_exit (   msg) [private]

Definition at line 651 of file trace.py.

00651 
00652 def _err_exit(msg):
00653     sys.stderr.write("%s: %s\n" % (sys.argv[0], msg))
00654     sys.exit(1)

Here is the caller graph for this function:

def trace._find_executable_linenos (   filename) [private]
Return dict where keys are line numbers in the line number table.

Definition at line 433 of file trace.py.

00433 
00434 def _find_executable_linenos(filename):
00435     """Return dict where keys are line numbers in the line number table."""
00436     try:
00437         with tokenize.open(filename) as f:
00438             prog = f.read()
00439             encoding = f.encoding
00440     except IOError as err:
00441         print(("Not printing coverage data for %r: %s"
00442                               % (filename, err)), file=sys.stderr)
00443         return {}
00444     code = compile(prog, filename, "exec")
00445     strs = _find_strings(filename, encoding)
00446     return _find_lines(code, strs)

Here is the call graph for this function:

Here is the caller graph for this function:

def trace._find_lines (   code,
  strs 
) [private]
Return lineno dict for all code objects reachable from code.

Definition at line 398 of file trace.py.

00398 
00399 def _find_lines(code, strs):
00400     """Return lineno dict for all code objects reachable from code."""
00401     # get all of the lineno information from the code of this scope level
00402     linenos = _find_lines_from_code(code, strs)
00403 
00404     # and check the constants for references to other code objects
00405     for c in code.co_consts:
00406         if inspect.iscode(c):
00407             # find another code object, so recurse into it
00408             linenos.update(_find_lines(c, strs))
00409     return linenos

Here is the call graph for this function:

Here is the caller graph for this function:

def trace._find_lines_from_code (   code,
  strs 
) [private]
Return dict where keys are lines in the line number table.

Definition at line 388 of file trace.py.

00388 
00389 def _find_lines_from_code(code, strs):
00390     """Return dict where keys are lines in the line number table."""
00391     linenos = {}
00392 
00393     for _, lineno in dis.findlinestarts(code):
00394         if lineno not in strs:
00395             linenos[lineno] = 1
00396 
00397     return linenos

Here is the call graph for this function:

Here is the caller graph for this function:

def trace._find_strings (   filename,
  encoding = None 
) [private]
Return a dict of possible docstring positions.

The dict maps line numbers to strings.  There is an entry for
line that contains only a string or a part of a triple-quoted
string.

Definition at line 410 of file trace.py.

00410 
00411 def _find_strings(filename, encoding=None):
00412     """Return a dict of possible docstring positions.
00413 
00414     The dict maps line numbers to strings.  There is an entry for
00415     line that contains only a string or a part of a triple-quoted
00416     string.
00417     """
00418     d = {}
00419     # If the first token is a string, then it's the module docstring.
00420     # Add this special case so that the test in the loop passes.
00421     prev_ttype = token.INDENT
00422     with open(filename, encoding=encoding) as f:
00423         tok = tokenize.generate_tokens(f.readline)
00424         for ttype, tstr, start, end, line in tok:
00425             if ttype == token.STRING:
00426                 if prev_ttype == token.INDENT:
00427                     sline, scol = start
00428                     eline, ecol = end
00429                     for i in range(sline, eline + 1):
00430                         d[i] = 1
00431             prev_ttype = ttype
00432     return d

Here is the caller graph for this function:

def trace._fullmodname (   path) [private]
Return a plausible module name for the path.

Definition at line 188 of file trace.py.

00188 
00189 def _fullmodname(path):
00190     """Return a plausible module name for the path."""
00191 
00192     # If the file 'path' is part of a package, then the filename isn't
00193     # enough to uniquely identify it.  Try to do the right thing by
00194     # looking in sys.path for the longest matching prefix.  We'll
00195     # assume that the rest is the package name.
00196 
00197     comparepath = os.path.normcase(path)
00198     longest = ""
00199     for dir in sys.path:
00200         dir = os.path.normcase(dir)
00201         if comparepath.startswith(dir) and comparepath[len(dir)] == os.sep:
00202             if len(dir) > len(longest):
00203                 longest = dir
00204 
00205     if longest:
00206         base = path[len(longest) + 1:]
00207     else:
00208         base = path
00209     # the drive letter is never part of the module name
00210     drive, base = os.path.splitdrive(base)
00211     base = base.replace(os.sep, ".")
00212     if os.altsep:
00213         base = base.replace(os.altsep, ".")
00214     filename, ext = os.path.splitext(base)
00215     return filename.lstrip(".")

Here is the caller graph for this function:

def trace._modname (   path) [private]
Return a plausible module name for the patch.

Definition at line 181 of file trace.py.

00181 
00182 def _modname(path):
00183     """Return a plausible module name for the patch."""
00184 
00185     base = os.path.basename(path)
00186     filename, ext = os.path.splitext(base)
00187     return filename

Here is the caller graph for this function:

def trace._settrace (   func) [private]

Definition at line 73 of file trace.py.

00073 
00074     def _settrace(func):
00075         threading.settrace(func)
00076         sys.settrace(func)

Here is the call graph for this function:

def trace._unsettrace ( ) [private]

Definition at line 70 of file trace.py.

00070 
00071     def _unsettrace():
00072         sys.settrace(None)
else:

Here is the caller graph for this function:

def trace._usage (   outfile) [private]

Definition at line 81 of file trace.py.

00081 
00082 def _usage(outfile):
00083     outfile.write("""Usage: %s [OPTIONS] <file> [ARGS]
00084 
00085 Meta-options:
00086 --help                Display this help then exit.
00087 --version             Output version information then exit.
00088 
00089 Otherwise, exactly one of the following three options must be given:
00090 -t, --trace           Print each line to sys.stdout before it is executed.
00091 -c, --count           Count the number of times each line is executed
00092                       and write the counts to <module>.cover for each
00093                       module executed, in the module's directory.
00094                       See also `--coverdir', `--file', `--no-report' below.
00095 -l, --listfuncs       Keep track of which functions are executed at least
00096                       once and write the results to sys.stdout after the
00097                       program exits.
00098 -T, --trackcalls      Keep track of caller/called pairs and write the
00099                       results to sys.stdout after the program exits.
00100 -r, --report          Generate a report from a counts file; do not execute
00101                       any code.  `--file' must specify the results file to
00102                       read, which must have been created in a previous run
00103                       with `--count --file=FILE'.
00104 
00105 Modifiers:
00106 -f, --file=<file>     File to accumulate counts over several runs.
00107 -R, --no-report       Do not generate the coverage report files.
00108                       Useful if you want to accumulate over several runs.
00109 -C, --coverdir=<dir>  Directory where the report files.  The coverage
00110                       report for <package>.<module> is written to file
00111                       <dir>/<package>/<module>.cover.
00112 -m, --missing         Annotate executable lines that were not executed
00113                       with '>>>>>> '.
00114 -s, --summary         Write a brief summary on stdout for each file.
00115                       (Can only be used with --count or --report.)
00116 -g, --timing          Prefix each line with the time since the program started.
00117                       Only used while tracing.
00118 
00119 Filters, may be repeated multiple times:
00120 --ignore-module=<mod> Ignore the given module(s) and its submodules
00121                       (if it is a package).  Accepts comma separated
00122                       list of module names
00123 --ignore-dir=<dir>    Ignore files in the given directory (multiple
00124                       directories can be joined by os.pathsep).
00125 """ % sys.argv[0])

Here is the caller graph for this function:

def trace.find_executable_linenos (   filename)

Definition at line 851 of file trace.py.

00851 
00852 def find_executable_linenos(filename):
00853     _warn("The trace.find_executable_linenos() function is deprecated",
00854          DeprecationWarning, 2)
00855     return _find_executable_linenos(filename)

Here is the call graph for this function:

def trace.find_lines (   code,
  strs 
)

Definition at line 841 of file trace.py.

00841 
00842 def find_lines(code, strs):
00843     _warn("The trace.find_lines() function is deprecated",
00844          DeprecationWarning, 2)
00845     return _find_lines(code, strs)

Here is the call graph for this function:

def trace.find_lines_from_code (   code,
  strs 
)

Definition at line 836 of file trace.py.

00836 
00837 def find_lines_from_code(code, strs):
00838     _warn("The trace.find_lines_from_code() function is deprecated",
00839          DeprecationWarning, 2)
00840     return _find_lines_from_code(code, strs)

Here is the call graph for this function:

def trace.find_strings (   filename,
  encoding = None 
)

Definition at line 846 of file trace.py.

00846 
00847 def find_strings(filename, encoding=None):
00848     _warn("The trace.find_strings() function is deprecated",
00849          DeprecationWarning, 2)
00850     return _find_strings(filename, encoding=None)

Here is the call graph for this function:

def trace.fullmodname (   path)

Definition at line 831 of file trace.py.

00831 
00832 def fullmodname(path):
00833     _warn("The trace.fullmodname() function is deprecated",
00834          DeprecationWarning, 2)
00835     return _fullmodname(path)

Here is the call graph for this function:

def trace.main (   argv = None)

Definition at line 655 of file trace.py.

00655 
00656 def main(argv=None):
00657     import getopt
00658 
00659     if argv is None:
00660         argv = sys.argv
00661     try:
00662         opts, prog_argv = getopt.getopt(argv[1:], "tcrRf:d:msC:lTg",
00663                                         ["help", "version", "trace", "count",
00664                                          "report", "no-report", "summary",
00665                                          "file=", "missing",
00666                                          "ignore-module=", "ignore-dir=",
00667                                          "coverdir=", "listfuncs",
00668                                          "trackcalls", "timing"])
00669 
00670     except getopt.error as msg:
00671         sys.stderr.write("%s: %s\n" % (sys.argv[0], msg))
00672         sys.stderr.write("Try `%s --help' for more information\n"
00673                          % sys.argv[0])
00674         sys.exit(1)
00675 
00676     trace = 0
00677     count = 0
00678     report = 0
00679     no_report = 0
00680     counts_file = None
00681     missing = 0
00682     ignore_modules = []
00683     ignore_dirs = []
00684     coverdir = None
00685     summary = 0
00686     listfuncs = False
00687     countcallers = False
00688     timing = False
00689 
00690     for opt, val in opts:
00691         if opt == "--help":
00692             _usage(sys.stdout)
00693             sys.exit(0)
00694 
00695         if opt == "--version":
00696             sys.stdout.write("trace 2.0\n")
00697             sys.exit(0)
00698 
00699         if opt == "-T" or opt == "--trackcalls":
00700             countcallers = True
00701             continue
00702 
00703         if opt == "-l" or opt == "--listfuncs":
00704             listfuncs = True
00705             continue
00706 
00707         if opt == "-g" or opt == "--timing":
00708             timing = True
00709             continue
00710 
00711         if opt == "-t" or opt == "--trace":
00712             trace = 1
00713             continue
00714 
00715         if opt == "-c" or opt == "--count":
00716             count = 1
00717             continue
00718 
00719         if opt == "-r" or opt == "--report":
00720             report = 1
00721             continue
00722 
00723         if opt == "-R" or opt == "--no-report":
00724             no_report = 1
00725             continue
00726 
00727         if opt == "-f" or opt == "--file":
00728             counts_file = val
00729             continue
00730 
00731         if opt == "-m" or opt == "--missing":
00732             missing = 1
00733             continue
00734 
00735         if opt == "-C" or opt == "--coverdir":
00736             coverdir = val
00737             continue
00738 
00739         if opt == "-s" or opt == "--summary":
00740             summary = 1
00741             continue
00742 
00743         if opt == "--ignore-module":
00744             for mod in val.split(","):
00745                 ignore_modules.append(mod.strip())
00746             continue
00747 
00748         if opt == "--ignore-dir":
00749             for s in val.split(os.pathsep):
00750                 s = os.path.expandvars(s)
00751                 # should I also call expanduser? (after all, could use $HOME)
00752 
00753                 s = s.replace("$prefix",
00754                               os.path.join(sys.prefix, "lib",
00755                                            "python" + sys.version[:3]))
00756                 s = s.replace("$exec_prefix",
00757                               os.path.join(sys.exec_prefix, "lib",
00758                                            "python" + sys.version[:3]))
00759                 s = os.path.normpath(s)
00760                 ignore_dirs.append(s)
00761             continue
00762 
00763         assert 0, "Should never get here"
00764 
00765     if listfuncs and (count or trace):
00766         _err_exit("cannot specify both --listfuncs and (--trace or --count)")
00767 
00768     if not (count or trace or report or listfuncs or countcallers):
00769         _err_exit("must specify one of --trace, --count, --report, "
00770                   "--listfuncs, or --trackcalls")
00771 
00772     if report and no_report:
00773         _err_exit("cannot specify both --report and --no-report")
00774 
00775     if report and not counts_file:
00776         _err_exit("--report requires a --file")
00777 
00778     if no_report and len(prog_argv) == 0:
00779         _err_exit("missing name of file to run")
00780 
00781     # everything is ready
00782     if report:
00783         results = CoverageResults(infile=counts_file, outfile=counts_file)
00784         results.write_results(missing, summary=summary, coverdir=coverdir)
00785     else:
00786         sys.argv = prog_argv
00787         progname = prog_argv[0]
00788         sys.path[0] = os.path.split(progname)[0]
00789 
00790         t = Trace(count, trace, countfuncs=listfuncs,
00791                   countcallers=countcallers, ignoremods=ignore_modules,
00792                   ignoredirs=ignore_dirs, infile=counts_file,
00793                   outfile=counts_file, timing=timing)
00794         try:
00795             with open(progname) as fp:
00796                 code = compile(fp.read(), progname, 'exec')
00797             # try to emulate __main__ namespace as much as possible
00798             globs = {
00799                 '__file__': progname,
00800                 '__name__': '__main__',
00801                 '__package__': None,
00802                 '__cached__': None,
00803             }
00804             t.runctx(code, globs, globs)
00805         except IOError as err:
00806             _err_exit("Cannot run file %r because: %s" % (sys.argv[0], err))
00807         except SystemExit:
00808             pass
00809 
00810         results = t.results()
00811 
00812         if not no_report:
00813             results.write_results(missing, summary=summary, coverdir=coverdir)
00814 
#  Deprecated API

Here is the call graph for this function:

Here is the caller graph for this function:

def trace.modname (   path)

Definition at line 826 of file trace.py.

00826 
00827 def modname(path):
00828     _warn("The trace.modname() function is deprecated",
00829          DeprecationWarning, 2)
00830     return _modname(path)

Here is the call graph for this function:

Here is the caller graph for this function:

def trace.usage (   outfile)

Definition at line 815 of file trace.py.

00815 
00816 def usage(outfile):
00817     _warn("The trace.usage() function is deprecated",
00818          DeprecationWarning, 2)
00819     _usage(outfile)

Here is the call graph for this function:


Variable Documentation

Definition at line 50 of file trace.py.

trace._settrace = sys.settrace

Definition at line 68 of file trace.py.

string trace.PRAGMA_NOCOVER = "#pragma NO COVER"

Definition at line 126 of file trace.py.

tuple trace.rx_blank = re.compile(r'^\s*(#.*)?$')

Definition at line 129 of file trace.py.