Parameterized Tests Using pytest

Learn how to write parameterized tests using pytest.

Running parameterized tests with pytest is better, not only because it provides a cleaner API, but also because each combination of the test with its parameters generates a new test case (a new function).

Writing parameterized tests using pytest

To work with this, we have to use the pytest.mark.parametrize decorator on our test. The first parameter of the decorator is a string indicating the names of the parameters to pass to the test function, and the second has to be iterable with the respective values for those parameters.

Example

Notice how the body of the testing function is reduced to one line (after removing the internal for loop, and its nested context manager), and the data for each test case is correctly isolated from the body of the function, making it easier to extend and maintain:

Get hands-on with 1400+ tech skills courses.