2010-11-06 18:38:53 +08:00
|
|
|
""" Python test discovery, setup and run of test functions. """
|
2015-08-07 13:31:04 +08:00
|
|
|
import re
|
2014-10-17 06:27:10 +08:00
|
|
|
import fnmatch
|
2015-07-13 23:16:51 +08:00
|
|
|
import functools
|
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
|
2015-03-24 03:01:58 +08:00
|
|
|
from _pytest.mark import MarkDecorator, MarkerError
|
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
|
2015-04-29 22:40:51 +08:00
|
|
|
import pluggy
|
|
|
|
|
|
|
|
cutdir2 = py.path.local(_pytest.__file__).dirpath()
|
|
|
|
cutdir1 = py.path.local(pluggy.__file__.rstrip("oc"))
|
|
|
|
|
2010-10-10 19:48:49 +08:00
|
|
|
|
2013-07-16 21:43:20 +08:00
|
|
|
NoneType = type(None)
|
2013-11-21 20:15:32 +08:00
|
|
|
NOTSET = object()
|
2014-03-12 05:10:18 +08:00
|
|
|
isfunction = inspect.isfunction
|
|
|
|
isclass = inspect.isclass
|
2012-10-19 16:07:11 +08:00
|
|
|
callable = py.builtin.callable
|
2015-01-10 02:55:49 +08:00
|
|
|
# used to work around a python2 exception info leak
|
|
|
|
exc_clear = getattr(sys, 'exc_clear', lambda: None)
|
2012-10-19 16:07:11 +08:00
|
|
|
|
2015-04-29 22:40:51 +08:00
|
|
|
def filter_traceback(entry):
|
|
|
|
return entry.path != cutdir1 and not entry.path.relto(cutdir2)
|
|
|
|
|
|
|
|
|
2015-07-03 10:13:59 +08:00
|
|
|
def get_real_func(obj):
|
|
|
|
"""gets the real function object of the (possibly) wrapped object by
|
|
|
|
functools.wraps or functools.partial.
|
|
|
|
"""
|
2013-11-20 06:22:27 +08:00
|
|
|
while hasattr(obj, "__wrapped__"):
|
|
|
|
obj = obj.__wrapped__
|
2015-07-13 23:16:51 +08:00
|
|
|
if isinstance(obj, functools.partial):
|
2015-07-03 10:13:59 +08:00
|
|
|
obj = obj.func
|
|
|
|
return obj
|
|
|
|
|
|
|
|
def getfslineno(obj):
|
|
|
|
# xxx let decorators etc specify a sane ordering
|
|
|
|
obj = get_real_func(obj)
|
2013-11-20 06:22:27 +08:00
|
|
|
if hasattr(obj, 'place_as'):
|
|
|
|
obj = obj.place_as
|
|
|
|
fslineno = py.code.getfslineno(obj)
|
|
|
|
assert isinstance(fslineno[1], int), obj
|
|
|
|
return fslineno
|
|
|
|
|
2012-10-20 15:59:20 +08:00
|
|
|
def getimfunc(func):
|
|
|
|
try:
|
|
|
|
return func.__func__
|
|
|
|
except AttributeError:
|
|
|
|
try:
|
|
|
|
return func.im_func
|
|
|
|
except AttributeError:
|
|
|
|
return func
|
|
|
|
|
|
|
|
|
2012-10-05 16:21:35 +08:00
|
|
|
class FixtureFunctionMarker:
|
2013-12-16 06:15:15 +08:00
|
|
|
def __init__(self, scope, params,
|
|
|
|
autouse=False, yieldctx=False, ids=None):
|
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
|
2013-09-26 18:57:21 +08:00
|
|
|
self.yieldctx = yieldctx
|
2013-12-16 06:15:15 +08:00
|
|
|
self.ids = ids
|
2012-10-05 16:21:35 +08:00
|
|
|
|
2012-08-02 18:41:46 +08:00
|
|
|
def __call__(self, function):
|
2014-03-12 05:10:18 +08:00
|
|
|
if isclass(function):
|
2013-09-26 18:57:21 +08:00
|
|
|
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
|
|
|
|
|
|
|
|
|
2013-12-16 06:15:15 +08:00
|
|
|
def fixture(scope="function", params=None, autouse=False, ids=None):
|
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.
|
2013-09-26 18:57:21 +08:00
|
|
|
|
2013-12-16 18:51:50 +08:00
|
|
|
:arg ids: list of string ids each corresponding to the params
|
2013-12-16 06:15:15 +08:00
|
|
|
so that they are part of the test id. If no ids are provided
|
2013-12-16 18:51:50 +08:00
|
|
|
they will be generated automatically from the params.
|
2013-12-16 06:15:15 +08:00
|
|
|
|
2012-08-02 18:41:46 +08:00
|
|
|
"""
|
2012-10-19 16:07:11 +08:00
|
|
|
if callable(scope) and params is None and autouse == False:
|
2012-10-07 03:03:55 +08:00
|
|
|
# direct decoration
|
2013-09-26 18:57:21 +08:00
|
|
|
return FixtureFunctionMarker(
|
2013-09-30 19:42:39 +08:00
|
|
|
"function", params, autouse)(scope)
|
2013-12-09 17:48:15 +08:00
|
|
|
if params is not None and not isinstance(params, (list, tuple)):
|
|
|
|
params = list(params)
|
2013-12-16 06:15:15 +08:00
|
|
|
return FixtureFunctionMarker(scope, params, autouse, ids=ids)
|
2013-09-30 19:42:39 +08:00
|
|
|
|
2013-12-16 06:15:15 +08:00
|
|
|
def yield_fixture(scope="function", params=None, autouse=False, ids=None):
|
2013-09-30 19:42:39 +08:00
|
|
|
""" (return a) decorator to mark a yield-fixture factory function
|
|
|
|
(EXPERIMENTAL).
|
|
|
|
|
|
|
|
This takes the same arguments as :py:func:`pytest.fixture` but
|
|
|
|
expects a fixture function to use a ``yield`` instead of a ``return``
|
|
|
|
statement to provide a fixture. See
|
|
|
|
http://pytest.org/en/latest/yieldfixture.html for more info.
|
|
|
|
"""
|
|
|
|
if callable(scope) and params is None and autouse == False:
|
|
|
|
# direct decoration
|
|
|
|
return FixtureFunctionMarker(
|
|
|
|
"function", params, autouse, yieldctx=True)(scope)
|
|
|
|
else:
|
2013-12-16 06:15:15 +08:00
|
|
|
return FixtureFunctionMarker(scope, params, autouse,
|
|
|
|
yieldctx=True, ids=ids)
|
2012-08-02 18:41:46 +08:00
|
|
|
|
2012-10-05 16:21:35 +08:00
|
|
|
defaultfuncargprefixmarker = fixture()
|
|
|
|
|
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-17 18:57:05 +08:00
|
|
|
group.addoption('--fixtures', '--funcargs',
|
2012-10-05 20:24:44 +08:00
|
|
|
action="store_true", dest="showfixtures", default=False,
|
|
|
|
help="show available fixtures, sorted by plugin appearance")
|
2012-10-16 22:13:12 +08:00
|
|
|
parser.addini("usefixtures", type="args", default=[],
|
2012-10-06 01:20:40 +08:00
|
|
|
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",
|
2014-10-03 05:32:35 +08:00
|
|
|
default=['test_*.py', '*_test.py'],
|
2010-11-25 05:01:04 +08:00
|
|
|
help="glob-style file patterns for Python test module discovery")
|
2014-10-03 05:32:35 +08:00
|
|
|
parser.addini("python_classes", type="args", default=["Test",],
|
2014-10-17 06:27:10 +08:00
|
|
|
help="prefixes or glob names for Python test class discovery")
|
2014-10-03 05:32:35 +08:00
|
|
|
parser.addini("python_functions", type="args", default=["test",],
|
2014-10-17 06:27:10 +08:00
|
|
|
help="prefixes or glob names 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):
|
2015-03-22 06:30:13 +08:00
|
|
|
# this misspelling is common - raise a specific error to alert the user
|
|
|
|
if hasattr(metafunc.function, 'parameterize'):
|
2015-03-24 03:01:58 +08:00
|
|
|
msg = "{0} has 'parameterize', spelling should be 'parametrize'"
|
|
|
|
raise MarkerError(msg.format(metafunc.function.__name__))
|
2011-11-17 19:09:21 +08:00
|
|
|
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 "
|
2013-12-10 17:16:27 +08:00
|
|
|
"times passing in different arguments in turn. argvalues generally "
|
|
|
|
"needs to be a list of values if argnames specifies only one name "
|
|
|
|
"or a list of tuples of values if argnames specifies multiple names. "
|
|
|
|
"Example: @parametrize('arg1', [1,2]) would lead to two calls of the "
|
|
|
|
"decorated test function, one with arg1=1 and another with arg1=2."
|
|
|
|
"see http://pytest.org/latest/parametrize.html for more info and "
|
2012-10-20 19:56:53 +08:00
|
|
|
"examples."
|
2011-11-17 19:09:21 +08:00
|
|
|
)
|
2012-10-19 16:17:13 +08:00
|
|
|
config.addinivalue_line("markers",
|
|
|
|
"usefixtures(fixturename1, fixturename2, ...): mark tests as needing "
|
2012-10-20 19:56:53 +08:00
|
|
|
"all of the specified fixtures. see http://pytest.org/latest/fixture.html#usefixtures "
|
2012-10-19 16:17:13 +08:00
|
|
|
)
|
2011-11-17 19:09:21 +08:00
|
|
|
|
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
|
|
|
|
2015-05-06 16:08:08 +08:00
|
|
|
@pytest.hookimpl(trylast=True)
|
2010-11-22 06:17:59 +08:00
|
|
|
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,
|
2013-09-30 19:42:39 +08:00
|
|
|
'yield_fixture': yield_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
|
|
|
|
2013-10-21 19:33:36 +08:00
|
|
|
@fixture(scope="session")
|
2012-10-05 20:24:44 +08:00
|
|
|
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
|
|
|
|
2015-05-06 16:08:08 +08:00
|
|
|
@pytest.hookimpl(trylast=True)
|
2014-10-09 02:23:40 +08:00
|
|
|
def pytest_pyfunc_call(pyfuncitem):
|
|
|
|
testfunction = pyfuncitem.obj
|
|
|
|
if pyfuncitem._isyieldedfunction():
|
|
|
|
testfunction(*pyfuncitem._args)
|
|
|
|
else:
|
|
|
|
funcargs = pyfuncitem.funcargs
|
|
|
|
testargs = {}
|
|
|
|
for arg in pyfuncitem._fixtureinfo.argnames:
|
|
|
|
testargs[arg] = funcargs[arg]
|
|
|
|
testfunction(**testargs)
|
|
|
|
return True
|
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
|
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
|
2012-10-22 16:17:50 +08:00
|
|
|
ihook = parent.session.gethookproxy(path)
|
|
|
|
return ihook.pytest_pycollect_makemodule(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
|
|
|
|
2015-05-06 16:08:08 +08:00
|
|
|
@pytest.hookimpl(hookwrapper=True)
|
2014-10-09 02:23:40 +08:00
|
|
|
def pytest_pycollect_makeitem(collector, name, obj):
|
|
|
|
outcome = yield
|
|
|
|
res = outcome.get_result()
|
2010-09-26 00:23:26 +08:00
|
|
|
if res is not None:
|
2014-10-09 02:23:40 +08:00
|
|
|
raise StopIteration
|
|
|
|
# nothing was collected elsewhere, let's do it here
|
2014-03-12 05:10:18 +08:00
|
|
|
if isclass(obj):
|
2011-03-16 23:36:18 +08:00
|
|
|
if collector.classnamefilter(name):
|
2013-02-15 17:18:00 +08:00
|
|
|
Class = collector._getcustomclass("Class")
|
2014-10-09 02:23:40 +08:00
|
|
|
outcome.force_result(Class(name, parent=collector))
|
|
|
|
elif collector.funcnamefilter(name) and hasattr(obj, "__call__") and\
|
2013-04-29 16:31:51 +08:00
|
|
|
getfixturemarker(obj) is None:
|
2014-10-09 02:23:40 +08:00
|
|
|
# mock seems to store unbound methods (issue473), normalize it
|
2014-04-08 18:50:13 +08:00
|
|
|
obj = getattr(obj, "__func__", obj)
|
2014-03-12 05:10:18 +08:00
|
|
|
if not isfunction(obj):
|
|
|
|
collector.warn(code="C2", message=
|
|
|
|
"cannot collect %r because it is not a function."
|
|
|
|
% name, )
|
2014-04-10 19:37:39 +08:00
|
|
|
if getattr(obj, "__test__", True):
|
|
|
|
if is_generator(obj):
|
2014-10-09 02:23:40 +08:00
|
|
|
res = Generator(name, parent=collector)
|
2014-04-10 19:37:39 +08:00
|
|
|
else:
|
2014-10-09 02:23:40 +08:00
|
|
|
res = list(collector._genfunctions(name, obj))
|
|
|
|
outcome.force_result(res)
|
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
|
|
|
|
else:
|
2012-07-20 20:16:28 +08:00
|
|
|
fspath, lineno = getfslineno(obj)
|
2013-12-03 18:23:22 +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):
|
2010-07-27 03:15:15 +08:00
|
|
|
|
|
|
|
def funcnamefilter(self, name):
|
2014-10-17 06:27:10 +08:00
|
|
|
return self._matches_prefix_or_glob_option('python_functions', name)
|
2011-01-18 19:47:31 +08:00
|
|
|
|
2010-07-27 03:15:15 +08:00
|
|
|
def classnamefilter(self, name):
|
2014-10-17 06:27:10 +08:00
|
|
|
return self._matches_prefix_or_glob_option('python_classes', name)
|
|
|
|
|
|
|
|
def _matches_prefix_or_glob_option(self, option_name, name):
|
|
|
|
"""
|
|
|
|
checks if the given name matches the prefix or glob-pattern defined
|
|
|
|
in ini configuration.
|
|
|
|
"""
|
|
|
|
for option in self.config.getini(option_name):
|
|
|
|
if name.startswith(option):
|
|
|
|
return True
|
2014-10-21 04:36:31 +08:00
|
|
|
# check that name looks like a glob-string before calling fnmatch
|
|
|
|
# because this is called for every name in each collected module,
|
|
|
|
# and fnmatch is somewhat expensive to call
|
|
|
|
elif ('*' in option or '?' in option or '[' in option) and \
|
|
|
|
fnmatch.fnmatch(name, option):
|
2010-11-25 05:01:04 +08:00
|
|
|
return True
|
2014-10-17 06:27:10 +08:00
|
|
|
return False
|
2008-08-16 23:26:59 +08:00
|
|
|
|
2008-09-02 16:58:14 +08:00
|
|
|
def collect(self):
|
2014-04-10 18:46:27 +08:00
|
|
|
if not getattr(self.obj, "__test__", True):
|
|
|
|
return []
|
|
|
|
|
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
|
2012-11-28 00:58:08 +08:00
|
|
|
res = self.makeitem(name, obj)
|
|
|
|
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):
|
2012-10-22 22:12:22 +08:00
|
|
|
#assert self.ihook.fspath == self.fspath, self
|
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-17 17:20:45 +08:00
|
|
|
fm = self.session._fixturemanager
|
|
|
|
fixtureinfo = fm.getfixtureinfo(self, funcobj, cls)
|
2012-10-16 19:47:59 +08:00
|
|
|
metafunc = Metafunc(funcobj, fixtureinfo, self.config,
|
|
|
|
cls=cls, module=module)
|
2015-04-25 17:29:11 +08:00
|
|
|
methods = []
|
|
|
|
if hasattr(module, "pytest_generate_tests"):
|
|
|
|
methods.append(module.pytest_generate_tests)
|
2014-10-01 18:19:11 +08:00
|
|
|
if hasattr(cls, "pytest_generate_tests"):
|
|
|
|
methods.append(cls().pytest_generate_tests)
|
2015-04-25 17:29:11 +08:00
|
|
|
if methods:
|
2015-04-25 19:38:30 +08:00
|
|
|
self.ihook.pytest_generate_tests.call_extra(methods,
|
|
|
|
dict(metafunc=metafunc))
|
2015-04-25 17:29:11 +08:00
|
|
|
else:
|
|
|
|
self.ihook.pytest_generate_tests(metafunc=metafunc)
|
2014-10-01 18:19:11 +08:00
|
|
|
|
2011-03-05 21:16:27 +08:00
|
|
|
Function = self._getcustomclass("Function")
|
2012-07-19 15:20:14 +08:00
|
|
|
if not metafunc._calls:
|
2014-10-06 20:06:17 +08:00
|
|
|
yield Function(name, parent=self, fixtureinfo=fixtureinfo)
|
2012-10-06 17:34:06 +08:00
|
|
|
else:
|
2013-12-07 23:37:46 +08:00
|
|
|
# add funcargs() as fixturedefs to fixtureinfo.arg2fixturedefs
|
|
|
|
add_funcarg_pseudo_fixture_def(self, metafunc, fm)
|
|
|
|
|
2012-10-06 17:34:06 +08:00
|
|
|
for callspec in metafunc._calls:
|
|
|
|
subname = "%s[%s]" %(name, callspec.id)
|
|
|
|
yield Function(name=subname, parent=self,
|
|
|
|
callspec=callspec, callobj=funcobj,
|
2014-10-06 20:06:17 +08:00
|
|
|
fixtureinfo=fixtureinfo,
|
2012-10-06 17:34:06 +08:00
|
|
|
keywords={callspec.id:True})
|
2010-07-27 03:15:15 +08:00
|
|
|
|
2013-12-07 23:37:46 +08:00
|
|
|
def add_funcarg_pseudo_fixture_def(collector, metafunc, fixturemanager):
|
|
|
|
# this function will transform all collected calls to a functions
|
|
|
|
# if they use direct funcargs (i.e. direct parametrization)
|
|
|
|
# because we want later test execution to be able to rely on
|
|
|
|
# an existing FixtureDef structure for all arguments.
|
|
|
|
# XXX we can probably avoid this algorithm if we modify CallSpec2
|
|
|
|
# to directly care for creating the fixturedefs within its methods.
|
|
|
|
if not metafunc._calls[0].funcargs:
|
|
|
|
return # this function call does not have direct parametrization
|
|
|
|
# collect funcargs of all callspecs into a list of values
|
|
|
|
arg2params = {}
|
|
|
|
arg2scope = {}
|
2014-01-27 19:53:44 +08:00
|
|
|
for callspec in metafunc._calls:
|
2013-12-07 23:37:46 +08:00
|
|
|
for argname, argvalue in callspec.funcargs.items():
|
2014-01-27 19:53:44 +08:00
|
|
|
assert argname not in callspec.params
|
|
|
|
callspec.params[argname] = argvalue
|
|
|
|
arg2params_list = arg2params.setdefault(argname, [])
|
|
|
|
callspec.indices[argname] = len(arg2params_list)
|
|
|
|
arg2params_list.append(argvalue)
|
2013-12-07 23:37:46 +08:00
|
|
|
if argname not in arg2scope:
|
2014-01-27 19:53:44 +08:00
|
|
|
scopenum = callspec._arg2scopenum.get(argname,
|
|
|
|
scopenum_function)
|
2013-12-07 23:37:46 +08:00
|
|
|
arg2scope[argname] = scopes[scopenum]
|
|
|
|
callspec.funcargs.clear()
|
|
|
|
|
|
|
|
# register artificial FixtureDef's so that later at test execution
|
|
|
|
# time we can rely on a proper FixtureDef to exist for fixture setup.
|
2014-01-27 19:53:44 +08:00
|
|
|
arg2fixturedefs = metafunc._arg2fixturedefs
|
2013-12-07 23:37:46 +08:00
|
|
|
for argname, valuelist in arg2params.items():
|
|
|
|
# if we have a scope that is higher than function we need
|
|
|
|
# to make sure we only ever create an according fixturedef on
|
|
|
|
# a per-scope basis. We thus store and cache the fixturedef on the
|
|
|
|
# node related to the scope.
|
|
|
|
scope = arg2scope[argname]
|
|
|
|
node = None
|
|
|
|
if scope != "function":
|
|
|
|
node = get_scope_node(collector, scope)
|
|
|
|
if node is None:
|
|
|
|
assert scope == "class" and isinstance(collector, Module)
|
|
|
|
# use module-level collector for class-scope (for now)
|
|
|
|
node = collector
|
|
|
|
if node and argname in node._name2pseudofixturedef:
|
|
|
|
arg2fixturedefs[argname] = [node._name2pseudofixturedef[argname]]
|
|
|
|
else:
|
|
|
|
fixturedef = FixtureDef(fixturemanager, '', argname,
|
|
|
|
get_direct_param_fixture_func,
|
|
|
|
arg2scope[argname],
|
|
|
|
valuelist, False, False)
|
|
|
|
arg2fixturedefs[argname] = [fixturedef]
|
|
|
|
if node is not None:
|
|
|
|
node._name2pseudofixturedef[argname] = fixturedef
|
|
|
|
|
|
|
|
|
|
|
|
def get_direct_param_fixture_func(request):
|
|
|
|
return request.param
|
2012-10-16 19:47:59 +08:00
|
|
|
|
|
|
|
class FuncFixtureInfo:
|
2012-10-16 20:19:38 +08:00
|
|
|
def __init__(self, argnames, names_closure, name2fixturedefs):
|
|
|
|
self.argnames = argnames
|
2012-10-16 19:47:59 +08:00
|
|
|
self.names_closure = names_closure
|
2012-10-16 19:59:12 +08:00
|
|
|
self.name2fixturedefs = name2fixturedefs
|
2012-10-16 19:48:00 +08:00
|
|
|
|
2015-07-25 22:28:18 +08:00
|
|
|
|
|
|
|
def _marked(func, mark):
|
|
|
|
"""Returns True if :func: is already marked with :mark:, False orherwise.
|
|
|
|
This can happen if marker is applied to class and the test file is
|
|
|
|
invoked more than once.
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
func_mark = getattr(func, mark.name)
|
|
|
|
except AttributeError:
|
|
|
|
return False
|
|
|
|
return mark.args == func_mark.args and mark.kwargs == func_mark.kwargs
|
|
|
|
|
|
|
|
|
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:
|
2015-07-25 22:28:18 +08:00
|
|
|
if not _marked(funcobj, mark):
|
|
|
|
mark(funcobj)
|
2011-12-28 23:47:19 +08:00
|
|
|
else:
|
2015-07-25 22:28:18 +08:00
|
|
|
if not _marked(funcobj, pytestmark):
|
|
|
|
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-16 22:13:12 +08:00
|
|
|
self.session._fixturemanager.parsefactories(self)
|
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:
|
2015-04-18 04:25:35 +08:00
|
|
|
mod = self.fspath.pyimport(ensuresyspath="append")
|
2010-07-04 23:06:50 +08:00
|
|
|
except SyntaxError:
|
2014-04-02 21:34:36 +08:00
|
|
|
raise self.CollectError(
|
|
|
|
py.code.ExceptionInfo().getrepr(style="short"))
|
2010-07-04 23:06:50 +08:00
|
|
|
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):
|
2013-06-20 22:43:42 +08:00
|
|
|
setup_module = xunitsetup(self.obj, "setUpModule")
|
|
|
|
if setup_module is None:
|
|
|
|
setup_module = xunitsetup(self.obj, "setup_module")
|
2012-08-13 19:37:14 +08:00
|
|
|
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()
|
2013-08-02 15:52:40 +08:00
|
|
|
fin = getattr(self.obj, 'tearDownModule', None)
|
|
|
|
if fin is None:
|
|
|
|
fin = getattr(self.obj, 'teardown_module', None)
|
|
|
|
if fin is not None:
|
2009-10-23 22:17:06 +08:00
|
|
|
#XXX: nose compat hack, move to nose plugin
|
2014-01-18 19:39:16 +08:00
|
|
|
# if it takes a positional arg, it's probably a pytest style one
|
2009-10-23 22:17:06 +08:00
|
|
|
# so we pass the current module object
|
2013-08-02 15:52:40 +08:00
|
|
|
if inspect.getargspec(fin)[0]:
|
|
|
|
finalizer = lambda: fin(self.obj)
|
2009-10-23 22:17:06 +08:00
|
|
|
else:
|
2013-08-02 15:52:40 +08:00
|
|
|
finalizer = fin
|
|
|
|
self.addfinalizer(finalizer)
|
|
|
|
|
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):
|
2013-02-15 17:18:00 +08:00
|
|
|
if hasinit(self.obj):
|
2014-03-12 05:10:18 +08:00
|
|
|
self.warn("C1", "cannot collect test class %r because it has a "
|
|
|
|
"__init__ constructor" % self.obj.__name__)
|
|
|
|
return []
|
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)
|
|
|
|
|
2013-08-02 15:52:40 +08:00
|
|
|
fin_class = getattr(self.obj, 'teardown_class', None)
|
|
|
|
if fin_class is not None:
|
|
|
|
fin_class = getattr(fin_class, 'im_func', fin_class)
|
|
|
|
fin_class = getattr(fin_class, '__func__', fin_class)
|
|
|
|
self.addfinalizer(lambda: fin_class(self.obj))
|
2010-07-27 03:15:15 +08:00
|
|
|
|
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-16 22:13:12 +08:00
|
|
|
self.session._fixturemanager.parsefactories(self)
|
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):
|
2013-08-02 15:52:40 +08:00
|
|
|
setup_name = 'setup_method'
|
|
|
|
teardown_name = 'teardown_method'
|
2011-03-03 01:03:43 +08:00
|
|
|
else:
|
2013-08-02 15:52:40 +08:00
|
|
|
setup_name = 'setup_function'
|
|
|
|
teardown_name = 'teardown_function'
|
|
|
|
setup_func_or_method = xunitsetup(obj, setup_name)
|
2010-07-27 03:15:15 +08:00
|
|
|
if setup_func_or_method is not None:
|
|
|
|
setup_func_or_method(self.obj)
|
2013-08-02 15:52:40 +08:00
|
|
|
fin = getattr(obj, teardown_name, None)
|
|
|
|
if fin is not None:
|
|
|
|
self.addfinalizer(lambda: fin(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:
|
2015-07-13 23:16:51 +08:00
|
|
|
code = py.code.Code(get_real_func(self.obj))
|
2010-07-27 03:15:15 +08:00
|
|
|
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:
|
2015-04-29 22:40:51 +08:00
|
|
|
#ntraceback = ntraceback.cut(excludepath=cutdir2)
|
|
|
|
ntraceback = ntraceback.filter(filter_traceback)
|
|
|
|
if not ntraceback:
|
|
|
|
ntraceback = traceback
|
|
|
|
|
2010-11-06 06:37:31 +08:00
|
|
|
excinfo.traceback = ntraceback.filter()
|
2014-06-29 19:32:53 +08:00
|
|
|
# issue364: mark all but first and last frames to
|
|
|
|
# only show a single-line message for each frame
|
|
|
|
if self.config.option.tbstyle == "auto":
|
|
|
|
if len(excinfo.traceback) > 2:
|
|
|
|
for entry in excinfo.traceback[1:-1]:
|
|
|
|
entry.set_repr_style('short')
|
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"
|
2014-06-29 19:32:53 +08:00
|
|
|
style = self.config.option.tbstyle
|
|
|
|
if style == "auto":
|
|
|
|
style = "long"
|
|
|
|
return self._repr_failure_py(excinfo, style=style)
|
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)
|
2012-10-19 16:07:11 +08:00
|
|
|
if not 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. """
|
2013-12-07 23:37:46 +08:00
|
|
|
try:
|
|
|
|
request = function._request
|
|
|
|
except AttributeError:
|
|
|
|
# XXX this special code path is only expected to execute
|
|
|
|
# with the oejskit plugin. It uses classes with funcargs
|
|
|
|
# and we thus have to work a bit to allow this.
|
|
|
|
fm = function.session._fixturemanager
|
|
|
|
fi = fm.getfixtureinfo(function.parent, function.obj, None)
|
|
|
|
function._fixtureinfo = fi
|
|
|
|
request = function._request = FixtureRequest(function)
|
|
|
|
request._fillfixtures()
|
|
|
|
# prune out funcargs for jstests
|
|
|
|
newfuncargs = {}
|
|
|
|
for name in fi.argnames:
|
|
|
|
newfuncargs[name] = function.funcargs[name]
|
|
|
|
function.funcargs = newfuncargs
|
|
|
|
else:
|
|
|
|
request._fillfixtures()
|
2012-10-17 17:20:45 +08:00
|
|
|
|
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
|
2013-05-17 16:46:36 +08:00
|
|
|
self.keywords = {}
|
2013-12-04 04:05:19 +08:00
|
|
|
self.indices = {}
|
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)
|
2013-05-17 16:46:36 +08:00
|
|
|
cs.keywords.update(self.keywords)
|
2013-12-04 04:05:19 +08:00
|
|
|
cs.indices.update(self.indices)
|
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
|
|
|
|
2013-12-04 04:05:19 +08:00
|
|
|
def setmulti(self, valtype, argnames, valset, id, keywords, scopenum,
|
|
|
|
param_index):
|
2011-11-17 19:09:21 +08:00
|
|
|
for arg,val in zip(argnames, valset):
|
|
|
|
self._checkargnotcontained(arg)
|
|
|
|
getattr(self, valtype)[arg] = val
|
2013-12-04 04:05:19 +08:00
|
|
|
self.indices[arg] = param_index
|
2012-07-30 16:46:03 +08:00
|
|
|
self._arg2scopenum[arg] = scopenum
|
2012-10-28 21:52:43 +08:00
|
|
|
if val is _notexists:
|
2012-10-06 17:34:06 +08:00
|
|
|
self._emptyparamspecified = True
|
2011-11-17 19:09:21 +08:00
|
|
|
self._idlist.append(id)
|
2013-05-17 16:46:36 +08:00
|
|
|
self.keywords.update(keywords)
|
2011-11-17 19:09:21 +08:00
|
|
|
|
|
|
|
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
|
2013-12-07 23:37:46 +08:00
|
|
|
for arg in funcargs:
|
|
|
|
self._arg2scopenum[arg] = scopenum_function
|
2011-11-17 19:09:21 +08:00
|
|
|
|
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):
|
2015-07-10 08:50:38 +08:00
|
|
|
"""
|
|
|
|
Metafunc objects are passed to the ``pytest_generate_tests`` hook.
|
|
|
|
They help to inspect a test function and to generate tests according to
|
|
|
|
test configuration or values specified in the class or module where a
|
|
|
|
test function is defined.
|
|
|
|
|
|
|
|
:ivar fixturenames: set of fixture names required by the test function
|
|
|
|
|
|
|
|
:ivar function: underlying python test function
|
|
|
|
|
|
|
|
:ivar cls: class object where the test function is defined in or ``None``.
|
|
|
|
|
|
|
|
:ivar module: the module object where the test function is defined in.
|
|
|
|
|
|
|
|
:ivar config: access to the :class:`_pytest.config.Config` object for the
|
|
|
|
test session.
|
|
|
|
|
|
|
|
:ivar funcargnames:
|
|
|
|
.. deprecated:: 2.3
|
|
|
|
Use ``fixturenames`` instead.
|
|
|
|
"""
|
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
|
2012-10-16 19:59:12 +08:00
|
|
|
self._arg2fixturedefs = fixtureinfo.name2fixturedefs
|
2010-09-26 00:23:26 +08:00
|
|
|
self.cls = cls
|
|
|
|
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
|
|
|
|
2013-05-28 16:32:54 +08:00
|
|
|
:arg argnames: a comma-separated string denoting one or more argument
|
|
|
|
names, or a list/tuple of argument strings.
|
2011-11-17 19:09:21 +08:00
|
|
|
|
2013-05-22 21:24:58 +08:00
|
|
|
:arg argvalues: The list of argvalues determines how often a
|
|
|
|
test is invoked with different argument values. If only one
|
|
|
|
argname was specified argvalues is a list of simple values. If N
|
|
|
|
argnames were specified, argvalues must be a list of N-tuples,
|
|
|
|
where each tuple-element specifies a value for its respective
|
|
|
|
argname.
|
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
|
|
|
|
2014-04-18 03:08:49 +08:00
|
|
|
:arg ids: list of string ids, or a callable.
|
|
|
|
If strings, each is corresponding to the argvalues so that they are
|
|
|
|
part of the test id.
|
|
|
|
If callable, it should take one argument (a single argvalue) and return
|
|
|
|
a string or return None. If None, the automatically generated id for that
|
|
|
|
argument will be used.
|
|
|
|
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
|
|
|
"""
|
2013-05-22 21:24:58 +08:00
|
|
|
|
2013-11-02 12:10:13 +08:00
|
|
|
# individual parametrized argument sets can be wrapped in a series
|
|
|
|
# of markers in which case we unwrap the values and apply the mark
|
2013-05-22 21:24:58 +08:00
|
|
|
# at Function init
|
2013-05-17 16:46:36 +08:00
|
|
|
newkeywords = {}
|
2013-05-22 21:24:58 +08:00
|
|
|
unwrapped_argvalues = []
|
2013-05-17 16:46:36 +08:00
|
|
|
for i, argval in enumerate(argvalues):
|
2013-11-02 12:10:13 +08:00
|
|
|
while isinstance(argval, MarkDecorator):
|
2013-05-22 21:24:58 +08:00
|
|
|
newmark = MarkDecorator(argval.markname,
|
|
|
|
argval.args[:-1], argval.kwargs)
|
2013-11-02 12:10:13 +08:00
|
|
|
newmarks = newkeywords.setdefault(i, {})
|
|
|
|
newmarks[newmark.markname] = newmark
|
2013-05-22 21:24:58 +08:00
|
|
|
argval = argval.args[-1]
|
|
|
|
unwrapped_argvalues.append(argval)
|
|
|
|
argvalues = unwrapped_argvalues
|
2013-05-17 16:46:36 +08:00
|
|
|
|
2013-05-20 10:52:20 +08:00
|
|
|
if not isinstance(argnames, (tuple, list)):
|
2013-05-28 16:32:54 +08:00
|
|
|
argnames = [x.strip() for x in argnames.split(",") if x.strip()]
|
2013-10-02 14:08:26 +08:00
|
|
|
if len(argnames) == 1:
|
|
|
|
argvalues = [(val,) for val in argvalues]
|
2013-05-20 10:52:20 +08:00
|
|
|
if not argvalues:
|
|
|
|
argvalues = [(_notexists,) * len(argnames)]
|
2013-05-17 16:46:36 +08:00
|
|
|
|
2012-07-30 18:39:45 +08:00
|
|
|
if scope is None:
|
2013-12-07 23:37:46 +08:00
|
|
|
scope = "function"
|
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"
|
2014-04-18 03:08:49 +08:00
|
|
|
idfn = None
|
|
|
|
if callable(ids):
|
|
|
|
idfn = ids
|
|
|
|
ids = None
|
2013-05-29 10:59:47 +08:00
|
|
|
if ids and len(ids) != len(argvalues):
|
|
|
|
raise ValueError('%d tests specified with %d ids' %(
|
|
|
|
len(argvalues), len(ids)))
|
2011-11-17 19:09:21 +08:00
|
|
|
if not ids:
|
2014-04-18 03:08:49 +08:00
|
|
|
ids = idmaker(argnames, argvalues, idfn)
|
2011-11-17 19:09:21 +08:00
|
|
|
newcalls = []
|
|
|
|
for callspec in self._calls or [CallSpec2(self)]:
|
2013-12-04 04:05:19 +08:00
|
|
|
for param_index, valset in enumerate(argvalues):
|
2011-11-17 19:09:21 +08:00
|
|
|
assert len(valset) == len(argnames)
|
|
|
|
newcallspec = callspec.copy(self)
|
2013-12-04 04:05:19 +08:00
|
|
|
newcallspec.setmulti(valtype, argnames, valset, ids[param_index],
|
|
|
|
newkeywords.get(param_index, {}), scopenum,
|
|
|
|
param_index)
|
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)
|
|
|
|
|
2014-04-18 03:08:49 +08:00
|
|
|
|
|
|
|
def _idval(val, argname, idx, idfn):
|
|
|
|
if idfn:
|
|
|
|
try:
|
|
|
|
s = idfn(val)
|
|
|
|
if s:
|
|
|
|
return s
|
|
|
|
except Exception:
|
|
|
|
pass
|
2015-08-07 13:31:04 +08:00
|
|
|
|
|
|
|
try:
|
|
|
|
import enum
|
|
|
|
except ImportError:
|
|
|
|
# Only available in Python 3.4+
|
|
|
|
enum = None
|
2015-08-08 05:10:22 +08:00
|
|
|
# The type of re.compile objects is not exposed in Python.
|
|
|
|
RegexType = type(re.compile(''))
|
2015-08-07 13:31:04 +08:00
|
|
|
|
2014-04-18 03:08:49 +08:00
|
|
|
if isinstance(val, (float, int, str, bool, NoneType)):
|
|
|
|
return str(val)
|
2015-08-08 05:10:22 +08:00
|
|
|
elif isinstance(val, RegexType):
|
2015-08-07 13:31:04 +08:00
|
|
|
return val.pattern
|
|
|
|
elif enum is not None and isinstance(val, enum.Enum):
|
|
|
|
return str(val)
|
2015-08-08 05:10:22 +08:00
|
|
|
elif inspect.isclass(val) and hasattr(val, '__name__'):
|
2015-08-07 13:31:04 +08:00
|
|
|
return val.__name__
|
2014-04-18 03:08:49 +08:00
|
|
|
return str(argname)+str(idx)
|
|
|
|
|
|
|
|
def _idvalset(idx, valset, argnames, idfn):
|
|
|
|
this_id = [_idval(val, argname, idx, idfn)
|
|
|
|
for val, argname in zip(valset, argnames)]
|
|
|
|
return "-".join(this_id)
|
|
|
|
|
|
|
|
def idmaker(argnames, argvalues, idfn=None):
|
|
|
|
ids = [_idvalset(valindex, valset, argnames, idfn)
|
|
|
|
for valindex, valset in enumerate(argvalues)]
|
|
|
|
if len(set(ids)) < len(ids):
|
2014-10-27 17:02:15 +08:00
|
|
|
# user may have provided a bad idfn which means the ids are not unique
|
|
|
|
ids = [str(i) + testid for i, testid in enumerate(ids)]
|
2014-04-18 03:08:49 +08:00
|
|
|
return ids
|
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):
|
2015-07-19 03:39:55 +08:00
|
|
|
import _pytest.config
|
2010-11-07 17:19:58 +08:00
|
|
|
session.perform_collect()
|
2012-10-09 22:49:04 +08:00
|
|
|
curdir = py.path.local()
|
2015-07-19 03:39:55 +08:00
|
|
|
tw = _pytest.config.create_terminal_writer(config)
|
2010-09-26 00:23:26 +08:00
|
|
|
verbose = config.getvalue("verbose")
|
2012-10-09 22:49:04 +08:00
|
|
|
|
|
|
|
fm = session._fixturemanager
|
|
|
|
|
|
|
|
available = []
|
2015-07-13 04:32:39 +08:00
|
|
|
for argname, fixturedefs in fm._arg2fixturedefs.items():
|
2012-10-16 19:59:12 +08:00
|
|
|
assert fixturedefs is not None
|
|
|
|
if not fixturedefs:
|
2012-10-09 22:49:04 +08:00
|
|
|
continue
|
2012-10-16 19:59:12 +08:00
|
|
|
fixturedef = fixturedefs[-1]
|
2012-10-09 22:49:04 +08:00
|
|
|
loc = getlocation(fixturedef.func, curdir)
|
|
|
|
available.append((len(fixturedef.baseid),
|
2012-10-17 18:57:05 +08:00
|
|
|
fixturedef.func.__module__,
|
2012-10-09 22:49:04 +08:00
|
|
|
curdir.bestrelpath(loc),
|
|
|
|
fixturedef.argname, fixturedef))
|
|
|
|
|
|
|
|
available.sort()
|
2012-10-17 18:57:05 +08:00
|
|
|
currentmodule = None
|
|
|
|
for baseid, module, bestrel, argname, fixturedef in available:
|
|
|
|
if currentmodule != module:
|
|
|
|
if not module.startswith("_pytest."):
|
|
|
|
tw.line()
|
|
|
|
tw.sep("-", "fixtures defined from %s" %(module,))
|
|
|
|
currentmodule = module
|
|
|
|
if verbose <= 0 and argname[0] == "_":
|
|
|
|
continue
|
2012-10-09 22:49:04 +08:00
|
|
|
if verbose > 0:
|
2012-10-17 19:12:33 +08:00
|
|
|
funcargspec = "%s -- %s" %(argname, bestrel,)
|
2012-10-09 22:49:04 +08:00
|
|
|
else:
|
2012-10-17 18:57:05 +08:00
|
|
|
funcargspec = argname
|
2012-10-09 22:49:04 +08:00
|
|
|
tw.line(funcargspec, green=True)
|
|
|
|
loc = getlocation(fixturedef.func, curdir)
|
|
|
|
doc = fixturedef.func.__doc__ or ""
|
|
|
|
if doc:
|
2015-03-05 00:00:24 +08:00
|
|
|
for line in doc.strip().split("\n"):
|
2012-10-09 22:49:04 +08:00
|
|
|
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
|
|
|
|
|
2015-07-29 07:01:11 +08:00
|
|
|
def raises(expected_exception, *args, **kwargs):
|
|
|
|
""" assert that a code block/function call raises @expected_exception
|
2010-11-25 19:11:10 +08:00
|
|
|
and raise a failure exception otherwise.
|
2011-01-18 19:47:31 +08:00
|
|
|
|
2013-08-01 17:19:47 +08:00
|
|
|
This helper produces a ``py.code.ExceptionInfo()`` object.
|
|
|
|
|
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 ...>
|
2014-01-23 18:36:04 +08:00
|
|
|
|
|
|
|
Performance note:
|
|
|
|
-----------------
|
|
|
|
|
2014-04-15 06:09:10 +08:00
|
|
|
Similar to caught exception objects in Python, explicitly clearing
|
|
|
|
local references to returned ``py.code.ExceptionInfo`` objects can
|
|
|
|
help the Python interpreter speed up its garbage collection.
|
|
|
|
|
|
|
|
Clearing those references breaks a reference cycle
|
|
|
|
(``ExceptionInfo`` --> caught exception --> frame stack raising
|
|
|
|
the exception --> current frame stack --> local variables -->
|
|
|
|
``ExceptionInfo``) which makes Python keep all objects referenced
|
|
|
|
from that cycle (including all local variables in the current
|
|
|
|
frame) alive until the next cyclic garbage collection run. See the
|
2014-01-23 18:36:04 +08:00
|
|
|
official Python ``try`` statement documentation for more detailed
|
|
|
|
information.
|
|
|
|
|
2010-11-06 06:37:31 +08:00
|
|
|
"""
|
|
|
|
__tracebackhide__ = True
|
2015-07-29 07:01:11 +08:00
|
|
|
if expected_exception is AssertionError:
|
2012-08-19 19:45:26 +08:00
|
|
|
# we want to catch a AssertionError
|
|
|
|
# replace our subclass with the builtin one
|
2015-06-16 05:28:31 +08:00
|
|
|
# see https://github.com/pytest-dev/pytest/issues/176
|
2014-04-15 06:09:10 +08:00
|
|
|
from _pytest.assertion.util import BuiltinAssertionError \
|
2015-07-29 07:01:11 +08:00
|
|
|
as expected_exception
|
2014-04-15 06:09:10 +08:00
|
|
|
msg = ("exceptions must be old-style classes or"
|
|
|
|
" derived from BaseException, not %s")
|
2015-07-29 07:01:11 +08:00
|
|
|
if isinstance(expected_exception, tuple):
|
|
|
|
for exc in expected_exception:
|
2014-04-15 06:09:10 +08:00
|
|
|
if not inspect.isclass(exc):
|
|
|
|
raise TypeError(msg % type(exc))
|
2015-07-29 07:01:11 +08:00
|
|
|
elif not inspect.isclass(expected_exception):
|
|
|
|
raise TypeError(msg % type(expected_exception))
|
2010-11-06 06:37:31 +08:00
|
|
|
|
|
|
|
if not args:
|
2015-07-29 07:01:11 +08:00
|
|
|
return RaisesContext(expected_exception)
|
2010-11-06 06:37:31 +08:00
|
|
|
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 ...
|
2015-07-29 07:01:11 +08:00
|
|
|
except expected_exception:
|
2010-11-06 06:37:31 +08:00
|
|
|
return py.code.ExceptionInfo()
|
|
|
|
else:
|
|
|
|
func = args[0]
|
|
|
|
try:
|
|
|
|
func(*args[1:], **kwargs)
|
2015-07-29 07:01:11 +08:00
|
|
|
except expected_exception:
|
2010-11-06 06:37:31 +08:00
|
|
|
return py.code.ExceptionInfo()
|
|
|
|
pytest.fail("DID NOT RAISE")
|
|
|
|
|
|
|
|
class RaisesContext(object):
|
2015-07-29 07:01:11 +08:00
|
|
|
def __init__(self, expected_exception):
|
|
|
|
self.expected_exception = expected_exception
|
2010-11-06 06:37:31 +08:00
|
|
|
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")
|
2015-06-19 08:04:47 +08:00
|
|
|
if sys.version_info < (2, 7):
|
|
|
|
# py26: on __exit__() exc_value often does not contain the
|
|
|
|
# exception value.
|
|
|
|
# http://bugs.python.org/issue7853
|
|
|
|
if not isinstance(tp[1], BaseException):
|
|
|
|
exc_type, value, traceback = tp
|
|
|
|
tp = exc_type, exc_type(value), traceback
|
2010-11-06 06:37:31 +08:00
|
|
|
self.excinfo.__init__(tp)
|
2015-07-29 07:01:11 +08:00
|
|
|
return issubclass(self.excinfo.type, self.expected_exception)
|
2011-01-18 19:47:31 +08:00
|
|
|
|
2012-06-25 23:35:33 +08:00
|
|
|
#
|
2014-01-18 19:31:33 +08:00
|
|
|
# the basic pytest Function item
|
2012-06-25 23:35:33 +08:00
|
|
|
#
|
2013-11-21 20:15:32 +08:00
|
|
|
|
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,
|
2014-10-06 20:06:17 +08:00
|
|
|
callspec=None, callobj=NOTSET, keywords=None, session=None,
|
|
|
|
fixtureinfo=None):
|
2012-06-25 23:35:33 +08:00
|
|
|
super(Function, self).__init__(name, parent, config=config,
|
|
|
|
session=session)
|
|
|
|
self._args = args
|
2013-11-21 20:15:32 +08:00
|
|
|
if callobj is not NOTSET:
|
2012-10-16 19:48:00 +08:00
|
|
|
self.obj = callobj
|
|
|
|
|
2014-10-06 20:06:17 +08:00
|
|
|
self.keywords.update(self.obj.__dict__)
|
2013-05-17 16:46:36 +08:00
|
|
|
if callspec:
|
2013-04-22 16:35:48 +08:00
|
|
|
self.callspec = callspec
|
2014-10-06 20:06:17 +08:00
|
|
|
self.keywords.update(callspec.keywords)
|
|
|
|
if keywords:
|
|
|
|
self.keywords.update(keywords)
|
|
|
|
|
|
|
|
if fixtureinfo is None:
|
|
|
|
fixtureinfo = self.session._fixturemanager.getfixtureinfo(
|
|
|
|
self.parent, self.obj, self.cls,
|
|
|
|
funcargs=not self._isyieldedfunction())
|
|
|
|
self._fixtureinfo = fixtureinfo
|
|
|
|
self.fixturenames = fixtureinfo.names_closure
|
2013-04-22 16:35:48 +08:00
|
|
|
self._initrequest()
|
|
|
|
|
|
|
|
def _initrequest(self):
|
2013-12-07 23:37:46 +08:00
|
|
|
self.funcargs = {}
|
2013-04-22 16:35:48 +08:00
|
|
|
if self._isyieldedfunction():
|
|
|
|
assert not hasattr(self, "callspec"), (
|
2012-06-25 23:35:33 +08:00
|
|
|
"yielded functions (deprecated) cannot have funcargs")
|
|
|
|
else:
|
2013-04-22 16:35:48 +08:00
|
|
|
if hasattr(self, "callspec"):
|
|
|
|
callspec = self.callspec
|
2013-12-07 23:37:46 +08:00
|
|
|
assert not callspec.funcargs
|
2012-06-25 23:35:33 +08:00
|
|
|
self._genid = callspec.id
|
|
|
|
if hasattr(callspec, "param"):
|
|
|
|
self.param = callspec.param
|
2013-04-22 16:35:48 +08:00
|
|
|
self._request = FixtureRequest(self)
|
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:
|
2013-10-12 21:39:22 +08:00
|
|
|
self.callspec._emptyparamspecified
|
2012-10-06 17:34:06 +08:00
|
|
|
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
|
|
|
|
|
|
|
|
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-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"
|
2013-12-07 23:37:46 +08:00
|
|
|
self._funcargs = {}
|
|
|
|
self._fixturedefs = {}
|
2013-11-21 19:21:52 +08:00
|
|
|
fixtureinfo = pyfuncitem._fixtureinfo
|
2013-12-07 23:37:46 +08:00
|
|
|
self._arg2fixturedefs = fixtureinfo.name2fixturedefs.copy()
|
2012-10-16 19:59:12 +08:00
|
|
|
self._arg2index = {}
|
2013-11-21 19:21:52 +08:00
|
|
|
self.fixturenames = fixtureinfo.names_closure
|
2012-10-05 20:24:44 +08:00
|
|
|
self._fixturemanager = pyfuncitem.session._fixturemanager
|
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
|
|
|
|
2013-12-07 23:37:46 +08:00
|
|
|
|
2012-10-16 19:59:12 +08:00
|
|
|
def _getnextfixturedef(self, argname):
|
|
|
|
fixturedefs = self._arg2fixturedefs.get(argname, None)
|
|
|
|
if fixturedefs is None:
|
2013-12-07 23:37:46 +08:00
|
|
|
# we arrive here because of a a dynamic call to
|
|
|
|
# getfuncargvalue(argname) usage which was naturally
|
|
|
|
# not known at parsing/collection time
|
2012-10-16 19:59:12 +08:00
|
|
|
fixturedefs = self._fixturemanager.getfixturedefs(
|
2013-11-21 19:21:52 +08:00
|
|
|
argname, self._pyfuncitem.parent.nodeid)
|
2012-10-16 19:59:12 +08:00
|
|
|
self._arg2fixturedefs[argname] = fixturedefs
|
2013-12-07 23:37:46 +08:00
|
|
|
# fixturedefs list is immutable so we maintain a decreasing index
|
2012-10-16 19:59:12 +08:00
|
|
|
index = self._arg2index.get(argname, 0) - 1
|
|
|
|
if fixturedefs is None or (-index > len(fixturedefs)):
|
2012-10-05 20:24:45 +08:00
|
|
|
raise FixtureLookupError(argname, self)
|
2012-10-16 19:59:12 +08:00
|
|
|
self._arg2index[argname] = index
|
|
|
|
return fixturedefs[index]
|
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:
|
2013-12-07 23:37:46 +08:00
|
|
|
function = getattr(self, "function", None)
|
|
|
|
if function is not None:
|
|
|
|
return py.builtin._getimself(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-10-18 19:52:32 +08:00
|
|
|
""" keywords/markers dictionary for the underlying node. """
|
2012-10-18 21:06:55 +08:00
|
|
|
return self.node.keywords
|
2012-09-17 22:36:10 +08:00
|
|
|
|
|
|
|
@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):
|
2013-12-07 23:37:46 +08:00
|
|
|
colitem = self._getscopeitem(scope)
|
2012-09-17 22:36:10 +08:00
|
|
|
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
|
2014-01-18 19:31:33 +08:00
|
|
|
created by a call to ``pytest.mark.NAME(...)``.
|
2012-07-19 01:49:14 +08:00
|
|
|
"""
|
2012-10-18 19:52:32 +08:00
|
|
|
try:
|
|
|
|
self.node.keywords[marker.markname] = marker
|
|
|
|
except AttributeError:
|
|
|
|
raise ValueError(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:
|
2015-04-02 00:42:48 +08:00
|
|
|
self._check_scope(self.fixturename, self.scope, scope)
|
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
|
|
|
"""
|
2013-12-07 23:37:46 +08:00
|
|
|
return self._get_active_fixturedef(argname).cached_result[0]
|
|
|
|
|
|
|
|
def _get_active_fixturedef(self, argname):
|
2012-07-19 01:49:14 +08:00
|
|
|
try:
|
2013-12-07 23:37:46 +08:00
|
|
|
return self._fixturedefs[argname]
|
2012-07-19 01:49:14 +08:00
|
|
|
except KeyError:
|
2013-12-07 23:37:46 +08:00
|
|
|
try:
|
|
|
|
fixturedef = self._getnextfixturedef(argname)
|
|
|
|
except FixtureLookupError:
|
|
|
|
if argname == "request":
|
|
|
|
class PseudoFixtureDef:
|
2014-04-16 10:22:41 +08:00
|
|
|
cached_result = (self, [0], None)
|
2015-04-02 00:42:48 +08:00
|
|
|
scope = "function"
|
2013-12-07 23:37:46 +08:00
|
|
|
return PseudoFixtureDef
|
|
|
|
raise
|
2015-01-10 02:55:49 +08:00
|
|
|
# remove indent to prevent the python3 exception
|
|
|
|
# from leaking into the call
|
|
|
|
result = self._getfuncargvalue(fixturedef)
|
|
|
|
self._funcargs[argname] = result
|
|
|
|
self._fixturedefs[argname] = fixturedef
|
|
|
|
return fixturedef
|
2013-11-21 20:15:32 +08:00
|
|
|
|
|
|
|
def _get_fixturestack(self):
|
|
|
|
current = self
|
|
|
|
l = []
|
|
|
|
while 1:
|
|
|
|
fixturedef = getattr(current, "_fixturedef", None)
|
|
|
|
if fixturedef is None:
|
|
|
|
l.reverse()
|
|
|
|
return l
|
|
|
|
l.append(fixturedef)
|
|
|
|
current = current._parent_request
|
2012-07-23 16:55:09 +08:00
|
|
|
|
2012-10-05 20:24:44 +08:00
|
|
|
def _getfuncargvalue(self, fixturedef):
|
2013-11-21 19:21:52 +08:00
|
|
|
# prepare a subrequest object before calling fixture function
|
|
|
|
# (latter managed by fixturedef)
|
2012-10-05 20:24:44 +08:00
|
|
|
argname = fixturedef.argname
|
2013-12-07 23:37:46 +08:00
|
|
|
funcitem = self._pyfuncitem
|
2013-11-21 19:21:52 +08:00
|
|
|
scope = fixturedef.scope
|
2012-07-20 20:16:28 +08:00
|
|
|
try:
|
2013-12-07 23:37:46 +08:00
|
|
|
param = funcitem.callspec.getparam(argname)
|
2012-07-20 20:16:28 +08:00
|
|
|
except (AttributeError, ValueError):
|
2013-11-21 20:15:32 +08:00
|
|
|
param = NOTSET
|
2013-12-07 23:37:46 +08:00
|
|
|
param_index = 0
|
2012-07-20 20:16:28 +08:00
|
|
|
else:
|
2013-12-07 23:37:46 +08:00
|
|
|
# indices might not be set if old-style metafunc.addcall() was used
|
|
|
|
param_index = funcitem.callspec.indices.get(argname, 0)
|
2013-11-21 19:21:52 +08:00
|
|
|
# if a parametrize invocation set a scope it will override
|
|
|
|
# the static scope defined with the fixture function
|
2013-12-07 23:37:46 +08:00
|
|
|
paramscopenum = funcitem.callspec._arg2scopenum.get(argname)
|
|
|
|
if paramscopenum is not None:
|
2012-10-07 03:01:13 +08:00
|
|
|
scope = scopes[paramscopenum]
|
|
|
|
|
2013-12-07 23:37:46 +08:00
|
|
|
subrequest = SubRequest(self, scope, param, param_index, fixturedef)
|
2013-11-21 20:15:32 +08:00
|
|
|
|
2012-11-16 17:03:51 +08:00
|
|
|
# check if a higher-level scoped fixture accesses a lower level one
|
2015-04-02 00:42:48 +08:00
|
|
|
subrequest._check_scope(argname, self.scope, scope)
|
2012-11-16 17:03:51 +08:00
|
|
|
|
2015-01-10 02:55:49 +08:00
|
|
|
# clear sys.exc_info before invoking the fixture (python bug?)
|
|
|
|
# if its not explicitly cleared it will leak into the call
|
|
|
|
exc_clear()
|
2013-07-17 16:29:11 +08:00
|
|
|
try:
|
2013-12-07 23:37:46 +08:00
|
|
|
# call the fixture function
|
2013-11-21 19:21:52 +08:00
|
|
|
val = fixturedef.execute(request=subrequest)
|
2013-07-17 16:29:11 +08:00
|
|
|
finally:
|
2013-12-07 23:37:46 +08:00
|
|
|
# if fixture function failed it might have registered finalizers
|
2013-07-17 16:29:11 +08:00
|
|
|
self.session._setupstate.addfinalizer(fixturedef.finish,
|
2013-11-21 19:21:52 +08:00
|
|
|
subrequest.node)
|
2012-07-20 20:16:46 +08:00
|
|
|
return val
|
2012-07-19 01:49:14 +08:00
|
|
|
|
2015-04-02 00:42:48 +08:00
|
|
|
def _check_scope(self, argname, invoking_scope, requested_scope):
|
|
|
|
if argname == "request":
|
|
|
|
return
|
|
|
|
if scopemismatch(invoking_scope, requested_scope):
|
|
|
|
# try to report something helpful
|
|
|
|
lines = self._factorytraceback()
|
2015-04-17 17:57:09 +08:00
|
|
|
pytest.fail("ScopeMismatch: You tried to access the %r scoped "
|
2015-04-02 00:42:48 +08:00
|
|
|
"fixture %r with a %r scoped request object, "
|
|
|
|
"involved factories\n%s" %(
|
|
|
|
(requested_scope, argname, invoking_scope, "\n".join(lines))),
|
|
|
|
pytrace=False)
|
|
|
|
|
2012-08-08 17:48:53 +08:00
|
|
|
def _factorytraceback(self):
|
|
|
|
lines = []
|
2013-11-21 20:15:32 +08:00
|
|
|
for fixturedef in self._get_fixturestack():
|
2012-10-05 20:24:44 +08:00
|
|
|
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":
|
2013-12-07 23:37:46 +08:00
|
|
|
# this might also be a non-function Item despite its attribute name
|
2012-07-19 01:49:14 +08:00
|
|
|
return self._pyfuncitem
|
2013-12-07 23:37:46 +08:00
|
|
|
node = get_scope_node(self._pyfuncitem, scope)
|
|
|
|
if node is None and scope == "class":
|
|
|
|
# fallback to function item itself
|
|
|
|
node = self._pyfuncitem
|
|
|
|
assert node
|
|
|
|
return node
|
2012-07-19 01:49:14 +08:00
|
|
|
|
|
|
|
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
|
|
|
|
2013-11-21 20:15:32 +08:00
|
|
|
|
2013-11-21 19:21:52 +08:00
|
|
|
class SubRequest(FixtureRequest):
|
|
|
|
""" a sub request for handling getting a fixture from a
|
|
|
|
test function/fixture. """
|
2013-12-07 23:37:46 +08:00
|
|
|
def __init__(self, request, scope, param, param_index, fixturedef):
|
2013-11-21 19:21:52 +08:00
|
|
|
self._parent_request = request
|
2013-11-21 19:42:22 +08:00
|
|
|
self.fixturename = fixturedef.argname
|
2013-11-21 20:15:32 +08:00
|
|
|
if param is not NOTSET:
|
2013-11-21 19:21:52 +08:00
|
|
|
self.param = param
|
2013-12-07 23:37:46 +08:00
|
|
|
self.param_index = param_index
|
2013-11-21 19:21:52 +08:00
|
|
|
self.scope = scope
|
2013-11-21 20:15:32 +08:00
|
|
|
self._fixturedef = fixturedef
|
2013-11-21 19:42:22 +08:00
|
|
|
self.addfinalizer = fixturedef.addfinalizer
|
2013-11-21 19:21:52 +08:00
|
|
|
self._pyfuncitem = request._pyfuncitem
|
|
|
|
self._funcargs = request._funcargs
|
2013-12-07 23:37:46 +08:00
|
|
|
self._fixturedefs = request._fixturedefs
|
2013-11-21 19:21:52 +08:00
|
|
|
self._arg2fixturedefs = request._arg2fixturedefs
|
|
|
|
self._arg2index = request._arg2index
|
|
|
|
self.fixturenames = request.fixturenames
|
|
|
|
self._fixturemanager = request._fixturemanager
|
|
|
|
|
|
|
|
def __repr__(self):
|
2013-11-21 20:15:32 +08:00
|
|
|
return "<SubRequest %r for %r>" % (self.fixturename, self._pyfuncitem)
|
|
|
|
|
2013-11-21 19:21:52 +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
|
|
|
|
2013-12-07 23:37:46 +08:00
|
|
|
scopes = "session module class function".split()
|
2013-11-21 21:16:44 +08:00
|
|
|
scopenum_function = scopes.index("function")
|
2012-07-23 16:55:09 +08:00
|
|
|
def scopemismatch(currentscope, newscope):
|
|
|
|
return scopes.index(newscope) > scopes.index(currentscope)
|
|
|
|
|
2015-04-02 00:42:48 +08:00
|
|
|
|
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
|
2013-11-21 20:15:32 +08:00
|
|
|
self.fixturestack = request._get_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)
|
2015-04-16 06:31:22 +08:00
|
|
|
try:
|
2015-07-03 10:13:59 +08:00
|
|
|
lines, _ = inspect.getsourcelines(get_real_func(function))
|
2015-04-16 06:31:22 +08:00
|
|
|
except IOError:
|
|
|
|
error_msg = "file %s, line %s: source code not available"
|
|
|
|
addline(error_msg % (fspath, lineno+1))
|
|
|
|
else:
|
|
|
|
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
|
2012-10-05 20:24:45 +08:00
|
|
|
|
|
|
|
if msg is None:
|
|
|
|
fm = self.request._fixturemanager
|
|
|
|
available = []
|
2012-10-16 22:13:12 +08:00
|
|
|
for name, fixturedef in fm._arg2fixturedefs.items():
|
2013-11-21 19:21:52 +08:00
|
|
|
parentid = self.request._pyfuncitem.parent.nodeid
|
|
|
|
faclist = list(fm._matchfactories(fixturedef, parentid))
|
2012-10-05 20:24:45 +08:00
|
|
|
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-10-17 17:20:45 +08:00
|
|
|
"""
|
|
|
|
pytest fixtures definitions and information is stored and managed
|
|
|
|
from this class.
|
|
|
|
|
|
|
|
During collection fm.parsefactories() is called multiple times to parse
|
|
|
|
fixture function definitions into FixtureDef objects and internal
|
|
|
|
data structures.
|
|
|
|
|
|
|
|
During collection of test functions, metafunc-mechanics instantiate
|
|
|
|
a FuncFixtureInfo object which is cached per node/func-name.
|
|
|
|
This FuncFixtureInfo object is later retrieved by Function nodes
|
|
|
|
which themselves offer a fixturenames attribute.
|
|
|
|
|
|
|
|
The FuncFixtureInfo object holds information about fixtures and FixtureDefs
|
|
|
|
relevant for a particular function. An initial list of fixtures is
|
|
|
|
assembled like this:
|
|
|
|
|
|
|
|
- ini-defined usefixtures
|
|
|
|
- autouse-marked fixtures along the collection chain up from the function
|
|
|
|
- usefixtures markers at module/class/function level
|
|
|
|
- test function funcargs
|
|
|
|
|
|
|
|
Subsequently the funcfixtureinfo.fixturenames attribute is computed
|
|
|
|
as the closure of the fixtures needed to setup the initial fixtures,
|
|
|
|
i. e. fixtures needed by fixture functions themselves are appended
|
|
|
|
to the fixturenames list.
|
|
|
|
|
|
|
|
Upon the test-setup phases all fixturenames are instantiated, retrieved
|
|
|
|
by a lookup of their FuncFixtureInfo.
|
|
|
|
"""
|
|
|
|
|
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-16 22:13:12 +08:00
|
|
|
self._arg2fixturedefs = {}
|
2012-08-01 15:23:39 +08:00
|
|
|
self._holderobjseen = set()
|
|
|
|
self._arg2finish = {}
|
2012-10-16 22:13:12 +08:00
|
|
|
self._nodeid_and_autousenames = [("", self.config.getini("usefixtures"))]
|
2012-09-12 18:51:45 +08:00
|
|
|
session.config.pluginmanager.register(self, "funcmanage")
|
2012-08-01 15:23:39 +08:00
|
|
|
|
2012-10-17 17:20:45 +08:00
|
|
|
|
2012-11-20 05:17:59 +08:00
|
|
|
def getfixtureinfo(self, node, func, cls, funcargs=True):
|
|
|
|
if funcargs and not hasattr(node, "nofuncargs"):
|
2012-10-17 17:20:45 +08:00
|
|
|
if cls is not None:
|
|
|
|
startindex = 1
|
|
|
|
else:
|
|
|
|
startindex = None
|
|
|
|
argnames = getfuncargnames(func, startindex)
|
|
|
|
else:
|
|
|
|
argnames = ()
|
|
|
|
usefixtures = getattr(func, "usefixtures", None)
|
|
|
|
initialnames = argnames
|
|
|
|
if usefixtures is not None:
|
|
|
|
initialnames = usefixtures.args + initialnames
|
|
|
|
fm = node.session._fixturemanager
|
|
|
|
names_closure, arg2fixturedefs = fm.getfixtureclosure(initialnames,
|
|
|
|
node)
|
2014-10-06 20:06:17 +08:00
|
|
|
return FuncFixtureInfo(argnames, names_closure, arg2fixturedefs)
|
2012-10-17 17:20:45 +08:00
|
|
|
|
2012-08-01 15:23:39 +08:00
|
|
|
def pytest_plugin_registered(self, plugin):
|
2013-07-06 23:56:54 +08:00
|
|
|
nodeid = None
|
2012-08-01 15:23:39 +08:00
|
|
|
try:
|
|
|
|
p = py.path.local(plugin.__file__)
|
|
|
|
except AttributeError:
|
|
|
|
pass
|
|
|
|
else:
|
2014-09-15 18:44:16 +08:00
|
|
|
# construct the base nodeid which is later used to check
|
|
|
|
# what fixtures are visible for particular tests (as denoted
|
|
|
|
# by their test id)
|
2012-08-01 15:23:39 +08:00
|
|
|
if p.basename.startswith("conftest.py"):
|
2015-02-27 04:56:44 +08:00
|
|
|
nodeid = p.dirpath().relto(self.config.rootdir)
|
2012-10-17 19:42:40 +08:00
|
|
|
if p.sep != "/":
|
2012-10-17 19:45:03 +08:00
|
|
|
nodeid = nodeid.replace(p.sep, "/")
|
2012-10-16 22:13:12 +08:00
|
|
|
self.parsefactories(plugin, nodeid)
|
2012-08-01 15:23:39 +08:00
|
|
|
|
2012-10-16 22:13:12 +08:00
|
|
|
def _getautousenames(self, nodeid):
|
|
|
|
""" return a tuple of fixture names to be used. """
|
|
|
|
autousenames = []
|
|
|
|
for baseid, basenames in self._nodeid_and_autousenames:
|
|
|
|
if nodeid.startswith(baseid):
|
|
|
|
if baseid:
|
2012-11-20 05:17:55 +08:00
|
|
|
i = len(baseid)
|
2012-10-16 22:13:12 +08:00
|
|
|
nextchar = nodeid[i:i+1]
|
|
|
|
if nextchar and nextchar not in ":/":
|
|
|
|
continue
|
|
|
|
autousenames.extend(basenames)
|
|
|
|
# make sure autousenames are sorted by scope, scopenum 0 is session
|
|
|
|
autousenames.sort(
|
|
|
|
key=lambda x: self._arg2fixturedefs[x][-1].scopenum)
|
|
|
|
return autousenames
|
2012-10-06 01:20:40 +08:00
|
|
|
|
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
|
2012-10-16 19:59:12 +08:00
|
|
|
# factory definitions anyway, we also return a arg2fixturedefs
|
2012-10-05 20:24:44 +08:00
|
|
|
# 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-16 22:13:12 +08:00
|
|
|
fixturenames_closure = self._getautousenames(parentid)
|
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)
|
2012-10-16 19:59:12 +08:00
|
|
|
arg2fixturedefs = {}
|
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:
|
2012-10-16 19:59:12 +08:00
|
|
|
if argname in arg2fixturedefs:
|
2012-09-24 23:04:34 +08:00
|
|
|
continue
|
2012-10-16 19:59:12 +08:00
|
|
|
fixturedefs = self.getfixturedefs(argname, parentid)
|
2013-11-14 01:25:55 +08:00
|
|
|
if fixturedefs:
|
2013-12-07 23:37:46 +08:00
|
|
|
arg2fixturedefs[argname] = fixturedefs
|
2013-11-12 20:45:36 +08:00
|
|
|
merge(fixturedefs[-1].argnames)
|
2012-10-16 19:59:12 +08:00
|
|
|
return fixturenames_closure, arg2fixturedefs
|
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:
|
2013-12-07 23:37:46 +08:00
|
|
|
faclist = metafunc._arg2fixturedefs.get(argname)
|
2015-03-02 15:55:57 +08:00
|
|
|
if faclist:
|
|
|
|
fixturedef = faclist[-1]
|
2012-10-05 20:24:44 +08:00
|
|
|
if fixturedef.params is not None:
|
2015-03-01 22:15:37 +08:00
|
|
|
func_params = getattr(getattr(metafunc.function, 'parametrize', None), 'args', [[None]])
|
|
|
|
# skip directly parametrized arguments
|
|
|
|
if argname not in func_params and argname not in func_params[0]:
|
|
|
|
metafunc.parametrize(argname, fixturedef.params,
|
|
|
|
indirect=True, scope=fixturedef.scope,
|
|
|
|
ids=fixturedef.ids)
|
2015-03-02 15:55:57 +08:00
|
|
|
else:
|
|
|
|
continue # will raise FixtureLookupError at setup time
|
2012-08-01 15:23:39 +08:00
|
|
|
|
|
|
|
def pytest_collection_modifyitems(self, items):
|
|
|
|
# separate parametrized setups
|
2013-12-09 17:05:44 +08:00
|
|
|
items[:] = reorder_items(items)
|
2012-08-01 15:23:39 +08:00
|
|
|
|
2013-11-21 20:15:32 +08:00
|
|
|
def parsefactories(self, node_or_obj, nodeid=NOTSET, unittest=False):
|
|
|
|
if nodeid is not NOTSET:
|
2012-10-16 22:13:12 +08:00
|
|
|
holderobj = node_or_obj
|
|
|
|
else:
|
|
|
|
holderobj = node_or_obj.obj
|
|
|
|
nodeid = node_or_obj.nodeid
|
2012-08-01 15:23:39 +08:00
|
|
|
if holderobj in self._holderobjseen:
|
|
|
|
return
|
|
|
|
self._holderobjseen.add(holderobj)
|
2012-10-16 22:13:12 +08:00
|
|
|
autousenames = []
|
2012-08-01 15:23:39 +08:00
|
|
|
for name in dir(holderobj):
|
2012-10-18 21:09:20 +08:00
|
|
|
obj = getattr(holderobj, name, None)
|
2012-08-01 15:23:39 +08:00
|
|
|
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
|
2013-04-29 16:31:51 +08:00
|
|
|
marker = getfixturemarker(obj)
|
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
|
2013-12-09 14:07:47 +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,
|
2013-09-27 18:28:34 +08:00
|
|
|
yieldctx=marker.yieldctx,
|
2013-12-16 06:15:15 +08:00
|
|
|
unittest=unittest, ids=marker.ids)
|
2012-10-16 22:13:12 +08:00
|
|
|
faclist = self._arg2fixturedefs.setdefault(name, [])
|
2013-12-09 17:40:39 +08:00
|
|
|
if fixturedef.has_location:
|
|
|
|
faclist.append(fixturedef)
|
|
|
|
else:
|
|
|
|
# fixturedefs with no location are at the front
|
2013-08-02 01:58:28 +08:00
|
|
|
# so this inserts the current fixturedef after the
|
|
|
|
# existing fixturedefs from external plugins but
|
|
|
|
# before the fixturedefs provided in conftests.
|
|
|
|
i = len([f for f in faclist if not f.has_location])
|
2013-12-09 17:40:39 +08:00
|
|
|
faclist.insert(i, fixturedef)
|
2012-10-12 20:52:36 +08:00
|
|
|
if marker.autouse:
|
2012-10-16 22:13:12 +08:00
|
|
|
autousenames.append(name)
|
|
|
|
if autousenames:
|
2013-08-02 01:58:28 +08:00
|
|
|
self._nodeid_and_autousenames.append((nodeid or '', autousenames))
|
2012-08-01 15:23:39 +08:00
|
|
|
|
2012-10-16 19:59:12 +08:00
|
|
|
def getfixturedefs(self, argname, nodeid):
|
2012-08-01 15:23:39 +08:00
|
|
|
try:
|
2012-10-16 22:13:12 +08:00
|
|
|
fixturedefs = self._arg2fixturedefs[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-16 19:59:12 +08:00
|
|
|
return tuple(self._matchfactories(fixturedefs, nodeid))
|
2012-08-01 15:23:39 +08:00
|
|
|
|
2012-10-16 19:59:12 +08:00
|
|
|
def _matchfactories(self, fixturedefs, nodeid):
|
|
|
|
for fixturedef in fixturedefs:
|
2012-10-05 20:24:44 +08:00
|
|
|
if nodeid.startswith(fixturedef.baseid):
|
|
|
|
yield fixturedef
|
2012-08-01 15:23:39 +08:00
|
|
|
|
|
|
|
|
2013-09-26 18:57:21 +08:00
|
|
|
def fail_fixturefunc(fixturefunc, msg):
|
|
|
|
fs, lineno = getfslineno(fixturefunc)
|
|
|
|
location = "%s:%s" % (fs, lineno+1)
|
|
|
|
source = py.code.Source(fixturefunc)
|
|
|
|
pytest.fail(msg + ":\n\n" + str(source.indent()) + "\n" + location,
|
|
|
|
pytrace=False)
|
|
|
|
|
|
|
|
def call_fixture_func(fixturefunc, request, kwargs, yieldctx):
|
|
|
|
if yieldctx:
|
|
|
|
if not is_generator(fixturefunc):
|
|
|
|
fail_fixturefunc(fixturefunc,
|
2013-09-30 19:42:39 +08:00
|
|
|
msg="yield_fixture requires yield statement in function")
|
2013-05-05 20:48:37 +08:00
|
|
|
iter = fixturefunc(**kwargs)
|
|
|
|
next = getattr(iter, "__next__", None)
|
|
|
|
if next is None:
|
|
|
|
next = getattr(iter, "next")
|
|
|
|
res = next()
|
|
|
|
def teardown():
|
|
|
|
try:
|
|
|
|
next()
|
|
|
|
except StopIteration:
|
|
|
|
pass
|
|
|
|
else:
|
2013-09-26 18:57:21 +08:00
|
|
|
fail_fixturefunc(fixturefunc,
|
2013-09-30 19:42:39 +08:00
|
|
|
"yield_fixture function has more than one 'yield'")
|
2013-05-05 20:48:37 +08:00
|
|
|
request.addfinalizer(teardown)
|
|
|
|
else:
|
2013-09-30 19:56:54 +08:00
|
|
|
if is_generator(fixturefunc):
|
|
|
|
fail_fixturefunc(fixturefunc,
|
|
|
|
msg="pytest.fixture functions cannot use ``yield``. "
|
|
|
|
"Instead write and return an inner function/generator "
|
|
|
|
"and let the consumer call and iterate over it.")
|
2013-05-05 20:48:37 +08:00
|
|
|
res = fixturefunc(**kwargs)
|
|
|
|
return res
|
|
|
|
|
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-11-14 16:40:01 +08:00
|
|
|
def __init__(self, fixturemanager, baseid, argname, func, scope, params,
|
2013-12-16 06:15:15 +08:00
|
|
|
yieldctx, unittest=False, ids=None):
|
2012-11-14 16:40:01 +08:00
|
|
|
self._fixturemanager = fixturemanager
|
2013-07-06 23:56:54 +08:00
|
|
|
self.baseid = baseid or ''
|
|
|
|
self.has_location = baseid is not None
|
2012-08-01 15:23:39 +08:00
|
|
|
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-16 20:19:38 +08:00
|
|
|
self.argnames = getfuncargnames(func, startindex=startindex)
|
2013-09-26 18:57:21 +08:00
|
|
|
self.yieldctx = yieldctx
|
2012-10-05 16:21:35 +08:00
|
|
|
self.unittest = unittest
|
2013-12-16 06:15:15 +08:00
|
|
|
self.ids = ids
|
2012-08-01 15:23:39 +08:00
|
|
|
self._finalizer = []
|
|
|
|
|
|
|
|
def addfinalizer(self, finalizer):
|
|
|
|
self._finalizer.append(finalizer)
|
|
|
|
|
|
|
|
def finish(self):
|
2012-11-19 19:42:10 +08:00
|
|
|
try:
|
2014-04-07 19:29:57 +08:00
|
|
|
while self._finalizer:
|
|
|
|
func = self._finalizer.pop()
|
|
|
|
func()
|
|
|
|
finally:
|
|
|
|
# even if finalization fails, we invalidate
|
|
|
|
# the cached fixture value
|
|
|
|
if hasattr(self, "cached_result"):
|
|
|
|
del self.cached_result
|
2012-10-05 16:21:35 +08:00
|
|
|
|
|
|
|
def execute(self, request):
|
2013-12-07 23:37:46 +08:00
|
|
|
# get required arguments and register our own finish()
|
|
|
|
# with their finalization
|
2012-10-05 16:21:35 +08:00
|
|
|
kwargs = {}
|
2013-12-07 23:37:46 +08:00
|
|
|
for argname in self.argnames:
|
|
|
|
fixturedef = request._get_active_fixturedef(argname)
|
2014-04-16 10:22:41 +08:00
|
|
|
result, arg_cache_key, exc = fixturedef.cached_result
|
2015-04-02 00:42:48 +08:00
|
|
|
request._check_scope(argname, request.scope, fixturedef.scope)
|
2013-12-07 23:37:46 +08:00
|
|
|
kwargs[argname] = result
|
|
|
|
if argname != "request":
|
|
|
|
fixturedef.addfinalizer(self.finish)
|
|
|
|
|
|
|
|
my_cache_key = request.param_index
|
|
|
|
cached_result = getattr(self, "cached_result", None)
|
|
|
|
if cached_result is not None:
|
2014-04-16 10:22:41 +08:00
|
|
|
result, cache_key, err = cached_result
|
2013-12-07 23:37:46 +08:00
|
|
|
if my_cache_key == cache_key:
|
2014-04-16 10:22:41 +08:00
|
|
|
if err is not None:
|
|
|
|
py.builtin._reraise(*err)
|
|
|
|
else:
|
|
|
|
return result
|
2013-12-07 23:37:46 +08:00
|
|
|
# we have a previous but differently parametrized fixture instance
|
|
|
|
# so we need to tear it down before creating a new one
|
|
|
|
self.finish()
|
|
|
|
assert not hasattr(self, "cached_result")
|
|
|
|
|
2015-07-21 06:25:01 +08:00
|
|
|
fixturefunc = self.func
|
|
|
|
|
2012-10-05 16:21:35 +08:00
|
|
|
if self.unittest:
|
2015-07-21 06:25:01 +08:00
|
|
|
if request.instance is not None:
|
|
|
|
# bind the unbound method to the TestCase instance
|
|
|
|
fixturefunc = self.func.__get__(request.instance)
|
2012-10-05 16:21:35 +08:00
|
|
|
else:
|
2012-10-20 15:59:20 +08:00
|
|
|
# the fixture function needs to be bound to the actual
|
|
|
|
# request.instance so that code working with "self" behaves
|
2013-12-07 23:37:46 +08:00
|
|
|
# as expected.
|
|
|
|
if request.instance is not None:
|
|
|
|
fixturefunc = getimfunc(self.func)
|
|
|
|
if fixturefunc != self.func:
|
|
|
|
fixturefunc = fixturefunc.__get__(request.instance)
|
2015-07-21 06:25:01 +08:00
|
|
|
|
|
|
|
try:
|
|
|
|
result = call_fixture_func(fixturefunc, request, kwargs,
|
|
|
|
self.yieldctx)
|
|
|
|
except Exception:
|
|
|
|
self.cached_result = (None, my_cache_key, sys.exc_info())
|
|
|
|
raise
|
2014-04-16 10:22:41 +08:00
|
|
|
self.cached_result = (result, my_cache_key, None)
|
2012-10-05 16:21:35 +08:00
|
|
|
return result
|
2012-08-01 15:23:39 +08:00
|
|
|
|
2012-10-05 16:21:35 +08:00
|
|
|
def __repr__(self):
|
2013-12-07 23:37:46 +08:00
|
|
|
return ("<FixtureDef name=%r scope=%r baseid=%r >" %
|
|
|
|
(self.argname, self.scope, self.baseid))
|
2012-08-01 15:23:39 +08:00
|
|
|
|
2014-07-28 16:34:01 +08:00
|
|
|
def num_mock_patch_args(function):
|
|
|
|
""" return number of arguments used up by mock arguments (if any) """
|
|
|
|
patchings = getattr(function, "patchings", None)
|
|
|
|
if not patchings:
|
|
|
|
return 0
|
|
|
|
mock = sys.modules.get("mock", sys.modules.get("unittest.mock", None))
|
|
|
|
if mock is not None:
|
|
|
|
return len([p for p in patchings
|
|
|
|
if not p.attribute_name and p.new is mock.DEFAULT])
|
|
|
|
return len(patchings)
|
|
|
|
|
2014-07-27 16:43:50 +08:00
|
|
|
|
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)
|
2012-11-06 18:04:11 +08:00
|
|
|
realfunction = function
|
|
|
|
while hasattr(realfunction, "__wrapped__"):
|
|
|
|
realfunction = realfunction.__wrapped__
|
2012-10-08 17:22:31 +08:00
|
|
|
if startindex is None:
|
2012-09-18 20:00:47 +08:00
|
|
|
startindex = inspect.ismethod(function) and 1 or 0
|
2012-11-06 18:04:11 +08:00
|
|
|
if realfunction != function:
|
2014-07-28 16:34:01 +08:00
|
|
|
startindex += num_mock_patch_args(function)
|
2012-11-06 18:04:11 +08:00
|
|
|
function = realfunction
|
2015-07-13 23:16:51 +08:00
|
|
|
if isinstance(function, functools.partial):
|
2015-07-03 10:13:59 +08:00
|
|
|
argnames = inspect.getargs(py.code.getrawcode(function.func))[0]
|
|
|
|
partial = function
|
|
|
|
argnames = argnames[len(partial.args):]
|
|
|
|
if partial.keywords:
|
|
|
|
for kw in partial.keywords:
|
|
|
|
argnames.remove(kw)
|
|
|
|
else:
|
|
|
|
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
|
2013-12-05 13:09:29 +08:00
|
|
|
# it is called for scopenum==0 (session) first and performs sorting
|
|
|
|
# down to the lower scopes such as to minimize number of "high scope"
|
|
|
|
# setups and teardowns
|
2012-08-01 15:23:39 +08:00
|
|
|
|
2013-12-09 17:05:44 +08:00
|
|
|
def reorder_items(items):
|
|
|
|
argkeys_cache = {}
|
|
|
|
for scopenum in range(0, scopenum_function):
|
|
|
|
argkeys_cache[scopenum] = d = {}
|
|
|
|
for item in items:
|
|
|
|
keys = set(get_parametrized_fixture_keys(item, scopenum))
|
|
|
|
if keys:
|
|
|
|
d[item] = keys
|
|
|
|
return reorder_items_atscope(items, set(), argkeys_cache, 0)
|
|
|
|
|
|
|
|
def reorder_items_atscope(items, ignore, argkeys_cache, scopenum):
|
2013-12-08 03:55:17 +08:00
|
|
|
if scopenum >= scopenum_function or len(items) < 3:
|
2012-08-01 15:23:39 +08:00
|
|
|
return items
|
2013-12-08 03:55:17 +08:00
|
|
|
items_done = []
|
|
|
|
while 1:
|
|
|
|
items_before, items_same, items_other, newignore = \
|
2013-12-09 17:05:44 +08:00
|
|
|
slice_items(items, ignore, argkeys_cache[scopenum])
|
|
|
|
items_before = reorder_items_atscope(
|
|
|
|
items_before, ignore, argkeys_cache,scopenum+1)
|
2013-12-08 03:55:17 +08:00
|
|
|
if items_same is None:
|
|
|
|
# nothing to reorder in this scope
|
|
|
|
assert items_other is None
|
|
|
|
return items_done + items_before
|
|
|
|
items_done.extend(items_before)
|
|
|
|
items = items_same + items_other
|
|
|
|
ignore = newignore
|
|
|
|
|
|
|
|
|
2013-12-09 17:05:44 +08:00
|
|
|
def slice_items(items, ignore, scoped_argkeys_cache):
|
|
|
|
# we pick the first item which uses a fixture instance in the
|
|
|
|
# requested scope and which we haven't seen yet. We slice the input
|
|
|
|
# items list into a list of items_nomatch, items_same and
|
|
|
|
# items_other
|
|
|
|
if scoped_argkeys_cache: # do we need to do work at all?
|
|
|
|
it = iter(items)
|
|
|
|
# first find a slicing key
|
|
|
|
for i, item in enumerate(it):
|
|
|
|
argkeys = scoped_argkeys_cache.get(item)
|
|
|
|
if argkeys is not None:
|
|
|
|
argkeys = argkeys.difference(ignore)
|
|
|
|
if argkeys: # found a slicing key
|
|
|
|
slicing_argkey = argkeys.pop()
|
|
|
|
items_before = items[:i]
|
|
|
|
items_same = [item]
|
|
|
|
items_other = []
|
|
|
|
# now slice the remainder of the list
|
|
|
|
for item in it:
|
|
|
|
argkeys = scoped_argkeys_cache.get(item)
|
|
|
|
if argkeys and slicing_argkey in argkeys and \
|
|
|
|
slicing_argkey not in ignore:
|
|
|
|
items_same.append(item)
|
|
|
|
else:
|
|
|
|
items_other.append(item)
|
|
|
|
newignore = ignore.copy()
|
|
|
|
newignore.add(slicing_argkey)
|
|
|
|
return (items_before, items_same, items_other, newignore)
|
|
|
|
return items, None, None, None
|
|
|
|
|
|
|
|
def get_parametrized_fixture_keys(item, scopenum):
|
2013-12-05 13:09:29 +08:00
|
|
|
""" return list of keys for all parametrized arguments which match
|
|
|
|
the specified scope. """
|
|
|
|
assert scopenum < scopenum_function # function
|
2012-08-01 15:23:39 +08:00
|
|
|
try:
|
|
|
|
cs = item.callspec
|
|
|
|
except AttributeError:
|
2013-12-09 17:05:44 +08:00
|
|
|
pass
|
|
|
|
else:
|
|
|
|
# cs.indictes.items() is random order of argnames but
|
|
|
|
# then again different functions (items) can change order of
|
|
|
|
# arguments so it doesn't matter much probably
|
|
|
|
for argname, param_index in cs.indices.items():
|
|
|
|
if cs._arg2scopenum[argname] != scopenum:
|
|
|
|
continue
|
|
|
|
if scopenum == 0: # session
|
|
|
|
key = (argname, param_index)
|
|
|
|
elif scopenum == 1: # module
|
|
|
|
key = (argname, param_index, item.fspath)
|
|
|
|
elif scopenum == 2: # class
|
|
|
|
key = (argname, param_index, item.fspath, item.cls)
|
|
|
|
yield key
|
2012-08-01 15:23:39 +08:00
|
|
|
|
2012-08-13 19:37:14 +08:00
|
|
|
|
|
|
|
def xunitsetup(obj, name):
|
|
|
|
meth = getattr(obj, name, None)
|
2013-04-29 16:31:51 +08:00
|
|
|
if getfixturemarker(meth) is None:
|
|
|
|
return meth
|
|
|
|
|
|
|
|
def getfixturemarker(obj):
|
|
|
|
""" return fixturemarker or None if it doesn't exist or raised
|
|
|
|
exceptions."""
|
|
|
|
try:
|
|
|
|
return getattr(obj, "_pytestfixturefunction", None)
|
|
|
|
except KeyboardInterrupt:
|
|
|
|
raise
|
|
|
|
except Exception:
|
|
|
|
# some objects raise errors like request (from flask import request)
|
|
|
|
# we don't expect them to be fixture functions
|
|
|
|
return None
|
|
|
|
|
2013-12-07 23:37:46 +08:00
|
|
|
scopename2class = {
|
|
|
|
'class': Class,
|
|
|
|
'module': Module,
|
|
|
|
'function': pytest.Item,
|
|
|
|
}
|
|
|
|
def get_scope_node(node, scope):
|
|
|
|
cls = scopename2class.get(scope)
|
|
|
|
if cls is None:
|
|
|
|
if scope == "session":
|
|
|
|
return node.session
|
|
|
|
raise ValueError("unknown scope")
|
|
|
|
return node.getparent(cls)
|