Using Pytest Markers to Categorize and Run Test Cases
This article explains how to define, register, and use Pytest markers to classify test cases such as smoke, regression, and integration tests, demonstrates command‑line options for selective execution, and shows dynamic marker assignment with practical code examples.
Pytest markers provide a powerful way to categorize and filter test cases, improving flexibility and efficiency during test execution.
1. Setting Test Case Markers
Use the @pytest.mark decorator to attach arbitrary string tags to test functions, e.g., @pytest.mark.smoke or @pytest.mark.regression . Example:
import pytest
@pytest.mark.smoke
def test_login():
assert True
@pytest.mark.regression
def test_update_profile():
assert True
@pytest.mark.smoke
@pytest.mark.regression
def test_logout():
assert TrueRegister custom markers in pytest.ini to make them discoverable and documented:
[pytest]
markers =
smoke: mark test as smoke
regression: mark test as regression
integration: mark test as integration2. Running Specific Marked Tests
Use the -m option to select tests by marker:
pytest -m smokeCombine markers with logical operators:
pytest -m "smoke or regression"
pytest -m "not smoke"
pytest -m "smoke and regression"3. Dynamically Setting Markers
Markers can be applied at runtime based on conditions:
import pytest
def test_dynamic_mark():
if some_condition():
pytest.mark.smoke(test_dynamic_mark)
else:
pytest.mark.regression(test_dynamic_mark)4. Marker Use Cases
Smoke tests verify core functionality quickly after each build; regression tests ensure changes haven’t broken existing features; integration tests validate interactions between modules. Each type is marked accordingly and run with pytest -m commands.
5. Conclusion
By defining and registering markers, and using the -m option, developers can flexibly select and run relevant test suites, improving test coverage, efficiency, and maintainability in automated testing workflows.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.