0
0
PyTesttesting~5 mins

Why markers categorize and control tests in PyTest

Choose your learning style9 modes available
Introduction

Markers help organize tests by grouping them. They also let you choose which tests to run or skip easily.

You want to run only fast tests during development.
You need to skip tests that require a database when it is not available.
You want to group tests by feature or priority.
You want to run tests only on certain environments like Windows or Linux.
Syntax
PyTest
@pytest.mark.marker_name
def test_function():
    pass

Markers are added above test functions using @pytest.mark.name.

You can use markers to select or skip tests when running pytest.

Examples
This test is marked as 'slow' to identify it as a long-running test.
PyTest
@pytest.mark.slow
def test_long_process():
    assert True
This test is skipped with a reason given.
PyTest
@pytest.mark.skip(reason="Not ready")
def test_not_ready():
    assert False
This test is marked to indicate it needs database access.
PyTest
@pytest.mark.database
def test_db_access():
    assert True
Sample Program

This script has three tests with different markers: 'fast', 'slow', and 'skip'. You can run only the fast tests using pytest -m fast.

PyTest
import pytest

@pytest.mark.fast
def test_addition():
    assert 1 + 1 == 2

@pytest.mark.slow
def test_wait():
    import time
    time.sleep(1)
    assert True

@pytest.mark.skip(reason="Skip this test")
def test_skip():
    assert False

# Run only fast tests
# Command: pytest -m fast
OutputSuccess
Important Notes

Use markers to organize tests by type, speed, or requirements.

You can combine markers to run complex selections of tests.

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

Summary

Markers group tests to make running specific sets easier.

Markers can skip or select tests based on conditions.

Using markers helps save time and focus testing efforts.