0
0
PyTesttesting~5 mins

@pytest.mark.parametrize decorator

Choose your learning style9 modes available
Introduction

The @pytest.mark.parametrize decorator helps run the same test with different inputs easily. It saves time and avoids repeating code.

When you want to test a function with many input values.
When you want to check different expected results for the same test logic.
When you want to run multiple cases quickly without writing separate test functions.
When you want to find bugs that happen only with certain inputs.
When you want clear test reports showing which inputs passed or failed.
Syntax
PyTest
@pytest.mark.parametrize("input_name, expected_output", [
    (input1, expected1),
    (input2, expected2),
    ...
])
def test_function(input_name, expected_output):
    # test code here

Use a string with comma-separated parameter names as the first argument.

Use a list of tuples for different input and expected output pairs.

Examples
This runs test_add_one three times with different numbers and expected results.
PyTest
@pytest.mark.parametrize("number, expected", [(1, 2), (3, 4), (5, 6)])
def test_add_one(number, expected):
    assert number + 1 == expected
This tests that the length of each string is greater than zero.
PyTest
@pytest.mark.parametrize("text", ["hello", "world", "pytest"])
def test_length(text):
    assert len(text) > 0
Sample Program

This test checks if adding two numbers gives the expected result. It runs four times with different inputs.

PyTest
import pytest

@pytest.mark.parametrize("a, b, expected", [
    (2, 3, 5),
    (0, 0, 0),
    (-1, 1, 0),
    (100, 200, 300)
])
def test_addition(a, b, expected):
    assert a + b == expected
OutputSuccess
Important Notes

Each tuple in the list must match the order of parameter names.

Use descriptive parameter names to make tests clear.

Test reports show each input set separately for easy debugging.

Summary

@pytest.mark.parametrize runs one test with many inputs.

It helps find bugs by testing different cases quickly.

It keeps test code clean and easy to read.