Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add capteesys capture fixture to bubble up output to --capture handler #12854

Open
wants to merge 11 commits into
base: main
Choose a base branch
from
9 changes: 7 additions & 2 deletions doc/en/how-to/capture-stdout-stderr.rst
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@
How to capture stdout/stderr output
=========================================================

Pytest can intercept stdout and stderr by using the ``--capture=`` command-line
or argument or by using fixtures. The flag ``--capture=`` configures reporting,
whereas the fixtures offer somewhat more granular control and allow inspection
during testing. The reports can customized with the `-r flag <../reference/reference.html#command-line-flags>`_.
ayjayt marked this conversation as resolved.
Show resolved Hide resolved

ayjayt marked this conversation as resolved.
Show resolved Hide resolved
Default stdout/stderr/stdin capturing behaviour
---------------------------------------------------------

Expand Down Expand Up @@ -106,8 +111,8 @@ of the failing function and hide the other one:
Accessing captured output from a test function
---------------------------------------------------

The :fixture:`capsys`, :fixture:`capsysbinary`, :fixture:`capfd`, and :fixture:`capfdbinary` fixtures
allow access to ``stdout``/``stderr`` output created during test execution.
The :fixture:`capsys`, :fixture:`capteesys`, :fixture:`capsysbinary`, :fixture:`capfd`, and :fixture:`capfdbinary`
fixtures allow access to ``stdout``/``stderr`` output created during test execution.

Here is an example test function that performs some output related checks:

Expand Down
4 changes: 4 additions & 0 deletions doc/en/reference/fixtures.rst
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ Built-in fixtures
:fixture:`capsys`
Capture, as text, output to ``sys.stdout`` and ``sys.stderr``.

:fixture:`capteesys`
Capture in the same manner as :fixture:`capsys`, but also pass text
through according to ``--capture=``.

:fixture:`capsysbinary`
Capture, as bytes, output to ``sys.stdout`` and ``sys.stderr``.

Expand Down
10 changes: 10 additions & 0 deletions doc/en/reference/reference.rst
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,16 @@ capsys
.. autoclass:: pytest.CaptureFixture()
:members:

.. fixture:: capteesys

capteesys
~~~~~~~~~

**Tutorial**: :ref:`captures`

.. autofunction:: _pytest.capture.capteesys()
:no-auto-options:

.. fixture:: capsysbinary

capsysbinary
Expand Down
41 changes: 39 additions & 2 deletions src/_pytest/capture.py
Original file line number Diff line number Diff line change
Expand Up @@ -902,11 +902,13 @@ def __init__(
captureclass: type[CaptureBase[AnyStr]],
request: SubRequest,
*,
config: dict[str, Any] | None = None,
_ispytest: bool = False,
) -> None:
check_ispytest(_ispytest)
self.captureclass: type[CaptureBase[AnyStr]] = captureclass
self.request = request
self._config = config if config else {}
self._capture: MultiCapture[AnyStr] | None = None
self._captured_out: AnyStr = self.captureclass.EMPTY_BUFFER
self._captured_err: AnyStr = self.captureclass.EMPTY_BUFFER
Expand All @@ -915,8 +917,8 @@ def _start(self) -> None:
if self._capture is None:
self._capture = MultiCapture(
in_=None,
out=self.captureclass(1),
err=self.captureclass(2),
out=self.captureclass(1, **self._config),
err=self.captureclass(2, **self._config),
)
self._capture.start_capturing()

Expand Down Expand Up @@ -1002,6 +1004,41 @@ def test_output(capsys):
capman.unset_fixture()


@fixture
def capteesys(request: SubRequest) -> Generator[CaptureFixture[str]]:
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this fixture is almost 100% a copy of the capsys one above it, since a tee-sys is just a sys w/ an extra argument (tree=True)

r"""Enable simultaneous text capturing and pass-through of writes
to ``sys.stdout`` and ``sys.stderr`` as defined by ``--capture=``.


The captured output is made available via ``capteesys.readouterr()`` method
calls, which return a ``(out, err)`` namedtuple.
``out`` and ``err`` will be ``text`` objects.

The output is also passed-through, allowing it to be "live-printed",
reported, or both as defined by ``--capture=``.

Returns an instance of :class:`CaptureFixture[str] <pytest.CaptureFixture>`.

Example:

.. code-block:: python

def test_output(capsys):
print("hello")
captured = capteesys.readouterr()
assert captured.out == "hello\n"
"""
capman: CaptureManager = request.config.pluginmanager.getplugin("capturemanager")
capture_fixture = CaptureFixture(
SysCapture, request, config=dict(tee=True), _ispytest=True
)
capman.set_fixture(capture_fixture)
capture_fixture._start()
yield capture_fixture
capture_fixture.close()
capman.unset_fixture()


@fixture
def capsysbinary(request: SubRequest) -> Generator[CaptureFixture[bytes]]:
r"""Enable bytes capturing of writes to ``sys.stdout`` and ``sys.stderr``.
Expand Down
19 changes: 19 additions & 0 deletions testing/test_capture.py
Original file line number Diff line number Diff line change
Expand Up @@ -445,6 +445,25 @@ def test_hello(capsys):
)
reprec.assertoutcome(passed=1)

def test_capteesys(self, pytester: Pytester) -> None:
p = pytester.makepyfile(
"""\
import sys
def test_one(capteesys):
print("sTdoUt")
print("sTdeRr", file=sys.stderr)
out, err = capteesys.readouterr()
assert out == "sTdoUt\\n"
assert err == "sTdeRr\\n"
"""
)
# -rN and --capture=tee-sys means we'll read them on stdout/stderr,
# as opposed to both being reported on stdout
result = pytester.runpytest(p, "--quiet", "--quiet", "-rN", "--capture=tee-sys")
assert result.ret == ExitCode.OK
result.stdout.fnmatch_lines(["sTdoUt"])
result.stderr.fnmatch_lines(["sTdeRr"])

def test_capsyscapfd(self, pytester: Pytester) -> None:
p = pytester.makepyfile(
"""\
Expand Down