How to Use @pytest.mark.skipif to Conditionally Skip Tests
Use
@pytest.mark.skipif(condition, reason='explanation') to skip a test when the condition is True. This decorator helps you avoid running tests in specific environments or situations by providing a clear reason for skipping.Syntax
The @pytest.mark.skipif decorator takes two main parts:
- condition: A Python expression that returns True or False. If True, the test is skipped.
- reason: A string explaining why the test is skipped. This helps others understand the skip.
python
@pytest.mark.skipif(condition, reason='reason for skipping') def test_function(): pass
Example
This example shows skipping a test if Python version is less than 3.8. The test will run only on Python 3.8 or higher.
python
import sys import pytest @pytest.mark.skipif(sys.version_info < (3, 8), reason='Requires Python 3.8 or higher') def test_new_feature(): assert True
Output
============================= test session starts =============================
collected 1 item
example.py s [100%]
============================== 1 skipped in 0.01s =============================
Common Pitfalls
Common mistakes when using @pytest.mark.skipif include:
- Not providing a
reason, which makes it unclear why the test was skipped. - Using a condition that always evaluates to True or False unintentionally, causing tests to always skip or never skip.
- Writing complex conditions that are hard to read or maintain.
Always keep the condition simple and the reason clear.
python
import sys import pytest # Wrong: no reason given @pytest.mark.skipif(sys.platform == 'win32') def test_windows_feature(): assert True # Right: clear reason provided @pytest.mark.skipif(sys.platform == 'win32', reason='Not supported on Windows') def test_windows_feature(): assert True
Quick Reference
| Parameter | Description |
|---|---|
| condition | Python expression; if True, test is skipped |
| reason | String explaining why the test is skipped (required) |
Key Takeaways
Use @pytest.mark.skipif with a clear condition and reason to skip tests conditionally.
Always provide a reason to explain why a test is skipped for better clarity.
Keep the skip condition simple and easy to understand.
Skipping tests helps avoid failures in unsupported environments or setups.