Skip to content

Commit

Permalink
Merge pull request #2880 from samueldg/capture-result-namedtuple
Browse files Browse the repository at this point in the history
Capture result namedtuple
  • Loading branch information
RonnyPfannschmidt authored Oct 30, 2017
2 parents def471b + 8e178e9 commit cb30848
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 2 deletions.
1 change: 1 addition & 0 deletions AUTHORS
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,7 @@ Ronny Pfannschmidt
Ross Lawley
Russel Winder
Ryan Wooden
Samuel Dion-Girardeau
Samuele Pedroni
Segev Finer
Simon Gomizelj
Expand Down
8 changes: 6 additions & 2 deletions _pytest/capture.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"""
from __future__ import absolute_import, division, print_function

import collections
import contextlib
import sys
import os
Expand Down Expand Up @@ -306,6 +307,9 @@ def __getattr__(self, name):
return getattr(object.__getattribute__(self, "buffer"), name)


CaptureResult = collections.namedtuple("CaptureResult", ["out", "err"])


class MultiCapture(object):
out = err = in_ = None

Expand Down Expand Up @@ -366,8 +370,8 @@ def stop_capturing(self):

def readouterr(self):
""" return snapshot unicode value of stdout/stderr capturings. """
return (self.out.snap() if self.out is not None else "",
self.err.snap() if self.err is not None else "")
return CaptureResult(self.out.snap() if self.out is not None else "",
self.err.snap() if self.err is not None else "")


class NoCapture:
Expand Down
1 change: 1 addition & 0 deletions changelog/2879.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Return stdout/stderr capture results as a ``namedtuple``, so ``out`` and ``err`` can be accessed by attribute.
16 changes: 16 additions & 0 deletions testing/test_capture.py
Original file line number Diff line number Diff line change
Expand Up @@ -922,6 +922,14 @@ def test_capturing_readouterr(self):
out, err = cap.readouterr()
assert err == "error2"

def test_capture_results_accessible_by_attribute(self):
with self.getcapture() as cap:
sys.stdout.write("hello")
sys.stderr.write("world")
capture_result = cap.readouterr()
assert capture_result.out == "hello"
assert capture_result.err == "world"

def test_capturing_readouterr_unicode(self):
with self.getcapture() as cap:
print("hx\xc4\x85\xc4\x87")
Expand Down Expand Up @@ -1083,6 +1091,14 @@ def test_using_capsys_fixture_works_with_sys_stdout_encoding(capsys):
assert err == ''


def test_capsys_results_accessible_by_attribute(capsys):
sys.stdout.write("spam")
sys.stderr.write("eggs")
capture_result = capsys.readouterr()
assert capture_result.out == "spam"
assert capture_result.err == "eggs"


@needsosdup
@pytest.mark.parametrize('use', [True, False])
def test_fdcapture_tmpfile_remains_the_same(tmpfile, use):
Expand Down

0 comments on commit cb30848

Please sign in to comment.