Course contentsShow
← Python
Lesson 754 of 1,06012. Testing and DebuggingFree lesson

Scaling Test Coverage through Function Parametrization

Run the same test logic against multiple input datasets using decorators to efficiently verify edge cases and boundary conditions.

In this lesson, you will learn how to use pytest parametrization to run the same test logic against multiple input datasets, allowing you to scale your test coverage without writing repetitive code.

The Problem: Repetitive Testing

When testing a function, you often need to verify several scenarios: typical values, empty inputs, negative numbers, and boundary conditions. A naive approach is to write a separate test function for every single case:

def test_add_numbers_positive():
    assert add(1, 2) == 3

def test_add_numbers_negative():
    assert add(-1, -1) == -2

def test_add_numbers_zero():
    assert add(0, 0) == 0

This becomes difficult to maintain as your project grows. If you change the function signature, you have to update every individual test function.

The Solution: @pytest.mark.parametrize

Parametrization allows you to define a list of inputs and expected outputs, which pytest then uses to generate individual test instances automatically. You decorate your test function with the arguments you want to pass, and the decorator injects them into your function for each iteration.

Here is how you would refactor the tests above:

import pytest

@pytest.mark.parametrize("a, b, expected", [
    (1, 2, 3),    # Normal case
    (-1, -1, -2), # Negative case
    (0, 0, 0),    # Boundary case
    (100, -50, 50)
])
def test_add(a, b, expected):
    assert add(a, b) == expected

Why This Scales

  1. Efficiency: You write the assertion logic exactly once. If you discover a bug, you fix it in one place.
  2. Readability: You separate the test data (the "what") from the test logic (the "how"). This makes it easy to add new test cases—you simply add a new tuple to the list.
  3. Granularity: pytest treats each tuple as a unique test. If the second case fails, the other three will still run and report their status, giving you precise feedback on which inputs are failing.

By decoupling your test data from the execution logic, you can easily verify complex boundary conditions and edge cases with minimal overhead.

Key Takeaway: Function parametrization allows you to multiply your test coverage by feeding diverse datasets into a single, clean test function using the @pytest.mark.parametrize decorator.