Parameterized Testing - Running Tests with Multiple Data Sets
flowchart LR
A["@pytest.mark.parametrize('a,b,want', [(1,1,2), (2,3,5), (0,0,0)])"] --> B["one function"]
B --> C["test_add[1-1-2]"]
B --> D["test_add[2-3-5]"]
B --> E["test_add[0-0-0]"]
F["a loop inside one test"] --> G["first failure stops the rest"]
G --> H["one result for all cases"]
C --> I["3 independent results"]
D --> I
E --> I
Why parameterize?
Section titled “Why parameterize?”Instead of repeating similar tests, parameterize inputs.
Example
Section titled “Example”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
Section titled “Parametrize with ids”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
Section titled “🧪 Try It Yourself”Exercise 1 – Write a unittest TestCase
Section titled “Exercise 1 – Write a unittest TestCase”Exercise 2 – assertRaises
Section titled “Exercise 2 – assertRaises”Exercise 3 – setUp and tearDown
Section titled “Exercise 3 – setUp and tearDown”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading