pythontestingpytest

How do I disable a test using pytest?


Let's say I have a bunch of tests:

def test_func_one():
    ...

def test_func_two():
    ...

def test_func_three():
    ...

Is there a decorator or something similar that I could add to the functions to prevent pytest from running just that test? The result might look something like...

@pytest.disable()
def test_func_one():
    ...

def test_func_two():
    ...

def test_func_three():
    ...

Solution

  • Pytest has the skip and skipif decorators, similar to the Python unittest module (which uses skip and skipIf), which can be found in the documentation here.

    Examples from the link can be found here:

    @pytest.mark.skip(reason="no way of currently testing this")
    def test_the_unknown():
        ...
    
    import sys
    @pytest.mark.skipif(sys.version_info < (3,3), reason="requires python3.3")
    def test_function():
        ...
    

    The first example always skips the test, the second example allows you to conditionally skip tests (great when tests depend on the platform, executable version, or optional libraries).

    For example, if I want to check if someone has the library pandas installed for a test.

    @pytest.mark.skipif(
        not importlib.util.find_spec("pandas"), reason="requires the Pandas library"
    )
    def test_pandas_function():
        import pandas
        ...