Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I skip a test if another test fails with py.test?

Tags:

python

pytest

Let's say I have these test functions:

def test_function_one():
    assert # etc...

def test_function_two():
    # should only run if test_function_one passes
    assert # etc.

How can I make sure that test_function_two only runs if test_function_one passes (I'm hoping that it's possible)?

Edit: I need this because test two is using the property that test one verifies.

like image 309
Te-jé Rodgers Avatar asked May 05 '12 17:05

Te-jé Rodgers


People also ask

Which decorator is used to skip a test unconditionally with pytest?

You can mark a test with the skip and skipif decorators when you want to skip a test in pytest .

Which option can be passed to pytest to stop test execution after 4 failures have been triggered?

PyTest offers a command-line option called maxfail which is used to stop test suite after n test failures.

How do I stop pytest execution?

pytest has the option -x or --exitfirst which stops the execution of the tests instanly on first error or failed test. pytest also has the option --maxfail=num in which num indicates the number of errors or failures required to stop the execution of the tests.


2 Answers

I'm using the plugin for pytest called pytest-dependency.

Adding to the stated above - if you are using tests inside test classes - you got to add the test class name to the function test name.

For example:

import pytest


class TestFoo:

    @pytest.mark.dependency()
    def test_A(self):
        assert False

    @pytest.mark.dependency(depends=['TestFoo::test_A'])
    def test_B(self):
        assert True

So if test_A fails - test_B won't run. and if test_A passes - test_B will run.

like image 186
sheldonzy Avatar answered Oct 02 '22 13:10

sheldonzy


You can use plugin for pytest called pytest-dependency.

The code can look like this:

import pytest

@pytest.mark.dependency()   #First test have to have mark too
def test_function_one():
    assert 0, "Deliberate fail"

@pytest.mark.dependency(depends=["test_function_one"])
def test_function_two():
    pass   #but will be skipped because first function failed
like image 28
Jakub Wagner Avatar answered Oct 02 '22 15:10

Jakub Wagner