0
0
PyTesttesting~5 mins

Parametrize with IDs in PyTest

Choose your learning style9 modes available
Introduction

Parametrizing tests lets you run the same test with different data easily. Adding IDs helps you see which data set caused a test to pass or fail.

You want to test a function with many input values without writing many test functions.
You want clear names for each test case in the test report.
You want to quickly identify which input caused a test failure.
You want to organize your tests better when using multiple data sets.
Syntax
PyTest
@pytest.mark.parametrize("param", [value1, value2], ids=["id1", "id2"])
def test_func(param):
    assert something

The ids list must have the same length as the data list.

IDs are shown in test reports and help identify test cases.

Examples
This runs the test three times with numbers 1, 2, and 3. The test report shows 'one', 'two', and 'three' as test IDs.
PyTest
@pytest.mark.parametrize("num", [1, 2, 3], ids=["one", "two", "three"])
def test_is_positive(num):
    assert num > 0
Here, IDs are created dynamically using a function. The test IDs will be 'animal_cat' and 'animal_dog'.
PyTest
@pytest.mark.parametrize("word", ["cat", "dog"], ids=lambda x: f"animal_{x}")
def test_length(word):
    assert len(word) == 3
Sample Program

This test runs three times with different numbers. The IDs help us know which case failed if any.

PyTest
import pytest

@pytest.mark.parametrize("number", [10, 0, -5], ids=["positive", "zero", "negative"])
def test_is_positive(number):
    assert number > 0
OutputSuccess
Important Notes

Always provide IDs when you have many test cases to make reports clearer.

IDs can be strings or functions that return strings.

If you skip IDs, pytest uses default numeric indexes which are less readable.

Summary

Parametrize runs one test with many inputs.

IDs label each test case for easy identification.

Use IDs to quickly find which input caused a failure.