George Shuklin
George Shuklin

Reputation: 7927

How to stop running other tests in a module if a specific test fails in pytest?

I have a module with tests for pytest. There are many tests there, and the fist checks if there is a connectivity to a target. If this test fails, there is no reason to wait for all other tests in this particular module to timeout. I'd like to stop all tests in the module if this one specific test failed.

I found pytest.exit(), but it's too strong, it terminates the whole pytest run. I have other modules to work with, so I want to skip/fail quickly all other tests in only one (current) module.

Are there a way to do this?

Upvotes: 1

Views: 2002

Answers (1)

Guy
Guy

Reputation: 50949

You can use @pytest.mark.skipif annotation instead of running another test first

def has_connection():
    return True


@pytest.mark.skipif(not has_connection(), reason='No connection')
def test_example(self):
    pass

If all the tests are under class you can add the annotation to the class, this will skip all the tests

@pytest.mark.skipif(not has_connection(), reason='No connection')
class TestExample:

    def test_example1(self):
        pass

    def test_example2(self):
        pass

Upvotes: 1

Related Questions