Imagine you want to write a test for a particular function, but for multiple input values. Writing a for-loop is a bad idea as the test will fail as soon as it hits the first AssertionError. Subsequent input values will not be tested and you have no idea which part of your code is actually broken. At the same time you want to stick to DRY and not implement the same unittest.Testcase method over and over again with slightly different input values.
Keep in mind why we write unit tests:
Pytest provides various ways of creating individual test items. There are parametrized fixtures and mark.parametrize (and hooks).
Using this built-in marker @pytest.mark.parametrize you do not need to implement any fixtures. Instead you define your scenarios in a decorator and the only thing you really need to look out for is to match the number of positional test arguments with your iterable.
To parametrize a fixture you need pass an iterable to the params keyword argument. The built-in fixture request knows about the current parameter and if you don't want to do anything fancy, you can pass it right to the test via the returnstatement.
Sometimes you may find yourself struggling to chose which is the best way to parametrize your tests. At the end of the day it really depends on what you want to test. But... Good news! Pytest lets you combine both methods to get the most out of both worlds.
Some Classes in a Module
Imagine this Python module (foobar.py) which contains a few class definitions with a bit of logic:
With only two few lines of pytest code, we can create loads of different scenarios that we would like to test. By re-using parametrized fixtures and applying the aforementioned markers to your tests, you can focus on the actual test implementation, as opposed to writing the same boilerplate code for each of the methods that you would have to write with unittest.Testcase.
Going the extra mile and setting up ids for your test scenarios greatly increases the comprehensibilty of your test report. In this case we would like to display the name of each Package rather than the fixture name with a numbered suffix such as python_package2.