0
0
PyTesttesting~15 mins

@pytest.mark.parametrize decorator - Build an Automation Script

Choose your learning style9 modes available
Test addition function with multiple inputs using @pytest.mark.parametrize
Preconditions (3)
Step 1: Create a test function named test_add that takes two inputs and an expected output
Step 2: Use @pytest.mark.parametrize to provide three sets of inputs and expected outputs: (1, 2, 3), (5, 5, 10), (0, 0, 0)
Step 3: Inside the test function, call the addition function with the two inputs
Step 4: Assert that the result equals the expected output
✅ Expected Result: The test runs three times with different inputs and all assertions pass
Automation Requirements - pytest
Assertions Needed:
Assert the addition function output equals the expected result for each input set
Best Practices:
Use @pytest.mark.parametrize to avoid repeating test code
Name test function clearly
Keep test data simple and readable
Automated Solution
PyTest
import pytest

def add(a: int, b: int) -> int:
    return a + b

@pytest.mark.parametrize("a,b,expected", [
    (1, 2, 3),
    (5, 5, 10),
    (0, 0, 0)
])
def test_add(a, b, expected):
    result = add(a, b)
    assert result == expected, f"Expected {expected} but got {result}"

This code defines a simple addition function add.

The @pytest.mark.parametrize decorator runs the test_add function three times with different inputs and expected outputs.

Inside the test, it calls add with the inputs and checks if the result matches the expected value.

This way, we test multiple cases without writing separate test functions.

Common Mistakes - 3 Pitfalls
Not using @pytest.mark.parametrize and writing separate test functions for each input
Incorrect parameter names in the decorator string and function signature mismatch
Using complex or unclear test data inside parametrize
Bonus Challenge

Now add data-driven testing with 3 different inputs including negative numbers and zero

Show Hint