我们从Python开源项目中,提取了以下24个代码示例,用于说明如何使用coverage.files()。
def combine(self): """Combine together a number of similarly-named coverage data files. All coverage data files whose name starts with `data_file` (from the coverage() constructor) will be read, and combined together into the current measurements. """ aliases = None if self.config.paths: aliases = PathAliases(self.file_locator) for paths in self.config.paths.values(): result = paths[0] for pattern in paths[1:]: aliases.add(pattern, result) self.data.combine_parallel_data(aliases=aliases)
def _get_file_reporters(self, morfs=None): """Get a list of FileReporters for a list of modules or file names. For each module or file name in `morfs`, find a FileReporter. Return the list of FileReporters. If `morfs` is a single module or file name, this returns a list of one FileReporter. If `morfs` is empty or None, then the list of all files measured is used to find the FileReporters. """ if not morfs: morfs = self.data.measured_files() # Be sure we have a list. if not isinstance(morfs, (list, tuple)): morfs = [morfs] file_reporters = [] for morf in morfs: file_reporter = self._get_file_reporter(morf) file_reporters.append(file_reporter) return file_reporters
def index_file(self): """Write the index.html file for this report.""" index_tmpl = Templite(data("index.html"), self.template_globals) self.totals = sum(f['nums'] for f in self.files) html = index_tmpl.render({ 'has_arcs': self.has_arcs, 'extra_css': self.extra_css, 'files': self.files, 'totals': self.totals, 'time_stamp': self.time_stamp, }) self.write_html(os.path.join(self.directory, "index.html"), html) # Write the latest hashes for next time. self.status.write(self.directory)
def read(self, directory): """Read the last status in `directory`.""" usable = False try: status_file = os.path.join(directory, self.STATUS_FILE) with open(status_file, "r") as fstatus: status = json.load(fstatus) except (IOError, ValueError): usable = False else: usable = True if status['format'] != self.STATUS_FORMAT: usable = False elif status['version'] != coverage.__version__: usable = False if usable: self.files = {} for filename, fileinfo in iitems(status['files']): fileinfo['index']['nums'] = Numbers(*fileinfo['index']['nums']) self.files[filename] = fileinfo self.settings = status['settings'] else: self.reset()
def _harvest_data(self): """Get the collected data and reset the collector. Also warn about various problems collecting data. """ if not self._measured: return self.data.add_line_data(self.collector.get_line_data()) self.data.add_arc_data(self.collector.get_arc_data()) self.collector.reset() # If there are still entries in the source_pkgs list, then we never # encountered those packages. if self._warn_unimported_source: for pkg in self.source_pkgs: self._warn("Module %s was never imported." % pkg) # Find out if we got any data. summary = self.data.summary() if not summary and self._warn_no_data: self._warn("No data was collected.") # Find files that were never executed at all. for src in self.source: for py_file in find_python_files(src): py_file = self.file_locator.canonical_filename(py_file) if self.omit_match and self.omit_match.match(py_file): # Turns out this file was omitted, so don't pull it back # in as unexecuted. continue self.data.touch_file(py_file) self._measured = False # Backward compatibility with version 1.
def _source_for_file(self, filename): """Return the source file for `filename`. Given a file name being traced, return the best guess as to the source file to attribute it to. """ if filename.endswith(".py"): # .py files are themselves source files. return filename elif filename.endswith((".pyc", ".pyo")): # Bytecode files probably have source files near them. py_filename = filename[:-1] if os.path.exists(py_filename): # Found a .py file, use that. return py_filename if env.WINDOWS: # On Windows, it could be a .pyw file. pyw_filename = py_filename + "w" if os.path.exists(pyw_filename): return pyw_filename # Didn't find source, but it's probably the .py file we want. return py_filename elif filename.endswith("$py.class"): # Jython is easy to guess. return filename[:-9] + ".py" # No idea, just use the file name as-is. return filename
def combine(self, data_paths=None): """Combine together a number of similarly-named coverage data files. All coverage data files whose name starts with `data_file` (from the coverage() constructor) will be read, and combined together into the current measurements. `data_paths` is a list of files or directories from which data should be combined. If no list is passed, then the data files from the directory indicated by the current data file (probably the current directory) will be combined. .. versionadded:: 4.0 The `data_paths` parameter. """ self._init() self.get_data() aliases = None if self.config.paths: aliases = PathAliases() for paths in self.config.paths.values(): result = paths[0] for pattern in paths[1:]: aliases.add(pattern, result) self.data_files.combine_parallel_data(self.data, aliases=aliases, data_paths=data_paths)
def report(self, morfs): """Generate an HTML report for `morfs`. `morfs` is a list of modules or file names. """ assert self.config.html_dir, "must give a directory for html reporting" # Read the status data. self.status.read(self.config.html_dir) # Check that this run used the same settings as the last run. m = Hasher() m.update(self.config) these_settings = m.hexdigest() if self.status.settings_hash() != these_settings: self.status.reset() self.status.set_settings_hash(these_settings) # The user may have extra CSS they want copied. if self.config.extra_css: self.extra_css = os.path.basename(self.config.extra_css) # Process all the files. self.report_files(self.html_file, morfs, self.config.html_dir) if not self.files: raise CoverageException("No data to report.") # Write the index file. self.index_file() self.make_local_static_report_files() return self.totals.n_statements and self.totals.pc_covered
def make_local_static_report_files(self): """Make local instances of static files for HTML report.""" # The files we provide must always be copied. for static, pkgdir in self.STATIC_FILES: shutil.copyfile( data_filename(static, pkgdir), os.path.join(self.directory, static) ) # The user may have extra CSS they want copied. if self.extra_css: shutil.copyfile( self.config.extra_css, os.path.join(self.directory, self.extra_css) )
def reset(self): """Initialize to empty.""" self.settings = '' self.files = {}
def file_hash(self, fname): """Get the hash of `fname`'s contents.""" return self.files.get(fname, {}).get('hash', '')
def set_file_hash(self, fname, val): """Set the hash of `fname`'s contents.""" self.files.setdefault(fname, {})['hash'] = val
def index_info(self, fname): """Get the information for index.html for `fname`.""" return self.files.get(fname, {}).get('index', {})
def set_index_info(self, fname, info): """Set the information for index.html for `fname`.""" self.files.setdefault(fname, {})['index'] = info # Helpers for templates and generating HTML
def get_data(self): """Get the collected data and reset the collector. Also warn about various problems collecting data. Returns a :class:`coverage.CoverageData`, the collected coverage data. .. versionadded:: 4.0 """ self._init() if not self._measured: return self.data self.collector.save_data(self.data) # If there are still entries in the source_pkgs list, then we never # encountered those packages. if self._warn_unimported_source: for pkg in self.source_pkgs: if pkg not in sys.modules: self._warn("Module %s was never imported." % pkg) elif not ( hasattr(sys.modules[pkg], '__file__') and os.path.exists(sys.modules[pkg].__file__) ): self._warn("Module %s has no Python source." % pkg) else: self._warn("Module %s was previously imported, but not measured." % pkg) # Find out if we got any data. if not self.data and self._warn_no_data: self._warn("No data was collected.") # Find files that were never executed at all. for src in self.source: for py_file in find_python_files(src): py_file = files.canonical_filename(py_file) if self.omit_match and self.omit_match.match(py_file): # Turns out this file was omitted, so don't pull it back # in as unexecuted. continue self.data.touch_file(py_file) if self.config.note: self.data.add_run_info(note=self.config.note) self._measured = False return self.data # Backward compatibility with version 1.
def xml_report( self, morfs=None, outfile=None, ignore_errors=None, omit=None, include=None, ): """Generate an XML report of coverage results. The report is compatible with Cobertura reports. Each module in `morfs` is included in the report. `outfile` is the path to write the file to, "-" will write to stdout. See :meth:`report` for other arguments. Returns a float, the total percentage covered. """ self.get_data() self.config.from_args( ignore_errors=ignore_errors, omit=omit, include=include, xml_output=outfile, ) file_to_close = None delete_file = False if self.config.xml_output: if self.config.xml_output == '-': outfile = sys.stdout else: # Ensure that the output directory is created; done here # because this report pre-opens the output file. # HTMLReport does this using the Report plumbing because # its task is more complex, being multiple files. output_dir = os.path.dirname(self.config.xml_output) if output_dir and not os.path.isdir(output_dir): os.makedirs(output_dir) open_kwargs = {} if env.PY3: open_kwargs['encoding'] = 'utf8' outfile = open(self.config.xml_output, "w", **open_kwargs) file_to_close = outfile try: reporter = XmlReporter(self, self.config) return reporter.report(morfs, outfile=outfile) except CoverageException: delete_file = True raise finally: if file_to_close: file_to_close.close() if delete_file: file_be_gone(self.config.xml_output)