Using pytest, can the results of a testing-function cause a further testing-function to skip?
Question:
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?
Answers:
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():
...
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?
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():
...