Test Parameterization in PyTest
Test Parameterization in PyTest
Test parameterization is a technique in PyTest that allows you to run a test function multiple times with different sets of input values. Instead of writing multiple test functions with different input values, parameterization helps in reducing code duplication and improving maintainability. PyTest provides the @pytest.mark.parametrize
decorator to achieve this.
Understanding @pytest.mark.parametrize
The @pytest.mark.parametrize
decorator allows you to specify multiple sets of input values for a single test function. It takes two arguments:
- A string containing comma-separated parameter names.
- A list of tuples containing the values to be used for testing.
Each tuple represents a different test case, and the test function will be executed once for each set of parameters.
Advantages of Test Parameterization
- Reduces Code Duplication: Instead of writing multiple test functions, you can use one test function with different inputs.
- Enhances Test Coverage: Ensures that the function works correctly with various input values.
- Improves Maintainability: Updating test cases is easier since all inputs are managed in one place.
- Automates Repetitive Testing: Automatically runs the test multiple times with different values.
Simple Example
Below is an example of using @pytest.mark.parametrize
to test a function that adds two numbers:
import pytest
@pytest.mark.parametrize("a, b, expected", [(1, 2, 3), (4, 5, 9), (10, 20, 30)])
def test_addition(a, b, expected):
assert a + b == expected
In this example:
- The test function
test_addition
runs three times, once for each tuple. - Each tuple contains different values for
a
,b
, and the expected result. - PyTest automatically executes the function with each set of parameters.
- This code will run three tests as shown:
Test Output
============================= test session starts =============================
collecting … collected 3 items
parameters.py::test_addition[1-2-3] PASSED [ 33%]
parameters.py::test_addition[4-5-9] PASSED [ 66%]
parameters.py::test_addition[10-20-30] PASSED [100%]
============================== 3 passed in 0.03s ==============================
Process finished with exit code 0