blob: c59424df31bda827f031868824b0215cc533ea92 [file] [log] [blame]
"""Core control stuff for Coverage."""
import atexit, inspect, os, platform, random, socket, sys
from coverage.annotate import AnnotateReporter
from coverage.backward import string_class, iitems
from coverage.codeunit import code_unit_factory, CodeUnit, PythonCodeUnit
from coverage.collector import Collector
from coverage.config import CoverageConfig
from import CoverageData
from coverage.debug import DebugControl
from coverage.plugin import CoveragePlugin, Plugins
from coverage.files import FileLocator, TreeMatcher, FnmatchMatcher
from coverage.files import PathAliases, find_python_files, prep_patterns
from coverage.files import ModuleMatcher
from coverage.html import HtmlReporter
from coverage.misc import CoverageException, bool_or_none, join_regex
from coverage.misc import file_be_gone, overrides
from coverage.results import Analysis, Numbers
from coverage.summary import SummaryReporter
from coverage.xmlreport import XmlReporter
# Pypy has some unusual stuff in the "stdlib". Consider those locations
# when deciding where the stdlib is.
import _structseq
except ImportError:
_structseq = None
class Coverage(object):
"""Programmatic access to
To use::
from coverage import Coverage
cov = Coverage()
#.. call your code ..
def __init__(self, data_file=None, data_suffix=None, cover_pylib=None,
auto_data=False, timid=None, branch=None, config_file=True,
source=None, omit=None, include=None, debug=None,
`data_file` is the base name of the data file to use, defaulting to
".coverage". `data_suffix` is appended (with a dot) to `data_file` to
create the final file name. If `data_suffix` is simply True, then a
suffix is created with the machine and process identity included.
`cover_pylib` is a boolean determining whether Python code installed
with the Python interpreter is measured. This includes the Python
standard library and any packages installed with the interpreter.
If `auto_data` is true, then any existing data file will be read when
coverage measurement starts, and data will be saved automatically when
measurement stops.
If `timid` is true, then a slower and simpler trace function will be
used. This is important for some environments where manipulation of
tracing functions breaks the faster trace function.
If `branch` is true, then branch coverage will be measured in addition
to the usual statement coverage.
`config_file` determines what config file to read. If it is a string,
it is the name of the config file to read. If it is True, then a
standard file is read (".coveragerc"). If it is False, then no file is
`source` is a list of file paths or package names. Only code located
in the trees indicated by the file paths or package names will be
`include` and `omit` are lists of filename patterns. Files that match
`include` will be measured, files that match `omit` will not. Each
will also accept a single string argument.
`debug` is a list of strings indicating what debugging information is
`concurrency` is a string indicating the concurrency library being used
in the measured code. Without this, will get incorrect
results. Valid strings are "greenlet", "eventlet", "gevent", or
"thread" (the default).
# Build our configuration from a number of sources:
# 1: defaults:
self.config = CoverageConfig()
# 2: from the rcfile, .coveragerc or setup.cfg file:
if config_file:
did_read_rc = False
specified_file = (config_file is not True)
if not specified_file:
config_file = ".coveragerc"
did_read_rc = self.config.from_file(config_file)
if not did_read_rc:
if specified_file:
raise CoverageException(
"Couldn't read %r as a config file" % config_file
self.config.from_file("setup.cfg", section_prefix="coverage:")
# 3: from environment variables:
env_data_file = os.environ.get('COVERAGE_FILE')
if env_data_file:
self.config.data_file = env_data_file
# 4: from constructor arguments:
data_file=data_file, cover_pylib=cover_pylib, timid=timid,
branch=branch, parallel=bool_or_none(data_suffix),
source=source, omit=omit, include=include, debug=debug,
self._debug_file = None
self._auto_data = auto_data
self._data_suffix = data_suffix
# The matchers for _should_trace.
self.source_match = None
self.source_pkgs_match = None
self.pylib_match = self.cover_match = None
self.include_match = self.omit_match = None
# Is it ok for no data to be collected?
self._warn_no_data = True
self._warn_unimported_source = True
# A record of all the warnings that have been issued.
self._warnings = []
# Other instance attributes, set later.
self.omit = self.include = self.source = None
self.source_pkgs = self.file_locator = None = self.collector = None
self.plugins = self.file_tracers = None
self.pylib_dirs = self.cover_dir = None
self.data_suffix = self.run_suffix = None
self._exclude_re = None
self.debug = None
# State machine variables:
# Have we initialized everything?
self._inited = False
# Have we started collecting and not stopped it?
self._started = False
# Have we measured some data and not harvested it?
self._measured = False
def _init(self):
"""Set all the initial state.
This is called by the public methods to initialize state. This lets us
construct a Coverage object, then tweak its state before this function
is called.
from coverage import __version__
if self._inited:
# Create and configure the debugging controller.
if self._debug_file is None:
self._debug_file = sys.stderr
self.debug = DebugControl(self.config.debug, self._debug_file)
# Load plugins
self.plugins = Plugins.load_plugins(self.config.plugins, self.config)
self.file_tracers = []
for plugin in self.plugins:
if overrides(plugin, "file_tracer", CoveragePlugin):
self.file_tracers.append(None) # The Python case.
# _exclude_re is a dict mapping exclusion list names to compiled
# regexes.
self._exclude_re = {}
self.file_locator = FileLocator()
# The source argument can be directories or package names.
self.source = []
self.source_pkgs = []
for src in self.config.source or []:
if os.path.exists(src):
self.omit = prep_patterns(self.config.omit)
self.include = prep_patterns(self.config.include)
self.collector = Collector(
# Suffixes are a bit tricky. We want to use the data suffix only when
# collecting data, not when combining data. So we save it as
# `self.run_suffix` now, and promote it to `self.data_suffix` if we
# find that we are collecting data later.
if self._data_suffix or self.config.parallel:
if not isinstance(self._data_suffix, string_class):
# if data_suffix=True, use
self._data_suffix = True
self._data_suffix = None
self.data_suffix = None
self.run_suffix = self._data_suffix
# Create the data file. We do this at construction time so that the
# data file will be written into the directory where the process
# started rather than wherever the process eventually chdir'd to. = CoverageData(
collector="coverage v%s" % __version__,
# The dirs for files considered "installed with the interpreter".
self.pylib_dirs = set()
if not self.config.cover_pylib:
# Look at where some standard modules are located. That's the
# indication for "installed with the interpreter". In some
# environments (virtualenv, for example), these modules may be
# spread across a few locations. Look at all the candidate modules
# we've imported, and take all the different ones.
for m in (atexit, os, platform, random, socket, _structseq):
if m is not None and hasattr(m, "__file__"):
if _structseq and not hasattr(_structseq, '__file__'):
# PyPy 2.4 has no __file__ in the builtin modules, but the code
# objects still have the filenames. So dig into one to find
# the path to exclude.
structseq_new = _structseq.structseq_new
structseq_file = structseq_new.func_code.co_filename
except AttributeError:
structseq_file = structseq_new.__code__.co_filename
# To avoid tracing the coverage code itself, we skip anything located
# where we are.
self.cover_dir = self._canonical_dir(__file__)
# Set the reporting precision.
self._inited = True
# Create the matchers we need for _should_trace
if self.source or self.source_pkgs:
self.source_match = TreeMatcher(self.source)
self.source_pkgs_match = ModuleMatcher(self.source_pkgs)
if self.cover_dir:
self.cover_match = TreeMatcher([self.cover_dir])
if self.pylib_dirs:
self.pylib_match = TreeMatcher(self.pylib_dirs)
if self.include:
self.include_match = FnmatchMatcher(self.include)
if self.omit:
self.omit_match = FnmatchMatcher(self.omit)
# The user may want to debug things, show info if desired.
if self.debug.should('config'):
self.debug.write("Configuration values:")
config_info = sorted(self.config.__dict__.items())
if self.debug.should('sys'):
self.debug.write("Debugging info:")
def _canonical_dir(self, morf):
"""Return the canonical directory of the module or file `morf`."""
morf_filename = PythonCodeUnit(morf, self.file_locator).filename
return os.path.split(morf_filename)[0]
def _source_for_file(self, filename):
"""Return the source file for `filename`."""
if not filename.endswith(".py"):
if filename[-4:-1] == ".py":
filename = filename[:-1]
elif filename.endswith("$py.class"): # jython
filename = filename[:-9] + ".py"
return filename
def _name_for_module(self, module_globals, filename):
"""Get the name of the module for a set of globals and filename.
For configurability's sake, we allow __main__ modules to be matched by
their importable name.
If loaded via runpy (aka -m), we can usually recover the "original" full
dotted module name, otherwise, we resort to interpreting the filename to
get the module's name. In the case that the module name can't be
determined, None is returned.
dunder_name = module_globals.get('__name__', None)
if isinstance(dunder_name, str) and dunder_name != '__main__':
# This is the usual case: an imported module.
return dunder_name
loader = module_globals.get('__loader__', None)
for attrname in ('fullname', 'name'): # attribute renamed in py3.2
if hasattr(loader, attrname):
fullname = getattr(loader, attrname)
if isinstance(fullname, str) and fullname != '__main__':
# Module loaded via: runpy -m
return fullname
# Script as first argument to Python command line.
inspectedname = inspect.getmodulename(filename)
if inspectedname is not None:
return inspectedname
return dunder_name
def _should_trace_with_reason(self, filename, frame):
"""Decide whether to trace execution in `filename`, with a reason.
This function is called from the trace function. As each new file name
is encountered, this function determines whether it is traced or not.
Returns a FileDisposition object.
disp = FileDisposition(filename)
def nope(disp, reason):
"""Simple helper to make it easy to return NO."""
disp.trace = False
disp.reason = reason
return disp
# Compiled Python files have two filenames: frame.f_code.co_filename is
# the filename at the time the .pyc was compiled. The second name is
# __file__, which is where the .pyc was actually loaded from. Since
# .pyc files can be moved after compilation (for example, by being
# installed), we look for __file__ in the frame and prefer it to the
# co_filename value.
dunder_file = frame.f_globals.get('__file__')
if dunder_file:
filename = self._source_for_file(dunder_file)
if not filename:
# Empty string is pretty useless
return nope(disp, "empty string isn't a filename")
if filename.startswith('memory:'):
return nope(disp, "memory isn't traceable")
if filename.startswith('<'):
# Lots of non-file execution is represented with artificial
# filenames like "<string>", "<doctest readme.txt[0]>", or
# "<exec_function>". Don't ever trace these executions, since we
# can't do anything with the data later anyway.
return nope(disp, "not a real filename")
# Jython reports the .class file to the tracer, use the source file.
if filename.endswith("$py.class"):
filename = filename[:-9] + ".py"
canonical = self.file_locator.canonical_filename(filename)
disp.canonical_filename = canonical
# Try the plugins, see if they have an opinion about the file.
for plugin in self.file_tracers:
if plugin:
file_tracer = plugin.file_tracer(canonical)
if file_tracer is not None:
file_tracer.plugin_name = plugin.plugin_name
disp.trace = True
disp.file_tracer = file_tracer
if file_tracer.has_dynamic_source_filename():
disp.has_dynamic_filename = True
disp.source_filename = self.file_locator.canonical_filename(file_tracer.source_filename())
disp.trace = True
disp.source_filename = canonical
file_tracer = None
if disp.trace:
if file_tracer:
disp.file_tracer = file_tracer
if not disp.has_dynamic_filename:
if disp.source_filename is None:
raise CoverageException(
"Plugin %r didn't set source_filename for %r" %
(plugin, disp.original_filename)
if disp.check_filters:
reason = self._check_include_omit_etc(
disp.source_filename, frame,
if reason:
nope(disp, reason)
return disp
return nope(disp, "no plugin found") # TODO: a test that causes this.
def _check_include_omit_etc(self, filename, frame):
"""Check a filename against the include, omit, etc, rules.
Returns a string or None. String means, don't trace, and is the reason
why. None means no reason found to not trace.
modulename = self._name_for_module(frame.f_globals, filename)
# If the user specified source or include, then that's authoritative
# about the outer bound of what to measure and we don't have to apply
# any canned exclusions. If they didn't, then we have to exclude the
# stdlib and directories.
if self.source_match:
if self.source_pkgs_match.match(modulename):
if modulename in self.source_pkgs:
return None # There's no reason to skip this file.
if not self.source_match.match(filename):
return "falls outside the --source trees"
elif self.include_match:
if not self.include_match.match(filename):
return "falls outside the --include trees"
# If we aren't supposed to trace installed code, then check if this
# is near the Python standard library and skip it if so.
if self.pylib_match and self.pylib_match.match(filename):
return "is in the stdlib"
# We exclude the coverage code itself, since a little of it will be
# measured otherwise.
if self.cover_match and self.cover_match.match(filename):
return "is part of"
# Check the file against the omit pattern.
if self.omit_match and self.omit_match.match(filename):
return "is inside an --omit pattern"
# No reason found to skip this file.
return None
def _should_trace(self, filename, frame):
"""Decide whether to trace execution in `filename`.
Calls `_should_trace_with_reason`, and returns the FileDisposition.
disp = self._should_trace_with_reason(filename, frame)
if self.debug.should('trace'):
return disp
def _tracing_check_include_omit_etc(self, filename, frame):
"""Check a filename against the include/omit/etc, rules, verbosely.
Returns a boolean: True if the file should be traced, False if not.
reason = self._check_include_omit_etc(filename, frame)
if self.debug.should('trace'):
if not reason:
msg = "Tracing %r" % (filename,)
msg = "Not tracing %r: %s" % (filename, reason)
return not reason
def _warn(self, msg):
"""Use `msg` as a warning."""
sys.stderr.write(" warning: %s\n" % msg)
def use_cache(self, usecache):
"""Control the use of a data file (incorrectly called a cache).
`usecache` is true or false, whether to read and write data on disk.
def load(self):
"""Load previously-collected coverage data from the data file."""
def start(self):
"""Start measuring code coverage.
Coverage measurement actually occurs in functions called after `start`
is invoked. Statements in the same scope as `start` won't be measured.
Once you invoke `start`, you must also call `stop` eventually, or your
process might not shut down cleanly.
if self.run_suffix:
# Calling start() means we're running code, so use the run_suffix
# as the data_suffix when we eventually save the data.
self.data_suffix = self.run_suffix
if self._auto_data:
self._started = True
self._measured = True
def stop(self):
"""Stop measuring code coverage."""
if self._started:
self._started = False
def _atexit(self):
"""Clean up on process shutdown."""
if self._started:
if self._auto_data:
def erase(self):
"""Erase previously-collected coverage data.
This removes the in-memory data collected in this session as well as
discarding the data file.
def clear_exclude(self, which='exclude'):
"""Clear the exclude list."""
setattr(self.config, which + "_list", [])
def exclude(self, regex, which='exclude'):
"""Exclude source lines from execution consideration.
A number of lists of regular expressions are maintained. Each list
selects lines that are treated differently during reporting.
`which` determines which list is modified. The "exclude" list selects
lines that are not considered executable at all. The "partial" list
indicates lines with branches that are not taken.
`regex` is a regular expression. The regex is added to the specified
list. If any of the regexes in the list is found in a line, the line
is marked for special treatment during reporting.
excl_list = getattr(self.config, which + "_list")
def _exclude_regex_stale(self):
"""Drop all the compiled exclusion regexes, a list was modified."""
def _exclude_regex(self, which):
"""Return a compiled regex for the given exclusion list."""
if which not in self._exclude_re:
excl_list = getattr(self.config, which + "_list")
self._exclude_re[which] = join_regex(excl_list)
return self._exclude_re[which]
def get_exclude_list(self, which='exclude'):
"""Return a list of excluded regex patterns.
`which` indicates which list is desired. See `exclude` for the lists
that are available, and their meaning.
return getattr(self.config, which + "_list")
def save(self):
"""Save the collected coverage data to the data file."""
data_suffix = self.data_suffix
if data_suffix is True:
# If data_suffix was a simple true value, then make a suffix with
# plenty of distinguishing information. We do this here in
# `save()` at the last minute so that the pid will be correct even
# if the process forks.
extra = ""
if _TEST_NAME_FILE: # pragma: debugging
with open(_TEST_NAME_FILE) as f:
test_name =
extra = "." + test_name
data_suffix = "%s%s.%s.%06d" % (
socket.gethostname(), extra, os.getpid(),
random.randint(0, 999999)
def combine(self):
"""Combine together a number of similarly-named coverage data files.
All coverage data files whose name starts with `data_file` (from the
coverage() constructor) will be read, and combined together into the
current measurements.
aliases = None
if self.config.paths:
aliases = PathAliases(self.file_locator)
for paths in self.config.paths.values():
result = paths[0]
for pattern in paths[1:]:
aliases.add(pattern, result)
def _harvest_data(self):
"""Get the collected data and reset the collector.
Also warn about various problems collecting data.
if not self._measured:
# TODO: seems like this parallel structure is getting kinda old...
# If there are still entries in the source_pkgs list, then we never
# encountered those packages.
if self._warn_unimported_source:
for pkg in self.source_pkgs:
if pkg not in sys.modules:
self._warn("Module %s was never imported." % pkg)
elif not (
hasattr(sys.modules[pkg], '__file__') and
self._warn("Module %s has no Python source." % pkg)
raise AssertionError(
"Unexpected third case: name = %s, "
"object = %r, "
"__file__ = %s" % (
pkg, sys.modules[pkg], sys.modules[pkg].__file__
# Find out if we got any data.
summary =
if not summary and self._warn_no_data:
self._warn("No data was collected.")
# Find files that were never executed at all.
for src in self.source:
for py_file in find_python_files(src):
py_file = self.file_locator.canonical_filename(py_file)
if self.omit_match and self.omit_match.match(py_file):
# Turns out this file was omitted, so don't pull it back
# in as un-executed.
self._measured = False
# Backward compatibility with version 1.
def analysis(self, morf):
"""Like `analysis2` but doesn't return excluded line numbers."""
f, s, _, m, mf = self.analysis2(morf)
return f, s, m, mf
def analysis2(self, morf):
"""Analyze a module.
`morf` is a module or a filename. It will be analyzed to determine
its coverage statistics. The return value is a 5-tuple:
* The filename for the module.
* A list of line numbers of executable statements.
* A list of line numbers of excluded statements.
* A list of line numbers of statements not run (missing from
* A readable formatted string of the missing line numbers.
The analysis uses the source file itself and the current measured
coverage data.
analysis = self._analyze(morf)
return (
def _analyze(self, it):
"""Analyze a single morf or code unit.
Returns an `Analysis` object.
def get_plugin(filename):
"""For code_unit_factory to use to find the plugin for a file."""
plugin = None
plugin_name =
if plugin_name:
plugin = self.plugins.get(plugin_name)
return plugin
if not isinstance(it, CodeUnit):
it = code_unit_factory(it, self.file_locator, get_plugin)[0]
return Analysis(self, it)
def report(self, morfs=None, show_missing=True, ignore_errors=None,
file=None, # pylint: disable=redefined-builtin
omit=None, include=None, skip_covered=False,
"""Write a summary report to `file`.
Each module in `morfs` is listed, with counts of statements, executed
statements, missing statements, and a list of lines missed.
`include` is a list of filename patterns. Modules whose filenames
match those patterns will be included in the report. Modules matching
`omit` will not be included in the report.
Returns a float, the total percentage covered.
ignore_errors=ignore_errors, omit=omit, include=include,
show_missing=show_missing, skip_covered=skip_covered,
reporter = SummaryReporter(self, self.config)
return, outfile=file)
def annotate(self, morfs=None, directory=None, ignore_errors=None,
omit=None, include=None):
"""Annotate a list of modules.
Each module in `morfs` is annotated. The source is written to a new
file, named with a ",cover" suffix, with each line prefixed with a
marker to indicate the coverage of the line. Covered lines have ">",
excluded lines have "-", and missing lines have "!".
See `` for other arguments.
ignore_errors=ignore_errors, omit=omit, include=include
reporter = AnnotateReporter(self, self.config), directory=directory)
def html_report(self, morfs=None, directory=None, ignore_errors=None,
omit=None, include=None, extra_css=None, title=None):
"""Generate an HTML report.
The HTML is written to `directory`. The file "index.html" is the
overview starting point, with links to more detailed pages for
individual modules.
`extra_css` is a path to a file of other CSS to apply on the page.
It will be copied into the HTML directory.
`title` is a text string (not HTML) to use as the title of the HTML
See `` for other arguments.
Returns a float, the total percentage covered.
ignore_errors=ignore_errors, omit=omit, include=include,
html_dir=directory, extra_css=extra_css, html_title=title,
reporter = HtmlReporter(self, self.config)
def xml_report(self, morfs=None, outfile=None, ignore_errors=None,
omit=None, include=None):
"""Generate an XML report of coverage results.
The report is compatible with Cobertura reports.
Each module in `morfs` is included in the report. `outfile` is the
path to write the file to, "-" will write to stdout.
See `` for other arguments.
Returns a float, the total percentage covered.
ignore_errors=ignore_errors, omit=omit, include=include,
file_to_close = None
delete_file = False
if self.config.xml_output:
if self.config.xml_output == '-':
outfile = sys.stdout
# Ensure that the output directory is created; done here
# because this report pre-opens the output file.
# HTMLReport does this using the Report plumbing because
# its task is more complex, being multiple files.
output_dir = os.path.dirname(self.config.xml_output)
if output_dir and not os.path.isdir(output_dir):
outfile = open(self.config.xml_output, "w")
file_to_close = outfile
reporter = XmlReporter(self, self.config)
return, outfile=outfile)
except CoverageException:
delete_file = True
if file_to_close:
if delete_file:
def sysinfo(self):
"""Return a list of (key, value) pairs showing internal information."""
import coverage as covmod
implementation = platform.python_implementation()
except AttributeError:
implementation = "unknown"
info = [
('version', covmod.__version__),
('coverage', covmod.__file__),
('cover_dir', self.cover_dir),
('pylib_dirs', self.pylib_dirs),
('tracer', self.collector.tracer_name()),
('config_files', self.config.attempted_config_files),
('configs_read', self.config.config_files),
('python', sys.version.replace('\n', '')),
('platform', platform.platform()),
('implementation', implementation),
('executable', sys.executable),
('cwd', os.getcwd()),
('path', sys.path),
('environment', sorted(
("%s = %s" % (k, v)) for k, v in iitems(os.environ)
if k.startswith(("COV", "PY"))
('command_line', " ".join(getattr(sys, 'argv', ['???']))),
matcher_names = [
'source_match', 'source_pkgs_match',
'include_match', 'omit_match',
'cover_match', 'pylib_match',
for matcher_name in matcher_names:
matcher = getattr(self, matcher_name)
if matcher:
matcher_info =
matcher_info = '-none-'
info.append((matcher_name, matcher_info))
return info
class FileDisposition(object):
"""A simple object for noting a number of details of files to trace."""
def __init__(self, original_filename):
self.original_filename = original_filename
self.canonical_filename = original_filename
self.source_filename = None
self.check_filters = True
self.trace = False
self.reason = ""
self.file_tracer = None
self.has_dynamic_filename = False
def debug_message(self):
"""Produce a debugging message explaining the outcome."""
if self.trace:
msg = "Tracing %r" % (self.original_filename,)
msg = "Not tracing %r: %s" % (self.original_filename, self.reason)
return msg
def process_startup():
"""Call this at Python start-up to perhaps measure coverage.
If the environment variable COVERAGE_PROCESS_START is defined, coverage
measurement is started. The value of the variable is the config file
to use.
There are two ways to configure your Python installation to invoke this
function when Python starts:
#. Create or append to to add these lines::
import coverage
#. Create a .pth file in your Python installation containing::
import coverage; coverage.process_startup()
cps = os.environ.get("COVERAGE_PROCESS_START")
if cps:
cov = Coverage(config_file=cps, auto_data=True)
cov._warn_no_data = False
cov._warn_unimported_source = False
# A hack for debugging testing in sub-processes.
_TEST_NAME_FILE = "" #"/tmp/covtest.txt"