2

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.

3
  • pytest will finish test execution after first failed assertion so you will see only one error log. Commented May 17, 2019 at 15:15
  • @Sanyash yeah, there will be one error log but it will contain output from all previous logic calls because they are in the same scope as failed assert Commented May 17, 2019 at 16:40
  • Oh, you meant output of logic calls... It wasn't clear. Glad that you got an answer :) Commented May 17, 2019 at 16:41

2 Answers 2

2

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 
Sign up to request clarification or add additional context in comments.

1 Comment

this is even better than what I wanted
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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.