0
0
PytestHow-ToBeginner ยท 3 min read

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., slow vs Slow).
  • Not using the -m option correctly to select or skip slow tests.

To avoid warnings, add this to pytest.ini:

[pytest]
markers =
    slow: marks tests as slow to run
python
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

CommandDescription
@pytest.mark.slowMark a test as slow
pytest -m slowRun only tests marked slow
pytest -m "not slow"Run all tests except slow ones
Add to pytest.iniRegister 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.