0
0
PyTesttesting~3 mins

Why @pytest.mark.parametrize decorator? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could run dozens of tests with just one simple function?

The Scenario

Imagine you have a function that needs to be tested with many different inputs and expected results. You write separate test functions for each case, copying and changing code repeatedly.

The Problem

This manual way is slow and boring. You might forget to update some tests or make mistakes copying code. Running many tests means a lot of repeated work and hard-to-read code.

The Solution

The @pytest.mark.parametrize decorator lets you write one test function and run it multiple times with different inputs automatically. It keeps your code clean and saves time.

Before vs After
Before
def test_add_1():
    assert add(1, 2) == 3

def test_add_2():
    assert add(3, 4) == 7
After
import pytest

@pytest.mark.parametrize('a,b,expected', [(1,2,3), (3,4,7)])
def test_add(a, b, expected):
    assert add(a, b) == expected
What It Enables

You can easily test many input cases with less code and fewer mistakes, making your tests faster and clearer.

Real Life Example

Testing a calculator app with many operations and numbers becomes simple and organized using @pytest.mark.parametrize.

Key Takeaways

Manual tests for many inputs are slow and error-prone.

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

This saves time, reduces mistakes, and keeps tests clean.