Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I create a `pytest.mark.failif`?

Tags:

python

pytest

pytest allows you to skip a test under some condition (i.e.: on a platform):

@pytest.mark.skipif(sys.platform == "win32")
def test_foo(fixture):
    assert bar(fixture)

Is there a way to create a mark to make the test fail under a certain condition?

@pytest.mark.failif(sys.platform == "win32")
def test_foo(fixture):
    assert bar(fixture)
like image 532
Peque Avatar asked Oct 19 '25 14:10

Peque


1 Answers

Even without pytest you could write a simple decorator that does this:

def failif(condition: bool, *, reason: str) -> Callable[[T], T]:
    def failif_decorator(func: T) -> T:
        @functools.wraps(func)
        def failif_decorator_inner(*args: Any, **kwargs: Any) -> Any:
            assert not condition, reason
            return func(*args, **kwargs)
        return cast(T, failif_decorator_inner)
    return failif_decorator

Usage would be

@failif(sys.platform == 'win32', reason='we do not support windows')
def test():
    ...

for a pytest-specific solution you could use one of the hooks for registering marks -- though that's quite a bit more involved

like image 58
Anthony Sottile Avatar answered Oct 21 '25 02:10

Anthony Sottile



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!