1

I'm using pytest and in the test function I'm using I have several conditions I would like to check with an assert and then at the end of the test, have a list of the ones which failed.

Unfortunately, if an assert fails, the test instantly breaks and does not check the other conditions. Is there away to use an assert which dodes not break the flow of the programme?

import pytest

def test_example():
  value1 = 1
  value2 = 0
  value3 = 0

  assert value1 == 1
  assert value2 == 2
  assert value3 == 3

Output

================================== FAILURES ===================================
________________________________ test_example _________________________________

    def test_example():
      value1 = 1
      value2 = 0
      value3 = 0

      assert value1 == 1
>     assert value2 == 2
E     assert 0 == 2

test_demo.py:50: AssertionError
========================== 1 failed in 0.21 seconds ===========================

As you can see after failing the second assert it stops running, is there a way around this. I considering writing if statements to check every condition and if they fail, increment a counter and at the end checking to see if that counter is 0 but that wouldn't keep track of which test failed.

1 Answers1

0

A lot of asserts in a test is a bad practice. Please, read the rule 5 in "The Power of 10: Rules for Developing Safety-Critical Code" by NASA and other sources. And you can parameterize your test.

Jn Liv
  • 37
  • 4
  • 2
    That rule gives a _minimum_ of two assertions per function, and refers to runtime assertions rather than unit test assertions. – Maximilian Mar 01 '20 at 20:24