How to clear captured stdout/stderr in between of multiple assert statements

旧巷老猫 提交于 2020-03-04 06:07:56

问题


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 assertion.

def test_foos(captured):
    foos = []  # some data
    for foo, bar in foos:
        captured.clear()
        assert logic(foo) == bar

I have found caplog.clear but it doesn't seem to work.


回答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)
def test_foos(x, expected):
    assert logic(foo) == bar # in the example, say logic squares the input



回答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:

def logic(letter):
    print("Handling letter", letter)
    return letter.isupper()

def test_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:

def test_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


来源:https://stackoverflow.com/questions/56187165/how-to-clear-captured-stdout-stderr-in-between-of-multiple-assert-statements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!