Coverage for /home/ionel/open-source/pytest-cov/examples/adhoc-layout/.tox/py27/lib/python2.7/site-packages/_pytest/runner.py : 42%

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
""" basic collect and runtest protocol implementations """ from __future__ import absolute_import from __future__ import division from __future__ import print_function
import bdb import os import sys from time import time
import attr import six
from .reports import CollectErrorRepr from .reports import CollectReport from .reports import TestReport from _pytest._code.code import ExceptionInfo from _pytest.outcomes import Exit from _pytest.outcomes import skip from _pytest.outcomes import Skipped from _pytest.outcomes import TEST_OUTCOME
# # pytest plugin hooks
def pytest_addoption(parser): group = parser.getgroup("terminal reporting", "reporting", after="general") group.addoption( "--durations", action="store", type=int, default=None, metavar="N", help="show N slowest setup/test durations (N=0 for all).", ),
def pytest_terminal_summary(terminalreporter): durations = terminalreporter.config.option.durations verbose = terminalreporter.config.getvalue("verbose") if durations is None: return tr = terminalreporter dlist = [] for replist in tr.stats.values(): for rep in replist: if hasattr(rep, "duration"): dlist.append(rep) if not dlist: return dlist.sort(key=lambda x: x.duration) dlist.reverse() if not durations: tr.write_sep("=", "slowest test durations") else: tr.write_sep("=", "slowest %s test durations" % durations) dlist = dlist[:durations]
for rep in dlist: if verbose < 2 and rep.duration < 0.005: tr.write_line("") tr.write_line("(0.00 durations hidden. Use -vv to show these durations.)") break tr.write_line("%02.2fs %-8s %s" % (rep.duration, rep.when, rep.nodeid))
def pytest_sessionstart(session):
def pytest_sessionfinish(session): session._setupstate.teardown_all()
def pytest_runtest_protocol(item, nextitem):
def runtestprotocol(item, log=True, nextitem=None): item._initrequest() show_test_item(item) # after all teardown hooks have been called # want funcargs and request info to go away
def show_test_item(item): """Show test function, parameters and the fixtures of the test item.""" tw = item.config.get_terminal_writer() tw.line() tw.write(" " * 8) tw.write(item._nodeid) used_fixtures = sorted(item._fixtureinfo.name2fixturedefs.keys()) if used_fixtures: tw.write(" (fixtures used: {})".format(", ".join(used_fixtures)))
def pytest_runtest_setup(item):
def pytest_runtest_call(item): except Exception: # Store trace info to allow postmortem debugging type, value, tb = sys.exc_info() tb = tb.tb_next # Skip *this* frame sys.last_type = type sys.last_value = value sys.last_traceback = tb del type, value, tb # Get rid of these in this frame raise
def pytest_runtest_teardown(item, nextitem):
def _update_current_test_var(item, when): """ Update PYTEST_CURRENT_TEST to reflect the current item and stage.
If ``when`` is None, delete PYTEST_CURRENT_TEST from the environment. """ # don't allow null bytes on environment variables (see #2644, #2957) else:
def pytest_report_teststatus(report): # category, shortletter, verbose-word return "error", "E", "ERROR" return "skipped", "s", "SKIPPED" else:
# # Implementation
def call_and_report(item, when, log=True, **kwds): hook.pytest_exception_interact(node=item, call=call, report=report)
def check_interactive_exception(call, report): hasattr(report, "wasxfail") or call.excinfo.errisinstance(skip.Exception) or call.excinfo.errisinstance(bdb.BdbQuit) )
def call_runtest_hook(item, when, **kwds): lambda: ihook(item=item, **kwds), when=when, reraise=reraise )
@attr.s(repr=False) class CallInfo(object): """ Result/Exception info a function invocation. """
_result = attr.ib() # Optional[ExceptionInfo] excinfo = attr.ib() start = attr.ib() stop = attr.ib() when = attr.ib()
@property def result(self): raise AttributeError("{!r} has no valid result".format(self))
@classmethod def from_call(cls, func, when, reraise=None): #: context of invocation: one of "setup", "call", #: "teardown", "memocollect" except: # noqa excinfo = ExceptionInfo.from_current() if reraise is not None and excinfo.errisinstance(reraise): raise result = None
def __repr__(self): if self.excinfo is not None: status = "exception" value = self.excinfo.value else: # TODO: investigate unification value = repr(self._result) status = "result" return "<CallInfo when={when!r} {status}: {value}>".format( when=self.when, value=value, status=status )
def pytest_runtest_makereport(item, call): else: if not isinstance(excinfo, ExceptionInfo): outcome = "failed" longrepr = excinfo elif excinfo.errisinstance(skip.Exception): outcome = "skipped" r = excinfo._getreprcrash() longrepr = (str(r.path), r.lineno, r.message) else: outcome = "failed" if call.when == "call": longrepr = item.repr_failure(excinfo) else: # exception in setup or teardown longrepr = item._repr_failure_py( excinfo, style=item.config.option.tbstyle ) sections.append(("Captured %s %s" % (key, rwhen), content)) item.nodeid, item.location, keywords, outcome, longrepr, when, sections, duration, user_properties=item.user_properties, )
def pytest_make_collect_report(collector): else: from _pytest import nose
skip_exceptions = (Skipped,) + nose.get_skip_exceptions() if call.excinfo.errisinstance(skip_exceptions): outcome = "skipped" r = collector._repr_failure_py(call.excinfo, "line").reprcrash longrepr = (str(r.path), r.lineno, r.message) else: outcome = "failed" errorinfo = collector.repr_failure(call.excinfo) if not hasattr(errorinfo, "toterminal"): errorinfo = CollectErrorRepr(errorinfo) longrepr = errorinfo collector.nodeid, outcome, longrepr, getattr(call, "result", None) )
class SetupState(object): """ shared state for setting up/tearing down test items or collectors. """
def __init__(self):
def addfinalizer(self, finalizer, colitem): """ attach a finalizer to the given colitem. if colitem is None, this will add a finalizer that is called at the end of teardown_all(). """ # assert colitem in self.stack # some unit tests don't setup stack :/
def _pop_and_teardown(self):
def _callfinalizers(self, colitem): except TEST_OUTCOME: # XXX Only first exception will be seen by user, # ideally all should be reported. if exc is None: exc = sys.exc_info() six.reraise(*exc)
def _teardown_with_finalization(self, colitem): assert ( colitem is None or colitem in self.stack or isinstance(colitem, tuple) )
def teardown_all(self): while self.stack: self._pop_and_teardown() for key in list(self._finalizers): self._teardown_with_finalization(key) assert not self._finalizers
def teardown_exact(self, item, nextitem):
def _teardown_towards(self, needed_collectors): break except TEST_OUTCOME: # XXX Only first exception will be seen by user, # ideally all should be reported. if exc is None: exc = sys.exc_info() six.reraise(*exc)
def prepare(self, colitem): """ setup objects along the collector chain to the test-method and teardown previously setup objects."""
# check if the last collection node has raised an error if hasattr(col, "_prepare_exc"): six.reraise(*col._prepare_exc) except TEST_OUTCOME: col._prepare_exc = sys.exc_info() raise
def collect_one_node(collector): ihook.pytest_exception_interact(node=collector, call=call, report=rep) |