2010-11-06 18:38:53 +08:00
|
|
|
""" Python test discovery, setup and run of test functions. """
|
2008-08-16 23:26:59 +08:00
|
|
|
import py
|
2009-09-01 22:10:21 +08:00
|
|
|
import inspect
|
2010-07-04 23:06:50 +08:00
|
|
|
import sys
|
2010-10-07 17:59:00 +08:00
|
|
|
import pytest
|
2010-02-04 23:01:02 +08:00
|
|
|
from py._code.code import TerminalRepr
|
2011-11-17 19:09:21 +08:00
|
|
|
from _pytest.monkeypatch import monkeypatch
|
2008-08-16 23:26:59 +08:00
|
|
|
|
2010-11-13 18:10:45 +08:00
|
|
|
import _pytest
|
|
|
|
cutdir = py.path.local(_pytest.__file__).dirpath()
|
2010-10-10 19:48:49 +08:00
|
|
|
|
2010-09-26 00:23:26 +08:00
|
|
|
def pytest_addoption(parser):
|
2010-11-07 05:17:33 +08:00
|
|
|
group = parser.getgroup("general")
|
|
|
|
group.addoption('--funcargs',
|
2010-09-26 00:23:26 +08:00
|
|
|
action="store_true", dest="showfuncargs", default=False,
|
|
|
|
help="show available function arguments, sorted by plugin")
|
2010-11-25 05:01:04 +08:00
|
|
|
parser.addini("python_files", type="args",
|
|
|
|
default=('test_*.py', '*_test.py'),
|
|
|
|
help="glob-style file patterns for Python test module discovery")
|
|
|
|
parser.addini("python_classes", type="args", default=("Test",),
|
|
|
|
help="prefixes for Python test class discovery")
|
|
|
|
parser.addini("python_functions", type="args", default=("test",),
|
|
|
|
help="prefixes for Python test function and method discovery")
|
2010-09-26 00:23:26 +08:00
|
|
|
|
|
|
|
def pytest_cmdline_main(config):
|
|
|
|
if config.option.showfuncargs:
|
|
|
|
showfuncargs(config)
|
|
|
|
return 0
|
|
|
|
|
2011-11-17 19:09:21 +08:00
|
|
|
|
|
|
|
def pytest_generate_tests(metafunc):
|
|
|
|
try:
|
|
|
|
param = metafunc.function.parametrize
|
|
|
|
except AttributeError:
|
|
|
|
return
|
2011-12-28 23:47:19 +08:00
|
|
|
for p in param:
|
|
|
|
metafunc.parametrize(*p.args, **p.kwargs)
|
2011-11-17 19:09:21 +08:00
|
|
|
|
|
|
|
def pytest_configure(config):
|
|
|
|
config.addinivalue_line("markers",
|
|
|
|
"parametrize(argnames, argvalues): call a test function multiple "
|
|
|
|
"times passing in multiple different argument value sets. Example: "
|
2011-11-19 02:32:11 +08:00
|
|
|
"@parametrize('arg1', [1,2]) would lead to two calls of the decorated "
|
2011-11-17 19:09:21 +08:00
|
|
|
"test function, one with arg1=1 and another with arg1=2."
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2010-11-22 06:17:59 +08:00
|
|
|
@pytest.mark.trylast
|
|
|
|
def pytest_namespace():
|
2010-11-06 06:37:31 +08:00
|
|
|
raises.Exception = pytest.fail.Exception
|
|
|
|
return {
|
|
|
|
'raises' : raises,
|
|
|
|
'collect': {
|
2010-10-07 17:59:00 +08:00
|
|
|
'Module': Module, 'Class': Class, 'Instance': Instance,
|
|
|
|
'Function': Function, 'Generator': Generator,
|
2011-03-06 15:56:58 +08:00
|
|
|
'_fillfuncargs': fillfuncargs}
|
2010-11-06 06:37:31 +08:00
|
|
|
}
|
2010-09-26 00:23:26 +08:00
|
|
|
|
|
|
|
def pytest_funcarg__pytestconfig(request):
|
|
|
|
""" the pytest config object with access to command line opts."""
|
|
|
|
return request.config
|
|
|
|
|
|
|
|
def pytest_pyfunc_call(__multicall__, pyfuncitem):
|
|
|
|
if not __multicall__.execute():
|
|
|
|
testfunction = pyfuncitem.obj
|
|
|
|
if pyfuncitem._isyieldedfunction():
|
|
|
|
testfunction(*pyfuncitem._args)
|
|
|
|
else:
|
|
|
|
funcargs = pyfuncitem.funcargs
|
|
|
|
testfunction(**funcargs)
|
|
|
|
|
|
|
|
def pytest_collect_file(path, parent):
|
|
|
|
ext = path.ext
|
|
|
|
pb = path.purebasename
|
2010-11-25 05:01:04 +08:00
|
|
|
if ext == ".py":
|
|
|
|
if not parent.session.isinitpath(path):
|
|
|
|
for pat in parent.config.getini('python_files'):
|
|
|
|
if path.fnmatch(pat):
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
return
|
2011-05-29 07:47:16 +08:00
|
|
|
return parent.ihook.pytest_pycollect_makemodule(
|
2010-11-06 16:58:04 +08:00
|
|
|
path=path, parent=parent)
|
2010-09-26 00:23:26 +08:00
|
|
|
|
|
|
|
def pytest_pycollect_makemodule(path, parent):
|
2010-10-14 00:41:53 +08:00
|
|
|
return Module(path, parent)
|
2010-09-26 00:23:26 +08:00
|
|
|
|
|
|
|
def pytest_pycollect_makeitem(__multicall__, collector, name, obj):
|
|
|
|
res = __multicall__.execute()
|
|
|
|
if res is not None:
|
|
|
|
return res
|
2011-03-16 23:36:18 +08:00
|
|
|
if inspect.isclass(obj):
|
2010-11-17 19:21:24 +08:00
|
|
|
#if hasattr(collector.obj, 'unittest'):
|
|
|
|
# return # we assume it's a mixin class for a TestCase derived one
|
2011-03-16 23:36:18 +08:00
|
|
|
if collector.classnamefilter(name):
|
|
|
|
if not hasinit(obj):
|
|
|
|
Class = collector._getcustomclass("Class")
|
|
|
|
return Class(name, parent=collector)
|
2010-09-26 00:23:26 +08:00
|
|
|
elif collector.funcnamefilter(name) and hasattr(obj, '__call__'):
|
|
|
|
if is_generator(obj):
|
2010-10-14 00:41:53 +08:00
|
|
|
return Generator(name, parent=collector)
|
2010-09-26 00:23:26 +08:00
|
|
|
else:
|
|
|
|
return collector._genfunctions(name, obj)
|
|
|
|
|
|
|
|
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
|
|
|
|
|
2008-08-16 23:26:59 +08:00
|
|
|
class PyobjMixin(object):
|
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):
|
2008-08-16 23:26:59 +08:00
|
|
|
try:
|
|
|
|
return self._fslineno
|
|
|
|
except AttributeError:
|
|
|
|
pass
|
2008-11-26 03:15:01 +08:00
|
|
|
obj = self.obj
|
2009-05-12 19:39:09 +08:00
|
|
|
# xxx let decorators etc specify a sane ordering
|
2008-11-26 03:15:01 +08:00
|
|
|
if hasattr(obj, 'place_as'):
|
|
|
|
obj = obj.place_as
|
2008-08-16 23:26:59 +08:00
|
|
|
|
2009-05-12 19:39:09 +08:00
|
|
|
self._fslineno = py.code.getfslineno(obj)
|
2011-12-14 18:56:51 +08:00
|
|
|
assert isinstance(self._fslineno[1], int), obj
|
2009-05-12 19:39:09 +08:00
|
|
|
return self._fslineno
|
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]
|
|
|
|
#assert 0
|
|
|
|
#fn = inspect.getsourcefile(obj) or inspect.getfile(obj)
|
|
|
|
lineno = obj.compat_co_firstlineno
|
|
|
|
modpath = obj.__module__
|
|
|
|
else:
|
|
|
|
fspath, lineno = self._getfslineno()
|
|
|
|
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
|
|
|
|
2010-11-13 16:05:11 +08:00
|
|
|
class PyCollectorMixin(PyobjMixin, pytest.Collector):
|
2010-07-27 03:15:15 +08:00
|
|
|
|
|
|
|
def funcnamefilter(self, name):
|
2010-11-25 05:01:04 +08:00
|
|
|
for prefix in self.config.getini("python_functions"):
|
|
|
|
if name.startswith(prefix):
|
|
|
|
return True
|
2011-01-18 19:47:31 +08:00
|
|
|
|
2010-07-27 03:15:15 +08:00
|
|
|
def classnamefilter(self, name):
|
2010-11-25 05:01:04 +08:00
|
|
|
for prefix in self.config.getini("python_classes"):
|
|
|
|
if name.startswith(prefix):
|
|
|
|
return True
|
2008-08-16 23:26:59 +08:00
|
|
|
|
2008-09-02 16:58:14 +08:00
|
|
|
def collect(self):
|
2008-08-16 23:26:59 +08:00
|
|
|
# NB. we avoid random getattrs and peek in the __dict__ instead
|
2010-10-26 05:08:56 +08:00
|
|
|
# (XXX originally introduced from a PyPy need, still true?)
|
2008-08-16 23:26:59 +08:00
|
|
|
dicts = [getattr(self.obj, '__dict__', {})]
|
2009-09-01 22:10:21 +08:00
|
|
|
for basecls in inspect.getmro(self.obj.__class__):
|
2008-08-16 23:26:59 +08:00
|
|
|
dicts.append(basecls.__dict__)
|
|
|
|
seen = {}
|
2010-01-16 00:38:09 +08:00
|
|
|
l = []
|
2008-08-16 23:26:59 +08:00
|
|
|
for dic in dicts:
|
|
|
|
for name, obj in dic.items():
|
|
|
|
if name in seen:
|
|
|
|
continue
|
|
|
|
seen[name] = True
|
2009-10-22 00:44:12 +08:00
|
|
|
if name[0] != "_":
|
|
|
|
res = self.makeitem(name, obj)
|
2010-01-16 00:50:02 +08:00
|
|
|
if res is None:
|
|
|
|
continue
|
|
|
|
if not isinstance(res, list):
|
|
|
|
res = [res]
|
|
|
|
l.extend(res)
|
2010-01-16 00:38:09 +08:00
|
|
|
l.sort(key=lambda item: item.reportinfo()[:2])
|
|
|
|
return l
|
2008-08-16 23:26:59 +08:00
|
|
|
|
2009-02-27 18:18:27 +08:00
|
|
|
def makeitem(self, name, obj):
|
2009-12-30 09:36:58 +08:00
|
|
|
return self.ihook.pytest_pycollect_makeitem(
|
2009-05-08 05:12:17 +08:00
|
|
|
collector=self, name=name, obj=obj)
|
2009-05-12 01:23:57 +08:00
|
|
|
|
|
|
|
def _genfunctions(self, name, funcobj):
|
2009-05-20 00:13:33 +08:00
|
|
|
module = self.getparent(Module).obj
|
|
|
|
clscol = self.getparent(Class)
|
2009-05-12 01:23:57 +08:00
|
|
|
cls = clscol and clscol.obj or None
|
2010-09-26 00:23:26 +08:00
|
|
|
metafunc = Metafunc(funcobj, config=self.config,
|
2009-08-07 00:15:21 +08:00
|
|
|
cls=cls, module=module)
|
2011-12-28 23:47:19 +08:00
|
|
|
transfer_markers(metafunc)
|
2009-12-30 09:36:58 +08:00
|
|
|
gentesthook = self.config.hook.pytest_generate_tests
|
2010-11-25 05:22:52 +08:00
|
|
|
extra = [module]
|
|
|
|
if cls is not None:
|
|
|
|
extra.append(cls())
|
|
|
|
plugins = self.getplugins() + extra
|
2009-12-30 21:05:41 +08:00
|
|
|
gentesthook.pcall(plugins, metafunc=metafunc)
|
2011-03-05 21:16:27 +08:00
|
|
|
Function = self._getcustomclass("Function")
|
2009-05-13 05:32:19 +08:00
|
|
|
if not metafunc._calls:
|
2011-03-05 21:16:27 +08:00
|
|
|
return Function(name, parent=self)
|
2010-01-16 00:50:02 +08:00
|
|
|
l = []
|
|
|
|
for callspec in metafunc._calls:
|
|
|
|
subname = "%s[%s]" %(name, callspec.id)
|
2011-03-05 21:16:27 +08:00
|
|
|
function = Function(name=subname, parent=self,
|
2010-10-13 18:26:14 +08:00
|
|
|
callspec=callspec, callobj=funcobj, keywords={callspec.id:True})
|
2010-01-16 00:50:02 +08:00
|
|
|
l.append(function)
|
|
|
|
return l
|
2010-07-27 03:15:15 +08:00
|
|
|
|
2011-12-28 23:47:19 +08:00
|
|
|
def transfer_markers(metafunc):
|
|
|
|
# XXX this should rather be code in the mark plugin or the mark
|
|
|
|
# plugin should merge with the python plugin.
|
|
|
|
for holder in (metafunc.cls, metafunc.module):
|
|
|
|
try:
|
|
|
|
pytestmark = holder.pytestmark
|
|
|
|
except AttributeError:
|
|
|
|
continue
|
|
|
|
if isinstance(pytestmark, list):
|
|
|
|
for mark in pytestmark:
|
|
|
|
mark(metafunc.function)
|
|
|
|
else:
|
|
|
|
pytestmark(metafunc.function)
|
|
|
|
|
2011-03-05 21:16:27 +08:00
|
|
|
|
2010-11-13 16:05:11 +08:00
|
|
|
class Module(pytest.File, PyCollectorMixin):
|
2008-08-16 23:26:59 +08:00
|
|
|
def _getobj(self):
|
2009-02-27 18:18:27 +08:00
|
|
|
return self._memoizedcall('_obj', self._importtestmodule)
|
|
|
|
|
|
|
|
def _importtestmodule(self):
|
2010-07-27 03:15:15 +08:00
|
|
|
# we assume we are only called once per module
|
2010-07-04 23:06:50 +08:00
|
|
|
try:
|
2011-06-29 10:13:12 +08:00
|
|
|
mod = self.fspath.pyimport(ensuresyspath=True)
|
2010-07-04 23:06:50 +08:00
|
|
|
except SyntaxError:
|
|
|
|
excinfo = py.code.ExceptionInfo()
|
|
|
|
raise self.CollectError(excinfo.getrepr(style="short"))
|
|
|
|
except self.fspath.ImportMismatchError:
|
|
|
|
e = sys.exc_info()[1]
|
|
|
|
raise self.CollectError(
|
|
|
|
"import file mismatch:\n"
|
2010-07-27 03:15:15 +08:00
|
|
|
"imported module %r has this __file__ attribute:\n"
|
2010-07-04 23:06:50 +08:00
|
|
|
" %s\n"
|
|
|
|
"which is not the same as the test file we want to collect:\n"
|
|
|
|
" %s\n"
|
2011-12-20 20:20:59 +08:00
|
|
|
"HINT: remove __pycache__ / .pyc files and/or use a "
|
|
|
|
"unique basename for your test file modules"
|
2010-07-04 23:06:50 +08:00
|
|
|
% e.args
|
|
|
|
)
|
2009-02-27 18:18:27 +08:00
|
|
|
#print "imported test module", mod
|
2009-04-09 22:03:09 +08:00
|
|
|
self.config.pluginmanager.consider_module(mod)
|
2009-02-27 18:18:27 +08:00
|
|
|
return mod
|
2008-08-16 23:26:59 +08:00
|
|
|
|
2010-07-27 03:15:15 +08:00
|
|
|
def setup(self):
|
|
|
|
if hasattr(self.obj, 'setup_module'):
|
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
|
|
|
|
if inspect.getargspec(self.obj.setup_module)[0]:
|
|
|
|
self.obj.setup_module(self.obj)
|
|
|
|
else:
|
|
|
|
self.obj.setup_module()
|
2008-08-16 23:26:59 +08:00
|
|
|
|
2010-07-27 03:15:15 +08:00
|
|
|
def teardown(self):
|
|
|
|
if hasattr(self.obj, 'teardown_module'):
|
2009-10-23 22:17:06 +08:00
|
|
|
#XXX: nose compat hack, move to nose plugin
|
|
|
|
# if it takes a positional arg, its probably a py.test style one
|
|
|
|
# so we pass the current module object
|
|
|
|
if inspect.getargspec(self.obj.teardown_module)[0]:
|
|
|
|
self.obj.teardown_module(self.obj)
|
|
|
|
else:
|
|
|
|
self.obj.teardown_module()
|
2008-08-16 23:26:59 +08:00
|
|
|
|
2010-11-13 16:05:11 +08:00
|
|
|
class Class(PyCollectorMixin, pytest.Collector):
|
2008-08-16 23:26:59 +08:00
|
|
|
|
2008-09-02 16:58:14 +08:00
|
|
|
def collect(self):
|
2011-03-05 21:16:27 +08:00
|
|
|
return [self._getcustomclass("Instance")(name="()", parent=self)]
|
2008-08-16 23:26:59 +08:00
|
|
|
|
2010-07-27 03:15:15 +08:00
|
|
|
def setup(self):
|
2008-08-16 23:26:59 +08:00
|
|
|
setup_class = getattr(self.obj, 'setup_class', None)
|
2010-07-27 03:15:15 +08:00
|
|
|
if setup_class is not None:
|
|
|
|
setup_class = getattr(setup_class, 'im_func', setup_class)
|
|
|
|
setup_class(self.obj)
|
|
|
|
|
|
|
|
def teardown(self):
|
|
|
|
teardown_class = getattr(self.obj, 'teardown_class', None)
|
|
|
|
if teardown_class is not None:
|
|
|
|
teardown_class = getattr(teardown_class, 'im_func', teardown_class)
|
|
|
|
teardown_class(self.obj)
|
|
|
|
|
2010-11-13 16:05:11 +08:00
|
|
|
class Instance(PyCollectorMixin, pytest.Collector):
|
2010-07-27 03:15:15 +08:00
|
|
|
def _getobj(self):
|
|
|
|
return self.parent.obj()
|
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.
|
|
|
|
"""
|
2010-07-27 03:15:15 +08:00
|
|
|
def setup(self):
|
2008-08-16 23:26:59 +08:00
|
|
|
""" perform setup for this test function. """
|
2011-01-14 20:30:36 +08:00
|
|
|
if hasattr(self, '_preservedparent'):
|
|
|
|
obj = self._preservedparent
|
|
|
|
elif isinstance(self.parent, Instance):
|
2008-08-16 23:26:59 +08:00
|
|
|
obj = self.parent.newinstance()
|
|
|
|
self.obj = self._getobj()
|
|
|
|
else:
|
2010-07-27 03:15:15 +08:00
|
|
|
obj = self.parent.obj
|
2011-03-03 01:03:43 +08:00
|
|
|
if inspect.ismethod(self.obj):
|
|
|
|
name = 'setup_method'
|
|
|
|
else:
|
|
|
|
name = 'setup_function'
|
2008-08-16 23:26:59 +08:00
|
|
|
setup_func_or_method = getattr(obj, name, None)
|
2010-07-27 03:15:15 +08:00
|
|
|
if setup_func_or_method is not None:
|
|
|
|
setup_func_or_method(self.obj)
|
2008-08-16 23:26:59 +08:00
|
|
|
|
2010-07-27 03:15:15 +08:00
|
|
|
def teardown(self):
|
2008-08-16 23:26:59 +08:00
|
|
|
""" perform teardown for this test function. """
|
2009-09-01 22:10:21 +08:00
|
|
|
if inspect.ismethod(self.obj):
|
2010-07-27 03:15:15 +08:00
|
|
|
name = 'teardown_method'
|
|
|
|
else:
|
|
|
|
name = 'teardown_function'
|
|
|
|
obj = self.parent.obj
|
2008-08-16 23:26:59 +08:00
|
|
|
teardown_func_or_meth = getattr(obj, name, None)
|
2010-07-27 03:15:15 +08:00
|
|
|
if teardown_func_or_meth is not None:
|
|
|
|
teardown_func_or_meth(self.obj)
|
2008-08-16 23:26:59 +08:00
|
|
|
|
2010-11-06 06:37:31 +08:00
|
|
|
def _prunetraceback(self, excinfo):
|
2010-07-27 03:15:15 +08:00
|
|
|
if hasattr(self, '_obj') and not self.config.option.fulltrace:
|
|
|
|
code = py.code.Code(self.obj)
|
|
|
|
path, firstlineno = code.path, code.firstlineno
|
2010-11-06 06:37:31 +08:00
|
|
|
traceback = excinfo.traceback
|
2008-08-16 23:26:59 +08:00
|
|
|
ntraceback = traceback.cut(path=path, firstlineno=firstlineno)
|
|
|
|
if ntraceback == traceback:
|
|
|
|
ntraceback = ntraceback.cut(path=path)
|
2009-03-01 19:24:52 +08:00
|
|
|
if ntraceback == traceback:
|
2010-10-10 19:48:49 +08:00
|
|
|
ntraceback = ntraceback.cut(excludepath=cutdir)
|
2010-11-06 06:37:31 +08:00
|
|
|
excinfo.traceback = ntraceback.filter()
|
2008-08-16 23:26:59 +08:00
|
|
|
|
2010-05-22 22:18:24 +08:00
|
|
|
def _repr_failure_py(self, excinfo, style="long"):
|
2010-09-26 00:23:26 +08:00
|
|
|
if excinfo.errisinstance(FuncargRequest.LookupError):
|
2010-02-04 23:01:02 +08:00
|
|
|
fspath, lineno, msg = self.reportinfo()
|
|
|
|
lines, _ = inspect.getsourcelines(self.obj)
|
|
|
|
for i, line in enumerate(lines):
|
|
|
|
if line.strip().startswith('def'):
|
|
|
|
return FuncargLookupErrorRepr(fspath, lineno,
|
|
|
|
lines[:i+1], str(excinfo.value))
|
2010-11-24 23:43:55 +08:00
|
|
|
if excinfo.errisinstance(pytest.fail.Exception):
|
|
|
|
if not excinfo.value.pytrace:
|
|
|
|
return str(excinfo.value)
|
2010-07-27 03:15:15 +08:00
|
|
|
return super(FunctionMixin, self)._repr_failure_py(excinfo,
|
2010-05-22 22:18:24 +08:00
|
|
|
style=style)
|
2010-02-04 23:01:02 +08:00
|
|
|
|
2009-07-26 00:09:01 +08:00
|
|
|
def repr_failure(self, excinfo, outerr=None):
|
|
|
|
assert outerr is None, "XXX outerr usage is deprecated"
|
2010-07-27 03:15:15 +08:00
|
|
|
return self._repr_failure_py(excinfo,
|
2010-11-01 06:28:31 +08:00
|
|
|
style=self.config.option.tbstyle)
|
2008-08-16 23:26:59 +08:00
|
|
|
|
2010-02-04 23:01:02 +08:00
|
|
|
class FuncargLookupErrorRepr(TerminalRepr):
|
|
|
|
def __init__(self, filename, firstlineno, deflines, errorstring):
|
|
|
|
self.deflines = deflines
|
|
|
|
self.errorstring = errorstring
|
|
|
|
self.filename = filename
|
|
|
|
self.firstlineno = firstlineno
|
|
|
|
|
|
|
|
def toterminal(self, tw):
|
|
|
|
tw.line()
|
|
|
|
for line in self.deflines:
|
|
|
|
tw.line(" " + line.strip())
|
|
|
|
for line in self.errorstring.split("\n"):
|
|
|
|
tw.line(" " + line.strip(), red=True)
|
|
|
|
tw.line()
|
|
|
|
tw.line("%s:%d" % (self.filename, self.firstlineno+1))
|
|
|
|
|
2011-11-19 00:01:29 +08:00
|
|
|
|
2010-11-13 16:05:11 +08:00
|
|
|
class Generator(FunctionMixin, PyCollectorMixin, pytest.Collector):
|
2008-09-02 16:58:14 +08:00
|
|
|
def collect(self):
|
2010-07-27 03:15:15 +08:00
|
|
|
# test generators are seen as collectors but they also
|
|
|
|
# invoke setup/teardown on popular request
|
2009-05-07 21:44:56 +08:00
|
|
|
# (induced by the common "test_*" naming shared with normal tests)
|
2011-05-27 06:08:56 +08:00
|
|
|
self.session._setupstate.prepare(self)
|
2011-01-14 20:30:36 +08:00
|
|
|
# see FunctionMixin.setup and test_setupstate_is_preserved_134
|
|
|
|
self._preservedparent = self.parent.obj
|
2008-09-02 16:58:14 +08:00
|
|
|
l = []
|
2009-03-19 22:34:33 +08:00
|
|
|
seen = {}
|
2010-07-27 03:15:15 +08:00
|
|
|
for i, x in enumerate(self.obj()):
|
2008-11-26 00:10:16 +08:00
|
|
|
name, call, args = self.getcallargs(x)
|
2010-07-27 03:15:15 +08:00
|
|
|
if not py.builtin.callable(call):
|
2008-08-16 23:26:59 +08:00
|
|
|
raise TypeError("%r yielded non callable test %r" %(self.obj, call,))
|
2008-11-26 00:10:16 +08:00
|
|
|
if name is None:
|
|
|
|
name = "[%d]" % i
|
|
|
|
else:
|
|
|
|
name = "['%s']" % name
|
2009-03-19 22:34:33 +08:00
|
|
|
if name in seen:
|
|
|
|
raise ValueError("%r generated tests with non-unique name %r" %(self, name))
|
|
|
|
seen[name] = True
|
2011-01-18 19:47:31 +08:00
|
|
|
l.append(self.Function(name, self, args=args, callobj=call))
|
2008-09-02 16:58:14 +08:00
|
|
|
return l
|
2010-07-27 03:15:15 +08:00
|
|
|
|
2008-08-16 23:26:59 +08:00
|
|
|
def getcallargs(self, obj):
|
2008-11-26 00:10:16 +08:00
|
|
|
if not isinstance(obj, (tuple, list)):
|
|
|
|
obj = (obj,)
|
|
|
|
# explict naming
|
2009-08-29 22:40:03 +08:00
|
|
|
if isinstance(obj[0], py.builtin._basestring):
|
2008-11-26 00:10:16 +08:00
|
|
|
name = obj[0]
|
|
|
|
obj = obj[1:]
|
2008-08-16 23:26:59 +08:00
|
|
|
else:
|
2008-11-26 00:10:16 +08:00
|
|
|
name = None
|
|
|
|
call, args = obj[0], obj[1:]
|
2010-07-27 03:15:15 +08:00
|
|
|
return name, call, args
|
|
|
|
|
2008-08-16 23:26:59 +08:00
|
|
|
|
|
|
|
#
|
2010-07-27 03:15:15 +08:00
|
|
|
# Test Items
|
2008-08-16 23:26:59 +08:00
|
|
|
#
|
|
|
|
_dummy = object()
|
2010-11-13 16:05:11 +08:00
|
|
|
class Function(FunctionMixin, pytest.Item):
|
2010-07-27 03:15:15 +08:00
|
|
|
""" a Function Item is responsible for setting up
|
2008-08-16 23:26:59 +08:00
|
|
|
and executing a Python callable test object.
|
|
|
|
"""
|
2009-05-25 16:46:04 +08:00
|
|
|
_genid = None
|
2009-12-30 23:18:59 +08:00
|
|
|
def __init__(self, name, parent=None, args=None, config=None,
|
2010-11-07 17:19:58 +08:00
|
|
|
callspec=None, callobj=_dummy, keywords=None, session=None):
|
2010-09-15 16:30:50 +08:00
|
|
|
super(Function, self).__init__(name, parent,
|
2010-11-07 17:19:58 +08:00
|
|
|
config=config, session=session)
|
2010-07-27 03:15:15 +08:00
|
|
|
self._args = args
|
2009-06-15 21:15:40 +08:00
|
|
|
if self._isyieldedfunction():
|
2010-11-02 06:08:16 +08:00
|
|
|
assert not callspec, (
|
|
|
|
"yielded functions (deprecated) cannot have funcargs")
|
2009-05-13 09:01:02 +08:00
|
|
|
else:
|
2009-05-25 16:46:04 +08:00
|
|
|
if callspec is not None:
|
2011-11-17 19:09:21 +08:00
|
|
|
self.callspec = callspec
|
2009-05-25 16:46:04 +08:00
|
|
|
self.funcargs = callspec.funcargs or {}
|
2010-07-27 03:15:15 +08:00
|
|
|
self._genid = callspec.id
|
2009-05-25 16:46:04 +08:00
|
|
|
if hasattr(callspec, "param"):
|
|
|
|
self._requestparam = callspec.param
|
|
|
|
else:
|
|
|
|
self.funcargs = {}
|
2010-07-27 03:15:15 +08:00
|
|
|
if callobj is not _dummy:
|
|
|
|
self._obj = callobj
|
2009-12-30 17:42:01 +08:00
|
|
|
self.function = getattr(self.obj, 'im_func', self.obj)
|
2010-06-08 08:34:51 +08:00
|
|
|
self.keywords.update(py.builtin._getfuncdict(self.obj) or {})
|
2010-10-13 18:26:14 +08:00
|
|
|
if keywords:
|
|
|
|
self.keywords.update(keywords)
|
2008-08-16 23:26:59 +08:00
|
|
|
|
2010-01-16 00:50:02 +08:00
|
|
|
def _getobj(self):
|
|
|
|
name = self.name
|
|
|
|
i = name.find("[") # parametrization
|
|
|
|
if i != -1:
|
|
|
|
name = name[:i]
|
|
|
|
return getattr(self.parent.obj, name)
|
|
|
|
|
2009-06-15 21:15:40 +08:00
|
|
|
def _isyieldedfunction(self):
|
|
|
|
return self._args is not None
|
|
|
|
|
2008-09-02 16:58:14 +08:00
|
|
|
def runtest(self):
|
2009-06-09 00:31:10 +08:00
|
|
|
""" execute the underlying test function. """
|
2009-12-30 09:36:58 +08:00
|
|
|
self.ihook.pytest_pyfunc_call(pyfuncitem=self)
|
2009-02-27 18:18:27 +08:00
|
|
|
|
2009-05-06 14:38:42 +08:00
|
|
|
def setup(self):
|
|
|
|
super(Function, self).setup()
|
2010-07-27 03:15:15 +08:00
|
|
|
if hasattr(self, 'funcargs'):
|
2010-09-26 00:23:26 +08:00
|
|
|
fillfuncargs(self)
|
2008-08-16 23:26:59 +08:00
|
|
|
|
|
|
|
def __eq__(self, other):
|
|
|
|
try:
|
2010-07-27 03:15:15 +08:00
|
|
|
return (self.name == other.name and
|
2008-08-16 23:26:59 +08:00
|
|
|
self._args == other._args and
|
|
|
|
self.parent == other.parent and
|
2010-07-27 03:15:15 +08:00
|
|
|
self.obj == other.obj and
|
|
|
|
getattr(self, '_genid', None) ==
|
|
|
|
getattr(other, '_genid', None)
|
2009-05-19 01:06:16 +08:00
|
|
|
)
|
2008-08-16 23:26:59 +08:00
|
|
|
except AttributeError:
|
|
|
|
pass
|
|
|
|
return False
|
2009-05-12 01:23:57 +08:00
|
|
|
|
2008-08-16 23:26:59 +08:00
|
|
|
def __ne__(self, other):
|
|
|
|
return not self == other
|
2010-07-27 03:15:15 +08:00
|
|
|
|
2009-08-29 01:16:15 +08:00
|
|
|
def __hash__(self):
|
|
|
|
return hash((self.parent, self.name))
|
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
|
|
|
|
|
|
|
|
2011-03-05 19:11:35 +08:00
|
|
|
def getfuncargnames(function, startindex=None):
|
2010-11-06 06:37:31 +08:00
|
|
|
# XXX merge with main.py's varnames
|
2010-09-26 00:23:26 +08:00
|
|
|
argnames = py.std.inspect.getargs(py.code.getrawcode(function))[0]
|
2011-03-05 19:11:35 +08:00
|
|
|
if startindex is None:
|
|
|
|
startindex = py.std.inspect.ismethod(function) and 1 or 0
|
2010-09-26 00:23:26 +08:00
|
|
|
defaults = getattr(function, 'func_defaults',
|
|
|
|
getattr(function, '__defaults__', None)) or ()
|
|
|
|
numdefaults = len(defaults)
|
|
|
|
if numdefaults:
|
|
|
|
return argnames[startindex:-numdefaults]
|
|
|
|
return argnames[startindex:]
|
|
|
|
|
|
|
|
def fillfuncargs(function):
|
|
|
|
""" fill missing funcargs. """
|
|
|
|
request = FuncargRequest(pyfuncitem=function)
|
|
|
|
request._fillfuncargs()
|
|
|
|
|
|
|
|
_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
|
|
|
|
|
|
|
|
def copy(self, metafunc):
|
|
|
|
cs = CallSpec2(self.metafunc)
|
|
|
|
cs.funcargs.update(self.funcargs)
|
|
|
|
cs.params.update(self.params)
|
|
|
|
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
|
|
|
|
|
|
|
def setmulti(self, valtype, argnames, valset, id):
|
|
|
|
for arg,val in zip(argnames, valset):
|
|
|
|
self._checkargnotcontained(arg)
|
|
|
|
getattr(self, valtype)[arg] = val
|
|
|
|
self._idlist.append(id)
|
|
|
|
|
|
|
|
def setall(self, funcargs, id, param):
|
|
|
|
for x in funcargs:
|
|
|
|
self._checkargnotcontained(x)
|
|
|
|
self.funcargs.update(funcargs)
|
|
|
|
if id is not _notexists:
|
|
|
|
self._idlist.append(id)
|
2010-09-26 00:23:26 +08:00
|
|
|
if param is not _notexists:
|
2011-11-17 19:09:21 +08:00
|
|
|
assert self._globalparam is _notexists
|
|
|
|
self._globalparam = param
|
|
|
|
|
2010-09-26 00:23:26 +08:00
|
|
|
|
|
|
|
class Metafunc:
|
|
|
|
def __init__(self, function, config=None, cls=None, module=None):
|
|
|
|
self.config = config
|
|
|
|
self.module = module
|
|
|
|
self.function = function
|
2011-03-05 19:11:35 +08:00
|
|
|
self.funcargnames = getfuncargnames(function,
|
|
|
|
startindex=int(cls is not None))
|
2010-09-26 00:23:26 +08:00
|
|
|
self.cls = cls
|
|
|
|
self.module = module
|
|
|
|
self._calls = []
|
|
|
|
self._ids = py.builtin.set()
|
|
|
|
|
2011-11-17 19:09:21 +08:00
|
|
|
def parametrize(self, argnames, argvalues, indirect=False, ids=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
|
|
|
|
you may pass indirect=True and implement a funcarg factory which can
|
|
|
|
perform the expensive setup just before a test is actually run.
|
2011-11-17 19:09:21 +08:00
|
|
|
|
|
|
|
:arg argnames: an argument name or a list of argument names
|
|
|
|
|
2011-11-20 07:45:05 +08:00
|
|
|
:arg argvalues: a list of values for the argname or a list of tuples of
|
|
|
|
values for the list of argument names.
|
2011-11-17 19:09:21 +08:00
|
|
|
|
2011-12-05 18:10:48 +08:00
|
|
|
:arg indirect: if True each argvalue corresponding to an argument will
|
|
|
|
be passed as request.param to its respective funcarg factory so
|
|
|
|
that it can perform more expensive setups during the setup phase of
|
2011-11-20 07:45:05 +08:00
|
|
|
a test rather than at collection time.
|
2011-11-17 19:09:21 +08:00
|
|
|
|
2011-12-05 18:10:48 +08:00
|
|
|
:arg ids: list of string ids each corresponding to the argvalues so
|
|
|
|
that they are part of the test id. If no ids are provided they will
|
|
|
|
be generated automatically from the argvalues.
|
2011-11-17 19:09:21 +08:00
|
|
|
"""
|
|
|
|
if not isinstance(argnames, (tuple, list)):
|
|
|
|
argnames = (argnames,)
|
|
|
|
argvalues = [(val,) for val in argvalues]
|
|
|
|
for arg in argnames:
|
|
|
|
if arg not in self.funcargnames:
|
|
|
|
raise ValueError("%r has no argument %r" %(self.function, arg))
|
|
|
|
valtype = indirect and "params" or "funcargs"
|
|
|
|
if not ids:
|
|
|
|
idmaker = IDMaker()
|
|
|
|
ids = list(map(idmaker, argvalues))
|
|
|
|
newcalls = []
|
|
|
|
for callspec in self._calls or [CallSpec2(self)]:
|
|
|
|
for i, valset in enumerate(argvalues):
|
|
|
|
assert len(valset) == len(argnames)
|
|
|
|
newcallspec = callspec.copy(self)
|
|
|
|
newcallspec.setmulti(valtype, argnames, valset, ids[i])
|
|
|
|
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
|
|
|
|
2011-11-17 19:09:21 +08:00
|
|
|
:arg param: a parameter which will be exposed to a later funcarg factory
|
|
|
|
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:
|
|
|
|
if name not in self.funcargnames:
|
|
|
|
pytest.fail("funcarg %r not used in this function." % name)
|
2011-11-17 19:09:21 +08:00
|
|
|
else:
|
|
|
|
funcargs = {}
|
2010-09-26 00:23:26 +08:00
|
|
|
if id is None:
|
|
|
|
raise ValueError("id=None not allowed")
|
|
|
|
if id is _notexists:
|
|
|
|
id = len(self._calls)
|
|
|
|
id = str(id)
|
|
|
|
if id in self._ids:
|
|
|
|
raise ValueError("duplicate id %r" % id)
|
|
|
|
self._ids.add(id)
|
2011-11-17 19:09:21 +08:00
|
|
|
|
|
|
|
cs = CallSpec2(self)
|
|
|
|
cs.setall(funcargs, id, param)
|
|
|
|
self._calls.append(cs)
|
|
|
|
|
|
|
|
class IDMaker:
|
|
|
|
def __init__(self):
|
|
|
|
self.counter = 0
|
|
|
|
def __call__(self, valset):
|
|
|
|
l = []
|
|
|
|
for val in valset:
|
|
|
|
if not isinstance(val, (int, str)):
|
|
|
|
val = "."+str(self.counter)
|
|
|
|
self.counter += 1
|
|
|
|
l.append(str(val))
|
|
|
|
return "-".join(l)
|
2010-09-26 00:23:26 +08:00
|
|
|
|
|
|
|
class FuncargRequest:
|
2011-02-09 21:55:21 +08:00
|
|
|
""" A request for function arguments from a test function.
|
2011-11-17 19:09:21 +08:00
|
|
|
|
2011-02-09 21:55:21 +08:00
|
|
|
Note that there is an optional ``param`` attribute in case
|
|
|
|
there was an invocation to metafunc.addcall(param=...).
|
|
|
|
If no such call was done in a ``pytest_generate_tests``
|
|
|
|
hook, the attribute will not be present.
|
|
|
|
"""
|
2010-09-26 00:23:26 +08:00
|
|
|
_argprefix = "pytest_funcarg__"
|
|
|
|
_argname = None
|
|
|
|
|
|
|
|
class LookupError(LookupError):
|
|
|
|
""" error on performing funcarg request. """
|
2011-01-18 19:47:31 +08:00
|
|
|
|
2010-09-26 00:23:26 +08:00
|
|
|
def __init__(self, pyfuncitem):
|
|
|
|
self._pyfuncitem = pyfuncitem
|
|
|
|
if hasattr(pyfuncitem, '_requestparam'):
|
|
|
|
self.param = pyfuncitem._requestparam
|
2010-11-25 09:18:42 +08:00
|
|
|
extra = [obj for obj in (self.module, self.instance) if obj]
|
2010-11-25 05:22:52 +08:00
|
|
|
self._plugins = pyfuncitem.getplugins() + extra
|
2010-09-26 00:23:26 +08:00
|
|
|
self._funcargs = self._pyfuncitem.funcargs.copy()
|
|
|
|
self._name2factory = {}
|
|
|
|
self._currentarg = None
|
|
|
|
|
2010-10-17 05:59:38 +08:00
|
|
|
@property
|
|
|
|
def function(self):
|
|
|
|
""" function object of the test invocation. """
|
|
|
|
return self._pyfuncitem.obj
|
|
|
|
|
|
|
|
@property
|
|
|
|
def keywords(self):
|
|
|
|
""" keywords of the test function item.
|
|
|
|
|
|
|
|
.. versionadded:: 2.0
|
|
|
|
"""
|
|
|
|
return self._pyfuncitem.keywords
|
|
|
|
|
|
|
|
@property
|
|
|
|
def module(self):
|
|
|
|
""" module where the test function was collected. """
|
2010-11-13 16:05:11 +08:00
|
|
|
return self._pyfuncitem.getparent(pytest.Module).obj
|
2011-01-18 19:47:31 +08:00
|
|
|
|
2010-10-17 05:59:38 +08:00
|
|
|
@property
|
|
|
|
def cls(self):
|
|
|
|
""" class (can be None) where the test function was collected. """
|
2010-11-13 16:05:11 +08:00
|
|
|
clscol = self._pyfuncitem.getparent(pytest.Class)
|
2010-10-17 05:59:38 +08:00
|
|
|
if clscol:
|
|
|
|
return clscol.obj
|
|
|
|
@property
|
|
|
|
def instance(self):
|
|
|
|
""" instance (can be None) on which test function was collected. """
|
|
|
|
return py.builtin._getimself(self.function)
|
|
|
|
|
|
|
|
@property
|
|
|
|
def config(self):
|
|
|
|
""" the pytest config object associated with this request. """
|
|
|
|
return self._pyfuncitem.config
|
2011-01-18 19:47:31 +08:00
|
|
|
|
2010-10-17 05:59:38 +08:00
|
|
|
@property
|
|
|
|
def fspath(self):
|
|
|
|
""" the file system path of the test module which collected this test. """
|
|
|
|
return self._pyfuncitem.fspath
|
|
|
|
|
2011-06-01 21:08:54 +08:00
|
|
|
def _fillfuncargs(self):
|
|
|
|
argnames = getfuncargnames(self.function)
|
|
|
|
if argnames:
|
|
|
|
assert not getattr(self._pyfuncitem, '_args', None), (
|
|
|
|
"yielded functions cannot have funcargs")
|
|
|
|
for argname in argnames:
|
|
|
|
if argname not in self._pyfuncitem.funcargs:
|
|
|
|
self._pyfuncitem.funcargs[argname] = self.getfuncargvalue(argname)
|
2010-09-26 00:23:26 +08:00
|
|
|
|
|
|
|
|
|
|
|
def applymarker(self, marker):
|
2011-12-05 18:10:48 +08:00
|
|
|
""" Apply a marker to a single test function invocation.
|
2010-10-14 01:30:00 +08:00
|
|
|
This method is useful if you don't want to have a keyword/marker
|
2010-11-05 06:21:23 +08:00
|
|
|
on all function invocations.
|
2010-09-26 00:23:26 +08:00
|
|
|
|
2010-11-13 18:10:45 +08:00
|
|
|
:arg marker: a :py:class:`_pytest.mark.MarkDecorator` object
|
2010-10-14 01:30:00 +08:00
|
|
|
created by a call to ``py.test.mark.NAME(...)``.
|
2010-09-26 00:23:26 +08:00
|
|
|
"""
|
|
|
|
if not isinstance(marker, py.test.mark.XYZ.__class__):
|
|
|
|
raise ValueError("%r is not a py.test.mark.* object")
|
|
|
|
self._pyfuncitem.keywords[marker.markname] = marker
|
|
|
|
|
|
|
|
def cached_setup(self, setup, teardown=None, scope="module", extrakey=None):
|
2011-12-05 18:10:48 +08:00
|
|
|
""" Return a testing resource managed by ``setup`` &
|
2010-10-11 05:45:45 +08:00
|
|
|
``teardown`` calls. ``scope`` and ``extrakey`` determine when the
|
|
|
|
``teardown`` function will be called so that subsequent calls to
|
|
|
|
``setup`` would recreate the resource.
|
|
|
|
|
|
|
|
:arg teardown: function receiving a previously setup resource.
|
|
|
|
:arg setup: a no-argument function creating a resource.
|
2010-11-21 01:03:18 +08:00
|
|
|
:arg scope: a string value out of ``function``, ``class``, ``module``
|
|
|
|
or ``session`` indicating the caching lifecycle of the resource.
|
2010-10-11 05:45:45 +08:00
|
|
|
:arg extrakey: added to internal caching key of (funcargname, scope).
|
2010-09-26 00:23:26 +08:00
|
|
|
"""
|
|
|
|
if not hasattr(self.config, '_setupcache'):
|
|
|
|
self.config._setupcache = {} # XXX weakref?
|
|
|
|
cachekey = (self._currentarg, self._getscopeitem(scope), extrakey)
|
|
|
|
cache = self.config._setupcache
|
|
|
|
try:
|
|
|
|
val = cache[cachekey]
|
|
|
|
except KeyError:
|
|
|
|
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):
|
2010-10-11 05:45:45 +08:00
|
|
|
""" Retrieve a function argument by name for this test
|
|
|
|
function invocation. This allows one function argument factory
|
|
|
|
to call another function argument factory. If there are two
|
|
|
|
funcarg factories for the same test function argument the first
|
|
|
|
factory may use ``getfuncargvalue`` to call the second one and
|
|
|
|
do something additional with the resource.
|
|
|
|
"""
|
2010-09-26 00:23:26 +08:00
|
|
|
try:
|
|
|
|
return self._funcargs[argname]
|
|
|
|
except KeyError:
|
|
|
|
pass
|
|
|
|
if argname not in self._name2factory:
|
|
|
|
self._name2factory[argname] = self.config.pluginmanager.listattr(
|
|
|
|
plugins=self._plugins,
|
|
|
|
attrname=self._argprefix + str(argname)
|
|
|
|
)
|
|
|
|
#else: we are called recursively
|
|
|
|
if not self._name2factory[argname]:
|
|
|
|
self._raiselookupfailed(argname)
|
|
|
|
funcargfactory = self._name2factory[argname].pop()
|
|
|
|
oldarg = self._currentarg
|
2011-11-17 19:09:21 +08:00
|
|
|
mp = monkeypatch()
|
|
|
|
mp.setattr(self, '_currentarg', argname)
|
|
|
|
try:
|
|
|
|
param = self._pyfuncitem.callspec.getparam(argname)
|
|
|
|
except (AttributeError, ValueError):
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
mp.setattr(self, 'param', param, raising=False)
|
2010-09-26 00:23:26 +08:00
|
|
|
try:
|
|
|
|
self._funcargs[argname] = res = funcargfactory(request=self)
|
|
|
|
finally:
|
2011-11-17 19:09:21 +08:00
|
|
|
mp.undo()
|
2010-09-26 00:23:26 +08:00
|
|
|
return res
|
|
|
|
|
|
|
|
def _getscopeitem(self, scope):
|
|
|
|
if scope == "function":
|
|
|
|
return self._pyfuncitem
|
|
|
|
elif scope == "session":
|
|
|
|
return None
|
2010-11-21 01:03:18 +08:00
|
|
|
elif scope == "class":
|
|
|
|
x = self._pyfuncitem.getparent(pytest.Class)
|
|
|
|
if x is not None:
|
|
|
|
return x
|
|
|
|
scope = "module"
|
|
|
|
if scope == "module":
|
|
|
|
return self._pyfuncitem.getparent(pytest.Module)
|
2010-09-26 00:23:26 +08:00
|
|
|
raise ValueError("unknown finalization scope %r" %(scope,))
|
|
|
|
|
2010-10-11 05:45:45 +08:00
|
|
|
def addfinalizer(self, finalizer):
|
|
|
|
"""add finalizer function to be called after test function
|
|
|
|
finished execution. """
|
|
|
|
self._addfinalizer(finalizer, scope="function")
|
|
|
|
|
2010-09-26 00:23:26 +08:00
|
|
|
def _addfinalizer(self, finalizer, scope):
|
|
|
|
colitem = self._getscopeitem(scope)
|
2011-05-27 06:08:56 +08:00
|
|
|
self._pyfuncitem.session._setupstate.addfinalizer(
|
2010-09-26 00:23:26 +08:00
|
|
|
finalizer=finalizer, colitem=colitem)
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
return "<FuncargRequest for %r>" %(self._pyfuncitem)
|
|
|
|
|
|
|
|
def _raiselookupfailed(self, argname):
|
|
|
|
available = []
|
|
|
|
for plugin in self._plugins:
|
|
|
|
for name in vars(plugin):
|
|
|
|
if name.startswith(self._argprefix):
|
|
|
|
name = name[len(self._argprefix):]
|
|
|
|
if name not in available:
|
|
|
|
available.append(name)
|
|
|
|
fspath, lineno, msg = self._pyfuncitem.reportinfo()
|
|
|
|
msg = "LookupError: no factory found for function argument %r" % (argname,)
|
|
|
|
msg += "\n available funcargs: %s" %(", ".join(available),)
|
|
|
|
msg += "\n use 'py.test --funcargs [testpath]' for help on them."
|
|
|
|
raise self.LookupError(msg)
|
|
|
|
|
|
|
|
def showfuncargs(config):
|
2011-05-27 08:09:42 +08:00
|
|
|
from _pytest.main import wrap_session
|
|
|
|
return wrap_session(config, _showfuncargs_main)
|
|
|
|
|
|
|
|
def _showfuncargs_main(config, session):
|
2010-11-07 17:19:58 +08:00
|
|
|
session.perform_collect()
|
|
|
|
if session.items:
|
2010-11-25 05:22:52 +08:00
|
|
|
plugins = session.items[0].getplugins()
|
2010-11-06 16:58:04 +08:00
|
|
|
else:
|
2010-11-25 05:22:52 +08:00
|
|
|
plugins = session.getplugins()
|
2010-09-26 00:23:26 +08:00
|
|
|
curdir = py.path.local()
|
|
|
|
tw = py.io.TerminalWriter()
|
|
|
|
verbose = config.getvalue("verbose")
|
|
|
|
for plugin in plugins:
|
|
|
|
available = []
|
|
|
|
for name, factory in vars(plugin).items():
|
|
|
|
if name.startswith(FuncargRequest._argprefix):
|
|
|
|
name = name[len(FuncargRequest._argprefix):]
|
|
|
|
if name not in available:
|
|
|
|
available.append([name, factory])
|
|
|
|
if available:
|
|
|
|
pluginname = plugin.__name__
|
|
|
|
for name, factory in available:
|
|
|
|
loc = getlocation(factory, curdir)
|
|
|
|
if verbose:
|
|
|
|
funcargspec = "%s -- %s" %(name, loc,)
|
|
|
|
else:
|
|
|
|
funcargspec = name
|
|
|
|
tw.line(funcargspec, green=True)
|
|
|
|
doc = factory.__doc__ or ""
|
|
|
|
if doc:
|
|
|
|
for line in doc.split("\n"):
|
|
|
|
tw.line(" " + line.strip())
|
|
|
|
else:
|
|
|
|
tw.line(" %s: no docstring available" %(loc,),
|
|
|
|
red=True)
|
|
|
|
|
|
|
|
def getlocation(function, curdir):
|
|
|
|
import inspect
|
|
|
|
fn = py.path.local(inspect.getfile(function))
|
|
|
|
lineno = py.builtin._getcode(function).co_firstlineno
|
|
|
|
if fn.relto(curdir):
|
|
|
|
fn = fn.relto(curdir)
|
|
|
|
return "%s:%d" %(fn, lineno+1)
|
2010-11-06 06:37:31 +08:00
|
|
|
|
|
|
|
# builtin pytest.raises helper
|
|
|
|
|
|
|
|
def raises(ExpectedException, *args, **kwargs):
|
2010-11-25 19:11:10 +08:00
|
|
|
""" assert that a code block/function call raises @ExpectedException
|
|
|
|
and raise a failure exception otherwise.
|
2011-01-18 19:47:31 +08:00
|
|
|
|
2010-11-25 19:11:10 +08:00
|
|
|
If using Python 2.5 or above, you may use this function as a
|
|
|
|
context manager::
|
2010-11-06 06:37:31 +08:00
|
|
|
|
2010-11-25 19:11:10 +08:00
|
|
|
>>> with raises(ZeroDivisionError):
|
|
|
|
... 1/0
|
2010-11-18 21:56:16 +08:00
|
|
|
|
2010-11-25 19:11:10 +08:00
|
|
|
Or you can specify a callable by passing a to-be-called lambda::
|
2010-11-18 21:56:16 +08:00
|
|
|
|
2010-11-25 19:11:10 +08:00
|
|
|
>>> raises(ZeroDivisionError, lambda: 1/0)
|
|
|
|
<ExceptionInfo ...>
|
2010-11-18 21:56:16 +08:00
|
|
|
|
2010-11-25 19:11:10 +08:00
|
|
|
or you can specify an arbitrary callable with arguments::
|
2010-11-18 21:56:16 +08:00
|
|
|
|
2010-11-25 19:11:10 +08:00
|
|
|
>>> def f(x): return 1/x
|
|
|
|
...
|
|
|
|
>>> raises(ZeroDivisionError, f, 0)
|
|
|
|
<ExceptionInfo ...>
|
|
|
|
>>> raises(ZeroDivisionError, f, x=0)
|
|
|
|
<ExceptionInfo ...>
|
2010-11-18 21:56:16 +08:00
|
|
|
|
2011-12-05 18:10:48 +08:00
|
|
|
A third possibility is to use a string to be executed::
|
2011-01-18 19:47:31 +08:00
|
|
|
|
2010-11-25 19:11:10 +08:00
|
|
|
>>> raises(ZeroDivisionError, "f(0)")
|
|
|
|
<ExceptionInfo ...>
|
2010-11-06 06:37:31 +08:00
|
|
|
"""
|
|
|
|
__tracebackhide__ = True
|
|
|
|
|
|
|
|
if not args:
|
|
|
|
return RaisesContext(ExpectedException)
|
|
|
|
elif isinstance(args[0], str):
|
|
|
|
code, = args
|
|
|
|
assert isinstance(code, str)
|
|
|
|
frame = sys._getframe(1)
|
|
|
|
loc = frame.f_locals.copy()
|
|
|
|
loc.update(kwargs)
|
|
|
|
#print "raises frame scope: %r" % frame.f_locals
|
|
|
|
try:
|
|
|
|
code = py.code.Source(code).compile()
|
|
|
|
py.builtin.exec_(code, frame.f_globals, loc)
|
|
|
|
# XXX didn'T mean f_globals == f_locals something special?
|
|
|
|
# this is destroyed here ...
|
|
|
|
except ExpectedException:
|
|
|
|
return py.code.ExceptionInfo()
|
|
|
|
else:
|
|
|
|
func = args[0]
|
|
|
|
try:
|
|
|
|
func(*args[1:], **kwargs)
|
|
|
|
except ExpectedException:
|
|
|
|
return py.code.ExceptionInfo()
|
|
|
|
k = ", ".join(["%s=%r" % x for x in kwargs.items()])
|
|
|
|
if k:
|
|
|
|
k = ', ' + k
|
|
|
|
expr = '%s(%r%s)' %(getattr(func, '__name__', func), args, k)
|
|
|
|
pytest.fail("DID NOT RAISE")
|
|
|
|
|
|
|
|
class RaisesContext(object):
|
|
|
|
def __init__(self, ExpectedException):
|
|
|
|
self.ExpectedException = ExpectedException
|
|
|
|
self.excinfo = None
|
|
|
|
|
|
|
|
def __enter__(self):
|
|
|
|
self.excinfo = object.__new__(py.code.ExceptionInfo)
|
|
|
|
return self.excinfo
|
|
|
|
|
|
|
|
def __exit__(self, *tp):
|
|
|
|
__tracebackhide__ = True
|
|
|
|
if tp[0] is None:
|
|
|
|
pytest.fail("DID NOT RAISE")
|
|
|
|
self.excinfo.__init__(tp)
|
|
|
|
return issubclass(self.excinfo.type, self.ExpectedException)
|
2011-01-18 19:47:31 +08:00
|
|
|
|