I am having trouble capturing the stderr and stdout for pytest when I am using a fixture. It works okay if the test is just directly called. The reason I want it in a fixture is because I need to call it multiple times based on a file that I will be reading.
Here's a working example, lets say this content is in 'test_something.py':
import sys
import pytest
def printing():
print("testing only")
print("erroring", file=sys.stderr)
sys.exit(1)
def test_print(capsys):
with pytest.raises(SystemExit) as excinfo:
printing()
stdout, errout = capsys.readouterr()
assert stdout == "testing only\n"
assert errout == "erroring\n"
assert excinfo.type == SystemExit
class TestPrint():
@pytest.fixture(name="getResponse", scope="class", params=[0])
def getResponse(self, request):
with pytest.raises(SystemExit) as excinfo:
printing()
return excinfo
def test_print_class(self, getResponse, capsys):
excinfo = getResponse
stdout, errout = capsys.readouterr()
assert stdout == "testing only\n"
assert errout == "erroring\n"
assert excinfo.type == SystemExit
if you run 'pytest -v' for the above, you get:
tests/test_something.py::test_print PASSED [ 50%]
tests/test_something.py::TestPrint::test_print_class[0] FAILED [100%]
The 'test_print_class' reads empty stdout and stderr, why is that? How can I make it work? Thanks for the help!