Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple tests in one pytest function

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?

like image 982
porthunt Avatar asked Jan 22 '18 14:01

porthunt


People also ask

How do I run multiple tests in pytest?

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.

What is Autouse in pytest?

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.


1 Answers

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)
like image 57
Ignacio Vergara Kausel Avatar answered Nov 10 '22 23:11

Ignacio Vergara Kausel