2014-01-25 04:22:19 +08:00
|
|
|
"""
|
2014-03-14 19:49:36 +08:00
|
|
|
per-test stdout/stderr capturing mechanism.
|
|
|
|
|
2014-01-25 04:22:19 +08:00
|
|
|
"""
|
2017-03-17 09:21:30 +08:00
|
|
|
from __future__ import absolute_import, division, print_function
|
2014-03-14 22:58:16 +08:00
|
|
|
|
2017-10-29 02:53:19 +08:00
|
|
|
import collections
|
2016-06-09 07:21:17 +08:00
|
|
|
import contextlib
|
2013-09-30 19:14:16 +08:00
|
|
|
import sys
|
2009-09-05 22:54:52 +08:00
|
|
|
import os
|
2017-06-02 16:19:03 +08:00
|
|
|
import io
|
2016-09-26 18:15:35 +08:00
|
|
|
from io import UnsupportedOperation
|
2014-03-28 14:11:25 +08:00
|
|
|
from tempfile import TemporaryFile
|
2014-01-25 04:22:19 +08:00
|
|
|
|
2017-08-03 01:33:52 +08:00
|
|
|
import six
|
2014-01-25 04:22:19 +08:00
|
|
|
import pytest
|
2017-02-20 01:16:32 +08:00
|
|
|
from _pytest.compat import CaptureIO
|
2014-01-25 04:22:19 +08:00
|
|
|
|
|
|
|
|
|
|
|
patchsysdict = {0: 'stdin', 1: 'stdout', 2: 'stderr'}
|
|
|
|
|
2009-02-27 18:18:27 +08:00
|
|
|
|
2009-07-26 00:09:01 +08:00
|
|
|
def pytest_addoption(parser):
|
|
|
|
group = parser.getgroup("general")
|
2014-01-25 04:22:19 +08:00
|
|
|
group._addoption(
|
2014-07-28 19:17:37 +08:00
|
|
|
'--capture', action="store",
|
2014-04-01 20:32:12 +08:00
|
|
|
default="fd" if hasattr(os, "dup") else "sys",
|
2013-07-25 21:33:43 +08:00
|
|
|
metavar="method", choices=['fd', 'sys', 'no'],
|
2014-04-01 20:32:12 +08:00
|
|
|
help="per-test capturing method: one of fd|sys|no.")
|
2014-01-25 04:22:19 +08:00
|
|
|
group._addoption(
|
|
|
|
'-s', action="store_const", const="no", dest="capture",
|
2009-10-17 23:43:59 +08:00
|
|
|
help="shortcut for --capture=no.")
|
2009-07-31 20:21:02 +08:00
|
|
|
|
2014-01-25 04:22:19 +08:00
|
|
|
|
2015-05-06 16:08:08 +08:00
|
|
|
@pytest.hookimpl(hookwrapper=True)
|
2014-10-09 02:23:40 +08:00
|
|
|
def pytest_load_initial_conftests(early_config, parser, args):
|
2014-04-02 17:29:23 +08:00
|
|
|
ns = early_config.known_args_namespace
|
2017-06-02 16:19:03 +08:00
|
|
|
if ns.capture == "fd":
|
2017-08-08 07:55:28 +08:00
|
|
|
_py36_windowsconsoleio_workaround(sys.stdout)
|
2017-07-24 20:17:39 +08:00
|
|
|
_colorama_workaround()
|
2017-06-02 16:19:03 +08:00
|
|
|
_readline_workaround()
|
2014-03-14 19:49:36 +08:00
|
|
|
pluginmanager = early_config.pluginmanager
|
2014-04-01 21:03:17 +08:00
|
|
|
capman = CaptureManager(ns.capture)
|
2014-03-14 19:49:36 +08:00
|
|
|
pluginmanager.register(capman, "capturemanager")
|
2014-01-25 04:22:19 +08:00
|
|
|
|
2013-09-29 04:23:00 +08:00
|
|
|
# make sure that capturemanager is properly reset at final shutdown
|
2017-09-27 06:54:26 +08:00
|
|
|
early_config.add_cleanup(capman.stop_global_capturing)
|
2014-01-25 04:22:19 +08:00
|
|
|
|
2013-10-02 18:39:01 +08:00
|
|
|
# make sure logging does not raise exceptions at the end
|
2013-09-30 22:09:26 +08:00
|
|
|
def silence_logging_at_shutdown():
|
|
|
|
if "logging" in sys.modules:
|
|
|
|
sys.modules["logging"].raiseExceptions = False
|
2015-04-22 22:33:20 +08:00
|
|
|
early_config.add_cleanup(silence_logging_at_shutdown)
|
2013-09-30 19:14:16 +08:00
|
|
|
|
|
|
|
# finally trigger conftest loading but while capturing (issue93)
|
2017-09-27 06:54:26 +08:00
|
|
|
capman.start_global_capturing()
|
2014-10-09 02:23:40 +08:00
|
|
|
outcome = yield
|
2017-09-27 06:54:26 +08:00
|
|
|
out, err = capman.suspend_global_capture()
|
2014-10-09 02:23:40 +08:00
|
|
|
if outcome.excinfo is not None:
|
2013-09-30 19:14:16 +08:00
|
|
|
sys.stdout.write(out)
|
|
|
|
sys.stderr.write(err)
|
2011-11-08 02:08:41 +08:00
|
|
|
|
2014-01-25 04:22:19 +08:00
|
|
|
|
2017-05-18 05:16:11 +08:00
|
|
|
class CaptureManager:
|
2017-09-26 13:34:41 +08:00
|
|
|
"""
|
|
|
|
Capture plugin, manages that the appropriate capture method is enabled/disabled during collection and each
|
|
|
|
test phase (setup, call, teardown). After each of those points, the captured output is obtained and
|
|
|
|
attached to the collection/runtest report.
|
|
|
|
|
|
|
|
There are two levels of capture:
|
|
|
|
* global: which is enabled by default and can be suppressed by the ``-s`` option. This is always enabled/disabled
|
|
|
|
during collection and each test phase.
|
|
|
|
* fixture: when a test function or one of its fixture depend on the ``capsys`` or ``capfd`` fixtures. In this
|
|
|
|
case special handling is needed to ensure the fixtures take precedence over the global capture.
|
|
|
|
"""
|
|
|
|
|
2014-04-01 20:32:12 +08:00
|
|
|
def __init__(self, method):
|
|
|
|
self._method = method
|
2017-09-27 06:54:26 +08:00
|
|
|
self._global_capturing = None
|
2009-07-31 20:21:02 +08:00
|
|
|
|
2010-05-18 01:00:39 +08:00
|
|
|
def _getcapture(self, method):
|
2010-07-27 03:15:15 +08:00
|
|
|
if method == "fd":
|
2014-04-01 20:19:52 +08:00
|
|
|
return MultiCapture(out=True, err=True, Capture=FDCapture)
|
2009-07-31 20:21:02 +08:00
|
|
|
elif method == "sys":
|
2014-04-01 20:19:52 +08:00
|
|
|
return MultiCapture(out=True, err=True, Capture=SysCapture)
|
2010-05-18 01:00:39 +08:00
|
|
|
elif method == "no":
|
2014-04-01 20:19:52 +08:00
|
|
|
return MultiCapture(out=False, err=False, in_=False)
|
2009-07-31 20:21:02 +08:00
|
|
|
else:
|
|
|
|
raise ValueError("unknown capturing method: %r" % method)
|
|
|
|
|
2017-09-27 06:54:26 +08:00
|
|
|
def start_global_capturing(self):
|
|
|
|
assert self._global_capturing is None
|
|
|
|
self._global_capturing = self._getcapture(self._method)
|
|
|
|
self._global_capturing.start_capturing()
|
2009-07-31 20:21:02 +08:00
|
|
|
|
2017-09-27 06:54:26 +08:00
|
|
|
def stop_global_capturing(self):
|
|
|
|
if self._global_capturing is not None:
|
|
|
|
self._global_capturing.pop_outerr_to_orig()
|
|
|
|
self._global_capturing.stop_capturing()
|
|
|
|
self._global_capturing = None
|
2009-07-31 20:21:02 +08:00
|
|
|
|
2017-09-27 06:54:26 +08:00
|
|
|
def resume_global_capture(self):
|
|
|
|
self._global_capturing.resume_capturing()
|
2014-04-01 20:32:12 +08:00
|
|
|
|
2017-09-27 06:54:26 +08:00
|
|
|
def suspend_global_capture(self, item=None, in_=False):
|
2017-09-26 13:34:41 +08:00
|
|
|
if item is not None:
|
|
|
|
self.deactivate_fixture(item)
|
2017-09-27 06:54:26 +08:00
|
|
|
cap = getattr(self, "_global_capturing", None)
|
2014-04-01 20:32:12 +08:00
|
|
|
if cap is not None:
|
2015-07-26 07:15:51 +08:00
|
|
|
try:
|
|
|
|
outerr = cap.readouterr()
|
|
|
|
finally:
|
|
|
|
cap.suspend_capturing(in_=in_)
|
2014-04-01 20:32:12 +08:00
|
|
|
return outerr
|
2009-07-31 20:21:02 +08:00
|
|
|
|
2017-09-26 13:34:41 +08:00
|
|
|
def activate_fixture(self, item):
|
|
|
|
"""If the current item is using ``capsys`` or ``capfd``, activate them so they take precedence over
|
|
|
|
the global capture.
|
|
|
|
"""
|
|
|
|
fixture = getattr(item, "_capture_fixture", None)
|
|
|
|
if fixture is not None:
|
|
|
|
fixture._start()
|
2009-07-31 20:21:02 +08:00
|
|
|
|
2017-09-26 13:34:41 +08:00
|
|
|
def deactivate_fixture(self, item):
|
|
|
|
"""Deactivates the ``capsys`` or ``capfd`` fixture of this item, if any."""
|
|
|
|
fixture = getattr(item, "_capture_fixture", None)
|
|
|
|
if fixture is not None:
|
|
|
|
fixture.close()
|
2009-07-31 20:21:02 +08:00
|
|
|
|
2015-05-06 16:08:08 +08:00
|
|
|
@pytest.hookimpl(hookwrapper=True)
|
2014-10-09 02:23:40 +08:00
|
|
|
def pytest_make_collect_report(self, collector):
|
|
|
|
if isinstance(collector, pytest.File):
|
2017-09-27 06:54:26 +08:00
|
|
|
self.resume_global_capture()
|
2014-10-09 02:23:40 +08:00
|
|
|
outcome = yield
|
2017-09-27 06:54:26 +08:00
|
|
|
out, err = self.suspend_global_capture()
|
2014-10-09 02:23:40 +08:00
|
|
|
rep = outcome.get_result()
|
|
|
|
if out:
|
|
|
|
rep.sections.append(("Captured stdout", out))
|
|
|
|
if err:
|
|
|
|
rep.sections.append(("Captured stderr", err))
|
|
|
|
else:
|
|
|
|
yield
|
2014-03-14 19:49:36 +08:00
|
|
|
|
2015-05-06 16:08:08 +08:00
|
|
|
@pytest.hookimpl(hookwrapper=True)
|
2009-07-26 00:09:01 +08:00
|
|
|
def pytest_runtest_setup(self, item):
|
2017-09-27 06:54:26 +08:00
|
|
|
self.resume_global_capture()
|
2017-09-26 13:34:41 +08:00
|
|
|
# no need to activate a capture fixture because they activate themselves during creation; this
|
|
|
|
# only makes sense when a fixture uses a capture fixture, otherwise the capture fixture will
|
|
|
|
# be activated during pytest_runtest_call
|
2014-04-01 21:03:17 +08:00
|
|
|
yield
|
2017-09-27 06:54:26 +08:00
|
|
|
self.suspend_capture_item(item, "setup")
|
2009-07-26 00:09:01 +08:00
|
|
|
|
2015-05-06 16:08:08 +08:00
|
|
|
@pytest.hookimpl(hookwrapper=True)
|
2009-07-26 00:09:01 +08:00
|
|
|
def pytest_runtest_call(self, item):
|
2017-09-27 06:54:26 +08:00
|
|
|
self.resume_global_capture()
|
2017-09-26 13:34:41 +08:00
|
|
|
# it is important to activate this fixture during the call phase so it overwrites the "global"
|
|
|
|
# capture
|
|
|
|
self.activate_fixture(item)
|
2014-04-01 21:03:17 +08:00
|
|
|
yield
|
2017-09-27 06:54:26 +08:00
|
|
|
self.suspend_capture_item(item, "call")
|
2009-07-26 00:09:01 +08:00
|
|
|
|
2015-05-06 16:08:08 +08:00
|
|
|
@pytest.hookimpl(hookwrapper=True)
|
2009-07-26 00:09:01 +08:00
|
|
|
def pytest_runtest_teardown(self, item):
|
2017-09-27 06:54:26 +08:00
|
|
|
self.resume_global_capture()
|
2017-09-26 13:34:41 +08:00
|
|
|
self.activate_fixture(item)
|
2014-04-01 21:03:17 +08:00
|
|
|
yield
|
2017-09-27 06:54:26 +08:00
|
|
|
self.suspend_capture_item(item, "teardown")
|
2009-07-26 00:09:01 +08:00
|
|
|
|
2015-05-06 16:08:08 +08:00
|
|
|
@pytest.hookimpl(tryfirst=True)
|
2009-07-26 00:09:01 +08:00
|
|
|
def pytest_keyboard_interrupt(self, excinfo):
|
2017-09-27 06:54:26 +08:00
|
|
|
self.stop_global_capturing()
|
2009-07-26 00:09:01 +08:00
|
|
|
|
2015-05-06 16:08:08 +08:00
|
|
|
@pytest.hookimpl(tryfirst=True)
|
2014-03-14 19:49:36 +08:00
|
|
|
def pytest_internalerror(self, excinfo):
|
2017-09-27 06:54:26 +08:00
|
|
|
self.stop_global_capturing()
|
2014-03-14 19:49:36 +08:00
|
|
|
|
2017-09-27 06:54:26 +08:00
|
|
|
def suspend_capture_item(self, item, when, in_=False):
|
|
|
|
out, err = self.suspend_global_capture(item, in_=in_)
|
2015-09-23 02:29:16 +08:00
|
|
|
item.add_report_section(when, "stdout", out)
|
|
|
|
item.add_report_section(when, "stderr", err)
|
2009-07-26 00:09:01 +08:00
|
|
|
|
2016-11-21 04:59:15 +08:00
|
|
|
|
2017-11-18 01:02:46 +08:00
|
|
|
capture_fixtures = {'capfd', 'capfdbinary', 'capsys', 'capsysbinary'}
|
2017-11-15 06:08:23 +08:00
|
|
|
|
|
|
|
|
|
|
|
def _ensure_only_one_capture_fixture(request, name):
|
|
|
|
fixtures = set(request.fixturenames) & capture_fixtures - set((name,))
|
|
|
|
if fixtures:
|
|
|
|
fixtures = sorted(fixtures)
|
|
|
|
fixtures = fixtures[0] if len(fixtures) == 1 else fixtures
|
|
|
|
raise request.raiseerror(
|
|
|
|
"cannot use {0} and {1} at the same time".format(
|
|
|
|
fixtures, name,
|
|
|
|
),
|
|
|
|
)
|
2012-06-04 03:01:27 +08:00
|
|
|
|
2014-01-25 04:22:19 +08:00
|
|
|
|
2014-03-28 16:46:38 +08:00
|
|
|
@pytest.fixture
|
|
|
|
def capsys(request):
|
2016-07-22 18:39:06 +08:00
|
|
|
"""Enable capturing of writes to sys.stdout/sys.stderr and make
|
2011-03-04 06:40:38 +08:00
|
|
|
captured output available via ``capsys.readouterr()`` method calls
|
2017-11-15 06:08:23 +08:00
|
|
|
which return a ``(out, err)`` tuple. ``out`` and ``err`` will be ``text``
|
|
|
|
objects.
|
2010-07-27 03:15:15 +08:00
|
|
|
"""
|
2017-11-15 06:08:23 +08:00
|
|
|
_ensure_only_one_capture_fixture(request, 'capsys')
|
2017-09-26 13:34:41 +08:00
|
|
|
with _install_capture_fixture_on_item(request, SysCapture) as fixture:
|
|
|
|
yield fixture
|
2009-02-27 18:18:27 +08:00
|
|
|
|
2017-07-17 07:25:09 +08:00
|
|
|
|
2017-11-18 01:02:46 +08:00
|
|
|
@pytest.fixture
|
|
|
|
def capsysbinary(request):
|
|
|
|
"""Enable capturing of writes to sys.stdout/sys.stderr and make
|
|
|
|
captured output available via ``capsys.readouterr()`` method calls
|
|
|
|
which return a ``(out, err)`` tuple. ``out`` and ``err`` will be ``bytes``
|
|
|
|
objects.
|
|
|
|
"""
|
|
|
|
_ensure_only_one_capture_fixture(request, 'capsysbinary')
|
|
|
|
# Currently, the implementation uses the python3 specific `.buffer`
|
|
|
|
# property of CaptureIO.
|
|
|
|
if sys.version_info < (3,):
|
|
|
|
raise request.raiseerror('capsysbinary is only supported on python 3')
|
|
|
|
with _install_capture_fixture_on_item(request, SysCaptureBinary) as fixture:
|
|
|
|
yield fixture
|
|
|
|
|
|
|
|
|
2014-03-28 16:46:38 +08:00
|
|
|
@pytest.fixture
|
|
|
|
def capfd(request):
|
2016-07-22 18:39:06 +08:00
|
|
|
"""Enable capturing of writes to file descriptors 1 and 2 and make
|
2014-04-03 15:59:04 +08:00
|
|
|
captured output available via ``capfd.readouterr()`` method calls
|
2017-11-15 06:08:23 +08:00
|
|
|
which return a ``(out, err)`` tuple. ``out`` and ``err`` will be ``text``
|
|
|
|
objects.
|
2010-07-27 03:15:15 +08:00
|
|
|
"""
|
2017-11-15 06:08:23 +08:00
|
|
|
_ensure_only_one_capture_fixture(request, 'capfd')
|
2010-05-18 01:00:39 +08:00
|
|
|
if not hasattr(os, 'dup'):
|
2017-09-26 13:34:41 +08:00
|
|
|
pytest.skip("capfd fixture needs os.dup function which is not available in this system")
|
|
|
|
with _install_capture_fixture_on_item(request, FDCapture) as fixture:
|
|
|
|
yield fixture
|
|
|
|
|
|
|
|
|
2017-11-15 06:08:23 +08:00
|
|
|
@pytest.fixture
|
|
|
|
def capfdbinary(request):
|
|
|
|
"""Enable capturing of write to file descriptors 1 and 2 and make
|
|
|
|
captured output available via ``capfdbinary.readouterr`` method calls
|
|
|
|
which return a ``(out, err)`` tuple. ``out`` and ``err`` will be
|
|
|
|
``bytes`` objects.
|
|
|
|
"""
|
|
|
|
_ensure_only_one_capture_fixture(request, 'capfdbinary')
|
|
|
|
if not hasattr(os, 'dup'):
|
|
|
|
pytest.skip("capfdbinary fixture needs os.dup function which is not available in this system")
|
|
|
|
with _install_capture_fixture_on_item(request, FDCaptureBinary) as fixture:
|
|
|
|
yield fixture
|
|
|
|
|
|
|
|
|
2017-09-26 13:34:41 +08:00
|
|
|
@contextlib.contextmanager
|
|
|
|
def _install_capture_fixture_on_item(request, capture_class):
|
|
|
|
"""
|
|
|
|
Context manager which creates a ``CaptureFixture`` instance and "installs" it on
|
|
|
|
the item/node of the given request. Used by ``capsys`` and ``capfd``.
|
|
|
|
|
|
|
|
The CaptureFixture is added as attribute of the item because it needs to accessed
|
|
|
|
by ``CaptureManager`` during its ``pytest_runtest_*`` hooks.
|
|
|
|
"""
|
|
|
|
request.node._capture_fixture = fixture = CaptureFixture(capture_class, request)
|
|
|
|
capmanager = request.config.pluginmanager.getplugin('capturemanager')
|
|
|
|
# need to active this fixture right away in case it is being used by another fixture (setup phase)
|
|
|
|
# if this fixture is being used only by a test function (call phase), then we wouldn't need this
|
|
|
|
# activation, but it doesn't hurt
|
|
|
|
capmanager.activate_fixture(request.node)
|
|
|
|
yield fixture
|
|
|
|
fixture.close()
|
|
|
|
del request.node._capture_fixture
|
2014-01-25 04:22:19 +08:00
|
|
|
|
2009-06-09 22:08:34 +08:00
|
|
|
|
2017-05-18 05:16:11 +08:00
|
|
|
class CaptureFixture:
|
2016-06-09 07:21:17 +08:00
|
|
|
def __init__(self, captureclass, request):
|
2014-03-28 14:11:25 +08:00
|
|
|
self.captureclass = captureclass
|
2016-06-09 07:21:17 +08:00
|
|
|
self.request = request
|
2009-07-31 20:21:02 +08:00
|
|
|
|
|
|
|
def _start(self):
|
2014-04-01 20:19:52 +08:00
|
|
|
self._capture = MultiCapture(out=True, err=True, in_=False,
|
2016-06-09 07:21:17 +08:00
|
|
|
Capture=self.captureclass)
|
2014-03-14 19:49:36 +08:00
|
|
|
self._capture.start_capturing()
|
2009-02-27 18:18:27 +08:00
|
|
|
|
2014-03-28 14:13:08 +08:00
|
|
|
def close(self):
|
|
|
|
cap = self.__dict__.pop("_capture", None)
|
|
|
|
if cap is not None:
|
2014-04-01 20:32:12 +08:00
|
|
|
self._outerr = cap.pop_outerr_to_orig()
|
2014-03-28 14:13:08 +08:00
|
|
|
cap.stop_capturing()
|
2009-02-27 18:18:27 +08:00
|
|
|
|
2009-07-31 20:21:02 +08:00
|
|
|
def readouterr(self):
|
2012-11-22 03:43:31 +08:00
|
|
|
try:
|
2014-01-25 04:22:19 +08:00
|
|
|
return self._capture.readouterr()
|
2012-11-22 03:43:31 +08:00
|
|
|
except AttributeError:
|
2014-04-01 20:32:12 +08:00
|
|
|
return self._outerr
|
2014-01-25 04:22:19 +08:00
|
|
|
|
2016-06-09 07:21:17 +08:00
|
|
|
@contextlib.contextmanager
|
|
|
|
def disabled(self):
|
2017-09-30 04:24:31 +08:00
|
|
|
self._capture.suspend_capturing()
|
2016-06-09 07:21:17 +08:00
|
|
|
capmanager = self.request.config.pluginmanager.getplugin('capturemanager')
|
2017-09-30 04:24:31 +08:00
|
|
|
capmanager.suspend_global_capture(item=None, in_=False)
|
2016-06-09 07:21:17 +08:00
|
|
|
try:
|
|
|
|
yield
|
|
|
|
finally:
|
2017-09-27 06:54:26 +08:00
|
|
|
capmanager.resume_global_capture()
|
2017-09-30 04:24:31 +08:00
|
|
|
self._capture.resume_capturing()
|
2016-06-09 07:21:17 +08:00
|
|
|
|
2014-01-25 04:22:19 +08:00
|
|
|
|
2014-03-28 18:27:02 +08:00
|
|
|
def safe_text_dupfile(f, mode, default_encoding="UTF8"):
|
|
|
|
""" return a open text file object that's a duplicate of f on the
|
|
|
|
FD-level if possible.
|
2014-01-25 04:22:19 +08:00
|
|
|
"""
|
2014-03-28 18:27:02 +08:00
|
|
|
encoding = getattr(f, "encoding", None)
|
2014-01-25 04:22:19 +08:00
|
|
|
try:
|
|
|
|
fd = f.fileno()
|
2014-03-28 18:27:02 +08:00
|
|
|
except Exception:
|
|
|
|
if "b" not in getattr(f, "mode", "") and hasattr(f, "encoding"):
|
|
|
|
# we seem to have a text stream, let's just use it
|
|
|
|
return f
|
2014-01-25 04:22:19 +08:00
|
|
|
else:
|
2014-03-28 18:27:02 +08:00
|
|
|
newfd = os.dup(fd)
|
|
|
|
if "b" not in mode:
|
|
|
|
mode += "b"
|
|
|
|
f = os.fdopen(newfd, mode, 0) # no buffering
|
|
|
|
return EncodedFile(f, encoding or default_encoding)
|
2014-01-25 04:22:19 +08:00
|
|
|
|
|
|
|
|
|
|
|
class EncodedFile(object):
|
2014-08-07 17:05:42 +08:00
|
|
|
errors = "strict" # possibly needed by py3 code (issue555)
|
2017-07-17 07:25:09 +08:00
|
|
|
|
2014-03-28 18:27:02 +08:00
|
|
|
def __init__(self, buffer, encoding):
|
|
|
|
self.buffer = buffer
|
2014-01-25 04:22:19 +08:00
|
|
|
self.encoding = encoding
|
|
|
|
|
|
|
|
def write(self, obj):
|
2017-08-03 01:33:52 +08:00
|
|
|
if isinstance(obj, six.text_type):
|
2014-03-28 18:27:02 +08:00
|
|
|
obj = obj.encode(self.encoding, "replace")
|
|
|
|
self.buffer.write(obj)
|
2014-01-25 04:22:19 +08:00
|
|
|
|
|
|
|
def writelines(self, linelist):
|
|
|
|
data = ''.join(linelist)
|
|
|
|
self.write(data)
|
|
|
|
|
2017-07-06 03:54:33 +08:00
|
|
|
@property
|
|
|
|
def name(self):
|
|
|
|
"""Ensure that file.name is a string."""
|
|
|
|
return repr(self.buffer)
|
|
|
|
|
2014-01-25 04:22:19 +08:00
|
|
|
def __getattr__(self, name):
|
2014-09-06 06:55:14 +08:00
|
|
|
return getattr(object.__getattribute__(self, "buffer"), name)
|
2014-01-25 04:22:19 +08:00
|
|
|
|
|
|
|
|
2017-10-29 02:53:19 +08:00
|
|
|
CaptureResult = collections.namedtuple("CaptureResult", ["out", "err"])
|
|
|
|
|
|
|
|
|
2014-04-01 20:19:52 +08:00
|
|
|
class MultiCapture(object):
|
2014-03-28 14:03:37 +08:00
|
|
|
out = err = in_ = None
|
|
|
|
|
|
|
|
def __init__(self, out=True, err=True, in_=True, Capture=None):
|
|
|
|
if in_:
|
|
|
|
self.in_ = Capture(0)
|
|
|
|
if out:
|
|
|
|
self.out = Capture(1)
|
|
|
|
if err:
|
|
|
|
self.err = Capture(2)
|
|
|
|
|
2014-03-14 19:49:36 +08:00
|
|
|
def start_capturing(self):
|
2014-03-28 14:03:37 +08:00
|
|
|
if self.in_:
|
2014-01-25 04:22:19 +08:00
|
|
|
self.in_.start()
|
2014-03-28 14:03:37 +08:00
|
|
|
if self.out:
|
2014-01-25 04:22:19 +08:00
|
|
|
self.out.start()
|
2014-03-28 14:03:37 +08:00
|
|
|
if self.err:
|
2014-01-25 04:22:19 +08:00
|
|
|
self.err.start()
|
|
|
|
|
2014-03-28 14:03:37 +08:00
|
|
|
def pop_outerr_to_orig(self):
|
|
|
|
""" pop current snapshot out/err capture and flush to orig streams. """
|
|
|
|
out, err = self.readouterr()
|
|
|
|
if out:
|
|
|
|
self.out.writeorg(out)
|
|
|
|
if err:
|
|
|
|
self.err.writeorg(err)
|
2014-04-01 20:32:12 +08:00
|
|
|
return out, err
|
2014-03-28 14:03:37 +08:00
|
|
|
|
2014-04-01 20:32:12 +08:00
|
|
|
def suspend_capturing(self, in_=False):
|
2014-04-01 20:19:58 +08:00
|
|
|
if self.out:
|
|
|
|
self.out.suspend()
|
|
|
|
if self.err:
|
|
|
|
self.err.suspend()
|
2014-04-01 20:32:12 +08:00
|
|
|
if in_ and self.in_:
|
|
|
|
self.in_.suspend()
|
|
|
|
self._in_suspended = True
|
2014-04-01 20:19:58 +08:00
|
|
|
|
|
|
|
def resume_capturing(self):
|
|
|
|
if self.out:
|
|
|
|
self.out.resume()
|
|
|
|
if self.err:
|
|
|
|
self.err.resume()
|
2014-04-01 20:32:12 +08:00
|
|
|
if hasattr(self, "_in_suspended"):
|
|
|
|
self.in_.resume()
|
|
|
|
del self._in_suspended
|
2014-04-01 20:19:58 +08:00
|
|
|
|
2014-03-28 14:11:25 +08:00
|
|
|
def stop_capturing(self):
|
|
|
|
""" stop capturing and reset capturing streams """
|
|
|
|
if hasattr(self, '_reset'):
|
|
|
|
raise ValueError("was already stopped")
|
|
|
|
self._reset = True
|
|
|
|
if self.out:
|
|
|
|
self.out.done()
|
|
|
|
if self.err:
|
|
|
|
self.err.done()
|
|
|
|
if self.in_:
|
|
|
|
self.in_.done()
|
|
|
|
|
2014-01-25 04:22:19 +08:00
|
|
|
def readouterr(self):
|
2014-03-28 14:03:37 +08:00
|
|
|
""" return snapshot unicode value of stdout/stderr capturings. """
|
2017-10-29 02:53:19 +08:00
|
|
|
return CaptureResult(self.out.snap() if self.out is not None else "",
|
|
|
|
self.err.snap() if self.err is not None else "")
|
2014-01-25 04:22:19 +08:00
|
|
|
|
2017-07-17 07:25:09 +08:00
|
|
|
|
2017-05-18 05:16:11 +08:00
|
|
|
class NoCapture:
|
2014-04-01 20:19:58 +08:00
|
|
|
__init__ = start = done = suspend = resume = lambda *args: None
|
2014-03-28 14:03:37 +08:00
|
|
|
|
2017-07-17 07:25:09 +08:00
|
|
|
|
2017-11-15 06:08:23 +08:00
|
|
|
class FDCaptureBinary:
|
|
|
|
"""Capture IO to/from a given os-level filedescriptor.
|
|
|
|
|
|
|
|
snap() produces `bytes`
|
|
|
|
"""
|
2014-03-28 14:03:37 +08:00
|
|
|
|
2015-12-26 03:51:55 +08:00
|
|
|
def __init__(self, targetfd, tmpfile=None):
|
2014-03-28 14:03:37 +08:00
|
|
|
self.targetfd = targetfd
|
|
|
|
try:
|
2014-04-01 20:19:55 +08:00
|
|
|
self.targetfd_save = os.dup(self.targetfd)
|
2014-03-28 14:03:37 +08:00
|
|
|
except OSError:
|
|
|
|
self.start = lambda: None
|
|
|
|
self.done = lambda: None
|
|
|
|
else:
|
2014-04-01 20:19:55 +08:00
|
|
|
if targetfd == 0:
|
|
|
|
assert not tmpfile, "cannot set tmpfile with stdin"
|
|
|
|
tmpfile = open(os.devnull, "r")
|
|
|
|
self.syscapture = SysCapture(targetfd)
|
|
|
|
else:
|
|
|
|
if tmpfile is None:
|
2014-03-28 14:11:25 +08:00
|
|
|
f = TemporaryFile()
|
|
|
|
with f:
|
2014-03-28 18:27:02 +08:00
|
|
|
tmpfile = safe_text_dupfile(f, mode="wb+")
|
2014-04-01 20:19:55 +08:00
|
|
|
if targetfd in patchsysdict:
|
|
|
|
self.syscapture = SysCapture(targetfd, tmpfile)
|
|
|
|
else:
|
|
|
|
self.syscapture = NoCapture()
|
2014-03-28 14:03:37 +08:00
|
|
|
self.tmpfile = tmpfile
|
2014-04-01 20:19:55 +08:00
|
|
|
self.tmpfile_fd = tmpfile.fileno()
|
2014-03-28 14:03:37 +08:00
|
|
|
|
2014-03-28 14:11:25 +08:00
|
|
|
def __repr__(self):
|
2014-04-01 20:19:55 +08:00
|
|
|
return "<FDCapture %s oldfd=%s>" % (self.targetfd, self.targetfd_save)
|
2014-03-28 14:11:25 +08:00
|
|
|
|
2014-03-28 14:03:37 +08:00
|
|
|
def start(self):
|
|
|
|
""" Start capturing on targetfd using memorized tmpfile. """
|
|
|
|
try:
|
2014-04-01 20:19:55 +08:00
|
|
|
os.fstat(self.targetfd_save)
|
|
|
|
except (AttributeError, OSError):
|
2014-03-28 14:03:37 +08:00
|
|
|
raise ValueError("saved filedescriptor not valid anymore")
|
2014-04-01 20:19:55 +08:00
|
|
|
os.dup2(self.tmpfile_fd, self.targetfd)
|
|
|
|
self.syscapture.start()
|
2014-03-28 14:03:37 +08:00
|
|
|
|
2014-03-28 14:11:25 +08:00
|
|
|
def snap(self):
|
2017-11-15 06:08:23 +08:00
|
|
|
self.tmpfile.seek(0)
|
|
|
|
res = self.tmpfile.read()
|
|
|
|
self.tmpfile.seek(0)
|
|
|
|
self.tmpfile.truncate()
|
|
|
|
return res
|
2014-03-28 14:11:25 +08:00
|
|
|
|
2014-03-28 14:03:37 +08:00
|
|
|
def done(self):
|
|
|
|
""" stop capturing, restore streams, return original capture file,
|
|
|
|
seeked to position zero. """
|
2014-04-01 20:19:55 +08:00
|
|
|
targetfd_save = self.__dict__.pop("targetfd_save")
|
|
|
|
os.dup2(targetfd_save, self.targetfd)
|
|
|
|
os.close(targetfd_save)
|
|
|
|
self.syscapture.done()
|
2014-03-28 14:11:25 +08:00
|
|
|
self.tmpfile.close()
|
2014-03-14 19:49:36 +08:00
|
|
|
|
2014-04-01 20:19:55 +08:00
|
|
|
def suspend(self):
|
|
|
|
self.syscapture.suspend()
|
|
|
|
os.dup2(self.targetfd_save, self.targetfd)
|
|
|
|
|
|
|
|
def resume(self):
|
|
|
|
self.syscapture.resume()
|
|
|
|
os.dup2(self.tmpfile_fd, self.targetfd)
|
|
|
|
|
2014-03-14 19:49:36 +08:00
|
|
|
def writeorg(self, data):
|
2014-03-28 14:13:08 +08:00
|
|
|
""" write to original file descriptor. """
|
2017-08-03 01:33:52 +08:00
|
|
|
if isinstance(data, six.text_type):
|
2017-07-17 07:25:09 +08:00
|
|
|
data = data.encode("utf8") # XXX use encoding of original stream
|
2014-04-01 20:19:55 +08:00
|
|
|
os.write(self.targetfd_save, data)
|
2014-03-14 19:49:36 +08:00
|
|
|
|
2014-01-25 04:22:19 +08:00
|
|
|
|
2017-11-15 06:08:23 +08:00
|
|
|
class FDCapture(FDCaptureBinary):
|
|
|
|
"""Capture IO to/from a given os-level filedescriptor.
|
|
|
|
|
|
|
|
snap() produces text
|
|
|
|
"""
|
|
|
|
def snap(self):
|
|
|
|
res = FDCaptureBinary.snap(self)
|
|
|
|
enc = getattr(self.tmpfile, "encoding", None)
|
|
|
|
if enc and isinstance(res, bytes):
|
|
|
|
res = six.text_type(res, enc, "replace")
|
|
|
|
return res
|
|
|
|
|
|
|
|
|
2017-05-18 05:16:11 +08:00
|
|
|
class SysCapture:
|
2014-04-01 20:19:55 +08:00
|
|
|
def __init__(self, fd, tmpfile=None):
|
2014-03-28 14:03:37 +08:00
|
|
|
name = patchsysdict[fd]
|
|
|
|
self._old = getattr(sys, name)
|
|
|
|
self.name = name
|
2014-04-01 20:19:55 +08:00
|
|
|
if tmpfile is None:
|
|
|
|
if name == "stdin":
|
|
|
|
tmpfile = DontReadFromInput()
|
|
|
|
else:
|
2017-02-20 01:16:32 +08:00
|
|
|
tmpfile = CaptureIO()
|
2014-04-01 20:19:55 +08:00
|
|
|
self.tmpfile = tmpfile
|
2014-01-25 04:22:19 +08:00
|
|
|
|
2014-03-28 14:03:37 +08:00
|
|
|
def start(self):
|
|
|
|
setattr(sys, self.name, self.tmpfile)
|
2014-01-25 04:22:19 +08:00
|
|
|
|
2014-03-28 14:11:25 +08:00
|
|
|
def snap(self):
|
2017-11-18 01:02:46 +08:00
|
|
|
res = self.tmpfile.getvalue()
|
|
|
|
self.tmpfile.seek(0)
|
|
|
|
self.tmpfile.truncate()
|
2014-03-28 14:11:25 +08:00
|
|
|
return res
|
|
|
|
|
2014-03-28 14:03:37 +08:00
|
|
|
def done(self):
|
|
|
|
setattr(sys, self.name, self._old)
|
2014-04-01 20:19:55 +08:00
|
|
|
del self._old
|
2014-03-28 14:11:25 +08:00
|
|
|
self.tmpfile.close()
|
2014-01-25 04:22:19 +08:00
|
|
|
|
2014-04-01 20:19:55 +08:00
|
|
|
def suspend(self):
|
|
|
|
setattr(sys, self.name, self._old)
|
|
|
|
|
|
|
|
def resume(self):
|
|
|
|
setattr(sys, self.name, self.tmpfile)
|
|
|
|
|
2014-03-28 14:03:37 +08:00
|
|
|
def writeorg(self, data):
|
|
|
|
self._old.write(data)
|
|
|
|
self._old.flush()
|
2014-01-25 04:22:19 +08:00
|
|
|
|
|
|
|
|
2017-11-18 01:02:46 +08:00
|
|
|
class SysCaptureBinary(SysCapture):
|
|
|
|
def snap(self):
|
|
|
|
res = self.tmpfile.buffer.getvalue()
|
|
|
|
self.tmpfile.seek(0)
|
|
|
|
self.tmpfile.truncate()
|
|
|
|
return res
|
|
|
|
|
|
|
|
|
2017-05-18 05:16:11 +08:00
|
|
|
class DontReadFromInput:
|
2014-01-25 04:22:19 +08:00
|
|
|
"""Temporary stub class. Ideally when stdin is accessed, the
|
|
|
|
capturing should be turned off, with possibly all data captured
|
|
|
|
so far sent to the screen. This should be configurable, though,
|
|
|
|
because in automated test runs it is better to crash than
|
|
|
|
hang indefinitely.
|
|
|
|
"""
|
2014-09-22 19:19:27 +08:00
|
|
|
|
|
|
|
encoding = None
|
|
|
|
|
2014-01-25 04:22:19 +08:00
|
|
|
def read(self, *args):
|
|
|
|
raise IOError("reading from stdin while output is captured")
|
|
|
|
readline = read
|
|
|
|
readlines = read
|
|
|
|
__iter__ = read
|
|
|
|
|
|
|
|
def fileno(self):
|
2016-09-26 18:59:28 +08:00
|
|
|
raise UnsupportedOperation("redirected stdin is pseudofile, "
|
|
|
|
"has no fileno()")
|
2014-01-25 04:22:19 +08:00
|
|
|
|
|
|
|
def isatty(self):
|
|
|
|
return False
|
|
|
|
|
|
|
|
def close(self):
|
|
|
|
pass
|
2015-12-25 05:43:34 +08:00
|
|
|
|
2016-08-25 06:44:43 +08:00
|
|
|
@property
|
|
|
|
def buffer(self):
|
2017-07-17 07:25:08 +08:00
|
|
|
if sys.version_info >= (3, 0):
|
2016-08-25 06:44:43 +08:00
|
|
|
return self
|
|
|
|
else:
|
|
|
|
raise AttributeError('redirected stdin has no attribute buffer')
|
|
|
|
|
2015-12-25 05:43:34 +08:00
|
|
|
|
2017-07-24 20:17:39 +08:00
|
|
|
def _colorama_workaround():
|
|
|
|
"""
|
|
|
|
Ensure colorama is imported so that it attaches to the correct stdio
|
|
|
|
handles on Windows.
|
2017-07-24 21:55:50 +08:00
|
|
|
|
2017-07-24 20:17:39 +08:00
|
|
|
colorama uses the terminal on import time. So if something does the
|
|
|
|
first import of colorama while I/O capture is active, colorama will
|
|
|
|
fail in various ways.
|
|
|
|
"""
|
|
|
|
|
|
|
|
if not sys.platform.startswith('win32'):
|
|
|
|
return
|
|
|
|
try:
|
|
|
|
import colorama # noqa
|
|
|
|
except ImportError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
2015-12-26 03:46:19 +08:00
|
|
|
def _readline_workaround():
|
2015-12-25 05:43:34 +08:00
|
|
|
"""
|
|
|
|
Ensure readline is imported so that it attaches to the correct stdio
|
|
|
|
handles on Windows.
|
|
|
|
|
|
|
|
Pdb uses readline support where available--when not running from the Python
|
|
|
|
prompt, the readline module is not imported until running the pdb REPL. If
|
2016-06-21 22:16:57 +08:00
|
|
|
running pytest with the --pdb option this means the readline module is not
|
2015-12-25 05:43:34 +08:00
|
|
|
imported until after I/O capture has been started.
|
|
|
|
|
|
|
|
This is a problem for pyreadline, which is often used to implement readline
|
|
|
|
support on Windows, as it does not attach to the correct handles for stdout
|
|
|
|
and/or stdin if they have been redirected by the FDCapture mechanism. This
|
|
|
|
workaround ensures that readline is imported before I/O capture is setup so
|
|
|
|
that it can attach to the actual stdin/out for the console.
|
|
|
|
|
|
|
|
See https://github.com/pytest-dev/pytest/pull/1281
|
|
|
|
"""
|
|
|
|
|
2015-12-26 03:46:19 +08:00
|
|
|
if not sys.platform.startswith('win32'):
|
|
|
|
return
|
2015-12-25 05:43:34 +08:00
|
|
|
try:
|
|
|
|
import readline # noqa
|
|
|
|
except ImportError:
|
|
|
|
pass
|
2017-06-02 16:19:03 +08:00
|
|
|
|
|
|
|
|
2017-08-08 07:55:28 +08:00
|
|
|
def _py36_windowsconsoleio_workaround(stream):
|
2017-06-02 16:19:03 +08:00
|
|
|
"""
|
|
|
|
Python 3.6 implemented unicode console handling for Windows. This works
|
|
|
|
by reading/writing to the raw console handle using
|
|
|
|
``{Read,Write}ConsoleW``.
|
|
|
|
|
|
|
|
The problem is that we are going to ``dup2`` over the stdio file
|
|
|
|
descriptors when doing ``FDCapture`` and this will ``CloseHandle`` the
|
|
|
|
handles used by Python to write to the console. Though there is still some
|
|
|
|
weirdness and the console handle seems to only be closed randomly and not
|
|
|
|
on the first call to ``CloseHandle``, or maybe it gets reopened with the
|
|
|
|
same handle value when we suspend capturing.
|
|
|
|
|
|
|
|
The workaround in this case will reopen stdio with a different fd which
|
|
|
|
also means a different handle by replicating the logic in
|
|
|
|
"Py_lifecycle.c:initstdio/create_stdio".
|
|
|
|
|
2017-08-08 07:55:28 +08:00
|
|
|
:param stream: in practice ``sys.stdout`` or ``sys.stderr``, but given
|
|
|
|
here as parameter for unittesting purposes.
|
|
|
|
|
2017-06-02 16:19:03 +08:00
|
|
|
See https://github.com/pytest-dev/py/issues/103
|
|
|
|
"""
|
2017-06-02 17:34:26 +08:00
|
|
|
if not sys.platform.startswith('win32') or sys.version_info[:2] < (3, 6):
|
2017-06-02 16:19:03 +08:00
|
|
|
return
|
|
|
|
|
2017-08-08 07:55:28 +08:00
|
|
|
# bail out if ``stream`` doesn't seem like a proper ``io`` stream (#2666)
|
|
|
|
if not hasattr(stream, 'buffer'):
|
|
|
|
return
|
|
|
|
|
|
|
|
buffered = hasattr(stream.buffer, 'raw')
|
|
|
|
raw_stdout = stream.buffer.raw if buffered else stream.buffer
|
2017-06-02 16:19:03 +08:00
|
|
|
|
|
|
|
if not isinstance(raw_stdout, io._WindowsConsoleIO):
|
|
|
|
return
|
|
|
|
|
|
|
|
def _reopen_stdio(f, mode):
|
|
|
|
if not buffered and mode[0] == 'w':
|
|
|
|
buffering = 0
|
|
|
|
else:
|
|
|
|
buffering = -1
|
|
|
|
|
|
|
|
return io.TextIOWrapper(
|
|
|
|
open(os.dup(f.fileno()), mode, buffering),
|
|
|
|
f.encoding,
|
|
|
|
f.errors,
|
|
|
|
f.newlines,
|
|
|
|
f.line_buffering)
|
|
|
|
|
|
|
|
sys.__stdin__ = sys.stdin = _reopen_stdio(sys.stdin, 'rb')
|
|
|
|
sys.__stdout__ = sys.stdout = _reopen_stdio(sys.stdout, 'wb')
|
|
|
|
sys.__stderr__ = sys.stderr = _reopen_stdio(sys.stderr, 'wb')
|