I have a "conceptual" question regarding pytest and how I should handle multiple tests.
Let's say I need to test something for a bunch of strings: names = [" ", "a ", " a", " a "]
.
I could create multiple test_
functions to test them individually, but they would be exactly the same, but with different input.
I was thinking on doing something like:
def test_names():
names = [" ", "a ", " a", " a "]
for name in names:
with pytest.raises(errors.MyFooError) as ex:
random_method(name)
The problem is: doing this, in case one element doesn't raise errors.MyFooError
, I would receive this:
Failed: DID NOT RAISE <class 'errors.MyFooError'
The message is generic, I have no idea in which element this occurred.
I would probably just split into 4 tests, one for each element of the list, I guess this is the correct way to do it? What happens if the list is huge?
Run Multiple Tests From a Specific File and Multiple Files To run all the tests from all the files in the folder and subfolders we need to just run the pytest command. This will run all the filenames starting with test_ and the filenames ending with _test in that folder and subfolders under that folder.
It is possible to apply a fixture to all of the tests in a hierarchy, even if the tests don't explicitly request a fixture, by passing autouse=True to the @pytest. fixture decorator. This is useful when we need to apply a side-effect before and/or after each test unconditionally.
You should use the parametrize
capabilities of pytest
as shown here.
Your code would look as
import pytest
@pytest.mark.parametrize('input', [" ", "a ", " a", " a "])
def test_names(input):
with pytest.raises(errors.MyFooError) as ex:
random_method(input)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With