Skip or Disable Tests in Pytest

What is the proper way to disable or skip a test in pytest?

Let’s say I have several tests defined as follows:

def test_func_one():
    ...

def test_func_two():
    ...

def test_func_three():
    ...

Is there a decorator or method I can use to prevent pytest from running a specific test? I’m looking for a way to skip certain tests without removing them from the codebase. For example, it would be great if I could do something like this:

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

def test_func_two():
    ...

def test_func_three():
    ...

What’s the best way to apply pytest skip to disable a test in pytest?

The easiest way to skip a test in pytest is using @pytest.mark.skip. If you know for sure a test shouldn’t run, just mark it as skipped and provide a reason. Simple and effective!

import pytest

@pytest.mark.skip(reason="No way of currently testing this")
def test_the_unknown():
    pass  # This test will be skipped

Now pytest won’t run this test, and it will clearly display the reason in the output. Super useful when you want to disable tests temporarily but keep track of why!

Taking it further—what if you only want to skip a test in certain conditions? That’s where pytest skipif shines. You can make it conditional based on Python version, OS, or environment!

import pytest
import sys

@pytest.mark.skipif(sys.version_info < (3, 3), reason="Requires Python 3.3 or higher")
def test_function():
    pass  # Skipped on older Python versions

This keeps your test suite adaptable! No need to disable tests entirely—just skip them when needed. pytest skip makes life easier. :white_check_mark:

And if you’re working with optional dependencies, pytest skipif is even more powerful! You can use it to check if a library (like Pandas) is installed before running a test."

import pytest
import importlib.util

@pytest.mark.skipif(not importlib.util.find_spec("pandas"), reason="Requires the Pandas library")
def test_pandas_function():
    import pandas
    pass  # Only runs if Pandas is installed

Now, your test suite won’t fail unnecessarily—pytest will only run tests when the required dependencies are available. pytest skip keeps your testing workflow smooth!