How to Register Custom Marker in pytest: Simple Guide
To register a custom marker in
pytest, add it to the markers list in your pytest.ini file under the [pytest] section. This tells pytest about your marker and avoids warnings when you use it in tests.Syntax
Register a custom marker by adding it to the pytest.ini configuration file. The syntax is:
[pytest]: Section header for pytest settings.markers: Key to list all custom markers.marker_name: description: Each marker with a short description.
ini
[pytest]
markers =
slow: marks tests as slow
smoke: marks smoke testsExample
This example shows how to register a custom marker named slow and use it in a test. Running pytest with -m slow will run only tests marked as slow.
ini and python
[pytest]
markers =
slow: marks tests as slow
# test_sample.py
import pytest
@pytest.mark.slow
def test_example():
assert 1 + 1 == 2Output
============================= test session starts =============================
collected 1 item
test_sample.py . [100%]
============================== 1 passed in 0.01s ==============================
Common Pitfalls
Common mistakes when registering custom markers include:
- Not adding the marker to
pytest.ini, which causes pytest to show warnings. - Misspelling the marker name in the test or config file.
- Forgetting to reload pytest after changing
pytest.ini.
Always keep marker names consistent and restart pytest to apply changes.
python and ini
## Wrong: marker used but not registered # test_sample.py import pytest @pytest.mark.slow def test_example(): assert True # Running pytest shows warning: # "PytestUnknownMarkWarning: Unknown pytest.mark.slow" ## Right: add to pytest.ini # [pytest] # markers = # slow: marks tests as slow
Quick Reference
| Step | Description |
|---|---|
| 1 | Create or open pytest.ini file in your project root |
| 2 | Add [pytest] section if missing |
| 3 | Add markers = followed by your marker names and descriptions |
| 4 | Use @pytest.mark.marker_name in your test functions |
| 5 | Run tests with pytest -m marker_name to select tests |
Key Takeaways
Always register custom markers in pytest.ini under the [pytest] section to avoid warnings.
Use clear descriptions for markers to document their purpose.
Restart pytest after editing pytest.ini to apply marker registrations.
Use @pytest.mark.marker_name to mark tests and pytest -m marker_name to run them selectively.
Misspelled or unregistered markers cause pytest warnings and should be fixed promptly.