Coverage for /home/ionel/open-source/pytest-cov/examples/adhoc-layout/.tox/py36/lib/python3.6/site-packages/_pytest/terminal.py : 30%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
""" terminal reporting of the full testing process.
This is a good source for looking at the various reporting hooks. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function
import argparse import collections import platform import sys import time
import attr import pluggy import py import six from more_itertools import collapse
import pytest from _pytest import nodes from _pytest.main import EXIT_INTERRUPTED from _pytest.main import EXIT_NOTESTSCOLLECTED from _pytest.main import EXIT_OK from _pytest.main import EXIT_TESTSFAILED from _pytest.main import EXIT_USAGEERROR
class MoreQuietAction(argparse.Action): """ a modified copy of the argparse count action which counts down and updates the legacy quiet attribute at the same time
used to unify verbosity handling """
def __init__(self, option_strings, dest, default=None, required=False, help=None): option_strings=option_strings, dest=dest, nargs=0, default=default, required=required, help=help, )
def __call__(self, parser, namespace, values, option_string=None): new_count = getattr(namespace, self.dest, 0) - 1 setattr(namespace, self.dest, new_count) # todo Deprecate config.quiet namespace.quiet = getattr(namespace, "quiet", 0) + 1
def pytest_addoption(parser): group = parser.getgroup("terminal reporting", "reporting", after="general") group._addoption( "-v", "--verbose", action="count", default=0, dest="verbose", help="increase verbosity.", ), group._addoption( "-q", "--quiet", action=MoreQuietAction, default=0, dest="verbose", help="decrease verbosity.", ), group._addoption( "--verbosity", dest="verbose", type=int, default=0, help="set verbosity" ) group._addoption( "-r", action="store", dest="reportchars", default="", metavar="chars", help="show extra test summary info as specified by chars (f)ailed, " "(E)error, (s)skipped, (x)failed, (X)passed, " "(p)passed, (P)passed with output, (a)all except pP. " "Warnings are displayed at all times except when " "--disable-warnings is set", ) group._addoption( "--disable-warnings", "--disable-pytest-warnings", default=False, dest="disable_warnings", action="store_true", help="disable warnings summary", ) group._addoption( "-l", "--showlocals", action="store_true", dest="showlocals", default=False, help="show locals in tracebacks (disabled by default).", ) group._addoption( "--tb", metavar="style", action="store", dest="tbstyle", default="auto", choices=["auto", "long", "short", "no", "line", "native"], help="traceback print mode (auto/long/short/line/native/no).", ) group._addoption( "--show-capture", action="store", dest="showcapture", choices=["no", "stdout", "stderr", "log", "all"], default="all", help="Controls how captured stdout/stderr/log is shown on failed tests. " "Default is 'all'.", ) group._addoption( "--fulltrace", "--full-trace", action="store_true", default=False, help="don't cut any tracebacks (default is to cut).", ) group._addoption( "--color", metavar="color", action="store", dest="color", default="auto", choices=["yes", "no", "auto"], help="color terminal output (yes/no/auto).", )
parser.addini( "console_output_style", help="console output: classic or with additional progress information (classic|progress).", default="progress", )
def pytest_configure(config):
def mywriter(tags, args): msg = " ".join(map(str, args)) reporter.write_line("[traceconfig] " + msg)
config.trace.root.setprocessor("pytest:config", mywriter)
def getreportopt(config): elif config.option.disable_warnings and "w" in reportchars: reportchars = reportchars.replace("w", "") reportopts += char
def pytest_report_teststatus(report): elif report.skipped: letter = "s" elif report.failed: letter = "F" if report.when != "call": letter = "f"
@attr.s class WarningReport(object): """ Simple structure to hold warnings information captured by ``pytest_warning_captured``.
:ivar str message: user friendly message about the warning :ivar str|None nodeid: node id that generated the warning (see ``get_location``). :ivar tuple|py.path.local fslocation: file system location of the source of the warning (see ``get_location``). """
message = attr.ib() nodeid = attr.ib(default=None) fslocation = attr.ib(default=None)
def get_location(self, config): """ Returns the more user-friendly information about the location of a warning, or None. """ if self.nodeid: return self.nodeid if self.fslocation: if isinstance(self.fslocation, tuple) and len(self.fslocation) >= 2: filename, linenum = self.fslocation[:2] relpath = py.path.local(filename).relto(config.invocation_dir) if not relpath: relpath = str(filename) return "%s:%s" % (relpath, linenum) else: return str(self.fslocation) return None
class TerminalReporter(object): def __init__(self, config, file=None):
file = sys.stdout # self.writer will be deprecated in pytest-3.4
def _determine_show_progress_info(self): """Return True if we should display progress information based on the current config""" # do not show progress if we are not capturing output (#3038) return False # do not show progress if we are showing fixture setup/teardown return False
@property def verbosity(self):
@property def showheader(self):
@property def showfspath(self): return self._showfspath
@showfspath.setter def showfspath(self, value): self._showfspath = value
@property def showlongtestinfo(self):
def hasopt(self, char): char = {"xfailed": "x", "skipped": "s"}.get(char, char) return char in self.reportchars
def write_fspath_result(self, nodeid, res, **markup): fspath = self.config.rootdir.join(nodeid.split("::")[0]) if fspath != self.currentfspath: if self.currentfspath is not None and self._show_progress_info: self._write_progress_information_filling_space() self.currentfspath = fspath fspath = self.startdir.bestrelpath(fspath) self._tw.line() self._tw.write(fspath + " ") self._tw.write(res, **markup)
def write_ensure_prefix(self, prefix, extra="", **kwargs):
def ensure_newline(self): self._tw.line() self.currentfspath = None
def write(self, content, **markup):
def write_line(self, line, **markup): line = six.text_type(line, errors="replace")
def rewrite(self, line, **markup): """ Rewinds the terminal cursor to the beginning and writes the given line.
:kwarg erase: if True, will also add spaces until the full terminal width to ensure previous lines are properly erased.
The rest of the keyword arguments are markup instructions. """ else: fill = ""
def write_sep(self, sep, title=None, **markup):
def section(self, title, sep="=", **kw): self._tw.sep(sep, title, **kw)
def line(self, msg, **kw): self._tw.line(msg, **kw)
def pytest_internalerror(self, excrepr): for line in six.text_type(excrepr).split("\n"): self.write_line("INTERNALERROR> " + line) return 1
def pytest_warning_captured(self, warning_message, item): # from _pytest.nodes import get_fslocation_from_item from _pytest.warnings import warning_record_to_str
warnings = self.stats.setdefault("warnings", []) fslocation = warning_message.filename, warning_message.lineno message = warning_record_to_str(warning_message)
nodeid = item.nodeid if item is not None else "" warning_report = WarningReport( fslocation=fslocation, message=message, nodeid=nodeid ) warnings.append(warning_report)
def pytest_plugin_registered(self, plugin): msg = "PLUGIN registered: %s" % (plugin,) # XXX this event may happen during setup/teardown time # which unfortunately captures our output here # which garbles our output if we use self.write_line self.write_line(msg)
def pytest_deselected(self, items): self.stats.setdefault("deselected", []).extend(items)
def pytest_runtest_logstart(self, nodeid, location): # ensure that the path is printed before the # 1st test of a module starts running elif self.showfspath: fsid = nodeid.split("::")[0] self.write_fspath_result(fsid, "")
def pytest_runtest_logreport(self, report): word, markup = word else: # probably passed setup/teardown elif rep.passed and was_xfail: markup = {"yellow": True} elif rep.failed: markup = {"red": True} elif rep.skipped: markup = {"yellow": True} else: markup = {} if not running_xdist and self.showfspath: self.write_fspath_result(rep.nodeid, letter, **markup) else: self._tw.write(letter, **markup) else: else: self.ensure_newline() self._tw.write("[%s]" % rep.node.gateway.id) if self._show_progress_info: self._tw.write( self._get_progress_information_message() + " ", cyan=True ) else: self._tw.write(" ") self._tw.write(word, **markup) self._tw.write(" " + line) self.currentfspath = -2
def pytest_runtest_logfinish(self, nodeid): num_tests = self._session.testscollected progress_length = len(" [{}/{}]".format(str(num_tests), str(num_tests))) else:
self._progress_nodeids_reported.add(nodeid) last_item = ( len(self._progress_nodeids_reported) == self._session.testscollected ) if last_item: self._write_progress_information_filling_space() else: w = self._width_of_current_line past_edge = w + progress_length + 1 >= self._screen_width if past_edge: msg = self._get_progress_information_message() self._tw.write(msg + "\n", cyan=True)
def _get_progress_information_message(self): return "" if collected: progress = self._progress_nodeids_reported counter_format = "{{:{}d}}".format(len(str(collected))) format_string = " [{}/{{}}]".format(counter_format) return format_string.format(len(progress), collected) return " [ {} / {} ]".format(collected, collected) else: return " [100%]"
def _write_progress_information_filling_space(self):
@property def _width_of_current_line(self): """Return the width of current line, using the superior implementation of py-1.6 when available""" except AttributeError: # py < 1.6.0 return self._tw.chars_on_current_line
def pytest_collection(self): elif self.config.option.verbose >= 1: self.write("collecting ... ", bold=True)
def pytest_collectreport(self, report): self.stats.setdefault("error", []).append(report) self.stats.setdefault("skipped", []).append(report)
def report_collect(self, final=False): return
# Only write "collecting" report every 0.5s. self._collect_report_last_write is not None and self._collect_report_last_write > t - 0.5 ): self._collect_report_last_write = t
else: line = "collecting " str(self._numcollected) + " item" + ("" if self._numcollected == 1 else "s") ) line += " / %d errors" % errors line += " / %d deselected" % deselected line += " / %d skipped" % skipped line += " / %d selected" % selected else: self.write_line(line)
@pytest.hookimpl(trylast=True) def pytest_collection_modifyitems(self):
@pytest.hookimpl(trylast=True) def pytest_sessionstart(self, session): return verinfo = ".".join(map(str, sys.pypy_version_info[:3])) msg += "[pypy-%s-%s]" % (verinfo, sys.pypy_version_info[3]) pytest.__version__, py.__version__, pluggy.__version__, ) self.verbosity > 0 or self.config.option.debug or getattr(self.config.option, "pastebin", None) ): config=self.config, startdir=self.startdir )
def _write_report_lines_from_hooks(self, lines):
def pytest_report_header(self, config):
def pytest_collection_finish(self, session): self._printcollecteditems(session.items)
config=self.config, startdir=self.startdir, items=session.items )
if self.stats.get("failed"): self._tw.sep("!", "collection failures") for rep in self.stats.get("failed"): rep.toterminal(self._tw)
def _printcollecteditems(self, items): # to print out items and their parent collectors # we take care to leave out Instances aka () # because later versions are going to get rid of them anyway if self.config.option.verbose < 0: if self.config.option.verbose < -1: counts = {} for item in items: name = item.nodeid.split("::", 1)[0] counts[name] = counts.get(name, 0) + 1 for name, count in sorted(counts.items()): self._tw.line("%s: %d" % (name, count)) else: for item in items: self._tw.line(item.nodeid) return stack = [] indent = "" for item in items: needed_collectors = item.listchain()[1:] # strip root node while stack: if stack == needed_collectors[: len(stack)]: break stack.pop() for col in needed_collectors[len(stack) :]: stack.append(col) if col.name == "()": # Skip Instances. continue indent = (len(stack) - 1) * " " self._tw.line("%s%s" % (indent, col)) if self.config.option.verbose >= 1: if hasattr(col, "_obj") and col._obj.__doc__: for line in col._obj.__doc__.strip().splitlines(): self._tw.line("%s%s" % (indent + " ", line.strip()))
@pytest.hookimpl(hookwrapper=True) def pytest_sessionfinish(self, exitstatus): outcome = yield outcome.get_result() self._tw.line("") summary_exit_codes = ( EXIT_OK, EXIT_TESTSFAILED, EXIT_INTERRUPTED, EXIT_USAGEERROR, EXIT_NOTESTSCOLLECTED, ) if exitstatus in summary_exit_codes: self.config.hook.pytest_terminal_summary( terminalreporter=self, exitstatus=exitstatus, config=self.config ) if exitstatus == EXIT_INTERRUPTED: self._report_keyboardinterrupt() del self._keyboardinterrupt_memo self.summary_stats()
@pytest.hookimpl(hookwrapper=True) def pytest_terminal_summary(self): self.summary_errors() self.summary_failures() self.summary_warnings() yield self.summary_passes() # Display any extra warnings from teardown here (if any). self.summary_warnings() self.summary_deprecated_python()
def pytest_keyboard_interrupt(self, excinfo): self._keyboardinterrupt_memo = excinfo.getrepr(funcargs=True)
def pytest_unconfigure(self): if hasattr(self, "_keyboardinterrupt_memo"): self._report_keyboardinterrupt()
def _report_keyboardinterrupt(self): excrepr = self._keyboardinterrupt_memo msg = excrepr.reprcrash.message self.write_sep("!", msg) if "KeyboardInterrupt" in msg: if self.config.option.fulltrace: excrepr.toterminal(self._tw) else: excrepr.reprcrash.toterminal(self._tw) self._tw.line( "(to show a full traceback on KeyboardInterrupt use --fulltrace)", yellow=True, )
def _locationline(self, nodeid, fspath, lineno, domain):
# collect_fspath comes from testid which has a "/"-normalized path
"\\", nodes.SEP ): res += " <- " + self.startdir.bestrelpath(fspath) else: res = "[location]"
def _getfailureheadline(self, rep): if hasattr(rep, "location"): fspath, lineno, domain = rep.location return domain else: return "test session" # XXX?
def _getcrashline(self, rep): try: return str(rep.longrepr.reprcrash) except AttributeError: try: return str(rep.longrepr)[:50] except AttributeError: return ""
# # summaries for sessionfinish # def getreports(self, name): values = [] for x in self.stats.get(name, []): if not hasattr(x, "_pdbshown"): values.append(x) return values
def summary_warnings(self): if self.hasopt("w"): all_warnings = self.stats.get("warnings") if not all_warnings: return
final = hasattr(self, "_already_displayed_warnings") if final: warning_reports = all_warnings[self._already_displayed_warnings :] else: warning_reports = all_warnings self._already_displayed_warnings = len(warning_reports) if not warning_reports: return
reports_grouped_by_message = collections.OrderedDict() for wr in warning_reports: reports_grouped_by_message.setdefault(wr.message, []).append(wr)
title = "warnings summary (final)" if final else "warnings summary" self.write_sep("=", title, yellow=True, bold=False) for message, warning_reports in reports_grouped_by_message.items(): has_any_location = False for w in warning_reports: location = w.get_location(self.config) if location: self._tw.line(str(location)) has_any_location = True if has_any_location: lines = message.splitlines() indented = "\n".join(" " + x for x in lines) message = indented.rstrip() else: message = message.rstrip() self._tw.line(message) self._tw.line() self._tw.line("-- Docs: https://docs.pytest.org/en/latest/warnings.html")
def summary_passes(self): if self.config.option.tbstyle != "no": if self.hasopt("P"): reports = self.getreports("passed") if not reports: return self.write_sep("=", "PASSES") for rep in reports: if rep.sections: msg = self._getfailureheadline(rep) self.write_sep("_", msg) self._outrep_summary(rep)
def summary_deprecated_python(self): if sys.version_info[:2] <= (3, 4) and self.verbosity >= 0: self.write_sep("=", "deprecated python version", yellow=True, bold=False) using_version = ".".join(str(x) for x in sys.version_info[:3]) self.line( "You are using Python {}, which will no longer be supported in pytest 5.0".format( using_version ), yellow=True, bold=False, ) self.line("For more information, please read:") self.line(" https://docs.pytest.org/en/latest/py27-py34-deprecation.html")
def print_teardown_sections(self, rep): showcapture = self.config.option.showcapture if showcapture == "no": return for secname, content in rep.sections: if showcapture != "all" and showcapture not in secname: continue if "teardown" in secname: self._tw.sep("-", secname) if content[-1:] == "\n": content = content[:-1] self._tw.line(content)
def summary_failures(self): if self.config.option.tbstyle != "no": reports = self.getreports("failed") if not reports: return self.write_sep("=", "FAILURES") for rep in reports: if self.config.option.tbstyle == "line": line = self._getcrashline(rep) self.write_line(line) else: msg = self._getfailureheadline(rep) self.write_sep("_", msg, red=True, bold=True) self._outrep_summary(rep) for report in self.getreports(""): if report.nodeid == rep.nodeid and report.when == "teardown": self.print_teardown_sections(report)
def summary_errors(self): if self.config.option.tbstyle != "no": reports = self.getreports("error") if not reports: return self.write_sep("=", "ERRORS") for rep in self.stats["error"]: msg = self._getfailureheadline(rep) if rep.when == "collect": msg = "ERROR collecting " + msg elif rep.when == "setup": msg = "ERROR at setup of " + msg elif rep.when == "teardown": msg = "ERROR at teardown of " + msg self.write_sep("_", msg, red=True, bold=True) self._outrep_summary(rep)
def _outrep_summary(self, rep): rep.toterminal(self._tw) showcapture = self.config.option.showcapture if showcapture == "no": return for secname, content in rep.sections: if showcapture != "all" and showcapture not in secname: continue self._tw.sep("-", secname) if content[-1:] == "\n": content = content[:-1] self._tw.line(content)
def summary_stats(self): session_duration = time.time() - self._sessionstarttime (line, color) = build_summary_stats_line(self.stats) msg = "%s in %.2f seconds" % (line, session_duration) markup = {color: True, "bold": True}
if self.verbosity >= 0: self.write_sep("=", msg, **markup) if self.verbosity == -1: self.write_line(msg, **markup)
def build_summary_stats_line(stats): keys = ("failed passed skipped deselected xfailed xpassed warnings error").split() unknown_key_seen = False for key in stats.keys(): if key not in keys: if key: # setup/teardown reports have an empty key, ignore them keys.append(key) unknown_key_seen = True parts = [] for key in keys: val = stats.get(key, None) if val: parts.append("%d %s" % (len(val), key))
if parts: line = ", ".join(parts) else: line = "no tests ran"
if "failed" in stats or "error" in stats: color = "red" elif "warnings" in stats or unknown_key_seen: color = "yellow" elif "passed" in stats: color = "green" else: color = "yellow"
return (line, color)
def _plugin_nameversions(plugininfo): # gets us name and version! # questionable convenience, but it keeps things short # we decided to print python package names # they can have more than one plugin |