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 slowdef test_example():: the test functionpytest -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.iniwhich 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
| Marker | Purpose | Usage Example |
|---|---|---|
| @pytest.mark.skip | Skip a test | @pytest.mark.skip(reason="skip reason") |
| @pytest.mark.xfail | Mark test expected to fail | @pytest.mark.xfail |
| @pytest.mark.custom | Custom label for tests | @pytest.mark.custom |
| pytest -m 'marker_name' | Run tests with marker | pytest -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.