pytest: assert no output from tests

Viewed 319

Is it possible to assert that tests run using pytest do not output anything from Python or C stdout? Ideally this would be global, along with a few manually-annotated exclusions.

I've read the pytest capturing docs and could use that system within each test, but am hoping to avoid passing the capture fixture everywhere, along with modifying all tests.

(running doctests implicitly checks this, because it checks output against expectation for each example line, but I want to error on any unexpected output from unit tests)

1 Answers

An auto-use fixture can check the contents of capsys at teardown time:

# in conftest.py
import pytest

@pytest.fixture(autouse=True)
def no_output(capsys):
    yield
    out, err = capsys.readouterr()
    if out or err:
        pytest.fail(f"output captured: {out + err}")

This will still allow your test suite to have some tests which explicitly do expect output, since by the time the no_output fixture is in teardown the capsys will have already been consumed.

# test_example.py

def test_no_output():
    pass

def test_output_allowed(capsys):
    print("ok")
    out, err = capsys.readouterr()
    assert not err
    assert out == "ok\n"
Related