2017-12-01 20:21:06 +08:00
|
|
|
"""(disabled by default) support for testing pytest and pytest plugins."""
|
2017-03-17 09:21:30 +08:00
|
|
|
from __future__ import absolute_import, division, print_function
|
|
|
|
|
2015-11-27 22:43:01 +08:00
|
|
|
import codecs
|
2015-04-28 17:54:53 +08:00
|
|
|
import gc
|
2014-08-01 06:13:40 +08:00
|
|
|
import os
|
2015-11-27 22:43:01 +08:00
|
|
|
import platform
|
2009-12-25 07:24:58 +08:00
|
|
|
import re
|
2015-11-27 22:43:01 +08:00
|
|
|
import subprocess
|
2017-08-03 01:33:52 +08:00
|
|
|
import six
|
2015-11-27 22:43:01 +08:00
|
|
|
import sys
|
2009-12-30 18:37:46 +08:00
|
|
|
import time
|
2015-11-27 22:43:01 +08:00
|
|
|
import traceback
|
2010-09-28 02:48:30 +08:00
|
|
|
from fnmatch import fnmatch
|
2014-08-01 06:13:40 +08:00
|
|
|
|
2016-08-27 19:04:00 +08:00
|
|
|
from weakref import WeakKeyDictionary
|
|
|
|
|
2017-02-20 02:24:41 +08:00
|
|
|
from _pytest.capture import MultiCapture, SysCapture
|
2015-11-27 22:43:01 +08:00
|
|
|
from _pytest._code import Source
|
|
|
|
import py
|
|
|
|
import pytest
|
2014-08-01 06:13:40 +08:00
|
|
|
from _pytest.main import Session, EXIT_OK
|
2016-06-24 05:51:02 +08:00
|
|
|
from _pytest.assertion.rewrite import AssertionRewritingHook
|
2014-08-01 06:13:40 +08:00
|
|
|
|
2015-04-28 17:54:53 +08:00
|
|
|
|
2018-05-23 22:48:46 +08:00
|
|
|
PYTEST_FULLPATH = os.path.abspath(pytest.__file__.rstrip("oc")).replace(
|
|
|
|
"$py.class", ".py"
|
|
|
|
)
|
2017-07-18 14:24:48 +08:00
|
|
|
|
|
|
|
|
2017-09-17 03:20:04 +08:00
|
|
|
IGNORE_PAM = [ # filenames added when obtaining details about the current user
|
2018-05-23 22:48:46 +08:00
|
|
|
u"/var/lib/sss/mc/passwd"
|
2017-09-17 03:20:04 +08:00
|
|
|
]
|
|
|
|
|
|
|
|
|
2015-04-28 17:54:53 +08:00
|
|
|
def pytest_addoption(parser):
|
2018-05-23 22:48:46 +08:00
|
|
|
parser.addoption(
|
|
|
|
"--lsof",
|
|
|
|
action="store_true",
|
|
|
|
dest="lsof",
|
|
|
|
default=False,
|
|
|
|
help=("run FD checks if lsof is available"),
|
|
|
|
)
|
|
|
|
|
|
|
|
parser.addoption(
|
|
|
|
"--runpytest",
|
|
|
|
default="inprocess",
|
|
|
|
dest="runpytest",
|
|
|
|
choices=("inprocess", "subprocess"),
|
|
|
|
help=(
|
|
|
|
"run pytest sub runs in tests using an 'inprocess' "
|
|
|
|
"or 'subprocess' (python -m main) method"
|
|
|
|
),
|
|
|
|
)
|
2015-04-28 17:54:53 +08:00
|
|
|
|
|
|
|
|
|
|
|
def pytest_configure(config):
|
|
|
|
if config.getvalue("lsof"):
|
|
|
|
checker = LsofFdLeakChecker()
|
|
|
|
if checker.matching_platform():
|
|
|
|
config.pluginmanager.register(checker)
|
|
|
|
|
|
|
|
|
|
|
|
class LsofFdLeakChecker(object):
|
2018-05-23 22:48:46 +08:00
|
|
|
|
2015-04-28 17:54:53 +08:00
|
|
|
def get_open_files(self):
|
|
|
|
out = self._exec_lsof()
|
|
|
|
open_files = self._parse_lsof_output(out)
|
|
|
|
return open_files
|
|
|
|
|
|
|
|
def _exec_lsof(self):
|
|
|
|
pid = os.getpid()
|
|
|
|
return py.process.cmdexec("lsof -Ffn0 -p %d" % pid)
|
|
|
|
|
|
|
|
def _parse_lsof_output(self, out):
|
2018-05-23 22:48:46 +08:00
|
|
|
|
2015-04-28 17:54:53 +08:00
|
|
|
def isopen(line):
|
2018-05-23 22:48:46 +08:00
|
|
|
return line.startswith("f") and (
|
|
|
|
"deleted" not in line
|
|
|
|
and "mem" not in line
|
|
|
|
and "txt" not in line
|
|
|
|
and "cwd" not in line
|
|
|
|
)
|
2015-04-28 17:54:53 +08:00
|
|
|
|
|
|
|
open_files = []
|
|
|
|
|
|
|
|
for line in out.split("\n"):
|
|
|
|
if isopen(line):
|
2018-05-23 22:48:46 +08:00
|
|
|
fields = line.split("\0")
|
2015-04-28 17:54:53 +08:00
|
|
|
fd = fields[0][1:]
|
|
|
|
filename = fields[1][1:]
|
2017-09-17 03:20:04 +08:00
|
|
|
if filename in IGNORE_PAM:
|
|
|
|
continue
|
2018-05-23 22:48:46 +08:00
|
|
|
if filename.startswith("/"):
|
2015-04-28 17:54:53 +08:00
|
|
|
open_files.append((fd, filename))
|
|
|
|
|
|
|
|
return open_files
|
|
|
|
|
|
|
|
def matching_platform(self):
|
|
|
|
try:
|
|
|
|
py.process.cmdexec("lsof -v")
|
2015-07-25 06:21:57 +08:00
|
|
|
except (py.process.cmdexec.Error, UnicodeDecodeError):
|
2017-12-01 20:21:06 +08:00
|
|
|
# cmdexec may raise UnicodeDecodeError on Windows systems with
|
|
|
|
# locale other than English:
|
2015-07-25 06:21:57 +08:00
|
|
|
# https://bitbucket.org/pytest-dev/py/issues/66
|
2015-04-28 17:54:53 +08:00
|
|
|
return False
|
|
|
|
else:
|
|
|
|
return True
|
|
|
|
|
2015-05-06 16:08:08 +08:00
|
|
|
@pytest.hookimpl(hookwrapper=True, tryfirst=True)
|
2017-04-12 08:53:01 +08:00
|
|
|
def pytest_runtest_protocol(self, item):
|
2015-04-28 17:54:53 +08:00
|
|
|
lines1 = self.get_open_files()
|
|
|
|
yield
|
|
|
|
if hasattr(sys, "pypy_version_info"):
|
|
|
|
gc.collect()
|
|
|
|
lines2 = self.get_open_files()
|
|
|
|
|
2018-05-18 05:31:16 +08:00
|
|
|
new_fds = {t[0] for t in lines2} - {t[0] for t in lines1}
|
2015-04-28 17:54:53 +08:00
|
|
|
leaked_files = [t for t in lines2 if t[0] in new_fds]
|
|
|
|
if leaked_files:
|
|
|
|
error = []
|
|
|
|
error.append("***** %s FD leakage detected" % len(leaked_files))
|
|
|
|
error.extend([str(f) for f in leaked_files])
|
|
|
|
error.append("*** Before:")
|
|
|
|
error.extend([str(f) for f in lines1])
|
|
|
|
error.append("*** After:")
|
|
|
|
error.extend([str(f) for f in lines2])
|
|
|
|
error.append(error[0])
|
|
|
|
error.append("*** function %s:%s: %s " % item.location)
|
2017-04-14 04:34:48 +08:00
|
|
|
error.append("See issue #2366")
|
2018-05-23 22:48:46 +08:00
|
|
|
item.warn("", "\n".join(error))
|
2015-04-28 17:54:53 +08:00
|
|
|
|
|
|
|
|
|
|
|
# XXX copied from execnet's conftest.py - needs to be merged
|
|
|
|
winpymap = {
|
2018-05-23 22:48:46 +08:00
|
|
|
"python2.7": r"C:\Python27\python.exe",
|
|
|
|
"python3.4": r"C:\Python34\python.exe",
|
|
|
|
"python3.5": r"C:\Python35\python.exe",
|
|
|
|
"python3.6": r"C:\Python36\python.exe",
|
2015-04-28 17:54:53 +08:00
|
|
|
}
|
|
|
|
|
2017-07-17 07:25:09 +08:00
|
|
|
|
2015-04-28 17:54:53 +08:00
|
|
|
def getexecutable(name, cache={}):
|
|
|
|
try:
|
|
|
|
return cache[name]
|
|
|
|
except KeyError:
|
|
|
|
executable = py.path.local.sysfind(name)
|
|
|
|
if executable:
|
2016-06-21 14:36:02 +08:00
|
|
|
import subprocess
|
2018-05-23 22:48:46 +08:00
|
|
|
|
|
|
|
popen = subprocess.Popen(
|
|
|
|
[str(executable), "--version"],
|
|
|
|
universal_newlines=True,
|
|
|
|
stderr=subprocess.PIPE,
|
|
|
|
)
|
2016-06-21 14:36:02 +08:00
|
|
|
out, err = popen.communicate()
|
2015-04-28 17:54:53 +08:00
|
|
|
if name == "jython":
|
|
|
|
if not err or "2.5" not in err:
|
|
|
|
executable = None
|
|
|
|
if "2.5.2" in err:
|
2017-07-17 07:25:09 +08:00
|
|
|
executable = None # http://bugs.jython.org/issue1790
|
2016-06-21 14:36:02 +08:00
|
|
|
elif popen.returncode != 0:
|
2017-12-01 20:21:06 +08:00
|
|
|
# handle pyenv's 127
|
2016-06-21 14:36:02 +08:00
|
|
|
executable = None
|
2015-04-28 17:54:53 +08:00
|
|
|
cache[name] = executable
|
|
|
|
return executable
|
|
|
|
|
2017-07-17 07:25:09 +08:00
|
|
|
|
2018-05-23 22:48:46 +08:00
|
|
|
@pytest.fixture(params=["python2.7", "python3.4", "pypy", "pypy3"])
|
2015-04-28 17:54:53 +08:00
|
|
|
def anypython(request):
|
|
|
|
name = request.param
|
|
|
|
executable = getexecutable(name)
|
|
|
|
if executable is None:
|
|
|
|
if sys.platform == "win32":
|
|
|
|
executable = winpymap.get(name, None)
|
|
|
|
if executable:
|
|
|
|
executable = py.path.local(executable)
|
|
|
|
if executable.check():
|
|
|
|
return executable
|
|
|
|
pytest.skip("no suitable %s found" % (name,))
|
|
|
|
return executable
|
|
|
|
|
2018-05-23 22:48:46 +08:00
|
|
|
|
2015-04-22 23:06:00 +08:00
|
|
|
# used at least by pytest-xdist plugin
|
2017-07-17 07:25:09 +08:00
|
|
|
|
|
|
|
|
2015-04-23 03:04:36 +08:00
|
|
|
@pytest.fixture
|
|
|
|
def _pytest(request):
|
2017-12-01 20:21:06 +08:00
|
|
|
"""Return a helper which offers a gethookrecorder(hook) method which
|
|
|
|
returns a HookRecorder instance which helps to make assertions about called
|
|
|
|
hooks.
|
|
|
|
|
2015-04-23 03:04:36 +08:00
|
|
|
"""
|
2015-04-22 23:06:00 +08:00
|
|
|
return PytestArg(request)
|
|
|
|
|
2017-07-17 07:25:09 +08:00
|
|
|
|
2018-01-25 04:23:42 +08:00
|
|
|
class PytestArg(object):
|
2018-05-23 22:48:46 +08:00
|
|
|
|
2015-04-22 23:06:00 +08:00
|
|
|
def __init__(self, request):
|
|
|
|
self.request = request
|
|
|
|
|
|
|
|
def gethookrecorder(self, hook):
|
|
|
|
hookrecorder = HookRecorder(hook._pm)
|
|
|
|
self.request.addfinalizer(hookrecorder.finish_recording)
|
|
|
|
return hookrecorder
|
|
|
|
|
2013-08-02 05:48:40 +08:00
|
|
|
|
2017-11-04 23:17:20 +08:00
|
|
|
def get_public_names(values):
|
|
|
|
"""Only return names from iterator values without a leading underscore."""
|
|
|
|
return [x for x in values if x[0] != "_"]
|
2013-08-02 05:48:40 +08:00
|
|
|
|
|
|
|
|
2018-01-25 04:23:42 +08:00
|
|
|
class ParsedCall(object):
|
2018-05-23 22:48:46 +08:00
|
|
|
|
2014-10-04 21:49:31 +08:00
|
|
|
def __init__(self, name, kwargs):
|
|
|
|
self.__dict__.update(kwargs)
|
2010-10-12 19:10:39 +08:00
|
|
|
self._name = name
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
d = self.__dict__.copy()
|
2018-05-23 22:48:46 +08:00
|
|
|
del d["_name"]
|
2017-07-17 07:25:08 +08:00
|
|
|
return "<ParsedCall %r(**%r)>" % (self._name, d)
|
2010-10-12 19:10:39 +08:00
|
|
|
|
2014-10-04 21:49:31 +08:00
|
|
|
|
2018-01-25 04:23:42 +08:00
|
|
|
class HookRecorder(object):
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Record all hooks called in a plugin manager.
|
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
This wraps all the hook calls in the plugin manager, recording each call
|
|
|
|
before propagating the normal calls.
|
2015-04-12 00:07:37 +08:00
|
|
|
|
|
|
|
"""
|
|
|
|
|
2010-10-13 17:12:27 +08:00
|
|
|
def __init__(self, pluginmanager):
|
|
|
|
self._pluginmanager = pluginmanager
|
2010-10-12 19:10:39 +08:00
|
|
|
self.calls = []
|
2014-10-06 19:37:57 +08:00
|
|
|
|
2015-05-07 17:02:55 +08:00
|
|
|
def before(hook_name, hook_impls, kwargs):
|
|
|
|
self.calls.append(ParsedCall(hook_name, kwargs))
|
|
|
|
|
|
|
|
def after(outcome, hook_name, hook_impls, kwargs):
|
2015-04-26 00:15:39 +08:00
|
|
|
pass
|
2015-05-07 17:02:55 +08:00
|
|
|
|
|
|
|
self._undo_wrapping = pluginmanager.add_hookcall_monitoring(before, after)
|
2010-10-12 19:10:39 +08:00
|
|
|
|
|
|
|
def finish_recording(self):
|
2014-10-06 19:37:57 +08:00
|
|
|
self._undo_wrapping()
|
2010-10-12 19:10:39 +08:00
|
|
|
|
|
|
|
def getcalls(self, names):
|
|
|
|
if isinstance(names, str):
|
|
|
|
names = names.split()
|
2014-10-04 21:49:31 +08:00
|
|
|
return [call for call in self.calls if call._name in names]
|
2010-10-12 19:10:39 +08:00
|
|
|
|
2014-10-06 19:37:57 +08:00
|
|
|
def assert_contains(self, entries):
|
2010-11-06 16:58:04 +08:00
|
|
|
__tracebackhide__ = True
|
2010-10-12 19:10:39 +08:00
|
|
|
i = 0
|
|
|
|
entries = list(entries)
|
2014-08-01 06:13:40 +08:00
|
|
|
backlocals = sys._getframe(1).f_locals
|
2010-10-12 19:10:39 +08:00
|
|
|
while entries:
|
|
|
|
name, check = entries.pop(0)
|
|
|
|
for ind, call in enumerate(self.calls[i:]):
|
|
|
|
if call._name == name:
|
2017-03-17 09:27:28 +08:00
|
|
|
print("NAMEMATCH", name, call)
|
2010-10-12 19:10:39 +08:00
|
|
|
if eval(check, backlocals, call.__dict__):
|
2017-03-17 09:27:28 +08:00
|
|
|
print("CHECKERMATCH", repr(check), "->", call)
|
2010-10-12 19:10:39 +08:00
|
|
|
else:
|
2017-03-17 09:27:28 +08:00
|
|
|
print("NOCHECKERMATCH", repr(check), "-", call)
|
2010-10-12 19:10:39 +08:00
|
|
|
continue
|
|
|
|
i += ind + 1
|
|
|
|
break
|
2017-03-17 09:27:28 +08:00
|
|
|
print("NONAMEMATCH", name, "with", call)
|
2010-10-12 19:10:39 +08:00
|
|
|
else:
|
2014-01-18 19:31:33 +08:00
|
|
|
pytest.fail("could not find %r check %r" % (name, check))
|
2010-10-12 19:10:39 +08:00
|
|
|
|
|
|
|
def popcall(self, name):
|
2010-11-22 22:20:18 +08:00
|
|
|
__tracebackhide__ = True
|
2010-10-12 19:10:39 +08:00
|
|
|
for i, call in enumerate(self.calls):
|
|
|
|
if call._name == name:
|
|
|
|
del self.calls[i]
|
|
|
|
return call
|
2010-11-22 22:20:18 +08:00
|
|
|
lines = ["could not find call %r, in:" % (name,)]
|
|
|
|
lines.extend([" %s" % str(x) for x in self.calls])
|
2014-01-18 19:31:33 +08:00
|
|
|
pytest.fail("\n".join(lines))
|
2010-10-12 19:10:39 +08:00
|
|
|
|
|
|
|
def getcall(self, name):
|
2017-11-04 23:17:20 +08:00
|
|
|
values = self.getcalls(name)
|
|
|
|
assert len(values) == 1, (name, values)
|
|
|
|
return values[0]
|
2010-10-12 19:10:39 +08:00
|
|
|
|
2014-10-06 19:37:57 +08:00
|
|
|
# functionality for test reports
|
|
|
|
|
2018-05-23 22:48:46 +08:00
|
|
|
def getreports(self, names="pytest_runtest_logreport pytest_collectreport"):
|
2014-10-06 19:37:57 +08:00
|
|
|
return [x.report for x in self.getcalls(names)]
|
|
|
|
|
2018-05-23 22:48:46 +08:00
|
|
|
def matchreport(
|
|
|
|
self,
|
|
|
|
inamepart="",
|
|
|
|
names="pytest_runtest_logreport pytest_collectreport",
|
|
|
|
when=None,
|
|
|
|
):
|
2017-12-01 20:21:06 +08:00
|
|
|
"""return a testreport whose dotted import path matches"""
|
2017-11-04 23:17:20 +08:00
|
|
|
values = []
|
2014-10-06 19:37:57 +08:00
|
|
|
for rep in self.getreports(names=names):
|
|
|
|
try:
|
|
|
|
if not when and rep.when != "call" and rep.passed:
|
|
|
|
# setup/teardown passing reports - let's ignore those
|
|
|
|
continue
|
|
|
|
except AttributeError:
|
|
|
|
pass
|
2018-05-23 22:48:46 +08:00
|
|
|
if when and getattr(rep, "when", None) != when:
|
2014-10-06 19:37:57 +08:00
|
|
|
continue
|
|
|
|
if not inamepart or inamepart in rep.nodeid.split("::"):
|
2017-11-04 23:17:20 +08:00
|
|
|
values.append(rep)
|
|
|
|
if not values:
|
2018-05-23 22:48:46 +08:00
|
|
|
raise ValueError(
|
|
|
|
"could not find test report matching %r: "
|
|
|
|
"no test reports at all!" % (inamepart,)
|
|
|
|
)
|
2017-11-04 23:17:20 +08:00
|
|
|
if len(values) > 1:
|
2014-10-06 19:37:57 +08:00
|
|
|
raise ValueError(
|
2018-05-23 22:48:46 +08:00
|
|
|
"found 2 or more testreports matching %r: %s" % (inamepart, values)
|
|
|
|
)
|
2017-11-04 23:17:20 +08:00
|
|
|
return values[0]
|
2014-10-06 19:37:57 +08:00
|
|
|
|
2018-05-23 22:48:46 +08:00
|
|
|
def getfailures(self, names="pytest_runtest_logreport pytest_collectreport"):
|
2014-10-06 19:37:57 +08:00
|
|
|
return [rep for rep in self.getreports(names) if rep.failed]
|
|
|
|
|
|
|
|
def getfailedcollections(self):
|
2018-05-23 22:48:46 +08:00
|
|
|
return self.getfailures("pytest_collectreport")
|
2014-10-06 19:37:57 +08:00
|
|
|
|
|
|
|
def listoutcomes(self):
|
|
|
|
passed = []
|
|
|
|
skipped = []
|
|
|
|
failed = []
|
2018-05-23 22:48:46 +08:00
|
|
|
for rep in self.getreports("pytest_collectreport pytest_runtest_logreport"):
|
2014-10-06 19:37:57 +08:00
|
|
|
if rep.passed:
|
|
|
|
if getattr(rep, "when", None) == "call":
|
|
|
|
passed.append(rep)
|
|
|
|
elif rep.skipped:
|
|
|
|
skipped.append(rep)
|
|
|
|
elif rep.failed:
|
|
|
|
failed.append(rep)
|
|
|
|
return passed, skipped, failed
|
|
|
|
|
|
|
|
def countoutcomes(self):
|
|
|
|
return [len(x) for x in self.listoutcomes()]
|
|
|
|
|
|
|
|
def assertoutcome(self, passed=0, skipped=0, failed=0):
|
|
|
|
realpassed, realskipped, realfailed = self.listoutcomes()
|
|
|
|
assert passed == len(realpassed)
|
|
|
|
assert skipped == len(realskipped)
|
|
|
|
assert failed == len(realfailed)
|
|
|
|
|
|
|
|
def clear(self):
|
|
|
|
self.calls[:] = []
|
|
|
|
|
2009-05-20 01:25:21 +08:00
|
|
|
|
2015-07-16 07:03:58 +08:00
|
|
|
@pytest.fixture
|
|
|
|
def linecomp(request):
|
2009-05-19 05:26:16 +08:00
|
|
|
return LineComp()
|
2009-04-09 07:33:48 +08:00
|
|
|
|
2015-07-16 07:03:58 +08:00
|
|
|
|
2018-05-23 22:48:46 +08:00
|
|
|
@pytest.fixture(name="LineMatcher")
|
2016-07-12 09:03:53 +08:00
|
|
|
def LineMatcher_fixture(request):
|
2009-05-19 05:26:16 +08:00
|
|
|
return LineMatcher
|
2009-02-27 18:18:27 +08:00
|
|
|
|
|
|
|
|
2015-07-16 07:03:58 +08:00
|
|
|
@pytest.fixture
|
|
|
|
def testdir(request, tmpdir_factory):
|
|
|
|
return Testdir(request, tmpdir_factory)
|
2015-04-28 17:54:45 +08:00
|
|
|
|
|
|
|
|
2017-02-15 22:54:53 +08:00
|
|
|
rex_outcome = re.compile(r"(\d+) ([\w-]+)")
|
2017-07-17 07:25:09 +08:00
|
|
|
|
|
|
|
|
2018-01-25 04:23:42 +08:00
|
|
|
class RunResult(object):
|
2015-04-12 00:07:37 +08:00
|
|
|
"""The result of running a command.
|
|
|
|
|
|
|
|
Attributes:
|
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
:ret: the return value
|
|
|
|
:outlines: list of lines captured from stdout
|
|
|
|
:errlines: list of lines captures from stderr
|
2015-04-28 17:54:53 +08:00
|
|
|
:stdout: :py:class:`LineMatcher` of stdout, use ``stdout.str()`` to
|
2017-12-01 20:21:06 +08:00
|
|
|
reconstruct stdout or the commonly used ``stdout.fnmatch_lines()``
|
|
|
|
method
|
2017-12-13 09:39:10 +08:00
|
|
|
:stderr: :py:class:`LineMatcher` of stderr
|
2017-12-01 20:21:06 +08:00
|
|
|
:duration: duration in seconds
|
2015-04-12 00:07:37 +08:00
|
|
|
|
|
|
|
"""
|
2017-07-17 07:25:09 +08:00
|
|
|
|
2009-12-30 18:37:46 +08:00
|
|
|
def __init__(self, ret, outlines, errlines, duration):
|
2009-02-27 18:18:27 +08:00
|
|
|
self.ret = ret
|
|
|
|
self.outlines = outlines
|
|
|
|
self.errlines = errlines
|
|
|
|
self.stdout = LineMatcher(outlines)
|
|
|
|
self.stderr = LineMatcher(errlines)
|
2009-12-30 18:37:46 +08:00
|
|
|
self.duration = duration
|
|
|
|
|
2009-12-25 07:24:58 +08:00
|
|
|
def parseoutcomes(self):
|
2017-12-01 20:21:06 +08:00
|
|
|
"""Return a dictionary of outcomestring->num from parsing the terminal
|
|
|
|
output that the test process produced.
|
|
|
|
|
|
|
|
"""
|
2009-12-25 07:24:58 +08:00
|
|
|
for line in reversed(self.outlines):
|
2018-05-23 22:48:46 +08:00
|
|
|
if "seconds" in line:
|
2009-12-25 07:24:58 +08:00
|
|
|
outcomes = rex_outcome.findall(line)
|
|
|
|
if outcomes:
|
|
|
|
d = {}
|
|
|
|
for num, cat in outcomes:
|
|
|
|
d[cat] = int(num)
|
|
|
|
return d
|
2017-01-11 22:49:09 +08:00
|
|
|
raise ValueError("Pytest terminal report not found")
|
2009-02-27 18:18:27 +08:00
|
|
|
|
2017-08-02 07:49:07 +08:00
|
|
|
def assert_outcomes(self, passed=0, skipped=0, failed=0, error=0):
|
2017-12-01 20:21:06 +08:00
|
|
|
"""Assert that the specified outcomes appear with the respective
|
|
|
|
numbers (0 means it didn't occur) in the text output from a test run.
|
|
|
|
|
|
|
|
"""
|
2015-04-27 21:06:47 +08:00
|
|
|
d = self.parseoutcomes()
|
2017-08-02 07:49:07 +08:00
|
|
|
obtained = {
|
2018-05-23 22:48:46 +08:00
|
|
|
"passed": d.get("passed", 0),
|
|
|
|
"skipped": d.get("skipped", 0),
|
|
|
|
"failed": d.get("failed", 0),
|
|
|
|
"error": d.get("error", 0),
|
2017-08-02 07:49:07 +08:00
|
|
|
}
|
2018-05-23 22:48:46 +08:00
|
|
|
assert (
|
|
|
|
obtained == dict(passed=passed, skipped=skipped, failed=failed, error=error)
|
|
|
|
)
|
2015-04-27 21:06:47 +08:00
|
|
|
|
|
|
|
|
2018-01-25 04:23:42 +08:00
|
|
|
class CwdSnapshot(object):
|
2018-05-23 22:48:46 +08:00
|
|
|
|
2017-12-01 21:52:20 +08:00
|
|
|
def __init__(self):
|
|
|
|
self.__saved = os.getcwd()
|
|
|
|
|
|
|
|
def restore(self):
|
|
|
|
os.chdir(self.__saved)
|
|
|
|
|
|
|
|
|
2018-01-25 04:23:42 +08:00
|
|
|
class SysModulesSnapshot(object):
|
2018-05-23 22:48:46 +08:00
|
|
|
|
2017-12-01 21:52:20 +08:00
|
|
|
def __init__(self, preserve=None):
|
|
|
|
self.__preserve = preserve
|
|
|
|
self.__saved = dict(sys.modules)
|
|
|
|
|
|
|
|
def restore(self):
|
|
|
|
if self.__preserve:
|
|
|
|
self.__saved.update(
|
2018-05-23 22:48:46 +08:00
|
|
|
(k, m) for k, m in sys.modules.items() if self.__preserve(k)
|
|
|
|
)
|
2017-12-01 21:52:20 +08:00
|
|
|
sys.modules.clear()
|
|
|
|
sys.modules.update(self.__saved)
|
|
|
|
|
|
|
|
|
2018-01-25 04:23:42 +08:00
|
|
|
class SysPathsSnapshot(object):
|
2018-05-23 22:48:46 +08:00
|
|
|
|
2017-12-01 21:52:20 +08:00
|
|
|
def __init__(self):
|
|
|
|
self.__saved = list(sys.path), list(sys.meta_path)
|
|
|
|
|
|
|
|
def restore(self):
|
|
|
|
sys.path[:], sys.meta_path[:] = self.__saved
|
|
|
|
|
|
|
|
|
2018-01-25 04:23:42 +08:00
|
|
|
class Testdir(object):
|
2016-06-21 22:16:57 +08:00
|
|
|
"""Temporary test directory with tools to test/run pytest itself.
|
2015-04-12 00:07:37 +08:00
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
This is based on the ``tmpdir`` fixture but provides a number of methods
|
|
|
|
which aid with testing pytest itself. Unless :py:meth:`chdir` is used all
|
|
|
|
methods will use :py:attr:`tmpdir` as their current working directory.
|
2015-04-12 00:07:37 +08:00
|
|
|
|
|
|
|
Attributes:
|
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
:tmpdir: The :py:class:`py.path.local` instance of the temporary directory.
|
2015-04-12 00:07:37 +08:00
|
|
|
|
|
|
|
:plugins: A list of plugins to use with :py:meth:`parseconfig` and
|
2017-12-01 20:21:06 +08:00
|
|
|
:py:meth:`runpytest`. Initially this is an empty list but plugins can
|
|
|
|
be added to the list. The type of items to add to the list depends on
|
|
|
|
the method using them so refer to them for details.
|
2015-04-12 00:07:37 +08:00
|
|
|
|
|
|
|
"""
|
|
|
|
|
2015-07-16 07:03:58 +08:00
|
|
|
def __init__(self, request, tmpdir_factory):
|
2009-04-15 00:30:26 +08:00
|
|
|
self.request = request
|
2017-07-17 07:25:08 +08:00
|
|
|
self._mod_collections = WeakKeyDictionary()
|
2009-04-15 01:57:00 +08:00
|
|
|
name = request.function.__name__
|
2017-09-06 02:22:04 +08:00
|
|
|
self.tmpdir = tmpdir_factory.mktemp(name, numbered=True)
|
2009-02-27 18:18:27 +08:00
|
|
|
self.plugins = []
|
2017-12-01 21:52:20 +08:00
|
|
|
self._cwd_snapshot = CwdSnapshot()
|
|
|
|
self._sys_path_snapshot = SysPathsSnapshot()
|
|
|
|
self._sys_modules_snapshot = self.__take_sys_modules_snapshot()
|
|
|
|
self.chdir()
|
2009-04-15 00:30:26 +08:00
|
|
|
self.request.addfinalizer(self.finalize)
|
2015-04-28 17:54:53 +08:00
|
|
|
method = self.request.config.getoption("--runpytest")
|
|
|
|
if method == "inprocess":
|
|
|
|
self._runpytest_method = self.runpytest_inprocess
|
|
|
|
elif method == "subprocess":
|
|
|
|
self._runpytest_method = self.runpytest_subprocess
|
2009-04-01 01:58:02 +08:00
|
|
|
|
|
|
|
def __repr__(self):
|
2015-04-28 17:54:53 +08:00
|
|
|
return "<Testdir %r>" % (self.tmpdir,)
|
2009-03-01 21:43:53 +08:00
|
|
|
|
2009-02-27 18:18:27 +08:00
|
|
|
def finalize(self):
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Clean up global state artifacts.
|
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
Some methods modify the global interpreter state and this tries to
|
|
|
|
clean this up. It does not remove the temporary directory however so
|
|
|
|
it can be looked at after the test run has finished.
|
2015-04-12 00:07:37 +08:00
|
|
|
|
|
|
|
"""
|
2017-12-01 21:52:20 +08:00
|
|
|
self._sys_modules_snapshot.restore()
|
|
|
|
self._sys_path_snapshot.restore()
|
|
|
|
self._cwd_snapshot.restore()
|
|
|
|
|
|
|
|
def __take_sys_modules_snapshot(self):
|
|
|
|
# some zope modules used by twisted-related tests keep internal state
|
|
|
|
# and can't be deleted; we had some trouble in the past with
|
|
|
|
# `zope.interface` for example
|
|
|
|
def preserve_module(name):
|
|
|
|
return name.startswith("zope")
|
2018-05-23 22:48:46 +08:00
|
|
|
|
2017-12-01 21:52:20 +08:00
|
|
|
return SysModulesSnapshot(preserve=preserve_module)
|
2015-04-21 10:18:04 +08:00
|
|
|
|
2014-10-06 19:37:57 +08:00
|
|
|
def make_hook_recorder(self, pluginmanager):
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Create a new :py:class:`HookRecorder` for a PluginManager."""
|
2014-10-06 19:37:57 +08:00
|
|
|
assert not hasattr(pluginmanager, "reprec")
|
|
|
|
pluginmanager.reprec = reprec = HookRecorder(pluginmanager)
|
|
|
|
self.request.addfinalizer(reprec.finish_recording)
|
2009-05-21 15:45:43 +08:00
|
|
|
return reprec
|
2009-04-05 03:06:20 +08:00
|
|
|
|
2009-02-27 18:18:27 +08:00
|
|
|
def chdir(self):
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Cd into the temporary directory.
|
|
|
|
|
|
|
|
This is done automatically upon instantiation.
|
|
|
|
|
|
|
|
"""
|
2017-12-01 21:52:20 +08:00
|
|
|
self.tmpdir.chdir()
|
2009-02-27 18:18:27 +08:00
|
|
|
|
2018-05-23 22:48:46 +08:00
|
|
|
def _makefile(self, ext, args, kwargs, encoding="utf-8"):
|
2009-08-29 01:16:15 +08:00
|
|
|
items = list(kwargs.items())
|
2017-09-01 04:40:05 +08:00
|
|
|
|
|
|
|
def to_text(s):
|
|
|
|
return s.decode(encoding) if isinstance(s, bytes) else six.text_type(s)
|
|
|
|
|
2009-02-27 18:18:27 +08:00
|
|
|
if args:
|
2017-09-01 04:40:05 +08:00
|
|
|
source = u"\n".join(to_text(x) for x in args)
|
2009-04-15 01:57:00 +08:00
|
|
|
basename = self.request.function.__name__
|
2009-02-27 18:18:27 +08:00
|
|
|
items.insert(0, (basename, source))
|
2017-09-01 04:40:05 +08:00
|
|
|
|
2009-02-27 18:18:27 +08:00
|
|
|
ret = None
|
2017-09-01 04:40:05 +08:00
|
|
|
for basename, value in items:
|
|
|
|
p = self.tmpdir.join(basename).new(ext=ext)
|
2016-11-21 22:50:21 +08:00
|
|
|
p.dirpath().ensure_dir()
|
2015-11-27 22:43:01 +08:00
|
|
|
source = Source(value)
|
2017-09-01 04:40:05 +08:00
|
|
|
source = u"\n".join(to_text(line) for line in source.lines)
|
|
|
|
p.write(source.strip().encode(encoding), "wb")
|
2009-02-27 18:18:27 +08:00
|
|
|
if ret is None:
|
|
|
|
ret = p
|
2010-07-27 03:15:15 +08:00
|
|
|
return ret
|
2009-02-27 18:18:27 +08:00
|
|
|
|
|
|
|
def makefile(self, ext, *args, **kwargs):
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Create a new file in the testdir.
|
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
ext: The extension the file should use, including the dot, e.g. `.py`.
|
2015-04-12 00:07:37 +08:00
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
args: All args will be treated as strings and joined using newlines.
|
|
|
|
The result will be written as contents to the file. The name of the
|
|
|
|
file will be based on the test function requesting this fixture.
|
2015-04-12 00:07:37 +08:00
|
|
|
E.g. "testdir.makefile('.txt', 'line1', 'line2')"
|
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
kwargs: Each keyword is the name of a file, while the value of it will
|
|
|
|
be written as contents of the file.
|
2015-04-12 00:07:37 +08:00
|
|
|
E.g. "testdir.makefile('.ini', pytest='[pytest]\naddopts=-rs\n')"
|
|
|
|
|
|
|
|
"""
|
2009-02-27 18:18:27 +08:00
|
|
|
return self._makefile(ext, args, kwargs)
|
|
|
|
|
|
|
|
def makeconftest(self, source):
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Write a contest.py file with 'source' as contents."""
|
2009-02-27 18:18:27 +08:00
|
|
|
return self.makepyfile(conftest=source)
|
|
|
|
|
2010-11-01 00:41:58 +08:00
|
|
|
def makeini(self, source):
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Write a tox.ini file with 'source' as contents."""
|
2018-05-23 22:48:46 +08:00
|
|
|
return self.makefile(".ini", tox=source)
|
2010-11-01 00:41:58 +08:00
|
|
|
|
|
|
|
def getinicfg(self, source):
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Return the pytest section from the tox.ini config file."""
|
2010-11-01 00:41:58 +08:00
|
|
|
p = self.makeini(source)
|
2018-05-23 22:48:46 +08:00
|
|
|
return py.iniconfig.IniConfig(p)["pytest"]
|
2010-11-01 00:41:58 +08:00
|
|
|
|
2009-02-27 18:18:27 +08:00
|
|
|
def makepyfile(self, *args, **kwargs):
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Shortcut for .makefile() with a .py extension."""
|
2018-05-23 22:48:46 +08:00
|
|
|
return self._makefile(".py", args, kwargs)
|
2009-02-27 18:18:27 +08:00
|
|
|
|
|
|
|
def maketxtfile(self, *args, **kwargs):
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Shortcut for .makefile() with a .txt extension."""
|
2018-05-23 22:48:46 +08:00
|
|
|
return self._makefile(".txt", args, kwargs)
|
2009-02-27 18:18:27 +08:00
|
|
|
|
|
|
|
def syspathinsert(self, path=None):
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Prepend a directory to sys.path, defaults to :py:attr:`tmpdir`.
|
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
This is undone automatically when this object dies at the end of each
|
|
|
|
test.
|
|
|
|
|
2015-04-12 00:07:37 +08:00
|
|
|
"""
|
2009-02-27 18:18:27 +08:00
|
|
|
if path is None:
|
|
|
|
path = self.tmpdir
|
2014-08-01 06:13:40 +08:00
|
|
|
sys.path.insert(0, str(path))
|
2017-12-01 20:21:06 +08:00
|
|
|
# a call to syspathinsert() usually means that the caller wants to
|
|
|
|
# import some dynamically created files, thus with python3 we
|
|
|
|
# invalidate its import caches
|
2015-09-29 19:10:59 +08:00
|
|
|
self._possibly_invalidate_import_caches()
|
|
|
|
|
|
|
|
def _possibly_invalidate_import_caches(self):
|
|
|
|
# invalidate caches if we can (py33 and above)
|
|
|
|
try:
|
|
|
|
import importlib
|
|
|
|
except ImportError:
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
if hasattr(importlib, "invalidate_caches"):
|
|
|
|
importlib.invalidate_caches()
|
2010-07-27 03:15:15 +08:00
|
|
|
|
2009-02-27 18:18:27 +08:00
|
|
|
def mkdir(self, name):
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Create a new (sub)directory."""
|
2009-02-27 18:18:27 +08:00
|
|
|
return self.tmpdir.mkdir(name)
|
2009-07-30 15:52:12 +08:00
|
|
|
|
|
|
|
def mkpydir(self, name):
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Create a new python package.
|
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
This creates a (sub)directory with an empty ``__init__.py`` file so it
|
|
|
|
gets recognised as a python package.
|
2015-04-12 00:07:37 +08:00
|
|
|
|
|
|
|
"""
|
2009-07-30 15:52:12 +08:00
|
|
|
p = self.mkdir(name)
|
|
|
|
p.ensure("__init__.py")
|
|
|
|
return p
|
|
|
|
|
2010-11-07 17:19:58 +08:00
|
|
|
Session = Session
|
2017-07-17 07:25:09 +08:00
|
|
|
|
2010-09-15 16:30:50 +08:00
|
|
|
def getnode(self, config, arg):
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Return the collection node of a file.
|
|
|
|
|
|
|
|
:param config: :py:class:`_pytest.config.Config` instance, see
|
2017-12-01 20:21:06 +08:00
|
|
|
:py:meth:`parseconfig` and :py:meth:`parseconfigure` to create the
|
|
|
|
configuration
|
2015-04-12 00:07:37 +08:00
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
:param arg: a :py:class:`py.path.local` instance of the file
|
2015-04-12 00:07:37 +08:00
|
|
|
|
|
|
|
"""
|
2010-11-07 17:19:58 +08:00
|
|
|
session = Session(config)
|
2018-05-23 22:48:46 +08:00
|
|
|
assert "::" not in str(arg)
|
2010-11-06 16:58:04 +08:00
|
|
|
p = py.path.local(arg)
|
2011-05-27 06:08:44 +08:00
|
|
|
config.hook.pytest_sessionstart(session=session)
|
2015-02-27 04:56:44 +08:00
|
|
|
res = session.perform_collect([str(p)], genitems=False)[0]
|
2011-05-27 06:08:44 +08:00
|
|
|
config.hook.pytest_sessionfinish(session=session, exitstatus=EXIT_OK)
|
|
|
|
return res
|
2010-11-06 16:58:04 +08:00
|
|
|
|
|
|
|
def getpathnode(self, path):
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Return the collection node of a file.
|
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
This is like :py:meth:`getnode` but uses :py:meth:`parseconfigure` to
|
|
|
|
create the (configured) pytest Config instance.
|
2015-04-12 00:07:37 +08:00
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
:param path: a :py:class:`py.path.local` instance of the file
|
2015-04-12 00:07:37 +08:00
|
|
|
|
|
|
|
"""
|
2011-05-27 07:37:04 +08:00
|
|
|
config = self.parseconfigure(path)
|
2010-11-07 17:19:58 +08:00
|
|
|
session = Session(config)
|
|
|
|
x = session.fspath.bestrelpath(path)
|
2011-05-27 06:08:44 +08:00
|
|
|
config.hook.pytest_sessionstart(session=session)
|
|
|
|
res = session.perform_collect([x], genitems=False)[0]
|
|
|
|
config.hook.pytest_sessionfinish(session=session, exitstatus=EXIT_OK)
|
|
|
|
return res
|
2010-09-15 16:30:50 +08:00
|
|
|
|
2009-02-27 18:18:27 +08:00
|
|
|
def genitems(self, colitems):
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Generate all test items from a collection node.
|
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
This recurses into the collection node and returns a list of all the
|
|
|
|
test items contained within.
|
2015-04-12 00:07:37 +08:00
|
|
|
|
|
|
|
"""
|
2010-11-07 17:19:58 +08:00
|
|
|
session = colitems[0].session
|
2010-09-15 16:30:50 +08:00
|
|
|
result = []
|
2010-10-26 05:08:41 +08:00
|
|
|
for colitem in colitems:
|
2010-11-07 17:19:58 +08:00
|
|
|
result.extend(session.genitems(colitem))
|
2010-09-15 16:30:50 +08:00
|
|
|
return result
|
2009-02-27 18:18:27 +08:00
|
|
|
|
2009-05-23 01:57:21 +08:00
|
|
|
def runitem(self, source):
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Run the "test_func" Item.
|
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
The calling test instance (class containing the test method) must
|
|
|
|
provide a ``.getrunner()`` method which should return a runner which
|
|
|
|
can run the test protocol for a single item, e.g.
|
|
|
|
:py:func:`_pytest.runner.runtestprotocol`.
|
2015-04-12 00:07:37 +08:00
|
|
|
|
|
|
|
"""
|
2010-07-27 03:15:15 +08:00
|
|
|
# used from runner functional tests
|
2009-02-27 18:18:27 +08:00
|
|
|
item = self.getitem(source)
|
2010-07-27 03:15:15 +08:00
|
|
|
# the test class where we are called from wants to provide the runner
|
2012-06-25 23:35:33 +08:00
|
|
|
testclassinstance = self.request.instance
|
2009-02-27 18:18:27 +08:00
|
|
|
runner = testclassinstance.getrunner()
|
2009-05-23 01:57:21 +08:00
|
|
|
return runner(item)
|
2009-02-27 18:18:27 +08:00
|
|
|
|
|
|
|
def inline_runsource(self, source, *cmdlineargs):
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Run a test module in process using ``pytest.main()``.
|
|
|
|
|
|
|
|
This run writes "source" into a temporary file and runs
|
2017-12-01 20:21:06 +08:00
|
|
|
``pytest.main()`` on it, returning a :py:class:`HookRecorder` instance
|
|
|
|
for the result.
|
2015-04-12 00:07:37 +08:00
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
:param source: the source code of the test module
|
2015-04-12 00:07:37 +08:00
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
:param cmdlineargs: any extra command line arguments to use
|
2015-04-12 00:07:37 +08:00
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
:return: :py:class:`HookRecorder` instance of the result
|
2015-04-12 00:07:37 +08:00
|
|
|
|
|
|
|
"""
|
2009-02-27 18:18:27 +08:00
|
|
|
p = self.makepyfile(source)
|
2017-11-04 23:17:20 +08:00
|
|
|
values = list(cmdlineargs) + [p]
|
|
|
|
return self.inline_run(*values)
|
2009-02-27 18:18:27 +08:00
|
|
|
|
2011-11-08 02:08:41 +08:00
|
|
|
def inline_genitems(self, *args):
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Run ``pytest.main(['--collectonly'])`` in-process.
|
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
Runs the :py:func:`pytest.main` function to run all of pytest inside
|
|
|
|
the test process itself like :py:meth:`inline_run`, but returns a
|
|
|
|
tuple of the collected items and a :py:class:`HookRecorder` instance.
|
2015-04-12 00:07:37 +08:00
|
|
|
|
|
|
|
"""
|
2015-04-28 17:54:53 +08:00
|
|
|
rec = self.inline_run("--collect-only", *args)
|
2014-10-06 19:37:57 +08:00
|
|
|
items = [x.item for x in rec.getcalls("pytest_itemcollected")]
|
|
|
|
return items, rec
|
2011-11-08 02:08:41 +08:00
|
|
|
|
2014-10-06 19:37:57 +08:00
|
|
|
def inline_run(self, *args, **kwargs):
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Run ``pytest.main()`` in-process, returning a HookRecorder.
|
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
Runs the :py:func:`pytest.main` function to run all of pytest inside
|
|
|
|
the test process itself. This means it can return a
|
|
|
|
:py:class:`HookRecorder` instance which gives more detailed results
|
|
|
|
from that run than can be done by matching stdout/stderr from
|
|
|
|
:py:meth:`runpytest`.
|
2015-04-12 00:07:37 +08:00
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
:param args: command line arguments to pass to :py:func:`pytest.main`
|
2015-04-12 00:07:37 +08:00
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
:param plugin: (keyword-only) extra plugin instances the
|
|
|
|
``pytest.main()`` instance should use
|
|
|
|
|
|
|
|
:return: a :py:class:`HookRecorder` instance
|
2015-04-12 00:07:37 +08:00
|
|
|
|
|
|
|
"""
|
2017-12-09 04:04:52 +08:00
|
|
|
finalizers = []
|
|
|
|
try:
|
2018-05-13 18:09:47 +08:00
|
|
|
# When running pytest inline any plugins active in the main test
|
2017-12-09 04:04:52 +08:00
|
|
|
# process are already imported. So this disables the warning which
|
|
|
|
# will trigger to say they can no longer be rewritten, which is
|
|
|
|
# fine as they have already been rewritten.
|
|
|
|
orig_warn = AssertionRewritingHook._warn_already_imported
|
|
|
|
|
|
|
|
def revert_warn_already_imported():
|
|
|
|
AssertionRewritingHook._warn_already_imported = orig_warn
|
2018-05-23 22:48:46 +08:00
|
|
|
|
2017-12-09 04:04:52 +08:00
|
|
|
finalizers.append(revert_warn_already_imported)
|
|
|
|
AssertionRewritingHook._warn_already_imported = lambda *a: None
|
|
|
|
|
2018-05-13 18:09:47 +08:00
|
|
|
# Any sys.module or sys.path changes done while running pytest
|
2017-12-09 04:04:52 +08:00
|
|
|
# inline should be reverted after the test run completes to avoid
|
|
|
|
# clashing with later inline tests run within the same pytest test,
|
|
|
|
# e.g. just because they use matching test module names.
|
|
|
|
finalizers.append(self.__take_sys_modules_snapshot().restore)
|
|
|
|
finalizers.append(SysPathsSnapshot().restore)
|
|
|
|
|
|
|
|
# Important note:
|
|
|
|
# - our tests should not leave any other references/registrations
|
|
|
|
# laying around other than possibly loaded test modules
|
|
|
|
# referenced from sys.modules, as nothing will clean those up
|
|
|
|
# automatically
|
|
|
|
|
|
|
|
rec = []
|
|
|
|
|
2018-01-25 04:23:42 +08:00
|
|
|
class Collect(object):
|
2018-05-23 22:48:46 +08:00
|
|
|
|
2017-12-09 04:04:52 +08:00
|
|
|
def pytest_configure(x, config):
|
|
|
|
rec.append(self.make_hook_recorder(config.pluginmanager))
|
|
|
|
|
|
|
|
plugins = kwargs.get("plugins") or []
|
|
|
|
plugins.append(Collect())
|
|
|
|
ret = pytest.main(list(args), plugins=plugins)
|
|
|
|
if len(rec) == 1:
|
|
|
|
reprec = rec.pop()
|
|
|
|
else:
|
2018-05-23 22:48:46 +08:00
|
|
|
|
2018-01-25 04:23:42 +08:00
|
|
|
class reprec(object):
|
2017-12-09 04:04:52 +08:00
|
|
|
pass
|
2018-05-23 22:48:46 +08:00
|
|
|
|
2017-12-09 04:04:52 +08:00
|
|
|
reprec.ret = ret
|
|
|
|
|
|
|
|
# typically we reraise keyboard interrupts from the child run
|
|
|
|
# because it's our user requesting interruption of the testing
|
|
|
|
if ret == 2 and not kwargs.get("no_reraise_ctrlc"):
|
|
|
|
calls = reprec.getcalls("pytest_keyboard_interrupt")
|
|
|
|
if calls and calls[-1].excinfo.type == KeyboardInterrupt:
|
|
|
|
raise KeyboardInterrupt()
|
|
|
|
return reprec
|
|
|
|
finally:
|
|
|
|
for finalizer in finalizers:
|
|
|
|
finalizer()
|
2009-02-27 18:18:27 +08:00
|
|
|
|
2015-04-28 17:54:53 +08:00
|
|
|
def runpytest_inprocess(self, *args, **kwargs):
|
2017-12-01 20:21:06 +08:00
|
|
|
"""Return result of running pytest in-process, providing a similar
|
|
|
|
interface to what self.runpytest() provides.
|
|
|
|
|
|
|
|
"""
|
2015-04-28 17:54:46 +08:00
|
|
|
if kwargs.get("syspathinsert"):
|
|
|
|
self.syspathinsert()
|
2015-04-28 17:54:45 +08:00
|
|
|
now = time.time()
|
2017-02-20 02:24:41 +08:00
|
|
|
capture = MultiCapture(Capture=SysCapture)
|
|
|
|
capture.start_capturing()
|
2015-04-28 17:54:45 +08:00
|
|
|
try:
|
2015-04-28 17:54:46 +08:00
|
|
|
try:
|
2015-05-07 17:02:55 +08:00
|
|
|
reprec = self.inline_run(*args, **kwargs)
|
2015-04-28 17:54:46 +08:00
|
|
|
except SystemExit as e:
|
2016-11-21 04:59:15 +08:00
|
|
|
|
2018-01-25 04:23:42 +08:00
|
|
|
class reprec(object):
|
2015-04-28 17:54:46 +08:00
|
|
|
ret = e.args[0]
|
2016-11-21 04:59:15 +08:00
|
|
|
|
2015-04-28 17:54:46 +08:00
|
|
|
except Exception:
|
|
|
|
traceback.print_exc()
|
2016-11-21 04:59:15 +08:00
|
|
|
|
2018-01-25 04:23:42 +08:00
|
|
|
class reprec(object):
|
2015-04-28 17:54:46 +08:00
|
|
|
ret = 3
|
2018-05-23 22:48:46 +08:00
|
|
|
|
2015-04-28 17:54:45 +08:00
|
|
|
finally:
|
2017-02-20 02:24:41 +08:00
|
|
|
out, err = capture.readouterr()
|
|
|
|
capture.stop_capturing()
|
2015-04-28 17:54:46 +08:00
|
|
|
sys.stdout.write(out)
|
|
|
|
sys.stderr.write(err)
|
2015-04-28 17:54:45 +08:00
|
|
|
|
2018-05-23 22:48:46 +08:00
|
|
|
res = RunResult(reprec.ret, out.split("\n"), err.split("\n"), time.time() - now)
|
2015-04-28 17:54:45 +08:00
|
|
|
res.reprec = reprec
|
|
|
|
return res
|
|
|
|
|
2015-04-28 17:54:46 +08:00
|
|
|
def runpytest(self, *args, **kwargs):
|
2017-12-01 20:21:06 +08:00
|
|
|
"""Run pytest inline or in a subprocess, depending on the command line
|
2015-04-28 17:54:53 +08:00
|
|
|
option "--runpytest" and return a :py:class:`RunResult`.
|
|
|
|
|
|
|
|
"""
|
2015-05-06 20:58:46 +08:00
|
|
|
args = self._ensure_basetemp(args)
|
2015-04-28 17:54:53 +08:00
|
|
|
return self._runpytest_method(*args, **kwargs)
|
2015-04-28 17:54:46 +08:00
|
|
|
|
2015-05-06 20:58:46 +08:00
|
|
|
def _ensure_basetemp(self, args):
|
|
|
|
args = [str(x) for x in args]
|
|
|
|
for x in args:
|
2018-05-23 22:48:46 +08:00
|
|
|
if str(x).startswith("--basetemp"):
|
2017-07-17 07:25:09 +08:00
|
|
|
# print("basedtemp exists: %s" %(args,))
|
2015-05-06 20:58:46 +08:00
|
|
|
break
|
|
|
|
else:
|
2018-05-23 22:48:46 +08:00
|
|
|
args.append("--basetemp=%s" % self.tmpdir.dirpath("basetemp"))
|
2017-07-17 07:25:09 +08:00
|
|
|
# print("added basetemp: %s" %(args,))
|
2015-05-06 20:58:46 +08:00
|
|
|
return args
|
|
|
|
|
2009-02-27 18:18:27 +08:00
|
|
|
def parseconfig(self, *args):
|
2016-06-21 22:16:57 +08:00
|
|
|
"""Return a new pytest Config instance from given commandline args.
|
2015-04-12 00:07:37 +08:00
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
This invokes the pytest bootstrapping code in _pytest.config to create
|
|
|
|
a new :py:class:`_pytest.core.PluginManager` and call the
|
|
|
|
pytest_cmdline_parse hook to create a new
|
2015-04-12 00:07:37 +08:00
|
|
|
:py:class:`_pytest.config.Config` instance.
|
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
If :py:attr:`plugins` has been populated they should be plugin modules
|
|
|
|
to be registered with the PluginManager.
|
2015-04-12 00:07:37 +08:00
|
|
|
|
|
|
|
"""
|
2015-05-06 20:58:46 +08:00
|
|
|
args = self._ensure_basetemp(args)
|
|
|
|
|
2013-09-30 19:14:14 +08:00
|
|
|
import _pytest.config
|
2018-05-23 22:48:46 +08:00
|
|
|
|
2013-09-30 19:14:14 +08:00
|
|
|
config = _pytest.config._prepareconfig(args, self.plugins)
|
2013-09-29 04:23:00 +08:00
|
|
|
# we don't know what the test will do with this half-setup config
|
|
|
|
# object and thus we make sure it gets unconfigured properly in any
|
|
|
|
# case (otherwise capturing could still be active, for example)
|
2015-04-22 22:33:20 +08:00
|
|
|
self.request.addfinalizer(config._ensure_unconfigure)
|
2010-07-27 03:15:15 +08:00
|
|
|
return config
|
2009-02-27 18:18:27 +08:00
|
|
|
|
2009-03-23 01:41:36 +08:00
|
|
|
def parseconfigure(self, *args):
|
2016-06-21 22:16:57 +08:00
|
|
|
"""Return a new pytest configured Config instance.
|
2015-04-12 00:07:37 +08:00
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
This returns a new :py:class:`_pytest.config.Config` instance like
|
|
|
|
:py:meth:`parseconfig`, but also calls the pytest_configure hook.
|
2015-04-12 00:07:37 +08:00
|
|
|
|
|
|
|
"""
|
2009-03-23 01:41:36 +08:00
|
|
|
config = self.parseconfig(*args)
|
2015-04-22 22:33:20 +08:00
|
|
|
config._do_configure()
|
|
|
|
self.request.addfinalizer(config._ensure_unconfigure)
|
2009-03-23 01:41:36 +08:00
|
|
|
return config
|
|
|
|
|
2017-07-17 07:25:08 +08:00
|
|
|
def getitem(self, source, funcname="test_func"):
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Return the test item for a test function.
|
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
This writes the source to a python file and runs pytest's collection on
|
|
|
|
the resulting module, returning the test item for the requested
|
|
|
|
function name.
|
2015-04-12 00:07:37 +08:00
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
:param source: the module source
|
2015-04-12 00:07:37 +08:00
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
:param funcname: the name of the test function for which to return a
|
|
|
|
test item
|
2015-04-12 00:07:37 +08:00
|
|
|
|
|
|
|
"""
|
2012-07-20 20:16:28 +08:00
|
|
|
items = self.getitems(source)
|
|
|
|
for item in items:
|
2009-04-05 03:06:20 +08:00
|
|
|
if item.name == funcname:
|
2010-07-27 03:15:15 +08:00
|
|
|
return item
|
2018-05-23 22:48:46 +08:00
|
|
|
assert 0, (
|
|
|
|
"%r item not found in module:\n%s\nitems: %s" % (funcname, source, items)
|
|
|
|
)
|
2009-02-27 18:18:27 +08:00
|
|
|
|
2017-07-17 07:25:08 +08:00
|
|
|
def getitems(self, source):
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Return all test items collected from the module.
|
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
This writes the source to a python file and runs pytest's collection on
|
|
|
|
the resulting module, returning all test items contained within.
|
2015-04-12 00:07:37 +08:00
|
|
|
|
|
|
|
"""
|
2009-02-27 18:18:27 +08:00
|
|
|
modcol = self.getmodulecol(source)
|
2010-09-15 16:30:50 +08:00
|
|
|
return self.genitems([modcol])
|
2009-02-27 18:18:27 +08:00
|
|
|
|
2017-07-17 07:25:08 +08:00
|
|
|
def getmodulecol(self, source, configargs=(), withinit=False):
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Return the module collection node for ``source``.
|
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
This writes ``source`` to a file using :py:meth:`makepyfile` and then
|
|
|
|
runs the pytest collection on it, returning the collection node for the
|
|
|
|
test module.
|
2015-04-12 00:07:37 +08:00
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
:param source: the source code of the module to collect
|
2015-04-12 00:07:37 +08:00
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
:param configargs: any extra arguments to pass to
|
|
|
|
:py:meth:`parseconfigure`
|
2015-04-12 00:07:37 +08:00
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
:param withinit: whether to also write an ``__init__.py`` file to the
|
|
|
|
same directory to ensure it is a package
|
2015-04-12 00:07:37 +08:00
|
|
|
|
|
|
|
"""
|
2015-11-27 22:43:01 +08:00
|
|
|
kw = {self.request.function.__name__: Source(source).strip()}
|
2009-02-27 18:18:27 +08:00
|
|
|
path = self.makepyfile(**kw)
|
|
|
|
if withinit:
|
2017-07-17 07:25:08 +08:00
|
|
|
self.makepyfile(__init__="#")
|
2010-09-15 16:30:50 +08:00
|
|
|
self.config = config = self.parseconfigure(path, *configargs)
|
|
|
|
node = self.getnode(config, path)
|
2016-08-27 19:04:00 +08:00
|
|
|
|
2010-09-15 16:30:50 +08:00
|
|
|
return node
|
2009-02-27 18:18:27 +08:00
|
|
|
|
2010-11-01 01:01:33 +08:00
|
|
|
def collect_by_name(self, modcol, name):
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Return the collection node for name from the module collection.
|
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
This will search a module collection node for a collection node
|
|
|
|
matching the given name.
|
2015-04-12 00:07:37 +08:00
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
:param modcol: a module collection node; see :py:meth:`getmodulecol`
|
2015-04-12 00:07:37 +08:00
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
:param name: the name of the node to return
|
2015-04-12 00:07:37 +08:00
|
|
|
|
|
|
|
"""
|
2016-08-27 19:04:00 +08:00
|
|
|
if modcol not in self._mod_collections:
|
|
|
|
self._mod_collections[modcol] = list(modcol.collect())
|
|
|
|
for colitem in self._mod_collections[modcol]:
|
2010-11-01 01:01:33 +08:00
|
|
|
if colitem.name == name:
|
|
|
|
return colitem
|
|
|
|
|
2009-02-27 18:18:27 +08:00
|
|
|
def popen(self, cmdargs, stdout, stderr, **kw):
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Invoke subprocess.Popen.
|
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
This calls subprocess.Popen making sure the current working directory
|
|
|
|
is in the PYTHONPATH.
|
2015-04-12 00:07:37 +08:00
|
|
|
|
|
|
|
You probably want to use :py:meth:`run` instead.
|
|
|
|
|
|
|
|
"""
|
2009-04-29 05:49:03 +08:00
|
|
|
env = os.environ.copy()
|
2018-05-23 22:48:46 +08:00
|
|
|
env["PYTHONPATH"] = os.pathsep.join(
|
|
|
|
filter(None, [str(os.getcwd()), env.get("PYTHONPATH", "")])
|
|
|
|
)
|
|
|
|
kw["env"] = env
|
|
|
|
|
|
|
|
popen = subprocess.Popen(
|
|
|
|
cmdargs, stdin=subprocess.PIPE, stdout=stdout, stderr=stderr, **kw
|
|
|
|
)
|
2017-07-22 03:27:48 +08:00
|
|
|
popen.stdin.close()
|
|
|
|
|
|
|
|
return popen
|
2009-02-27 18:18:27 +08:00
|
|
|
|
|
|
|
def run(self, *cmdargs):
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Run a command with arguments.
|
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
Run a process using subprocess.Popen saving the stdout and stderr.
|
2015-04-12 00:07:37 +08:00
|
|
|
|
|
|
|
Returns a :py:class:`RunResult`.
|
|
|
|
|
|
|
|
"""
|
2010-01-02 04:54:27 +08:00
|
|
|
return self._run(*cmdargs)
|
2009-02-27 18:18:27 +08:00
|
|
|
|
|
|
|
def _run(self, *cmdargs):
|
2009-08-29 21:51:49 +08:00
|
|
|
cmdargs = [str(x) for x in cmdargs]
|
2010-01-02 06:05:00 +08:00
|
|
|
p1 = self.tmpdir.join("stdout")
|
|
|
|
p2 = self.tmpdir.join("stderr")
|
2018-05-23 22:48:46 +08:00
|
|
|
print("running:", " ".join(cmdargs))
|
2017-03-17 09:27:28 +08:00
|
|
|
print(" in:", str(py.path.local()))
|
2012-09-20 16:57:23 +08:00
|
|
|
f1 = codecs.open(str(p1), "w", encoding="utf8")
|
|
|
|
f2 = codecs.open(str(p2), "w", encoding="utf8")
|
|
|
|
try:
|
|
|
|
now = time.time()
|
2018-05-23 22:48:46 +08:00
|
|
|
popen = self.popen(
|
|
|
|
cmdargs, stdout=f1, stderr=f2, close_fds=(sys.platform != "win32")
|
|
|
|
)
|
2012-09-20 16:57:23 +08:00
|
|
|
ret = popen.wait()
|
|
|
|
finally:
|
|
|
|
f1.close()
|
|
|
|
f2.close()
|
|
|
|
f1 = codecs.open(str(p1), "r", encoding="utf8")
|
|
|
|
f2 = codecs.open(str(p2), "r", encoding="utf8")
|
|
|
|
try:
|
|
|
|
out = f1.read().splitlines()
|
|
|
|
err = f2.read().splitlines()
|
|
|
|
finally:
|
|
|
|
f1.close()
|
|
|
|
f2.close()
|
|
|
|
self._dump_lines(out, sys.stdout)
|
|
|
|
self._dump_lines(err, sys.stderr)
|
2017-07-17 07:25:08 +08:00
|
|
|
return RunResult(ret, out, err, time.time() - now)
|
2009-02-27 18:18:27 +08:00
|
|
|
|
2012-09-20 16:57:23 +08:00
|
|
|
def _dump_lines(self, lines, fp):
|
|
|
|
try:
|
|
|
|
for line in lines:
|
2017-03-17 09:27:28 +08:00
|
|
|
print(line, file=fp)
|
2012-09-20 16:57:23 +08:00
|
|
|
except UnicodeEncodeError:
|
|
|
|
print("couldn't print to %s because of encoding" % (fp,))
|
|
|
|
|
2015-04-28 17:54:53 +08:00
|
|
|
def _getpytestargs(self):
|
2017-12-01 20:21:06 +08:00
|
|
|
# we cannot use `(sys.executable, script)` because on Windows the
|
|
|
|
# script is e.g. `pytest.exe`
|
2018-05-23 22:48:46 +08:00
|
|
|
return (sys.executable, PYTEST_FULLPATH) # noqa
|
2015-04-12 00:07:37 +08:00
|
|
|
|
2015-04-28 17:54:53 +08:00
|
|
|
def runpython(self, script):
|
|
|
|
"""Run a python script using sys.executable as interpreter.
|
2015-04-12 00:07:37 +08:00
|
|
|
|
|
|
|
Returns a :py:class:`RunResult`.
|
2017-12-01 20:21:06 +08:00
|
|
|
|
2015-04-12 00:07:37 +08:00
|
|
|
"""
|
2010-01-11 03:45:37 +08:00
|
|
|
return self.run(sys.executable, script)
|
|
|
|
|
|
|
|
def runpython_c(self, command):
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Run python -c "command", return a :py:class:`RunResult`."""
|
2014-08-01 06:13:40 +08:00
|
|
|
return self.run(sys.executable, "-c", command)
|
2009-07-31 20:21:02 +08:00
|
|
|
|
2015-04-28 17:54:53 +08:00
|
|
|
def runpytest_subprocess(self, *args, **kwargs):
|
2016-06-21 22:16:57 +08:00
|
|
|
"""Run pytest as a subprocess with given arguments.
|
2015-04-12 00:07:37 +08:00
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
Any plugins added to the :py:attr:`plugins` list will added using the
|
|
|
|
``-p`` command line option. Additionally ``--basetemp`` is used put
|
|
|
|
any temporary files and directories in a numbered directory prefixed
|
|
|
|
with "runpytest-" so they do not conflict with the normal numbered
|
|
|
|
pytest location for temporary files and directories.
|
2015-04-12 00:07:37 +08:00
|
|
|
|
|
|
|
Returns a :py:class:`RunResult`.
|
|
|
|
|
|
|
|
"""
|
2018-05-23 22:48:46 +08:00
|
|
|
p = py.path.local.make_numbered_dir(
|
|
|
|
prefix="runpytest-", keep=None, rootdir=self.tmpdir
|
|
|
|
)
|
|
|
|
args = ("--basetemp=%s" % p,) + args
|
2009-12-25 07:24:58 +08:00
|
|
|
plugins = [x for x in self.plugins if isinstance(x, str)]
|
|
|
|
if plugins:
|
2018-05-23 22:48:46 +08:00
|
|
|
args = ("-p", plugins[0]) + args
|
2015-04-28 17:54:53 +08:00
|
|
|
args = self._getpytestargs() + args
|
|
|
|
return self.run(*args)
|
2009-02-27 18:18:27 +08:00
|
|
|
|
2009-05-06 17:47:48 +08:00
|
|
|
def spawn_pytest(self, string, expect_timeout=10.0):
|
2016-06-21 22:16:57 +08:00
|
|
|
"""Run pytest using pexpect.
|
2015-04-12 00:07:37 +08:00
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
This makes sure to use the right pytest and sets up the temporary
|
|
|
|
directory locations.
|
2015-04-12 00:07:37 +08:00
|
|
|
|
|
|
|
The pexpect child is returned.
|
|
|
|
|
|
|
|
"""
|
2017-03-22 09:17:07 +08:00
|
|
|
basetemp = self.tmpdir.mkdir("temp-pexpect")
|
2015-04-28 17:54:53 +08:00
|
|
|
invoke = " ".join(map(str, self._getpytestargs()))
|
2009-05-06 17:47:48 +08:00
|
|
|
cmd = "%s --basetemp=%s %s" % (invoke, basetemp, string)
|
2010-10-06 20:48:24 +08:00
|
|
|
return self.spawn(cmd, expect_timeout=expect_timeout)
|
|
|
|
|
|
|
|
def spawn(self, cmd, expect_timeout=10.0):
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Run a command using pexpect.
|
|
|
|
|
|
|
|
The pexpect child is returned.
|
2017-12-01 20:21:06 +08:00
|
|
|
|
2015-04-12 00:07:37 +08:00
|
|
|
"""
|
2014-01-18 19:31:33 +08:00
|
|
|
pexpect = pytest.importorskip("pexpect", "3.0")
|
2018-05-23 22:48:46 +08:00
|
|
|
if hasattr(sys, "pypy_version_info") and "64" in platform.machine():
|
2010-11-27 23:40:52 +08:00
|
|
|
pytest.skip("pypy-64 bit not supported")
|
2012-10-19 21:59:29 +08:00
|
|
|
if sys.platform.startswith("freebsd"):
|
|
|
|
pytest.xfail("pexpect does not work reliably on freebsd")
|
2013-11-19 17:10:27 +08:00
|
|
|
logfile = self.tmpdir.join("spawn.out").open("wb")
|
|
|
|
child = pexpect.spawn(cmd, logfile=logfile)
|
|
|
|
self.request.addfinalizer(logfile.close)
|
2009-05-06 17:47:48 +08:00
|
|
|
child.timeout = expect_timeout
|
|
|
|
return child
|
|
|
|
|
2017-07-17 07:25:09 +08:00
|
|
|
|
2010-05-21 22:42:46 +08:00
|
|
|
def getdecoded(out):
|
2017-07-17 07:25:06 +08:00
|
|
|
try:
|
|
|
|
return out.decode("utf-8")
|
|
|
|
except UnicodeDecodeError:
|
|
|
|
return "INTERNAL not-utf8-decodeable, truncated string:\n%s" % (
|
2018-05-23 22:48:46 +08:00
|
|
|
py.io.saferepr(out),
|
|
|
|
)
|
2010-05-21 22:42:46 +08:00
|
|
|
|
2009-02-27 18:18:27 +08:00
|
|
|
|
2018-01-25 04:23:42 +08:00
|
|
|
class LineComp(object):
|
2018-05-23 22:48:46 +08:00
|
|
|
|
2009-02-27 18:18:27 +08:00
|
|
|
def __init__(self):
|
2009-08-21 02:47:39 +08:00
|
|
|
self.stringio = py.io.TextIO()
|
2009-02-27 18:18:27 +08:00
|
|
|
|
|
|
|
def assert_contains_lines(self, lines2):
|
2017-12-01 20:21:06 +08:00
|
|
|
"""Assert that lines2 are contained (linearly) in lines1.
|
|
|
|
|
|
|
|
Return a list of extralines found.
|
|
|
|
|
2009-02-27 18:18:27 +08:00
|
|
|
"""
|
|
|
|
__tracebackhide__ = True
|
|
|
|
val = self.stringio.getvalue()
|
2010-04-28 19:22:05 +08:00
|
|
|
self.stringio.truncate(0)
|
|
|
|
self.stringio.seek(0)
|
2009-02-27 18:18:27 +08:00
|
|
|
lines1 = val.split("\n")
|
|
|
|
return LineMatcher(lines1).fnmatch_lines(lines2)
|
2010-07-27 03:15:15 +08:00
|
|
|
|
2015-04-27 21:06:47 +08:00
|
|
|
|
2018-01-25 04:23:42 +08:00
|
|
|
class LineMatcher(object):
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Flexible matching of text.
|
|
|
|
|
|
|
|
This is a convenience class to test large texts like the output of
|
|
|
|
commands.
|
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
The constructor takes a list of lines without their trailing newlines, i.e.
|
|
|
|
``text.splitlines()``.
|
2015-04-12 00:07:37 +08:00
|
|
|
|
|
|
|
"""
|
|
|
|
|
2017-07-17 07:25:08 +08:00
|
|
|
def __init__(self, lines):
|
2009-02-27 18:18:27 +08:00
|
|
|
self.lines = lines
|
2016-07-21 09:35:43 +08:00
|
|
|
self._log_output = []
|
2009-02-27 18:18:27 +08:00
|
|
|
|
|
|
|
def str(self):
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Return the entire original text."""
|
2009-02-27 18:18:27 +08:00
|
|
|
return "\n".join(self.lines)
|
|
|
|
|
2010-09-28 02:48:30 +08:00
|
|
|
def _getlines(self, lines2):
|
2009-02-27 18:18:27 +08:00
|
|
|
if isinstance(lines2, str):
|
2015-11-27 22:43:01 +08:00
|
|
|
lines2 = Source(lines2)
|
|
|
|
if isinstance(lines2, Source):
|
2009-02-27 18:18:27 +08:00
|
|
|
lines2 = lines2.strip().lines
|
2010-09-28 02:48:30 +08:00
|
|
|
return lines2
|
|
|
|
|
|
|
|
def fnmatch_lines_random(self, lines2):
|
2017-12-01 20:21:06 +08:00
|
|
|
"""Check lines exist in the output using in any order.
|
|
|
|
|
|
|
|
Lines are checked using ``fnmatch.fnmatch``. The argument is a list of
|
|
|
|
lines which have to occur in the output, in any order.
|
2017-11-22 06:05:11 +08:00
|
|
|
|
|
|
|
"""
|
|
|
|
self._match_lines_random(lines2, fnmatch)
|
|
|
|
|
|
|
|
def re_match_lines_random(self, lines2):
|
2017-11-23 03:15:59 +08:00
|
|
|
"""Check lines exist in the output using ``re.match``, in any order.
|
2017-11-22 06:05:11 +08:00
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
The argument is a list of lines which have to occur in the output, in
|
|
|
|
any order.
|
2017-11-22 06:05:11 +08:00
|
|
|
|
|
|
|
"""
|
|
|
|
self._match_lines_random(lines2, lambda name, pat: re.match(pat, name))
|
|
|
|
|
|
|
|
def _match_lines_random(self, lines2, match_func):
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Check lines exist in the output.
|
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
The argument is a list of lines which have to occur in the output, in
|
|
|
|
any order. Each line can contain glob whildcards.
|
2015-04-12 00:07:37 +08:00
|
|
|
|
|
|
|
"""
|
2010-09-28 02:48:30 +08:00
|
|
|
lines2 = self._getlines(lines2)
|
|
|
|
for line in lines2:
|
|
|
|
for x in self.lines:
|
2017-11-22 06:05:11 +08:00
|
|
|
if line == x or match_func(x, line):
|
2016-07-21 09:35:43 +08:00
|
|
|
self._log("matched: ", repr(line))
|
2010-09-28 02:48:30 +08:00
|
|
|
break
|
|
|
|
else:
|
2016-07-21 09:35:43 +08:00
|
|
|
self._log("line %r not found in output" % line)
|
|
|
|
raise ValueError(self._log_text)
|
2009-02-27 18:18:27 +08:00
|
|
|
|
2013-10-01 18:37:11 +08:00
|
|
|
def get_lines_after(self, fnline):
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Return all lines following the given line in the text.
|
|
|
|
|
|
|
|
The given line can contain glob wildcards.
|
2017-12-01 20:21:06 +08:00
|
|
|
|
2015-04-12 00:07:37 +08:00
|
|
|
"""
|
2013-10-01 18:37:11 +08:00
|
|
|
for i, line in enumerate(self.lines):
|
|
|
|
if fnline == line or fnmatch(line, fnline):
|
2017-07-17 07:25:08 +08:00
|
|
|
return self.lines[i + 1:]
|
2013-10-01 18:37:11 +08:00
|
|
|
raise ValueError("line %r not found in output" % fnline)
|
|
|
|
|
2016-07-21 09:35:43 +08:00
|
|
|
def _log(self, *args):
|
2018-05-23 22:48:46 +08:00
|
|
|
self._log_output.append(" ".join((str(x) for x in args)))
|
2016-07-21 09:35:43 +08:00
|
|
|
|
|
|
|
@property
|
|
|
|
def _log_text(self):
|
2018-05-23 22:48:46 +08:00
|
|
|
return "\n".join(self._log_output)
|
2016-07-21 09:35:43 +08:00
|
|
|
|
2010-09-28 02:48:30 +08:00
|
|
|
def fnmatch_lines(self, lines2):
|
2017-11-22 06:05:11 +08:00
|
|
|
"""Search captured text for matching lines using ``fnmatch.fnmatch``.
|
2015-04-12 00:07:37 +08:00
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
The argument is a list of lines which have to match and can use glob
|
|
|
|
wildcards. If they do not match a pytest.fail() is called. The
|
|
|
|
matches and non-matches are also printed on stdout.
|
2015-04-12 00:07:37 +08:00
|
|
|
|
2017-11-22 06:05:11 +08:00
|
|
|
"""
|
2018-05-23 22:48:46 +08:00
|
|
|
self._match_lines(lines2, fnmatch, "fnmatch")
|
2017-11-22 06:05:11 +08:00
|
|
|
|
|
|
|
def re_match_lines(self, lines2):
|
|
|
|
"""Search captured text for matching lines using ``re.match``.
|
|
|
|
|
|
|
|
The argument is a list of lines which have to match using ``re.match``.
|
|
|
|
If they do not match a pytest.fail() is called.
|
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
The matches and non-matches are also printed on stdout.
|
|
|
|
|
2017-11-22 06:05:11 +08:00
|
|
|
"""
|
2018-05-23 22:48:46 +08:00
|
|
|
self._match_lines(lines2, lambda name, pat: re.match(pat, name), "re.match")
|
2017-11-22 06:05:11 +08:00
|
|
|
|
|
|
|
def _match_lines(self, lines2, match_func, match_nickname):
|
|
|
|
"""Underlying implementation of ``fnmatch_lines`` and ``re_match_lines``.
|
|
|
|
|
2017-12-01 20:21:06 +08:00
|
|
|
:param list[str] lines2: list of string patterns to match. The actual
|
|
|
|
format depends on ``match_func``
|
|
|
|
:param match_func: a callable ``match_func(line, pattern)`` where line
|
|
|
|
is the captured line from stdout/stderr and pattern is the matching
|
|
|
|
pattern
|
|
|
|
:param str match_nickname: the nickname for the match function that
|
|
|
|
will be logged to stdout when a match occurs
|
2017-11-22 06:05:11 +08:00
|
|
|
|
2015-04-12 00:07:37 +08:00
|
|
|
"""
|
2010-09-28 02:48:30 +08:00
|
|
|
lines2 = self._getlines(lines2)
|
2009-02-27 18:18:27 +08:00
|
|
|
lines1 = self.lines[:]
|
|
|
|
nextline = None
|
|
|
|
extralines = []
|
2010-04-29 05:51:36 +08:00
|
|
|
__tracebackhide__ = True
|
2009-02-27 18:18:27 +08:00
|
|
|
for line in lines2:
|
|
|
|
nomatchprinted = False
|
|
|
|
while lines1:
|
|
|
|
nextline = lines1.pop(0)
|
|
|
|
if line == nextline:
|
2016-07-21 09:35:43 +08:00
|
|
|
self._log("exact match:", repr(line))
|
2010-07-27 03:15:15 +08:00
|
|
|
break
|
2017-11-22 06:05:11 +08:00
|
|
|
elif match_func(nextline, line):
|
|
|
|
self._log("%s:" % match_nickname, repr(line))
|
2016-07-21 09:35:43 +08:00
|
|
|
self._log(" with:", repr(nextline))
|
2009-02-27 18:18:27 +08:00
|
|
|
break
|
|
|
|
else:
|
|
|
|
if not nomatchprinted:
|
2016-07-21 09:35:43 +08:00
|
|
|
self._log("nomatch:", repr(line))
|
2009-02-27 18:18:27 +08:00
|
|
|
nomatchprinted = True
|
2016-07-21 09:35:43 +08:00
|
|
|
self._log(" and:", repr(nextline))
|
2009-02-27 18:18:27 +08:00
|
|
|
extralines.append(nextline)
|
|
|
|
else:
|
2016-07-21 09:35:43 +08:00
|
|
|
self._log("remains unmatched: %r" % (line,))
|
|
|
|
pytest.fail(self._log_text)
|