简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM