Labs ICT
โญ Pro Login

Parameterizing Tests

Running the same test with different inputs using @pytest.mark.parametrize.

Parameterizing Tests

@pytest.mark.parametrize lets you run the same test function with different inputs. This eliminates repetitive test code and makes your tests more thorough.

Basic Usage

import pytest

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

# pytest runs this test 4 times with different values

Single Parameter

When parameterizing a single value, you can use a simple list:

@pytest.mark.parametrize("number", [1, 2, 3, 4, 5])
def test_is_positive(number):
    assert number > 0

Multiple Parameters

Pass multiple arguments by providing tuples:

@pytest.mark.parametrize("a,b,expected", [
    (1, 1, 2),
    (2, 3, 5),
    (-1, 1, 0),
    (0, 0, 0),
])
def test_add(a, b, expected):
    assert a + b == expected

Named Test IDs

Use the ids parameter to give each test case a readable name:

@pytest.mark.parametrize(
    "input,expected",
    [
        (1, 2),
        (2, 4),
        (3, 6),
    ],
    ids=["one", "two", "three"]
)
def test_double(input, expected):
    assert input * 2 == expected

# Output: test_double[one], test_double[two], test_double[three]

Stacking Parametrize

You can stack multiple parametrize decorators to create combinations:

@pytest.mark.parametrize("x", [1, 2])
@pytest.mark.parametrize("y", [10, 20])
def test_multiply(x, y):
    result = x * y
    assert result > 0

# Runs 4 tests: (1,10), (1,20), (2,10), (2,20)

๐Ÿงช Quick Quiz

How do you run the same test with multiple input sets?