Pet
Pet

Reputation: 251

looping over tests in python using pytest

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

Upvotes: 7

Views: 17612

Answers (2)

Oppy
Oppy

Reputation: 2887

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 ==============================

Upvotes: 17

vencaslac
vencaslac

Reputation: 2854

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

Upvotes: 2

Related Questions