Skip to content Skip to sidebar Skip to footer

How To Clear Captured Stdout/stderr In Between Of Multiple Assert Statements

I have some tests with assertions in loop, each assertion is kinda like separate test and I don't want previous assertions' output to pollute error logs of current failed assertio

Solution 1:

Parametrize your test. Pass the foos as parameter and pytest will run the test assert line multiple times, recording success/failure as if each were a separate test.

import pytest

testdata = [
    (3,9),
    (4,16),
    (5,25)
]

@pytest.mark.parametrize("x,expected", testdata)deftest_foos(x, expected):
    assert logic(foo) == bar # in the example, say logic squares the input

Solution 2:

I agree with the other answer that in your case, using pytest.mark.parametrize is the best approach. However, for completeness, you are able to clear captured output with the capsys fixture.

Example:

deflogic(letter):
    print("Handling letter", letter)
    return letter.isupper()

deftest_foo():
    letters = ["A", "b", "c"]
    for letter in letters:
        assert logic(letter)

The test will fail at "b" and print:

----------------------------- Captured stdout call -----------------------------
Handling letter A
Handling letter b

To prevent the output from (successfully) handling "A", we can add capsys to the arguments and use capsys.readouterr to clear the buffer in between:

deftest_foo(capsys):
    letters = ["A", "b", "c"]
    for letter in letters:
        assert logic(letter)
        capsys.readouterr()

Now, the tests still fail at "b", but only print:

----------------------------- Captured stdout call -----------------------------
Handling letter b

Post a Comment for "How To Clear Captured Stdout/stderr In Between Of Multiple Assert Statements"