porthunt
porthunt

Reputation: 504

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?

Upvotes: 11

Views: 11058

Answers (1)

Ignacio Vergara Kausel
Ignacio Vergara Kausel

Reputation: 6026

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)

Upvotes: 25

Related Questions