/usr/lib/python3/dist-packages/testfixtures/outputcapture.py is in python3-testfixtures 4.14.3-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | # Copyright (c) 2008-2013 Simplistix Ltd
# Copyright (c) 2015 Chris Withers
# See license.txt for license details.
import sys
from testfixtures.comparison import compare
from testfixtures.compat import StringIO
class OutputCapture(object):
"""
A context manager for capturing output to the
:attr:`sys.stdout` and :attr:`sys.stderr` streams.
:param separate: If ``True``, ``stdout`` and ``stderr`` will be captured
separately and their expected values must be passed to
:meth:`~OutputCapture.compare`.
.. note:: If ``separate`` is passed as ``True``,
:attr:`OutputCapture.captured` will be an empty string.
"""
original_stdout = None
original_stderr = None
def __init__(self, separate=False):
self.separate = separate
def __enter__(self):
self.output = StringIO()
self.stdout = StringIO()
self.stderr = StringIO()
self.enable()
return self
def __exit__(self, *args):
self.disable()
def disable(self):
"Disable the output capture if it is enabled."
sys.stdout = self.original_stdout
sys.stderr = self.original_stderr
def enable(self):
"Enable the output capture if it is disabled."
if self.original_stdout is None:
self.original_stdout = sys.stdout
self.original_stderr = sys.stderr
if self.separate:
sys.stdout = self.stdout
sys.stderr = self.stderr
else:
sys.stdout = sys.stderr = self.output
@property
def captured(self):
"A property containing any output that has been captured so far."
return self.output.getvalue()
def compare(self, expected='', stdout='', stderr=''):
"""
Compare the captured output to that expected. If the output is
not the same, an :class:`AssertionError` will be raised.
:param expected: A string containing the expected combined output
of ``stdout`` and ``stderr``.
:param stdout: A string containing the expected output to ``stdout``.
:param stderr: A string containing the expected output to ``stderr``.
"""
for prefix, _expected, captured in (
(None, expected, self.captured),
('stdout', stdout, self.stdout.getvalue()),
('stderr', stderr, self.stderr.getvalue()),
):
compare(_expected.strip(), actual=captured.strip(), prefix=prefix)
|