0
0
PytestHow-ToBeginner ยท 3 min read

How to Parametrize with Multiple Arguments in pytest

Use @pytest.mark.parametrize with a tuple of argument names and a list of tuples containing argument values. This runs the test function multiple times with different combinations of arguments.
๐Ÿ“

Syntax

The @pytest.mark.parametrize decorator takes two main parts: a string of comma-separated argument names, and a list of tuples with values for those arguments. Each tuple in the list represents one test case with values matching the argument names.

python
@pytest.mark.parametrize("arg1, arg2", [(val1, val2), (val3, val4)])
def test_example(arg1, arg2):
    assert arg1 != arg2
๐Ÿ’ป

Example

This example shows a test function that checks if the sum of two numbers equals the expected result. It uses multiple arguments a, b, and expected to run several test cases.

python
import pytest

@pytest.mark.parametrize("a, b, expected", [
    (1, 2, 3),
    (5, 5, 10),
    (10, 0, 10),
    (-1, 1, 0)
])
def test_addition(a, b, expected):
    assert a + b == expected
Output
==== test session starts ==== collected 4 items test_sample.py .... [100%] ==== 4 passed in 0.03s ====
โš ๏ธ

Common Pitfalls

Common mistakes include mismatching the number of argument names and values, or using a single tuple instead of a list of tuples. Also, forgetting to separate argument names by commas in the string causes errors.

Wrong example: Using a single tuple instead of a list of tuples.

python
import pytest

# Wrong: single tuple instead of list of tuples
@pytest.mark.parametrize("x, y", [(1, 2)])
def test_wrong(x, y):
    assert x != y

# Right: list of tuples
@pytest.mark.parametrize("x, y", [(1, 2), (3, 4)])
def test_right(x, y):
    assert x != y
๐Ÿ“Š

Quick Reference

  • Argument names: Comma-separated string, e.g., "x, y"
  • Values: List of tuples, each tuple matches argument order
  • Test runs: One run per tuple of values
  • Use cases: Test multiple input combinations easily
โœ…

Key Takeaways

Use @pytest.mark.parametrize with a string of argument names and a list of tuples for values.
Each tuple in the list runs the test once with those argument values.
Ensure the number of argument names matches the number of values in each tuple.
Separate argument names with commas inside the string.
Always provide a list of tuples, not a single tuple, for multiple test cases.