How to Skip Slow Tests with pytest.mark in Python
Use pytest.mark.skip and custom marks like @pytest.mark.slow to skip or deselect slow tests during test runs.
pip install pytest
Python code
22 linesimport pytest
import time
def test_fast():
assert 1 + 1 == 2
@pytest.mark.skip(reason="slow test skipped by default")
def test_slow():
time.sleep(5)
assert True
@pytest.mark.slow
def test_marked_slow():
time.sleep(5)
assert True
if __name__ == "__main__":
pytest.main([__file__, "-v", "--deselect", "test_marked_slow"])
Output
============================= test session starts ==============================
platform linux -- Python 3.11.0, pytest-8.0.0, pluggy-1.4.0
rootdir: /home/user
collected 3 items
test_example.py::test_fast PASSED
============================== 1 passed in 0.01s ===============================
How it works
The @pytest.mark.skip decorator marks a test to be excluded from the test run, and the reason parameter documents why it's skipped. Custom marks like @pytest.mark.slow tag tests for selective execution — you can run only marked tests with -m slow or exclude them with -m "not slow". The --deselect option in pytest.main filters out specific test nodes by their full ID. Skipped tests are reported as 'S' in verbose output and don't count as failures, keeping your CI green while still acknowledging the test exists.
Common mistakes
- Forgetting to pass a reason to skip — pytest will warn about missing reasons
- Using `@pytest.mark.skipif` with a wrong condition, causing tests to skip unexpectedly
- Placing the mark on the wrong function or class when using parametrized tests
- Not registering custom marks in pytest.ini, which triggers PytestUnknownMarkWarning
Variations
- Use `@pytest.mark.skipif(sys.version_info < (3, 10), reason="requires 3.10+")` for conditional skips
- Run only fast tests with `pytest -m "not slow"` instead of deselecting individually
Real-world use cases
- Skipping integration tests that require external services in your CI pipeline.
- Tagging flaky or network-dependent tests to run only in nightly regression suites.
- Marking performance benchmarks to exclude during rapid development iteration.
Sponsored
More from Testing & modern typing
- Capture stdout and stderr with pytest capsys easy
- Characterization Test for Legacy Python Code medium
- Dataclass with Type Hints Fields in Python easy
- Dependency Injection in Python for Testability easy
- Design Data Helpers with Python TypedDict and Literal easy
- Fix and Test a Regression Bug in Python with Unit Tests easy
Keep learning
Related tutorials and quizzes for this topic.