Phase 19 of 25 · Topic 19.3

Parametrized Tests with @pytest.mark.parametrize

1Concept

`@pytest.mark.parametrize` runs a single test function across multiple datasets, generating independent test cases for each data tuple.

2Architecture Diagram

@pytest.mark.parametrize("input, expected", [(1, 2), (2, 4), (3, 6)])
def test_double(input, expected): assert double(input) == expected

3Code Example

Python 3.12
# Demonstrating parameterized testing pattern
test_cases = [
    (10, 20, 30),
    (0, 5, 5),
    (-5, 5, 0),
]

for a, b, expected in test_cases:
    assert a + b == expected
    print(f"Verified: {a} + {b} == {expected}")

4Expected Output

Verified: 10 + 20 == 30
Verified: 0 + 5 == 5
Verified: -5 + 5 == 0

5Key Takeaways

  • Parametrization eliminates duplicate test code for boundary condition testing.
  • PyTest reports each parameter set as a separate test in test summaries.
  • Can combine multiple `@pytest.mark.parametrize` decorators to compute Cartesian products.