0
0
PyTesttesting~15 mins

Parametrize with IDs in PyTest - Build an Automation Script

Choose your learning style9 modes available
Test addition function with multiple inputs using pytest parametrize with IDs
Preconditions (2)
Step 1: Create a test function that adds two numbers
Step 2: Use pytest.mark.parametrize to run the test with multiple input pairs
Step 3: Assign custom IDs to each input set for better test report readability
Step 4: Run the tests using pytest
Step 5: Observe that each test case is identified by its custom ID in the test report
✅ Expected Result: All test cases pass and the test report shows each test case with its custom ID
Automation Requirements - pytest
Assertions Needed:
Assert that the sum of two numbers equals the expected result
Best Practices:
Use @pytest.mark.parametrize decorator with ids parameter for clarity
Keep test function simple and focused
Use descriptive IDs for each test case
Write clear assertion messages
Automated Solution
PyTest
import pytest

@pytest.mark.parametrize(
    "a, b, expected",
    [
        (1, 2, 3),
        (5, 5, 10),
        (10, 0, 10)
    ],
    ids=["one_plus_two", "five_plus_five", "ten_plus_zero"]
)
def test_addition(a, b, expected):
    result = a + b
    assert result == expected, f"Expected {a} + {b} to be {expected}, but got {result}"

This test uses pytest.mark.parametrize to run the test_addition function three times with different inputs.

The ids parameter assigns friendly names to each test case. This helps when reading test reports because you see names like one_plus_two instead of just numbers.

The assertion checks if the sum is correct and gives a clear message if it fails.

This approach keeps tests simple, readable, and easy to maintain.

Common Mistakes - 3 Pitfalls
Not using the ids parameter in parametrize
Using complex logic inside the test function
Hardcoding expected results inside the test function instead of parametrize
Bonus Challenge

Now add data-driven testing with 3 different inputs including negative numbers and zero, each with descriptive IDs

Show Hint