Skip to content

[Suggestion] Use a namedtuple for capsys results #2879

@samueldg

Description

@samueldg

Currently, the capsys fixture's readouterr() method returns a tuple with (stdout, stderr) results.

Usage will look something like this:

def test_print_1(capsys):
    print('something')
    out, err = capsys.readouterr()  # Named, unused variable
    assert 'something' in out

def test_print_2(capsys):
    print('something ')
    out, _ = capsys.readouterr()  # Anonymous, ignored variable
    assert 'something' in out

def test_print_3(capsys):
    print('something')
    assert 'something' in capsys.readouterr()[0]  # Index access (not super readable)

My suggestion would be to return a namedtuple instead, so the attributes can be accessed by name

def test_print_4(capsys):
    print('something')
    assert 'something' in capsys.readouterr().out  # Attribute access

Which could be achieved by wrapping the result with something like:

from collections import namedtuple
CapsysResult = namedtuple('CapsysResult', ['out', 'err'])

This would be pretty straightforward, and still fully compatible with existing code using tuples either for index access or unpacking.

Metadata

Metadata

Assignees

No one assigned

    Labels

    good first issueeasy issue that is friendly to new contributortype: enhancementnew feature or API change, should be merged into features branch

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions