Coverage for .tox/testcoverage/lib/python2.7/site-packages/_pytest/capture : 66%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
""" per-test stdout/stderr capturing mechanism.
"""
'--capture', action="store", default="fd" if hasattr(os, "dup") else "sys", metavar="method", choices=['fd', 'sys', 'no'], help="per-test capturing method: one of fd|sys|no.") '-s', action="store_const", const="no", dest="capture", help="shortcut for --capture=no.")
def pytest_load_initial_conftests(early_config, parser, args):
# make sure that capturemanager is properly reset at final shutdown
# make sure logging does not raise exceptions at the end sys.modules["logging"].raiseExceptions = False
# finally trigger conftest loading but while capturing (issue93) sys.stdout.write(out) sys.stderr.write(err)
elif method == "sys": return MultiCapture(out=True, err=True, Capture=SysCapture) elif method == "no": return MultiCapture(out=False, err=False, in_=False) else: raise ValueError("unknown capturing method: %r" % method)
finally:
capfuncarg._start() self._capfuncarg = capfuncarg
capfuncarg.close()
def pytest_make_collect_report(self, collector): rep.sections.append(("Captured stdout", out)) rep.sections.append(("Captured stderr", err)) else:
def pytest_runtest_setup(self, item):
def pytest_runtest_call(self, item): #self.deactivate_funcargs() called from suspendcapture()
def pytest_runtest_teardown(self, item):
def pytest_keyboard_interrupt(self, excinfo): self.reset_capturings()
def pytest_internalerror(self, excinfo): self.reset_capturings()
def capsys(request): """enables capturing of writes to sys.stdout/sys.stderr and makes captured output available via ``capsys.readouterr()`` method calls which return a ``(out, err)`` tuple. """ if "capfd" in request._funcargs: raise request.raiseerror(error_capsysfderror) request.node._capfuncarg = c = CaptureFixture(SysCapture) return c
def capfd(request): """enables capturing of writes to file descriptors 1 and 2 and makes captured output available via ``capfd.readouterr()`` method calls which return a ``(out, err)`` tuple. """ if "capsys" in request._funcargs: request.raiseerror(error_capsysfderror) if not hasattr(os, 'dup'): pytest.skip("capfd funcarg needs os.dup") request.node._capfuncarg = c = CaptureFixture(FDCapture) return c
self.captureclass = captureclass
self._capture = MultiCapture(out=True, err=True, in_=False, Capture=self.captureclass) self._capture.start_capturing()
cap = self.__dict__.pop("_capture", None) if cap is not None: self._outerr = cap.pop_outerr_to_orig() cap.stop_capturing()
try: return self._capture.readouterr() except AttributeError: return self._outerr
""" return a open text file object that's a duplicate of f on the FD-level if possible. """ 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 else: mode += "b"
if isinstance(obj, unicode): obj = obj.encode(self.encoding, "replace") self.buffer.write(obj)
data = ''.join(linelist) self.write(data)
""" pop current snapshot out/err capture and flush to orig streams. """ self.out.writeorg(out) self.err.writeorg(err)
self.in_.suspend() self._in_suspended = True
self.in_.resume() del self._in_suspended
""" stop capturing and reset capturing streams """ raise ValueError("was already stopped")
""" return snapshot unicode value of stdout/stderr capturings. """ self.err.snap() if self.err is not None else "")
""" Capture IO to/from a given os-level filedescriptor. """
except OSError: self.start = lambda: None self.done = lambda: None else: else: else: self.syscapture = NoCapture()
return "<FDCapture %s oldfd=%s>" % (self.targetfd, self.targetfd_save)
""" Start capturing on targetfd using memorized tmpfile. """ except (AttributeError, OSError): raise ValueError("saved filedescriptor not valid anymore")
enc = getattr(f, "encoding", None) if enc and isinstance(res, bytes): res = py.builtin._totext(res, enc, "replace") f.truncate(0) f.seek(0) return res
""" stop capturing, restore streams, return original capture file, seeked to position zero. """
""" write to original file descriptor. """ if py.builtin._istext(data): data = data.encode("utf8") # XXX use encoding of original stream os.write(self.targetfd_save, data)
else: tmpfile = TextIO()
f = self.tmpfile res = f.getvalue() f.truncate(0) f.seek(0) return res
self._old.write(data) self._old.flush()
"""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. """
raise IOError("reading from stdin while output is captured")
raise ValueError("redirected Stdin is pseudofile, has no fileno()")
return False
""" 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 py.test 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 """
try: import readline # noqa except ImportError: pass |