0
0
PyTesttesting~5 mins

Why parametrize multiplies test coverage in PyTest

Choose your learning style9 modes available
Introduction

Parametrizing tests lets you run the same test with many inputs. This helps find more problems quickly without writing many tests.

You want to check a function with different input values.
You need to test multiple user roles with the same test steps.
You want to verify a feature works on various browsers or devices.
You want to test edge cases and normal cases together easily.
You want to avoid repeating similar test code for different data.
Syntax
PyTest
@pytest.mark.parametrize("input,expected", [(value1, result1), (value2, result2), ...])
def test_function(input, expected):
    assert function_to_test(input) == expected
Use a list of tuples to provide multiple sets of inputs and expected results.
The test runs once for each tuple, increasing coverage without extra code.
Examples
This test checks if adding 1 to numbers 1, 3, and 5 gives 2, 4, and 6 respectively.
PyTest
@pytest.mark.parametrize("num,expected", [(1, 2), (3, 4), (5, 6)])
def test_increment(num, expected):
    assert num + 1 == expected
This test verifies string lengths for different inputs.
PyTest
@pytest.mark.parametrize("text,expected_len", [("hello", 5), ("", 0), ("pytest", 6)])
def test_length(text, expected_len):
    assert len(text) == expected_len
Sample Program

This test runs four times with different pairs of numbers to check if their sum matches the expected value.

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

Parametrization helps catch bugs that only appear with certain inputs.

It keeps tests clean and avoids repeating similar code.

Use descriptive names for parameters to make tests easy to read.

Summary

Parametrizing runs one test many times with different data.

This increases test coverage without extra test functions.

It helps find more bugs and keeps tests simple.