0
0
PyTesttesting~5 mins

Custom markers in PyTest

Choose your learning style9 modes available
Introduction

Custom markers help you label tests so you can run or skip groups of tests easily.

You want to run only slow tests separately from fast tests.
You want to skip tests that need a database when it is not available.
You want to mark tests that check new features under development.
You want to group tests by feature or module for easier management.
Syntax
PyTest
import pytest

@pytest.mark.marker_name
def test_example():
    assert True

Markers are added with @pytest.mark.marker_name above test functions.

You can run tests with a marker using pytest -m marker_name.

Examples
This test is marked as slow to run separately.
PyTest
import pytest

@pytest.mark.slow
def test_long_process():
    assert True
This test is skipped because the condition is True.
PyTest
import pytest

@pytest.mark.skipif(condition=True, reason="Not ready")
def test_skip():
    assert False
This test is marked for feature X grouping.
PyTest
import pytest

@pytest.mark.feature_x
def test_feature_x():
    assert 1 + 1 == 2
Sample Program

Here, two tests are marked database and one test is marked api. You can run only database tests with pytest -m database.

PyTest
import pytest

@pytest.mark.database
def test_db_connection():
    assert True

@pytest.mark.api
def test_api_response():
    assert True

@pytest.mark.database
def test_db_query():
    assert True
OutputSuccess
Important Notes

Always register custom markers in pytest.ini to avoid warnings.

Use clear marker names to keep tests organized.

Summary

Custom markers label tests for easy grouping and running.

Use @pytest.mark.name to add markers.

Run marked tests with pytest -m name.