Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def covered_main(includes, require_native=None, required_percentage=100.0):
"""Equivalent of unittest.main(), except that it gathers coverage data, and
asserts if the test is not at 100% coverage.
Args:
includes (list(str) or str) - List of paths to include in coverage report.
May also be a single path instead of a list.
require_native (str) - If non-None, will require that
at least |require_native| version of coverage is installed on the
system with CTracer.
"""
try:
import coverage
if require_native is not None:
got_ver = coverage.__version__
if not getattr(coverage.collector, 'CTracer', None):
native_error((
"Native python-coverage module required.\n"
"Pure-python implementation (version: %s) found: %s"
) % (got_ver, coverage), require_native)
if got_ver < distutils.version.LooseVersion(require_native):
native_error("Wrong version (%s) found: %s" % (got_ver, coverage),
require_native)
except ImportError:
if require_native is None:
sys.path.insert(0, os.path.join(ROOT_PATH, 'third_party'))
import coverage
else:
print ("ERROR: python-coverage (%s) is required to be installed on your "
"PYTHONPATH to run this test." % require_native)
sys.exit(1)
def _validate_options(self):
if (self.options.coverage_xml or self.options.coverage_html) and \
not self.options.coverage:
self.options.coverage = True
if self.options.coverage is True and COVERAGE_AVAILABLE is False:
self.error(
'Cannot run tests with coverage report. '
'Please install coverage>=3.5.3'
)
if self.options.coverage is True:
coverage_version = tuple([
int(part) for part in re.search(
r'([0-9.]+)', coverage.__version__).group(0).split('.')
])
if coverage_version < (3, 5, 3):
# Should we just print the error instead of exiting?
self.error(
'Versions lower than 3.5.3 of the coverage library are '
'know to produce incorrect results. Please consider '
'upgrading...'
)
SaltTestingParser._validate_options(self)
def test_html_delta_from_coverage_version_change(self):
# HTML generation can create only the files that have changed.
# In this case, everything changes because the coverage.py version has
# changed.
self.create_initial_files()
self.run_coverage()
index1 = self.get_html_index_content()
# "Upgrade" coverage.py!
coverage.__version__ = "XYZZY"
self.run_coverage()
# All the files have been reported again.
self.assert_htmlcov_files_exist()
assert "htmlcov/index.html" in self.files_written
assert "htmlcov/helper1_py.html" in self.files_written
assert "htmlcov/helper2_py.html" in self.files_written
assert "htmlcov/main_file_py.html" in self.files_written
index2 = self.get_html_index_content()
fixed_index2 = index2.replace("XYZZY", self.real_coverage_version)
self.assertMultiLineEqual(index1, fixed_index2)
if options.bisect_repo and not options.known_good_rev:
parser.error("--bisect-repo cannot be used without --known-good-rev")
global useipv6
if options.ipv6:
useipv6 = checksocketfamily("AF_INET6")
else:
# only use IPv6 if IPv4 is unavailable and IPv6 is available
useipv6 = (not checksocketfamily("AF_INET")) and checksocketfamily("AF_INET6")
options.anycoverage = options.cover or options.annotate or options.htmlcov
if options.anycoverage:
try:
import coverage
covver = version.StrictVersion(coverage.__version__).version
if covver < (3, 3):
parser.error("coverage options require coverage 3.3 or later")
except ImportError:
parser.error("coverage options now require the coverage package")
if options.anycoverage and options.local:
# this needs some path mangling somewhere, I guess
parser.error("sorry, coverage options do not work when --local is specified")
if options.anycoverage and options.with_hg:
parser.error("sorry, coverage options do not work when --with-hg is specified")
global verbose
if options.verbose:
verbose = ""
def test_metadata(self):
status, output = self.run_command_status(
"python setup.py --description --version --url --author"
)
self.assertEqual(status, 0)
out = output.splitlines()
self.assertIn("measurement", out[0])
self.assertEqual(coverage.__version__, out[1])
self.assertIn("github.com/nedbat/coveragepy", out[2])
self.assertIn("Ned Batchelder", out[3])
self._init()
self._post_init()
def plugin_info(plugins):
"""Make an entry for the sys_info from a list of plug-ins."""
entries = []
for plugin in plugins:
entry = plugin._coverage_plugin_name
if not plugin._coverage_enabled:
entry += " (disabled)"
entries.append(entry)
return entries
info = [
('version', covmod.__version__),
('coverage', covmod.__file__),
('tracer', self._collector.tracer_name() if self._collector else "-none-"),
('CTracer', 'available' if CTracer else "unavailable"),
('plugins.file_tracers', plugin_info(self._plugins.file_tracers)),
('plugins.configurers', plugin_info(self._plugins.configurers)),
('plugins.context_switchers', plugin_info(self._plugins.context_switchers)),
('configs_attempted', self.config.attempted_config_files),
('configs_read', self.config.config_files_read),
('config_file', self.config.config_file),
('config_contents',
repr(self.config._config_contents)
if self.config._config_contents
else '-none-'
),
('data_file', self._data.data_filename() if self._data is not None else "-none-"),
('python', sys.version.replace('\n', '')),
os.environ['COVERAGE_FILE'] = sys.argv[1]
del sys.argv[1]
try:
import coverage #@UnresolvedImport
except:
sys.stderr.write('Error: coverage module could not be imported\n')
sys.stderr.write('Please make sure that the coverage module '
'(http://nedbatchelder.com/code/coverage/)\n')
sys.stderr.write('is properly installed in your interpreter: %s\n' % (sys.executable,))
import traceback;traceback.print_exc()
return
if hasattr(coverage, '__version__'):
version = tuple(map(int, coverage.__version__.split('.')[:2]))
if version < (4, 3):
sys.stderr.write('Error: minimum supported coverage version is 4.3.'
'\nFound: %s\nLocation: %s\n'
% ('.'.join(str(x) for x in version), coverage.__file__))
sys.exit(1)
else:
sys.stderr.write('Warning: Could not determine version of python module coverage.'
'\nEnsure coverage version is >= 4.3\n')
from coverage.cmdline import main #@UnresolvedImport
if files is not None:
sys.argv.append('xml')
sys.argv += files
main()
worker_type=hl(klass.WORKER_TYPE),
worker_id=hlid(options.worker),
node_id=hlid(options.node),
realm=hlid(options.realm),
personality=hl(Personality.NAME),
worker_class=hltype(klass),
)
log.info(
'Running as PID {pid} on {python}-{reactor}',
pid=os.getpid(),
python=platform.python_implementation(),
reactor=qual(reactor.__class__).split('.')[-1],
)
if MEASURING_COVERAGE:
log.info(hl('Code coverage measurements enabled (coverage={coverage_version}).', color='green', bold=True),
coverage_version=coverage.__version__)
# set process title if requested to
#
try:
import setproctitle
except ImportError:
log.debug("Could not set worker process title (setproctitle not installed)")
else:
if options.title:
setproctitle.setproctitle(options.title)
else:
setproctitle.setproctitle('crossbar-worker [{}]'.format(options.klass))
# node directory
#
options.cbdir = os.path.abspath(options.cbdir)
def report(self, morfs, outfile=None):
"""Generate a json report for `morfs`.
`morfs` is a list of modules or file names.
`outfile` is a file object to write the json to
"""
outfile = outfile or sys.stdout
coverage_data = self.coverage.get_data()
coverage_data.set_query_contexts(self.config.report_contexts)
self.report_data["meta"] = {
"version": __version__,
"timestamp": datetime.datetime.now().isoformat(),
"branch_coverage": coverage_data.has_arcs(),
"show_contexts": self.config.json_show_contexts,
}
measured_files = {}
for file_reporter, analysis in get_analysis_to_report(self.coverage, morfs):
measured_files[file_reporter.relative_filename()] = self.report_one_file(
coverage_data,
analysis
)
self.report_data["files"] = measured_files
self.report_data["totals"] = {
'covered_lines': self.total.n_executed,
"""
# Initial setup.
outfile = outfile or sys.stdout
# Create the DOM that will store the data.
impl = xml.dom.minidom.getDOMImplementation()
docType = impl.createDocumentType(
"coverage", None,
"http://cobertura.sourceforge.net/xml/coverage-03.dtd"
)
self.xml_out = impl.createDocument(None, "coverage", docType)
# Write header stuff.
xcoverage = self.xml_out.documentElement
xcoverage.setAttribute("version", __version__)
xcoverage.setAttribute("timestamp", str(int(time.time()*1000)))
xcoverage.appendChild(self.xml_out.createComment(
" Generated by coverage.py: %s " % __url__
))
xpackages = self.xml_out.createElement("packages")
xcoverage.appendChild(xpackages)
# Call xml_file for each file in the data.
self.packages = {}
self.report_files(self.xml_file, morfs, config)
lnum_tot, lhits_tot = 0, 0
bnum_tot, bhits_tot = 0, 0
# Populate the XML DOM with the package info.
for pkg_name in sorted(self.packages.keys()):