8

I have a question and hope, that anyone can help me. I am using pytest and set up some test functions at the moment. Here is an example:

def square(number):
    return(number ** 2)

with pytest I am able to set up different testing functions like

def test_square_2():
    assert(square(2) == 4)
def test_square_3():
    assert(square(3) == 9)

Now my Question: Is there a way to set up a list of lists like

test_list = [[1,1],[2,4],[3,9],[4,16],[5,25]]

and set up a loop to test all the tuples in the list?

Best F

1
  • You can use @pytest.mark.parametrize. For information, see the official docs. There is also a similar question that might help in case the documentation is not clear. Commented May 8, 2020 at 12:59

2 Answers 2

19

As mentioned by other posters, the parametrize library in pytest is your friend here. One of the advantages of using parametrize instead of writing your own loop is that all of the tests will run, even if one of them fails. If you write your own loop and use pytest, the test script will stop at the first failure without running any of the subsequent tests.

squares.py contains the code that you want to test:

def square(number):
    return(number ** 2)

test_squares.py contains the testing code in the same directory:

import pytest
from squares import *

@pytest.mark.parametrize("test_input, expected", [(1,1), (2,4), (3,9), (4,16)])
def test_squares(test_input, expected):
  assert square(test_input) == expected

At the command line enter:

python -m pytest test_squares.py

output:

============================= test session starts =============================
platform win32 -- Python 3.7.0, pytest-5.4.2, py-1.8.1, pluggy-0.13.1
rootdir: D:\matopp\stackoverflow\parametrize
collected 4 items

test_squares.py ....                                                     [100%]

============================== 4 passed in 0.12s ==============================
Sign up to request clarification or add additional context in comments.

Comments

2

there's a library for that (i know, shocking) called parameterized that does exactly that with a cool decorator

3 Comments

even if your answer sounds cynical, thank you very much :-)
no no, i was not trying to be cynical, the jest was directed at the python ecosysstem rather than your question. i actually found out about it when i too became annoyed at writing 6 test functions to test one thing
ahhh, okay :-).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.