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_filereporter():
from covimerage.coveragepy import FileReporter
f = FileReporter('/doesnotexist')
assert repr(f) == ""
with pytest.raises(coverage.misc.NoSource) as excinfo:
f.lines()
assert excinfo.value.args == (
"[Errno 2] No such file or directory: '/doesnotexist'",)
def test_directory_without_main(self):
self.make_file("without_main/__init__.py", "")
with self.assertRaisesRegex(NoSource, "Can't find '__main__' module in 'without_main'"):
run_python_file(["without_main"])
def make_code_from_py(filename):
"""Get source from `filename` and make a code object of it."""
# Open the source file.
try:
source = get_python_source(filename)
except (IOError, NoSource):
raise NoSource("No file to run: '%s'" % filename)
code = compile_unicode(source, filename, "exec")
return code
`config` is a CoverageConfig instance.
"""
self.find_code_units(morfs, config)
if not self.code_units:
raise CoverageException("No data to report.")
self.directory = directory
if self.directory and not os.path.exists(self.directory):
os.makedirs(self.directory)
for cu in self.code_units:
try:
report_fn(cu, self.coverage._analyze(cu))
except (NoSource, NotPython):
if not self.ignore_errors:
raise
def find_module(modulename):
"""Find the module named `modulename`.
Returns the file path of the module, the name of the enclosing
package, and the spec.
"""
try:
spec = importlib_util_find_spec(modulename)
except ImportError as err:
raise NoSource(str(err))
if not spec:
raise NoSource("No module named %r" % (modulename,))
pathname = spec.origin
packagename = spec.name
if spec.submodule_search_locations:
mod_main = modulename + ".__main__"
spec = importlib_util_find_spec(mod_main)
if not spec:
raise NoSource(
"No module named %s; "
"%r is a package and cannot be directly executed"
% (mod_main, modulename)
)
pathname = spec.origin
packagename = spec.name
packagename = packagename.rpartition(".")[0]
return pathname, packagename, spec
else:
for ext in exts:
try_filename = base + ext
if os.path.exists(try_filename):
# A regular text file: open it.
source = read_python_source(try_filename)
break
# Maybe it's in a zip file?
source = get_zip_bytes(try_filename)
if source is not None:
break
else:
# Couldn't find source.
exc_msg = "No source for code: '%s'.\n" % (filename,)
exc_msg += "Aborting report output, consider using -i."
raise NoSource(exc_msg)
# Replace \f because of http://bugs.python.org/issue19035
source = source.replace(b'\f', b' ')
source = source.decode(source_encoding(source), "replace")
# Python code should always end with a line with a newline.
if source and source[-1] != '\n':
source += '\n'
return source
# Complain if this is a magic non-file module.
if openfile is None and pathname is None:
raise NoSource(
"module does not live in a file: %r" % modulename
)
# If `modulename` is actually a package, not a mere module, then we
# pretend to be Python 2.7 and try running its __main__.py script.
if openfile is None:
packagename = modulename
name = '__main__'
package = __import__(packagename, glo, loc, ['__path__'])
searchpath = package.__path__
openfile, pathname, _ = imp.find_module(name, searchpath)
except ImportError as err:
raise NoSource(str(err))
finally:
if openfile:
openfile.close()
return pathname, packagename, None
def __init__(self, cov, code_unit):
self.coverage = cov
self.code_unit = code_unit
self.filename = self.code_unit.filename
ext = os.path.splitext(self.filename)[1]
source = None
if ext == '.py':
if not os.path.exists(self.filename):
source = self.coverage.file_locator.get_zip_data(self.filename)
if not source:
raise NoSource("No source for code: %r" % self.filename)
self.parser = CodeParser(
text=source, filename=self.filename,
exclude=self.coverage._exclude_regex('exclude')
)
self.statements, self.excluded = self.parser.parse_source()
# Identify missing statements.
executed = self.coverage.data.executed_lines(self.filename)
exec1 = self.parser.first_lines(executed)
self.missing = sorted(set(self.statements) - set(exec1))
if self.coverage.data.has_arcs():
self.no_branch = self.parser.lines_matching(
join_regex(self.coverage.config.partial_list),
join_regex(self.coverage.config.partial_always_list)
"Remove --{} from the command line.".format(opt_name)
)
return ERR
runner = PyRunner(args, as_module=bool(options.module))
runner.prepare()
if options.append:
self.coverage.load()
# Run the script.
self.coverage.start()
code_ran = True
try:
runner.run()
except NoSource:
code_ran = False
raise
finally:
self.coverage.stop()
if code_ran:
self.coverage.save()
return OK