2010-11-06 18:38:53 +08:00
|
|
|
""" Python test discovery, setup and run of test functions. """
|
2016-03-08 08:43:53 +08:00
|
|
|
|
2014-10-17 06:27:10 +08:00
|
|
|
import fnmatch
|
2009-09-01 22:10:21 +08:00
|
|
|
import inspect
|
2010-07-04 23:06:50 +08:00
|
|
|
import sys
|
2016-03-23 05:58:28 +08:00
|
|
|
import collections
|
2016-07-06 17:51:48 +08:00
|
|
|
import math
|
2015-11-27 22:43:01 +08:00
|
|
|
|
|
|
|
import py
|
2010-10-07 17:59:00 +08:00
|
|
|
import pytest
|
2015-03-24 03:01:58 +08:00
|
|
|
from _pytest.mark import MarkDecorator, MarkerError
|
2008-08-16 23:26:59 +08:00
|
|
|
|
2015-08-08 21:25:10 +08:00
|
|
|
|
2010-11-13 18:10:45 +08:00
|
|
|
import _pytest
|
2015-08-26 06:43:09 +08:00
|
|
|
import _pytest._pluggy as pluggy
|
2016-07-10 02:36:00 +08:00
|
|
|
from _pytest import fixtures
|
|
|
|
from _pytest.compat import (
|
|
|
|
isclass, isfunction, is_generator, _escape_strings,
|
|
|
|
REGEX_TYPE, STRING_TYPES, NoneType, NOTSET,
|
|
|
|
get_real_func, getfslineno, safe_getattr,
|
|
|
|
getlocation, enum,
|
|
|
|
)
|
2015-04-29 22:40:51 +08:00
|
|
|
|
|
|
|
cutdir2 = py.path.local(_pytest.__file__).dirpath()
|
|
|
|
cutdir1 = py.path.local(pluggy.__file__.rstrip("oc"))
|
|
|
|
|
2010-10-10 19:48:49 +08:00
|
|
|
|
2015-04-29 22:40:51 +08:00
|
|
|
def filter_traceback(entry):
|
2015-10-17 07:08:12 +08:00
|
|
|
# entry.path might sometimes return a str object when the entry
|
2015-10-01 04:15:53 +08:00
|
|
|
# points to dynamically generated code
|
2015-09-30 09:29:43 +08:00
|
|
|
# see https://bitbucket.org/pytest-dev/py/issues/71
|
2015-10-01 04:15:53 +08:00
|
|
|
raw_filename = entry.frame.code.raw.co_filename
|
|
|
|
is_generated = '<' in raw_filename and '>' in raw_filename
|
|
|
|
if is_generated:
|
|
|
|
return False
|
2015-10-17 07:08:12 +08:00
|
|
|
# entry.path might point to an inexisting file, in which case it will
|
|
|
|
# alsso return a str object. see #1133
|
|
|
|
p = py.path.local(entry.path)
|
|
|
|
return p != cutdir1 and not p.relto(cutdir2)
|
2015-04-29 22:40:51 +08:00
|
|
|
|
|
|
|
|
2012-10-05 16:21:35 +08:00
|
|
|
|
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")
|
2016-06-12 07:20:06 +08:00
|
|
|
group.addoption(
|
|
|
|
'--fixtures-per-test',
|
|
|
|
action="store_true",
|
|
|
|
dest="show_fixtures_per_test",
|
|
|
|
default=False,
|
|
|
|
help="show fixtures per test",
|
|
|
|
)
|
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
|
|
|
|
2015-09-17 04:12:20 +08:00
|
|
|
group.addoption("--import-mode", default="prepend",
|
|
|
|
choices=["prepend", "append"], dest="importmode",
|
|
|
|
help="prepend/append to sys.path when importing test modules, "
|
|
|
|
"default is to prepend.")
|
|
|
|
|
|
|
|
|
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
|
2016-06-12 07:20:06 +08:00
|
|
|
if config.option.show_fixtures_per_test:
|
|
|
|
show_fixtures_per_test(config)
|
|
|
|
return 0
|
2010-09-26 00:23:26 +08:00
|
|
|
|
2011-11-17 19:09:21 +08:00
|
|
|
|
|
|
|
def pytest_generate_tests(metafunc):
|
2015-08-07 13:51:59 +08:00
|
|
|
# those alternative spellings are common - raise a specific error to alert
|
|
|
|
# the user
|
|
|
|
alt_spellings = ['parameterize', 'parametrise', 'parameterise']
|
|
|
|
for attr in alt_spellings:
|
|
|
|
if hasattr(metafunc.function, attr):
|
|
|
|
msg = "{0} has '{1}', spelling should be 'parametrize'"
|
|
|
|
raise MarkerError(msg.format(metafunc.function.__name__, attr))
|
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
|
|
|
|
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 {
|
2016-03-07 10:53:48 +08:00
|
|
|
'raises': raises,
|
|
|
|
'approx': approx,
|
2010-11-06 06:37:31 +08:00
|
|
|
'collect': {
|
2016-07-10 02:36:00 +08:00
|
|
|
'Module': Module,
|
|
|
|
'Class': Class,
|
|
|
|
'Instance': Instance,
|
|
|
|
'Function': Function,
|
|
|
|
'Generator': Generator,
|
|
|
|
}
|
2010-11-06 06:37:31 +08:00
|
|
|
}
|
2010-09-26 00:23:26 +08:00
|
|
|
|
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):
|
2015-08-07 02:36:59 +08:00
|
|
|
if collector.istestclass(obj, 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))
|
2015-08-07 02:36:59 +08:00
|
|
|
elif collector.istestfunction(obj, name):
|
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)
|
2015-09-23 07:06:55 +08:00
|
|
|
# We need to try and unwrap the function if it's a functools.partial
|
|
|
|
# or a funtools.wrapped.
|
|
|
|
# We musn't if it's been wrapped with mock.patch (python 2 only)
|
|
|
|
if not (isfunction(obj) or isfunction(get_real_func(obj))):
|
2014-03-12 05:10:18 +08:00
|
|
|
collector.warn(code="C2", message=
|
|
|
|
"cannot collect %r because it is not a function."
|
|
|
|
% name, )
|
2015-09-23 07:06:55 +08:00
|
|
|
elif getattr(obj, "__test__", True):
|
2014-04-10 19:37:39 +08:00
|
|
|
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
|
|
|
|
2016-04-26 15:23:57 +08:00
|
|
|
def pytest_make_parametrize_id(config, val):
|
2016-04-25 22:11:47 +08:00
|
|
|
return None
|
|
|
|
|
2016-07-10 02:36:00 +08:00
|
|
|
|
2010-09-26 00:23:26 +08:00
|
|
|
|
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
|
2015-11-30 23:13:15 +08:00
|
|
|
compat_co_firstlineno = getattr(obj, 'compat_co_firstlineno', None)
|
|
|
|
if isinstance(compat_co_firstlineno, int):
|
2010-11-05 06:21:23 +08:00
|
|
|
# nose compatibility
|
|
|
|
fspath = sys.modules[obj.__module__].__file__
|
|
|
|
if fspath.endswith(".pyc"):
|
|
|
|
fspath = fspath[:-1]
|
2015-11-30 23:13:15 +08:00
|
|
|
lineno = compat_co_firstlineno
|
2010-11-05 06:21:23 +08:00
|
|
|
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
|
|
|
|
2015-08-07 02:36:59 +08:00
|
|
|
def isnosetest(self, obj):
|
|
|
|
""" Look for the __test__ attribute, which is applied by the
|
|
|
|
@nose.tools.istest decorator
|
|
|
|
"""
|
2015-11-30 23:41:13 +08:00
|
|
|
# We explicitly check for "is True" here to not mistakenly treat
|
|
|
|
# classes with a custom __getattr__ returning something truthy (like a
|
|
|
|
# function) as test classes.
|
|
|
|
return safe_getattr(obj, '__test__', False) is True
|
2015-08-07 02:36:59 +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)
|
|
|
|
|
2015-08-07 02:36:59 +08:00
|
|
|
def istestfunction(self, obj, name):
|
|
|
|
return (
|
2016-01-15 07:01:07 +08:00
|
|
|
(self.funcnamefilter(name) or self.isnosetest(obj)) and
|
2016-07-10 02:36:00 +08:00
|
|
|
safe_getattr(obj, "__call__", False) and fixtures.getfixturemarker(obj) is None
|
2015-08-07 02:36:59 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
def istestclass(self, obj, name):
|
|
|
|
return self.classnamefilter(name) or self.isnosetest(obj)
|
|
|
|
|
2014-10-17 06:27:10 +08:00
|
|
|
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:
|
2015-12-10 03:32:19 +08:00
|
|
|
for name, obj in list(dic.items()):
|
2008-08-16 23:26:59 +08:00
|
|
|
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
|
2016-07-10 02:36:00 +08:00
|
|
|
fixtures.add_funcarg_pseudo_fixture_def(self, metafunc, fm)
|
2013-12-07 23:37:46 +08:00
|
|
|
|
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
|
|
|
|
2015-07-25 22:28:18 +08:00
|
|
|
|
|
|
|
def _marked(func, mark):
|
2015-08-07 02:36:59 +08:00
|
|
|
""" Returns True if :func: is already marked with :mark:, False otherwise.
|
2015-07-25 22:28:18 +08:00
|
|
|
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
|
2015-09-17 04:12:20 +08:00
|
|
|
importmode = self.config.getoption("--import-mode")
|
2010-07-04 23:06:50 +08:00
|
|
|
try:
|
2015-09-17 04:12:20 +08:00
|
|
|
mod = self.fspath.pyimport(ensuresyspath=importmode)
|
2010-07-04 23:06:50 +08:00
|
|
|
except SyntaxError:
|
2014-04-02 21:34:36 +08:00
|
|
|
raise self.CollectError(
|
2015-11-27 22:43:01 +08:00
|
|
|
_pytest._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
|
|
|
|
)
|
2016-04-17 18:43:04 +08:00
|
|
|
except ImportError:
|
|
|
|
exc_class, exc, _ = sys.exc_info()
|
|
|
|
raise self.CollectError(
|
|
|
|
"ImportError while importing test module '%s'.\n"
|
|
|
|
"Original error message:\n'%s'\n"
|
|
|
|
"Make sure your test modules/packages have valid Python names."
|
|
|
|
% (self.fspath, exc or exc_class)
|
|
|
|
)
|
2016-04-11 01:57:45 +08:00
|
|
|
except _pytest.runner.Skipped:
|
|
|
|
raise self.CollectError(
|
|
|
|
"Using @pytest.skip outside a test (e.g. as a test function "
|
|
|
|
"decorator) is not allowed. Use @pytest.mark.skip or "
|
|
|
|
"@pytest.mark.skipif instead."
|
|
|
|
)
|
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):
|
2016-07-15 08:28:59 +08:00
|
|
|
setup_module = _get_xunit_setup_teardown(self.obj, "setUpModule")
|
2013-06-20 22:43:42 +08:00
|
|
|
if setup_module is None:
|
2016-07-15 08:28:59 +08:00
|
|
|
setup_module = _get_xunit_setup_teardown(self.obj, "setup_module")
|
2012-08-13 19:37:14 +08:00
|
|
|
if setup_module is not None:
|
2016-07-15 08:28:59 +08:00
|
|
|
setup_module()
|
|
|
|
|
|
|
|
teardown_module = _get_xunit_setup_teardown(self.obj, 'tearDownModule')
|
|
|
|
if teardown_module is None:
|
|
|
|
teardown_module = _get_xunit_setup_teardown(self.obj, 'teardown_module')
|
|
|
|
if teardown_module is not None:
|
|
|
|
self.addfinalizer(teardown_module)
|
|
|
|
|
|
|
|
|
|
|
|
def _get_xunit_setup_teardown(holder, attr_name, param_obj=None):
|
|
|
|
"""
|
|
|
|
Return a callable to perform xunit-style setup or teardown if
|
|
|
|
the function exists in the ``holder`` object.
|
|
|
|
The ``param_obj`` parameter is the parameter which will be passed to the function
|
|
|
|
when the callable is called without arguments, defaults to the ``holder`` object.
|
|
|
|
Return ``None`` if a suitable callable is not found.
|
|
|
|
"""
|
|
|
|
param_obj = param_obj if param_obj is not None else holder
|
|
|
|
result = _get_xunit_func(holder, attr_name)
|
|
|
|
if result is not None:
|
|
|
|
arg_count = result.__code__.co_argcount
|
|
|
|
if inspect.ismethod(result):
|
|
|
|
arg_count -= 1
|
|
|
|
if arg_count:
|
|
|
|
return lambda: result(param_obj)
|
|
|
|
else:
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
|
|
def _get_xunit_func(obj, name):
|
|
|
|
"""Return the attribute from the given object to be used as a setup/teardown
|
|
|
|
xunit-style function, but only if not marked as a fixture to
|
|
|
|
avoid calling it twice.
|
|
|
|
"""
|
|
|
|
meth = getattr(obj, name, None)
|
|
|
|
if fixtures.getfixturemarker(meth) is None:
|
|
|
|
return meth
|
2013-08-02 15:52:40 +08:00
|
|
|
|
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 []
|
2016-07-23 23:37:58 +08:00
|
|
|
elif hasnew(self.obj):
|
|
|
|
self.warn("C1", "cannot collect test class %r because it has a "
|
|
|
|
"__new__ 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):
|
2016-07-15 08:28:59 +08:00
|
|
|
setup_class = _get_xunit_func(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):
|
2016-07-23 23:37:58 +08:00
|
|
|
return self.parent.obj()
|
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(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'
|
2016-07-15 08:28:59 +08:00
|
|
|
setup_func_or_method = _get_xunit_setup_teardown(obj, setup_name, param_obj=self.obj)
|
2010-07-27 03:15:15 +08:00
|
|
|
if setup_func_or_method is not None:
|
2016-07-15 08:28:59 +08:00
|
|
|
setup_func_or_method()
|
|
|
|
teardown_func_or_method = _get_xunit_setup_teardown(obj, teardown_name, param_obj=self.obj)
|
|
|
|
if teardown_func_or_method is not None:
|
|
|
|
self.addfinalizer(teardown_func_or_method)
|
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-11-27 22:43:01 +08:00
|
|
|
code = _pytest._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:
|
2016-03-06 03:09:01 +08:00
|
|
|
return py._builtin._totext(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)
|
2016-07-23 22:56:04 +08:00
|
|
|
from _pytest import deprecated
|
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))
|
2016-07-23 22:56:04 +08:00
|
|
|
self.config.warn('C1', deprecated.YIELD_TESTS, fslocation=self.fspath)
|
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:
|
2016-07-23 23:37:58 +08:00
|
|
|
return init != object.__init__
|
|
|
|
|
2010-09-26 00:23:26 +08:00
|
|
|
|
2016-07-23 23:37:58 +08:00
|
|
|
def hasnew(obj):
|
|
|
|
new = getattr(obj, '__new__', None)
|
|
|
|
if new:
|
|
|
|
return new != object.__new__
|
2010-09-26 00:23:26 +08:00
|
|
|
|
|
|
|
|
2011-11-17 19:09:21 +08:00
|
|
|
class CallSpec2(object):
|
|
|
|
def __init__(self, metafunc):
|
|
|
|
self.metafunc = metafunc
|
|
|
|
self.funcargs = {}
|
|
|
|
self._idlist = []
|
|
|
|
self.params = {}
|
2016-07-10 02:36:00 +08:00
|
|
|
self._globalid = NOTSET
|
2011-11-17 19:09:21 +08:00
|
|
|
self._globalid_args = set()
|
2016-07-10 02:36:00 +08:00
|
|
|
self._globalparam = NOTSET
|
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:
|
2016-07-10 02:36:00 +08:00
|
|
|
if self._globalparam is NOTSET:
|
2011-11-17 19:09:21 +08:00
|
|
|
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
|
|
|
|
2015-08-02 21:40:40 +08:00
|
|
|
def setmulti(self, valtypes, argnames, valset, id, keywords, scopenum,
|
2013-12-04 04:05:19 +08:00
|
|
|
param_index):
|
2011-11-17 19:09:21 +08:00
|
|
|
for arg,val in zip(argnames, valset):
|
|
|
|
self._checkargnotcontained(arg)
|
2015-08-02 21:40:40 +08:00
|
|
|
valtype_for_arg = valtypes[arg]
|
|
|
|
getattr(self, valtype_for_arg)[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
|
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)
|
2016-07-10 02:36:00 +08:00
|
|
|
if id is not NOTSET:
|
2011-11-17 19:09:21 +08:00
|
|
|
self._idlist.append(id)
|
2016-07-10 02:36:00 +08:00
|
|
|
if param is not NOTSET:
|
|
|
|
assert self._globalparam is NOTSET
|
2011-11-17 19:09:21 +08:00
|
|
|
self._globalparam = param
|
2013-12-07 23:37:46 +08:00
|
|
|
for arg in funcargs:
|
2016-07-10 02:36:00 +08:00
|
|
|
self._arg2scopenum[arg] = fixtures.scopenum_function
|
2011-11-17 19:09:21 +08:00
|
|
|
|
2010-09-26 00:23:26 +08:00
|
|
|
|
2016-07-10 02:36:00 +08:00
|
|
|
class Metafunc(fixtures.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
|
2015-08-04 05:48:41 +08:00
|
|
|
see about setting indirect 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
|
2015-09-22 22:45:49 +08:00
|
|
|
argname was specified argvalues is a list of values. If N
|
2013-05-22 21:24:58 +08:00
|
|
|
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
|
|
|
|
2015-08-02 21:40:40 +08:00
|
|
|
:arg indirect: The list of argnames or boolean. A list of arguments'
|
|
|
|
names (subset of argnames). If True the list contains all names from
|
|
|
|
the argnames. Each argvalue corresponding to an argname in this list will
|
2012-10-09 20:35:17 +08:00
|
|
|
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
|
2016-03-21 00:54:48 +08:00
|
|
|
part of the test id. If None is given as id of specific test, the
|
|
|
|
automatically generated id for that argument will be used.
|
2014-04-18 03:08:49 +08:00
|
|
|
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
|
|
|
"""
|
2016-07-26 06:04:39 +08:00
|
|
|
from _pytest.fixtures import scopes
|
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:
|
2016-07-10 02:36:00 +08:00
|
|
|
argvalues = [(NOTSET,) * len(argnames)]
|
2016-04-22 02:57:53 +08:00
|
|
|
# we passed a empty list to parameterize, skip that test
|
|
|
|
#
|
2016-05-30 20:41:00 +08:00
|
|
|
fs, lineno = getfslineno(self.function)
|
2016-04-22 02:57:53 +08:00
|
|
|
newmark = pytest.mark.skip(
|
2016-05-30 20:42:55 +08:00
|
|
|
reason="got empty parameter set %r, function %s at %s:%d" % (
|
|
|
|
argnames, self.function.__name__, fs, lineno))
|
2016-04-22 02:57:53 +08:00
|
|
|
newmarks = newkeywords.setdefault(0, {})
|
|
|
|
newmarks[newmark.markname] = newmark
|
|
|
|
|
2012-07-30 18:39:45 +08:00
|
|
|
if scope is None:
|
2016-07-25 16:54:02 +08:00
|
|
|
if self._arg2fixturedefs:
|
|
|
|
# Takes the most narrow scope from used fixtures
|
|
|
|
fixtures_scopes = [fixturedef[0].scope for fixturedef in self._arg2fixturedefs.values()]
|
|
|
|
for scope in reversed(scopes):
|
|
|
|
if scope in fixtures_scopes:
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
scope = 'function'
|
2012-07-30 16:46:03 +08:00
|
|
|
scopenum = scopes.index(scope)
|
2015-08-04 05:02:03 +08:00
|
|
|
valtypes = {}
|
2015-08-23 18:42:40 +08:00
|
|
|
for arg in argnames:
|
|
|
|
if arg not in self.fixturenames:
|
2016-07-23 22:49:20 +08:00
|
|
|
if isinstance(indirect, (tuple, list)):
|
|
|
|
name = 'fixture' if arg in indirect else 'argument'
|
|
|
|
else:
|
2016-07-24 16:47:06 +08:00
|
|
|
name = 'fixture' if indirect else 'argument'
|
2016-07-23 22:49:20 +08:00
|
|
|
raise ValueError(
|
|
|
|
"%r uses no %s %r" % (
|
|
|
|
self.function, name, arg))
|
2015-08-23 18:42:40 +08:00
|
|
|
|
2015-08-04 05:02:03 +08:00
|
|
|
if indirect is True:
|
|
|
|
valtypes = dict.fromkeys(argnames, "params")
|
|
|
|
elif indirect is False:
|
|
|
|
valtypes = dict.fromkeys(argnames, "funcargs")
|
|
|
|
elif isinstance(indirect, (tuple, list)):
|
|
|
|
valtypes = dict.fromkeys(argnames, "funcargs")
|
|
|
|
for arg in indirect:
|
|
|
|
if arg not in argnames:
|
2016-07-23 22:49:20 +08:00
|
|
|
raise ValueError("indirect given to %r: fixture %r doesn't exist" % (
|
2015-08-04 05:02:03 +08:00
|
|
|
self.function, arg))
|
|
|
|
valtypes[arg] = "params"
|
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)))
|
2016-04-25 22:11:47 +08:00
|
|
|
ids = idmaker(argnames, argvalues, idfn, ids, self.config)
|
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)
|
2015-08-02 21:40:40 +08:00
|
|
|
newcallspec.setmulti(valtypes, argnames, valset, ids[param_index],
|
2013-12-04 04:05:19 +08:00
|
|
|
newkeywords.get(param_index, {}), scopenum,
|
|
|
|
param_index)
|
2011-11-17 19:09:21 +08:00
|
|
|
newcalls.append(newcallspec)
|
|
|
|
self._calls = newcalls
|
|
|
|
|
2016-07-10 02:36:00 +08:00
|
|
|
def addcall(self, funcargs=None, id=NOTSET, param=NOTSET):
|
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")
|
2016-07-10 02:36:00 +08:00
|
|
|
if id is NOTSET:
|
2010-09-26 00:23:26 +08:00
|
|
|
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
|
|
|
|
2016-03-22 13:31:48 +08:00
|
|
|
|
2015-09-23 09:48:22 +08:00
|
|
|
|
2016-04-25 22:48:28 +08:00
|
|
|
def _idval(val, argname, idx, idfn, config=None):
|
2014-04-18 03:08:49 +08:00
|
|
|
if idfn:
|
|
|
|
try:
|
|
|
|
s = idfn(val)
|
|
|
|
if s:
|
2016-03-22 13:31:48 +08:00
|
|
|
return _escape_strings(s)
|
2014-04-18 03:08:49 +08:00
|
|
|
except Exception:
|
|
|
|
pass
|
2015-08-07 13:31:04 +08:00
|
|
|
|
2016-04-25 22:11:47 +08:00
|
|
|
if config:
|
2016-04-26 15:23:57 +08:00
|
|
|
hook_id = config.hook.pytest_make_parametrize_id(config=config, val=val)
|
2016-04-25 22:11:47 +08:00
|
|
|
if hook_id:
|
|
|
|
return hook_id
|
|
|
|
|
2016-07-10 02:36:00 +08:00
|
|
|
if isinstance(val, STRING_TYPES):
|
2016-03-22 13:31:48 +08:00
|
|
|
return _escape_strings(val)
|
2016-04-02 00:27:17 +08:00
|
|
|
elif isinstance(val, (float, int, bool, NoneType)):
|
2014-04-18 03:08:49 +08:00
|
|
|
return str(val)
|
2015-08-08 18:57:54 +08:00
|
|
|
elif isinstance(val, REGEX_TYPE):
|
2016-03-22 13:31:48 +08:00
|
|
|
return _escape_strings(val.pattern)
|
2015-08-07 13:31:04 +08:00
|
|
|
elif enum is not None and isinstance(val, enum.Enum):
|
|
|
|
return str(val)
|
2015-08-08 18:57:54 +08:00
|
|
|
elif 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)
|
|
|
|
|
2016-04-25 22:48:28 +08:00
|
|
|
def _idvalset(idx, valset, argnames, idfn, ids, config=None):
|
2016-03-20 03:22:49 +08:00
|
|
|
if ids is None or ids[idx] is None:
|
2016-04-25 22:11:47 +08:00
|
|
|
this_id = [_idval(val, argname, idx, idfn, config)
|
2016-03-20 03:22:49 +08:00
|
|
|
for val, argname in zip(valset, argnames)]
|
|
|
|
return "-".join(this_id)
|
|
|
|
else:
|
2016-03-23 04:22:00 +08:00
|
|
|
return _escape_strings(ids[idx])
|
2014-04-18 03:08:49 +08:00
|
|
|
|
2016-04-25 22:11:47 +08:00
|
|
|
def idmaker(argnames, argvalues, idfn=None, ids=None, config=None):
|
|
|
|
ids = [_idvalset(valindex, valset, argnames, idfn, ids, config)
|
2014-04-18 03:08:49 +08:00
|
|
|
for valindex, valset in enumerate(argvalues)]
|
2016-03-24 00:47:27 +08:00
|
|
|
if len(set(ids)) != len(ids):
|
2016-03-23 05:58:28 +08:00
|
|
|
# The ids are not unique
|
2016-03-24 00:47:27 +08:00
|
|
|
duplicates = [testid for testid in ids if ids.count(testid) > 1]
|
2016-03-23 05:58:28 +08:00
|
|
|
counters = collections.defaultdict(lambda: 0)
|
|
|
|
for index, testid in enumerate(ids):
|
|
|
|
if testid in duplicates:
|
|
|
|
ids[index] = testid + str(counters[testid])
|
|
|
|
counters[testid] += 1
|
2014-04-18 03:08:49 +08:00
|
|
|
return ids
|
2010-09-26 00:23:26 +08:00
|
|
|
|
2016-06-12 07:20:06 +08:00
|
|
|
|
|
|
|
def show_fixtures_per_test(config):
|
|
|
|
from _pytest.main import wrap_session
|
|
|
|
return wrap_session(config, _show_fixtures_per_test)
|
|
|
|
|
|
|
|
|
|
|
|
def _show_fixtures_per_test(config, session):
|
|
|
|
import _pytest.config
|
|
|
|
session.perform_collect()
|
|
|
|
curdir = py.path.local()
|
|
|
|
tw = _pytest.config.create_terminal_writer(config)
|
|
|
|
verbose = config.getvalue("verbose")
|
|
|
|
|
|
|
|
def get_best_rel(func):
|
|
|
|
loc = getlocation(func, curdir)
|
|
|
|
return curdir.bestrelpath(loc)
|
|
|
|
|
|
|
|
def write_fixture(fixture_def):
|
|
|
|
argname = fixture_def.argname
|
|
|
|
|
|
|
|
if verbose <= 0 and argname.startswith("_"):
|
|
|
|
return
|
|
|
|
if verbose > 0:
|
|
|
|
bestrel = get_best_rel(fixture_def.func)
|
2016-06-12 07:52:03 +08:00
|
|
|
funcargspec = "{0} -- {1}".format(argname, bestrel)
|
2016-06-12 07:20:06 +08:00
|
|
|
else:
|
|
|
|
funcargspec = argname
|
|
|
|
tw.line(funcargspec, green=True)
|
|
|
|
|
2016-06-12 07:52:03 +08:00
|
|
|
INDENT = ' {0}'
|
2016-06-12 07:20:06 +08:00
|
|
|
fixture_doc = fixture_def.func.__doc__
|
|
|
|
|
|
|
|
if fixture_doc:
|
|
|
|
for line in fixture_doc.strip().split('\n'):
|
|
|
|
tw.line(INDENT.format(line.strip()))
|
|
|
|
else:
|
|
|
|
tw.line(INDENT.format('no docstring available'), red=True)
|
|
|
|
|
|
|
|
def write_item(item):
|
|
|
|
name2fixturedefs = item._fixtureinfo.name2fixturedefs
|
|
|
|
|
|
|
|
if not name2fixturedefs:
|
|
|
|
# The given test item does not use any fixtures
|
|
|
|
return
|
|
|
|
bestrel = get_best_rel(item.function)
|
|
|
|
|
|
|
|
tw.line()
|
2016-06-12 07:52:03 +08:00
|
|
|
tw.sep('-', 'fixtures used by {0}'.format(item.name))
|
2016-06-12 22:58:32 +08:00
|
|
|
tw.sep('-', '({0})'.format(bestrel))
|
2016-06-12 07:20:06 +08:00
|
|
|
for argname, fixture_defs in sorted(name2fixturedefs.items()):
|
|
|
|
assert fixture_defs is not None
|
|
|
|
if not fixture_defs:
|
|
|
|
continue
|
|
|
|
# The last fixture def item in the list is expected
|
|
|
|
# to be the one used by the test item
|
|
|
|
write_fixture(fixture_defs[-1])
|
|
|
|
|
|
|
|
for item in session.items:
|
|
|
|
write_item(item)
|
|
|
|
|
|
|
|
|
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
|
2016-08-02 06:51:35 +08:00
|
|
|
from _pytest.fixtures import strip_invocation_scope_suffix
|
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 = []
|
2016-08-02 04:59:51 +08:00
|
|
|
seen = set()
|
|
|
|
|
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
|
2016-05-31 01:00:31 +08:00
|
|
|
for fixturedef in fixturedefs:
|
|
|
|
loc = getlocation(fixturedef.func, curdir)
|
2016-08-02 04:59:51 +08:00
|
|
|
# invocation-scoped fixtures have argname in the form
|
|
|
|
# "<name>:<scope>" (for example: "monkeypatch:session").
|
2016-08-02 06:51:35 +08:00
|
|
|
fixture_argname = strip_invocation_scope_suffix(fixturedef.argname)
|
2016-08-02 04:59:51 +08:00
|
|
|
if (fixture_argname, loc) in seen:
|
|
|
|
continue
|
|
|
|
seen.add((fixture_argname, loc))
|
2016-05-31 01:00:31 +08:00
|
|
|
available.append((len(fixturedef.baseid),
|
|
|
|
fixturedef.func.__module__,
|
|
|
|
curdir.bestrelpath(loc),
|
2016-08-02 04:59:51 +08:00
|
|
|
fixture_argname, fixturedef))
|
2012-10-09 22:49:04 +08:00
|
|
|
|
|
|
|
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
|
|
|
|
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):
|
2016-03-08 10:14:49 +08:00
|
|
|
"""
|
|
|
|
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
|
|
|
|
2015-11-27 22:43:01 +08:00
|
|
|
This helper produces a ``ExceptionInfo()`` object (see below).
|
2013-08-01 17:19:47 +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
|
|
|
|
2016-06-20 04:56:43 +08:00
|
|
|
.. versionchanged:: 2.10
|
|
|
|
|
2016-06-20 04:34:42 +08:00
|
|
|
In the context manager form you may use the keyword argument
|
|
|
|
``message`` to specify a custom failure message::
|
|
|
|
|
|
|
|
>>> with raises(ZeroDivisionError, message="Expecting ZeroDivisionError"):
|
|
|
|
... pass
|
|
|
|
... Failed: Expecting ZeroDivisionError
|
|
|
|
|
|
|
|
|
2015-10-03 03:40:58 +08:00
|
|
|
.. note::
|
|
|
|
|
|
|
|
When using ``pytest.raises`` as a context manager, it's worthwhile to
|
|
|
|
note that normal context manager rules apply and that the exception
|
|
|
|
raised *must* be the final line in the scope of the context manager.
|
|
|
|
Lines of code after that, within the scope of the context manager will
|
|
|
|
not be executed. For example::
|
|
|
|
|
2015-11-27 22:43:01 +08:00
|
|
|
>>> with raises(OSError) as exc_info:
|
2015-10-03 03:40:58 +08:00
|
|
|
assert 1 == 1 # this will execute as expected
|
|
|
|
raise OSError(errno.EEXISTS, 'directory exists')
|
2015-11-27 22:43:01 +08:00
|
|
|
assert exc_info.value.errno == errno.EEXISTS # this will not execute
|
2015-10-03 03:40:58 +08:00
|
|
|
|
|
|
|
Instead, the following approach must be taken (note the difference in
|
|
|
|
scope)::
|
|
|
|
|
2015-11-27 22:43:01 +08:00
|
|
|
>>> with raises(OSError) as exc_info:
|
2015-10-03 03:40:58 +08:00
|
|
|
assert 1 == 1 # this will execute as expected
|
|
|
|
raise OSError(errno.EEXISTS, 'directory exists')
|
|
|
|
|
2015-11-27 22:43:01 +08:00
|
|
|
assert exc_info.value.errno == errno.EEXISTS # this will now execute
|
2015-10-06 03:13:25 +08:00
|
|
|
|
|
|
|
Or you can specify a callable by passing a to-be-called lambda::
|
|
|
|
|
|
|
|
>>> raises(ZeroDivisionError, lambda: 1/0)
|
|
|
|
<ExceptionInfo ...>
|
|
|
|
|
|
|
|
or you can specify an arbitrary callable with arguments::
|
|
|
|
|
|
|
|
>>> def f(x): return 1/x
|
|
|
|
...
|
|
|
|
>>> raises(ZeroDivisionError, f, 0)
|
|
|
|
<ExceptionInfo ...>
|
|
|
|
>>> raises(ZeroDivisionError, f, x=0)
|
|
|
|
<ExceptionInfo ...>
|
|
|
|
|
|
|
|
A third possibility is to use a string to be executed::
|
|
|
|
|
|
|
|
>>> raises(ZeroDivisionError, "f(0)")
|
|
|
|
<ExceptionInfo ...>
|
2015-10-03 03:40:58 +08:00
|
|
|
|
2015-11-27 22:43:01 +08:00
|
|
|
.. autoclass:: _pytest._code.ExceptionInfo
|
|
|
|
:members:
|
2014-04-15 06:09:10 +08:00
|
|
|
|
2015-11-27 22:43:01 +08:00
|
|
|
.. note::
|
|
|
|
Similar to caught exception objects in Python, explicitly clearing
|
|
|
|
local references to returned ``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
|
|
|
|
official Python ``try`` statement documentation for more detailed
|
|
|
|
information.
|
2014-01-23 18:36:04 +08:00
|
|
|
|
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:
|
2015-08-09 00:10:14 +08:00
|
|
|
if not isclass(exc):
|
2014-04-15 06:09:10 +08:00
|
|
|
raise TypeError(msg % type(exc))
|
2015-08-09 00:10:14 +08:00
|
|
|
elif not isclass(expected_exception):
|
2015-07-29 07:01:11 +08:00
|
|
|
raise TypeError(msg % type(expected_exception))
|
2010-11-06 06:37:31 +08:00
|
|
|
|
2016-06-20 02:24:47 +08:00
|
|
|
message = "DID NOT RAISE {0}".format(expected_exception)
|
2016-06-17 01:15:32 +08:00
|
|
|
|
2010-11-06 06:37:31 +08:00
|
|
|
if not args:
|
2016-06-20 02:24:47 +08:00
|
|
|
if "message" in kwargs:
|
|
|
|
message = kwargs.pop("message")
|
2016-06-17 01:15:32 +08:00
|
|
|
return RaisesContext(expected_exception, message)
|
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:
|
2015-11-27 22:43:01 +08:00
|
|
|
code = _pytest._code.Source(code).compile()
|
2010-11-06 06:37:31 +08:00
|
|
|
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:
|
2015-11-27 22:43:01 +08:00
|
|
|
return _pytest._code.ExceptionInfo()
|
2010-11-06 06:37:31 +08:00
|
|
|
else:
|
|
|
|
func = args[0]
|
|
|
|
try:
|
|
|
|
func(*args[1:], **kwargs)
|
2015-07-29 07:01:11 +08:00
|
|
|
except expected_exception:
|
2015-11-27 22:43:01 +08:00
|
|
|
return _pytest._code.ExceptionInfo()
|
2016-06-17 01:15:32 +08:00
|
|
|
pytest.fail(message)
|
2010-11-06 06:37:31 +08:00
|
|
|
|
|
|
|
class RaisesContext(object):
|
2016-06-17 01:15:32 +08:00
|
|
|
def __init__(self, expected_exception, message):
|
2015-07-29 07:01:11 +08:00
|
|
|
self.expected_exception = expected_exception
|
2016-06-17 01:15:32 +08:00
|
|
|
self.message = message
|
2010-11-06 06:37:31 +08:00
|
|
|
self.excinfo = None
|
|
|
|
|
|
|
|
def __enter__(self):
|
2015-11-27 22:43:01 +08:00
|
|
|
self.excinfo = object.__new__(_pytest._code.ExceptionInfo)
|
2010-11-06 06:37:31 +08:00
|
|
|
return self.excinfo
|
|
|
|
|
|
|
|
def __exit__(self, *tp):
|
|
|
|
__tracebackhide__ = True
|
|
|
|
if tp[0] is None:
|
2016-06-17 01:15:32 +08:00
|
|
|
pytest.fail(self.message)
|
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
|
|
|
|
2016-03-07 10:53:48 +08:00
|
|
|
# builtin pytest.approx helper
|
|
|
|
|
2016-03-08 08:40:41 +08:00
|
|
|
class approx(object):
|
2016-03-08 10:14:49 +08:00
|
|
|
"""
|
2016-03-12 07:59:48 +08:00
|
|
|
Assert that two numbers (or two sets of numbers) are equal to each other
|
|
|
|
within some tolerance.
|
2016-03-07 10:53:48 +08:00
|
|
|
|
2016-03-12 07:59:48 +08:00
|
|
|
Due to the `intricacies of floating-point arithmetic`__, numbers that we
|
|
|
|
would intuitively expect to be equal are not always so::
|
2016-03-07 10:53:48 +08:00
|
|
|
|
|
|
|
>>> 0.1 + 0.2 == 0.3
|
|
|
|
False
|
|
|
|
|
2016-03-12 07:59:48 +08:00
|
|
|
__ https://docs.python.org/3/tutorial/floatingpoint.html
|
|
|
|
|
2016-03-08 02:09:20 +08:00
|
|
|
This problem is commonly encountered when writing tests, e.g. when making
|
2016-03-08 10:14:49 +08:00
|
|
|
sure that floating-point values are what you expect them to be. One way to
|
|
|
|
deal with this problem is to assert that two floating-point numbers are
|
2016-03-12 07:59:48 +08:00
|
|
|
equal to within some appropriate tolerance::
|
|
|
|
|
2016-03-07 10:53:48 +08:00
|
|
|
>>> abs((0.1 + 0.2) - 0.3) < 1e-6
|
|
|
|
True
|
2016-03-12 07:59:48 +08:00
|
|
|
|
2016-03-07 10:53:48 +08:00
|
|
|
However, comparisons like this are tedious to write and difficult to
|
|
|
|
understand. Furthermore, absolute comparisons like the one above are
|
2016-03-12 07:59:48 +08:00
|
|
|
usually discouraged because there's no tolerance that works well for all
|
|
|
|
situations. ``1e-6`` is good for numbers around ``1``, but too small for
|
|
|
|
very big numbers and too big for very small ones. It's better to express
|
|
|
|
the tolerance as a fraction of the expected value, but relative comparisons
|
|
|
|
like that are even more difficult to write correctly and concisely.
|
|
|
|
|
|
|
|
The ``approx`` class performs floating-point comparisons using a syntax
|
|
|
|
that's as intuitive as possible::
|
2016-03-07 10:53:48 +08:00
|
|
|
|
|
|
|
>>> from pytest import approx
|
|
|
|
>>> 0.1 + 0.2 == approx(0.3)
|
|
|
|
True
|
|
|
|
|
2016-03-12 07:59:48 +08:00
|
|
|
The same syntax also works on sequences of numbers::
|
2016-03-07 10:53:48 +08:00
|
|
|
|
|
|
|
>>> (0.1 + 0.2, 0.2 + 0.4) == approx((0.3, 0.6))
|
|
|
|
True
|
|
|
|
|
2016-03-12 07:59:48 +08:00
|
|
|
By default, ``approx`` considers numbers within a relative tolerance of
|
|
|
|
``1e-6`` (i.e. one part in a million) of its expected value to be equal.
|
|
|
|
This treatment would lead to surprising results if the expected value was
|
|
|
|
``0.0``, because nothing but ``0.0`` itself is relatively close to ``0.0``.
|
|
|
|
To handle this case less surprisingly, ``approx`` also considers numbers
|
|
|
|
within an absolute tolerance of ``1e-12`` of its expected value to be
|
|
|
|
equal. Infinite numbers are another special case. They are only
|
|
|
|
considered equal to themselves, regardless of the relative tolerance. Both
|
|
|
|
the relative and absolute tolerances can be changed by passing arguments to
|
|
|
|
the ``approx`` constructor::
|
2016-03-07 10:53:48 +08:00
|
|
|
|
|
|
|
>>> 1.0001 == approx(1)
|
|
|
|
False
|
|
|
|
>>> 1.0001 == approx(1, rel=1e-3)
|
|
|
|
True
|
|
|
|
>>> 1.0001 == approx(1, abs=1e-3)
|
|
|
|
True
|
|
|
|
|
2016-03-12 07:59:48 +08:00
|
|
|
If you specify ``abs`` but not ``rel``, the comparison will not consider
|
|
|
|
the relative tolerance at all. In other words, two numbers that are within
|
|
|
|
the default relative tolerance of ``1e-6`` will still be considered unequal
|
|
|
|
if they exceed the specified absolute tolerance. If you specify both
|
|
|
|
``abs`` and ``rel``, the numbers will be considered equal if either
|
|
|
|
tolerance is met::
|
2016-03-07 10:53:48 +08:00
|
|
|
|
2016-03-08 08:43:53 +08:00
|
|
|
>>> 1 + 1e-8 == approx(1)
|
|
|
|
True
|
|
|
|
>>> 1 + 1e-8 == approx(1, abs=1e-12)
|
2016-03-07 10:53:48 +08:00
|
|
|
False
|
2016-03-08 08:43:53 +08:00
|
|
|
>>> 1 + 1e-8 == approx(1, rel=1e-6, abs=1e-12)
|
2016-03-08 02:09:20 +08:00
|
|
|
True
|
2016-03-12 07:59:48 +08:00
|
|
|
|
|
|
|
If you're thinking about using ``approx``, then you might want to know how
|
|
|
|
it compares to other good ways of comparing floating-point numbers. All of
|
2016-03-15 02:38:00 +08:00
|
|
|
these algorithms are based on relative and absolute tolerances and should
|
|
|
|
agree for the most part, but they do have meaningful differences:
|
2016-03-12 07:59:48 +08:00
|
|
|
|
|
|
|
- ``math.isclose(a, b, rel_tol=1e-9, abs_tol=0.0)``: True if the relative
|
|
|
|
tolerance is met w.r.t. either ``a`` or ``b`` or if the absolute
|
|
|
|
tolerance is met. Because the relative tolerance is calculated w.r.t.
|
|
|
|
both ``a`` and ``b``, this test is symmetric (i.e. neither ``a`` nor
|
|
|
|
``b`` is a "reference value"). You have to specify an absolute tolerance
|
|
|
|
if you want to compare to ``0.0`` because there is no tolerance by
|
|
|
|
default. Only available in python>=3.5. `More information...`__
|
|
|
|
|
|
|
|
__ https://docs.python.org/3/library/math.html#math.isclose
|
|
|
|
|
|
|
|
- ``numpy.isclose(a, b, rtol=1e-5, atol=1e-8)``: True if the difference
|
|
|
|
between ``a`` and ``b`` is less that the sum of the relative tolerance
|
|
|
|
w.r.t. ``b`` and the absolute tolerance. Because the relative tolerance
|
|
|
|
is only calculated w.r.t. ``b``, this test is asymmetric and you can
|
|
|
|
think of ``b`` as the reference value. Support for comparing sequences
|
|
|
|
is provided by ``numpy.allclose``. `More information...`__
|
|
|
|
|
|
|
|
__ http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.isclose.html
|
|
|
|
|
|
|
|
- ``unittest.TestCase.assertAlmostEqual(a, b)``: True if ``a`` and ``b``
|
|
|
|
are within an absolute tolerance of ``1e-7``. No relative tolerance is
|
|
|
|
considered and the absolute tolerance cannot be changed, so this function
|
|
|
|
is not appropriate for very large or very small numbers. Also, it's only
|
|
|
|
available in subclasses of ``unittest.TestCase`` and it's ugly because it
|
|
|
|
doesn't follow PEP8. `More information...`__
|
|
|
|
|
|
|
|
__ https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertAlmostEqual
|
|
|
|
|
|
|
|
- ``a == pytest.approx(b, rel=1e-6, abs=1e-12)``: True if the relative
|
2016-03-15 02:38:00 +08:00
|
|
|
tolerance is met w.r.t. ``b`` or if the absolute tolerance is met.
|
2016-03-12 07:59:48 +08:00
|
|
|
Because the relative tolerance is only calculated w.r.t. ``b``, this test
|
|
|
|
is asymmetric and you can think of ``b`` as the reference value. In the
|
|
|
|
special case that you explicitly specify an absolute tolerance but not a
|
|
|
|
relative tolerance, only the absolute tolerance is considered.
|
2016-03-07 10:53:48 +08:00
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, expected, rel=None, abs=None):
|
|
|
|
self.expected = expected
|
2016-03-12 00:49:26 +08:00
|
|
|
self.abs = abs
|
|
|
|
self.rel = rel
|
2016-03-07 10:53:48 +08:00
|
|
|
|
|
|
|
def __repr__(self):
|
2016-03-12 00:49:26 +08:00
|
|
|
return ', '.join(repr(x) for x in self.expected)
|
|
|
|
|
|
|
|
def __eq__(self, actual):
|
2016-03-07 10:53:48 +08:00
|
|
|
from collections import Iterable
|
2016-03-15 02:29:45 +08:00
|
|
|
if not isinstance(actual, Iterable):
|
|
|
|
actual = [actual]
|
|
|
|
if len(actual) != len(self.expected):
|
|
|
|
return False
|
2016-03-12 00:49:26 +08:00
|
|
|
return all(a == x for a, x in zip(actual, self.expected))
|
2016-03-07 10:53:48 +08:00
|
|
|
|
2016-03-12 08:29:18 +08:00
|
|
|
def __ne__(self, actual):
|
|
|
|
return not (actual == self)
|
|
|
|
|
2016-03-12 00:49:26 +08:00
|
|
|
@property
|
|
|
|
def expected(self):
|
2016-03-12 07:59:48 +08:00
|
|
|
# Regardless of whether the user-specified expected value is a number
|
|
|
|
# or a sequence of numbers, return a list of ApproxNotIterable objects
|
|
|
|
# that can be compared against.
|
2016-03-12 00:49:26 +08:00
|
|
|
from collections import Iterable
|
|
|
|
approx_non_iter = lambda x: ApproxNonIterable(x, self.rel, self.abs)
|
|
|
|
if isinstance(self._expected, Iterable):
|
|
|
|
return [approx_non_iter(x) for x in self._expected]
|
2016-03-07 10:53:48 +08:00
|
|
|
else:
|
2016-03-12 00:49:26 +08:00
|
|
|
return [approx_non_iter(self._expected)]
|
2016-03-07 10:53:48 +08:00
|
|
|
|
2016-03-12 00:49:26 +08:00
|
|
|
@expected.setter
|
|
|
|
def expected(self, expected):
|
|
|
|
self._expected = expected
|
|
|
|
|
|
|
|
|
|
|
|
class ApproxNonIterable(object):
|
|
|
|
"""
|
|
|
|
Perform approximate comparisons for single numbers only.
|
|
|
|
|
2016-03-12 07:59:48 +08:00
|
|
|
In other words, the ``expected`` attribute for objects of this class must
|
|
|
|
be some sort of number. This is in contrast to the ``approx`` class, where
|
|
|
|
the ``expected`` attribute can either be a number of a sequence of numbers.
|
|
|
|
This class is responsible for making comparisons, while ``approx`` is
|
|
|
|
responsible for abstracting the difference between numbers and sequences of
|
|
|
|
numbers. Although this class can stand on its own, it's only meant to be
|
|
|
|
used within ``approx``.
|
2016-03-12 00:49:26 +08:00
|
|
|
"""
|
2016-03-07 10:53:48 +08:00
|
|
|
|
2016-03-12 00:49:26 +08:00
|
|
|
def __init__(self, expected, rel=None, abs=None):
|
|
|
|
self.expected = expected
|
|
|
|
self.abs = abs
|
|
|
|
self.rel = rel
|
|
|
|
|
|
|
|
def __repr__(self):
|
2016-03-12 07:59:48 +08:00
|
|
|
# Infinities aren't compared using tolerances, so don't show a
|
2016-03-12 00:49:26 +08:00
|
|
|
# tolerance.
|
|
|
|
if math.isinf(self.expected):
|
|
|
|
return str(self.expected)
|
|
|
|
|
2016-03-12 07:59:48 +08:00
|
|
|
# If a sensible tolerance can't be calculated, self.tolerance will
|
2016-03-12 00:49:26 +08:00
|
|
|
# raise a ValueError. In this case, display '???'.
|
|
|
|
try:
|
|
|
|
vetted_tolerance = '{:.1e}'.format(self.tolerance)
|
|
|
|
except ValueError:
|
|
|
|
vetted_tolerance = '???'
|
|
|
|
|
2016-03-15 02:29:45 +08:00
|
|
|
plus_minus = u'{0} \u00b1 {1}'.format(self.expected, vetted_tolerance)
|
2016-03-12 00:49:26 +08:00
|
|
|
|
2016-03-12 07:59:48 +08:00
|
|
|
# In python2, __repr__() must return a string (i.e. not a unicode
|
|
|
|
# object). In python3, __repr__() must return a unicode object
|
|
|
|
# (although now strings are unicode objects and bytes are what
|
2016-03-12 00:49:26 +08:00
|
|
|
# strings were).
|
|
|
|
if sys.version_info[0] == 2:
|
2016-03-15 02:29:45 +08:00
|
|
|
return plus_minus.encode('utf-8')
|
2016-03-07 10:53:48 +08:00
|
|
|
else:
|
2016-03-15 02:29:45 +08:00
|
|
|
return plus_minus
|
2016-03-07 10:53:48 +08:00
|
|
|
|
2016-03-12 00:49:26 +08:00
|
|
|
def __eq__(self, actual):
|
|
|
|
# Short-circuit exact equality.
|
|
|
|
if actual == self.expected:
|
|
|
|
return True
|
|
|
|
|
2016-03-12 07:59:48 +08:00
|
|
|
# Infinity shouldn't be approximately equal to anything but itself, but
|
|
|
|
# if there's a relative tolerance, it will be infinite and infinity
|
|
|
|
# will seem approximately equal to everything. The equal-to-itself
|
|
|
|
# case would have been short circuited above, so here we can just
|
|
|
|
# return false if the expected value is infinite. The abs() call is
|
2016-03-12 00:49:26 +08:00
|
|
|
# for compatibility with complex numbers.
|
|
|
|
if math.isinf(abs(self.expected)):
|
|
|
|
return False
|
2016-03-07 10:53:48 +08:00
|
|
|
|
2016-03-12 00:49:26 +08:00
|
|
|
# Return true if the two numbers are within the tolerance.
|
|
|
|
return abs(self.expected - actual) <= self.tolerance
|
|
|
|
|
2016-03-12 08:29:18 +08:00
|
|
|
def __ne__(self, actual):
|
|
|
|
return not (actual == self)
|
|
|
|
|
2016-03-12 00:49:26 +08:00
|
|
|
@property
|
|
|
|
def tolerance(self):
|
|
|
|
set_default = lambda x, default: x if x is not None else default
|
|
|
|
|
2016-03-12 07:59:48 +08:00
|
|
|
# Figure out what the absolute tolerance should be. ``self.abs`` is
|
2016-03-12 00:49:26 +08:00
|
|
|
# either None or a value specified by the user.
|
|
|
|
absolute_tolerance = set_default(self.abs, 1e-12)
|
|
|
|
|
|
|
|
if absolute_tolerance < 0:
|
|
|
|
raise ValueError("absolute tolerance can't be negative: {}".format(absolute_tolerance))
|
|
|
|
if math.isnan(absolute_tolerance):
|
|
|
|
raise ValueError("absolute tolerance can't be NaN.")
|
2016-03-12 07:59:48 +08:00
|
|
|
|
|
|
|
# If the user specified an absolute tolerance but not a relative one,
|
2016-03-12 00:49:26 +08:00
|
|
|
# just return the absolute tolerance.
|
|
|
|
if self.rel is None:
|
|
|
|
if self.abs is not None:
|
|
|
|
return absolute_tolerance
|
|
|
|
|
2016-03-15 02:29:45 +08:00
|
|
|
# Figure out what the relative tolerance should be. ``self.rel`` is
|
2016-03-12 07:59:48 +08:00
|
|
|
# either None or a value specified by the user. This is done after
|
|
|
|
# we've made sure the user didn't ask for an absolute tolerance only,
|
|
|
|
# because we don't want to raise errors about the relative tolerance if
|
2016-03-15 02:29:45 +08:00
|
|
|
# we aren't even going to use it.
|
2016-03-12 00:49:26 +08:00
|
|
|
relative_tolerance = set_default(self.rel, 1e-6) * abs(self.expected)
|
|
|
|
|
|
|
|
if relative_tolerance < 0:
|
|
|
|
raise ValueError("relative tolerance can't be negative: {}".format(absolute_tolerance))
|
|
|
|
if math.isnan(relative_tolerance):
|
|
|
|
raise ValueError("relative tolerance can't be NaN.")
|
2016-03-12 07:59:48 +08:00
|
|
|
|
2016-03-12 00:49:26 +08:00
|
|
|
# Return the larger of the relative and absolute tolerances.
|
|
|
|
return max(relative_tolerance, absolute_tolerance)
|
2016-03-07 10:53:48 +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
|
|
|
|
2016-07-10 02:36:00 +08:00
|
|
|
class Function(FunctionMixin, pytest.Item, fixtures.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
|
2016-07-10 02:36:00 +08:00
|
|
|
self._request = fixtures.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):
|
|
|
|
super(Function, self).setup()
|
2016-07-10 02:36:00 +08:00
|
|
|
fixtures.fillfixtures(self)
|
2012-08-01 15:23:39 +08:00
|
|
|
|