本文整理汇总了Python中coverage.collector.Collector类的典型用法代码示例。如果您正苦于以下问题:Python Collector类的具体用法?Python Collector怎么用?Python Collector使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Collector类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _init
def _init(self):
"""Set all the initial state.
This is called by the public methods to initialize state. This lets us
construct a :class:`Coverage` object, then tweak its state before this
function is called.
"""
if self._inited:
return
# Create and configure the debugging controller. COVERAGE_DEBUG_FILE
# is an environment variable, the name of a file to append debug logs
# to.
if self._debug_file is None:
debug_file_name = os.environ.get("COVERAGE_DEBUG_FILE")
if debug_file_name:
self._debug_file = open(debug_file_name, "a")
else:
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.debug)
# _exclude_re is a dict that maps exclusion list names to compiled
# regexes.
self._exclude_re = {}
self._exclude_regex_stale()
files.set_relative_directory()
# 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.source.append(files.canonical_filename(src))
else:
self.source_pkgs.append(src)
self.omit = prep_patterns(self.config.omit)
self.include = prep_patterns(self.config.include)
concurrency = self.config.concurrency
if concurrency == "multiprocessing":
patch_multiprocessing()
concurrency = None
self.collector = Collector(
should_trace=self._should_trace,
check_include=self._check_include_omit_etc,
timid=self.config.timid,
branch=self.config.branch,
warn=self._warn,
concurrency=concurrency,
)
# Early warning if we aren't going to be able to support plugins.
if self.plugins.file_tracers and not self.collector.supports_plugins:
self._warn(
"Plugin file tracers (%s) aren't supported with %s" % (
", ".join(
plugin._coverage_plugin_name
for plugin in self.plugins.file_tracers
),
self.collector.tracer_name(),
)
)
for plugin in self.plugins.file_tracers:
plugin._coverage_enabled = False
# 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 .machinename.pid.random
self._data_suffix = True
else:
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.
self.data = CoverageData(debug=self.debug)
self.data_files = CoverageDataFiles(basename=self.config.data_file, warn=self._warn)
# The directories 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, inspect, os, platform, re, _structseq, traceback):
#.........这里部分代码省略.........
示例2: Coverage
#.........这里部分代码省略.........
if debug_file_name:
self._debug_file = open(debug_file_name, "a")
else:
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.debug)
# _exclude_re is a dict that maps exclusion list names to compiled
# regexes.
self._exclude_re = {}
self._exclude_regex_stale()
files.set_relative_directory()
# 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.source.append(files.canonical_filename(src))
else:
self.source_pkgs.append(src)
self.omit = prep_patterns(self.config.omit)
self.include = prep_patterns(self.config.include)
concurrency = self.config.concurrency
if concurrency == "multiprocessing":
patch_multiprocessing()
concurrency = None
self.collector = Collector(
should_trace=self._should_trace,
check_include=self._check_include_omit_etc,
timid=self.config.timid,
branch=self.config.branch,
warn=self._warn,
concurrency=concurrency,
)
# Early warning if we aren't going to be able to support plugins.
if self.plugins.file_tracers and not self.collector.supports_plugins:
self._warn(
"Plugin file tracers (%s) aren't supported with %s" % (
", ".join(
plugin._coverage_plugin_name
for plugin in self.plugins.file_tracers
),
self.collector.tracer_name(),
)
)
for plugin in self.plugins.file_tracers:
plugin._coverage_enabled = False
# 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 .machinename.pid.random
self._data_suffix = True
else:
self._data_suffix = None
示例3: Coverage
#.........这里部分代码省略.........
# Create and configure the debugging controller.
self.debug = DebugControl(self.config.debug, debug_file or sys.stderr)
# Load plugins
self.plugins = Plugins.load_plugins(self.config.plugins, self.config)
self.trace_judges = []
for plugin in self.plugins:
if plugin_implements(plugin, "trace_judge"):
self.trace_judges.append(plugin)
self.trace_judges.append(None) # The Python case.
self.auto_data = auto_data
# _exclude_re is a dict mapping exclusion list names to compiled
# regexes.
self._exclude_re = {}
self._exclude_regex_stale()
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.source.append(self.file_locator.canonical_filename(src))
else:
self.source_pkgs.append(src)
self.omit = prep_patterns(self.config.omit)
self.include = prep_patterns(self.config.include)
self.collector = Collector(
should_trace=self._should_trace,
check_include=self._tracing_check_include_omit_etc,
timid=self.config.timid,
branch=self.config.branch,
warn=self._warn,
concurrency=self.config.concurrency,
)
# 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 data_suffix or self.config.parallel:
if not isinstance(data_suffix, string_class):
# if data_suffix=True, use .machinename.pid.random
data_suffix = True
else:
data_suffix = None
self.data_suffix = None
self.run_suffix = 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.
self.data = CoverageData(
basename=self.config.data_file,
collector="coverage v%s" % __version__,
debug=self.debug,
)
# The dirs for files considered "installed with the interpreter".
self.pylib_dirs = set()
示例4: __init__
#.........这里部分代码省略.........
# Create and configure the debugging controller.
self.debug = DebugControl(self.config.debug, debug_file or sys.stderr)
# Load plugins
self.plugins = Plugins.load_plugins(self.config.plugins, self.config)
self.trace_judges = []
for plugin in self.plugins:
if plugin_implements(plugin, "trace_judge"):
self.trace_judges.append(plugin)
self.trace_judges.append(None) # The Python case.
self.auto_data = auto_data
# _exclude_re is a dict mapping exclusion list names to compiled
# regexes.
self._exclude_re = {}
self._exclude_regex_stale()
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.source.append(self.file_locator.canonical_filename(src))
else:
self.source_pkgs.append(src)
self.omit = prep_patterns(self.config.omit)
self.include = prep_patterns(self.config.include)
self.collector = Collector(
should_trace=self._should_trace,
check_include=self._tracing_check_include_omit_etc,
timid=self.config.timid,
branch=self.config.branch,
warn=self._warn,
concurrency=self.config.concurrency,
)
# 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 data_suffix or self.config.parallel:
if not isinstance(data_suffix, string_class):
# if data_suffix=True, use .machinename.pid.random
data_suffix = True
else:
data_suffix = None
self.data_suffix = None
self.run_suffix = 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.
self.data = CoverageData(
basename=self.config.data_file,
collector="coverage v%s" % __version__,
debug=self.debug,
)
# 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__"):
self.pylib_dirs.add(self._canonical_dir(m))
# To avoid tracing the coverage code itself, we skip anything located
# where we are.
self.cover_dir = self._canonical_dir(__file__)
# The matchers for _should_trace.
self.source_match = None
self.pylib_match = self.cover_match = None
self.include_match = self.omit_match = None
# Set the reporting precision.
Numbers.set_precision(self.config.precision)
# Is it ok for no data to be collected?
self._warn_no_data = True
self._warn_unimported_source = True
# State machine variables:
# Have we started collecting and not stopped it?
self._started = False
# Have we measured some data and not harvested it?
self._measured = False
atexit.register(self._atexit)
示例5: coverage
#.........这里部分代码省略.........
# 4: from constructor arguments:
if isinstance(omit, string_class):
omit = [omit]
if isinstance(include, string_class):
include = [include]
self.config.from_args(
data_file=data_file, cover_pylib=cover_pylib, timid=timid,
branch=branch, parallel=bool_or_none(data_suffix),
source=source, omit=omit, include=include
)
self.auto_data = auto_data
self.atexit_registered = False
# _exclude_re is a dict mapping exclusion list names to compiled
# regexes.
self._exclude_re = {}
self._exclude_regex_stale()
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.source.append(self.file_locator.canonical_filename(src))
else:
self.source_pkgs.append(src)
self.omit = self._prep_patterns(self.config.omit)
self.include = self._prep_patterns(self.config.include)
self.collector = Collector(
self._should_trace, timid=self.config.timid,
branch=self.config.branch, warn=self._warn
)
# 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 data_suffix or self.config.parallel:
if not isinstance(data_suffix, string_class):
# if data_suffix=True, use .machinename.pid.random
data_suffix = True
else:
data_suffix = None
self.data_suffix = None
self.run_suffix = 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.
self.data = CoverageData(
basename=self.config.data_file,
collector="coverage v%s" % __version__
)
# The dirs for files considered "installed with the interpreter".
self.pylib_dirs = []
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 centralfitestoque), these modules may be
# spread across a few locations. Look at all the candidate modules
示例6: __init__
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):
"""
`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
read.
`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
measured.
`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.
"""
from coverage import __version__
# A record of all the warnings that have been issued.
self._warnings = []
# Build our configuration from a number of sources:
# 1: defaults:
self.config = CoverageConfig()
# 2: from the coveragerc file:
if config_file:
if config_file is True:
config_file = ".coveragerc"
try:
self.config.from_file(config_file)
except ValueError:
_, err, _ = sys.exc_info()
raise CoverageException(
"Couldn't read config file %s: %s" % (config_file, err)
)
# 3: from environment variables:
self.config.from_environment('COVERAGE_OPTIONS')
env_data_file = os.environ.get('COVERAGE_FILE')
if env_data_file:
self.config.data_file = env_data_file
# 4: from constructor arguments:
if isinstance(omit, string_class):
omit = [omit]
if isinstance(include, string_class):
include = [include]
self.config.from_args(
data_file=data_file, cover_pylib=cover_pylib, timid=timid,
branch=branch, parallel=bool_or_none(data_suffix),
source=source, omit=omit, include=include
)
self.auto_data = auto_data
self.atexit_registered = False
# _exclude_re is a dict mapping exclusion list names to compiled
# regexes.
self._exclude_re = {}
self._exclude_regex_stale()
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.source.append(self.file_locator.canonical_filename(src))
else:
self.source_pkgs.append(src)
self.omit = self._prep_patterns(self.config.omit)
self.include = self._prep_patterns(self.config.include)
self.collector = Collector(
self._should_trace, timid=self.config.timid,
#.........这里部分代码省略.........
示例7: coverage
class coverage(object):
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, debug_file = None):
from coverage import __version__
self._warnings = []
self.config = CoverageConfig()
if config_file:
if config_file is True:
config_file = '.coveragerc'
try:
self.config.from_file(config_file)
except ValueError:
_, err, _ = sys.exc_info()
raise CoverageException("Couldn't read config file %s: %s" % (config_file, err))
self.config.from_environment('COVERAGE_OPTIONS')
env_data_file = os.environ.get('COVERAGE_FILE')
if env_data_file:
self.config.data_file = env_data_file
self.config.from_args(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 = DebugControl(self.config.debug, debug_file or sys.stderr)
self.auto_data = auto_data
self._exclude_re = {}
self._exclude_regex_stale()
self.file_locator = FileLocator()
self.source = []
self.source_pkgs = []
for src in self.config.source or []:
if os.path.exists(src):
self.source.append(self.file_locator.canonical_filename(src))
else:
self.source_pkgs.append(src)
self.omit = prep_patterns(self.config.omit)
self.include = prep_patterns(self.config.include)
self.collector = Collector(self._should_trace, timid=self.config.timid, branch=self.config.branch, warn=self._warn)
if data_suffix or self.config.parallel:
if not isinstance(data_suffix, string_class):
data_suffix = True
else:
data_suffix = None
self.data_suffix = None
self.run_suffix = data_suffix
self.data = CoverageData(basename=self.config.data_file, collector='coverage v%s' % __version__, debug=self.debug)
self.pylib_dirs = []
if not self.config.cover_pylib:
for m in (atexit,
os,
random,
socket,
_structseq):
if m is not None and hasattr(m, '__file__'):
m_dir = self._canonical_dir(m)
if m_dir not in self.pylib_dirs:
self.pylib_dirs.append(m_dir)
self.cover_dir = self._canonical_dir(__file__)
self.source_match = None
self.pylib_match = self.cover_match = None
self.include_match = self.omit_match = None
Numbers.set_precision(self.config.precision)
self._warn_no_data = True
self._warn_unimported_source = True
self._started = False
self._measured = False
atexit.register(self._atexit)
def _canonical_dir(self, morf):
return os.path.split(CodeUnit(morf, self.file_locator).filename)[0]
def _source_for_file(self, filename):
if not filename.endswith('.py'):
if filename[-4:-1] == '.py':
filename = filename[:-1]
elif filename.endswith('$py.class'):
filename = filename[:-9] + '.py'
return filename
def _should_trace_with_reason(self, filename, frame):
if not filename:
return (None, "empty string isn't a filename")
if filename.startswith('<'):
return (None, 'not a real filename')
self._check_for_packages()
dunder_file = frame.f_globals.get('__file__')
if dunder_file:
filename = self._source_for_file(dunder_file)
if filename.endswith('$py.class'):
filename = filename[:-9] + '.py'
canonical = self.file_locator.canonical_filename(filename)
if self.source_match:
if not self.source_match.match(canonical):
return (None, 'falls outside the --source trees')
elif self.include_match:
if not self.include_match.match(canonical):
return (None, 'falls outside the --include trees')
else:
if self.pylib_match and self.pylib_match.match(canonical):
return (None, 'is in the stdlib')
if self.cover_match and self.cover_match.match(canonical):
#.........这里部分代码省略.........
示例8: __init__
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, debug_file = None):
from coverage import __version__
self._warnings = []
self.config = CoverageConfig()
if config_file:
if config_file is True:
config_file = '.coveragerc'
try:
self.config.from_file(config_file)
except ValueError:
_, err, _ = sys.exc_info()
raise CoverageException("Couldn't read config file %s: %s" % (config_file, err))
self.config.from_environment('COVERAGE_OPTIONS')
env_data_file = os.environ.get('COVERAGE_FILE')
if env_data_file:
self.config.data_file = env_data_file
self.config.from_args(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 = DebugControl(self.config.debug, debug_file or sys.stderr)
self.auto_data = auto_data
self._exclude_re = {}
self._exclude_regex_stale()
self.file_locator = FileLocator()
self.source = []
self.source_pkgs = []
for src in self.config.source or []:
if os.path.exists(src):
self.source.append(self.file_locator.canonical_filename(src))
else:
self.source_pkgs.append(src)
self.omit = prep_patterns(self.config.omit)
self.include = prep_patterns(self.config.include)
self.collector = Collector(self._should_trace, timid=self.config.timid, branch=self.config.branch, warn=self._warn)
if data_suffix or self.config.parallel:
if not isinstance(data_suffix, string_class):
data_suffix = True
else:
data_suffix = None
self.data_suffix = None
self.run_suffix = data_suffix
self.data = CoverageData(basename=self.config.data_file, collector='coverage v%s' % __version__, debug=self.debug)
self.pylib_dirs = []
if not self.config.cover_pylib:
for m in (atexit,
os,
random,
socket,
_structseq):
if m is not None and hasattr(m, '__file__'):
m_dir = self._canonical_dir(m)
if m_dir not in self.pylib_dirs:
self.pylib_dirs.append(m_dir)
self.cover_dir = self._canonical_dir(__file__)
self.source_match = None
self.pylib_match = self.cover_match = None
self.include_match = self.omit_match = None
Numbers.set_precision(self.config.precision)
self._warn_no_data = True
self._warn_unimported_source = True
self._started = False
self._measured = False
atexit.register(self._atexit)
示例9: __init__
def __init__(self, data_file=None, data_suffix=False, cover_pylib=False,
auto_data=False, timid=False, branch=False):
"""
`data_file` is the base name of the data file to use, defaulting to
".coverage". `data_suffix` is appended 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.
"""
from coverage import __version__
self.cover_pylib = cover_pylib
self.auto_data = auto_data
self.atexit_registered = False
self.exclude_re = ""
self.exclude_list = []
self.file_locator = FileLocator()
# Timidity: for nose users, read an environment variable. This is a
# cheap hack, since the rest of the command line arguments aren't
# recognized, but it solves some users' problems.
timid = timid or ('--timid' in os.environ.get('COVERAGE_OPTIONS', ''))
self.collector = Collector(
self._should_trace, timid=timid, branch=branch
)
# Create the data file.
if data_suffix:
if not isinstance(data_suffix, string_class):
# if data_suffix=True, use .machinename.pid
data_suffix = ".%s.%s" % (socket.gethostname(), os.getpid())
else:
data_suffix = None
self.data = CoverageData(
basename=data_file, suffix=data_suffix,
collector="coverage v%s" % __version__
)
# The default exclude pattern.
self.exclude('# *pragma[: ]*[nN][oO] *[cC][oO][vV][eE][rR]')
# The prefix for files considered "installed with the interpreter".
if not self.cover_pylib:
# Look at where the "os" module is located. That's the indication
# for "installed with the interpreter".
os_file = self.file_locator.canonical_filename(os.__file__)
self.pylib_prefix = os.path.split(os_file)[0]
# To avoid tracing the coverage code itself, we skip anything located
# where we are.
here = self.file_locator.canonical_filename(__file__)
self.cover_prefix = os.path.split(here)[0]
示例10: __init__
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):
"""
`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
read.
`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
measured.
`include` and `omit` are lists of filename patterns. Files that match
`include` will be measured, files that match `omit` will not.
"""
from coverage import __version__
# Build our configuration from a number of sources:
# 1: defaults:
self.config = CoverageConfig()
# 2: from the coveragerc file:
if config_file:
if config_file is True:
config_file = ".coveragerc"
self.config.from_file(config_file)
# 3: from environment variables:
self.config.from_environment('COVERAGE_OPTIONS')
env_data_file = os.environ.get('COVERAGE_FILE')
if env_data_file:
self.config.data_file = env_data_file
# 4: from constructor arguments:
self.config.from_args(
data_file=data_file, cover_pylib=cover_pylib, timid=timid,
branch=branch, parallel=bool_or_none(data_suffix),
source=source, omit=omit, include=include
)
self.auto_data = auto_data
self.atexit_registered = False
self.exclude_re = ""
self._compile_exclude()
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.source.append(self.file_locator.canonical_filename(src))
else:
self.source_pkgs.append(src)
self.omit = self._abs_files(self.config.omit)
self.include = self._abs_files(self.config.include)
self.collector = Collector(
self._should_trace, timid=self.config.timid,
branch=self.config.branch
)
# 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 data_suffix or self.config.parallel:
if not isinstance(data_suffix, string_class):
# if data_suffix=True, use .machinename.pid.random
data_suffix = True
else:
data_suffix = None
self.data_suffix = None
self.run_suffix = data_suffix
#.........这里部分代码省略.........
示例11: coverage
class coverage(object):
"""Programmatic access to Coverage.
To use::
from coverage import coverage
cov = coverage()
cov.start()
#.. blah blah (run your code) blah blah ..
cov.stop()
cov.html_report(directory='covhtml')
"""
def __init__(self, data_file=None, data_suffix=False, cover_pylib=False,
auto_data=False, timid=False, branch=False):
"""
`data_file` is the base name of the data file to use, defaulting to
".coverage". `data_suffix` is appended 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.
"""
from coverage import __version__
self.cover_pylib = cover_pylib
self.auto_data = auto_data
self.atexit_registered = False
self.exclude_re = ""
self.exclude_list = []
self.file_locator = FileLocator()
# Timidity: for nose users, read an environment variable. This is a
# cheap hack, since the rest of the command line arguments aren't
# recognized, but it solves some users' problems.
timid = timid or ('--timid' in os.environ.get('COVERAGE_OPTIONS', ''))
self.collector = Collector(
self._should_trace, timid=timid, branch=branch
)
# Create the data file.
if data_suffix:
if not isinstance(data_suffix, string_class):
# if data_suffix=True, use .machinename.pid
data_suffix = ".%s.%s" % (socket.gethostname(), os.getpid())
else:
data_suffix = None
self.data = CoverageData(
basename=data_file, suffix=data_suffix,
collector="coverage v%s" % __version__
)
# The default exclude pattern.
self.exclude('# *pragma[: ]*[nN][oO] *[cC][oO][vV][eE][rR]')
# The prefix for files considered "installed with the interpreter".
if not self.cover_pylib:
# Look at where the "os" module is located. That's the indication
# for "installed with the interpreter".
os_file = self.file_locator.canonical_filename(os.__file__)
self.pylib_prefix = os.path.split(os_file)[0]
# To avoid tracing the coverage code itself, we skip anything located
# where we are.
here = self.file_locator.canonical_filename(__file__)
self.cover_prefix = os.path.split(here)[0]
def _should_trace(self, filename, frame):
"""Decide whether to trace execution in `filename`
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 canonicalized filename if it should be traced, False if it
should not.
"""
if filename == '<string>':
# There's no point in ever tracing string executions, we can't do
# anything with the data later anyway.
return False
#.........这里部分代码省略.........
示例12: __init__
def __init__(self, test_runner, search_strategy, test, settings, random):
self.test_runner = test_runner
self.search_strategy = search_strategy
self.settings = settings
self.at_least_one_success = False
self.last_exception = None
self.repr_for_last_exception = None
self.falsifying_examples = ()
self.__was_flaky = False
self.random = random
self.__warned_deadline = False
self.__existing_collector = None
self.__test_runtime = None
self.__in_final_replay = False
if self.settings.deadline is None:
self.test = test
else:
@proxies(test)
def timed_test(*args, **kwargs):
self.__test_runtime = None
start = time.time()
result = test(*args, **kwargs)
runtime = (time.time() - start) * 1000
self.__test_runtime = runtime
if self.settings.deadline is not_set:
if (
not self.__warned_deadline and
runtime >= 200
):
self.__warned_deadline = True
note_deprecation((
'Test took %.2fms to run. In future the default '
'deadline setting will be 200ms, which will '
'make this an error. You can set deadline to '
'an explicit value of e.g. %d to turn tests '
'slower than this into an error, or you can set '
'it to None to disable this check entirely.') % (
runtime, ceil(runtime / 100) * 100,
))
elif runtime >= self.current_deadline:
raise DeadlineExceeded(runtime, self.settings.deadline)
return result
self.test = timed_test
self.coverage_data = CoverageData()
self.files_to_propagate = set()
if settings.use_coverage and not IN_COVERAGE_TESTS: # pragma: no cover
if Collector._collectors:
self.hijack_collector(Collector._collectors[-1])
self.collector = Collector(
branch=True,
timid=FORCE_PURE_TRACER,
should_trace=self.should_trace,
check_include=hypothesis_check_include,
concurrency='thread',
warn=escalate_warning,
)
self.collector.reset()
# Hide the other collectors from this one so it doesn't attempt to
# pause them (we're doing trace function management ourselves so
# this will just cause problems).
self.collector._collectors = []
else:
self.collector = None
示例13: StateForActualGivenExecution
class StateForActualGivenExecution(object):
def __init__(self, test_runner, search_strategy, test, settings, random):
self.test_runner = test_runner
self.search_strategy = search_strategy
self.settings = settings
self.at_least_one_success = False
self.last_exception = None
self.repr_for_last_exception = None
self.falsifying_examples = ()
self.__was_flaky = False
self.random = random
self.__warned_deadline = False
self.__existing_collector = None
self.__test_runtime = None
self.__in_final_replay = False
if self.settings.deadline is None:
self.test = test
else:
@proxies(test)
def timed_test(*args, **kwargs):
self.__test_runtime = None
start = time.time()
result = test(*args, **kwargs)
runtime = (time.time() - start) * 1000
self.__test_runtime = runtime
if self.settings.deadline is not_set:
if (
not self.__warned_deadline and
runtime >= 200
):
self.__warned_deadline = True
note_deprecation((
'Test took %.2fms to run. In future the default '
'deadline setting will be 200ms, which will '
'make this an error. You can set deadline to '
'an explicit value of e.g. %d to turn tests '
'slower than this into an error, or you can set '
'it to None to disable this check entirely.') % (
runtime, ceil(runtime / 100) * 100,
))
elif runtime >= self.current_deadline:
raise DeadlineExceeded(runtime, self.settings.deadline)
return result
self.test = timed_test
self.coverage_data = CoverageData()
self.files_to_propagate = set()
if settings.use_coverage and not IN_COVERAGE_TESTS: # pragma: no cover
if Collector._collectors:
self.hijack_collector(Collector._collectors[-1])
self.collector = Collector(
branch=True,
timid=FORCE_PURE_TRACER,
should_trace=self.should_trace,
check_include=hypothesis_check_include,
concurrency='thread',
warn=escalate_warning,
)
self.collector.reset()
# Hide the other collectors from this one so it doesn't attempt to
# pause them (we're doing trace function management ourselves so
# this will just cause problems).
self.collector._collectors = []
else:
self.collector = None
@property
def current_deadline(self):
base = self.settings.deadline
if self.__in_final_replay:
return base
else:
return base * 1.25
def should_trace(self, original_filename, frame): # pragma: no cover
disp = FileDisposition()
assert original_filename is not None
disp.original_filename = original_filename
disp.canonical_filename = encoded_filepath(
canonical_filename(original_filename))
disp.source_filename = disp.canonical_filename
disp.reason = ''
disp.file_tracer = None
disp.has_dynamic_filename = False
disp.trace = hypothesis_check_include(disp.canonical_filename)
if not disp.trace:
disp.reason = 'hypothesis internal reasons'
elif self.__existing_collector is not None:
check = self.__existing_collector.should_trace(
original_filename, frame)
if check.trace:
self.files_to_propagate.add(check.canonical_filename)
return disp
def hijack_collector(self, collector): # pragma: no cover
#.........这里部分代码省略.........
示例14: Coverage
#.........这里部分代码省略.........
self._post_init()
if not should_skip:
self._data.read()
def _init_for_start(self):
"""Initialization for start()"""
# Construct the collector.
concurrency = self.config.concurrency or []
if "multiprocessing" in concurrency:
if not patch_multiprocessing:
raise CoverageException( # pragma: only jython
"multiprocessing is not supported on this Python"
)
patch_multiprocessing(rcfile=self.config.config_file)
# Multi-processing uses parallel for the subprocesses, so also use
# it for the main process.
self.config.parallel = True
if self.config.dynamic_context is None:
context_switchers = []
elif self.config.dynamic_context == "test_function":
context_switchers = [should_start_context_test_function]
else:
raise CoverageException(
"Don't understand dynamic_context setting: {!r}".format(self.config.dynamic_context)
)
context_switchers.extend(
plugin.dynamic_context for plugin in self._plugins.context_switchers
)
should_start_context = combine_context_switchers(context_switchers)
self._collector = Collector(
should_trace=self._should_trace,
check_include=self._check_include_omit_etc,
should_start_context=should_start_context,
timid=self.config.timid,
branch=self.config.branch,
warn=self._warn,
concurrency=concurrency,
)
suffix = self._data_suffix_specified
if suffix or self.config.parallel:
if not isinstance(suffix, string_class):
# if data_suffix=True, use .machinename.pid.random
suffix = True
else:
suffix = None
self._init_data(suffix)
self._collector.use_data(self._data, self.config.context)
# Early warning if we aren't going to be able to support plugins.
if self._plugins.file_tracers and not self._collector.supports_plugins:
self._warn(
"Plugin file tracers (%s) aren't supported with %s" % (
", ".join(
plugin._coverage_plugin_name
for plugin in self._plugins.file_tracers
),
self._collector.tracer_name(),
)
)
示例15: _init_for_start
def _init_for_start(self):
"""Initialization for start()"""
# Construct the collector.
concurrency = self.config.concurrency or []
if "multiprocessing" in concurrency:
if not patch_multiprocessing:
raise CoverageException( # pragma: only jython
"multiprocessing is not supported on this Python"
)
patch_multiprocessing(rcfile=self.config.config_file)
# Multi-processing uses parallel for the subprocesses, so also use
# it for the main process.
self.config.parallel = True
if self.config.dynamic_context is None:
context_switchers = []
elif self.config.dynamic_context == "test_function":
context_switchers = [should_start_context_test_function]
else:
raise CoverageException(
"Don't understand dynamic_context setting: {!r}".format(self.config.dynamic_context)
)
context_switchers.extend(
plugin.dynamic_context for plugin in self._plugins.context_switchers
)
should_start_context = combine_context_switchers(context_switchers)
self._collector = Collector(
should_trace=self._should_trace,
check_include=self._check_include_omit_etc,
should_start_context=should_start_context,
timid=self.config.timid,
branch=self.config.branch,
warn=self._warn,
concurrency=concurrency,
)
suffix = self._data_suffix_specified
if suffix or self.config.parallel:
if not isinstance(suffix, string_class):
# if data_suffix=True, use .machinename.pid.random
suffix = True
else:
suffix = None
self._init_data(suffix)
self._collector.use_data(self._data, self.config.context)
# Early warning if we aren't going to be able to support plugins.
if self._plugins.file_tracers and not self._collector.supports_plugins:
self._warn(
"Plugin file tracers (%s) aren't supported with %s" % (
", ".join(
plugin._coverage_plugin_name
for plugin in self._plugins.file_tracers
),
self._collector.tracer_name(),
)
)
for plugin in self._plugins.file_tracers:
plugin._coverage_enabled = False
# Create the file classifying substructure.
self._inorout = self._inorout_class(warn=self._warn)
self._inorout.configure(self.config)
self._inorout.plugins = self._plugins
self._inorout.disp_class = self._collector.file_disposition_class
atexit.register(self._atexit)