rbs
rbs

Reputation: 189

Is there a way to exit a pytest test and continue to the next one?

Say I have 2 tests defined. Is there a way to exit from the first test (for instance if a condition is True) without executing the rest of the test's code and proceed to the following test? (Something like the continue statement from loops, but instead of loops, continue to the next test)

Upvotes: 5

Views: 6412

Answers (3)

MortenB
MortenB

Reputation: 3529

pytest.exit("exit test successfully")

  • This test is handled as an successfull test

pytest.skip("we are skipping this test and continue to next")

  • This test is handled as a skipped test

We ignore skipped tests completely, while successful exited tests show up with logs and execution time in reports and stats.

Upvotes: 0

WaveRider
WaveRider

Reputation: 495

For pytest, there are plenty of skipping capabilities, check out pytest skip docs

But if you are using unittest, in similar fashion, you can manually skip it with a decorator prior to running the test, something like:

@unittest.skip("Skipping test_myFunction test"):
def test_myFunction(self):
    assert(testing_definition)

OR just put a condition that can be mapped either internally to the function or the unittest.Testcase constructor:

# @unittest.skip("Skipping test_myFunction test"):
def test_myFunction(self):
    condition = self.condition  # or however you define
    if condition:
        assert(testing_definition)
    else:
        print("Internal skip of test_myFunction where condition = {}".format(condition)"

Upvotes: 0

hspandher
hspandher

Reputation: 16733

You can always return from your test on basis of some condition, which would make it exit without executing any code that follows.

You can selectively run tests in pytest for debugging purposes, if that's what you mean -

py.test mytestfile.py -k <pattern>

Otherwise, the thing is people don't really like to spend too much time fixing tests. So tests need to be very simple and well written even more than the code they are testing, as no one is going to write tests to test the tests. Even if such random behaviour were possible, I won't recommend it.

Upvotes: 3

Related Questions