All Posts

Difference between Test Decorators and Markers

Difference between Test Decorators and Markers

PyTest is a popular testing framework for Python that provides powerful features for writing and managing tests. Among these features, test decorators and markers play a crucial role in customizing and controlling test execution. Decorators modify test functions, while markers help categorize and selectively run tests.

Test Decorators in PyTest

Test decorators in PyTest are special Python functions that modify the behavior of test functions. They are typically used to skip tests, parameterize test cases, or set up fixtures. Decorators help enhance test functions without modifying their core logic.

Test Markers in PyTest

Test markers in PyTest are used to categorize tests and control their execution. They allow users to selectively run specific tests, group tests under different categories, and apply conditions for execution. Markers help in organizing large test suites efficiently.

Markers vs Decorators

Feature Test Decorators Test Markers
Purpose Modifies the behavior of test functions Categorizes and controls test execution
Usage Used for skipping tests, parameterizing, or using fixtures Used for tagging tests, setting conditions, and filtering tests
Syntax Applied using @pytest... before the test function Defined using @pytest.mark... before the test function
Effect Changes test execution behavior Determines which tests to run based on criteria

Example of Test Decorator

import pytest

@pytest.mark.skip(reason="This test is temporarily disabled")
def test_example():
    assert 1 + 1 == 2
    

In this example, the @pytest.mark.skip decorator is used to skip the test execution.

Example of Test Marker

import pytest

@pytest.mark.slow
def test_slow_function():
    import time
    time.sleep(5)
    assert True
    

Here, @pytest.mark.slow is a custom marker that can be used to categorize the test as a slow-running test.