0
0
PytestHow-ToBeginner ยท 4 min read

How to Use Markers in pytest for Test Selection and Categorization

In pytest, markers are used to label tests for selective running or special handling by adding @pytest.mark.marker_name above test functions. You can run tests with specific markers using pytest -m 'marker_name' and also skip or expect failures with built-in markers like skip or xfail.
๐Ÿ“

Syntax

Markers are added as decorators above test functions using @pytest.mark.marker_name. You can create custom markers or use built-in ones like skip and xfail. To run tests with a marker, use pytest -m 'marker_name'.

Example parts:

  • @pytest.mark.slow: marks a test as slow
  • def test_example():: the test function
  • pytest -m 'slow': runs only tests marked as slow
python
import pytest

@pytest.mark.slow
def test_example():
    assert 1 + 1 == 2

@pytest.mark.skip(reason="Not ready")
def test_skip():
    assert False

@pytest.mark.xfail
def test_expected_fail():
    assert 1 == 0
๐Ÿ’ป

Example

This example shows how to mark tests as slow, skip a test, and mark a test as expected to fail. Running pytest -m 'slow' will only run the slow test.

python
import pytest

@pytest.mark.slow
def test_addition():
    assert 2 + 3 == 5

@pytest.mark.skip(reason="Skipping this test for now")
def test_skip_example():
    assert False

@pytest.mark.xfail
def test_fail_example():
    assert 1 == 0
Output
============================= test session starts ============================== collected 3 items <file_name>.py .sX [100%] =========================== 1 passed, 1 skipped, 1 xfailed ====================
โš ๏ธ

Common Pitfalls

Common mistakes include:

  • Using markers without registering them in pytest.ini which can cause warnings.
  • Misspelling marker names when running tests with -m.
  • Using markers on non-test functions or classes incorrectly.

Always register custom markers in pytest.ini to avoid warnings.

python
### Wrong: Using unregistered marker causes warning
import pytest

@pytest.mark.unknown_marker
def test_func():
    assert True

### Right: Register marker in pytest.ini
# [pytest]
# markers =
#     unknown_marker: mark test with unknown_marker

# Then use the same decorator without warnings
๐Ÿ“Š

Quick Reference

MarkerPurposeUsage Example
@pytest.mark.skipSkip a test@pytest.mark.skip(reason="skip reason")
@pytest.mark.xfailMark test expected to fail@pytest.mark.xfail
@pytest.mark.customCustom label for tests@pytest.mark.custom
pytest -m 'marker_name'Run tests with markerpytest -m 'slow'
โœ…

Key Takeaways

Use @pytest.mark.marker_name to label tests for selective running or special handling.
Run tests with a specific marker using pytest -m 'marker_name'.
Register custom markers in pytest.ini to avoid warnings.
Built-in markers like skip and xfail help control test execution flow.
Markers help organize tests by categories like slow, integration, or smoke.