0
0
PyTesttesting~15 mins

Combining multiple parametrize decorators in PyTest - Build an Automation Script

Choose your learning style9 modes available
Test addition function with multiple input sets using combined parametrize decorators
Preconditions (2)
Step 1: Use @pytest.mark.parametrize to provide first set of inputs for parameter 'a' with values 1 and 2
Step 2: Use another @pytest.mark.parametrize to provide second set of inputs for parameter 'b' with values 3 and 4
Step 3: Write a test function that takes parameters 'a' and 'b'
Step 4: Inside the test function, assert that the sum of 'a' and 'b' equals the expected result
Step 5: Run the test and observe that all combinations of 'a' and 'b' are tested
✅ Expected Result: The test runs 4 times with combinations (1,3), (1,4), (2,3), (2,4) and all assertions pass
Automation Requirements - pytest
Assertions Needed:
Assert that a + b equals expected sum
Best Practices:
Use multiple @pytest.mark.parametrize decorators to combine parameters
Name parameters clearly
Keep test function simple and focused
Use descriptive test function names
Automated Solution
PyTest
import pytest

@pytest.mark.parametrize('a', [1, 2])
@pytest.mark.parametrize('b', [3, 4])
def test_addition(a, b):
    expected = a + b
    assert a + b == expected

This test uses two @pytest.mark.parametrize decorators to provide values for parameters a and b. Pytest combines these to run the test for all pairs: (1,3), (1,4), (2,3), and (2,4).

The test function test_addition takes both parameters and asserts their sum equals the expected value. This confirms the addition logic works for all input combinations.

Using multiple parametrize decorators is a clean way to test combinations without writing nested loops.

Common Mistakes - 3 Pitfalls
{'mistake': 'Using a single parametrize with tuples but forgetting to unpack parameters', 'why_bad': "The test function parameters won't match the tuple structure, causing errors or incorrect tests", 'correct_approach': 'Use multiple parametrize decorators or unpack tuples properly in a single parametrize'}
Hardcoding expected results inside the test without calculating or verifying
Naming parameters inconsistently between decorators and test function
Bonus Challenge

Now add a third parametrize decorator for parameter 'c' with values 5 and 6 and update the test to assert a + b + c

Show Hint