2010-11-22 00:43:18 +08:00
|
|
|
""" command line options, ini-file and conftest.py processing. """
|
2014-08-01 06:13:40 +08:00
|
|
|
import argparse
|
|
|
|
import shlex
|
|
|
|
import traceback
|
|
|
|
import types
|
|
|
|
import warnings
|
2010-10-12 21:34:32 +08:00
|
|
|
|
2016-06-22 18:42:11 +08:00
|
|
|
import pkg_resources
|
2010-10-12 21:34:32 +08:00
|
|
|
import py
|
2014-01-22 18:17:25 +08:00
|
|
|
# DON't import pytest here because it causes import cycle troubles
|
2010-10-14 00:45:07 +08:00
|
|
|
import sys, os
|
2015-11-27 22:43:01 +08:00
|
|
|
import _pytest._code
|
2015-05-06 16:08:08 +08:00
|
|
|
import _pytest.hookspec # the extension point definitions
|
2016-06-26 00:26:45 +08:00
|
|
|
import _pytest.assertion
|
2015-08-26 06:43:09 +08:00
|
|
|
from _pytest._pluggy import PluginManager, HookimplMarker, HookspecMarker
|
2015-04-29 22:40:52 +08:00
|
|
|
|
2015-05-06 16:08:08 +08:00
|
|
|
hookimpl = HookimplMarker("pytest")
|
|
|
|
hookspec = HookspecMarker("pytest")
|
2013-09-30 19:14:14 +08:00
|
|
|
|
|
|
|
# pytest startup
|
2014-04-03 02:42:41 +08:00
|
|
|
#
|
2015-09-03 00:49:49 +08:00
|
|
|
|
|
|
|
|
2014-04-03 02:42:41 +08:00
|
|
|
class ConftestImportFailure(Exception):
|
|
|
|
def __init__(self, path, excinfo):
|
|
|
|
Exception.__init__(self, path, excinfo)
|
|
|
|
self.path = path
|
|
|
|
self.excinfo = excinfo
|
|
|
|
|
2016-07-05 16:56:54 +08:00
|
|
|
def __str__(self):
|
|
|
|
etype, evalue, etb = self.excinfo
|
|
|
|
formatted = traceback.format_tb(etb)
|
|
|
|
# The level of the tracebacks we want to print is hand crafted :(
|
|
|
|
return repr(evalue) + '\n' + ''.join(formatted[2:])
|
|
|
|
|
2013-09-30 19:14:14 +08:00
|
|
|
|
|
|
|
def main(args=None, plugins=None):
|
|
|
|
""" return exit code, after performing an in-process test run.
|
|
|
|
|
|
|
|
:arg args: list of command line arguments.
|
|
|
|
|
|
|
|
:arg plugins: list of plugin objects to be auto-registered during
|
|
|
|
initialization.
|
|
|
|
"""
|
2014-04-03 02:42:41 +08:00
|
|
|
try:
|
2015-04-28 17:54:45 +08:00
|
|
|
try:
|
|
|
|
config = _prepareconfig(args, plugins)
|
|
|
|
except ConftestImportFailure as e:
|
|
|
|
tw = py.io.TerminalWriter(sys.stderr)
|
|
|
|
for line in traceback.format_exception(*e.excinfo):
|
|
|
|
tw.line(line.rstrip(), red=True)
|
|
|
|
tw.line("ERROR: could not load %s\n" % (e.path), red=True)
|
|
|
|
return 4
|
|
|
|
else:
|
2015-04-28 17:54:46 +08:00
|
|
|
try:
|
|
|
|
config.pluginmanager.check_pending()
|
|
|
|
return config.hook.pytest_cmdline_main(config=config)
|
|
|
|
finally:
|
|
|
|
config._ensure_unconfigure()
|
2015-04-28 17:54:45 +08:00
|
|
|
except UsageError as e:
|
|
|
|
for msg in e.args:
|
|
|
|
sys.stderr.write("ERROR: %s\n" %(msg,))
|
2014-04-03 02:42:41 +08:00
|
|
|
return 4
|
2013-09-30 19:14:14 +08:00
|
|
|
|
|
|
|
class cmdline: # compatibility namespace
|
|
|
|
main = staticmethod(main)
|
|
|
|
|
|
|
|
class UsageError(Exception):
|
2014-01-18 19:31:33 +08:00
|
|
|
""" error in pytest usage or invocation"""
|
2013-09-30 19:14:14 +08:00
|
|
|
|
|
|
|
_preinit = []
|
|
|
|
|
|
|
|
default_plugins = (
|
2016-07-10 02:36:00 +08:00
|
|
|
"mark main terminal runner python fixtures debugging unittest capture skipping "
|
2016-06-25 17:27:10 +08:00
|
|
|
"tmpdir monkeypatch recwarn pastebin helpconfig nose assertion "
|
2016-06-25 20:11:39 +08:00
|
|
|
"junitxml resultlog doctest cacheprovider freeze_support "
|
|
|
|
"setuponly setupplan").split()
|
2013-09-30 19:14:14 +08:00
|
|
|
|
2015-04-23 18:39:11 +08:00
|
|
|
builtin_plugins = set(default_plugins)
|
|
|
|
builtin_plugins.add("pytester")
|
|
|
|
|
|
|
|
|
2013-09-30 19:14:14 +08:00
|
|
|
def _preloadplugins():
|
|
|
|
assert not _preinit
|
2015-04-26 00:14:41 +08:00
|
|
|
_preinit.append(get_config())
|
2013-09-30 19:14:14 +08:00
|
|
|
|
2015-04-26 00:14:41 +08:00
|
|
|
def get_config():
|
2013-09-30 19:14:14 +08:00
|
|
|
if _preinit:
|
|
|
|
return _preinit.pop(0)
|
|
|
|
# subsequent calls to main will create a fresh instance
|
|
|
|
pluginmanager = PytestPluginManager()
|
2015-04-26 00:14:41 +08:00
|
|
|
config = Config(pluginmanager)
|
2013-09-30 19:14:14 +08:00
|
|
|
for spec in default_plugins:
|
|
|
|
pluginmanager.import_plugin(spec)
|
2015-04-26 00:14:41 +08:00
|
|
|
return config
|
2013-09-30 19:14:14 +08:00
|
|
|
|
2015-06-18 05:57:45 +08:00
|
|
|
def get_plugin_manager():
|
|
|
|
"""
|
|
|
|
Obtain a new instance of the
|
|
|
|
:py:class:`_pytest.config.PytestPluginManager`, with default plugins
|
|
|
|
already loaded.
|
|
|
|
|
|
|
|
This function can be used by integration with other tools, like hooking
|
|
|
|
into pytest to run tests into an IDE.
|
|
|
|
"""
|
|
|
|
return get_config().pluginmanager
|
|
|
|
|
2013-09-30 19:14:14 +08:00
|
|
|
def _prepareconfig(args=None, plugins=None):
|
2016-07-14 06:35:05 +08:00
|
|
|
warning = None
|
2013-09-30 19:14:14 +08:00
|
|
|
if args is None:
|
|
|
|
args = sys.argv[1:]
|
|
|
|
elif isinstance(args, py.path.local):
|
|
|
|
args = [str(args)]
|
|
|
|
elif not isinstance(args, (tuple, list)):
|
|
|
|
if not isinstance(args, str):
|
|
|
|
raise ValueError("not a string or argument list: %r" % (args,))
|
2016-05-24 07:41:47 +08:00
|
|
|
args = shlex.split(args, posix=sys.platform != "win32")
|
2016-07-14 06:35:05 +08:00
|
|
|
# we want to remove this way of passing arguments to pytest.main()
|
|
|
|
# in pytest-4.0
|
|
|
|
warning = ('passing a string to pytest.main() is deprecated, '
|
|
|
|
'pass a list of arguments instead.')
|
2015-04-28 17:54:46 +08:00
|
|
|
config = get_config()
|
|
|
|
pluginmanager = config.pluginmanager
|
|
|
|
try:
|
|
|
|
if plugins:
|
|
|
|
for plugin in plugins:
|
2015-07-19 01:40:00 +08:00
|
|
|
if isinstance(plugin, py.builtin._basestring):
|
|
|
|
pluginmanager.consider_pluginarg(plugin)
|
|
|
|
else:
|
|
|
|
pluginmanager.register(plugin)
|
2016-07-14 06:35:05 +08:00
|
|
|
if warning:
|
|
|
|
config.warn('C1', warning)
|
2015-04-28 17:54:46 +08:00
|
|
|
return pluginmanager.hook.pytest_cmdline_parse(
|
|
|
|
pluginmanager=pluginmanager, args=args)
|
|
|
|
except BaseException:
|
|
|
|
config._ensure_unconfigure()
|
|
|
|
raise
|
|
|
|
|
2013-09-30 19:14:14 +08:00
|
|
|
|
|
|
|
class PytestPluginManager(PluginManager):
|
2015-06-18 05:57:45 +08:00
|
|
|
"""
|
|
|
|
Overwrites :py:class:`pluggy.PluginManager` to add pytest-specific
|
|
|
|
functionality:
|
|
|
|
|
|
|
|
* loading plugins from the command line, ``PYTEST_PLUGIN`` env variable and
|
|
|
|
``pytest_plugins`` global variables found in plugins being loaded;
|
|
|
|
* ``conftest.py`` loading during start-up;
|
|
|
|
"""
|
2015-04-22 19:31:46 +08:00
|
|
|
def __init__(self):
|
2015-05-06 03:53:04 +08:00
|
|
|
super(PytestPluginManager, self).__init__("pytest", implprefix="pytest_")
|
2015-04-26 06:10:52 +08:00
|
|
|
self._conftest_plugins = set()
|
2015-04-22 20:15:42 +08:00
|
|
|
|
|
|
|
# state related to local conftest plugins
|
|
|
|
self._path2confmods = {}
|
|
|
|
self._conftestpath2mod = {}
|
|
|
|
self._confcutdir = None
|
2015-06-23 13:53:32 +08:00
|
|
|
self._noconftest = False
|
2015-04-22 20:15:42 +08:00
|
|
|
|
2015-05-06 16:08:08 +08:00
|
|
|
self.add_hookspecs(_pytest.hookspec)
|
2013-09-30 19:14:14 +08:00
|
|
|
self.register(self)
|
|
|
|
if os.environ.get('PYTEST_DEBUG'):
|
|
|
|
err = sys.stderr
|
|
|
|
encoding = getattr(err, 'encoding', 'utf8')
|
|
|
|
try:
|
|
|
|
err = py.io.dupfile(err, encoding=encoding)
|
|
|
|
except Exception:
|
|
|
|
pass
|
2015-04-26 00:15:39 +08:00
|
|
|
self.trace.root.setwriter(err.write)
|
|
|
|
self.enable_tracing()
|
2013-09-30 19:14:14 +08:00
|
|
|
|
2016-06-26 00:26:45 +08:00
|
|
|
# Config._consider_importhook will set a real object if required.
|
|
|
|
self.rewrite_hook = _pytest.assertion.DummyRewriteHook()
|
|
|
|
|
2015-05-06 03:53:04 +08:00
|
|
|
def addhooks(self, module_or_class):
|
2015-06-18 05:57:45 +08:00
|
|
|
"""
|
|
|
|
.. deprecated:: 2.8
|
|
|
|
|
|
|
|
Use :py:meth:`pluggy.PluginManager.add_hookspecs` instead.
|
|
|
|
"""
|
2015-05-06 03:53:04 +08:00
|
|
|
warning = dict(code="I2",
|
2015-11-27 22:43:01 +08:00
|
|
|
fslocation=_pytest._code.getfslineno(sys._getframe(1)),
|
2015-09-29 00:05:58 +08:00
|
|
|
nodeid=None,
|
2015-05-06 03:53:04 +08:00
|
|
|
message="use pluginmanager.add_hookspecs instead of "
|
|
|
|
"deprecated addhooks() method.")
|
2015-09-01 03:54:12 +08:00
|
|
|
self._warn(warning)
|
2015-05-06 03:53:04 +08:00
|
|
|
return self.add_hookspecs(module_or_class)
|
|
|
|
|
|
|
|
def parse_hookimpl_opts(self, plugin, name):
|
2015-09-28 19:34:28 +08:00
|
|
|
# pytest hooks are always prefixed with pytest_
|
|
|
|
# so we avoid accessing possibly non-readable attributes
|
|
|
|
# (see issue #1073)
|
|
|
|
if not name.startswith("pytest_"):
|
|
|
|
return
|
2015-09-28 21:43:55 +08:00
|
|
|
# ignore some historic special names which can not be hooks anyway
|
|
|
|
if name == "pytest_plugins" or name.startswith("pytest_funcarg__"):
|
|
|
|
return
|
2015-09-28 19:34:28 +08:00
|
|
|
|
2015-05-06 03:53:04 +08:00
|
|
|
method = getattr(plugin, name)
|
|
|
|
opts = super(PytestPluginManager, self).parse_hookimpl_opts(plugin, name)
|
|
|
|
if opts is not None:
|
|
|
|
for name in ("tryfirst", "trylast", "optionalhook", "hookwrapper"):
|
|
|
|
opts.setdefault(name, hasattr(method, name))
|
2015-04-29 22:40:52 +08:00
|
|
|
return opts
|
|
|
|
|
2015-05-04 21:08:41 +08:00
|
|
|
def parse_hookspec_opts(self, module_or_class, name):
|
2015-05-06 03:53:04 +08:00
|
|
|
opts = super(PytestPluginManager, self).parse_hookspec_opts(
|
|
|
|
module_or_class, name)
|
2015-04-29 22:40:52 +08:00
|
|
|
if opts is None:
|
2015-05-06 03:53:04 +08:00
|
|
|
method = getattr(module_or_class, name)
|
2015-04-29 22:40:52 +08:00
|
|
|
if name.startswith("pytest_"):
|
2015-05-06 03:53:04 +08:00
|
|
|
opts = {"firstresult": hasattr(method, "firstresult"),
|
|
|
|
"historic": hasattr(method, "historic")}
|
2015-04-29 22:40:52 +08:00
|
|
|
return opts
|
|
|
|
|
|
|
|
def _verify_hook(self, hook, hookmethod):
|
|
|
|
super(PytestPluginManager, self)._verify_hook(hook, hookmethod)
|
|
|
|
if "__multicall__" in hookmethod.argnames:
|
2015-11-27 22:43:01 +08:00
|
|
|
fslineno = _pytest._code.getfslineno(hookmethod.function)
|
2015-04-27 18:50:34 +08:00
|
|
|
warning = dict(code="I1",
|
|
|
|
fslocation=fslineno,
|
2015-09-01 03:54:12 +08:00
|
|
|
nodeid=None,
|
2015-04-27 18:50:34 +08:00
|
|
|
message="%r hook uses deprecated __multicall__ "
|
|
|
|
"argument" % (hook.name))
|
2015-09-01 03:54:12 +08:00
|
|
|
self._warn(warning)
|
2015-04-27 18:50:34 +08:00
|
|
|
|
2015-04-26 06:22:34 +08:00
|
|
|
def register(self, plugin, name=None):
|
2015-04-22 19:33:01 +08:00
|
|
|
ret = super(PytestPluginManager, self).register(plugin, name)
|
2015-04-25 17:29:11 +08:00
|
|
|
if ret:
|
2015-04-25 19:38:30 +08:00
|
|
|
self.hook.pytest_plugin_registered.call_historic(
|
|
|
|
kwargs=dict(plugin=plugin, manager=self))
|
2015-04-22 19:33:01 +08:00
|
|
|
return ret
|
|
|
|
|
2015-04-26 02:17:32 +08:00
|
|
|
def getplugin(self, name):
|
2015-04-26 06:41:29 +08:00
|
|
|
# support deprecated naming because plugins (xdist e.g.) use it
|
2015-04-26 02:17:32 +08:00
|
|
|
return self.get_plugin(name)
|
|
|
|
|
2015-08-10 06:30:49 +08:00
|
|
|
def hasplugin(self, name):
|
|
|
|
"""Return True if the plugin with the given name is registered."""
|
|
|
|
return bool(self.get_plugin(name))
|
|
|
|
|
2013-09-30 19:14:14 +08:00
|
|
|
def pytest_configure(self, config):
|
2015-05-06 16:08:08 +08:00
|
|
|
# XXX now that the pluginmanager exposes hookimpl(tryfirst...)
|
2015-04-26 06:47:24 +08:00
|
|
|
# we should remove tryfirst/trylast as markers
|
|
|
|
config.addinivalue_line("markers",
|
|
|
|
"tryfirst: mark a hook implementation function such that the "
|
|
|
|
"plugin machinery will try to call it first/as early as possible.")
|
|
|
|
config.addinivalue_line("markers",
|
|
|
|
"trylast: mark a hook implementation function such that the "
|
|
|
|
"plugin machinery will try to call it last/as late as possible.")
|
2015-09-01 03:54:12 +08:00
|
|
|
|
|
|
|
def _warn(self, message):
|
2015-09-03 00:49:49 +08:00
|
|
|
kwargs = message if isinstance(message, dict) else {
|
|
|
|
'code': 'I1',
|
|
|
|
'message': message,
|
|
|
|
'fslocation': None,
|
|
|
|
'nodeid': None,
|
|
|
|
}
|
|
|
|
self.hook.pytest_logwarning.call_historic(kwargs=kwargs)
|
2013-09-30 19:14:14 +08:00
|
|
|
|
2015-04-22 20:15:42 +08:00
|
|
|
#
|
|
|
|
# internal API for local conftest plugin handling
|
|
|
|
#
|
|
|
|
def _set_initial_conftests(self, namespace):
|
|
|
|
""" load initial conftest files given a preparsed "namespace".
|
|
|
|
As conftest files may add their own command line options
|
|
|
|
which have arguments ('--my-opt somepath') we might get some
|
|
|
|
false positives. All builtin and 3rd party plugins will have
|
|
|
|
been loaded, however, so common options will not confuse our logic
|
|
|
|
here.
|
|
|
|
"""
|
|
|
|
current = py.path.local()
|
|
|
|
self._confcutdir = current.join(namespace.confcutdir, abs=True) \
|
|
|
|
if namespace.confcutdir else None
|
2015-06-23 13:53:32 +08:00
|
|
|
self._noconftest = namespace.noconftest
|
2015-04-22 20:15:42 +08:00
|
|
|
testpaths = namespace.file_or_dir
|
|
|
|
foundanchor = False
|
|
|
|
for path in testpaths:
|
|
|
|
path = str(path)
|
|
|
|
# remove node-id syntax
|
|
|
|
i = path.find("::")
|
|
|
|
if i != -1:
|
|
|
|
path = path[:i]
|
|
|
|
anchor = current.join(path, abs=1)
|
|
|
|
if exists(anchor): # we found some file object
|
|
|
|
self._try_load_conftest(anchor)
|
|
|
|
foundanchor = True
|
|
|
|
if not foundanchor:
|
|
|
|
self._try_load_conftest(current)
|
|
|
|
|
|
|
|
def _try_load_conftest(self, anchor):
|
|
|
|
self._getconftestmodules(anchor)
|
|
|
|
# let's also consider test* subdirs
|
|
|
|
if anchor.check(dir=1):
|
|
|
|
for x in anchor.listdir("test*"):
|
|
|
|
if x.check(dir=1):
|
|
|
|
self._getconftestmodules(x)
|
|
|
|
|
|
|
|
def _getconftestmodules(self, path):
|
2015-06-23 13:53:32 +08:00
|
|
|
if self._noconftest:
|
2015-06-23 20:05:44 +08:00
|
|
|
return []
|
2015-04-22 20:15:42 +08:00
|
|
|
try:
|
|
|
|
return self._path2confmods[path]
|
|
|
|
except KeyError:
|
2015-04-26 06:10:52 +08:00
|
|
|
if path.isfile():
|
|
|
|
clist = self._getconftestmodules(path.dirpath())
|
|
|
|
else:
|
|
|
|
# XXX these days we may rather want to use config.rootdir
|
|
|
|
# and allow users to opt into looking into the rootdir parent
|
|
|
|
# directories instead of requiring to specify confcutdir
|
|
|
|
clist = []
|
|
|
|
for parent in path.parts():
|
|
|
|
if self._confcutdir and self._confcutdir.relto(parent):
|
|
|
|
continue
|
|
|
|
conftestpath = parent.join("conftest.py")
|
|
|
|
if conftestpath.isfile():
|
|
|
|
mod = self._importconftest(conftestpath)
|
|
|
|
clist.append(mod)
|
2015-04-26 04:13:42 +08:00
|
|
|
|
2015-04-22 20:15:42 +08:00
|
|
|
self._path2confmods[path] = clist
|
|
|
|
return clist
|
|
|
|
|
|
|
|
def _rget_with_confmod(self, name, path):
|
|
|
|
modules = self._getconftestmodules(path)
|
|
|
|
for mod in reversed(modules):
|
|
|
|
try:
|
|
|
|
return mod, getattr(mod, name)
|
|
|
|
except AttributeError:
|
|
|
|
continue
|
|
|
|
raise KeyError(name)
|
|
|
|
|
|
|
|
def _importconftest(self, conftestpath):
|
|
|
|
try:
|
|
|
|
return self._conftestpath2mod[conftestpath]
|
|
|
|
except KeyError:
|
|
|
|
pkgpath = conftestpath.pypkgpath()
|
|
|
|
if pkgpath is None:
|
|
|
|
_ensure_removed_sysmodule(conftestpath.purebasename)
|
|
|
|
try:
|
|
|
|
mod = conftestpath.pyimport()
|
|
|
|
except Exception:
|
|
|
|
raise ConftestImportFailure(conftestpath, sys.exc_info())
|
2015-04-26 04:13:42 +08:00
|
|
|
|
2015-04-26 06:10:52 +08:00
|
|
|
self._conftest_plugins.add(mod)
|
2015-04-22 20:15:42 +08:00
|
|
|
self._conftestpath2mod[conftestpath] = mod
|
|
|
|
dirpath = conftestpath.dirpath()
|
|
|
|
if dirpath in self._path2confmods:
|
|
|
|
for path, mods in self._path2confmods.items():
|
|
|
|
if path and path.relto(dirpath) or path == dirpath:
|
|
|
|
assert mod not in mods
|
|
|
|
mods.append(mod)
|
|
|
|
self.trace("loaded conftestmodule %r" %(mod))
|
|
|
|
self.consider_conftest(mod)
|
|
|
|
return mod
|
|
|
|
|
2015-04-22 19:31:46 +08:00
|
|
|
#
|
|
|
|
# API for bootstrapping plugin loading
|
|
|
|
#
|
|
|
|
#
|
|
|
|
|
|
|
|
def consider_preparse(self, args):
|
|
|
|
for opt1,opt2 in zip(args, args[1:]):
|
|
|
|
if opt1 == "-p":
|
|
|
|
self.consider_pluginarg(opt2)
|
|
|
|
|
|
|
|
def consider_pluginarg(self, arg):
|
|
|
|
if arg.startswith("no:"):
|
2015-04-28 17:54:46 +08:00
|
|
|
name = arg[3:]
|
|
|
|
self.set_blocked(name)
|
|
|
|
if not name.startswith("pytest_"):
|
|
|
|
self.set_blocked("pytest_" + name)
|
2015-04-22 19:31:46 +08:00
|
|
|
else:
|
2015-04-26 02:17:32 +08:00
|
|
|
self.import_plugin(arg)
|
2015-04-22 19:31:46 +08:00
|
|
|
|
|
|
|
def consider_conftest(self, conftestmodule):
|
2015-04-26 06:22:34 +08:00
|
|
|
if self.register(conftestmodule, name=conftestmodule.__file__):
|
2015-04-22 19:31:46 +08:00
|
|
|
self.consider_module(conftestmodule)
|
|
|
|
|
2015-04-23 19:15:34 +08:00
|
|
|
def consider_env(self):
|
|
|
|
self._import_plugin_specs(os.environ.get("PYTEST_PLUGINS"))
|
|
|
|
|
2015-04-22 19:31:46 +08:00
|
|
|
def consider_module(self, mod):
|
2016-06-26 00:26:45 +08:00
|
|
|
plugins = getattr(mod, 'pytest_plugins', [])
|
|
|
|
self.rewrite_hook.mark_rewrite(*plugins)
|
|
|
|
self._import_plugin_specs(plugins)
|
2015-04-23 19:15:34 +08:00
|
|
|
|
|
|
|
def _import_plugin_specs(self, spec):
|
|
|
|
if spec:
|
|
|
|
if isinstance(spec, str):
|
|
|
|
spec = spec.split(",")
|
|
|
|
for import_spec in spec:
|
|
|
|
self.import_plugin(import_spec)
|
2015-04-22 19:31:46 +08:00
|
|
|
|
|
|
|
def import_plugin(self, modname):
|
2015-04-23 18:39:11 +08:00
|
|
|
# most often modname refers to builtin modules, e.g. "pytester",
|
|
|
|
# "terminal" or "capture". Those plugins are registered under their
|
|
|
|
# basename for historic purposes but must be imported with the
|
|
|
|
# _pytest prefix.
|
2015-04-22 19:31:46 +08:00
|
|
|
assert isinstance(modname, str)
|
2015-04-26 02:17:32 +08:00
|
|
|
if self.get_plugin(modname) is not None:
|
2015-04-22 19:31:46 +08:00
|
|
|
return
|
2015-04-23 18:39:11 +08:00
|
|
|
if modname in builtin_plugins:
|
|
|
|
importspec = "_pytest." + modname
|
|
|
|
else:
|
|
|
|
importspec = modname
|
2015-04-22 19:31:46 +08:00
|
|
|
try:
|
2015-04-23 18:39:11 +08:00
|
|
|
__import__(importspec)
|
2016-03-09 06:18:13 +08:00
|
|
|
except ImportError as e:
|
2016-03-11 05:13:59 +08:00
|
|
|
new_exc = ImportError('Error importing plugin "%s": %s' % (modname, e))
|
|
|
|
# copy over name and path attributes
|
|
|
|
for attr in ('name', 'path'):
|
|
|
|
if hasattr(e, attr):
|
|
|
|
setattr(new_exc, attr, getattr(e, attr))
|
|
|
|
raise new_exc
|
2015-04-22 19:37:42 +08:00
|
|
|
except Exception as e:
|
2015-04-22 19:31:46 +08:00
|
|
|
import pytest
|
|
|
|
if not hasattr(pytest, 'skip') or not isinstance(e, pytest.skip.Exception):
|
|
|
|
raise
|
2015-09-01 03:54:12 +08:00
|
|
|
self._warn("skipped plugin %r: %s" %((modname, e.msg)))
|
2015-04-22 19:31:46 +08:00
|
|
|
else:
|
2015-04-23 18:39:11 +08:00
|
|
|
mod = sys.modules[importspec]
|
2015-04-22 19:31:46 +08:00
|
|
|
self.register(mod, modname)
|
|
|
|
self.consider_module(mod)
|
|
|
|
|
2011-04-17 18:20:13 +08:00
|
|
|
|
2010-10-12 21:34:32 +08:00
|
|
|
class Parser:
|
2015-07-09 08:22:08 +08:00
|
|
|
""" Parser for command line arguments and ini-file values.
|
|
|
|
|
|
|
|
:ivar extra_info: dict of generic param -> value to display in case
|
|
|
|
there's an error processing the command line arguments.
|
|
|
|
"""
|
2010-10-12 21:34:32 +08:00
|
|
|
|
|
|
|
def __init__(self, usage=None, processopt=None):
|
|
|
|
self._anonymous = OptionGroup("custom options", parser=self)
|
|
|
|
self._groups = []
|
|
|
|
self._processopt = processopt
|
|
|
|
self._usage = usage
|
2010-10-31 01:23:50 +08:00
|
|
|
self._inidict = {}
|
2010-11-07 23:10:22 +08:00
|
|
|
self._ininames = []
|
2015-07-09 08:22:08 +08:00
|
|
|
self.extra_info = {}
|
2010-10-12 21:34:32 +08:00
|
|
|
|
|
|
|
def processoption(self, option):
|
|
|
|
if self._processopt:
|
|
|
|
if option.dest:
|
|
|
|
self._processopt(option)
|
|
|
|
|
|
|
|
def getgroup(self, name, description="", after=None):
|
2010-10-31 01:23:50 +08:00
|
|
|
""" get (or create) a named option Group.
|
2011-01-18 19:51:21 +08:00
|
|
|
|
2012-10-25 17:07:07 +08:00
|
|
|
:name: name of the option group.
|
2010-10-31 01:23:50 +08:00
|
|
|
:description: long description for --help output.
|
|
|
|
:after: name of other group, used for ordering --help output.
|
2012-10-25 17:07:07 +08:00
|
|
|
|
|
|
|
The returned group object has an ``addoption`` method with the same
|
|
|
|
signature as :py:func:`parser.addoption
|
|
|
|
<_pytest.config.Parser.addoption>` but will be shown in the
|
|
|
|
respective group in the output of ``pytest. --help``.
|
2010-10-31 01:23:50 +08:00
|
|
|
"""
|
2010-10-12 21:34:32 +08:00
|
|
|
for group in self._groups:
|
|
|
|
if group.name == name:
|
|
|
|
return group
|
|
|
|
group = OptionGroup(name, description, parser=self)
|
|
|
|
i = 0
|
|
|
|
for i, grp in enumerate(self._groups):
|
|
|
|
if grp.name == after:
|
|
|
|
break
|
|
|
|
self._groups.insert(i+1, group)
|
|
|
|
return group
|
|
|
|
|
|
|
|
def addoption(self, *opts, **attrs):
|
2012-10-25 17:07:07 +08:00
|
|
|
""" register a command line option.
|
|
|
|
|
|
|
|
:opts: option names, can be short or long options.
|
|
|
|
:attrs: same attributes which the ``add_option()`` function of the
|
2013-12-17 01:07:05 +08:00
|
|
|
`argparse library
|
|
|
|
<http://docs.python.org/2/library/argparse.html>`_
|
2012-10-25 17:07:07 +08:00
|
|
|
accepts.
|
|
|
|
|
|
|
|
After command line parsing options are available on the pytest config
|
|
|
|
object via ``config.option.NAME`` where ``NAME`` is usually set
|
|
|
|
by passing a ``dest`` attribute, for example
|
|
|
|
``addoption("--long", dest="NAME", ...)``.
|
|
|
|
"""
|
2010-10-12 21:34:32 +08:00
|
|
|
self._anonymous.addoption(*opts, **attrs)
|
|
|
|
|
2015-09-25 08:52:53 +08:00
|
|
|
def parse(self, args, namespace=None):
|
2013-09-30 19:14:16 +08:00
|
|
|
from _pytest._argcomplete import try_argcomplete
|
|
|
|
self.optparser = self._getparser()
|
|
|
|
try_argcomplete(self.optparser)
|
2015-09-25 08:52:53 +08:00
|
|
|
return self.optparser.parse_args([str(x) for x in args], namespace=namespace)
|
2013-09-30 19:14:16 +08:00
|
|
|
|
|
|
|
def _getparser(self):
|
|
|
|
from _pytest._argcomplete import filescompleter
|
2015-07-09 08:22:08 +08:00
|
|
|
optparser = MyOptionParser(self, self.extra_info)
|
2010-11-07 23:10:22 +08:00
|
|
|
groups = self._groups + [self._anonymous]
|
2010-10-12 21:34:32 +08:00
|
|
|
for group in groups:
|
|
|
|
if group.options:
|
|
|
|
desc = group.description or group.name
|
2013-07-25 21:33:43 +08:00
|
|
|
arggroup = optparser.add_argument_group(desc)
|
|
|
|
for option in group.options:
|
|
|
|
n = option.names()
|
|
|
|
a = option.attrs()
|
|
|
|
arggroup.add_argument(*n, **a)
|
2013-07-30 17:26:15 +08:00
|
|
|
# bash like autocompletion for dirs (appending '/')
|
2014-08-01 07:29:35 +08:00
|
|
|
optparser.add_argument(FILE_OR_DIR, nargs='*').completer=filescompleter
|
2013-09-30 19:14:16 +08:00
|
|
|
return optparser
|
2010-10-12 21:34:32 +08:00
|
|
|
|
2015-09-25 08:52:53 +08:00
|
|
|
def parse_setoption(self, args, option, namespace=None):
|
|
|
|
parsedoption = self.parse(args, namespace=namespace)
|
2010-10-12 21:34:32 +08:00
|
|
|
for name, value in parsedoption.__dict__.items():
|
|
|
|
setattr(option, name, value)
|
2013-09-28 15:52:41 +08:00
|
|
|
return getattr(parsedoption, FILE_OR_DIR)
|
2010-10-12 21:34:32 +08:00
|
|
|
|
2015-09-25 08:52:53 +08:00
|
|
|
def parse_known_args(self, args, namespace=None):
|
2015-08-28 06:35:32 +08:00
|
|
|
"""parses and returns a namespace object with known arguments at this
|
|
|
|
point.
|
|
|
|
"""
|
2015-09-25 08:52:53 +08:00
|
|
|
return self.parse_known_and_unknown_args(args, namespace=namespace)[0]
|
2015-08-28 06:35:32 +08:00
|
|
|
|
2015-09-25 08:52:53 +08:00
|
|
|
def parse_known_and_unknown_args(self, args, namespace=None):
|
2015-08-28 06:35:32 +08:00
|
|
|
"""parses and returns a namespace object with known arguments, and
|
|
|
|
the remaining arguments unknown at this point.
|
|
|
|
"""
|
2013-09-30 19:14:16 +08:00
|
|
|
optparser = self._getparser()
|
|
|
|
args = [str(x) for x in args]
|
2015-09-25 08:52:53 +08:00
|
|
|
return optparser.parse_known_args(args, namespace=namespace)
|
2013-09-30 19:14:16 +08:00
|
|
|
|
2010-11-05 06:21:26 +08:00
|
|
|
def addini(self, name, help, type=None, default=None):
|
2012-10-25 17:07:07 +08:00
|
|
|
""" register an ini-file option.
|
|
|
|
|
|
|
|
:name: name of the ini-variable
|
2016-02-15 05:27:48 +08:00
|
|
|
:type: type of the variable, can be ``pathlist``, ``args``, ``linelist``
|
|
|
|
or ``bool``.
|
2012-10-25 17:07:07 +08:00
|
|
|
:default: default value if no ini-file option exists but is queried.
|
|
|
|
|
|
|
|
The value of ini-variables can be retrieved via a call to
|
|
|
|
:py:func:`config.getini(name) <_pytest.config.Config.getini>`.
|
|
|
|
"""
|
2016-02-15 05:27:48 +08:00
|
|
|
assert type in (None, "pathlist", "args", "linelist", "bool")
|
2010-11-05 06:21:26 +08:00
|
|
|
self._inidict[name] = (help, type, default)
|
2010-11-07 23:10:22 +08:00
|
|
|
self._ininames.append(name)
|
2010-10-12 21:34:32 +08:00
|
|
|
|
2013-07-25 21:33:43 +08:00
|
|
|
|
|
|
|
class ArgumentError(Exception):
|
|
|
|
"""
|
|
|
|
Raised if an Argument instance is created with invalid or
|
|
|
|
inconsistent arguments.
|
|
|
|
"""
|
2011-11-12 06:56:08 +08:00
|
|
|
|
2013-07-25 21:33:43 +08:00
|
|
|
def __init__(self, msg, option):
|
|
|
|
self.msg = msg
|
|
|
|
self.option_id = str(option)
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
if self.option_id:
|
|
|
|
return "option %s: %s" % (self.option_id, self.msg)
|
|
|
|
else:
|
|
|
|
return self.msg
|
|
|
|
|
|
|
|
|
|
|
|
class Argument:
|
2016-07-19 16:20:41 +08:00
|
|
|
"""class that mimics the necessary behaviour of optparse.Option
|
|
|
|
|
|
|
|
its currently a least effort implementation
|
|
|
|
and ignoring choices and integer prefixes
|
|
|
|
https://docs.python.org/3/library/optparse.html#optparse-standard-option-types
|
|
|
|
"""
|
2013-07-25 21:33:43 +08:00
|
|
|
_typ_map = {
|
|
|
|
'int': int,
|
|
|
|
'string': str,
|
2016-07-19 16:20:41 +08:00
|
|
|
'float': float,
|
|
|
|
'complex': complex,
|
|
|
|
}
|
2013-08-01 20:24:25 +08:00
|
|
|
|
2013-07-25 21:33:43 +08:00
|
|
|
def __init__(self, *names, **attrs):
|
|
|
|
"""store parms in private vars for use in add_argument"""
|
|
|
|
self._attrs = attrs
|
|
|
|
self._short_opts = []
|
|
|
|
self._long_opts = []
|
|
|
|
self.dest = attrs.get('dest')
|
2016-07-19 16:33:25 +08:00
|
|
|
if '%default' in (attrs.get('help') or ''):
|
|
|
|
warnings.warn(
|
|
|
|
'pytest now uses argparse. "%default" should be'
|
|
|
|
' changed to "%(default)s" ',
|
|
|
|
DeprecationWarning,
|
|
|
|
stacklevel=3)
|
2013-07-25 21:33:43 +08:00
|
|
|
try:
|
|
|
|
typ = attrs['type']
|
|
|
|
except KeyError:
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
# this might raise a keyerror as well, don't want to catch that
|
2013-10-01 20:20:20 +08:00
|
|
|
if isinstance(typ, py.builtin._basestring):
|
2013-07-25 21:33:43 +08:00
|
|
|
if typ == 'choice':
|
2016-07-19 16:33:25 +08:00
|
|
|
warnings.warn(
|
|
|
|
'type argument to addoption() is a string %r.'
|
|
|
|
' For parsearg this is optional and when supplied '
|
|
|
|
' should be a type.'
|
|
|
|
' (options: %s)' % (typ, names),
|
|
|
|
DeprecationWarning,
|
|
|
|
stacklevel=3)
|
2013-07-25 21:33:43 +08:00
|
|
|
# argparse expects a type here take it from
|
|
|
|
# the type of the first element
|
|
|
|
attrs['type'] = type(attrs['choices'][0])
|
|
|
|
else:
|
2016-07-19 16:33:25 +08:00
|
|
|
warnings.warn(
|
|
|
|
'type argument to addoption() is a string %r.'
|
|
|
|
' For parsearg this should be a type.'
|
|
|
|
' (options: %s)' % (typ, names),
|
|
|
|
DeprecationWarning,
|
|
|
|
stacklevel=3)
|
2013-07-25 21:33:43 +08:00
|
|
|
attrs['type'] = Argument._typ_map[typ]
|
2013-08-01 20:24:25 +08:00
|
|
|
# used in test_parseopt -> test_parse_defaultgetter
|
2013-07-25 21:33:43 +08:00
|
|
|
self.type = attrs['type']
|
|
|
|
else:
|
|
|
|
self.type = typ
|
|
|
|
try:
|
|
|
|
# attribute existence is tested in Config._processopt
|
|
|
|
self.default = attrs['default']
|
|
|
|
except KeyError:
|
|
|
|
pass
|
|
|
|
self._set_opt_strings(names)
|
|
|
|
if not self.dest:
|
|
|
|
if self._long_opts:
|
|
|
|
self.dest = self._long_opts[0][2:].replace('-', '_')
|
|
|
|
else:
|
|
|
|
try:
|
|
|
|
self.dest = self._short_opts[0][1:]
|
|
|
|
except IndexError:
|
|
|
|
raise ArgumentError(
|
|
|
|
'need a long or short option', self)
|
|
|
|
|
|
|
|
def names(self):
|
|
|
|
return self._short_opts + self._long_opts
|
|
|
|
|
|
|
|
def attrs(self):
|
|
|
|
# update any attributes set by processopt
|
2013-07-25 23:26:48 +08:00
|
|
|
attrs = 'default dest help'.split()
|
2013-07-25 21:33:43 +08:00
|
|
|
if self.dest:
|
|
|
|
attrs.append(self.dest)
|
|
|
|
for attr in attrs:
|
|
|
|
try:
|
|
|
|
self._attrs[attr] = getattr(self, attr)
|
|
|
|
except AttributeError:
|
|
|
|
pass
|
2013-07-25 23:26:48 +08:00
|
|
|
if self._attrs.get('help'):
|
|
|
|
a = self._attrs['help']
|
|
|
|
a = a.replace('%default', '%(default)s')
|
|
|
|
#a = a.replace('%prog', '%(prog)s')
|
|
|
|
self._attrs['help'] = a
|
2013-07-25 21:33:43 +08:00
|
|
|
return self._attrs
|
2013-08-01 20:24:25 +08:00
|
|
|
|
2013-07-25 21:33:43 +08:00
|
|
|
def _set_opt_strings(self, opts):
|
|
|
|
"""directly from optparse
|
|
|
|
|
|
|
|
might not be necessary as this is passed to argparse later on"""
|
|
|
|
for opt in opts:
|
|
|
|
if len(opt) < 2:
|
|
|
|
raise ArgumentError(
|
|
|
|
"invalid option string %r: "
|
|
|
|
"must be at least two characters long" % opt, self)
|
|
|
|
elif len(opt) == 2:
|
|
|
|
if not (opt[0] == "-" and opt[1] != "-"):
|
|
|
|
raise ArgumentError(
|
|
|
|
"invalid short option string %r: "
|
|
|
|
"must be of the form -x, (x any non-dash char)" % opt,
|
|
|
|
self)
|
|
|
|
self._short_opts.append(opt)
|
|
|
|
else:
|
|
|
|
if not (opt[0:2] == "--" and opt[2] != "-"):
|
|
|
|
raise ArgumentError(
|
|
|
|
"invalid long option string %r: "
|
|
|
|
"must start with --, followed by non-dash" % opt,
|
|
|
|
self)
|
|
|
|
self._long_opts.append(opt)
|
2013-08-01 20:24:25 +08:00
|
|
|
|
2013-07-25 21:33:43 +08:00
|
|
|
def __repr__(self):
|
2016-06-23 03:59:56 +08:00
|
|
|
args = []
|
2013-07-25 21:33:43 +08:00
|
|
|
if self._short_opts:
|
2016-06-23 03:59:56 +08:00
|
|
|
args += ['_short_opts: ' + repr(self._short_opts)]
|
2013-07-25 21:33:43 +08:00
|
|
|
if self._long_opts:
|
2016-06-23 03:59:56 +08:00
|
|
|
args += ['_long_opts: ' + repr(self._long_opts)]
|
|
|
|
args += ['dest: ' + repr(self.dest)]
|
2013-07-25 21:33:43 +08:00
|
|
|
if hasattr(self, 'type'):
|
2016-06-23 03:59:56 +08:00
|
|
|
args += ['type: ' + repr(self.type)]
|
2013-07-25 21:33:43 +08:00
|
|
|
if hasattr(self, 'default'):
|
2016-06-23 03:59:56 +08:00
|
|
|
args += ['default: ' + repr(self.default)]
|
|
|
|
return 'Argument({0})'.format(', '.join(args))
|
2013-07-25 21:33:43 +08:00
|
|
|
|
2013-08-01 20:24:25 +08:00
|
|
|
|
2010-10-12 21:34:32 +08:00
|
|
|
class OptionGroup:
|
|
|
|
def __init__(self, name, description="", parser=None):
|
|
|
|
self.name = name
|
|
|
|
self.description = description
|
|
|
|
self.options = []
|
|
|
|
self.parser = parser
|
|
|
|
|
|
|
|
def addoption(self, *optnames, **attrs):
|
2013-08-01 22:21:33 +08:00
|
|
|
""" add an option to this group.
|
|
|
|
|
|
|
|
if a shortened version of a long option is specified it will
|
|
|
|
be suppressed in the help. addoption('--twowords', '--two-words')
|
|
|
|
results in help showing '--two-words' only, but --twowords gets
|
|
|
|
accepted **and** the automatic destination is in args.twowords
|
|
|
|
"""
|
2016-06-22 15:52:48 +08:00
|
|
|
conflict = set(optnames).intersection(
|
|
|
|
name for opt in self.options for name in opt.names())
|
|
|
|
if conflict:
|
|
|
|
raise ValueError("option names %s already added" % conflict)
|
2013-07-25 21:33:43 +08:00
|
|
|
option = Argument(*optnames, **attrs)
|
2010-10-12 21:34:32 +08:00
|
|
|
self._addoption_instance(option, shortupper=False)
|
|
|
|
|
|
|
|
def _addoption(self, *optnames, **attrs):
|
2013-07-25 21:33:43 +08:00
|
|
|
option = Argument(*optnames, **attrs)
|
2010-10-12 21:34:32 +08:00
|
|
|
self._addoption_instance(option, shortupper=True)
|
|
|
|
|
|
|
|
def _addoption_instance(self, option, shortupper=False):
|
|
|
|
if not shortupper:
|
|
|
|
for opt in option._short_opts:
|
|
|
|
if opt[0] == '-' and opt[1].islower():
|
|
|
|
raise ValueError("lowercase shortoptions reserved")
|
|
|
|
if self.parser:
|
|
|
|
self.parser.processoption(option)
|
|
|
|
self.options.append(option)
|
|
|
|
|
|
|
|
|
2014-08-01 06:13:40 +08:00
|
|
|
class MyOptionParser(argparse.ArgumentParser):
|
2015-07-09 08:22:08 +08:00
|
|
|
def __init__(self, parser, extra_info=None):
|
|
|
|
if not extra_info:
|
|
|
|
extra_info = {}
|
2010-10-12 21:34:32 +08:00
|
|
|
self._parser = parser
|
2014-08-01 06:13:40 +08:00
|
|
|
argparse.ArgumentParser.__init__(self, usage=parser._usage,
|
2013-08-01 22:21:33 +08:00
|
|
|
add_help=False, formatter_class=DropShorterLongHelpFormatter)
|
2015-07-09 08:22:08 +08:00
|
|
|
# extra_info is a dict of (param -> value) to display if there's
|
|
|
|
# an usage error to provide more contextual information to the user
|
|
|
|
self.extra_info = extra_info
|
2013-07-30 17:26:15 +08:00
|
|
|
|
|
|
|
def parse_args(self, args=None, namespace=None):
|
|
|
|
"""allow splitting of positional arguments"""
|
|
|
|
args, argv = self.parse_known_args(args, namespace)
|
|
|
|
if argv:
|
|
|
|
for arg in argv:
|
|
|
|
if arg and arg[0] == '-':
|
2015-07-09 08:22:08 +08:00
|
|
|
lines = ['unrecognized arguments: %s' % (' '.join(argv))]
|
|
|
|
for k, v in sorted(self.extra_info.items()):
|
|
|
|
lines.append(' %s: %s' % (k, v))
|
|
|
|
self.error('\n'.join(lines))
|
2013-09-28 15:52:41 +08:00
|
|
|
getattr(args, FILE_OR_DIR).extend(argv)
|
2013-07-30 17:26:15 +08:00
|
|
|
return args
|
|
|
|
|
2015-09-03 00:49:49 +08:00
|
|
|
|
2014-08-01 06:13:40 +08:00
|
|
|
class DropShorterLongHelpFormatter(argparse.HelpFormatter):
|
2013-08-01 22:21:33 +08:00
|
|
|
"""shorten help for long options that differ only in extra hyphens
|
|
|
|
|
|
|
|
- collapse **long** options that are the same except for extra hyphens
|
|
|
|
- special action attribute map_long_option allows surpressing additional
|
|
|
|
long options
|
|
|
|
- shortcut if there are only two options and one of them is a short one
|
|
|
|
- cache result on action object as this is called at least 2 times
|
|
|
|
"""
|
|
|
|
def _format_action_invocation(self, action):
|
2014-08-01 06:13:40 +08:00
|
|
|
orgstr = argparse.HelpFormatter._format_action_invocation(self, action)
|
2013-08-01 22:21:33 +08:00
|
|
|
if orgstr and orgstr[0] != '-': # only optional arguments
|
|
|
|
return orgstr
|
|
|
|
res = getattr(action, '_formatted_action_invocation', None)
|
|
|
|
if res:
|
|
|
|
return res
|
|
|
|
options = orgstr.split(', ')
|
|
|
|
if len(options) == 2 and (len(options[0]) == 2 or len(options[1]) == 2):
|
|
|
|
# a shortcut for '-h, --help' or '--abc', '-a'
|
|
|
|
action._formatted_action_invocation = orgstr
|
|
|
|
return orgstr
|
|
|
|
return_list = []
|
|
|
|
option_map = getattr(action, 'map_long_option', {})
|
|
|
|
if option_map is None:
|
|
|
|
option_map = {}
|
|
|
|
short_long = {}
|
|
|
|
for option in options:
|
|
|
|
if len(option) == 2 or option[2] == ' ':
|
|
|
|
continue
|
|
|
|
if not option.startswith('--'):
|
|
|
|
raise ArgumentError('long optional argument without "--": [%s]'
|
|
|
|
% (option), self)
|
|
|
|
xxoption = option[2:]
|
|
|
|
if xxoption.split()[0] not in option_map:
|
|
|
|
shortened = xxoption.replace('-', '')
|
|
|
|
if shortened not in short_long or \
|
|
|
|
len(short_long[shortened]) < len(xxoption):
|
|
|
|
short_long[shortened] = xxoption
|
|
|
|
# now short_long has been filled out to the longest with dashes
|
|
|
|
# **and** we keep the right option ordering from add_argument
|
|
|
|
for option in options: #
|
|
|
|
if len(option) == 2 or option[2] == ' ':
|
|
|
|
return_list.append(option)
|
|
|
|
if option[2:] == short_long.get(option.replace('-', '')):
|
2014-03-27 01:47:30 +08:00
|
|
|
return_list.append(option.replace(' ', '='))
|
2013-08-01 22:21:33 +08:00
|
|
|
action._formatted_action_invocation = ', '.join(return_list)
|
|
|
|
return action._formatted_action_invocation
|
|
|
|
|
2013-08-01 20:24:25 +08:00
|
|
|
|
2010-10-12 21:34:32 +08:00
|
|
|
|
2010-10-14 00:45:07 +08:00
|
|
|
def _ensure_removed_sysmodule(modname):
|
|
|
|
try:
|
|
|
|
del sys.modules[modname]
|
|
|
|
except KeyError:
|
|
|
|
pass
|
2010-10-12 21:34:32 +08:00
|
|
|
|
|
|
|
class CmdOptions(object):
|
|
|
|
""" holds cmdline options as attributes."""
|
2015-09-25 08:52:53 +08:00
|
|
|
def __init__(self, values=()):
|
|
|
|
self.__dict__.update(values)
|
2010-10-12 21:34:32 +08:00
|
|
|
def __repr__(self):
|
|
|
|
return "<CmdOptions %r>" %(self.__dict__,)
|
2015-09-25 08:52:53 +08:00
|
|
|
def copy(self):
|
|
|
|
return CmdOptions(self.__dict__)
|
2010-10-12 21:34:32 +08:00
|
|
|
|
2014-05-14 13:36:31 +08:00
|
|
|
class Notset:
|
|
|
|
def __repr__(self):
|
|
|
|
return "<NOTSET>"
|
|
|
|
|
|
|
|
notset = Notset()
|
2013-09-28 15:52:41 +08:00
|
|
|
FILE_OR_DIR = 'file_or_dir'
|
2015-04-26 06:41:29 +08:00
|
|
|
|
2010-10-12 21:34:32 +08:00
|
|
|
class Config(object):
|
|
|
|
""" access to configuration values, pluginmanager and plugin hooks. """
|
2013-08-01 20:24:25 +08:00
|
|
|
|
2013-09-29 04:22:53 +08:00
|
|
|
def __init__(self, pluginmanager):
|
2012-11-06 21:09:12 +08:00
|
|
|
#: access to command line option as attributes.
|
|
|
|
#: (deprecated), use :py:func:`getoption() <_pytest.config.Config.getoption>` instead
|
2010-10-12 21:34:32 +08:00
|
|
|
self.option = CmdOptions()
|
2013-09-28 15:52:41 +08:00
|
|
|
_a = FILE_OR_DIR
|
2010-10-12 21:34:32 +08:00
|
|
|
self._parser = Parser(
|
2013-07-25 21:33:43 +08:00
|
|
|
usage="%%(prog)s [options] [%s] [%s] [...]" % (_a, _a),
|
2010-10-12 21:34:32 +08:00
|
|
|
processopt=self._processopt,
|
|
|
|
)
|
|
|
|
#: a pluginmanager instance
|
2013-09-29 04:22:53 +08:00
|
|
|
self.pluginmanager = pluginmanager
|
2010-11-06 16:58:04 +08:00
|
|
|
self.trace = self.pluginmanager.trace.root.get("config")
|
2010-10-12 21:34:32 +08:00
|
|
|
self.hook = self.pluginmanager.hook
|
2010-11-25 05:01:04 +08:00
|
|
|
self._inicache = {}
|
2012-11-06 21:09:12 +08:00
|
|
|
self._opt2dest = {}
|
2011-04-17 18:20:13 +08:00
|
|
|
self._cleanup = []
|
2015-09-01 03:54:12 +08:00
|
|
|
self._warn = self.pluginmanager._warn
|
2013-09-30 19:14:14 +08:00
|
|
|
self.pluginmanager.register(self, "pytestconfig")
|
|
|
|
self._configured = False
|
2015-04-25 17:29:11 +08:00
|
|
|
def do_setns(dic):
|
2013-09-30 19:14:14 +08:00
|
|
|
import pytest
|
|
|
|
setns(pytest, dic)
|
2015-04-25 19:38:30 +08:00
|
|
|
self.hook.pytest_namespace.call_historic(do_setns, {})
|
|
|
|
self.hook.pytest_addoption.call_historic(kwargs=dict(parser=self._parser))
|
2013-09-30 19:14:14 +08:00
|
|
|
|
2015-04-22 22:33:20 +08:00
|
|
|
def add_cleanup(self, func):
|
|
|
|
""" Add a function to be called when the config object gets out of
|
|
|
|
use (usually coninciding with pytest_unconfigure)."""
|
|
|
|
self._cleanup.append(func)
|
|
|
|
|
|
|
|
def _do_configure(self):
|
2013-09-30 19:14:14 +08:00
|
|
|
assert not self._configured
|
|
|
|
self._configured = True
|
2015-04-25 19:38:30 +08:00
|
|
|
self.hook.pytest_configure.call_historic(kwargs=dict(config=self))
|
2013-09-30 19:14:14 +08:00
|
|
|
|
2015-04-22 22:33:20 +08:00
|
|
|
def _ensure_unconfigure(self):
|
|
|
|
if self._configured:
|
|
|
|
self._configured = False
|
|
|
|
self.hook.pytest_unconfigure(config=self)
|
2015-04-25 17:29:11 +08:00
|
|
|
self.hook.pytest_configure._call_history = []
|
2015-04-22 22:33:20 +08:00
|
|
|
while self._cleanup:
|
|
|
|
fin = self._cleanup.pop()
|
|
|
|
fin()
|
2013-09-30 19:14:14 +08:00
|
|
|
|
2015-04-27 18:50:34 +08:00
|
|
|
def warn(self, code, message, fslocation=None):
|
2014-03-12 05:10:17 +08:00
|
|
|
""" generate a warning for this test session. """
|
2015-09-03 00:49:49 +08:00
|
|
|
self.hook.pytest_logwarning.call_historic(kwargs=dict(
|
|
|
|
code=code, message=message,
|
|
|
|
fslocation=fslocation, nodeid=None))
|
2014-03-12 05:10:17 +08:00
|
|
|
|
2014-03-14 19:49:36 +08:00
|
|
|
def get_terminal_writer(self):
|
2015-04-26 02:17:32 +08:00
|
|
|
return self.pluginmanager.get_plugin("terminalreporter")._tw
|
2014-03-14 19:49:36 +08:00
|
|
|
|
2013-09-30 19:14:14 +08:00
|
|
|
def pytest_cmdline_parse(self, pluginmanager, args):
|
2015-04-26 00:14:41 +08:00
|
|
|
# REF1 assert self == pluginmanager.config, (self, pluginmanager.config)
|
2013-09-30 19:14:14 +08:00
|
|
|
self.parse(args)
|
|
|
|
return self
|
|
|
|
|
2013-09-30 19:14:14 +08:00
|
|
|
def notify_exception(self, excinfo, option=None):
|
|
|
|
if option and option.fulltrace:
|
|
|
|
style = "long"
|
|
|
|
else:
|
|
|
|
style = "native"
|
|
|
|
excrepr = excinfo.getrepr(funcargs=True,
|
|
|
|
showlocals=getattr(option, 'showlocals', False),
|
|
|
|
style=style,
|
|
|
|
)
|
|
|
|
res = self.hook.pytest_internalerror(excrepr=excrepr,
|
|
|
|
excinfo=excinfo)
|
|
|
|
if not py.builtin.any(res):
|
|
|
|
for line in str(excrepr).split("\n"):
|
|
|
|
sys.stderr.write("INTERNALERROR> %s\n" %line)
|
|
|
|
sys.stderr.flush()
|
|
|
|
|
2015-02-27 04:56:44 +08:00
|
|
|
def cwd_relative_nodeid(self, nodeid):
|
|
|
|
# nodeid's are relative to the rootpath, compute relative to cwd
|
|
|
|
if self.invocation_dir != self.rootdir:
|
|
|
|
fullpath = self.rootdir.join(nodeid)
|
|
|
|
nodeid = self.invocation_dir.bestrelpath(fullpath)
|
|
|
|
return nodeid
|
2013-09-30 19:14:14 +08:00
|
|
|
|
2011-03-17 01:00:52 +08:00
|
|
|
@classmethod
|
|
|
|
def fromdictargs(cls, option_dict, args):
|
|
|
|
""" constructor useable for subprocesses. """
|
2015-04-26 00:14:41 +08:00
|
|
|
config = get_config()
|
2011-03-17 01:00:52 +08:00
|
|
|
config.option.__dict__.update(option_dict)
|
2015-09-25 08:52:53 +08:00
|
|
|
config.parse(args, addopts=False)
|
2011-03-17 01:00:52 +08:00
|
|
|
for x in config.option.plugins:
|
|
|
|
config.pluginmanager.consider_pluginarg(x)
|
|
|
|
return config
|
|
|
|
|
2010-10-28 04:29:01 +08:00
|
|
|
def _processopt(self, opt):
|
2012-11-06 21:09:12 +08:00
|
|
|
for name in opt._short_opts + opt._long_opts:
|
|
|
|
self._opt2dest[name] = opt.dest
|
|
|
|
|
2010-10-28 04:29:01 +08:00
|
|
|
if hasattr(opt, 'default') and opt.dest:
|
|
|
|
if not hasattr(self.option, opt.dest):
|
|
|
|
setattr(self.option, opt.dest, opt.default)
|
|
|
|
|
2015-05-06 16:08:08 +08:00
|
|
|
@hookimpl(trylast=True)
|
2014-04-02 17:29:23 +08:00
|
|
|
def pytest_load_initial_conftests(self, early_config):
|
2015-04-22 20:15:42 +08:00
|
|
|
self.pluginmanager._set_initial_conftests(early_config.known_args_namespace)
|
2010-10-25 05:26:14 +08:00
|
|
|
|
2010-11-05 06:21:26 +08:00
|
|
|
def _initini(self, args):
|
2015-09-25 08:52:53 +08:00
|
|
|
ns, unknown_args = self._parser.parse_known_and_unknown_args(args, namespace=self.option.copy())
|
2015-08-28 06:35:32 +08:00
|
|
|
r = determine_setup(ns.inifilename, ns.file_or_dir + unknown_args)
|
2015-02-27 04:56:44 +08:00
|
|
|
self.rootdir, self.inifile, self.inicfg = r
|
2015-07-09 08:22:08 +08:00
|
|
|
self._parser.extra_info['rootdir'] = self.rootdir
|
|
|
|
self._parser.extra_info['inifile'] = self.inifile
|
2015-02-27 04:56:44 +08:00
|
|
|
self.invocation_dir = py.path.local()
|
2010-11-05 06:21:26 +08:00
|
|
|
self._parser.addini('addopts', 'extra command line options', 'args')
|
|
|
|
self._parser.addini('minversion', 'minimally required pytest version')
|
|
|
|
|
2016-06-22 18:42:11 +08:00
|
|
|
def _consider_importhook(self, args, entrypoint_name):
|
|
|
|
"""Install the PEP 302 import hook if using assertion re-writing.
|
|
|
|
|
|
|
|
Needs to parse the --assert=<mode> option from the commandline
|
|
|
|
and find all the installed plugins to mark them for re-writing
|
|
|
|
by the importhook.
|
|
|
|
"""
|
|
|
|
ns, unknown_args = self._parser.parse_known_and_unknown_args(args)
|
|
|
|
mode = ns.assertmode
|
2016-07-15 07:18:50 +08:00
|
|
|
if mode == 'rewrite':
|
|
|
|
try:
|
|
|
|
hook = _pytest.assertion.install_importhook(self)
|
|
|
|
except SystemError:
|
|
|
|
mode = 'plain'
|
|
|
|
else:
|
2016-06-26 00:26:45 +08:00
|
|
|
self.pluginmanager.rewrite_hook = hook
|
2016-06-22 18:42:11 +08:00
|
|
|
for entrypoint in pkg_resources.iter_entry_points('pytest11'):
|
|
|
|
for entry in entrypoint.dist._get_metadata('RECORD'):
|
|
|
|
fn = entry.split(',')[0]
|
|
|
|
is_simple_module = os.sep not in fn and fn.endswith('.py')
|
|
|
|
is_package = fn.count(os.sep) == 1 and fn.endswith('__init__.py')
|
|
|
|
if is_simple_module:
|
|
|
|
module_name, ext = os.path.splitext(fn)
|
|
|
|
hook.mark_rewrite(module_name)
|
|
|
|
elif is_package:
|
|
|
|
package_name = os.path.dirname(fn)
|
|
|
|
hook.mark_rewrite(package_name)
|
2016-07-15 07:18:50 +08:00
|
|
|
self._warn_about_missing_assertion(mode)
|
2016-06-22 18:42:11 +08:00
|
|
|
|
|
|
|
def _warn_about_missing_assertion(self, mode):
|
|
|
|
try:
|
|
|
|
assert False
|
|
|
|
except AssertionError:
|
|
|
|
pass
|
|
|
|
else:
|
2016-07-15 07:18:50 +08:00
|
|
|
if mode == 'plain':
|
|
|
|
sys.stderr.write("WARNING: ASSERTIONS ARE NOT EXECUTED"
|
|
|
|
" and FAILING TESTS WILL PASS. Are you"
|
|
|
|
" using python -O?")
|
2016-06-22 18:42:11 +08:00
|
|
|
else:
|
2016-07-15 07:18:50 +08:00
|
|
|
sys.stderr.write("WARNING: assertions not in test modules or"
|
|
|
|
" plugins will be ignored"
|
|
|
|
" because assert statements are not executed "
|
|
|
|
"by the underlying Python interpreter "
|
|
|
|
"(are you using python -O?)\n")
|
2016-06-22 18:42:11 +08:00
|
|
|
|
2010-11-05 06:21:26 +08:00
|
|
|
def _preparse(self, args, addopts=True):
|
|
|
|
self._initini(args)
|
|
|
|
if addopts:
|
2015-01-26 18:39:21 +08:00
|
|
|
args[:] = shlex.split(os.environ.get('PYTEST_ADDOPTS', '')) + args
|
2010-11-05 06:21:26 +08:00
|
|
|
args[:] = self.getini("addopts") + args
|
2010-10-28 01:35:27 +08:00
|
|
|
self._checkversion()
|
2016-06-22 18:42:11 +08:00
|
|
|
entrypoint_name = 'pytest11'
|
|
|
|
self._consider_importhook(args, entrypoint_name)
|
2010-12-06 23:54:42 +08:00
|
|
|
self.pluginmanager.consider_preparse(args)
|
2016-07-14 19:42:29 +08:00
|
|
|
self.pluginmanager.load_setuptools_entrypoints(entrypoint_name)
|
2010-10-12 21:34:32 +08:00
|
|
|
self.pluginmanager.consider_env()
|
2015-09-25 08:52:53 +08:00
|
|
|
self.known_args_namespace = ns = self._parser.parse_known_args(args, namespace=self.option.copy())
|
2015-07-24 08:48:59 +08:00
|
|
|
if self.known_args_namespace.confcutdir is None and self.inifile:
|
|
|
|
confcutdir = py.path.local(self.inifile).dirname
|
|
|
|
self.known_args_namespace.confcutdir = confcutdir
|
2014-04-03 02:42:41 +08:00
|
|
|
try:
|
|
|
|
self.hook.pytest_load_initial_conftests(early_config=self,
|
|
|
|
args=args, parser=self._parser)
|
|
|
|
except ConftestImportFailure:
|
|
|
|
e = sys.exc_info()[1]
|
|
|
|
if ns.help or ns.version:
|
2014-04-15 05:42:02 +08:00
|
|
|
# we don't want to prevent --help/--version to work
|
2014-04-03 02:42:41 +08:00
|
|
|
# so just let is pass and print a warning at the end
|
2015-09-01 03:54:12 +08:00
|
|
|
self._warn("could not load initial conftests (%s)\n" % e.path)
|
2014-04-03 02:42:41 +08:00
|
|
|
else:
|
|
|
|
raise
|
2010-10-12 21:34:32 +08:00
|
|
|
|
2010-10-28 01:35:27 +08:00
|
|
|
def _checkversion(self):
|
2013-09-30 19:14:14 +08:00
|
|
|
import pytest
|
2010-10-28 01:35:27 +08:00
|
|
|
minver = self.inicfg.get('minversion', None)
|
|
|
|
if minver:
|
|
|
|
ver = minver.split(".")
|
|
|
|
myver = pytest.__version__.split(".")
|
|
|
|
if myver < ver:
|
|
|
|
raise pytest.UsageError(
|
|
|
|
"%s:%d: requires pytest-%s, actual pytest-%s'" %(
|
|
|
|
self.inicfg.config.path, self.inicfg.lineof('minversion'),
|
|
|
|
minver, pytest.__version__))
|
|
|
|
|
2015-09-25 07:10:01 +08:00
|
|
|
def parse(self, args, addopts=True):
|
2010-10-31 01:23:50 +08:00
|
|
|
# parse given cmdline arguments into this config object.
|
2010-10-12 21:34:32 +08:00
|
|
|
assert not hasattr(self, 'args'), (
|
|
|
|
"can only parse cmdline args at most once per Config object")
|
2011-07-15 01:11:50 +08:00
|
|
|
self._origargs = args
|
2015-04-25 19:38:30 +08:00
|
|
|
self.hook.pytest_addhooks.call_historic(
|
|
|
|
kwargs=dict(pluginmanager=self.pluginmanager))
|
2015-09-25 07:10:01 +08:00
|
|
|
self._preparse(args, addopts=addopts)
|
2013-09-30 19:14:16 +08:00
|
|
|
# XXX deprecated hook:
|
|
|
|
self.hook.pytest_cmdline_preparse(config=self, args=args)
|
2015-09-25 08:52:53 +08:00
|
|
|
args = self._parser.parse_setoption(args, self.option, namespace=self.option)
|
2010-10-12 21:34:32 +08:00
|
|
|
if not args:
|
2015-07-09 09:51:18 +08:00
|
|
|
cwd = os.getcwd()
|
|
|
|
if cwd == self.rootdir:
|
|
|
|
args = self.getini('testpaths')
|
|
|
|
if not args:
|
|
|
|
args = [cwd]
|
2010-10-12 21:34:32 +08:00
|
|
|
self.args = args
|
|
|
|
|
2011-11-12 06:56:08 +08:00
|
|
|
def addinivalue_line(self, name, line):
|
|
|
|
""" add a line to an ini-file option. The option must have been
|
|
|
|
declared but might not yet be set in which case the line becomes the
|
|
|
|
the first line in its value. """
|
|
|
|
x = self.getini(name)
|
|
|
|
assert isinstance(x, list)
|
|
|
|
x.append(line) # modifies the cached list inline
|
|
|
|
|
2010-11-01 00:41:58 +08:00
|
|
|
def getini(self, name):
|
2012-11-06 21:09:12 +08:00
|
|
|
""" return configuration value from an :ref:`ini file <inifiles>`. If the
|
|
|
|
specified name hasn't been registered through a prior
|
|
|
|
:py:func:`parser.addini <pytest.config.Parser.addini>`
|
2010-11-01 01:01:33 +08:00
|
|
|
call (usually from a plugin), a ValueError is raised. """
|
2010-11-25 05:01:04 +08:00
|
|
|
try:
|
|
|
|
return self._inicache[name]
|
|
|
|
except KeyError:
|
|
|
|
self._inicache[name] = val = self._getini(name)
|
|
|
|
return val
|
|
|
|
|
|
|
|
def _getini(self, name):
|
2010-11-01 00:41:58 +08:00
|
|
|
try:
|
2010-11-05 06:21:26 +08:00
|
|
|
description, type, default = self._parser._inidict[name]
|
2010-11-01 00:41:58 +08:00
|
|
|
except KeyError:
|
|
|
|
raise ValueError("unknown configuration value: %r" %(name,))
|
2016-06-25 22:12:42 +08:00
|
|
|
value = self._get_override_ini_value(name)
|
|
|
|
if value is None:
|
|
|
|
try:
|
|
|
|
value = self.inicfg[name]
|
|
|
|
except KeyError:
|
|
|
|
if default is not None:
|
|
|
|
return default
|
|
|
|
if type is None:
|
|
|
|
return ''
|
|
|
|
return []
|
2010-11-01 00:41:58 +08:00
|
|
|
if type == "pathlist":
|
|
|
|
dp = py.path.local(self.inicfg.config.path).dirpath()
|
|
|
|
l = []
|
2014-08-01 06:13:40 +08:00
|
|
|
for relpath in shlex.split(value):
|
2010-11-01 00:41:58 +08:00
|
|
|
l.append(dp.join(relpath, abs=True))
|
|
|
|
return l
|
2010-11-05 06:21:26 +08:00
|
|
|
elif type == "args":
|
2014-08-01 06:13:40 +08:00
|
|
|
return shlex.split(value)
|
2010-11-06 06:37:31 +08:00
|
|
|
elif type == "linelist":
|
2010-11-07 07:34:00 +08:00
|
|
|
return [t for t in map(lambda x: x.strip(), value.split("\n")) if t]
|
2016-02-15 05:27:48 +08:00
|
|
|
elif type == "bool":
|
|
|
|
return bool(_strtobool(value.strip()))
|
2010-11-01 00:41:58 +08:00
|
|
|
else:
|
2010-11-05 06:21:26 +08:00
|
|
|
assert type is None
|
2010-11-01 00:41:58 +08:00
|
|
|
return value
|
|
|
|
|
2014-04-03 04:30:45 +08:00
|
|
|
def _getconftest_pathlist(self, name, path):
|
2010-10-12 21:34:32 +08:00
|
|
|
try:
|
2015-04-22 20:15:42 +08:00
|
|
|
mod, relroots = self.pluginmanager._rget_with_confmod(name, path)
|
2010-10-12 21:34:32 +08:00
|
|
|
except KeyError:
|
|
|
|
return None
|
|
|
|
modpath = py.path.local(mod.__file__).dirpath()
|
|
|
|
l = []
|
|
|
|
for relroot in relroots:
|
|
|
|
if not isinstance(relroot, py.path.local):
|
|
|
|
relroot = relroot.replace("/", py.path.local.sep)
|
|
|
|
relroot = modpath.join(relroot, abs=True)
|
|
|
|
l.append(relroot)
|
|
|
|
return l
|
|
|
|
|
2016-06-25 22:12:42 +08:00
|
|
|
def _get_override_ini_value(self, name):
|
|
|
|
value = None
|
|
|
|
# override_ini is a list of list, to support both -o foo1=bar1 foo2=bar2 and
|
|
|
|
# and -o foo1=bar1 -o foo2=bar2 options
|
|
|
|
# always use the last item if multiple value set for same ini-name,
|
|
|
|
# e.g. -o foo=bar1 -o foo=bar2 will set foo to bar2
|
|
|
|
if self.getoption("override_ini", None):
|
|
|
|
for ini_config_list in self.option.override_ini:
|
|
|
|
for ini_config in ini_config_list:
|
|
|
|
(key, user_ini_value) = ini_config.split("=", 1)
|
|
|
|
if key == name:
|
|
|
|
value = user_ini_value
|
|
|
|
return value
|
|
|
|
|
2014-04-03 04:30:45 +08:00
|
|
|
def getoption(self, name, default=notset, skip=False):
|
2012-11-06 21:09:12 +08:00
|
|
|
""" return command line option value.
|
|
|
|
|
|
|
|
:arg name: name of the option. You may also specify
|
|
|
|
the literal ``--OPT`` option instead of the "dest" option name.
|
2014-04-03 04:30:45 +08:00
|
|
|
:arg default: default value if no option of that name exists.
|
2014-05-14 13:36:31 +08:00
|
|
|
:arg skip: if True raise pytest.skip if option does not exists
|
|
|
|
or has a None value.
|
2012-11-06 21:09:12 +08:00
|
|
|
"""
|
|
|
|
name = self._opt2dest.get(name, name)
|
|
|
|
try:
|
2014-05-14 13:36:31 +08:00
|
|
|
val = getattr(self.option, name)
|
|
|
|
if val is None and skip:
|
|
|
|
raise AttributeError(name)
|
|
|
|
return val
|
2012-11-06 21:09:12 +08:00
|
|
|
except AttributeError:
|
2014-04-03 04:30:45 +08:00
|
|
|
if default is not notset:
|
|
|
|
return default
|
|
|
|
if skip:
|
2014-07-03 18:58:12 +08:00
|
|
|
import pytest
|
|
|
|
pytest.skip("no %r option found" %(name,))
|
2012-11-06 21:09:12 +08:00
|
|
|
raise ValueError("no option named %r" % (name,))
|
|
|
|
|
2010-11-01 00:41:58 +08:00
|
|
|
def getvalue(self, name, path=None):
|
2014-04-03 04:30:45 +08:00
|
|
|
""" (deprecated, use getoption()) """
|
|
|
|
return self.getoption(name)
|
2010-11-01 00:41:58 +08:00
|
|
|
|
2010-10-12 21:34:32 +08:00
|
|
|
def getvalueorskip(self, name, path=None):
|
2014-04-03 04:30:45 +08:00
|
|
|
""" (deprecated, use getoption(skip=True)) """
|
|
|
|
return self.getoption(name, skip=True)
|
2010-10-12 21:34:32 +08:00
|
|
|
|
2012-11-12 17:15:43 +08:00
|
|
|
def exists(path, ignore=EnvironmentError):
|
|
|
|
try:
|
|
|
|
return path.check()
|
|
|
|
except ignore:
|
|
|
|
return False
|
2010-10-12 21:34:32 +08:00
|
|
|
|
2010-10-28 01:35:27 +08:00
|
|
|
def getcfg(args, inibasenames):
|
2011-09-26 05:26:49 +08:00
|
|
|
args = [x for x in args if not str(x).startswith("-")]
|
2010-10-28 01:35:27 +08:00
|
|
|
if not args:
|
|
|
|
args = [py.path.local()]
|
2010-11-07 23:10:22 +08:00
|
|
|
for arg in args:
|
|
|
|
arg = py.path.local(arg)
|
2010-11-22 18:59:56 +08:00
|
|
|
for base in arg.parts(reverse=True):
|
|
|
|
for inibasename in inibasenames:
|
|
|
|
p = base.join(inibasename)
|
2012-11-12 17:15:43 +08:00
|
|
|
if exists(p):
|
2010-11-22 18:59:56 +08:00
|
|
|
iniconfig = py.iniconfig.IniConfig(p)
|
|
|
|
if 'pytest' in iniconfig.sections:
|
2015-02-27 04:56:44 +08:00
|
|
|
return base, p, iniconfig['pytest']
|
|
|
|
elif inibasename == "pytest.ini":
|
|
|
|
# allowed to be empty
|
|
|
|
return base, p, {}
|
|
|
|
return None, None, None
|
|
|
|
|
|
|
|
|
|
|
|
def get_common_ancestor(args):
|
|
|
|
# args are what we get after early command line parsing (usually
|
|
|
|
# strings, but can be py.path.local objects as well)
|
|
|
|
common_ancestor = None
|
|
|
|
for arg in args:
|
|
|
|
if str(arg)[0] == "-":
|
|
|
|
continue
|
|
|
|
p = py.path.local(arg)
|
|
|
|
if common_ancestor is None:
|
|
|
|
common_ancestor = p
|
|
|
|
else:
|
|
|
|
if p.relto(common_ancestor) or p == common_ancestor:
|
|
|
|
continue
|
|
|
|
elif common_ancestor.relto(p):
|
|
|
|
common_ancestor = p
|
|
|
|
else:
|
|
|
|
shared = p.common(common_ancestor)
|
|
|
|
if shared is not None:
|
|
|
|
common_ancestor = shared
|
|
|
|
if common_ancestor is None:
|
|
|
|
common_ancestor = py.path.local()
|
|
|
|
elif not common_ancestor.isdir():
|
|
|
|
common_ancestor = common_ancestor.dirpath()
|
|
|
|
return common_ancestor
|
|
|
|
|
|
|
|
|
|
|
|
def determine_setup(inifile, args):
|
|
|
|
if inifile:
|
|
|
|
iniconfig = py.iniconfig.IniConfig(inifile)
|
|
|
|
try:
|
|
|
|
inicfg = iniconfig["pytest"]
|
|
|
|
except KeyError:
|
|
|
|
inicfg = None
|
|
|
|
rootdir = get_common_ancestor(args)
|
|
|
|
else:
|
|
|
|
ancestor = get_common_ancestor(args)
|
|
|
|
rootdir, inifile, inicfg = getcfg(
|
|
|
|
[ancestor], ["pytest.ini", "tox.ini", "setup.cfg"])
|
|
|
|
if rootdir is None:
|
|
|
|
for rootdir in ancestor.parts(reverse=True):
|
|
|
|
if rootdir.join("setup.py").exists():
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
rootdir = ancestor
|
|
|
|
return rootdir, inifile, inicfg or {}
|
2011-01-18 19:51:21 +08:00
|
|
|
|
2013-09-30 19:14:14 +08:00
|
|
|
|
|
|
|
def setns(obj, dic):
|
|
|
|
import pytest
|
|
|
|
for name, value in dic.items():
|
|
|
|
if isinstance(value, dict):
|
|
|
|
mod = getattr(obj, name, None)
|
|
|
|
if mod is None:
|
|
|
|
modname = "pytest.%s" % name
|
2014-08-01 06:13:40 +08:00
|
|
|
mod = types.ModuleType(modname)
|
2013-09-30 19:14:14 +08:00
|
|
|
sys.modules[modname] = mod
|
|
|
|
mod.__all__ = []
|
|
|
|
setattr(obj, name, mod)
|
|
|
|
obj.__all__.append(name)
|
|
|
|
setns(mod, value)
|
|
|
|
else:
|
|
|
|
setattr(obj, name, value)
|
|
|
|
obj.__all__.append(name)
|
|
|
|
#if obj != pytest:
|
|
|
|
# pytest.__all__.append(name)
|
|
|
|
setattr(pytest, name, value)
|
2015-04-22 19:31:46 +08:00
|
|
|
|
2015-07-19 03:39:55 +08:00
|
|
|
|
|
|
|
def create_terminal_writer(config, *args, **kwargs):
|
|
|
|
"""Create a TerminalWriter instance configured according to the options
|
|
|
|
in the config object. Every code which requires a TerminalWriter object
|
|
|
|
and has access to a config object should use this function.
|
|
|
|
"""
|
|
|
|
tw = py.io.TerminalWriter(*args, **kwargs)
|
|
|
|
if config.option.color == 'yes':
|
|
|
|
tw.hasmarkup = True
|
|
|
|
if config.option.color == 'no':
|
|
|
|
tw.hasmarkup = False
|
|
|
|
return tw
|
2016-02-15 05:27:48 +08:00
|
|
|
|
|
|
|
|
|
|
|
def _strtobool(val):
|
|
|
|
"""Convert a string representation of truth to true (1) or false (0).
|
|
|
|
|
|
|
|
True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
|
|
|
|
are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
|
|
|
|
'val' is anything else.
|
|
|
|
|
|
|
|
.. note:: copied from distutils.util
|
|
|
|
"""
|
|
|
|
val = val.lower()
|
|
|
|
if val in ('y', 'yes', 't', 'true', 'on', '1'):
|
|
|
|
return 1
|
|
|
|
elif val in ('n', 'no', 'f', 'false', 'off', '0'):
|
|
|
|
return 0
|
|
|
|
else:
|
|
|
|
raise ValueError("invalid truth value %r" % (val,))
|