Member-only story
Introduction to Parametrized Testing in Pytest
Introduction:
Testing is an essential part of software development, and pytest is a popular testing framework for Python. One of the powerful features of pytest is parametrized testing, which allows you to define a test function with multiple sets of input values, and pytest will run the test function for each set of input values. In this article, we’ll explore how to use parametrized testing in pytest with examples.
Parametrized Testing in Pytest:
Parametrized testing in pytest allows you to define a test function with multiple sets of input values. You can use the @pytest.mark.parametrize
decorator to define the input values for your test function. The decorator takes the name of the parameter as the first argument, followed by a list of values or tuples of values for each parameter. The test function should take the same number of arguments as the number of parameters.
Here’s an example of how to use parametrized testing in pytest:
import pytest
@pytest.mark.parametrize("input1, input2, expected_output", [
(1, 2, 3),
(0, 0, 0),
(-1, 1, 0),
("hello", "world", "helloworld"),
])
def test_add(input1, input2, expected_output):
assert input1 + input2 == expected_output
In this example, we’re using the @pytest.mark.parametrize
decorator to define a test function test_add
with multiple sets of input and expected output values. The test function takes three…