Sometimes, you want to skip a test only when a certain condition is true. This helps avoid running tests that don't make sense in some situations.
0
0
@pytest.mark.skipif with condition
Introduction
Skip a test if a required package is not installed.
Skip a test on a specific operating system like Windows or Linux.
Skip a test if a certain environment variable is missing.
Skip a test when running on a slow or limited resource machine.
Syntax
PyTest
@pytest.mark.skipif(condition, reason="explanation") def test_function(): # test code here
The condition is a Python expression that returns True or False.
The reason explains why the test is skipped and shows in the test report.
Examples
Skip the test if the OS does not support the
fork function.PyTest
import os import pytest @pytest.mark.skipif(not hasattr(os, 'fork'), reason="No fork support on this OS") def test_fork(): pass
Skip the test when running on Windows.
PyTest
import sys import pytest @pytest.mark.skipif(sys.platform == 'win32', reason="Test not supported on Windows") def test_unix_only(): pass
Skip the test if the environment variable
MY_ENV is not set.PyTest
import os import pytest @pytest.mark.skipif('MY_ENV' not in os.environ, reason="Environment variable MY_ENV missing") def test_env_var(): pass
Sample Program
This script has two tests. One skips on Windows, the other runs only on Windows. When you run it, one test will be skipped depending on your OS.
PyTest
import pytest import sys @pytest.mark.skipif(sys.platform == 'win32', reason="Skip on Windows") def test_not_on_windows(): assert True @pytest.mark.skipif(sys.platform != 'win32', reason="Run only on Windows") def test_only_on_windows(): assert True if __name__ == '__main__': pytest.main(['-v', __file__])
OutputSuccess
Important Notes
Always provide a clear reason so others understand why the test is skipped.
The condition is evaluated when pytest collects tests, not when tests run.
Use skipif to keep your test suite clean and avoid false failures.
Summary
@pytest.mark.skipif skips tests based on a condition.
Use it to avoid running tests in unsuitable environments.
Always give a reason to explain the skip.