We’ll look at how to turn one test function into many test cases to test more thoroughly with less work. We’ll do this with parametrization.
Parametrized testing refers to adding parameters to our test functions and passing in multiple sets of arguments to the test to create new test cases. We’ll look at three ways to implement parametrized testing in pytest in the order in which they should be selected:
Parametrizing functions
Parametrizing fixtures
Using a hook function called pytest_generate_tests
We’ll compare them side by side by solving the same parametrization problem using all three methods; however, as you’ll see, there are times when one solution is preferred over the others.
Before we really jump in to how to use parametrization, though, we’ll take a look at the redundant code we are avoiding with parametrization. Then we’ll look at three methods of parametrization. When we’re done, you’ll be able to write concise, easy-to-read test code that tests a huge number of test cases.
We can parametrize test functions, creating many test cases, when we apply the @pytest.mark.parametrize() decorator.
We can parametrize fixtures with @pytest.fixture(params=()). This is helpful if the fixture needs to do different work based on the parameter values.
We can generate complex parametrization sets with pytest_generate_tests.