2014-01-18 19:31:33 +08:00
|
|
|
""" (disabled by default) support for testing pytest and pytest plugins. """
|
2015-04-28 17:54:53 +08:00
|
|
|
import gc
|
2014-08-01 06:13:40 +08:00
|
|
|
import sys
|
2015-04-28 17:54:46 +08:00
|
|
|
import traceback
|
2014-08-01 06:13:40 +08:00
|
|
|
import os
|
2012-09-20 16:57:23 +08:00
|
|
|
import codecs
|
2009-12-25 07:24:58 +08:00
|
|
|
import re
|
2009-12-30 18:37:46 +08:00
|
|
|
import time
|
2014-08-01 06:13:40 +08:00
|
|
|
import platform
|
2010-09-28 02:48:30 +08:00
|
|
|
from fnmatch import fnmatch
|
2014-08-01 06:13:40 +08:00
|
|
|
import subprocess
|
|
|
|
|
|
|
|
import py
|
|
|
|
import pytest
|
2009-08-29 01:16:15 +08:00
|
|
|
from py.builtin import print_
|
2009-02-27 18:18:27 +08:00
|
|
|
|
2014-08-01 06:13:40 +08:00
|
|
|
from _pytest.main import Session, EXIT_OK
|
|
|
|
|
2015-04-28 17:54:53 +08:00
|
|
|
|
|
|
|
def pytest_addoption(parser):
|
|
|
|
# group = parser.getgroup("pytester", "pytester (self-tests) options")
|
|
|
|
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"))
|
|
|
|
|
|
|
|
|
|
|
|
def pytest_configure(config):
|
|
|
|
# This might be called multiple times. Only take the first.
|
|
|
|
global _pytest_fullpath
|
|
|
|
try:
|
|
|
|
_pytest_fullpath
|
|
|
|
except NameError:
|
|
|
|
_pytest_fullpath = os.path.abspath(pytest.__file__.rstrip("oc"))
|
|
|
|
_pytest_fullpath = _pytest_fullpath.replace("$py.class", ".py")
|
|
|
|
|
|
|
|
if config.getvalue("lsof"):
|
|
|
|
checker = LsofFdLeakChecker()
|
|
|
|
if checker.matching_platform():
|
|
|
|
config.pluginmanager.register(checker)
|
|
|
|
|
|
|
|
|
|
|
|
class LsofFdLeakChecker(object):
|
|
|
|
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):
|
|
|
|
def isopen(line):
|
|
|
|
return line.startswith('f') and ("deleted" not in line and
|
|
|
|
'mem' not in line and "txt" not in line and 'cwd' not in line)
|
|
|
|
|
|
|
|
open_files = []
|
|
|
|
|
|
|
|
for line in out.split("\n"):
|
|
|
|
if isopen(line):
|
|
|
|
fields = line.split('\0')
|
|
|
|
fd = fields[0][1:]
|
|
|
|
filename = fields[1][1:]
|
|
|
|
if filename.startswith('/'):
|
|
|
|
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):
|
|
|
|
# cmdexec may raise UnicodeDecodeError on Windows systems
|
|
|
|
# with locale other than english:
|
|
|
|
# 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)
|
2015-04-28 17:54:53 +08:00
|
|
|
def pytest_runtest_item(self, item):
|
|
|
|
lines1 = self.get_open_files()
|
|
|
|
yield
|
|
|
|
if hasattr(sys, "pypy_version_info"):
|
|
|
|
gc.collect()
|
|
|
|
lines2 = self.get_open_files()
|
|
|
|
|
|
|
|
new_fds = set([t[0] for t in lines2]) - set([t[0] for t in lines1])
|
|
|
|
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)
|
|
|
|
pytest.fail("\n".join(error), pytrace=False)
|
|
|
|
|
|
|
|
|
|
|
|
# XXX copied from execnet's conftest.py - needs to be merged
|
|
|
|
winpymap = {
|
|
|
|
'python2.7': r'C:\Python27\python.exe',
|
|
|
|
'python2.6': r'C:\Python26\python.exe',
|
|
|
|
'python3.1': r'C:\Python31\python.exe',
|
|
|
|
'python3.2': r'C:\Python32\python.exe',
|
|
|
|
'python3.3': r'C:\Python33\python.exe',
|
|
|
|
'python3.4': r'C:\Python34\python.exe',
|
|
|
|
'python3.5': r'C:\Python35\python.exe',
|
|
|
|
}
|
|
|
|
|
|
|
|
def getexecutable(name, cache={}):
|
|
|
|
try:
|
|
|
|
return cache[name]
|
|
|
|
except KeyError:
|
|
|
|
executable = py.path.local.sysfind(name)
|
|
|
|
if executable:
|
|
|
|
if name == "jython":
|
|
|
|
import subprocess
|
|
|
|
popen = subprocess.Popen([str(executable), "--version"],
|
|
|
|
universal_newlines=True, stderr=subprocess.PIPE)
|
|
|
|
out, err = popen.communicate()
|
|
|
|
if not err or "2.5" not in err:
|
|
|
|
executable = None
|
|
|
|
if "2.5.2" in err:
|
|
|
|
executable = None # http://bugs.jython.org/issue1790
|
|
|
|
cache[name] = executable
|
|
|
|
return executable
|
|
|
|
|
|
|
|
@pytest.fixture(params=['python2.6', 'python2.7', 'python3.3', "python3.4",
|
|
|
|
'pypy', 'pypy3'])
|
|
|
|
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
|
|
|
|
|
2015-04-22 23:06:00 +08:00
|
|
|
# used at least by pytest-xdist plugin
|
2015-04-23 03:04:36 +08:00
|
|
|
@pytest.fixture
|
|
|
|
def _pytest(request):
|
|
|
|
""" Return a helper which offers a gethookrecorder(hook)
|
|
|
|
method which returns a HookRecorder instance which helps
|
|
|
|
to make assertions about called hooks.
|
|
|
|
"""
|
2015-04-22 23:06:00 +08:00
|
|
|
return PytestArg(request)
|
|
|
|
|
|
|
|
class PytestArg:
|
|
|
|
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
|
|
|
|
|
|
|
def get_public_names(l):
|
|
|
|
"""Only return names from iterator l without a leading underscore."""
|
|
|
|
return [x for x in l if x[0] != "_"]
|
|
|
|
|
|
|
|
|
2010-10-12 19:10:39 +08:00
|
|
|
class ParsedCall:
|
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()
|
|
|
|
del d['_name']
|
|
|
|
return "<ParsedCall %r(**%r)>" %(self._name, d)
|
|
|
|
|
2014-10-04 21:49:31 +08:00
|
|
|
|
2010-10-12 19:10:39 +08:00
|
|
|
class HookRecorder:
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Record all hooks called in a plugin manager.
|
|
|
|
|
|
|
|
This wraps all the hook calls in the plugin manager, recording
|
|
|
|
each call before propagating the normal calls.
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
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:
|
|
|
|
print_("NAMEMATCH", name, call)
|
|
|
|
if eval(check, backlocals, call.__dict__):
|
|
|
|
print_("CHECKERMATCH", repr(check), "->", call)
|
|
|
|
else:
|
|
|
|
print_("NOCHECKERMATCH", repr(check), "-", call)
|
|
|
|
continue
|
|
|
|
i += ind + 1
|
|
|
|
break
|
|
|
|
print_("NONAMEMATCH", name, "with", call)
|
|
|
|
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):
|
|
|
|
l = self.getcalls(name)
|
|
|
|
assert len(l) == 1, (name, l)
|
|
|
|
return l[0]
|
|
|
|
|
2014-10-06 19:37:57 +08:00
|
|
|
# functionality for test reports
|
|
|
|
|
|
|
|
def getreports(self,
|
|
|
|
names="pytest_runtest_logreport pytest_collectreport"):
|
|
|
|
return [x.report for x in self.getcalls(names)]
|
|
|
|
|
|
|
|
def matchreport(self, inamepart="",
|
|
|
|
names="pytest_runtest_logreport pytest_collectreport", when=None):
|
|
|
|
""" return a testreport whose dotted import path matches """
|
|
|
|
l = []
|
|
|
|
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
|
|
|
|
if when and getattr(rep, 'when', None) != when:
|
|
|
|
continue
|
|
|
|
if not inamepart or inamepart in rep.nodeid.split("::"):
|
|
|
|
l.append(rep)
|
|
|
|
if not l:
|
|
|
|
raise ValueError("could not find test report matching %r: "
|
|
|
|
"no test reports at all!" % (inamepart,))
|
|
|
|
if len(l) > 1:
|
|
|
|
raise ValueError(
|
|
|
|
"found 2 or more testreports matching %r: %s" %(inamepart, l))
|
|
|
|
return l[0]
|
|
|
|
|
|
|
|
def getfailures(self,
|
|
|
|
names='pytest_runtest_logreport pytest_collectreport'):
|
|
|
|
return [rep for rep in self.getreports(names) if rep.failed]
|
|
|
|
|
|
|
|
def getfailedcollections(self):
|
|
|
|
return self.getfailures('pytest_collectreport')
|
|
|
|
|
|
|
|
def listoutcomes(self):
|
|
|
|
passed = []
|
|
|
|
skipped = []
|
|
|
|
failed = []
|
|
|
|
for rep in self.getreports(
|
|
|
|
"pytest_collectreport pytest_runtest_logreport"):
|
|
|
|
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
|
|
|
|
2009-05-19 05:26:16 +08:00
|
|
|
def pytest_funcarg__LineMatcher(request):
|
|
|
|
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
|
|
|
|
|
|
|
|
2015-08-28 06:59:52 +08:00
|
|
|
rex_outcome = re.compile("(\d+) ([\w-]+)")
|
2009-02-27 18:18:27 +08:00
|
|
|
class RunResult:
|
2015-04-12 00:07:37 +08:00
|
|
|
"""The result of running a command.
|
|
|
|
|
|
|
|
Attributes:
|
|
|
|
|
|
|
|
: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
|
2015-04-12 00:07:37 +08:00
|
|
|
reconstruct stdout or the commonly used
|
|
|
|
``stdout.fnmatch_lines()`` method.
|
2015-04-28 17:54:53 +08:00
|
|
|
:stderrr: :py:class:`LineMatcher` of stderr.
|
2015-04-12 00:07:37 +08:00
|
|
|
:duration: Duration in seconds.
|
|
|
|
|
|
|
|
"""
|
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):
|
2015-04-28 17:54:45 +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):
|
|
|
|
if 'seconds' in line:
|
|
|
|
outcomes = rex_outcome.findall(line)
|
|
|
|
if outcomes:
|
|
|
|
d = {}
|
|
|
|
for num, cat in outcomes:
|
|
|
|
d[cat] = int(num)
|
|
|
|
return d
|
2009-02-27 18:18:27 +08:00
|
|
|
|
2015-04-28 17:54:45 +08:00
|
|
|
def assert_outcomes(self, passed=0, skipped=0, failed=0):
|
|
|
|
""" 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()
|
|
|
|
assert passed == d.get("passed", 0)
|
|
|
|
assert skipped == d.get("skipped", 0)
|
|
|
|
assert failed == d.get("failed", 0)
|
|
|
|
|
|
|
|
|
2015-04-28 17:54:45 +08:00
|
|
|
|
2015-04-28 17:54:53 +08:00
|
|
|
class Testdir:
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Temporary test directory with tools to test/run py.test itself.
|
|
|
|
|
|
|
|
This is based on the ``tmpdir`` fixture but provides a number of
|
|
|
|
methods which aid with testing py.test itself. Unless
|
|
|
|
:py:meth:`chdir` is used all methods will use :py:attr:`tmpdir` as
|
|
|
|
current working directory.
|
|
|
|
|
|
|
|
Attributes:
|
|
|
|
|
|
|
|
:tmpdir: The :py:class:`py.path.local` instance of the temporary
|
|
|
|
directory.
|
|
|
|
|
|
|
|
:plugins: A list of plugins to use with :py:meth:`parseconfig` and
|
|
|
|
: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 depend on the method which uses them so refer to them
|
|
|
|
for details.
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
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
|
2010-07-27 03:15:15 +08:00
|
|
|
# XXX remove duplication with tmpdir plugin
|
2015-07-16 07:03:58 +08:00
|
|
|
basetmp = tmpdir_factory.ensuretemp("testdir")
|
2009-04-15 01:57:00 +08:00
|
|
|
name = request.function.__name__
|
2009-02-27 18:18:27 +08:00
|
|
|
for i in range(100):
|
|
|
|
try:
|
|
|
|
tmpdir = basetmp.mkdir(name + str(i))
|
|
|
|
except py.error.EEXIST:
|
|
|
|
continue
|
|
|
|
break
|
2013-02-04 03:47:39 +08:00
|
|
|
self.tmpdir = tmpdir
|
2009-02-27 18:18:27 +08:00
|
|
|
self.plugins = []
|
2015-04-28 17:54:46 +08:00
|
|
|
self._savesyspath = (list(sys.path), list(sys.meta_path))
|
|
|
|
self._savemodulekeys = set(sys.modules)
|
2010-01-02 18:57:42 +08:00
|
|
|
self.chdir() # always 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.
|
|
|
|
|
|
|
|
Some methods modify the global interpreter state and this
|
|
|
|
tries to clean this up. It does not remove the temporary
|
2015-04-21 10:18:04 +08:00
|
|
|
directory however so it can be looked at after the test run
|
2015-04-12 00:07:37 +08:00
|
|
|
has finished.
|
|
|
|
|
|
|
|
"""
|
2015-04-28 17:54:46 +08:00
|
|
|
sys.path[:], sys.meta_path[:] = self._savesyspath
|
2009-02-27 18:18:27 +08:00
|
|
|
if hasattr(self, '_olddir'):
|
|
|
|
self._olddir.chdir()
|
2015-04-21 10:18:04 +08:00
|
|
|
self.delete_loaded_modules()
|
|
|
|
|
|
|
|
def delete_loaded_modules(self):
|
2015-04-28 17:54:46 +08:00
|
|
|
"""Delete modules that have been loaded during a test.
|
2015-04-21 10:18:04 +08:00
|
|
|
|
|
|
|
This allows the interpreter to catch module changes in case
|
|
|
|
the module is re-imported.
|
|
|
|
"""
|
2015-04-28 17:54:46 +08:00
|
|
|
for name in set(sys.modules).difference(self._savemodulekeys):
|
|
|
|
# it seems zope.interfaces is keeping some state
|
|
|
|
# (used by twisted related tests)
|
|
|
|
if name != "zope.interface":
|
|
|
|
del sys.modules[name]
|
2009-02-27 18:18:27 +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.
|
|
|
|
|
|
|
|
"""
|
2009-04-01 01:58:02 +08:00
|
|
|
old = self.tmpdir.chdir()
|
2009-02-27 18:18:27 +08:00
|
|
|
if not hasattr(self, '_olddir'):
|
2010-07-27 03:15:15 +08:00
|
|
|
self._olddir = old
|
2009-02-27 18:18:27 +08:00
|
|
|
|
|
|
|
def _makefile(self, ext, args, kwargs):
|
2009-08-29 01:16:15 +08:00
|
|
|
items = list(kwargs.items())
|
2009-02-27 18:18:27 +08:00
|
|
|
if args:
|
2011-04-12 06:15:56 +08:00
|
|
|
source = py.builtin._totext("\n").join(
|
|
|
|
map(py.builtin._totext, args)) + py.builtin._totext("\n")
|
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))
|
|
|
|
ret = None
|
|
|
|
for name, value in items:
|
|
|
|
p = self.tmpdir.join(name).new(ext=ext)
|
2014-03-29 00:44:18 +08:00
|
|
|
source = py.code.Source(value)
|
|
|
|
def my_totext(s, encoding="utf-8"):
|
|
|
|
if py.builtin._isbytes(s):
|
|
|
|
s = py.builtin._totext(s, encoding=encoding)
|
|
|
|
return s
|
|
|
|
source_unicode = "\n".join([my_totext(line) for line in source.lines])
|
|
|
|
source = py.builtin._totext(source_unicode)
|
|
|
|
content = source.strip().encode("utf-8") # + "\n"
|
2012-09-20 16:57:23 +08:00
|
|
|
#content = content.rstrip() + "\n"
|
|
|
|
p.write(content, "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.
|
|
|
|
|
|
|
|
ext: The extension the file should use, including the dot.
|
|
|
|
E.g. ".py".
|
|
|
|
|
|
|
|
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.
|
|
|
|
E.g. "testdir.makefile('.txt', 'line1', 'line2')"
|
|
|
|
|
|
|
|
kwargs: Each keyword is the name of a file, while the value of
|
|
|
|
it will be written as contents of the file.
|
|
|
|
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."""
|
2010-11-01 00:41:58 +08:00
|
|
|
return self.makefile('.ini', tox=source)
|
|
|
|
|
|
|
|
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)
|
|
|
|
return py.iniconfig.IniConfig(p)['pytest']
|
|
|
|
|
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."""
|
2009-02-27 18:18:27 +08:00
|
|
|
return self._makefile('.py', args, kwargs)
|
|
|
|
|
|
|
|
def maketxtfile(self, *args, **kwargs):
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Shortcut for .makefile() with a .txt extension."""
|
2009-02-27 18:18:27 +08:00
|
|
|
return self._makefile('.txt', args, kwargs)
|
|
|
|
|
|
|
|
def syspathinsert(self, path=None):
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Prepend a directory to sys.path, defaults to :py:attr:`tmpdir`.
|
|
|
|
|
|
|
|
This is undone automatically after the test.
|
|
|
|
"""
|
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))
|
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.
|
|
|
|
|
|
|
|
This creates a (sub)direcotry with an empty ``__init__.py``
|
|
|
|
file so that is recognised as a python package.
|
|
|
|
|
|
|
|
"""
|
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
|
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
|
|
|
|
:py:meth:`parseconfig` and :py:meth:`parseconfigure` to
|
|
|
|
create the configuration.
|
|
|
|
|
|
|
|
:param arg: A :py:class:`py.path.local` instance of the file.
|
|
|
|
|
|
|
|
"""
|
2010-11-07 17:19:58 +08:00
|
|
|
session = Session(config)
|
2010-11-06 16:58:04 +08:00
|
|
|
assert '::' not in str(arg)
|
|
|
|
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.
|
|
|
|
|
|
|
|
This is like :py:meth:`getnode` but uses
|
|
|
|
:py:meth:`parseconfigure` to create the (configured) py.test
|
|
|
|
Config instance.
|
|
|
|
|
|
|
|
:param path: A :py:class:`py.path.local` instance of the file.
|
|
|
|
|
|
|
|
"""
|
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.
|
|
|
|
|
|
|
|
This recurses into the collection node and returns a list of
|
|
|
|
all the test items contained within.
|
|
|
|
|
|
|
|
"""
|
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.
|
|
|
|
|
|
|
|
The calling test instance (the class which contains the test
|
|
|
|
method) must provide a ``.getrunner()`` method which should
|
|
|
|
return a runner which can run the test protocol for a single
|
|
|
|
item, like e.g. :py:func:`_pytest.runner.runtestprotocol`.
|
|
|
|
|
|
|
|
"""
|
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
|
|
|
|
``pytest.main()`` on it, returning a :py:class:`HookRecorder`
|
|
|
|
instance for the result.
|
|
|
|
|
|
|
|
:param source: The source code of the test module.
|
|
|
|
|
|
|
|
:param cmdlineargs: Any extra command line arguments to use.
|
|
|
|
|
|
|
|
:return: :py:class:`HookRecorder` instance of the result.
|
|
|
|
|
|
|
|
"""
|
2009-02-27 18:18:27 +08:00
|
|
|
p = self.makepyfile(source)
|
|
|
|
l = list(cmdlineargs) + [p]
|
|
|
|
return self.inline_run(*l)
|
|
|
|
|
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.
|
|
|
|
|
|
|
|
Retuns a tuple of the collected items and a
|
|
|
|
:py:class:`HookRecorder` instance.
|
|
|
|
|
|
|
|
This runs the :py:func:`pytest.main` function to run all of
|
|
|
|
py.test inside the test process itself like
|
|
|
|
:py:meth:`inline_run`. However the return value is a tuple of
|
|
|
|
the collection items and a :py:class:`HookRecorder` instance.
|
|
|
|
|
|
|
|
"""
|
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.
|
|
|
|
|
|
|
|
This runs the :py:func:`pytest.main` function to run all of
|
|
|
|
py.test inside the test process itself. This means it can
|
|
|
|
return a :py:class:`HookRecorder` instance which gives more
|
|
|
|
detailed results from then run then can be done by matching
|
|
|
|
stdout/stderr from :py:meth:`runpytest`.
|
|
|
|
|
|
|
|
:param args: Any command line arguments to pass to
|
|
|
|
:py:func:`pytest.main`.
|
|
|
|
|
|
|
|
:param plugin: (keyword-only) Extra plugin instances the
|
|
|
|
``pytest.main()`` instance should use.
|
|
|
|
|
|
|
|
:return: A :py:class:`HookRecorder` instance.
|
|
|
|
|
|
|
|
"""
|
2011-11-08 02:08:41 +08:00
|
|
|
rec = []
|
|
|
|
class Collect:
|
|
|
|
def pytest_configure(x, config):
|
2014-10-06 19:37:57 +08:00
|
|
|
rec.append(self.make_hook_recorder(config.pluginmanager))
|
2015-05-07 17:02:55 +08:00
|
|
|
|
2014-10-06 19:37:57 +08:00
|
|
|
plugins = kwargs.get("plugins") or []
|
2011-11-08 02:08:41 +08:00
|
|
|
plugins.append(Collect())
|
2013-09-29 04:23:00 +08:00
|
|
|
ret = pytest.main(list(args), plugins=plugins)
|
2015-04-21 10:18:04 +08:00
|
|
|
self.delete_loaded_modules()
|
2015-04-28 17:54:45 +08:00
|
|
|
if len(rec) == 1:
|
|
|
|
reprec = rec.pop()
|
|
|
|
else:
|
|
|
|
class reprec:
|
|
|
|
pass
|
|
|
|
reprec.ret = ret
|
2015-05-07 17:02:55 +08:00
|
|
|
|
|
|
|
# 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()
|
2014-10-06 19:37:57 +08:00
|
|
|
return reprec
|
2009-02-27 18:18:27 +08:00
|
|
|
|
2015-04-28 17:54:53 +08:00
|
|
|
def runpytest_inprocess(self, *args, **kwargs):
|
2015-04-28 17:54:45 +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()
|
2015-04-28 17:54:46 +08:00
|
|
|
capture = py.io.StdCapture()
|
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:
|
|
|
|
class reprec:
|
|
|
|
ret = e.args[0]
|
|
|
|
except Exception:
|
|
|
|
traceback.print_exc()
|
|
|
|
class reprec:
|
|
|
|
ret = 3
|
2015-04-28 17:54:45 +08:00
|
|
|
finally:
|
|
|
|
out, err = capture.reset()
|
2015-04-28 17:54:46 +08:00
|
|
|
sys.stdout.write(out)
|
|
|
|
sys.stderr.write(err)
|
2015-04-28 17:54:45 +08:00
|
|
|
|
|
|
|
res = RunResult(reprec.ret,
|
|
|
|
out.split("\n"), err.split("\n"),
|
|
|
|
time.time()-now)
|
|
|
|
res.reprec = reprec
|
|
|
|
return res
|
|
|
|
|
2015-04-28 17:54:46 +08:00
|
|
|
def runpytest(self, *args, **kwargs):
|
2015-04-28 17:54:53 +08:00
|
|
|
""" Run pytest inline or in a subprocess, depending on the command line
|
|
|
|
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:
|
|
|
|
if str(x).startswith('--basetemp'):
|
|
|
|
#print ("basedtemp exists: %s" %(args,))
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
args.append("--basetemp=%s" % self.tmpdir.dirpath('basetemp'))
|
|
|
|
#print ("added basetemp: %s" %(args,))
|
|
|
|
return args
|
|
|
|
|
2009-02-27 18:18:27 +08:00
|
|
|
def parseconfig(self, *args):
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Return a new py.test Config instance from given commandline args.
|
|
|
|
|
|
|
|
This invokes the py.test bootstrapping code in _pytest.config
|
|
|
|
to create a new :py:class:`_pytest.core.PluginManager` and
|
|
|
|
call the pytest_cmdline_parse hook to create new
|
|
|
|
:py:class:`_pytest.config.Config` instance.
|
|
|
|
|
|
|
|
If :py:attr:`plugins` has been populated they should be plugin
|
|
|
|
modules which will be registered with the PluginManager.
|
|
|
|
|
|
|
|
"""
|
2015-05-06 20:58:46 +08:00
|
|
|
args = self._ensure_basetemp(args)
|
|
|
|
|
2013-09-30 19:14:14 +08:00
|
|
|
import _pytest.config
|
|
|
|
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):
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Return a new py.test configured Config instance.
|
|
|
|
|
|
|
|
This returns a new :py:class:`_pytest.config.Config` instance
|
|
|
|
like :py:meth:`parseconfig`, but also calls the
|
|
|
|
pytest_configure hook.
|
|
|
|
|
|
|
|
"""
|
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
|
|
|
|
|
2009-02-27 18:18:27 +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.
|
|
|
|
|
|
|
|
This writes the source to a python file and runs py.test's
|
|
|
|
collection on the resulting module, returning the test item
|
|
|
|
for the requested function name.
|
|
|
|
|
|
|
|
:param source: The module source.
|
|
|
|
|
|
|
|
:param funcname: The name of the test function for which the
|
|
|
|
Item must be returned.
|
|
|
|
|
|
|
|
"""
|
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
|
2012-07-20 20:16:28 +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
|
|
|
|
|
|
|
def getitems(self, source):
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Return all test items collected from the module.
|
|
|
|
|
|
|
|
This writes the source to a python file and runs py.test's
|
|
|
|
collection on the resulting module, returning all test items
|
|
|
|
contained within.
|
|
|
|
|
|
|
|
"""
|
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
|
|
|
|
|
|
|
def getmodulecol(self, source, configargs=(), withinit=False):
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Return the module collection node for ``source``.
|
|
|
|
|
|
|
|
This writes ``source`` to a file using :py:meth:`makepyfile`
|
|
|
|
and then runs the py.test collection on it, returning the
|
|
|
|
collection node for the test module.
|
|
|
|
|
|
|
|
:param source: The source code of the module to collect.
|
|
|
|
|
|
|
|
:param configargs: Any extra arguments to pass to
|
|
|
|
:py:meth:`parseconfigure`.
|
|
|
|
|
|
|
|
:param withinit: Whether to also write a ``__init__.py`` file
|
|
|
|
to the temporarly directory to ensure it is a package.
|
|
|
|
|
|
|
|
"""
|
2009-04-15 01:57:00 +08:00
|
|
|
kw = {self.request.function.__name__: py.code.Source(source).strip()}
|
2009-02-27 18:18:27 +08:00
|
|
|
path = self.makepyfile(**kw)
|
|
|
|
if withinit:
|
|
|
|
self.makepyfile(__init__ = "#")
|
2010-09-15 16:30:50 +08:00
|
|
|
self.config = config = self.parseconfigure(path, *configargs)
|
|
|
|
node = self.getnode(config, path)
|
|
|
|
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.
|
|
|
|
|
|
|
|
This will search a module collection node for a collection
|
|
|
|
node matching the given name.
|
|
|
|
|
|
|
|
:param modcol: A module collection node, see
|
|
|
|
:py:meth:`getmodulecol`.
|
|
|
|
|
|
|
|
:param name: The name of the node to return.
|
|
|
|
|
|
|
|
"""
|
2010-11-01 01:01:33 +08:00
|
|
|
for colitem in modcol._memocollect():
|
|
|
|
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.
|
|
|
|
|
|
|
|
This calls subprocess.Popen making sure the current working
|
|
|
|
directory is the PYTHONPATH.
|
|
|
|
|
|
|
|
You probably want to use :py:meth:`run` instead.
|
|
|
|
|
|
|
|
"""
|
2009-04-29 05:49:03 +08:00
|
|
|
env = os.environ.copy()
|
2010-11-14 02:46:28 +08:00
|
|
|
env['PYTHONPATH'] = os.pathsep.join(filter(None, [
|
2009-05-08 03:04:56 +08:00
|
|
|
str(os.getcwd()), env.get('PYTHONPATH', '')]))
|
2009-04-29 05:49:03 +08:00
|
|
|
kw['env'] = env
|
2014-08-01 06:13:40 +08:00
|
|
|
return subprocess.Popen(cmdargs,
|
|
|
|
stdout=stdout, stderr=stderr, **kw)
|
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.
|
|
|
|
|
|
|
|
Run a process using subprocess.Popen saving the stdout and
|
|
|
|
stderr.
|
|
|
|
|
|
|
|
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")
|
2015-05-09 21:24:33 +08:00
|
|
|
print_("running:", ' '.join(cmdargs))
|
|
|
|
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()
|
|
|
|
popen = self.popen(cmdargs, stdout=f1, stderr=f2,
|
|
|
|
close_fds=(sys.platform != "win32"))
|
|
|
|
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)
|
2009-12-30 18:37:46 +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:
|
|
|
|
py.builtin.print_(line, file=fp)
|
|
|
|
except UnicodeEncodeError:
|
|
|
|
print("couldn't print to %s because of encoding" % (fp,))
|
|
|
|
|
2015-04-28 17:54:53 +08:00
|
|
|
def _getpytestargs(self):
|
|
|
|
# we cannot use "(sys.executable,script)"
|
|
|
|
# because on windows the script is e.g. a py.test.exe
|
|
|
|
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`.
|
|
|
|
"""
|
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):
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Run py.test as a subprocess with given arguments.
|
|
|
|
|
|
|
|
Any plugins added to the :py:attr:`plugins` list will added
|
|
|
|
using the ``-p`` command line option. Addtionally
|
|
|
|
``--basetemp`` is used put any temporary files and directories
|
|
|
|
in a numbered directory prefixed with "runpytest-" so they do
|
|
|
|
not conflict with the normal numberd pytest location for
|
|
|
|
temporary files and directories.
|
|
|
|
|
|
|
|
Returns a :py:class:`RunResult`.
|
|
|
|
|
|
|
|
"""
|
2010-07-27 03:15:15 +08:00
|
|
|
p = py.path.local.make_numbered_dir(prefix="runpytest-",
|
2009-03-17 18:29:45 +08:00
|
|
|
keep=None, rootdir=self.tmpdir)
|
2010-07-27 03:15:15 +08:00
|
|
|
args = ('--basetemp=%s' % p, ) + args
|
2010-11-06 16:58:04 +08:00
|
|
|
#for x in args:
|
|
|
|
# if '--confcutdir' in str(x):
|
|
|
|
# break
|
|
|
|
#else:
|
|
|
|
# pass
|
|
|
|
# args = ('--confcutdir=.',) + args
|
2009-12-25 07:24:58 +08:00
|
|
|
plugins = [x for x in self.plugins if isinstance(x, str)]
|
|
|
|
if plugins:
|
|
|
|
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):
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Run py.test using pexpect.
|
|
|
|
|
|
|
|
This makes sure to use the right py.test and sets up the
|
|
|
|
temporary directory locations.
|
|
|
|
|
|
|
|
The pexpect child is returned.
|
|
|
|
|
|
|
|
"""
|
2009-05-06 17:47:48 +08:00
|
|
|
basetemp = self.tmpdir.mkdir("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.
|
|
|
|
"""
|
2014-01-18 19:31:33 +08:00
|
|
|
pexpect = pytest.importorskip("pexpect", "3.0")
|
2014-08-01 06:13:40 +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")
|
2011-11-12 05:33:45 +08:00
|
|
|
if sys.platform == "darwin":
|
|
|
|
pytest.xfail("pexpect does not work reliably on darwin?!")
|
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
|
|
|
|
|
2010-05-21 22:42:46 +08:00
|
|
|
def getdecoded(out):
|
|
|
|
try:
|
|
|
|
return out.decode("utf-8")
|
|
|
|
except UnicodeDecodeError:
|
|
|
|
return "INTERNAL not-utf8-decodeable, truncated string:\n%s" % (
|
|
|
|
py.io.saferepr(out),)
|
|
|
|
|
2009-02-27 18:18:27 +08:00
|
|
|
|
|
|
|
class LineComp:
|
|
|
|
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):
|
2010-07-27 03:15:15 +08:00
|
|
|
""" assert that lines2 are contained (linearly) in lines1.
|
2009-02-27 18:18:27 +08:00
|
|
|
return a list of extralines found.
|
|
|
|
"""
|
|
|
|
__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
|
|
|
|
2009-02-27 18:18:27 +08:00
|
|
|
class LineMatcher:
|
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.
|
|
|
|
|
|
|
|
The constructor takes a list of lines without their trailing
|
|
|
|
newlines, i.e. ``text.splitlines()``.
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
2009-02-27 18:18:27 +08:00
|
|
|
def __init__(self, lines):
|
|
|
|
self.lines = lines
|
|
|
|
|
|
|
|
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):
|
|
|
|
lines2 = py.code.Source(lines2)
|
|
|
|
if isinstance(lines2, py.code.Source):
|
|
|
|
lines2 = lines2.strip().lines
|
2010-09-28 02:48:30 +08:00
|
|
|
return lines2
|
|
|
|
|
|
|
|
def fnmatch_lines_random(self, lines2):
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Check lines exist in the output.
|
|
|
|
|
|
|
|
The argument is a list of lines which have to occur in the
|
|
|
|
output, in any order. Each line can contain glob whildcards.
|
|
|
|
|
|
|
|
"""
|
2010-09-28 02:48:30 +08:00
|
|
|
lines2 = self._getlines(lines2)
|
|
|
|
for line in lines2:
|
|
|
|
for x in self.lines:
|
|
|
|
if line == x or fnmatch(x, line):
|
|
|
|
print_("matched: ", repr(line))
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
raise ValueError("line %r not found in output" % line)
|
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.
|
|
|
|
"""
|
2013-10-01 18:37:11 +08:00
|
|
|
for i, line in enumerate(self.lines):
|
|
|
|
if fnline == line or fnmatch(line, fnline):
|
|
|
|
return self.lines[i+1:]
|
|
|
|
raise ValueError("line %r not found in output" % fnline)
|
|
|
|
|
2010-09-28 02:48:30 +08:00
|
|
|
def fnmatch_lines(self, lines2):
|
2015-04-12 00:07:37 +08:00
|
|
|
"""Search the text for matching lines.
|
|
|
|
|
|
|
|
The argument is a list of lines which have to match and can
|
|
|
|
use glob wildcards. If they do not match an pytest.fail() is
|
|
|
|
called. The matches and non-matches are also printed on
|
|
|
|
stdout.
|
|
|
|
|
|
|
|
"""
|
2010-11-06 16:58:04 +08:00
|
|
|
def show(arg1, arg2):
|
2014-08-01 06:13:40 +08:00
|
|
|
py.builtin.print_(arg1, arg2, file=sys.stderr)
|
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:
|
2010-11-06 16:58:04 +08:00
|
|
|
show("exact match:", repr(line))
|
2010-07-27 03:15:15 +08:00
|
|
|
break
|
2009-02-27 18:18:27 +08:00
|
|
|
elif fnmatch(nextline, line):
|
2010-11-06 16:58:04 +08:00
|
|
|
show("fnmatch:", repr(line))
|
|
|
|
show(" with:", repr(nextline))
|
2009-02-27 18:18:27 +08:00
|
|
|
break
|
|
|
|
else:
|
|
|
|
if not nomatchprinted:
|
2010-11-06 16:58:04 +08:00
|
|
|
show("nomatch:", repr(line))
|
2009-02-27 18:18:27 +08:00
|
|
|
nomatchprinted = True
|
2010-11-06 16:58:04 +08:00
|
|
|
show(" and:", repr(nextline))
|
2009-02-27 18:18:27 +08:00
|
|
|
extralines.append(nextline)
|
|
|
|
else:
|
2014-01-18 19:31:33 +08:00
|
|
|
pytest.fail("remains unmatched: %r, see stderr" % (line,))
|