Parameterized Testing - Running Tests with Multiple Data Sets
Why parameterize?
Instead of repeating similar tests, parameterize inputs.
Example
test_parametrize.py
import pytest
def add(a, b):
return a + b
@pytest.mark.parametrize(
"a,b,expected",
[
(1, 2, 3),
(0, 0, 0),
(-1, 1, 0),
],
)
def test_add(a, b, expected):
assert add(a, b) == expectedtest_parametrize.py
import pytest
def add(a, b):
return a + b
@pytest.mark.parametrize(
"a,b,expected",
[
(1, 2, 3),
(0, 0, 0),
(-1, 1, 0),
],
)
def test_add(a, b, expected):
assert add(a, b) == expectedParametrize with ids
test_parametrize_ids.py
import pytest
@pytest.mark.parametrize(
"s,expected",
[("10", 10), ("0", 0)],
ids=["ten", "zero"],
)
def test_int_parse(s, expected):
assert int(s) == expectedtest_parametrize_ids.py
import pytest
@pytest.mark.parametrize(
"s,expected",
[("10", 10), ("0", 0)],
ids=["ten", "zero"],
)
def test_int_parse(s, expected):
assert int(s) == expected๐งช Try It Yourself
Exercise 1 โ Write a unittest TestCase
Exercise 2 โ assertRaises
Exercise 3 โ setUp and tearDown
If this helped you, consider buying me a coffee โ
Buy me a coffeeWas this page helpful?
Let us know how we did
