PyTest Test Decorators
PyTest Test Decorators
PyTest is a popular testing framework in Python used for writing and executing test cases efficiently. One of its powerful features is decorators, which help modify the behavior of test functions dynamically. These decorators provide various functionalities such as skipping tests, marking tests for specific conditions, parameterizing test cases, and more.
Understanding Test Decorators
Decorators in PyTest are special functions prefixed with @pytest
that modify the behavior of test functions. They are used to control test execution, provide metadata, and handle specific test conditions.
Common Test Decorators
Decorator | Description |
---|---|
@pytest.mark.skip |
Skips the test unconditionally. |
@pytest.mark.skipif(condition, reason) |
Skips the test if a given condition is True. |
@pytest.mark.xfail |
Marks a test as expected to fail. |
@pytest.mark.parametrize |
Runs the test multiple times with different values. |
@pytest.fixture |
Defines a fixture to provide setup and teardown functionality. |
Uses of Test Decorators
Some of the uses of test decorators are as follows:
- Enhances test modularity and reusability.
- Allows conditional execution of tests.
- Improves test readability and organization.
- Reduces code duplication through fixtures and parameterization.
- Helps in debugging and isolating failing test cases.
Example of Test Decorators
Let’s look at simple example of test decorators in PyTest:
import pytest @pytest.mark.skip(reason="Skipping this test for now") def test_skip_example(): assert 1 + 1 == 2 @pytest.mark.parametrize("x, y, result", [(1, 2, 3), (4, 5, 9), (10, 20, 30)]) def test_addition(x, y, result): assert x + y == result @pytest.fixture def sample_data(): return {"name": "John", "age": 30} def test_fixture_example(sample_data): assert sample_data["name"] == "John"
Test Output
============================= test session starts =============================
collecting … collected 5 items
decorators.py::test_skip_example SKIPPED (Skipping this test for now) [ 20%]
Skipped: Skipping this test for now
decorators.py::test_addition[1-2-3] PASSED [ 40%]
decorators.py::test_addition[4-5-9] PASSED [ 60%]
decorators.py::test_addition[10-20-30] PASSED [ 80%]
decorators.py::test_fixture_example PASSED [100%]
======================== 4 passed, 1 skipped in 0.03s =========================
Process finished with exit code 0