How to Use @pytest.mark.slow to Mark Slow Tests
Use
@pytest.mark.slow to label tests that take longer to run. This helps you run or skip slow tests easily by using pytest command-line options like -m slow.Syntax
The @pytest.mark.slow decorator is placed above a test function to mark it as slow. You can then use pytest's -m option to select or deselect these tests.
@pytest.mark.slow: Marks the test as slow.- Test function: The function you want to label.
- Command line
pytest -m slow: Runs only tests marked as slow. - Command line
pytest -m "not slow": Runs all tests except those marked slow.
python
import pytest @pytest.mark.slow def test_example(): assert True
Example
This example shows how to mark a slow test and run it selectively using pytest.
python
import pytest import time @pytest.mark.slow def test_slow_function(): time.sleep(2) # Simulate slow test assert True def test_fast_function(): assert True
Output
============================= test session starts ==============================
collected 2 items
example_test.py .. [100%]
============================== 2 passed in 2.01s ===============================
# Run only slow tests:
# pytest -m slow
============================= test session starts ==============================
collected 2 items
example_test.py .s [100%]
============================== 1 passed, 1 skipped in 2.01s ======================
Common Pitfalls
Common mistakes when using @pytest.mark.slow include:
- Forgetting to register the marker in
pytest.ini, which can cause warnings. - Using inconsistent marker names (e.g.,
slowvsSlow). - Not using the
-moption correctly to select or skip slow tests.
To avoid warnings, add this to pytest.ini:
[pytest]
markers =
slow: marks tests as slow to runpython
import pytest # Wrong: marker not registered, may cause warning @pytest.mark.Slow def test_wrong_marker(): assert True # Right: use lowercase and register marker @pytest.mark.slow def test_right_marker(): assert True
Quick Reference
| Command | Description |
|---|---|
| @pytest.mark.slow | Mark a test as slow |
| pytest -m slow | Run only tests marked slow |
| pytest -m "not slow" | Run all tests except slow ones |
| Add to pytest.ini | Register marker to avoid warnings |
Key Takeaways
Use @pytest.mark.slow to label tests that take longer to run.
Run slow tests selectively with pytest -m slow or skip them with pytest -m "not slow".
Register the slow marker in pytest.ini to avoid warnings.
Be consistent with marker names and use lowercase 'slow'.
Marking slow tests helps keep your test suite efficient and organized.