0
0
PyTesttesting~5 mins

Multiple parameters in PyTest

Choose your learning style9 modes available
Introduction

Using multiple parameters lets you test many input combinations easily. It saves time and finds more bugs.

You want to check a function with different pairs of inputs.
You need to test how two or more values work together.
You want to avoid writing many similar test functions.
You want clear test reports showing each input combination.
You want to catch errors that happen only with certain input pairs.
Syntax
PyTest
@pytest.mark.parametrize(("param1", "param2"), [(val1, val2), (val3, val4)])
def test_func(param1, param2):
    # test code here

List parameter names as a tuple or string with comma.

Provide a list of tuples with values for each test run.

Examples
Tests sum of pairs (1,2) and (3,4) to be positive.
PyTest
@pytest.mark.parametrize(("a", "b"), [(1, 2), (3, 4)])
def test_sum(a, b):
    assert a + b > 0
Tests difference for three pairs with string parameter names.
PyTest
@pytest.mark.parametrize("x,y", [(0, 0), (5, 10), (-1, 1)])
def test_diff(x, y):
    assert x - y <= 5
Sample Program

This test checks division with multiple pairs. It expects an error when dividing by zero and correct division otherwise.

PyTest
import pytest

@pytest.mark.parametrize(("num", "divisor"), [(10, 2), (15, 3), (9, 0)])
def test_division(num, divisor):
    if divisor == 0:
        with pytest.raises(ZeroDivisionError):
            result = num / divisor
    else:
        result = num / divisor
        assert result * divisor == num
OutputSuccess
Important Notes

Use descriptive parameter names for clarity.

Each tuple in the list must match the number of parameters.

pytest shows each parameter set as a separate test in reports.

Summary

Multiple parameters let you test many input combinations easily.

Use @pytest.mark.parametrize with tuples of parameter names and value lists.

This helps find bugs and keeps tests simple and clear.