_pytest.capture module

per-test stdout/stderr capturing mechanism.

class CloseStdinType(value)[source]

Bases: enum.Enum

An enumeration.

CLOSE_STDIN = 1
CLOSE_STDIN = <CloseStdinType.CLOSE_STDIN: 1>

Sentinel to close stdin.

pytest_addoption(parser)[source]
for ... in pytest_load_initial_conftests(early_config: _pytest.config.Config)[source]
_get_multicapture(method: _CaptureMethod) → MultiCapture[source]
class CaptureManager(method: _CaptureMethod)[source]

Bases: object

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.

is_capturing()[source]
is_globally_capturing()[source]
start_global_capturing()[source]
stop_global_capturing()[source]
resume_global_capture()[source]
suspend_global_capture(in_=False)[source]
suspend(in_=False)[source]
resume()[source]
read_global_capture()[source]
with _capturing_for_request(request: _pytest.fixtures.FixtureRequest) → Generator[CaptureFixture, None, None][source]

Context manager that creates a CaptureFixture instance for the given request, ensuring there is only a single one being requested at the same time.

This is used as a helper with capsys, capfd etc.

activate_fixture()[source]

If the current item is using capsys or capfd, activate them so they take precedence over the global capture.

deactivate_fixture()[source]

Deactivates the capsys or capfd fixture of this item, if any.

suspend_fixture()[source]
resume_fixture()[source]
with global_and_fixture_disabled()[source]

Context manager to temporarily disable global and current fixture capturing.

with item_capture(when, item)[source]
for ... in pytest_make_collect_report(collector)[source]
for ... in pytest_runtest_setup(item)[source]
for ... in pytest_runtest_call(item)[source]
for ... in pytest_runtest_teardown(item)[source]
pytest_keyboard_interrupt(excinfo)[source]
pytest_internalerror(excinfo)[source]
for ... in capsys(request)[source]

Enable text capturing of writes to sys.stdout and sys.stderr.

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

for ... in capsysbinary(request)[source]

Enable bytes capturing of writes to sys.stdout and sys.stderr.

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

for ... in capfd(request)[source]

Enable text capturing of writes to file descriptors 1 and 2.

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

for ... in capfdbinary(request)[source]

Enable bytes capturing of writes to file descriptors 1 and 2.

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

class CaptureFixture(captureclass, request)[source]

Bases: object

Object returned by capsys(), capsysbinary(), capfd() and capfdbinary() fixtures.

_start()[source]
close()[source]
readouterr()[source]

Read and return the captured output so far, resetting the internal buffer.

Returns

captured content as a namedtuple with out and err string attributes

_suspend()[source]

Suspends this fixture’s own capturing temporarily.

_resume()[source]

Resumes this fixture’s own capturing temporarily.

with disabled()[source]

Temporarily disables capture while inside the ‘with’ block.

safe_text_dupfile(f, mode, default_encoding='UTF8')[source]

return an open text file object that’s a duplicate of f on the FD-level if possible.

class EncodedFile(buffer: BinaryIO, encoding: str)[source]

Bases: object

errors = 'strict'
write(s: str)int[source]
writelines(lines: Iterable[str])None[source]
name

Ensure that file.name is a string.

mode
class CaptureResult(out, err)

Bases: tuple

_asdict()

Return a new dict which maps field names to their values.

_field_defaults = {}
_fields = ('out', 'err')
_fields_defaults = {}
classmethod _make(iterable)

Make a new CaptureResult object from a sequence or iterable

_replace(**kwds)

Return a new CaptureResult object replacing specified fields with new values

err

Alias for field number 1

out

Alias for field number 0

class MultiCapture(out=True, err=True, in_=True, Capture=None)[source]

Bases: object

_state = None
_in_suspended = False
in_ = None
out = None
err = None
start_capturing()[source]
pop_outerr_to_orig()[source]

pop current snapshot out/err capture and flush to orig streams.

suspend_capturing(in_=False)[source]
resume_capturing()[source]
stop_capturing()[source]

stop capturing and reset capturing streams

readouterr()[source]

return snapshot unicode value of stdout/stderr capturings.

class NoCapture[source]

Bases: object

EMPTY_BUFFER = None
start()
done()
suspend()
resume()
class FDCaptureBinary(targetfd, tmpfile=None)[source]

Bases: object

Capture IO to/from a given os-level filedescriptor.

snap() produces bytes

EMPTY_BUFFER = b''
_state = None
_start()[source]

Start capturing on targetfd using memorized tmpfile.

snap()[source]
_done()[source]

stop capturing, restore streams, return original capture file, seeked to position zero.

suspend()[source]
resume()[source]
writeorg(data)[source]

write to original file descriptor.

class FDCapture(targetfd, tmpfile=None)[source]

Bases: _pytest.capture.FDCaptureBinary

Capture IO to/from a given os-level filedescriptor.

snap() produces text

EMPTY_BUFFER = ''
snap()[source]
class SysCaptureBinary(fd, tmpfile=None, stdin=<CloseStdinType.CLOSE_STDIN: 1>)[source]

Bases: object

CLOSE_STDIN = 1
EMPTY_BUFFER = b''
_state = None
start()[source]
snap()[source]
done()[source]
suspend()[source]
resume()[source]
writeorg(data: bytes)None[source]
class SysCapture(fd, tmpfile=None, stdin=<CloseStdinType.CLOSE_STDIN: 1>)[source]

Bases: _pytest.capture.SysCaptureBinary

EMPTY_BUFFER = ''
snap()[source]
writeorg(data: str)None[source]
class TeeSysCapture(fd, tmpfile=None)[source]

Bases: _pytest.capture.SysCapture

class DontReadFromInput[source]

Bases: object

encoding = None
read(*args)[source]
readline(*args)
readlines(*args)
fileno()[source]
isatty()[source]
close()[source]
buffer
_colorama_workaround()[source]

Ensure colorama is imported so that it attaches to the correct stdio handles on Windows.

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.

_readline_workaround()[source]

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 running pytest with the –pdb option this means the readline module is not 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

_py36_windowsconsoleio_workaround(stream)[source]

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”.

Parameters

stream – in practice sys.stdout or sys.stderr, but given here as parameter for unittesting purposes.

See https://github.com/pytest-dev/py/issues/103