How to pass a test if condition is True using Pytest

Viewed 25

How can I properly pass a test if a condition is true?

Just a general example:

import pytest

def test_animal_color(color):
    
    fish_color = 'Blue'
    if fish_color == color:
        # pass the test and don't run anymore code

    rat_color = 'Gray'
    if rat_color == color:
        # pass the test and don't run anymore code

    frog_color = 'Green'
    if frog_color == color:
        # pass the test and don't run anymore code 

The real usage for this will be used in a much more complex piece of code of course on which I will have methods inside methods and I want to pass the test when the parameter condition is met, it doesn't matter in which method, the test must pass and the remaining code should no longer run.

1 Answers

You can combine assert with any to achieve that:

assert any(color == c for c in [fish_color, rat_color, frog_color])

any with generator expressions evaluates only up to first True value, so as soon as any condition is True any will also return True and the assertion will pass. If none are matching, False will be returned and assert will raise an AssertionError.

Related