Custom Markers in PyTest
Custom Markers in PyTest
PyTest is a powerful testing framework for Python that allows users to organize and execute test cases efficiently. One of its most useful features is markers, which help in categorizing and selectively running tests. While PyTest provides built-in markers, users can also define their own custom markers to better structure their test suites.
How to Specify Custom Markers in pytest.ini
File
To create and use custom markers, you need to register them in the pytest.ini
file. This ensures that PyTest recognizes the markers and does not raise warnings.
[pytest]
markers =
smoke: Marks test as a smoke test
regression: Marks test as a regression test
slow: Marks test as a slow-running test
Simple Example of Custom Test Marker
Below is an example of how to use custom markers in a PyTest script:
import pytest
@pytest.mark.smoke
def test_login():
assert 1 + 1 == 2
@pytest.mark.regression
def test_user_profile():
assert "username" in {"username": "John"}
@pytest.mark.slow
def test_data_processing():
import time
time.sleep(5)
assert True
You can run tests with a specific marker using the following command:
pytest -m smoke
This will execute only the tests marked with @pytest.mark.smoke
.