How to Create Custom Marker in pytest for Test Organization
To create a custom marker in
pytest, define it in your pytest.ini file under the [pytest] section using the markers option. Then, use @pytest.mark.your_marker above your test functions to tag them for selective running or grouping.Syntax
Define custom markers in the pytest.ini file to avoid warnings and enable pytest to recognize them. Use the markers option followed by a description. Apply markers to tests with @pytest.mark.marker_name.
- pytest.ini: Declare markers to register them.
- @pytest.mark.marker_name: Decorate test functions to tag them.
ini
[pytest]
markers =
slow: marks tests as slow running
smoke: marks smoke testsExample
This example shows how to create two custom markers slow and smoke in pytest.ini, then tag tests with them. You can run tests selectively using -m option.
python
# pytest.ini [pytest] markers = slow: marks tests as slow running smoke: marks smoke tests # test_sample.py import pytest @pytest.mark.slow def test_long_task(): assert 1 + 1 == 2 @pytest.mark.smoke def test_quick_check(): assert 'a'.upper() == 'A' def test_regular(): assert True
Output
============================= test session starts ==============================
collected 3 items
$ pytest -m slow
=============================== test session starts ===========================
collected 3 items / 1 deselected / 2 selected
test_sample.py . [100%]
============================== 1 passed, 1 deselected ===========================
$ pytest -m smoke
=============================== test session starts ===========================
collected 3 items / 2 deselected / 1 selected
test_sample.py . [100%]
============================== 1 passed, 2 deselected ===========================
Common Pitfalls
Common mistakes when creating custom markers include:
- Not declaring markers in
pytest.ini, which causes warnings. - Misspelling marker names in decorators or command line.
- Using markers without purpose, making test selection confusing.
Always declare markers to keep tests organized and avoid warnings.
python
# Wrong: Marker not declared in pytest.ini import pytest @pytest.mark.unknown_marker def test_example(): assert True # Right: Declare marker in pytest.ini # [pytest] # markers = # unknown_marker: example marker # Then use the marker as above without warnings.
Quick Reference
| Step | Description | Example |
|---|---|---|
| 1 | Declare marker in pytest.ini | [pytest] markers = mymarker: description |
| 2 | Tag test with marker | @pytest.mark.mymarker |
| 3 | Run tests with marker | pytest -m mymarker |
| 4 | Avoid warnings | Always declare markers before use |
Key Takeaways
Always declare custom markers in pytest.ini to avoid warnings.
Use @pytest.mark.marker_name to tag tests for selective runs.
Run tests with markers using pytest -m marker_name command.
Check marker spelling carefully to prevent test selection errors.
Custom markers help organize and run specific test groups efficiently.