How to Use Mark for Filtering Tests in pytest
In
pytest, you can use @pytest.mark.name to label tests and then run only those tests by using the -m option with the mark name. This lets you filter tests by categories or features quickly from the command line.Syntax
Use @pytest.mark.mark_name above a test function to assign a mark. Then run tests with pytest -m "mark_name" to execute only those marked tests.
@pytest.mark.mark_name: Decorator to tag a test.pytest -m "mark_name": Command line option to filter tests by mark.
python
import pytest @pytest.mark.slow def test_example_slow(): assert True @pytest.mark.fast def test_example_fast(): assert True
Example
This example shows two tests marked as slow and fast. Running pytest -m slow runs only the slow test.
python
import pytest @pytest.mark.slow def test_slow(): assert 1 + 1 == 2 @pytest.mark.fast def test_fast(): assert 2 * 2 == 4
Output
============================= test session starts =============================
collected 2 items
test_example.py . . [100%]
=========================== short test summary info ===========================
PASSED test_example.py::test_slow
PASSED test_example.py::test_fast
============================== 2 passed in 0.01s ==============================
Common Pitfalls
Common mistakes include:
- Not registering custom marks in
pytest.ini, which causes warnings. - Using incorrect mark names or typos in the command line.
- Trying to combine marks without quotes or proper syntax.
Always register custom marks in pytest.ini under [pytest] with markers = to avoid warnings.
pytest
### Wrong: Running without quotes or typo in mark name
# Command: pytest -m slowtest
### Right: Use quotes and correct mark name
# Command: pytest -m "slow"
### pytest.ini example to register marks
# [pytest]
# markers =
# slow: marks tests as slow
# fast: marks tests as fast
Quick Reference
| Command | Description |
|---|---|
| @pytest.mark. | Mark a test with a custom label |
| pytest -m " | Run tests with the specified mark |
| pytest.ini markers | Register custom marks to avoid warnings |
| pytest -m "not | Run tests without the specified mark |
Key Takeaways
Use @pytest.mark. to label tests for filtering.
Run pytest with -m "" to execute only marked tests.
Register custom marks in pytest.ini to prevent warnings.
Use quotes around mark expressions in the command line.
Combine marks with logical operators inside quotes for complex filtering.