Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assert once with multiple conditions?

Tags:

python

pytest

How can I make the following code more pythonic? so I can combine if/else and 2 assert statement into one line?

@pytest.mark.parametrize('para', [1, -1, 0])
def test_xxxx(self, para):
    def test(value):
        return False if value >= 0 else True

    if para >= 0:
        assert test(para) is False
    else:
        assert test(para) is True
like image 456
jacobcan118 Avatar asked Nov 26 '25 13:11

jacobcan118


1 Answers

Be explicit and simply write out 3 assertions with the inputs and expected outputs (note: I took your function outside your test and gave it a clearer name).

def my_func(value):
    return False if value >= 0 else True

def test_my_func(self):
    assert my_func(1) is False
    assert my_func(-1) is True
    assert my_func(0) is True

This is "being pythonic" because as PEP-8 says, "explicit is always better than implicit". When you're dealing with tests, writing as little functioning code as possible is more important than writing fewer lines.

Three explicit assertions is far less likely to fail than a wacky parameterizing loop or trying to make it a one-liner.

like image 188
Soviut Avatar answered Nov 28 '25 03:11

Soviut



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!