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