Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pytest parametrizing fixtures with multiple asserts

I have an example code where I have a parametrized test function with two asserts:

@pytest.mark.parametrize("test_input,expected", [
    ("3", 8),
    ("2", 6),
])
def test_eval(test_input, expected):
    assert test_input == expected # first assert
    assert test_input + 2 ==expected # second assert

So the output I wanted was (pseudo code):

assertion error 3==8
assertion error 5==8
assertion error 2==6
assertion error 4==6

While executing the test for all combinations is there a way to reach the second assert even if the first one fails ?

As alternative I'd like to know is there a way to put this into class for example something similar to this:

@pytest.mark.parametrize("test_input,expected", [
    ("3", 8),
    ("2", 6),
])
class TestFunc(object):
   def test_f1(test_input, expected):
     assert test_input==expected
   def test_f2(test_input, expected):
     assert test_input+2==expected

And I want to get the same output as the previous case:

assertion error 3==8
assertion error 5==8
assertion error 2==6
assertion error 4==6
like image 467
lcadc17 Avatar asked Jun 03 '26 10:06

lcadc17


1 Answers

There is the pytest-expect plugin which does that kind of thing.

The way you outlined with using @pytest.mark.parametrize on a class works out-of-the-box, you just forgot self.

Another possibility would be to simply write two tests and share the parametrization:

eval_parametrize = pytest.mark.parametrize("test_input, expected", [
    ("3", 8),
    ("2", 6),
])

@eval_parametrize
def test_f1(test_input, expected):
    assert test_input == expected

@eval_parametrize
def test_f2(test_input, expected):
    assert test_input + 2 == expected
like image 50
The Compiler Avatar answered Jun 04 '26 22:06

The Compiler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!