Grouping Tests Using pytest.mark
Grouping Tests Using pytest.mark
In Python, Pytest is a popular testing framework used for writing and running test cases. The pytest.mark decorator allows you to categorize and group tests based on specific markers. This helps in organizing tests efficiently and running selected test groups as needed.
pytest.mark Decorator
The pytest.mark decorator can be used to assign labels (markers) to test functions. This helps in selectively running tests based on their assigned markers. For example, you can mark tests as smoke, regression, database, etc., and run only specific categories when needed.
To use custom markers, you need to register them in the pytest.ini file to avoid warnings.
Example Code
import pytest
@pytest.mark.smoke
def test_function_1():
assert 2 + 2 == 4
@pytest.mark.regression
def test_function_2():
assert "hello".upper() == "HELLO"
@pytest.mark.database
def test_function_3():
assert len([1, 2, 3]) == 3
Running Tests by Marker
You can run tests with a specific marker using the -m option:
pytest -m smoke
Registering Custom Markers
To avoid warnings, register custom markers in the pytest.ini file:
[pytest]
markers =
smoke: Marks tests as smoke tests
regression: Marks tests as regression
database: Marks tests as database related
Using pytest.mark, you can better manage your test cases by grouping them into meaningful categories.