Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_unreadable_config(self):
# If a config file is explicitly specified, then it is an error for it
# to not be readable.
bad_files = [
"nosuchfile.txt",
".",
]
for bad_file in bad_files:
msg = "Couldn't read %r as a config file" % bad_file
with self.assertRaisesRegex(CoverageException, msg):
coverage.Coverage(config_file=bad_file)
def test_read_sql_errors(self):
with sqlite3.connect("wrong_schema.db") as con:
con.execute("create table coverage_schema (version integer)")
con.execute("insert into coverage_schema (version) values (99)")
msg = r"Couldn't .* '.*[/\\]{}': wrong schema: 99 instead of \d+".format("wrong_schema.db")
with self.assertRaisesRegex(CoverageException, msg):
covdata = CoverageData("wrong_schema.db")
covdata.read()
self.assertFalse(covdata)
with sqlite3.connect("no_schema.db") as con:
con.execute("create table foobar (baz text)")
msg = r"Couldn't .* '.*[/\\]{}': \S+".format("no_schema.db")
with self.assertRaisesRegex(CoverageException, msg):
covdata = CoverageData("no_schema.db")
covdata.read()
self.assertFalse(covdata)
This is installed as the script entrypoint.
"""
if argv is None:
argv = sys.argv[1:]
try:
status = CoverageScript(_covpkg=dtcov.dt_coverage, _help_fn=help).command_line(argv)
except ExceptionDuringRun:
# An exception was caught while running the product code. The
# sys.exc_info() return tuple is packed into an ExceptionDuringRun
# exception.
_, err, _ = sys.exc_info()
traceback.print_exception(*err.args)
status = 1
except CoverageException:
# A controlled error inside coverage.py: print the message to the user.
_, err, _ = sys.exc_info()
print(err)
status = 1
except SystemExit:
# The user called `sys.exit()`. Exit with their argument, if any.
_, err, _ = sys.exc_info()
if err.args:
status = err.args[0]
else:
status = None
return status
def touch_file(self, filename, plugin_name=""):
"""Ensure that `filename` appears in the data, empty if needed.
`plugin_name` is the name of the plugin responsible for this file. It is used
to associate the right filereporter, etc.
"""
if self._debug.should('dataop'):
self._debug.write("Touching %r" % (filename,))
self._start_using()
if not self._has_arcs and not self._has_lines:
raise CoverageException("Can't touch files in an empty CoverageData")
self._file_id(filename, add=True)
if plugin_name:
# Set the tracer for this file
self.add_file_tracers({filename: plugin_name})
def __nonzero__(self):
if (get_thread_id() not in self._dbs and not os.path.exists(self._filename)):
return False
try:
with self._connect() as con:
rows = con.execute("select * from file limit 1")
return bool(list(rows))
except CoverageException:
return False
class CoverageException(BaseCoverageException):
"""An exception raised by a coverage.py function."""
pass
class NoSource(CoverageException):
"""We couldn't find the source for a module."""
pass
class NoCode(NoSource):
"""We couldn't find any code at all."""
pass
class NotPython(CoverageException):
"""A source file turned out not to be parsable Python."""
pass
class ExceptionDuringRun(CoverageException):
"""An exception happened while running customer code.
Construct it with three arguments, the values from `sys.exc_info`.
"""
pass
class StopEverything(BaseCoverageException):
"""An exception that means everything should stop.
except Exception:
report_it = not self.config.ignore_errors
if report_it:
typ, msg = sys.exc_info()[:2]
# NotPython is only raised by PythonFileReporter, which has a
# should_be_python() method.
if typ is NotPython and not fr.should_be_python():
report_it = False
if report_it:
self.writeout(self.fmt_err % (fr.relative_filename(), typ.__name__, msg))
# Sort the lines and write them out.
if getattr(self.config, 'sort', None):
position = column_order.get(self.config.sort.lower())
if position is None:
raise CoverageException("Invalid sorting option: {!r}".format(self.config.sort))
lines.sort(key=lambda l: (l[1][position], l[0]))
for line in lines:
self.writeout(line[0])
# Write a TOTAl line if we had more than one file.
if self.total.n_files > 1:
self.writeout(rule)
args = ("TOTAL", self.total.n_statements, self.total.n_missing)
if self.branches:
args += (self.total.n_branches, self.total.n_partial_branches)
args += (self.total.pc_covered_str,)
if self.config.show_missing:
args += ("",)
self.writeout(fmt_coverage % args)
"""Generate an HTML report for `morfs`.
`morfs` is a list of modules or file names.
"""
# Read the status data and check that this run used the same
# global data as the last run.
self.incr.read()
self.incr.check_global_data(self.config, self.pyfile_html_source)
# Process all the files.
for fr, analysis in get_analysis_to_report(self.coverage, morfs):
self.html_file(fr, analysis)
if not self.all_files_nums:
raise CoverageException("No data to report.")
self.totals = sum(self.all_files_nums)
# Write the index file.
self.index_file()
self.make_local_static_report_files()
return self.totals.n_statements and self.totals.pc_covered
def dollar_replace(match):
"""Called for each $replacement."""
# Only one of the groups will have matched, just get its text.
word = next(g for g in match.group('dollar', 'word1', 'word2') if g)
if word == "$":
return "$"
elif word in variables:
return variables[word]
elif match.group('strict'):
msg = "Variable {} is undefined: {!r}".format(word, text)
raise CoverageException(msg)
else:
return match.group('defval')
def _get_file_reporter(self, morf):
"""Get a FileReporter for a module or file name."""
plugin = None
file_reporter = "python"
if isinstance(morf, string_class):
mapped_morf = self._file_mapper(morf)
plugin_name = self._data.file_tracer(mapped_morf)
if plugin_name:
plugin = self._plugins.get(plugin_name)
if plugin:
file_reporter = plugin.file_reporter(mapped_morf)
if file_reporter is None:
raise CoverageException(
"Plugin %r did not provide a file reporter for %r." % (
plugin._coverage_plugin_name, morf
)
)
if file_reporter == "python":
file_reporter = PythonFileReporter(morf, self)
return file_reporter