本文整理汇总了Python中coverage.files.FileLocator类的典型用法代码示例。如果您正苦于以下问题:Python FileLocator类的具体用法?Python FileLocator怎么用?Python FileLocator使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了FileLocator类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_simple
def test_simple(self):
self.make_file("hello.py")
fl = FileLocator()
self.assertEqual(fl.relative_filename("hello.py"), "hello.py")
a = self.abs_path("hello.py")
self.assertNotEqual(a, "hello.py")
self.assertEqual(fl.relative_filename(a), "hello.py")
示例2: test_peer_directories
def test_peer_directories(self):
self.make_file("sub/proj1/file1.py")
self.make_file("sub/proj2/file2.py")
a1 = self.abs_path("sub/proj1/file1.py")
a2 = self.abs_path("sub/proj2/file2.py")
d = os.path.normpath("sub/proj1")
os.chdir(d)
fl = FileLocator()
self.assertEqual(fl.relative_filename(a1), "file1.py")
self.assertEqual(fl.relative_filename(a2), a2)
示例3: test_filepath_contains_absolute_prefix_twice
def test_filepath_contains_absolute_prefix_twice(self):
# https://bitbucket.org/ned/coveragepy/issue/194
# Build a path that has two pieces matching the absolute path prefix.
# Technically, this test doesn't do that on Windows, but drive
# letters make that impractical to achieve.
fl = FileLocator()
d = abs_file(os.curdir)
trick = os.path.splitdrive(d)[1].lstrip(os.path.sep)
rel = os.path.join('sub', trick, 'file1.py')
self.assertEqual(fl.relative_filename(abs_file(rel)), rel)
示例4: test_fnmatch_matcher
def test_fnmatch_matcher(self):
file1 = self.make_file("sub/file1.py")
file2 = self.make_file("sub/file2.c")
file3 = self.make_file("sub2/file3.h")
file4 = self.make_file("sub3/file4.py")
file5 = self.make_file("sub3/file5.c")
fl = FileLocator()
fnm = FnmatchMatcher(["*.py", "*/sub2/*"])
self.assertTrue(fnm.match(fl.canonical_filename(file1)))
self.assertFalse(fnm.match(fl.canonical_filename(file2)))
self.assertTrue(fnm.match(fl.canonical_filename(file3)))
self.assertTrue(fnm.match(fl.canonical_filename(file4)))
self.assertFalse(fnm.match(fl.canonical_filename(file5)))
示例5: MatcherTest
class MatcherTest(CoverageTest):
"""Tests of file matchers."""
def setUp(self):
super(MatcherTest, self).setUp()
self.fl = FileLocator()
def assertMatches(self, matcher, filepath, matches):
"""The `matcher` should agree with `matches` about `filepath`."""
canonical = self.fl.canonical_filename(filepath)
self.assertEqual(
matcher.match(canonical), matches,
"File %s should have matched as %s" % (filepath, matches)
)
def test_tree_matcher(self):
matches_to_try = [
(self.make_file("sub/file1.py"), True),
(self.make_file("sub/file2.c"), True),
(self.make_file("sub2/file3.h"), False),
(self.make_file("sub3/file4.py"), True),
(self.make_file("sub3/file5.c"), False),
]
fl = FileLocator()
trees = [
fl.canonical_filename("sub"),
fl.canonical_filename("sub3/file4.py"),
]
tm = TreeMatcher(trees)
self.assertEqual(tm.info(), trees)
for filepath, matches in matches_to_try:
self.assertMatches(tm, filepath, matches)
def test_fnmatch_matcher(self):
matches_to_try = [
(self.make_file("sub/file1.py"), True),
(self.make_file("sub/file2.c"), False),
(self.make_file("sub2/file3.h"), True),
(self.make_file("sub3/file4.py"), True),
(self.make_file("sub3/file5.c"), False),
]
fnm = FnmatchMatcher(["*.py", "*/sub2/*"])
self.assertEqual(fnm.info(), ["*.py", "*/sub2/*"])
for filepath, matches in matches_to_try:
self.assertMatches(fnm, filepath, matches)
def test_fnmatch_matcher_overload(self):
fnm = FnmatchMatcher(["*x%03d*.txt" % i for i in range(500)])
self.assertMatches(fnm, "x007foo.txt", True)
self.assertMatches(fnm, "x123foo.txt", True)
self.assertMatches(fnm, "x798bar.txt", False)
def test_fnmatch_windows_paths(self):
# We should be able to match Windows paths even if we are running on
# a non-Windows OS.
fnm = FnmatchMatcher(["*/foo.py"])
self.assertMatches(fnm, r"dir\foo.py", True)
fnm = FnmatchMatcher([r"*\foo.py"])
self.assertMatches(fnm, r"dir\foo.py", True)
示例6: test_tree_matcher
def test_tree_matcher(self):
matches_to_try = [
(self.make_file("sub/file1.py"), True),
(self.make_file("sub/file2.c"), True),
(self.make_file("sub2/file3.h"), False),
(self.make_file("sub3/file4.py"), True),
(self.make_file("sub3/file5.c"), False),
]
fl = FileLocator()
trees = [
fl.canonical_filename("sub"),
fl.canonical_filename("sub3/file4.py"),
]
tm = TreeMatcher(trees)
self.assertEqual(tm.info(), trees)
for filepath, matches in matches_to_try:
self.assertMatches(tm, filepath, matches)
示例7: MatcherTest
class MatcherTest(CoverageTest):
"""Tests of file matchers."""
def setUp(self):
super(MatcherTest, self).setUp()
self.fl = FileLocator()
def assertMatches(self, matcher, filepath, matches):
"""The `matcher` should agree with `matches` about `filepath`."""
canonical = self.fl.canonical_filename(filepath)
self.assertEqual(
matcher.match(canonical), matches,
"File %s should have matched as %s" % (filepath, matches)
)
def test_tree_matcher(self):
matches_to_try = [
(self.make_file("sub/file1.py"), True),
(self.make_file("sub/file2.c"), True),
(self.make_file("sub2/file3.h"), False),
(self.make_file("sub3/file4.py"), True),
(self.make_file("sub3/file5.c"), False),
]
fl = FileLocator()
trees = [
fl.canonical_filename("sub"),
fl.canonical_filename("sub3/file4.py"),
]
tm = TreeMatcher(trees)
self.assertEqual(tm.info(), trees)
for filepath, matches in matches_to_try:
self.assertMatches(tm, filepath, matches)
def test_fnmatch_matcher(self):
matches_to_try = [
(self.make_file("sub/file1.py"), True),
(self.make_file("sub/file2.c"), False),
(self.make_file("sub2/file3.h"), True),
(self.make_file("sub3/file4.py"), True),
(self.make_file("sub3/file5.c"), False),
]
fnm = FnmatchMatcher(["*.py", "*/sub2/*"])
self.assertEqual(fnm.info(), ["*.py", "*/sub2/*"])
for filepath, matches in matches_to_try:
self.assertMatches(fnm, filepath, matches)
示例8: test_tree_matcher
def test_tree_matcher(self):
file1 = self.make_file("sub/file1.py")
file2 = self.make_file("sub/file2.c")
file3 = self.make_file("sub2/file3.h")
file4 = self.make_file("sub3/file4.py")
file5 = self.make_file("sub3/file5.c")
fl = FileLocator()
tm = TreeMatcher([
fl.canonical_filename("sub"),
fl.canonical_filename(file4),
])
self.assertTrue(tm.match(fl.canonical_filename(file1)))
self.assertTrue(tm.match(fl.canonical_filename(file2)))
self.assertFalse(tm.match(fl.canonical_filename(file3)))
self.assertTrue(tm.match(fl.canonical_filename(file4)))
self.assertFalse(tm.match(fl.canonical_filename(file5)))
示例9: Coverage
#.........这里部分代码省略.........
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:
return
# 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_tracing_plugins = []
for plugin in self.plugins:
if overrides(plugin, "file_tracer", CoveragePlugin):
self.file_tracing_plugins.append(plugin)
# _exclude_re is a dict that maps 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)
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.file_tracing_plugins and not self.collector.supports_plugins:
self._warn(
"Plugin file tracers (%s) aren't supported with %s" % (
", ".join(
示例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: _init
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:
return
# 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_tracing_plugins = []
for plugin in self.plugins:
if overrides(plugin, "file_tracer", CoveragePlugin):
self.file_tracing_plugins.append(plugin)
# _exclude_re is a dict that maps 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)
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.file_tracing_plugins 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.file_tracing_plugins
),
self.collector.tracer_name(),
)
)
for plugin in self.file_tracing_plugins:
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(
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
#.........这里部分代码省略.........
示例12: 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):
#.........这里部分代码省略.........
示例13: setUp
def setUp(self):
super(MatcherTest, self).setUp()
self.fl = FileLocator()
示例14: __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)
示例15: 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=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()
#.........这里部分代码省略.........