2010-11-06 18:38:53 +08:00
|
|
|
""" Python test discovery, setup and run of test functions. """
|
2008-08-16 23:26:59 +08:00
|
|
|
import py
|
2009-09-01 22:10:21 +08:00
|
|
|
import inspect
|
2010-07-04 23:06:50 +08:00
|
|
|
import sys
|
2010-10-07 17:59:00 +08:00
|
|
|
import pytest
|
2012-08-01 15:23:39 +08:00
|
|
|
from _pytest.main import getfslineno
|
2012-07-20 20:16:28 +08:00
|
|
|
from _pytest.monkeypatch import monkeypatch
|
2012-08-01 15:23:39 +08:00
|
|
|
from py._code.code import TerminalRepr
|
2008-08-16 23:26:59 +08:00
|
|
|
|
2010-11-13 18:10:45 +08:00
|
|
|
import _pytest
|
|
|
|
cutdir = py.path.local(_pytest.__file__).dirpath()
|
2010-10-10 19:48:49 +08:00
|
|
|
|
2012-10-05 16:21:35 +08:00
|
|
|
class FixtureFunctionMarker:
|
2012-10-12 20:52:36 +08:00
|
|
|
def __init__(self, scope, params, autouse=False):
|
2012-08-02 18:41:46 +08:00
|
|
|
self.scope = scope
|
|
|
|
self.params = params
|
2012-10-12 20:52:36 +08:00
|
|
|
self.autouse = autouse
|
2012-10-05 16:21:35 +08:00
|
|
|
|
2012-08-02 18:41:46 +08:00
|
|
|
def __call__(self, function):
|
2012-10-08 17:22:31 +08:00
|
|
|
if inspect.isclass(function):
|
|
|
|
raise ValueError("class fixtures not supported (may be in the future)")
|
2012-10-05 16:21:35 +08:00
|
|
|
function._pytestfixturefunction = self
|
2012-08-02 18:41:46 +08:00
|
|
|
return function
|
|
|
|
|
|
|
|
|
2012-10-12 20:52:36 +08:00
|
|
|
def fixture(scope="function", params=None, autouse=False):
|
2012-10-07 19:06:17 +08:00
|
|
|
""" (return a) decorator to mark a fixture factory function.
|
|
|
|
|
2012-10-08 14:34:21 +08:00
|
|
|
This decorator can be used (with or or without parameters) to define
|
2012-10-07 19:06:17 +08:00
|
|
|
a fixture function. The name of the fixture function can later be
|
|
|
|
referenced to cause its invocation ahead of running tests: test
|
|
|
|
modules or classes can use the pytest.mark.usefixtures(fixturename)
|
2012-10-08 14:34:21 +08:00
|
|
|
marker. Test functions can directly use fixture names as input
|
2012-10-07 03:03:55 +08:00
|
|
|
arguments in which case the fixture instance returned from the fixture
|
|
|
|
function will be injected.
|
2012-10-05 16:21:35 +08:00
|
|
|
|
|
|
|
:arg scope: the scope for which this fixture is shared, one of
|
2012-10-07 19:06:17 +08:00
|
|
|
"function" (default), "class", "module", "session".
|
|
|
|
|
2012-08-02 18:41:46 +08:00
|
|
|
:arg params: an optional list of parameters which will cause multiple
|
2012-10-07 19:06:17 +08:00
|
|
|
invocations of the fixture function and all of the tests
|
|
|
|
using it.
|
2012-10-07 03:03:55 +08:00
|
|
|
|
2012-10-12 20:52:36 +08:00
|
|
|
:arg autouse: if True, the fixture func is activated for all tests that
|
2012-10-07 03:03:55 +08:00
|
|
|
can see it. If False (the default) then an explicit
|
|
|
|
reference is needed to activate the fixture.
|
2012-08-02 18:41:46 +08:00
|
|
|
"""
|
2012-10-12 20:52:36 +08:00
|
|
|
if py.builtin.callable(scope) and params is None and autouse == False:
|
2012-10-07 03:03:55 +08:00
|
|
|
# direct decoration
|
2012-10-12 20:52:36 +08:00
|
|
|
return FixtureFunctionMarker("function", params, autouse)(scope)
|
2012-10-07 03:03:55 +08:00
|
|
|
else:
|
2012-10-12 20:52:36 +08:00
|
|
|
return FixtureFunctionMarker(scope, params, autouse=autouse)
|
2012-08-02 18:41:46 +08:00
|
|
|
|
2012-10-05 16:21:35 +08:00
|
|
|
defaultfuncargprefixmarker = fixture()
|
|
|
|
|
2012-06-25 23:35:33 +08:00
|
|
|
def cached_property(f):
|
|
|
|
"""returns a cached property that is calculated by function f.
|
|
|
|
taken from http://code.activestate.com/recipes/576563-cached-property/"""
|
|
|
|
def get(self):
|
|
|
|
try:
|
|
|
|
return self._property_cache[f]
|
|
|
|
except AttributeError:
|
|
|
|
self._property_cache = {}
|
|
|
|
x = self._property_cache[f] = f(self)
|
|
|
|
return x
|
|
|
|
except KeyError:
|
|
|
|
x = self._property_cache[f] = f(self)
|
|
|
|
return x
|
|
|
|
return property(get)
|
|
|
|
|
2012-07-16 16:46:44 +08:00
|
|
|
def pyobj_property(name):
|
|
|
|
def get(self):
|
|
|
|
node = self.getparent(getattr(pytest, name))
|
|
|
|
if node is not None:
|
|
|
|
return node.obj
|
|
|
|
doc = "python %s object this node was collected from (can be None)." % (
|
|
|
|
name.lower(),)
|
|
|
|
return property(get, None, None, doc)
|
|
|
|
|
2012-06-25 23:35:33 +08:00
|
|
|
|
2010-09-26 00:23:26 +08:00
|
|
|
def pytest_addoption(parser):
|
2010-11-07 05:17:33 +08:00
|
|
|
group = parser.getgroup("general")
|
2012-10-05 20:24:44 +08:00
|
|
|
group.addoption('--fixtures', '--fixtures',
|
|
|
|
action="store_true", dest="showfixtures", default=False,
|
|
|
|
help="show available fixtures, sorted by plugin appearance")
|
2012-10-06 01:20:40 +08:00
|
|
|
parser.addini("usefixtures", type="args", default=(),
|
|
|
|
help="list of default fixtures to be used with this project")
|
2010-11-25 05:01:04 +08:00
|
|
|
parser.addini("python_files", type="args",
|
|
|
|
default=('test_*.py', '*_test.py'),
|
|
|
|
help="glob-style file patterns for Python test module discovery")
|
|
|
|
parser.addini("python_classes", type="args", default=("Test",),
|
|
|
|
help="prefixes for Python test class discovery")
|
|
|
|
parser.addini("python_functions", type="args", default=("test",),
|
|
|
|
help="prefixes for Python test function and method discovery")
|
2010-09-26 00:23:26 +08:00
|
|
|
|
|
|
|
def pytest_cmdline_main(config):
|
2012-10-05 20:24:44 +08:00
|
|
|
if config.option.showfixtures:
|
|
|
|
showfixtures(config)
|
2010-09-26 00:23:26 +08:00
|
|
|
return 0
|
|
|
|
|
2011-11-17 19:09:21 +08:00
|
|
|
|
|
|
|
def pytest_generate_tests(metafunc):
|
|
|
|
try:
|
2012-10-06 17:34:06 +08:00
|
|
|
markers = metafunc.function.parametrize
|
2011-11-17 19:09:21 +08:00
|
|
|
except AttributeError:
|
|
|
|
return
|
2012-10-06 17:34:06 +08:00
|
|
|
for marker in markers:
|
|
|
|
metafunc.parametrize(*marker.args, **marker.kwargs)
|
2011-11-17 19:09:21 +08:00
|
|
|
|
|
|
|
def pytest_configure(config):
|
|
|
|
config.addinivalue_line("markers",
|
|
|
|
"parametrize(argnames, argvalues): call a test function multiple "
|
|
|
|
"times passing in multiple different argument value sets. Example: "
|
2011-11-19 02:32:11 +08:00
|
|
|
"@parametrize('arg1', [1,2]) would lead to two calls of the decorated "
|
2011-11-17 19:09:21 +08:00
|
|
|
"test function, one with arg1=1 and another with arg1=2."
|
|
|
|
)
|
|
|
|
|
2012-08-01 15:23:39 +08:00
|
|
|
def pytest_sessionstart(session):
|
2012-10-05 20:24:44 +08:00
|
|
|
session._fixturemanager = FixtureManager(session)
|
2011-11-17 19:09:21 +08:00
|
|
|
|
2010-11-22 06:17:59 +08:00
|
|
|
@pytest.mark.trylast
|
|
|
|
def pytest_namespace():
|
2010-11-06 06:37:31 +08:00
|
|
|
raises.Exception = pytest.fail.Exception
|
|
|
|
return {
|
2012-10-05 16:21:35 +08:00
|
|
|
'fixture': fixture,
|
2010-11-06 06:37:31 +08:00
|
|
|
'raises' : raises,
|
|
|
|
'collect': {
|
2010-10-07 17:59:00 +08:00
|
|
|
'Module': Module, 'Class': Class, 'Instance': Instance,
|
|
|
|
'Function': Function, 'Generator': Generator,
|
2012-10-05 20:24:44 +08:00
|
|
|
'_fillfuncargs': fillfixtures}
|
2010-11-06 06:37:31 +08:00
|
|
|
}
|
2010-09-26 00:23:26 +08:00
|
|
|
|
2012-10-05 20:24:44 +08:00
|
|
|
@fixture()
|
|
|
|
def pytestconfig(request):
|
2010-09-26 00:23:26 +08:00
|
|
|
""" the pytest config object with access to command line opts."""
|
|
|
|
return request.config
|
|
|
|
|
2012-06-25 23:35:33 +08:00
|
|
|
|
2010-09-26 00:23:26 +08:00
|
|
|
def pytest_pyfunc_call(__multicall__, pyfuncitem):
|
|
|
|
if not __multicall__.execute():
|
|
|
|
testfunction = pyfuncitem.obj
|
|
|
|
if pyfuncitem._isyieldedfunction():
|
|
|
|
testfunction(*pyfuncitem._args)
|
|
|
|
else:
|
2012-06-25 23:35:33 +08:00
|
|
|
try:
|
2012-10-05 20:24:44 +08:00
|
|
|
fixturenames = pyfuncitem.fixturenames
|
2012-06-25 23:35:33 +08:00
|
|
|
except AttributeError:
|
|
|
|
funcargs = pyfuncitem.funcargs
|
|
|
|
else:
|
|
|
|
funcargs = {}
|
2012-10-05 20:24:44 +08:00
|
|
|
for name in fixturenames:
|
2012-06-25 23:35:33 +08:00
|
|
|
funcargs[name] = pyfuncitem.funcargs[name]
|
2010-09-26 00:23:26 +08:00
|
|
|
testfunction(**funcargs)
|
|
|
|
|
2012-07-19 01:49:14 +08:00
|
|
|
def pytest_pyfunc_call(__multicall__, pyfuncitem):
|
|
|
|
if not __multicall__.execute():
|
|
|
|
testfunction = pyfuncitem.obj
|
|
|
|
if pyfuncitem._isyieldedfunction():
|
|
|
|
testfunction(*pyfuncitem._args)
|
|
|
|
else:
|
|
|
|
funcargs = pyfuncitem.funcargs
|
2012-10-05 16:21:35 +08:00
|
|
|
testargs = {}
|
|
|
|
for arg in getfuncargnames(testfunction):
|
|
|
|
testargs[arg] = funcargs[arg]
|
|
|
|
testfunction(**testargs)
|
2012-07-19 01:49:14 +08:00
|
|
|
|
2010-09-26 00:23:26 +08:00
|
|
|
def pytest_collect_file(path, parent):
|
|
|
|
ext = path.ext
|
|
|
|
pb = path.purebasename
|
2010-11-25 05:01:04 +08:00
|
|
|
if ext == ".py":
|
|
|
|
if not parent.session.isinitpath(path):
|
|
|
|
for pat in parent.config.getini('python_files'):
|
|
|
|
if path.fnmatch(pat):
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
return
|
2011-05-29 07:47:16 +08:00
|
|
|
return parent.ihook.pytest_pycollect_makemodule(
|
2010-11-06 16:58:04 +08:00
|
|
|
path=path, parent=parent)
|
2010-09-26 00:23:26 +08:00
|
|
|
|
|
|
|
def pytest_pycollect_makemodule(path, parent):
|
2010-10-14 00:41:53 +08:00
|
|
|
return Module(path, parent)
|
2010-09-26 00:23:26 +08:00
|
|
|
|
|
|
|
def pytest_pycollect_makeitem(__multicall__, collector, name, obj):
|
|
|
|
res = __multicall__.execute()
|
|
|
|
if res is not None:
|
|
|
|
return res
|
2011-03-16 23:36:18 +08:00
|
|
|
if inspect.isclass(obj):
|
2010-11-17 19:21:24 +08:00
|
|
|
#if hasattr(collector.obj, 'unittest'):
|
|
|
|
# return # we assume it's a mixin class for a TestCase derived one
|
2011-03-16 23:36:18 +08:00
|
|
|
if collector.classnamefilter(name):
|
|
|
|
if not hasinit(obj):
|
|
|
|
Class = collector._getcustomclass("Class")
|
|
|
|
return Class(name, parent=collector)
|
2010-09-26 00:23:26 +08:00
|
|
|
elif collector.funcnamefilter(name) and hasattr(obj, '__call__'):
|
|
|
|
if is_generator(obj):
|
2010-10-14 00:41:53 +08:00
|
|
|
return Generator(name, parent=collector)
|
2010-09-26 00:23:26 +08:00
|
|
|
else:
|
2012-10-06 17:34:06 +08:00
|
|
|
return list(collector._genfunctions(name, obj))
|
2010-09-26 00:23:26 +08:00
|
|
|
|
|
|
|
def is_generator(func):
|
|
|
|
try:
|
|
|
|
return py.code.getrawcode(func).co_flags & 32 # generator function
|
|
|
|
except AttributeError: # builtin functions have no bytecode
|
|
|
|
# assume them to not be generators
|
|
|
|
return False
|
|
|
|
|
2012-07-16 16:46:44 +08:00
|
|
|
class PyobjContext(object):
|
|
|
|
module = pyobj_property("Module")
|
|
|
|
cls = pyobj_property("Class")
|
|
|
|
instance = pyobj_property("Instance")
|
2012-06-25 23:35:33 +08:00
|
|
|
|
2012-07-19 01:49:14 +08:00
|
|
|
class PyobjMixin(PyobjContext):
|
2010-07-27 03:15:15 +08:00
|
|
|
def obj():
|
2008-08-16 23:26:59 +08:00
|
|
|
def fget(self):
|
2010-07-27 03:15:15 +08:00
|
|
|
try:
|
|
|
|
return self._obj
|
|
|
|
except AttributeError:
|
|
|
|
self._obj = obj = self._getobj()
|
|
|
|
return obj
|
|
|
|
def fset(self, value):
|
|
|
|
self._obj = value
|
|
|
|
return property(fget, fset, None, "underlying python object")
|
2008-08-16 23:26:59 +08:00
|
|
|
obj = obj()
|
|
|
|
|
|
|
|
def _getobj(self):
|
|
|
|
return getattr(self.parent.obj, self.name)
|
|
|
|
|
2009-02-27 18:18:27 +08:00
|
|
|
def getmodpath(self, stopatmodule=True, includemodule=False):
|
2008-08-16 23:26:59 +08:00
|
|
|
""" return python path relative to the containing module. """
|
|
|
|
chain = self.listchain()
|
|
|
|
chain.reverse()
|
|
|
|
parts = []
|
|
|
|
for node in chain:
|
|
|
|
if isinstance(node, Instance):
|
|
|
|
continue
|
2010-07-27 03:15:15 +08:00
|
|
|
name = node.name
|
2008-09-02 22:31:42 +08:00
|
|
|
if isinstance(node, Module):
|
|
|
|
assert name.endswith(".py")
|
|
|
|
name = name[:-3]
|
2009-02-27 18:18:27 +08:00
|
|
|
if stopatmodule:
|
|
|
|
if includemodule:
|
|
|
|
parts.append(name)
|
|
|
|
break
|
2008-09-02 22:31:42 +08:00
|
|
|
parts.append(name)
|
2008-08-16 23:26:59 +08:00
|
|
|
parts.reverse()
|
|
|
|
s = ".".join(parts)
|
|
|
|
return s.replace(".[", "[")
|
|
|
|
|
2009-05-12 19:39:09 +08:00
|
|
|
def _getfslineno(self):
|
2012-07-20 20:16:28 +08:00
|
|
|
return getfslineno(self.obj)
|
2008-08-16 23:26:59 +08:00
|
|
|
|
2009-05-12 23:02:22 +08:00
|
|
|
def reportinfo(self):
|
2010-11-07 06:45:48 +08:00
|
|
|
# XXX caching?
|
2010-11-05 06:21:23 +08:00
|
|
|
obj = self.obj
|
|
|
|
if hasattr(obj, 'compat_co_firstlineno'):
|
|
|
|
# nose compatibility
|
|
|
|
fspath = sys.modules[obj.__module__].__file__
|
|
|
|
if fspath.endswith(".pyc"):
|
|
|
|
fspath = fspath[:-1]
|
|
|
|
lineno = obj.compat_co_firstlineno
|
|
|
|
modpath = obj.__module__
|
|
|
|
else:
|
2012-07-20 20:16:28 +08:00
|
|
|
fspath, lineno = getfslineno(obj)
|
2010-11-05 06:21:23 +08:00
|
|
|
modpath = self.getmodpath()
|
2011-12-14 18:56:51 +08:00
|
|
|
assert isinstance(lineno, int)
|
2010-07-27 03:15:15 +08:00
|
|
|
return fspath, lineno, modpath
|
2008-08-16 23:26:59 +08:00
|
|
|
|
2012-07-16 16:46:44 +08:00
|
|
|
class PyCollector(PyobjMixin, pytest.Collector):
|
2012-10-16 19:48:00 +08:00
|
|
|
def _fixturemapper():
|
|
|
|
def get(self):
|
|
|
|
try:
|
|
|
|
return self._fixturemapper_memo
|
|
|
|
except AttributeError:
|
|
|
|
self._fixturemapper_memo = FixtureMapper(self, funcargs=False)
|
|
|
|
return self._fixturemapper_memo
|
|
|
|
def set(self, val):
|
|
|
|
assert not hasattr(self, "_fixturemapper_memo")
|
|
|
|
self._fixturemapper_memo = val
|
|
|
|
return property(get, set)
|
|
|
|
_fixturemapper = _fixturemapper()
|
2010-07-27 03:15:15 +08:00
|
|
|
|
|
|
|
def funcnamefilter(self, name):
|
2010-11-25 05:01:04 +08:00
|
|
|
for prefix in self.config.getini("python_functions"):
|
|
|
|
if name.startswith(prefix):
|
|
|
|
return True
|
2011-01-18 19:47:31 +08:00
|
|
|
|
2010-07-27 03:15:15 +08:00
|
|
|
def classnamefilter(self, name):
|
2010-11-25 05:01:04 +08:00
|
|
|
for prefix in self.config.getini("python_classes"):
|
|
|
|
if name.startswith(prefix):
|
|
|
|
return True
|
2008-08-16 23:26:59 +08:00
|
|
|
|
2008-09-02 16:58:14 +08:00
|
|
|
def collect(self):
|
2008-08-16 23:26:59 +08:00
|
|
|
# NB. we avoid random getattrs and peek in the __dict__ instead
|
2010-10-26 05:08:56 +08:00
|
|
|
# (XXX originally introduced from a PyPy need, still true?)
|
2008-08-16 23:26:59 +08:00
|
|
|
dicts = [getattr(self.obj, '__dict__', {})]
|
2009-09-01 22:10:21 +08:00
|
|
|
for basecls in inspect.getmro(self.obj.__class__):
|
2008-08-16 23:26:59 +08:00
|
|
|
dicts.append(basecls.__dict__)
|
|
|
|
seen = {}
|
2010-01-16 00:38:09 +08:00
|
|
|
l = []
|
2008-08-16 23:26:59 +08:00
|
|
|
for dic in dicts:
|
|
|
|
for name, obj in dic.items():
|
|
|
|
if name in seen:
|
|
|
|
continue
|
|
|
|
seen[name] = True
|
2009-10-22 00:44:12 +08:00
|
|
|
if name[0] != "_":
|
|
|
|
res = self.makeitem(name, obj)
|
2010-01-16 00:50:02 +08:00
|
|
|
if res is None:
|
|
|
|
continue
|
|
|
|
if not isinstance(res, list):
|
|
|
|
res = [res]
|
|
|
|
l.extend(res)
|
2010-01-16 00:38:09 +08:00
|
|
|
l.sort(key=lambda item: item.reportinfo()[:2])
|
|
|
|
return l
|
2008-08-16 23:26:59 +08:00
|
|
|
|
2009-02-27 18:18:27 +08:00
|
|
|
def makeitem(self, name, obj):
|
2009-12-30 09:36:58 +08:00
|
|
|
return self.ihook.pytest_pycollect_makeitem(
|
2009-05-08 05:12:17 +08:00
|
|
|
collector=self, name=name, obj=obj)
|
2009-05-12 01:23:57 +08:00
|
|
|
|
|
|
|
def _genfunctions(self, name, funcobj):
|
2009-05-20 00:13:33 +08:00
|
|
|
module = self.getparent(Module).obj
|
|
|
|
clscol = self.getparent(Class)
|
2009-05-12 01:23:57 +08:00
|
|
|
cls = clscol and clscol.obj or None
|
2011-12-29 00:47:08 +08:00
|
|
|
transfer_markers(funcobj, cls, module)
|
2012-10-16 19:48:00 +08:00
|
|
|
if not hasattr(self, "_fixturemapper_memo"):
|
2012-10-16 19:47:59 +08:00
|
|
|
self._fixturemapper = FixtureMapper(self)
|
|
|
|
fixtureinfo = self._fixturemapper.getfixtureinfo(funcobj, cls)
|
|
|
|
metafunc = Metafunc(funcobj, fixtureinfo, self.config,
|
|
|
|
cls=cls, module=module)
|
2009-12-30 09:36:58 +08:00
|
|
|
gentesthook = self.config.hook.pytest_generate_tests
|
2010-11-25 05:22:52 +08:00
|
|
|
extra = [module]
|
|
|
|
if cls is not None:
|
|
|
|
extra.append(cls())
|
|
|
|
plugins = self.getplugins() + extra
|
2009-12-30 21:05:41 +08:00
|
|
|
gentesthook.pcall(plugins, metafunc=metafunc)
|
2011-03-05 21:16:27 +08:00
|
|
|
Function = self._getcustomclass("Function")
|
2012-07-19 15:20:14 +08:00
|
|
|
if not metafunc._calls:
|
2012-10-06 17:34:06 +08:00
|
|
|
yield Function(name, parent=self)
|
|
|
|
else:
|
|
|
|
for callspec in metafunc._calls:
|
|
|
|
subname = "%s[%s]" %(name, callspec.id)
|
|
|
|
yield Function(name=subname, parent=self,
|
|
|
|
callspec=callspec, callobj=funcobj,
|
|
|
|
keywords={callspec.id:True})
|
2010-07-27 03:15:15 +08:00
|
|
|
|
2012-10-16 19:47:59 +08:00
|
|
|
class FixtureMapper:
|
2012-10-16 19:48:00 +08:00
|
|
|
def __init__(self, node, funcargs=True):
|
2012-10-16 19:47:59 +08:00
|
|
|
self.node = node
|
|
|
|
self.fm = node.session._fixturemanager
|
|
|
|
self._name2fixtureinfo = {}
|
2012-10-16 19:48:00 +08:00
|
|
|
self.hasfuncargs = funcargs
|
2012-10-16 19:47:59 +08:00
|
|
|
|
|
|
|
def getfixtureinfo(self, func, cls):
|
|
|
|
try:
|
|
|
|
return self._name2fixtureinfo[func]
|
|
|
|
except KeyError:
|
|
|
|
pass
|
2012-10-16 19:48:00 +08:00
|
|
|
if self.hasfuncargs:
|
|
|
|
argnames = getfuncargnames(func, int(cls is not None))
|
|
|
|
else:
|
|
|
|
argnames = ()
|
2012-10-16 19:47:59 +08:00
|
|
|
usefixtures = getattr(func, "usefixtures", None)
|
|
|
|
if usefixtures is not None:
|
|
|
|
argnames = usefixtures.args + argnames
|
|
|
|
names_closure, arg2fixturedeflist = self.fm.getfixtureclosure(
|
|
|
|
argnames, self.node)
|
|
|
|
fixtureinfo = FuncFixtureInfo(names_closure, arg2fixturedeflist)
|
|
|
|
self._name2fixtureinfo[func] = fixtureinfo
|
|
|
|
return fixtureinfo
|
|
|
|
|
|
|
|
class FuncFixtureInfo:
|
|
|
|
def __init__(self, names_closure, name2fixturedeflist):
|
|
|
|
self.names_closure = names_closure
|
|
|
|
self.name2fixturedeflist = name2fixturedeflist
|
|
|
|
|
2011-12-29 00:47:08 +08:00
|
|
|
def transfer_markers(funcobj, cls, mod):
|
2011-12-28 23:47:19 +08:00
|
|
|
# XXX this should rather be code in the mark plugin or the mark
|
|
|
|
# plugin should merge with the python plugin.
|
2011-12-29 00:47:08 +08:00
|
|
|
for holder in (cls, mod):
|
2011-12-28 23:47:19 +08:00
|
|
|
try:
|
|
|
|
pytestmark = holder.pytestmark
|
|
|
|
except AttributeError:
|
|
|
|
continue
|
|
|
|
if isinstance(pytestmark, list):
|
|
|
|
for mark in pytestmark:
|
2011-12-29 00:47:08 +08:00
|
|
|
mark(funcobj)
|
2011-12-28 23:47:19 +08:00
|
|
|
else:
|
2011-12-29 00:47:08 +08:00
|
|
|
pytestmark(funcobj)
|
2011-03-05 21:16:27 +08:00
|
|
|
|
2012-07-16 16:46:44 +08:00
|
|
|
class Module(pytest.File, PyCollector):
|
2012-06-25 23:35:33 +08:00
|
|
|
""" Collector for test classes and functions. """
|
2008-08-16 23:26:59 +08:00
|
|
|
def _getobj(self):
|
2012-09-24 17:36:24 +08:00
|
|
|
return self._memoizedcall('_obj', self._importtestmodule)
|
2009-02-27 18:18:27 +08:00
|
|
|
|
2012-07-20 20:16:28 +08:00
|
|
|
def collect(self):
|
2012-10-05 20:24:44 +08:00
|
|
|
self.session._fixturemanager._parsefactories(self.obj, self.nodeid)
|
2012-07-20 20:16:28 +08:00
|
|
|
return super(Module, self).collect()
|
|
|
|
|
2009-02-27 18:18:27 +08:00
|
|
|
def _importtestmodule(self):
|
2010-07-27 03:15:15 +08:00
|
|
|
# we assume we are only called once per module
|
2010-07-04 23:06:50 +08:00
|
|
|
try:
|
2011-06-29 10:13:12 +08:00
|
|
|
mod = self.fspath.pyimport(ensuresyspath=True)
|
2010-07-04 23:06:50 +08:00
|
|
|
except SyntaxError:
|
|
|
|
excinfo = py.code.ExceptionInfo()
|
|
|
|
raise self.CollectError(excinfo.getrepr(style="short"))
|
|
|
|
except self.fspath.ImportMismatchError:
|
|
|
|
e = sys.exc_info()[1]
|
|
|
|
raise self.CollectError(
|
|
|
|
"import file mismatch:\n"
|
2010-07-27 03:15:15 +08:00
|
|
|
"imported module %r has this __file__ attribute:\n"
|
2010-07-04 23:06:50 +08:00
|
|
|
" %s\n"
|
|
|
|
"which is not the same as the test file we want to collect:\n"
|
|
|
|
" %s\n"
|
2011-12-20 20:20:59 +08:00
|
|
|
"HINT: remove __pycache__ / .pyc files and/or use a "
|
|
|
|
"unique basename for your test file modules"
|
2010-07-04 23:06:50 +08:00
|
|
|
% e.args
|
|
|
|
)
|
2009-02-27 18:18:27 +08:00
|
|
|
#print "imported test module", mod
|
2009-04-09 22:03:09 +08:00
|
|
|
self.config.pluginmanager.consider_module(mod)
|
2009-02-27 18:18:27 +08:00
|
|
|
return mod
|
2008-08-16 23:26:59 +08:00
|
|
|
|
2010-07-27 03:15:15 +08:00
|
|
|
def setup(self):
|
2012-08-13 19:37:14 +08:00
|
|
|
setup_module = xunitsetup(self.obj, "setup_module")
|
|
|
|
if setup_module is not None:
|
2009-10-23 22:17:06 +08:00
|
|
|
#XXX: nose compat hack, move to nose plugin
|
2010-10-07 17:59:00 +08:00
|
|
|
# if it takes a positional arg, its probably a pytest style one
|
2009-10-23 22:17:06 +08:00
|
|
|
# so we pass the current module object
|
2012-08-13 19:37:14 +08:00
|
|
|
if inspect.getargspec(setup_module)[0]:
|
|
|
|
setup_module(self.obj)
|
2009-10-23 22:17:06 +08:00
|
|
|
else:
|
2012-08-13 19:37:14 +08:00
|
|
|
setup_module()
|
2008-08-16 23:26:59 +08:00
|
|
|
|
2010-07-27 03:15:15 +08:00
|
|
|
def teardown(self):
|
2012-08-13 19:37:14 +08:00
|
|
|
teardown_module = xunitsetup(self.obj, 'teardown_module')
|
|
|
|
if teardown_module is not None:
|
2009-10-23 22:17:06 +08:00
|
|
|
#XXX: nose compat hack, move to nose plugin
|
|
|
|
# if it takes a positional arg, its probably a py.test style one
|
|
|
|
# so we pass the current module object
|
2012-08-13 19:37:14 +08:00
|
|
|
if inspect.getargspec(teardown_module)[0]:
|
|
|
|
teardown_module(self.obj)
|
2009-10-23 22:17:06 +08:00
|
|
|
else:
|
2012-08-13 19:37:14 +08:00
|
|
|
teardown_module()
|
2008-08-16 23:26:59 +08:00
|
|
|
|
2012-07-16 16:46:44 +08:00
|
|
|
class Class(PyCollector):
|
2012-06-25 23:35:33 +08:00
|
|
|
""" Collector for test methods. """
|
2008-09-02 16:58:14 +08:00
|
|
|
def collect(self):
|
2011-03-05 21:16:27 +08:00
|
|
|
return [self._getcustomclass("Instance")(name="()", parent=self)]
|
2008-08-16 23:26:59 +08:00
|
|
|
|
2010-07-27 03:15:15 +08:00
|
|
|
def setup(self):
|
2012-08-13 19:37:14 +08:00
|
|
|
setup_class = xunitsetup(self.obj, 'setup_class')
|
2010-07-27 03:15:15 +08:00
|
|
|
if setup_class is not None:
|
|
|
|
setup_class = getattr(setup_class, 'im_func', setup_class)
|
2012-05-07 05:03:16 +08:00
|
|
|
setup_class = getattr(setup_class, '__func__', setup_class)
|
2010-07-27 03:15:15 +08:00
|
|
|
setup_class(self.obj)
|
|
|
|
|
|
|
|
def teardown(self):
|
2012-08-13 19:37:14 +08:00
|
|
|
teardown_class = xunitsetup(self.obj, 'teardown_class')
|
2010-07-27 03:15:15 +08:00
|
|
|
if teardown_class is not None:
|
|
|
|
teardown_class = getattr(teardown_class, 'im_func', teardown_class)
|
2012-05-07 05:03:16 +08:00
|
|
|
teardown_class = getattr(teardown_class, '__func__', teardown_class)
|
2010-07-27 03:15:15 +08:00
|
|
|
teardown_class(self.obj)
|
|
|
|
|
2012-07-16 16:46:44 +08:00
|
|
|
class Instance(PyCollector):
|
2010-07-27 03:15:15 +08:00
|
|
|
def _getobj(self):
|
2012-07-20 20:16:28 +08:00
|
|
|
obj = self.parent.obj()
|
|
|
|
return obj
|
|
|
|
|
|
|
|
def collect(self):
|
2012-10-05 20:24:44 +08:00
|
|
|
self.session._fixturemanager._parsefactories(self.obj, self.nodeid)
|
2012-07-20 20:16:28 +08:00
|
|
|
return super(Instance, self).collect()
|
2010-09-26 00:23:26 +08:00
|
|
|
|
2010-07-27 03:15:15 +08:00
|
|
|
def newinstance(self):
|
2008-08-16 23:26:59 +08:00
|
|
|
self.obj = self._getobj()
|
|
|
|
return self.obj
|
|
|
|
|
|
|
|
class FunctionMixin(PyobjMixin):
|
|
|
|
""" mixin for the code common to Function and Generator.
|
|
|
|
"""
|
2012-07-19 01:49:14 +08:00
|
|
|
|
2010-07-27 03:15:15 +08:00
|
|
|
def setup(self):
|
2008-08-16 23:26:59 +08:00
|
|
|
""" perform setup for this test function. """
|
2011-01-14 20:30:36 +08:00
|
|
|
if hasattr(self, '_preservedparent'):
|
|
|
|
obj = self._preservedparent
|
|
|
|
elif isinstance(self.parent, Instance):
|
2008-08-16 23:26:59 +08:00
|
|
|
obj = self.parent.newinstance()
|
|
|
|
self.obj = self._getobj()
|
|
|
|
else:
|
2010-07-27 03:15:15 +08:00
|
|
|
obj = self.parent.obj
|
2011-03-03 01:03:43 +08:00
|
|
|
if inspect.ismethod(self.obj):
|
|
|
|
name = 'setup_method'
|
|
|
|
else:
|
|
|
|
name = 'setup_function'
|
2012-08-13 19:37:14 +08:00
|
|
|
setup_func_or_method = xunitsetup(obj, name)
|
2010-07-27 03:15:15 +08:00
|
|
|
if setup_func_or_method is not None:
|
|
|
|
setup_func_or_method(self.obj)
|
2008-08-16 23:26:59 +08:00
|
|
|
|
2010-07-27 03:15:15 +08:00
|
|
|
def teardown(self):
|
2008-08-16 23:26:59 +08:00
|
|
|
""" perform teardown for this test function. """
|
2009-09-01 22:10:21 +08:00
|
|
|
if inspect.ismethod(self.obj):
|
2010-07-27 03:15:15 +08:00
|
|
|
name = 'teardown_method'
|
|
|
|
else:
|
|
|
|
name = 'teardown_function'
|
|
|
|
obj = self.parent.obj
|
2012-08-13 19:37:14 +08:00
|
|
|
teardown_func_or_meth = xunitsetup(obj, name)
|
2010-07-27 03:15:15 +08:00
|
|
|
if teardown_func_or_meth is not None:
|
|
|
|
teardown_func_or_meth(self.obj)
|
2008-08-16 23:26:59 +08:00
|
|
|
|
2010-11-06 06:37:31 +08:00
|
|
|
def _prunetraceback(self, excinfo):
|
2010-07-27 03:15:15 +08:00
|
|
|
if hasattr(self, '_obj') and not self.config.option.fulltrace:
|
|
|
|
code = py.code.Code(self.obj)
|
|
|
|
path, firstlineno = code.path, code.firstlineno
|
2010-11-06 06:37:31 +08:00
|
|
|
traceback = excinfo.traceback
|
2008-08-16 23:26:59 +08:00
|
|
|
ntraceback = traceback.cut(path=path, firstlineno=firstlineno)
|
|
|
|
if ntraceback == traceback:
|
|
|
|
ntraceback = ntraceback.cut(path=path)
|
2009-03-01 19:24:52 +08:00
|
|
|
if ntraceback == traceback:
|
2010-10-10 19:48:49 +08:00
|
|
|
ntraceback = ntraceback.cut(excludepath=cutdir)
|
2010-11-06 06:37:31 +08:00
|
|
|
excinfo.traceback = ntraceback.filter()
|
2008-08-16 23:26:59 +08:00
|
|
|
|
2010-05-22 22:18:24 +08:00
|
|
|
def _repr_failure_py(self, excinfo, style="long"):
|
2010-11-24 23:43:55 +08:00
|
|
|
if excinfo.errisinstance(pytest.fail.Exception):
|
|
|
|
if not excinfo.value.pytrace:
|
|
|
|
return str(excinfo.value)
|
2010-07-27 03:15:15 +08:00
|
|
|
return super(FunctionMixin, self)._repr_failure_py(excinfo,
|
2010-05-22 22:18:24 +08:00
|
|
|
style=style)
|
2010-02-04 23:01:02 +08:00
|
|
|
|
2009-07-26 00:09:01 +08:00
|
|
|
def repr_failure(self, excinfo, outerr=None):
|
|
|
|
assert outerr is None, "XXX outerr usage is deprecated"
|
2010-07-27 03:15:15 +08:00
|
|
|
return self._repr_failure_py(excinfo,
|
2010-11-01 06:28:31 +08:00
|
|
|
style=self.config.option.tbstyle)
|
2008-08-16 23:26:59 +08:00
|
|
|
|
2011-11-19 00:01:29 +08:00
|
|
|
|
2012-07-16 16:46:44 +08:00
|
|
|
class Generator(FunctionMixin, PyCollector):
|
2008-09-02 16:58:14 +08:00
|
|
|
def collect(self):
|
2010-07-27 03:15:15 +08:00
|
|
|
# test generators are seen as collectors but they also
|
|
|
|
# invoke setup/teardown on popular request
|
2009-05-07 21:44:56 +08:00
|
|
|
# (induced by the common "test_*" naming shared with normal tests)
|
2011-05-27 06:08:56 +08:00
|
|
|
self.session._setupstate.prepare(self)
|
2011-01-14 20:30:36 +08:00
|
|
|
# see FunctionMixin.setup and test_setupstate_is_preserved_134
|
|
|
|
self._preservedparent = self.parent.obj
|
2008-09-02 16:58:14 +08:00
|
|
|
l = []
|
2009-03-19 22:34:33 +08:00
|
|
|
seen = {}
|
2010-07-27 03:15:15 +08:00
|
|
|
for i, x in enumerate(self.obj()):
|
2008-11-26 00:10:16 +08:00
|
|
|
name, call, args = self.getcallargs(x)
|
2010-07-27 03:15:15 +08:00
|
|
|
if not py.builtin.callable(call):
|
2008-08-16 23:26:59 +08:00
|
|
|
raise TypeError("%r yielded non callable test %r" %(self.obj, call,))
|
2008-11-26 00:10:16 +08:00
|
|
|
if name is None:
|
|
|
|
name = "[%d]" % i
|
|
|
|
else:
|
|
|
|
name = "['%s']" % name
|
2009-03-19 22:34:33 +08:00
|
|
|
if name in seen:
|
|
|
|
raise ValueError("%r generated tests with non-unique name %r" %(self, name))
|
|
|
|
seen[name] = True
|
2011-01-18 19:47:31 +08:00
|
|
|
l.append(self.Function(name, self, args=args, callobj=call))
|
2008-09-02 16:58:14 +08:00
|
|
|
return l
|
2010-07-27 03:15:15 +08:00
|
|
|
|
2008-08-16 23:26:59 +08:00
|
|
|
def getcallargs(self, obj):
|
2008-11-26 00:10:16 +08:00
|
|
|
if not isinstance(obj, (tuple, list)):
|
|
|
|
obj = (obj,)
|
|
|
|
# explict naming
|
2009-08-29 22:40:03 +08:00
|
|
|
if isinstance(obj[0], py.builtin._basestring):
|
2008-11-26 00:10:16 +08:00
|
|
|
name = obj[0]
|
|
|
|
obj = obj[1:]
|
2008-08-16 23:26:59 +08:00
|
|
|
else:
|
2008-11-26 00:10:16 +08:00
|
|
|
name = None
|
|
|
|
call, args = obj[0], obj[1:]
|
2010-07-27 03:15:15 +08:00
|
|
|
return name, call, args
|
|
|
|
|
2008-08-16 23:26:59 +08:00
|
|
|
|
2009-08-07 00:15:21 +08:00
|
|
|
def hasinit(obj):
|
|
|
|
init = getattr(obj, '__init__', None)
|
|
|
|
if init:
|
2010-05-09 18:27:04 +08:00
|
|
|
if init != object.__init__:
|
2009-08-07 00:15:21 +08:00
|
|
|
return True
|
2010-09-26 00:23:26 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
2012-10-05 20:24:44 +08:00
|
|
|
def fillfixtures(function):
|
2012-10-01 15:23:39 +08:00
|
|
|
""" fill missing funcargs for a test function. """
|
|
|
|
if getattr(function, "_args", None) is None: # not a yielded function
|
2012-07-19 01:49:14 +08:00
|
|
|
try:
|
|
|
|
request = function._request
|
|
|
|
except AttributeError:
|
2012-10-05 20:24:44 +08:00
|
|
|
request = function._request = FixtureRequest(function)
|
|
|
|
request._fillfixtures()
|
2012-07-19 01:49:14 +08:00
|
|
|
|
2010-09-26 00:23:26 +08:00
|
|
|
_notexists = object()
|
2011-11-17 19:09:21 +08:00
|
|
|
|
|
|
|
class CallSpec2(object):
|
|
|
|
def __init__(self, metafunc):
|
|
|
|
self.metafunc = metafunc
|
|
|
|
self.funcargs = {}
|
|
|
|
self._idlist = []
|
|
|
|
self.params = {}
|
|
|
|
self._globalid = _notexists
|
|
|
|
self._globalid_args = set()
|
|
|
|
self._globalparam = _notexists
|
2012-07-30 16:46:03 +08:00
|
|
|
self._arg2scopenum = {} # used for sorting parametrized resources
|
2011-11-17 19:09:21 +08:00
|
|
|
|
|
|
|
def copy(self, metafunc):
|
|
|
|
cs = CallSpec2(self.metafunc)
|
|
|
|
cs.funcargs.update(self.funcargs)
|
|
|
|
cs.params.update(self.params)
|
2012-07-30 16:46:03 +08:00
|
|
|
cs._arg2scopenum.update(self._arg2scopenum)
|
2011-11-17 19:09:21 +08:00
|
|
|
cs._idlist = list(self._idlist)
|
|
|
|
cs._globalid = self._globalid
|
|
|
|
cs._globalid_args = self._globalid_args
|
|
|
|
cs._globalparam = self._globalparam
|
|
|
|
return cs
|
|
|
|
|
|
|
|
def _checkargnotcontained(self, arg):
|
|
|
|
if arg in self.params or arg in self.funcargs:
|
|
|
|
raise ValueError("duplicate %r" %(arg,))
|
|
|
|
|
|
|
|
def getparam(self, name):
|
|
|
|
try:
|
|
|
|
return self.params[name]
|
|
|
|
except KeyError:
|
|
|
|
if self._globalparam is _notexists:
|
|
|
|
raise ValueError(name)
|
|
|
|
return self._globalparam
|
|
|
|
|
|
|
|
@property
|
|
|
|
def id(self):
|
2011-12-28 23:47:19 +08:00
|
|
|
return "-".join(map(str, filter(None, self._idlist)))
|
2011-11-17 19:09:21 +08:00
|
|
|
|
2012-07-30 16:46:03 +08:00
|
|
|
def setmulti(self, valtype, argnames, valset, id, scopenum=0):
|
2011-11-17 19:09:21 +08:00
|
|
|
for arg,val in zip(argnames, valset):
|
|
|
|
self._checkargnotcontained(arg)
|
|
|
|
getattr(self, valtype)[arg] = val
|
2012-09-21 15:39:54 +08:00
|
|
|
# we want self.params to be always set because of
|
|
|
|
# parametrize_sorted() which groups tests by params/scope
|
|
|
|
if valtype == "funcargs":
|
|
|
|
self.params[arg] = id
|
2012-07-30 16:46:03 +08:00
|
|
|
self._arg2scopenum[arg] = scopenum
|
2012-10-06 17:34:06 +08:00
|
|
|
if val == _notexists:
|
|
|
|
self._emptyparamspecified = True
|
2011-11-17 19:09:21 +08:00
|
|
|
self._idlist.append(id)
|
|
|
|
|
|
|
|
def setall(self, funcargs, id, param):
|
|
|
|
for x in funcargs:
|
|
|
|
self._checkargnotcontained(x)
|
|
|
|
self.funcargs.update(funcargs)
|
|
|
|
if id is not _notexists:
|
|
|
|
self._idlist.append(id)
|
2010-09-26 00:23:26 +08:00
|
|
|
if param is not _notexists:
|
2011-11-17 19:09:21 +08:00
|
|
|
assert self._globalparam is _notexists
|
|
|
|
self._globalparam = param
|
|
|
|
|
2010-09-26 00:23:26 +08:00
|
|
|
|
2012-10-05 20:24:44 +08:00
|
|
|
class FuncargnamesCompatAttr:
|
|
|
|
""" helper class so that Metafunc, Function and FixtureRequest
|
|
|
|
don't need to each define the "funcargnames" compatibility attribute.
|
|
|
|
"""
|
|
|
|
@property
|
|
|
|
def funcargnames(self):
|
|
|
|
""" alias attribute for ``fixturenames`` for pre-2.3 compatibility"""
|
|
|
|
return self.fixturenames
|
|
|
|
|
|
|
|
class Metafunc(FuncargnamesCompatAttr):
|
2012-10-16 19:47:59 +08:00
|
|
|
def __init__(self, function, fixtureinfo, config, cls=None, module=None):
|
|
|
|
self.config = config
|
2010-09-26 00:23:26 +08:00
|
|
|
self.module = module
|
|
|
|
self.function = function
|
2012-10-16 19:47:59 +08:00
|
|
|
self.fixturenames = fixtureinfo.names_closure
|
|
|
|
self._arg2fixturedeflist = fixtureinfo.name2fixturedeflist
|
2010-09-26 00:23:26 +08:00
|
|
|
self.cls = cls
|
|
|
|
self.module = module
|
|
|
|
self._calls = []
|
|
|
|
self._ids = py.builtin.set()
|
|
|
|
|
2012-07-30 16:46:03 +08:00
|
|
|
def parametrize(self, argnames, argvalues, indirect=False, ids=None,
|
2012-10-07 03:01:13 +08:00
|
|
|
scope=None):
|
2011-12-05 18:10:48 +08:00
|
|
|
""" Add new invocations to the underlying test function using the list
|
|
|
|
of argvalues for the given argnames. Parametrization is performed
|
2011-11-20 07:45:05 +08:00
|
|
|
during the collection phase. If you need to setup expensive resources
|
2012-10-09 20:35:17 +08:00
|
|
|
see about setting indirect=True to do it rather at test setup time.
|
2011-11-17 19:09:21 +08:00
|
|
|
|
|
|
|
:arg argnames: an argument name or a list of argument names
|
|
|
|
|
2011-11-20 07:45:05 +08:00
|
|
|
:arg argvalues: a list of values for the argname or a list of tuples of
|
|
|
|
values for the list of argument names.
|
2011-11-17 19:09:21 +08:00
|
|
|
|
2012-10-09 20:35:17 +08:00
|
|
|
:arg indirect: if True each argvalue corresponding to an argname will
|
|
|
|
be passed as request.param to its respective argname fixture
|
|
|
|
function so that it can perform more expensive setups during the
|
|
|
|
setup phase of a test rather than at collection time.
|
2011-11-17 19:09:21 +08:00
|
|
|
|
2011-12-05 18:10:48 +08:00
|
|
|
:arg ids: list of string ids each corresponding to the argvalues so
|
|
|
|
that they are part of the test id. If no ids are provided they will
|
|
|
|
be generated automatically from the argvalues.
|
2012-10-07 03:01:13 +08:00
|
|
|
|
2012-10-09 20:35:17 +08:00
|
|
|
:arg scope: if specified it denotes the scope of the parameters.
|
|
|
|
The scope is used for grouping tests by parameter instances.
|
|
|
|
It will also override any fixture-function defined scope, allowing
|
|
|
|
to set a dynamic scope using test context or configuration.
|
2011-11-17 19:09:21 +08:00
|
|
|
"""
|
|
|
|
if not isinstance(argnames, (tuple, list)):
|
|
|
|
argnames = (argnames,)
|
|
|
|
argvalues = [(val,) for val in argvalues]
|
2012-10-06 17:34:06 +08:00
|
|
|
if not argvalues:
|
|
|
|
argvalues = [(_notexists,) * len(argnames)]
|
|
|
|
|
2012-07-30 18:39:45 +08:00
|
|
|
if scope is None:
|
2012-10-07 03:01:13 +08:00
|
|
|
scope = "subfunction"
|
2012-07-30 16:46:03 +08:00
|
|
|
scopenum = scopes.index(scope)
|
2012-02-03 23:54:00 +08:00
|
|
|
if not indirect:
|
|
|
|
#XXX should we also check for the opposite case?
|
|
|
|
for arg in argnames:
|
2012-10-05 20:24:44 +08:00
|
|
|
if arg not in self.fixturenames:
|
2012-10-06 17:34:06 +08:00
|
|
|
raise ValueError("%r uses no fixture %r" %(
|
|
|
|
self.function, arg))
|
2011-11-17 19:09:21 +08:00
|
|
|
valtype = indirect and "params" or "funcargs"
|
|
|
|
if not ids:
|
|
|
|
idmaker = IDMaker()
|
|
|
|
ids = list(map(idmaker, argvalues))
|
|
|
|
newcalls = []
|
|
|
|
for callspec in self._calls or [CallSpec2(self)]:
|
|
|
|
for i, valset in enumerate(argvalues):
|
|
|
|
assert len(valset) == len(argnames)
|
|
|
|
newcallspec = callspec.copy(self)
|
2012-07-30 16:46:03 +08:00
|
|
|
newcallspec.setmulti(valtype, argnames, valset, ids[i],
|
|
|
|
scopenum)
|
2011-11-17 19:09:21 +08:00
|
|
|
newcalls.append(newcallspec)
|
|
|
|
self._calls = newcalls
|
|
|
|
|
2010-09-26 00:23:26 +08:00
|
|
|
def addcall(self, funcargs=None, id=_notexists, param=_notexists):
|
2011-12-05 18:10:48 +08:00
|
|
|
""" (deprecated, use parametrize) Add a new call to the underlying
|
|
|
|
test function during the collection phase of a test run. Note that
|
|
|
|
request.addcall() is called during the test collection phase prior and
|
|
|
|
independently to actual test execution. You should only use addcall()
|
|
|
|
if you need to specify multiple arguments of a test function.
|
2011-01-18 19:47:31 +08:00
|
|
|
|
2010-10-11 05:45:45 +08:00
|
|
|
:arg funcargs: argument keyword dictionary used when invoking
|
|
|
|
the test function.
|
2011-01-18 19:47:31 +08:00
|
|
|
|
2010-11-05 06:21:23 +08:00
|
|
|
:arg id: used for reporting and identification purposes. If you
|
2011-11-17 19:09:21 +08:00
|
|
|
don't supply an `id` an automatic unique id will be generated.
|
2010-10-11 05:45:45 +08:00
|
|
|
|
2012-10-05 20:24:44 +08:00
|
|
|
:arg param: a parameter which will be exposed to a later fixture function
|
2011-11-17 19:09:21 +08:00
|
|
|
invocation through the ``request.param`` attribute.
|
2010-10-11 05:45:45 +08:00
|
|
|
"""
|
2010-09-26 00:23:26 +08:00
|
|
|
assert funcargs is None or isinstance(funcargs, dict)
|
2011-03-05 19:11:35 +08:00
|
|
|
if funcargs is not None:
|
|
|
|
for name in funcargs:
|
2012-10-05 20:24:44 +08:00
|
|
|
if name not in self.fixturenames:
|
2011-03-05 19:11:35 +08:00
|
|
|
pytest.fail("funcarg %r not used in this function." % name)
|
2011-11-17 19:09:21 +08:00
|
|
|
else:
|
|
|
|
funcargs = {}
|
2010-09-26 00:23:26 +08:00
|
|
|
if id is None:
|
|
|
|
raise ValueError("id=None not allowed")
|
|
|
|
if id is _notexists:
|
|
|
|
id = len(self._calls)
|
|
|
|
id = str(id)
|
|
|
|
if id in self._ids:
|
|
|
|
raise ValueError("duplicate id %r" % id)
|
|
|
|
self._ids.add(id)
|
2011-11-17 19:09:21 +08:00
|
|
|
|
|
|
|
cs = CallSpec2(self)
|
|
|
|
cs.setall(funcargs, id, param)
|
|
|
|
self._calls.append(cs)
|
|
|
|
|
|
|
|
class IDMaker:
|
|
|
|
def __init__(self):
|
|
|
|
self.counter = 0
|
|
|
|
def __call__(self, valset):
|
|
|
|
l = []
|
|
|
|
for val in valset:
|
|
|
|
if not isinstance(val, (int, str)):
|
|
|
|
val = "."+str(self.counter)
|
|
|
|
self.counter += 1
|
|
|
|
l.append(str(val))
|
|
|
|
return "-".join(l)
|
2010-09-26 00:23:26 +08:00
|
|
|
|
|
|
|
|
2012-10-05 20:24:44 +08:00
|
|
|
def showfixtures(config):
|
2011-05-27 08:09:42 +08:00
|
|
|
from _pytest.main import wrap_session
|
2012-10-05 20:24:44 +08:00
|
|
|
return wrap_session(config, _showfixtures_main)
|
2011-05-27 08:09:42 +08:00
|
|
|
|
2012-10-05 20:24:44 +08:00
|
|
|
def _showfixtures_main(config, session):
|
2010-11-07 17:19:58 +08:00
|
|
|
session.perform_collect()
|
2012-10-09 22:49:04 +08:00
|
|
|
curdir = py.path.local()
|
2010-11-07 17:19:58 +08:00
|
|
|
if session.items:
|
2012-10-09 22:49:04 +08:00
|
|
|
nodeid = session.items[0].nodeid
|
2010-11-06 16:58:04 +08:00
|
|
|
else:
|
2012-10-09 22:49:04 +08:00
|
|
|
part = session._initialparts[0]
|
|
|
|
nodeid = "::".join(map(str, [curdir.bestrelpath(part[0])] + part[1:]))
|
|
|
|
|
2010-09-26 00:23:26 +08:00
|
|
|
tw = py.io.TerminalWriter()
|
|
|
|
verbose = config.getvalue("verbose")
|
2012-10-09 22:49:04 +08:00
|
|
|
|
|
|
|
fm = session._fixturemanager
|
|
|
|
|
|
|
|
available = []
|
|
|
|
for argname in fm.arg2fixturedeflist:
|
|
|
|
fixturedeflist = fm.getfixturedeflist(argname, nodeid)
|
|
|
|
assert fixturedeflist is not None
|
|
|
|
if not fixturedeflist:
|
|
|
|
continue
|
|
|
|
fixturedef = fixturedeflist[-1]
|
|
|
|
loc = getlocation(fixturedef.func, curdir)
|
|
|
|
available.append((len(fixturedef.baseid),
|
|
|
|
curdir.bestrelpath(loc),
|
|
|
|
fixturedef.argname, fixturedef))
|
|
|
|
|
|
|
|
available.sort()
|
|
|
|
for baseid, bestrel, argname, fixturedef in available:
|
|
|
|
if verbose > 0:
|
|
|
|
funcargspec = "%s -- %s" %(name, loc,)
|
|
|
|
else:
|
|
|
|
funcargspec = argname # "%s %s" %(baseid, argname)
|
|
|
|
tw.line(funcargspec, green=True)
|
|
|
|
loc = getlocation(fixturedef.func, curdir)
|
|
|
|
doc = fixturedef.func.__doc__ or ""
|
|
|
|
if doc:
|
|
|
|
for line in doc.split("\n"):
|
|
|
|
tw.line(" " + line.strip())
|
|
|
|
else:
|
|
|
|
tw.line(" %s: no docstring available" %(loc,),
|
|
|
|
red=True)
|
2010-09-26 00:23:26 +08:00
|
|
|
|
|
|
|
def getlocation(function, curdir):
|
|
|
|
import inspect
|
|
|
|
fn = py.path.local(inspect.getfile(function))
|
|
|
|
lineno = py.builtin._getcode(function).co_firstlineno
|
|
|
|
if fn.relto(curdir):
|
|
|
|
fn = fn.relto(curdir)
|
|
|
|
return "%s:%d" %(fn, lineno+1)
|
2010-11-06 06:37:31 +08:00
|
|
|
|
|
|
|
# builtin pytest.raises helper
|
|
|
|
|
|
|
|
def raises(ExpectedException, *args, **kwargs):
|
2010-11-25 19:11:10 +08:00
|
|
|
""" assert that a code block/function call raises @ExpectedException
|
|
|
|
and raise a failure exception otherwise.
|
2011-01-18 19:47:31 +08:00
|
|
|
|
2010-11-25 19:11:10 +08:00
|
|
|
If using Python 2.5 or above, you may use this function as a
|
|
|
|
context manager::
|
2010-11-06 06:37:31 +08:00
|
|
|
|
2010-11-25 19:11:10 +08:00
|
|
|
>>> with raises(ZeroDivisionError):
|
|
|
|
... 1/0
|
2010-11-18 21:56:16 +08:00
|
|
|
|
2010-11-25 19:11:10 +08:00
|
|
|
Or you can specify a callable by passing a to-be-called lambda::
|
2010-11-18 21:56:16 +08:00
|
|
|
|
2010-11-25 19:11:10 +08:00
|
|
|
>>> raises(ZeroDivisionError, lambda: 1/0)
|
|
|
|
<ExceptionInfo ...>
|
2010-11-18 21:56:16 +08:00
|
|
|
|
2010-11-25 19:11:10 +08:00
|
|
|
or you can specify an arbitrary callable with arguments::
|
2010-11-18 21:56:16 +08:00
|
|
|
|
2010-11-25 19:11:10 +08:00
|
|
|
>>> def f(x): return 1/x
|
|
|
|
...
|
|
|
|
>>> raises(ZeroDivisionError, f, 0)
|
|
|
|
<ExceptionInfo ...>
|
|
|
|
>>> raises(ZeroDivisionError, f, x=0)
|
|
|
|
<ExceptionInfo ...>
|
2010-11-18 21:56:16 +08:00
|
|
|
|
2011-12-05 18:10:48 +08:00
|
|
|
A third possibility is to use a string to be executed::
|
2011-01-18 19:47:31 +08:00
|
|
|
|
2010-11-25 19:11:10 +08:00
|
|
|
>>> raises(ZeroDivisionError, "f(0)")
|
|
|
|
<ExceptionInfo ...>
|
2010-11-06 06:37:31 +08:00
|
|
|
"""
|
|
|
|
__tracebackhide__ = True
|
2012-08-19 19:45:26 +08:00
|
|
|
if ExpectedException is AssertionError:
|
|
|
|
# we want to catch a AssertionError
|
|
|
|
# replace our subclass with the builtin one
|
|
|
|
# see https://bitbucket.org/hpk42/pytest/issue/176/pytestraises
|
2012-08-29 04:35:06 +08:00
|
|
|
from _pytest.assertion.util import BuiltinAssertionError as ExpectedException
|
2010-11-06 06:37:31 +08:00
|
|
|
|
|
|
|
if not args:
|
|
|
|
return RaisesContext(ExpectedException)
|
|
|
|
elif isinstance(args[0], str):
|
|
|
|
code, = args
|
|
|
|
assert isinstance(code, str)
|
|
|
|
frame = sys._getframe(1)
|
|
|
|
loc = frame.f_locals.copy()
|
|
|
|
loc.update(kwargs)
|
|
|
|
#print "raises frame scope: %r" % frame.f_locals
|
|
|
|
try:
|
|
|
|
code = py.code.Source(code).compile()
|
|
|
|
py.builtin.exec_(code, frame.f_globals, loc)
|
|
|
|
# XXX didn'T mean f_globals == f_locals something special?
|
|
|
|
# this is destroyed here ...
|
|
|
|
except ExpectedException:
|
|
|
|
return py.code.ExceptionInfo()
|
|
|
|
else:
|
|
|
|
func = args[0]
|
|
|
|
try:
|
|
|
|
func(*args[1:], **kwargs)
|
|
|
|
except ExpectedException:
|
|
|
|
return py.code.ExceptionInfo()
|
|
|
|
k = ", ".join(["%s=%r" % x for x in kwargs.items()])
|
|
|
|
if k:
|
|
|
|
k = ', ' + k
|
|
|
|
expr = '%s(%r%s)' %(getattr(func, '__name__', func), args, k)
|
|
|
|
pytest.fail("DID NOT RAISE")
|
|
|
|
|
|
|
|
class RaisesContext(object):
|
|
|
|
def __init__(self, ExpectedException):
|
|
|
|
self.ExpectedException = ExpectedException
|
|
|
|
self.excinfo = None
|
|
|
|
|
|
|
|
def __enter__(self):
|
|
|
|
self.excinfo = object.__new__(py.code.ExceptionInfo)
|
|
|
|
return self.excinfo
|
|
|
|
|
|
|
|
def __exit__(self, *tp):
|
|
|
|
__tracebackhide__ = True
|
|
|
|
if tp[0] is None:
|
|
|
|
pytest.fail("DID NOT RAISE")
|
|
|
|
self.excinfo.__init__(tp)
|
|
|
|
return issubclass(self.excinfo.type, self.ExpectedException)
|
2011-01-18 19:47:31 +08:00
|
|
|
|
2012-06-25 23:35:33 +08:00
|
|
|
#
|
|
|
|
# the basic py.test Function item
|
|
|
|
#
|
|
|
|
_dummy = object()
|
2012-10-05 20:24:44 +08:00
|
|
|
class Function(FunctionMixin, pytest.Item, FuncargnamesCompatAttr):
|
2012-06-25 23:35:33 +08:00
|
|
|
""" a Function Item is responsible for setting up and executing a
|
|
|
|
Python test function.
|
|
|
|
"""
|
|
|
|
_genid = None
|
2012-10-16 19:47:59 +08:00
|
|
|
def __init__(self, name, parent, args=None, config=None,
|
2012-07-19 01:49:14 +08:00
|
|
|
callspec=None, callobj=_dummy, keywords=None, session=None):
|
2012-06-25 23:35:33 +08:00
|
|
|
super(Function, self).__init__(name, parent, config=config,
|
|
|
|
session=session)
|
|
|
|
self._args = args
|
|
|
|
if self._isyieldedfunction():
|
|
|
|
assert not callspec, (
|
|
|
|
"yielded functions (deprecated) cannot have funcargs")
|
|
|
|
else:
|
|
|
|
if callspec is not None:
|
|
|
|
self.callspec = callspec
|
2012-07-19 01:49:14 +08:00
|
|
|
self.funcargs = callspec.funcargs or {}
|
2012-06-25 23:35:33 +08:00
|
|
|
self._genid = callspec.id
|
|
|
|
if hasattr(callspec, "param"):
|
|
|
|
self.param = callspec.param
|
2012-07-19 01:49:14 +08:00
|
|
|
else:
|
|
|
|
self.funcargs = {}
|
2012-10-05 20:24:44 +08:00
|
|
|
self._request = req = FixtureRequest(self)
|
2012-07-20 20:16:28 +08:00
|
|
|
#req._discoverfactories()
|
2012-06-25 23:35:33 +08:00
|
|
|
if callobj is not _dummy:
|
2012-07-19 01:49:14 +08:00
|
|
|
self.obj = callobj
|
2012-10-05 16:21:35 +08:00
|
|
|
|
2012-09-17 23:32:23 +08:00
|
|
|
for name, val in (py.builtin._getfuncdict(self.obj) or {}).items():
|
|
|
|
setattr(self.markers, name, val)
|
2012-06-25 23:35:33 +08:00
|
|
|
if keywords:
|
2012-09-17 23:32:23 +08:00
|
|
|
for name, val in keywords.items():
|
|
|
|
setattr(self.markers, name, val)
|
2012-06-25 23:35:33 +08:00
|
|
|
|
2012-10-16 19:48:00 +08:00
|
|
|
fixtureinfo = self.parent._fixturemapper.getfixtureinfo(self.obj,
|
|
|
|
self.cls)
|
|
|
|
self.fixturenames = fixtureinfo.names_closure
|
2012-10-05 16:21:35 +08:00
|
|
|
|
2012-06-25 23:35:33 +08:00
|
|
|
@property
|
|
|
|
def function(self):
|
|
|
|
"underlying python 'function' object"
|
|
|
|
return getattr(self.obj, 'im_func', self.obj)
|
|
|
|
|
|
|
|
def _getobj(self):
|
|
|
|
name = self.name
|
|
|
|
i = name.find("[") # parametrization
|
|
|
|
if i != -1:
|
|
|
|
name = name[:i]
|
|
|
|
return getattr(self.parent.obj, name)
|
|
|
|
|
|
|
|
@property
|
|
|
|
def _pyfuncitem(self):
|
|
|
|
"(compatonly) for code expecting pytest-2.2 style request objects"
|
|
|
|
return self
|
|
|
|
|
|
|
|
def _isyieldedfunction(self):
|
|
|
|
return getattr(self, "_args", None) is not None
|
|
|
|
|
|
|
|
def runtest(self):
|
|
|
|
""" execute the underlying test function. """
|
|
|
|
self.ihook.pytest_pyfunc_call(pyfuncitem=self)
|
|
|
|
|
|
|
|
def setup(self):
|
2012-10-06 17:34:06 +08:00
|
|
|
# check if parametrization happend with an empty list
|
|
|
|
try:
|
|
|
|
empty = self.callspec._emptyparamspecified
|
|
|
|
except AttributeError:
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
fs, lineno = self._getfslineno()
|
|
|
|
pytest.skip("got empty parameter set, function %s at %s:%d" %(
|
|
|
|
self.function.__name__, fs, lineno))
|
2012-06-25 23:35:33 +08:00
|
|
|
super(Function, self).setup()
|
2012-10-05 20:24:44 +08:00
|
|
|
fillfixtures(self)
|
2012-06-25 23:35:33 +08:00
|
|
|
|
|
|
|
def __eq__(self, other):
|
|
|
|
try:
|
|
|
|
return (self.name == other.name and
|
|
|
|
self._args == other._args and
|
|
|
|
self.parent == other.parent and
|
|
|
|
self.obj == other.obj and
|
|
|
|
getattr(self, '_genid', None) ==
|
|
|
|
getattr(other, '_genid', None)
|
|
|
|
)
|
|
|
|
except AttributeError:
|
|
|
|
pass
|
|
|
|
return False
|
|
|
|
|
|
|
|
def __ne__(self, other):
|
|
|
|
return not self == other
|
|
|
|
|
|
|
|
def __hash__(self):
|
|
|
|
return hash((self.parent, self.name))
|
|
|
|
|
2012-09-17 22:36:10 +08:00
|
|
|
scope2props = dict(session=())
|
|
|
|
scope2props["module"] = ("fspath", "module")
|
|
|
|
scope2props["class"] = scope2props["module"] + ("cls",)
|
|
|
|
scope2props["instance"] = scope2props["class"] + ("instance", )
|
|
|
|
scope2props["function"] = scope2props["instance"] + ("function", "keywords")
|
|
|
|
|
|
|
|
def scopeproperty(name=None, doc=None):
|
|
|
|
def decoratescope(func):
|
|
|
|
scopename = name or func.__name__
|
|
|
|
def provide(self):
|
|
|
|
if func.__name__ in scope2props[self.scope]:
|
|
|
|
return func(self)
|
|
|
|
raise AttributeError("%s not available in %s-scoped context" % (
|
|
|
|
scopename, self.scope))
|
|
|
|
return property(provide, None, None, func.__doc__)
|
|
|
|
return decoratescope
|
|
|
|
|
2012-06-25 23:35:33 +08:00
|
|
|
|
2012-10-05 20:24:44 +08:00
|
|
|
class FixtureRequest(FuncargnamesCompatAttr):
|
2012-10-09 20:35:17 +08:00
|
|
|
""" A request for a fixture from a test or fixture function.
|
2012-09-17 22:36:10 +08:00
|
|
|
|
2012-10-09 20:35:17 +08:00
|
|
|
A request object gives access to the requesting test context
|
|
|
|
and has an optional ``param`` attribute in case
|
|
|
|
the fixture is parametrized indirectly.
|
2012-07-19 01:49:14 +08:00
|
|
|
"""
|
2012-06-25 23:35:33 +08:00
|
|
|
|
|
|
|
def __init__(self, pyfuncitem):
|
|
|
|
self._pyfuncitem = pyfuncitem
|
2012-07-19 01:49:14 +08:00
|
|
|
if hasattr(pyfuncitem, '_requestparam'):
|
|
|
|
self.param = pyfuncitem._requestparam
|
2012-10-09 20:35:17 +08:00
|
|
|
#: fixture for which this request is being performed
|
|
|
|
self.fixturename = None
|
2012-09-17 22:36:10 +08:00
|
|
|
#: Scope string, one of "function", "cls", "module", "session"
|
|
|
|
self.scope = "function"
|
2012-07-19 01:49:14 +08:00
|
|
|
self.getparent = pyfuncitem.getparent
|
|
|
|
self._funcargs = self._pyfuncitem.funcargs.copy()
|
2012-10-05 20:24:44 +08:00
|
|
|
self._arg2fixturedeflist = {}
|
|
|
|
self._fixturemanager = pyfuncitem.session._fixturemanager
|
|
|
|
self._parentid = pyfuncitem.parent.nodeid
|
|
|
|
self.fixturenames, self._arg2fixturedeflist_ = \
|
|
|
|
self._fixturemanager.getfixtureclosure(
|
2012-09-24 23:04:34 +08:00
|
|
|
getfuncargnames(self.function), # XXX _pyfuncitem...
|
|
|
|
pyfuncitem.parent)
|
2012-10-05 20:24:44 +08:00
|
|
|
self._fixturestack = []
|
2012-07-19 15:20:14 +08:00
|
|
|
|
2012-09-17 23:32:23 +08:00
|
|
|
@property
|
2012-09-18 02:43:37 +08:00
|
|
|
def node(self):
|
2012-10-07 19:06:17 +08:00
|
|
|
""" underlying collection node (depends on current request scope)"""
|
2012-09-18 02:43:37 +08:00
|
|
|
return self._getscopeitem(self.scope)
|
2012-09-17 23:32:23 +08:00
|
|
|
|
2012-10-05 20:24:44 +08:00
|
|
|
def _getfixturedeflist(self, argname):
|
|
|
|
fixturedeflist = self._arg2fixturedeflist.get(argname, None)
|
|
|
|
if fixturedeflist is None:
|
|
|
|
fixturedeflist = self._fixturemanager.getfixturedeflist(
|
|
|
|
argname, self._parentid)
|
|
|
|
self._arg2fixturedeflist[argname] = fixturedeflist
|
|
|
|
if not fixturedeflist:
|
2012-10-05 20:24:45 +08:00
|
|
|
raise FixtureLookupError(argname, self)
|
2012-10-05 20:24:44 +08:00
|
|
|
return fixturedeflist
|
2012-06-25 23:35:33 +08:00
|
|
|
|
2012-07-19 01:49:14 +08:00
|
|
|
@property
|
2012-09-17 22:36:10 +08:00
|
|
|
def config(self):
|
|
|
|
""" the pytest config object associated with this request. """
|
|
|
|
return self._pyfuncitem.config
|
2012-07-19 01:49:14 +08:00
|
|
|
|
2012-08-01 19:57:09 +08:00
|
|
|
|
2012-09-17 22:36:10 +08:00
|
|
|
@scopeproperty()
|
|
|
|
def function(self):
|
|
|
|
""" test function object if the request has a per-function scope. """
|
|
|
|
return self._pyfuncitem.obj
|
2012-07-19 01:49:14 +08:00
|
|
|
|
2012-09-17 22:36:10 +08:00
|
|
|
@scopeproperty("class")
|
2012-07-19 01:49:14 +08:00
|
|
|
def cls(self):
|
|
|
|
""" class (can be None) where the test function was collected. """
|
|
|
|
clscol = self._pyfuncitem.getparent(pytest.Class)
|
|
|
|
if clscol:
|
|
|
|
return clscol.obj
|
2012-09-17 22:36:10 +08:00
|
|
|
|
2012-09-18 16:54:12 +08:00
|
|
|
@property
|
2012-07-19 01:49:14 +08:00
|
|
|
def instance(self):
|
|
|
|
""" instance (can be None) on which test function was collected. """
|
2012-09-18 16:54:12 +08:00
|
|
|
# unittest support hack, see _pytest.unittest.TestCaseFunction
|
|
|
|
try:
|
|
|
|
return self._pyfuncitem._testcase
|
|
|
|
except AttributeError:
|
|
|
|
return py.builtin._getimself(self.function)
|
2012-07-19 01:49:14 +08:00
|
|
|
|
2012-09-17 22:36:10 +08:00
|
|
|
@scopeproperty()
|
|
|
|
def module(self):
|
|
|
|
""" python module object where the test function was collected. """
|
|
|
|
return self._pyfuncitem.getparent(pytest.Module).obj
|
2012-07-19 01:49:14 +08:00
|
|
|
|
2012-09-17 22:36:10 +08:00
|
|
|
@scopeproperty()
|
2012-07-19 01:49:14 +08:00
|
|
|
def fspath(self):
|
|
|
|
""" the file system path of the test module which collected this test. """
|
|
|
|
return self._pyfuncitem.fspath
|
|
|
|
|
2012-09-17 22:36:10 +08:00
|
|
|
@property
|
|
|
|
def keywords(self):
|
2012-09-18 02:43:37 +08:00
|
|
|
""" (deprecated, use node.markers class) dictionary of markers. """
|
2012-09-17 22:36:10 +08:00
|
|
|
return self._pyfuncitem.keywords
|
|
|
|
|
|
|
|
@property
|
|
|
|
def session(self):
|
|
|
|
""" pytest session object. """
|
|
|
|
return self._pyfuncitem.session
|
|
|
|
|
|
|
|
def addfinalizer(self, finalizer):
|
|
|
|
"""add finalizer/teardown function to be called after the
|
|
|
|
last test within the requesting test context finished
|
|
|
|
execution. """
|
2012-10-05 20:24:44 +08:00
|
|
|
# XXX usually this method is shadowed by fixturedef specific ones
|
2012-09-17 22:36:10 +08:00
|
|
|
self._addfinalizer(finalizer, scope=self.scope)
|
|
|
|
|
|
|
|
def _addfinalizer(self, finalizer, scope):
|
|
|
|
if scope != "function" and hasattr(self, "param"):
|
|
|
|
# parametrized resources are sorted by param
|
|
|
|
# so we rather store finalizers per (argname, param)
|
2012-10-09 20:35:17 +08:00
|
|
|
colitem = (self.fixturename, self.param)
|
2012-09-17 22:36:10 +08:00
|
|
|
else:
|
|
|
|
colitem = self._getscopeitem(scope)
|
|
|
|
self._pyfuncitem.session._setupstate.addfinalizer(
|
|
|
|
finalizer=finalizer, colitem=colitem)
|
2012-07-19 01:49:14 +08:00
|
|
|
|
|
|
|
def applymarker(self, marker):
|
|
|
|
""" Apply a marker to a single test function invocation.
|
|
|
|
This method is useful if you don't want to have a keyword/marker
|
|
|
|
on all function invocations.
|
|
|
|
|
|
|
|
:arg marker: a :py:class:`_pytest.mark.MarkDecorator` object
|
|
|
|
created by a call to ``py.test.mark.NAME(...)``.
|
|
|
|
"""
|
2012-10-01 04:17:33 +08:00
|
|
|
self.node.applymarker(marker)
|
2012-07-19 01:49:14 +08:00
|
|
|
|
2012-09-17 22:36:10 +08:00
|
|
|
def raiseerror(self, msg):
|
2012-10-05 20:24:44 +08:00
|
|
|
""" raise a FixtureLookupError with the given message. """
|
2012-10-05 20:24:45 +08:00
|
|
|
raise self._fixturemanager.FixtureLookupError(None, self, msg)
|
2012-09-17 22:36:10 +08:00
|
|
|
|
2012-10-05 20:24:44 +08:00
|
|
|
def _fillfixtures(self):
|
2012-09-24 23:04:34 +08:00
|
|
|
item = self._pyfuncitem
|
2012-10-05 20:24:44 +08:00
|
|
|
fixturenames = getattr(item, "fixturenames", self.fixturenames)
|
|
|
|
for argname in fixturenames:
|
2012-09-24 23:04:34 +08:00
|
|
|
if argname not in item.funcargs:
|
|
|
|
item.funcargs[argname] = self.getfuncargvalue(argname)
|
2012-09-17 22:36:10 +08:00
|
|
|
|
2012-07-19 01:49:14 +08:00
|
|
|
def cached_setup(self, setup, teardown=None, scope="module", extrakey=None):
|
2012-09-17 22:36:10 +08:00
|
|
|
""" (deprecated) Return a testing resource managed by ``setup`` &
|
2012-07-19 01:49:14 +08:00
|
|
|
``teardown`` calls. ``scope`` and ``extrakey`` determine when the
|
|
|
|
``teardown`` function will be called so that subsequent calls to
|
2012-10-05 20:24:44 +08:00
|
|
|
``setup`` would recreate the resource. With pytest-2.3 you often
|
2012-09-17 22:36:10 +08:00
|
|
|
do not need ``cached_setup()`` as you can directly declare a scope
|
2012-10-05 20:24:44 +08:00
|
|
|
on a fixture function and register a finalizer through
|
2012-09-17 22:36:10 +08:00
|
|
|
``request.addfinalizer()``.
|
2012-07-19 01:49:14 +08:00
|
|
|
|
|
|
|
:arg teardown: function receiving a previously setup resource.
|
|
|
|
:arg setup: a no-argument function creating a resource.
|
|
|
|
:arg scope: a string value out of ``function``, ``class``, ``module``
|
|
|
|
or ``session`` indicating the caching lifecycle of the resource.
|
|
|
|
:arg extrakey: added to internal caching key of (funcargname, scope).
|
|
|
|
"""
|
|
|
|
if not hasattr(self.config, '_setupcache'):
|
|
|
|
self.config._setupcache = {} # XXX weakref?
|
2012-10-09 20:35:17 +08:00
|
|
|
cachekey = (self.fixturename, self._getscopeitem(scope), extrakey)
|
2012-07-19 01:49:14 +08:00
|
|
|
cache = self.config._setupcache
|
|
|
|
try:
|
|
|
|
val = cache[cachekey]
|
|
|
|
except KeyError:
|
2012-07-20 20:16:46 +08:00
|
|
|
__tracebackhide__ = True
|
2012-07-23 16:55:09 +08:00
|
|
|
if scopemismatch(self.scope, scope):
|
|
|
|
raise ScopeMismatchError("You tried to access a %r scoped "
|
|
|
|
"resource with a %r scoped request object" %(
|
|
|
|
(scope, self.scope)))
|
2012-07-20 20:16:46 +08:00
|
|
|
__tracebackhide__ = False
|
2012-07-19 01:49:14 +08:00
|
|
|
val = setup()
|
|
|
|
cache[cachekey] = val
|
|
|
|
if teardown is not None:
|
|
|
|
def finalizer():
|
|
|
|
del cache[cachekey]
|
|
|
|
teardown(val)
|
|
|
|
self._addfinalizer(finalizer, scope=scope)
|
|
|
|
return val
|
|
|
|
|
|
|
|
def getfuncargvalue(self, argname):
|
2012-10-09 20:35:17 +08:00
|
|
|
""" Dynamically retrieve a named fixture function argument.
|
|
|
|
|
|
|
|
As of pytest-2.3, it is easier and usually better to access other
|
|
|
|
fixture values by stating it as an input argument in the fixture
|
|
|
|
function. If you only can decide about using another fixture at test
|
|
|
|
setup time, you may use this function to retrieve it inside a fixture
|
|
|
|
function body.
|
2012-07-19 01:49:14 +08:00
|
|
|
"""
|
|
|
|
try:
|
|
|
|
return self._funcargs[argname]
|
|
|
|
except KeyError:
|
|
|
|
pass
|
2012-10-01 15:23:39 +08:00
|
|
|
try:
|
2012-10-05 20:24:44 +08:00
|
|
|
fixturedeflist = self._getfixturedeflist(argname)
|
|
|
|
except FixtureLookupError:
|
2012-10-01 15:23:39 +08:00
|
|
|
if argname == "request":
|
|
|
|
return self
|
|
|
|
raise
|
2012-10-05 20:24:44 +08:00
|
|
|
fixturedef = fixturedeflist.pop()
|
|
|
|
self._fixturestack.append(fixturedef)
|
2012-07-23 16:55:09 +08:00
|
|
|
try:
|
2012-10-05 20:24:44 +08:00
|
|
|
result = self._getfuncargvalue(fixturedef)
|
2012-10-05 16:21:35 +08:00
|
|
|
self._funcargs[argname] = result
|
|
|
|
return result
|
2012-07-23 16:55:09 +08:00
|
|
|
finally:
|
2012-10-05 20:24:44 +08:00
|
|
|
self._fixturestack.pop()
|
2012-07-23 16:55:09 +08:00
|
|
|
|
2012-10-05 20:24:44 +08:00
|
|
|
def _getfuncargvalue(self, fixturedef):
|
|
|
|
if fixturedef.active:
|
|
|
|
return fixturedef.cached_result
|
2012-07-23 16:55:09 +08:00
|
|
|
|
2012-10-09 20:35:17 +08:00
|
|
|
# prepare request fixturename and param attributes before
|
2012-10-07 03:01:13 +08:00
|
|
|
# calling into fixture function
|
2012-10-05 20:24:44 +08:00
|
|
|
argname = fixturedef.argname
|
2012-07-20 20:16:28 +08:00
|
|
|
node = self._pyfuncitem
|
|
|
|
mp = monkeypatch()
|
2012-10-09 20:35:17 +08:00
|
|
|
mp.setattr(self, 'fixturename', argname)
|
2012-07-20 20:16:28 +08:00
|
|
|
try:
|
|
|
|
param = node.callspec.getparam(argname)
|
|
|
|
except (AttributeError, ValueError):
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
mp.setattr(self, 'param', param, raising=False)
|
2012-10-07 03:01:13 +08:00
|
|
|
|
|
|
|
# if a parametrize invocation set a scope it will override
|
|
|
|
# the static scope defined with the fixture function
|
2012-10-05 20:24:44 +08:00
|
|
|
scope = fixturedef.scope
|
2012-10-07 03:01:13 +08:00
|
|
|
try:
|
|
|
|
paramscopenum = node.callspec._arg2scopenum[argname]
|
|
|
|
except (KeyError, AttributeError):
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
if paramscopenum != scopenum_subfunction:
|
|
|
|
scope = scopes[paramscopenum]
|
|
|
|
|
2012-07-20 20:16:46 +08:00
|
|
|
if scope is not None:
|
|
|
|
__tracebackhide__ = True
|
2012-07-23 16:55:09 +08:00
|
|
|
if scopemismatch(self.scope, scope):
|
|
|
|
# try to report something helpful
|
2012-08-08 17:48:53 +08:00
|
|
|
lines = self._factorytraceback()
|
2012-07-23 16:55:09 +08:00
|
|
|
raise ScopeMismatchError("You tried to access the %r scoped "
|
|
|
|
"funcarg %r with a %r scoped request object, "
|
|
|
|
"involved factories\n%s" %(
|
|
|
|
(scope, argname, self.scope, "\n".join(lines))))
|
2012-07-20 20:16:46 +08:00
|
|
|
__tracebackhide__ = False
|
|
|
|
mp.setattr(self, "scope", scope)
|
2012-10-05 16:21:35 +08:00
|
|
|
|
|
|
|
# prepare finalization according to scope
|
2012-10-07 19:06:17 +08:00
|
|
|
# (XXX analyse exact finalizing mechanics / cleanup)
|
2012-10-05 20:24:44 +08:00
|
|
|
self.session._setupstate.addfinalizer(fixturedef.finish, self.node)
|
|
|
|
self._fixturemanager.addargfinalizer(fixturedef.finish, argname)
|
|
|
|
for subargname in fixturedef.fixturenames: # XXX all deps?
|
|
|
|
self._fixturemanager.addargfinalizer(fixturedef.finish, subargname)
|
|
|
|
mp.setattr(self, "addfinalizer", fixturedef.addfinalizer)
|
2012-10-07 19:06:17 +08:00
|
|
|
# finally perform the fixture call
|
2012-10-05 20:24:44 +08:00
|
|
|
val = fixturedef.execute(request=self)
|
2012-07-20 20:16:46 +08:00
|
|
|
mp.undo()
|
|
|
|
return val
|
2012-07-19 01:49:14 +08:00
|
|
|
|
2012-08-08 17:48:53 +08:00
|
|
|
def _factorytraceback(self):
|
|
|
|
lines = []
|
2012-10-05 20:24:44 +08:00
|
|
|
for fixturedef in self._fixturestack:
|
|
|
|
factory = fixturedef.func
|
2012-08-08 17:48:53 +08:00
|
|
|
fs, lineno = getfslineno(factory)
|
|
|
|
p = self._pyfuncitem.session.fspath.bestrelpath(fs)
|
|
|
|
args = inspect.formatargspec(*inspect.getargspec(factory))
|
|
|
|
lines.append("%s:%d: def %s%s" %(
|
|
|
|
p, lineno, factory.__name__, args))
|
|
|
|
return lines
|
|
|
|
|
2012-07-19 01:49:14 +08:00
|
|
|
def _getscopeitem(self, scope):
|
|
|
|
if scope == "function":
|
|
|
|
return self._pyfuncitem
|
|
|
|
elif scope == "session":
|
|
|
|
return None
|
|
|
|
elif scope == "class":
|
|
|
|
x = self._pyfuncitem.getparent(pytest.Class)
|
|
|
|
if x is not None:
|
|
|
|
return x
|
|
|
|
scope = "module"
|
|
|
|
if scope == "module":
|
|
|
|
return self._pyfuncitem.getparent(pytest.Module)
|
|
|
|
raise ValueError("unknown finalization scope %r" %(scope,))
|
|
|
|
|
|
|
|
def __repr__(self):
|
2012-10-09 20:35:17 +08:00
|
|
|
return "<FixtureRequest for %r>" %(self.node)
|
2012-07-19 01:49:14 +08:00
|
|
|
|
2012-07-20 20:16:46 +08:00
|
|
|
class ScopeMismatchError(Exception):
|
2012-10-05 20:24:44 +08:00
|
|
|
""" A fixture function tries to use a different fixture function which
|
2012-07-20 20:16:46 +08:00
|
|
|
which has a lower scope (e.g. a Session one calls a function one)
|
|
|
|
"""
|
2012-07-23 16:55:09 +08:00
|
|
|
|
2012-10-07 03:01:13 +08:00
|
|
|
scopes = "session module class function subfunction".split()
|
|
|
|
scopenum_subfunction = scopes.index("subfunction")
|
2012-07-23 16:55:09 +08:00
|
|
|
def scopemismatch(currentscope, newscope):
|
|
|
|
return scopes.index(newscope) > scopes.index(currentscope)
|
|
|
|
|
|
|
|
def slice_kwargs(names, kwargs):
|
|
|
|
new_kwargs = {}
|
|
|
|
for name in names:
|
|
|
|
new_kwargs[name] = kwargs[name]
|
|
|
|
return new_kwargs
|
|
|
|
|
2012-10-05 20:24:44 +08:00
|
|
|
class FixtureLookupError(LookupError):
|
2012-10-05 20:24:45 +08:00
|
|
|
""" could not return a requested Fixture (missing or invalid). """
|
|
|
|
def __init__(self, argname, request, msg=None):
|
|
|
|
self.argname = argname
|
|
|
|
self.request = request
|
|
|
|
self.fixturestack = list(request._fixturestack)
|
2012-08-01 15:23:39 +08:00
|
|
|
self.msg = msg
|
2012-10-05 20:24:45 +08:00
|
|
|
|
|
|
|
def formatrepr(self):
|
|
|
|
tblines = []
|
|
|
|
addline = tblines.append
|
|
|
|
stack = [self.request._pyfuncitem.obj]
|
|
|
|
stack.extend(map(lambda x: x.func, self.fixturestack))
|
|
|
|
msg = self.msg
|
|
|
|
if msg is not None:
|
|
|
|
stack = stack[:-1] # the last fixture raise an error, let's present
|
|
|
|
# it at the requesting side
|
|
|
|
for function in stack:
|
|
|
|
fspath, lineno = getfslineno(function)
|
|
|
|
lines, _ = inspect.getsourcelines(function)
|
|
|
|
addline("file %s, line %s" % (fspath, lineno+1))
|
|
|
|
for i, line in enumerate(lines):
|
|
|
|
line = line.rstrip()
|
|
|
|
addline(" " + line)
|
|
|
|
if line.lstrip().startswith('def'):
|
|
|
|
break
|
|
|
|
|
|
|
|
if msg is None:
|
|
|
|
fm = self.request._fixturemanager
|
|
|
|
nodeid = self.request._parentid
|
|
|
|
available = []
|
|
|
|
for name, fixturedef in fm.arg2fixturedeflist.items():
|
|
|
|
faclist = list(fm._matchfactories(fixturedef, self.request._parentid))
|
|
|
|
if faclist:
|
|
|
|
available.append(name)
|
|
|
|
msg = "fixture %r not found" % (self.argname,)
|
|
|
|
msg += "\n available fixtures: %s" %(", ".join(available),)
|
|
|
|
msg += "\n use 'py.test --fixtures [testpath]' for help on them."
|
|
|
|
|
|
|
|
return FixtureLookupErrorRepr(fspath, lineno, tblines, msg, self.argname)
|
2012-08-01 15:23:39 +08:00
|
|
|
|
2012-10-05 20:24:44 +08:00
|
|
|
class FixtureLookupErrorRepr(TerminalRepr):
|
2012-10-05 20:24:45 +08:00
|
|
|
def __init__(self, filename, firstlineno, tblines, errorstring, argname):
|
|
|
|
self.tblines = tblines
|
2012-08-01 15:23:39 +08:00
|
|
|
self.errorstring = errorstring
|
|
|
|
self.filename = filename
|
|
|
|
self.firstlineno = firstlineno
|
2012-10-05 20:24:45 +08:00
|
|
|
self.argname = argname
|
2012-08-01 15:23:39 +08:00
|
|
|
|
|
|
|
def toterminal(self, tw):
|
2012-10-05 20:24:45 +08:00
|
|
|
#tw.line("FixtureLookupError: %s" %(self.argname), red=True)
|
|
|
|
for tbline in self.tblines:
|
|
|
|
tw.line(tbline.rstrip())
|
2012-08-01 15:23:39 +08:00
|
|
|
for line in self.errorstring.split("\n"):
|
|
|
|
tw.line(" " + line.strip(), red=True)
|
|
|
|
tw.line()
|
|
|
|
tw.line("%s:%d" % (self.filename, self.firstlineno+1))
|
|
|
|
|
2012-10-05 20:24:44 +08:00
|
|
|
class FixtureManager:
|
2012-08-01 15:23:39 +08:00
|
|
|
_argprefix = "pytest_funcarg__"
|
2012-10-05 20:24:44 +08:00
|
|
|
FixtureLookupError = FixtureLookupError
|
|
|
|
FixtureLookupErrorRepr = FixtureLookupErrorRepr
|
2012-08-01 15:23:39 +08:00
|
|
|
|
|
|
|
def __init__(self, session):
|
|
|
|
self.session = session
|
|
|
|
self.config = session.config
|
2012-10-05 20:24:44 +08:00
|
|
|
self.arg2fixturedeflist = {}
|
2012-09-12 18:51:45 +08:00
|
|
|
self._seenplugins = set()
|
2012-08-01 15:23:39 +08:00
|
|
|
self._holderobjseen = set()
|
|
|
|
self._arg2finish = {}
|
2012-10-05 16:21:35 +08:00
|
|
|
self._autofixtures = []
|
2012-09-12 18:51:45 +08:00
|
|
|
session.config.pluginmanager.register(self, "funcmanage")
|
2012-08-01 15:23:39 +08:00
|
|
|
|
|
|
|
### XXX this hook should be called for historic events like pytest_configure
|
2012-09-12 18:51:45 +08:00
|
|
|
### so that we don't have to do the below pytest_configure hook
|
2012-08-01 15:23:39 +08:00
|
|
|
def pytest_plugin_registered(self, plugin):
|
2012-09-12 18:51:45 +08:00
|
|
|
if plugin in self._seenplugins:
|
|
|
|
return
|
2012-08-01 15:23:39 +08:00
|
|
|
#print "plugin_registered", plugin
|
|
|
|
nodeid = ""
|
|
|
|
try:
|
|
|
|
p = py.path.local(plugin.__file__)
|
|
|
|
except AttributeError:
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
if p.basename.startswith("conftest.py"):
|
|
|
|
nodeid = p.dirpath().relto(self.session.fspath)
|
|
|
|
self._parsefactories(plugin, nodeid)
|
2012-09-12 18:51:45 +08:00
|
|
|
self._seenplugins.add(plugin)
|
2012-08-01 15:23:39 +08:00
|
|
|
|
|
|
|
@pytest.mark.tryfirst
|
2012-09-12 18:51:45 +08:00
|
|
|
def pytest_configure(self, config):
|
|
|
|
plugins = config.pluginmanager.getplugins()
|
2012-08-01 15:23:39 +08:00
|
|
|
for plugin in plugins:
|
|
|
|
self.pytest_plugin_registered(plugin)
|
|
|
|
|
2012-10-06 01:20:40 +08:00
|
|
|
def getdefaultfixtures(self):
|
2012-10-16 19:47:59 +08:00
|
|
|
""" return a tuple of default fixture names (XXX for the given file path). """
|
2012-10-06 01:20:40 +08:00
|
|
|
try:
|
|
|
|
return self._defaultfixtures
|
|
|
|
except AttributeError:
|
2012-10-16 19:47:59 +08:00
|
|
|
defaultfixtures = tuple(self.config.getini("usefixtures"))
|
2012-10-06 01:20:40 +08:00
|
|
|
# make sure the self._autofixtures list is sorted
|
|
|
|
# by scope, scopenum 0 is session
|
|
|
|
self._autofixtures.sort(
|
|
|
|
key=lambda x: self.arg2fixturedeflist[x][-1].scopenum)
|
2012-10-16 19:47:59 +08:00
|
|
|
defaultfixtures = defaultfixtures + tuple(self._autofixtures)
|
2012-10-06 01:20:40 +08:00
|
|
|
self._defaultfixtures = defaultfixtures
|
|
|
|
return defaultfixtures
|
|
|
|
|
2012-10-05 20:24:44 +08:00
|
|
|
def getfixtureclosure(self, fixturenames, parentnode):
|
2012-10-06 01:20:40 +08:00
|
|
|
# collect the closure of all fixtures , starting with the given
|
2012-10-05 20:24:44 +08:00
|
|
|
# fixturenames as the initial set. As we have to visit all
|
|
|
|
# factory definitions anyway, we also return a arg2fixturedeflist
|
|
|
|
# mapping so that the caller can reuse it and does not have
|
|
|
|
# to re-discover fixturedefs again for each fixturename
|
|
|
|
# (discovering matching fixtures for a given name/node is expensive)
|
|
|
|
|
2012-09-24 23:04:34 +08:00
|
|
|
parentid = parentnode.nodeid
|
2012-10-06 01:20:40 +08:00
|
|
|
fixturenames_closure = list(self.getdefaultfixtures())
|
2012-09-24 23:04:34 +08:00
|
|
|
def merge(otherlist):
|
|
|
|
for arg in otherlist:
|
2012-10-05 20:24:44 +08:00
|
|
|
if arg not in fixturenames_closure:
|
|
|
|
fixturenames_closure.append(arg)
|
|
|
|
merge(fixturenames)
|
|
|
|
arg2fixturedeflist = {}
|
2012-09-24 23:04:34 +08:00
|
|
|
lastlen = -1
|
2012-10-05 20:24:44 +08:00
|
|
|
while lastlen != len(fixturenames_closure):
|
|
|
|
lastlen = len(fixturenames_closure)
|
|
|
|
for argname in fixturenames_closure:
|
|
|
|
if argname in arg2fixturedeflist:
|
2012-09-24 23:04:34 +08:00
|
|
|
continue
|
2012-10-05 20:24:44 +08:00
|
|
|
fixturedeflist = self.getfixturedeflist(argname, parentid)
|
|
|
|
arg2fixturedeflist[argname] = fixturedeflist
|
|
|
|
if fixturedeflist is not None:
|
|
|
|
for fixturedef in fixturedeflist:
|
|
|
|
merge(fixturedef.fixturenames)
|
|
|
|
return fixturenames_closure, arg2fixturedeflist
|
2012-09-24 23:04:34 +08:00
|
|
|
|
2012-08-01 15:23:39 +08:00
|
|
|
def pytest_generate_tests(self, metafunc):
|
2012-10-05 20:24:44 +08:00
|
|
|
for argname in metafunc.fixturenames:
|
|
|
|
faclist = metafunc._arg2fixturedeflist[argname]
|
2012-08-01 15:23:39 +08:00
|
|
|
if faclist is None:
|
2012-10-05 20:24:44 +08:00
|
|
|
continue # will raise FixtureLookupError at setup time
|
|
|
|
for fixturedef in faclist:
|
|
|
|
if fixturedef.params is not None:
|
|
|
|
metafunc.parametrize(argname, fixturedef.params, indirect=True,
|
|
|
|
scope=fixturedef.scope)
|
2012-08-01 15:23:39 +08:00
|
|
|
|
|
|
|
def pytest_collection_modifyitems(self, items):
|
|
|
|
# separate parametrized setups
|
|
|
|
items[:] = parametrize_sorted(items, set(), {}, 0)
|
|
|
|
|
|
|
|
def pytest_runtest_teardown(self, item, nextitem):
|
|
|
|
try:
|
|
|
|
cs1 = item.callspec
|
|
|
|
except AttributeError:
|
|
|
|
return
|
2012-10-05 16:21:35 +08:00
|
|
|
|
|
|
|
# determine which fixtures are not needed anymore for the next test
|
|
|
|
keylist = []
|
2012-08-01 15:23:39 +08:00
|
|
|
for name in cs1.params:
|
|
|
|
try:
|
|
|
|
if name in nextitem.callspec.params and \
|
|
|
|
cs1.params[name] == nextitem.callspec.params[name]:
|
|
|
|
continue
|
|
|
|
except AttributeError:
|
|
|
|
pass
|
2012-10-05 16:21:35 +08:00
|
|
|
key = (-cs1._arg2scopenum[name], name, cs1.params[name])
|
|
|
|
keylist.append(key)
|
|
|
|
|
|
|
|
# sort by scope (function scope first, then higher ones)
|
|
|
|
keylist.sort()
|
|
|
|
for (scopenum, name, param) in keylist:
|
|
|
|
item.session._setupstate._callfinalizers((name, param))
|
2012-08-01 15:23:39 +08:00
|
|
|
l = self._arg2finish.get(name)
|
|
|
|
if l is not None:
|
|
|
|
for fin in l:
|
|
|
|
fin()
|
|
|
|
|
2012-09-18 16:54:12 +08:00
|
|
|
def _parsefactories(self, holderobj, nodeid, unittest=False):
|
2012-08-01 15:23:39 +08:00
|
|
|
if holderobj in self._holderobjseen:
|
|
|
|
return
|
|
|
|
self._holderobjseen.add(holderobj)
|
|
|
|
for name in dir(holderobj):
|
|
|
|
obj = getattr(holderobj, name)
|
|
|
|
if not callable(obj):
|
|
|
|
continue
|
2012-10-05 20:24:44 +08:00
|
|
|
# fixture functions have a pytest_funcarg__ prefix (pre-2.3 style)
|
2012-10-05 16:21:35 +08:00
|
|
|
# or are "@pytest.fixture" marked
|
2012-10-05 16:21:35 +08:00
|
|
|
marker = getattr(obj, "_pytestfixturefunction", None)
|
2012-10-05 16:21:35 +08:00
|
|
|
if marker is None:
|
|
|
|
if not name.startswith(self._argprefix):
|
2012-08-19 20:57:07 +08:00
|
|
|
continue
|
2012-10-05 16:21:35 +08:00
|
|
|
marker = defaultfuncargprefixmarker
|
|
|
|
name = name[len(self._argprefix):]
|
|
|
|
elif not isinstance(marker, FixtureFunctionMarker):
|
|
|
|
# magic globals with __getattr__ might have got us a wrong
|
|
|
|
# fixture attribute
|
2012-08-01 15:23:39 +08:00
|
|
|
continue
|
2012-10-05 16:21:35 +08:00
|
|
|
else:
|
|
|
|
assert not name.startswith(self._argprefix)
|
2012-10-05 20:24:44 +08:00
|
|
|
fixturedef = FixtureDef(self, nodeid, name, obj,
|
2012-10-05 16:21:35 +08:00
|
|
|
marker.scope, marker.params,
|
|
|
|
unittest=unittest)
|
2012-10-05 20:24:44 +08:00
|
|
|
faclist = self.arg2fixturedeflist.setdefault(name, [])
|
|
|
|
faclist.append(fixturedef)
|
2012-10-12 20:52:36 +08:00
|
|
|
if marker.autouse:
|
2012-10-05 16:21:35 +08:00
|
|
|
self._autofixtures.append(name)
|
2012-10-06 01:20:40 +08:00
|
|
|
try:
|
|
|
|
del self._defaultfixtures
|
|
|
|
except AttributeError:
|
|
|
|
pass
|
2012-08-01 15:23:39 +08:00
|
|
|
|
2012-10-05 20:24:44 +08:00
|
|
|
def getfixturedeflist(self, argname, nodeid):
|
2012-08-01 15:23:39 +08:00
|
|
|
try:
|
2012-10-05 20:24:44 +08:00
|
|
|
fixturedeflist = self.arg2fixturedeflist[argname]
|
2012-08-01 15:23:39 +08:00
|
|
|
except KeyError:
|
2012-09-24 23:04:34 +08:00
|
|
|
return None
|
2012-08-01 15:23:39 +08:00
|
|
|
else:
|
2012-10-05 20:24:44 +08:00
|
|
|
return list(self._matchfactories(fixturedeflist, nodeid))
|
2012-08-01 15:23:39 +08:00
|
|
|
|
2012-10-05 20:24:44 +08:00
|
|
|
def _matchfactories(self, fixturedeflist, nodeid):
|
|
|
|
for fixturedef in fixturedeflist:
|
|
|
|
if nodeid.startswith(fixturedef.baseid):
|
|
|
|
yield fixturedef
|
2012-08-01 15:23:39 +08:00
|
|
|
|
|
|
|
def addargfinalizer(self, finalizer, argname):
|
|
|
|
l = self._arg2finish.setdefault(argname, [])
|
|
|
|
l.append(finalizer)
|
|
|
|
|
|
|
|
def removefinalizer(self, finalizer):
|
|
|
|
for l in self._arg2finish.values():
|
|
|
|
try:
|
|
|
|
l.remove(finalizer)
|
|
|
|
except ValueError:
|
|
|
|
pass
|
|
|
|
|
2012-10-05 20:24:44 +08:00
|
|
|
class FixtureDef:
|
2012-10-05 16:21:35 +08:00
|
|
|
""" A container for a factory definition. """
|
2012-10-05 20:24:44 +08:00
|
|
|
def __init__(self, fixturenanager, baseid, argname, func, scope, params,
|
2012-10-05 16:21:35 +08:00
|
|
|
unittest=False):
|
2012-10-05 20:24:44 +08:00
|
|
|
self._fixturemanager = fixturenanager
|
2012-08-01 15:23:39 +08:00
|
|
|
self.baseid = baseid
|
|
|
|
self.func = func
|
2012-10-05 16:21:35 +08:00
|
|
|
self.argname = argname
|
|
|
|
self.scope = scope
|
|
|
|
self.scopenum = scopes.index(scope or "function")
|
|
|
|
self.params = params
|
2012-09-18 19:46:24 +08:00
|
|
|
startindex = unittest and 1 or None
|
2012-10-05 20:24:44 +08:00
|
|
|
self.fixturenames = getfuncargnames(func, startindex=startindex)
|
2012-10-05 16:21:35 +08:00
|
|
|
self.unittest = unittest
|
2012-08-01 15:23:39 +08:00
|
|
|
self.active = False
|
|
|
|
self._finalizer = []
|
|
|
|
|
|
|
|
def addfinalizer(self, finalizer):
|
|
|
|
self._finalizer.append(finalizer)
|
|
|
|
|
|
|
|
def finish(self):
|
|
|
|
while self._finalizer:
|
|
|
|
func = self._finalizer.pop()
|
|
|
|
func()
|
|
|
|
# check neccesity of next commented call
|
2012-10-05 20:24:44 +08:00
|
|
|
self._fixturemanager.removefinalizer(self.finish)
|
2012-08-01 15:23:39 +08:00
|
|
|
self.active = False
|
2012-10-05 16:21:35 +08:00
|
|
|
#print "finished", self
|
|
|
|
#del self.cached_result
|
|
|
|
|
|
|
|
def execute(self, request):
|
|
|
|
kwargs = {}
|
2012-10-05 20:24:44 +08:00
|
|
|
for newname in self.fixturenames:
|
2012-10-05 16:21:35 +08:00
|
|
|
kwargs[newname] = request.getfuncargvalue(newname)
|
|
|
|
if self.unittest:
|
|
|
|
result = self.func(request.instance, **kwargs)
|
|
|
|
else:
|
|
|
|
result = self.func(**kwargs)
|
|
|
|
self.active = True
|
|
|
|
self.cached_result = result
|
|
|
|
return result
|
2012-08-01 15:23:39 +08:00
|
|
|
|
2012-10-05 16:21:35 +08:00
|
|
|
def __repr__(self):
|
2012-10-05 20:24:44 +08:00
|
|
|
return "<FixtureDef name=%r scope=%r>" % (self.argname, self.scope)
|
2012-08-01 15:23:39 +08:00
|
|
|
|
|
|
|
def getfuncargnames(function, startindex=None):
|
|
|
|
# XXX merge with main.py's varnames
|
2012-10-08 17:22:31 +08:00
|
|
|
#assert not inspect.isclass(function)
|
|
|
|
if startindex is None:
|
2012-09-18 20:00:47 +08:00
|
|
|
startindex = inspect.ismethod(function) and 1 or 0
|
|
|
|
argnames = inspect.getargs(py.code.getrawcode(function))[0]
|
2012-08-01 15:23:39 +08:00
|
|
|
defaults = getattr(function, 'func_defaults',
|
|
|
|
getattr(function, '__defaults__', None)) or ()
|
|
|
|
numdefaults = len(defaults)
|
|
|
|
if numdefaults:
|
2012-10-16 19:47:59 +08:00
|
|
|
return tuple(argnames[startindex:-numdefaults])
|
|
|
|
return tuple(argnames[startindex:])
|
2012-08-01 15:23:39 +08:00
|
|
|
|
|
|
|
# algorithm for sorting on a per-parametrized resource setup basis
|
|
|
|
|
|
|
|
def parametrize_sorted(items, ignore, cache, scopenum):
|
|
|
|
if scopenum >= 3:
|
|
|
|
return items
|
|
|
|
newitems = []
|
|
|
|
olditems = []
|
|
|
|
slicing_argparam = None
|
|
|
|
for item in items:
|
|
|
|
argparamlist = getfuncargparams(item, ignore, scopenum, cache)
|
|
|
|
if slicing_argparam is None and argparamlist:
|
|
|
|
slicing_argparam = argparamlist[0]
|
|
|
|
slicing_index = len(olditems)
|
|
|
|
if slicing_argparam in argparamlist:
|
|
|
|
newitems.append(item)
|
|
|
|
else:
|
|
|
|
olditems.append(item)
|
|
|
|
if newitems:
|
|
|
|
newignore = ignore.copy()
|
|
|
|
newignore.add(slicing_argparam)
|
|
|
|
newitems = parametrize_sorted(newitems + olditems[slicing_index:],
|
|
|
|
newignore, cache, scopenum)
|
|
|
|
old1 = parametrize_sorted(olditems[:slicing_index], newignore,
|
|
|
|
cache, scopenum+1)
|
|
|
|
return old1 + newitems
|
|
|
|
else:
|
|
|
|
olditems = parametrize_sorted(olditems, ignore, cache, scopenum+1)
|
|
|
|
return olditems + newitems
|
|
|
|
|
|
|
|
def getfuncargparams(item, ignore, scopenum, cache):
|
|
|
|
""" return list of (arg,param) tuple, sorted by broader scope first. """
|
|
|
|
assert scopenum < 3 # function
|
|
|
|
try:
|
|
|
|
cs = item.callspec
|
|
|
|
except AttributeError:
|
|
|
|
return []
|
|
|
|
if scopenum == 0:
|
|
|
|
argparams = [x for x in cs.params.items() if x not in ignore
|
|
|
|
and cs._arg2scopenum[x[0]] == scopenum]
|
|
|
|
elif scopenum == 1: # module
|
|
|
|
argparams = []
|
|
|
|
for argname, param in cs.params.items():
|
|
|
|
if cs._arg2scopenum[argname] == scopenum:
|
|
|
|
key = (argname, param, item.fspath)
|
|
|
|
if key in ignore:
|
|
|
|
continue
|
|
|
|
argparams.append(key)
|
|
|
|
elif scopenum == 2: # class
|
|
|
|
argparams = []
|
|
|
|
for argname, param in cs.params.items():
|
|
|
|
if cs._arg2scopenum[argname] == scopenum:
|
|
|
|
l = cache.setdefault(item.fspath, [])
|
|
|
|
try:
|
|
|
|
i = l.index(item.cls)
|
|
|
|
except ValueError:
|
|
|
|
i = len(l)
|
|
|
|
l.append(item.cls)
|
|
|
|
key = (argname, param, item.fspath, i)
|
|
|
|
if key in ignore:
|
|
|
|
continue
|
|
|
|
argparams.append(key)
|
|
|
|
#elif scopenum == 3:
|
|
|
|
# argparams = []
|
|
|
|
# for argname, param in cs.params.items():
|
|
|
|
# if cs._arg2scopenum[argname] == scopenum:
|
|
|
|
# key = (argname, param, getfslineno(item.obj))
|
|
|
|
# if key in ignore:
|
|
|
|
# continue
|
|
|
|
# argparams.append(key)
|
|
|
|
return argparams
|
|
|
|
|
2012-08-13 19:37:14 +08:00
|
|
|
|
|
|
|
def xunitsetup(obj, name):
|
|
|
|
meth = getattr(obj, name, None)
|
|
|
|
if meth is not None:
|
2012-10-05 16:21:35 +08:00
|
|
|
if not hasattr(meth, "_pytestfixturefunction"):
|
2012-08-13 19:37:14 +08:00
|
|
|
return meth
|