Coverage for .tox/testcoverage/lib/python2.7/site-packages/_pytest/main : 61%

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
""" core implementation of testing process: init, session, runtest loop. """
except ImportError: from UserDict import DictMixin as MappingMixin
# exitcodes for the command line
type="args", default=['.*', 'CVS', '_darcs', '{arch}', '*.egg']) type="args", default=[]) #parser.addini("dirpatterns", # "patterns specifying possible locations of test files", # type="linelist", default=["**/test_*.txt", # "**/test_*.py", "**/*_test.py"] #) dest="exitfirst", help="exit instantly on first error or failed test."), action="store", type=int, dest="maxfail", default=0, help="exit after first num failures or errors.") help="run pytest in strict mode, warnings become errors.") help="load configuration from `file` instead of trying to locate one of the implicit configuration files.")
help="only collect tests, don't execute them."), help="try to interpret all arguments as python packages.") help="ignore path during collection (multi-allowed).") # when changing this to --conf-cut-dir, config.py Conftest.setinitial # needs upgrading as well metavar="dir", help="only load conftest.py's relative to specified dir.") dest="noconftest", default=False, help="Don't load any conftest.py files.")
"test session debugging and configuration") help="base temporary directory for this test run.")
config.option.maxfail = 1
"""Skeleton command line program""" except pytest.UsageError: raise except KeyboardInterrupt: excinfo = _pytest._code.ExceptionInfo() config.hook.pytest_keyboard_interrupt(excinfo=excinfo) session.exitstatus = EXIT_INTERRUPTED except: excinfo = _pytest._code.ExceptionInfo() config.notify_exception(excinfo, config.option) session.exitstatus = EXIT_INTERNALERROR if excinfo.errisinstance(SystemExit): sys.stderr.write("mainloop: caught Spurious SystemExit!\n")
finally: session=session, exitstatus=session.exitstatus)
""" default command line protocol for initialization, session, running tests and reporting. """
return EXIT_TESTSFAILED return EXIT_NOTESTSCOLLECTED
return True
# this is a function to avoid python2 # keeping sys.exc_info set when calling into a test # python2 keeps sys.exc_info till the frame is left
raise session.Interrupted(session.shouldstop)
ignore_paths.extend([py.path.local(x) for x in excludeopt])
self.fspath = fspath self.pm = pm self.remove_mods = remove_mods
x = self.pm.subset_hook_caller(name, remove_plugins=self.remove_mods) self.__dict__[name] = x return x
# deprecated - use pytest.name
self._markers[key] = value
raise ValueError("cannot delete key in keywords dict")
return len(self.__iter__())
return list(self)
return "<NodeKeywords for node %s>" % (self.node, )
""" base class for Collector and Item the test collection tree. Collector subclasses have children, Items are terminal nodes."""
#: a unique name within the scope of the parent node
#: the parent collector node.
#: the pytest config object
#: the session this node is part of
#: filesystem path where this node was collected from (can be None)
#: keywords/markers collected from all scopes
#: allow adding of extra keywords to use for matching
# used for storing artificial fixturedefs for direct parametrization
def ihook(self): """ fspath sensitive hook proxy used to call pytest hooks"""
cls = getattr(self, name) if cls != getattr(pytest, name): py.log._apiwarn("2.0", "use of node.%s is deprecated, " "use pytest_pycollect_makeitem(...) to create custom " "collection nodes" % name) return cls
return "<%s %r>" %(self.__class__.__name__, getattr(self, 'name', None))
""" generate a warning with the given code and message for this item. """ assert isinstance(code, str) fslocation = getattr(self, "location", None) if fslocation is None: fslocation = getattr(self, "fspath", None) else: fslocation = "%s:%s" % fslocation[:2]
self.ihook.pytest_logwarning.call_historic(kwargs=dict( code=code, message=message, nodeid=self.nodeid, fslocation=fslocation))
# methods for ordering nodes def nodeid(self): """ a ::-separated string denoting its collection tree address. """
py.builtin._reraise(failure[0], failure[1], failure[2]) return getattr(self, attrname) except py.builtin._sysex: raise except: failure = sys.exc_info() setattr(self, exattrname, failure) raise
""" return list of all parent collectors up to self, starting from root of collection tree. """
""" dynamically add a marker object to the node.
``marker`` can be a string or pytest.mark.* instance. """ from _pytest.mark import MarkDecorator if isinstance(marker, py.builtin._basestring): marker = MarkDecorator(marker) elif not isinstance(marker, MarkDecorator): raise ValueError("is not a string or pytest.mark.* Marker") self.keywords[marker.name] = marker
""" get a marker object from this node or None if the node doesn't have a marker with that name. """ val = self.keywords.get(name, None) if val is not None: from _pytest.mark import MarkInfo, MarkDecorator if isinstance(val, (MarkDecorator, MarkInfo)): return val
""" Return a set of all extra keywords in self and any parents.""" extra_keywords = set() item = self for item in self.listchain(): extra_keywords.update(item.extra_keyword_matches) return extra_keywords
return [x.name for x in self.listchain()]
""" register a function to be called when this node is finalized.
This method can only be called when this node is active in a setup chain, for example during self.setup(). """
""" get the next parent node (including ourself) which is an instance of the given class"""
pass
fm = self.session._fixturemanager if excinfo.errisinstance(fm.FixtureLookupError): return excinfo.value.formatrepr() tbfilter = True if self.config.option.fulltrace: style="long" else: self._prunetraceback(excinfo) tbfilter = False # prunetraceback already does it if style == "auto": style = "long" # XXX should excinfo.getrepr record all data and toterminal() process it? if style is None: if self.config.option.tbstyle == "short": style = "short" else: style = "long"
return excinfo.getrepr(funcargs=True, showlocals=self.config.option.showlocals, style=style, tbfilter=tbfilter)
""" Collector instances create children through collect() and thus iteratively build a tree. """
""" an error during collection, contains a custom message. """
""" returns a list of children (items and collectors) for this collection node. """ raise NotImplementedError("abstract")
""" represent a collection failure. """ if excinfo.errisinstance(self.CollectError): exc = excinfo.value return str(exc.args[0]) return self._repr_failure_py(excinfo, style="short")
""" internal helper method to cache results of calling collect(). """
if hasattr(self, 'fspath'): traceback = excinfo.traceback ntraceback = traceback.cut(path=self.fspath) if ntraceback == traceback: ntraceback = ntraceback.cut(excludepath=tracebackcutdir) excinfo.traceback = ntraceback.filter()
relpath = relpath.replace(os.sep, "/")
""" base class for collecting tests from a file. """
""" a basic test invocation item. Note that for a single function there might be multiple test invocation items. """
self._report_sections.append((when, key, content))
return self.fspath, None, ""
def location(self): # bestrelpath is a quite slow function
""" raised if matching cannot locate a matching names. """
""" signals an interrupted test run. """
config=config, session=self)
def pytest_collectstart(self): raise self.Interrupted(self.shouldstop)
def pytest_runtest_logreport(self, report): self.testsfailed += 1 maxfail = self.config.getvalue("maxfail") if maxfail and self.testsfailed >= maxfail: self.shouldstop = "stopping after %d failures" % ( self.testsfailed)
# check if we have the common case of running # hooks with all conftest.py filesall conftest.py # one or more conftests are not in use at this fspath proxy = FSHookProxy(fspath, pm, remove_mods) else: # all plugis are active for this fspath
config=self.config, items=items) finally:
errors = [] for arg, exc in self._notfound: line = "(no name %r in any of %r)" % (arg, exc.args[0]) errors.append("not found: %s\n%s" % (arg, line)) #XXX: test this raise pytest.UsageError(*errors) return rep.result else:
except NoMatch: # we are inside a make_report hook so # we cannot directly pass through the exception self._notfound.append((arg, sys.exc_info()[1]))
rec=self._recurse, bf=True, sort=True): else: assert path.check(file=1) for x in self.matchnodes(self._collectfile(path), names): yield x
return ()
return return False
mod = None path = [os.path.abspath('.')] + sys.path for name in x.split('.'): # ignore anything that's not a proper name here # else something like --pyargs will mess up '.' # since imp.find_module will actually sometimes work for it # but it's supposed to be considered a filesystem path # not a package if name_re.match(name) is None: return x try: fd, mod, type_ = imp.find_module(name, path) except ImportError: return x else: if fd is not None: fd.close()
if type_[2] != imp.PKG_DIRECTORY: path = [os.path.dirname(mod)] else: path = [mod] return mod
""" return (fspath, names) tuple after checking the file exists. """ arg = self._tryconvertpyarg(arg) if self.config.option.pyargs: msg = "file or package not found: " else: msg = "file not found: " raise pytest.UsageError(msg + arg)
self.trace("matchnodes", matching, names) self.trace.root.indent += 1 nodes = self._matchnodes(matching, names) num = len(nodes) self.trace("matchnodes finished -> ", num, "nodes") self.trace.root.indent -= 1 if num == 0: raise NoMatch(matching, names[:1]) return nodes
if not matching or not names: return matching name = names[0] assert name nextnames = names[1:] resultnodes = [] for node in matching: if isinstance(node, pytest.Item): if not names: resultnodes.append(node) continue assert isinstance(node, pytest.Collector) rep = collect_one_node(node) if rep.passed: has_matched = False for x in rep.result: # TODO: remove parametrized workaround once collection structure contains parametrization if x.name == name or x.name.split("[")[0] == name: resultnodes.extend(self.matchnodes([x], nextnames)) has_matched = True # XXX accept IDs that don't have "()" for class instances if not has_matched and len(rep.result) == 1 and x.name == "()": nextnames.insert(0, name) resultnodes.extend(self.matchnodes([x], nextnames)) node.ihook.pytest_collectreport(report=rep) return resultnodes
else: |