本文整理汇总了Python中coverage.results.Numbers类的典型用法代码示例。如果您正苦于以下问题:Python Numbers类的具体用法?Python Numbers怎么用?Python Numbers使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Numbers类的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_pc_covered_str
def test_pc_covered_str(self):
# Numbers._precision is a global, which is bad.
Numbers.set_precision(0)
n0 = Numbers(n_files=1, n_statements=1000, n_missing=0)
n1 = Numbers(n_files=1, n_statements=1000, n_missing=1)
n999 = Numbers(n_files=1, n_statements=1000, n_missing=999)
n1000 = Numbers(n_files=1, n_statements=1000, n_missing=1000)
self.assertEqual(n0.pc_covered_str, "100")
self.assertEqual(n1.pc_covered_str, "99")
self.assertEqual(n999.pc_covered_str, "1")
self.assertEqual(n1000.pc_covered_str, "0")
示例2: test_pc_covered_str_precision
def test_pc_covered_str_precision(self):
assert Numbers._precision == 0
Numbers.set_precision(1)
n0 = Numbers(n_files=1, n_statements=10000, n_missing=0)
n1 = Numbers(n_files=1, n_statements=10000, n_missing=1)
n9999 = Numbers(n_files=1, n_statements=10000, n_missing=9999)
n10000 = Numbers(n_files=1, n_statements=10000, n_missing=10000)
self.assertEqual(n0.pc_covered_str, "100.0")
self.assertEqual(n1.pc_covered_str, "99.9")
self.assertEqual(n9999.pc_covered_str, "0.1")
self.assertEqual(n10000.pc_covered_str, "0.0")
Numbers.set_precision(0)
示例3: _analyze
def _analyze(self, it):
"""Analyze a single morf or code unit.
Returns an `Analysis` object.
"""
# All reporting comes through here, so do reporting initialization.
self._init()
Numbers.set_precision(self.config.precision)
self._post_init()
data = self.get_data()
if not isinstance(it, FileReporter):
it = self._get_file_reporter(it)
return Analysis(data, it)
示例4: header
def header(self):
header = (self.fmt_name % "Name") + " Stmts Miss"
if self.branches:
header += " Branch BrMiss"
width100 = Numbers.pc_str_width()
header += "%*s" % (width100 + 4, "Cover")
header += "\n"
return header
示例5: report
def report(self, morfs, outfile = None):
self.find_code_units(morfs)
max_name = max([ len(cu.name) for cu in self.code_units ] + [5])
fmt_name = '%%- %ds ' % max_name
fmt_err = '%s %s: %s\n'
header = fmt_name % 'Name' + ' Stmts Miss'
fmt_coverage = fmt_name + '%6d %6d'
if self.branches:
header += ' Branch BrMiss'
fmt_coverage += ' %6d %6d'
width100 = Numbers.pc_str_width()
header += '%*s' % (width100 + 4, 'Cover')
fmt_coverage += '%%%ds%%%%' % (width100 + 3,)
if self.config.show_missing:
header += ' Missing'
fmt_coverage += ' %s'
rule = '-' * len(header) + '\n'
header += '\n'
fmt_coverage += '\n'
if not outfile:
outfile = sys.stdout
outfile.write(header)
outfile.write(rule)
total = Numbers()
for cu in self.code_units:
try:
analysis = self.coverage._analyze(cu)
nums = analysis.numbers
args = (cu.name, nums.n_statements, nums.n_missing)
if self.branches:
args += (nums.n_branches, nums.n_missing_branches)
args += (nums.pc_covered_str,)
if self.config.show_missing:
args += (analysis.missing_formatted(),)
outfile.write(fmt_coverage % args)
total += nums
except KeyboardInterrupt:
raise
except:
report_it = not self.config.ignore_errors
if report_it:
typ, msg = sys.exc_info()[:2]
if typ is NotPython and not cu.should_be_python():
report_it = False
if report_it:
outfile.write(fmt_err % (cu.name, typ.__name__, msg))
if total.n_files > 1:
outfile.write(rule)
args = ('TOTAL', total.n_statements, total.n_missing)
if self.branches:
args += (total.n_branches, total.n_missing_branches)
args += (total.pc_covered_str,)
if self.config.show_missing:
args += ('',)
outfile.write(fmt_coverage % args)
return total.pc_covered
示例6: fmt_coverage
def fmt_coverage(self, perc):
fmt_coverage = self.fmt_name + "%6d %6d"
if self.branches:
fmt_coverage += " %6d %6d"
width100 = Numbers.pc_str_width()
color = green
if perc < 80:
color = blue
if perc < 50:
color = red
fmt_coverage += color("%%%ds%%%%" % (width100 + 3,))
if self.config.show_missing:
fmt_coverage += " %s"
fmt_coverage += "\n"
return fmt_coverage
示例7: _init
#.........这里部分代码省略.........
", ".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):
if m is not None and hasattr(m, "__file__"):
self.pylib_dirs.add(self._canonical_dir(m))
if _structseq and not hasattr(_structseq, '__file__'):
# PyPy 2.4 has no __file__ in the builtin modules, but the code
# objects still have the file names. So dig into one to find
# the path to exclude.
structseq_new = _structseq.structseq_new
try:
structseq_file = structseq_new.func_code.co_filename
except AttributeError:
structseq_file = structseq_new.__code__.co_filename
self.pylib_dirs.add(self._canonical_dir(structseq_file))
# To avoid tracing the coverage.py code itself, we skip anything
# located where we are.
self.cover_dirs = [self._canonical_dir(__file__)]
if env.TESTING:
# When testing, we use PyContracts, which should be considered
# part of coverage.py, and it uses six. Exclude those directories
# just as we exclude ourselves.
import contracts, six
for mod in [contracts, six]:
self.cover_dirs.append(self._canonical_dir(mod))
# Set the reporting precision.
Numbers.set_precision(self.config.precision)
atexit.register(self._atexit)
self._inited = True
# Create the matchers we need for _should_trace
if self.source or self.source_pkgs:
self.source_match = TreeMatcher(self.source)
self.source_pkgs_match = ModuleMatcher(self.source_pkgs)
else:
if self.cover_dirs:
self.cover_match = TreeMatcher(self.cover_dirs)
if self.pylib_dirs:
self.pylib_match = TreeMatcher(self.pylib_dirs)
if self.include:
self.include_match = FnmatchMatcher(self.include)
if self.omit:
self.omit_match = FnmatchMatcher(self.omit)
# The user may want to debug things, show info if desired.
wrote_any = False
if self.debug.should('config'):
config_info = sorted(self.config.__dict__.items())
self.debug.write_formatted_info("config", config_info)
wrote_any = True
if self.debug.should('sys'):
self.debug.write_formatted_info("sys", self.sys_info())
for plugin in self.plugins:
header = "sys: " + plugin._coverage_plugin_name
info = plugin.sys_info()
self.debug.write_formatted_info(header, info)
wrote_any = True
if wrote_any:
self.debug.write_formatted_info("end", ())
示例8: __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)
示例9: report
def report(self, morfs, outfile=None):
"""Writes a report summarizing coverage statistics per module.
`outfile` is a file object to write the summary to.
"""
self.find_code_units(morfs)
# Prepare the formatting strings
max_name = max([len(cu.name) for cu in self.code_units] + [5])
fmt_name = "%%- %ds " % max_name
fmt_err = "%s %s: %s\n"
header = (fmt_name % "Name") + " Stmts Miss"
fmt_coverage = fmt_name + "%6d %6d"
if self.branches:
header += " Branch BrMiss"
fmt_coverage += " %6d %6d"
width100 = Numbers.pc_str_width()
header += "%*s" % (width100+4, "Cover")
fmt_coverage += "%%%ds%%%%" % (width100+3,)
if self.config.show_missing:
header += " Missing"
fmt_coverage += " %s"
rule = "-" * len(header) + "\n"
header += "\n"
fmt_coverage += "\n"
if not outfile:
outfile = sys.stdout
# Write the header
outfile.write(header)
outfile.write(rule)
total = Numbers()
for cu in self.code_units:
try:
analysis = self.coverage._analyze(cu)
nums = analysis.numbers
args = (cu.name, nums.n_statements, nums.n_missing)
if self.branches:
args += (nums.n_branches, nums.n_missing_branches)
args += (nums.pc_covered_str,)
if self.config.show_missing:
missing_fmtd = analysis.missing_formatted()
if self.branches:
branches_fmtd = analysis.arcs_missing_formatted()
if branches_fmtd:
if missing_fmtd:
missing_fmtd += ", "
missing_fmtd += branches_fmtd
args += (missing_fmtd,)
outfile.write(fmt_coverage % args)
total += nums
except KeyboardInterrupt: # pragma: not covered
raise
except:
report_it = not self.config.ignore_errors
if report_it:
typ, msg = sys.exc_info()[:2]
if typ is NotPython and not cu.should_be_python():
report_it = False
if report_it:
outfile.write(fmt_err % (cu.name, typ.__name__, msg))
if total.n_files > 1:
outfile.write(rule)
args = ("TOTAL", total.n_statements, total.n_missing)
if self.branches:
args += (total.n_branches, total.n_missing_branches)
args += (total.pc_covered_str,)
if self.config.show_missing:
args += ("",)
outfile.write(fmt_coverage % args)
return total.pc_covered
示例10: __init__
#.........这里部分代码省略.........
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,
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
# we've imported, and take all the different ones.
for m in (atexit, os, random, socket):
if hasattr(m, "__file__"):
m_dir = self._canonical_dir(m.__file__)
if m_dir not in self.pylib_dirs:
self.pylib_dirs.append(m_dir)
# 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, created when tracing starts.
self.source_match = None
self.pylib_match = self.cover_match = None
self.include_match = self.omit_match = None
# Only _harvest_data once per measurement cycle.
self._harvested = False
# Set the reporting precision.
Numbers.set_precision(self.config.precision)
# When tearing down the coverage object, modules can become None.
# Saving the modules as object attributes avoids problems, but it is
# quite ad-hoc which modules need to be saved and which references
# need to use the object attributes.
self.socket = socket
self.os = os
self.random = random
示例11: report
def report(self, morfs, outfile=None):
"""Writes a report summarizing coverage statistics per module.
`outfile` is a file object to write the summary to.
"""
self.find_file_reporters(morfs)
# Prepare the formatting strings
max_name = max([len(fr.relative_filename()) for fr in self.file_reporters] + [5])
fmt_name = "%%- %ds " % max_name
fmt_err = "%s %s: %s\n"
header = (fmt_name % "Name") + " Stmts Miss"
fmt_coverage = fmt_name + "%6d %6d"
if self.branches:
header += " Branch BrPart"
fmt_coverage += " %6d %6d"
width100 = Numbers.pc_str_width()
header += "%*s" % (width100+4, "Cover")
fmt_coverage += "%%%ds%%%%" % (width100+3,)
if self.config.show_missing:
header += " Missing"
fmt_coverage += " %s"
rule = "-" * len(header) + "\n"
header += "\n"
fmt_coverage += "\n"
if not outfile:
outfile = sys.stdout
# Write the header
outfile.write(header)
outfile.write(rule)
total = Numbers()
for fr in self.file_reporters:
try:
analysis = self.coverage._analyze(fr)
nums = analysis.numbers
if self.config.skip_covered:
# Don't report on 100% files.
no_missing_lines = (nums.n_missing == 0)
no_missing_branches = (nums.n_partial_branches == 0)
if no_missing_lines and no_missing_branches:
continue
args = (fr.relative_filename(), nums.n_statements, nums.n_missing)
if self.branches:
args += (nums.n_branches, nums.n_partial_branches)
args += (nums.pc_covered_str,)
if self.config.show_missing:
missing_fmtd = analysis.missing_formatted()
if self.branches:
branches_fmtd = analysis.arcs_missing_formatted()
if branches_fmtd:
if missing_fmtd:
missing_fmtd += ", "
missing_fmtd += branches_fmtd
args += (missing_fmtd,)
outfile.write(fmt_coverage % args)
total += nums
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:
outfile.write(fmt_err % (fr.relative_filename(), typ.__name__, msg))
if total.n_files > 1:
outfile.write(rule)
args = ("TOTAL", total.n_statements, total.n_missing)
if self.branches:
args += (total.n_branches, total.n_partial_branches)
args += (total.pc_covered_str,)
if self.config.show_missing:
args += ("",)
outfile.write(fmt_coverage % args)
if not total.n_files:
raise CoverageException("No data to report.")
return total.n_statements and total.pc_covered
示例12: __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)
示例13: report
def report(self, morfs, outfile=None):
"""Writes a report summarizing coverage statistics per module.
`outfile` is a file object to write the summary to. It must be opened
for native strings (bytes on Python 2, Unicode on Python 3).
"""
file_reporters = self.find_file_reporters(morfs)
# Prepare the formatting strings, header, and column sorting.
max_name = max([len(fr.relative_filename()) for fr in file_reporters] + [5])
fmt_name = u"%%- %ds " % max_name
fmt_err = u"%s %s: %s"
fmt_skip_covered = u"\n%s file%s skipped due to complete coverage."
header = (fmt_name % "Name") + u" Stmts Miss"
fmt_coverage = fmt_name + u"%6d %6d"
if self.branches:
header += u" Branch BrPart"
fmt_coverage += u" %6d %6d"
width100 = Numbers.pc_str_width()
header += u"%*s" % (width100+4, "Cover")
fmt_coverage += u"%%%ds%%%%" % (width100+3,)
if self.config.show_missing:
header += u" Missing"
fmt_coverage += u" %s"
rule = u"-" * len(header)
column_order = dict(name=0, stmts=1, miss=2, cover=-1)
if self.branches:
column_order.update(dict(branch=3, brpart=4))
if outfile is None:
outfile = sys.stdout
def writeout(line):
"""Write a line to the output, adding a newline."""
if env.PY2:
line = line.encode(output_encoding())
outfile.write(line.rstrip())
outfile.write("\n")
# Write the header
writeout(header)
writeout(rule)
# `lines` is a list of pairs, (line text, line values). The line text
# is a string that will be printed, and line values is a tuple of
# sortable values.
lines = []
total = Numbers()
skipped_count = 0
for fr in file_reporters:
try:
analysis = self.coverage._analyze(fr)
nums = analysis.numbers
total += nums
if self.config.skip_covered:
# Don't report on 100% files.
no_missing_lines = (nums.n_missing == 0)
no_missing_branches = (nums.n_partial_branches == 0)
if no_missing_lines and no_missing_branches:
skipped_count += 1
continue
args = (fr.relative_filename(), nums.n_statements, nums.n_missing)
if self.branches:
args += (nums.n_branches, nums.n_partial_branches)
args += (nums.pc_covered_str,)
if self.config.show_missing:
missing_fmtd = analysis.missing_formatted()
if self.branches:
branches_fmtd = analysis.arcs_missing_formatted()
if branches_fmtd:
if missing_fmtd:
missing_fmtd += ", "
missing_fmtd += branches_fmtd
args += (missing_fmtd,)
text = fmt_coverage % args
# Add numeric percent coverage so that sorting makes sense.
args += (nums.pc_covered,)
lines.append((text, args))
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:
writeout(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:
#.........这里部分代码省略.........
示例14: report
def report(self, morfs, outfile=None):
"""Writes a report summarizing coverage statistics per module.
`outfile` is a file object to write the summary to. It must be opened
for native strings (bytes on Python 2, Unicode on Python 3).
"""
self.find_file_reporters(morfs)
# Prepare the formatting strings
max_name = max([len(fr.relative_filename()) for fr in self.file_reporters] + [5])
fmt_name = u"%%- %ds " % max_name
fmt_err = u"%s %s: %s"
fmt_skip_covered = u"\n%s file%s skipped due to complete coverage."
header = (fmt_name % "Name") + u" Stmts Miss"
fmt_coverage = fmt_name + u"%6d %6d"
if self.branches:
header += u" Branch BrPart"
fmt_coverage += u" %6d %6d"
width100 = Numbers.pc_str_width()
header += u"%*s" % (width100+4, "Cover")
fmt_coverage += u"%%%ds%%%%" % (width100+3,)
if self.config.show_missing:
header += u" Missing"
fmt_coverage += u" %s"
rule = u"-" * len(header)
if outfile is None:
outfile = sys.stdout
def writeout(line):
"""Write a line to the output, adding a newline."""
if env.PY2:
line = line.encode(output_encoding())
outfile.write(line.rstrip())
outfile.write("\n")
# Write the header
writeout(header)
writeout(rule)
total = Numbers()
skipped_count = 0
for fr in self.file_reporters:
try:
analysis = self.coverage._analyze(fr)
nums = analysis.numbers
total += nums
if self.config.skip_covered:
# Don't report on 100% files.
no_missing_lines = (nums.n_missing == 0)
no_missing_branches = (nums.n_partial_branches == 0)
if no_missing_lines and no_missing_branches:
skipped_count += 1
continue
args = (fr.relative_filename(), nums.n_statements, nums.n_missing)
if self.branches:
args += (nums.n_branches, nums.n_partial_branches)
args += (nums.pc_covered_str,)
if self.config.show_missing:
missing_fmtd = analysis.missing_formatted()
if self.branches:
branches_fmtd = analysis.arcs_missing_formatted()
if branches_fmtd:
if missing_fmtd:
missing_fmtd += ", "
missing_fmtd += branches_fmtd
args += (missing_fmtd,)
writeout(fmt_coverage % args)
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:
writeout(fmt_err % (fr.relative_filename(), typ.__name__, msg))
if total.n_files > 1:
writeout(rule)
args = ("TOTAL", total.n_statements, total.n_missing)
if self.branches:
args += (total.n_branches, total.n_partial_branches)
args += (total.pc_covered_str,)
if self.config.show_missing:
args += ("",)
writeout(fmt_coverage % args)
if not total.n_files and not skipped_count:
raise CoverageException("No data to report.")
if self.config.skip_covered and skipped_count:
writeout(fmt_skip_covered % (skipped_count, 's' if skipped_count > 1 else ''))
#.........这里部分代码省略.........