Search code examples
pythonpython-3.xpyteststdio

pytest: getting AttributeError: 'CaptureFixture' object has no attribute 'readouterror' capturing stdout


This should be a simple thing but I can't figure out what is causing the error.

I'm following the pytest docs on how to capture stdout into an object but am getting the following error:

capsys = <_pytest.capture.CaptureFixture object at 0x7f02a1e2f7f0>

    def test_can_output_to_stdout(capsys):
        print("hello")
>       capture = capsys.readouterror()
E       AttributeError: 'CaptureFixture' object has no attribute 'readouterror'

test_aaa.py:5: AttributeError

The code I'm using is similar to:

import pytest

def test_can_output_to_stdout(capsys):
    print("hello")
    capture = capsys.readouterror()
    assert "hello" in capture.out

I'm calling the test like so:

py.test --capture=sys --capture=fd test_aaa.py

The versions are:

pytest:

py.test --version
This is pytest version 4.6.5, imported from /usr/local/lib/python3.4/site-packages/pytest.p

Python:

python --version
Python 3.4.8

Any help would be greatly appreciated.


Solution

  • It turns out copy pasting is probably better than writing out the examples. The error was with the attribute name.

    It should be capsys.readouterr(), not capsys.readouterror(), and in full:

    import pytest
    
    def test_can_output_to_stdout(capsys):
        print("hello")
        capture = capsys.readouterr()
        assert "hello" in capture.out