Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using pytest, can the results of a testing-function cause a further testing-function to skip?

My goal is to skip a test based on the outcome of a previous testing-function.
In this code-snippet, I hoped test_zero would make skip_further_tests equal to True & therefore test_one would be skipped:

import pytest

skip_further_tests = False

def test_zero():
    global skip_further_tests
    skip_further_tests = True

@pytest.mark.skipif(skip_further_tests, reason='a previous test failed')
def test_one():
    pass

test_one doesn’t skip. Is there a way I can achieve my goal?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can check variable in test body. The drawback is that this pattern means that you rely on tests execution order, which is often bad practice.

import pytest

skip_further_tests = False

def test_zero():
    global skip_further_tests
    skip_further_tests = True

def test_one():
    if skip_further_tests:
        pytest.skip('Previous test failed')
    ...

This will result in the same results display as skipif decorator. Alternatively, you can write your own decorator, like

# Underscore to make it look different from pytest.mak.skipif
def skip_if(var_name: str, reason: str = 'Runtime condition not fulfilled'):

    def decorator(func):

        @functools.wraps(func)
        def inner(*args, **kwargs):
            if globals()[var_name]:
                pytest.skip(reason)
            return func(*args, **kwargs)

        return inner

    return decorator

@skip_if('skip_further_tests')
def test_one():
    ...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading