0
0
PyTesttesting~15 mins

Conditional parametrize in PyTest - Build an Automation Script

Choose your learning style9 modes available
Test addition function with conditional parameters
Preconditions (2)
Step 1: Create a test function that adds two numbers
Step 2: Use pytest parametrize to test multiple input pairs
Step 3: Add a condition to skip some parameters based on a flag
Step 4: Run the tests
Step 5: Verify that only the parameters meeting the condition are tested
✅ Expected Result: Tests run only for the parameters that meet the condition, others are skipped or not run
Automation Requirements - pytest
Assertions Needed:
Verify the addition result is correct for each parameter set
Verify tests are skipped or not run for parameters failing the condition
Best Practices:
Use @pytest.mark.parametrize with a conditional filter
Use clear test names for each parameter set
Avoid hardcoding test data inside the test function
Use pytest skip markers or conditional logic inside parametrize
Automated Solution
PyTest
import pytest

# Flag to control which parameters to test
run_extended_tests = False

# Define test data with a condition
params = [
    (1, 2, 3, True),    # (a, b, expected, run_test)
    (3, 5, 8, True),
    (10, 20, 30, False),
    (0, 0, 0, True)
]

# Filter parameters based on the flag
filtered_params = [ (a, b, expected) for a, b, expected, run_test in params if run_test or run_extended_tests ]

@pytest.mark.parametrize("a,b,expected", filtered_params)
def test_addition(a, b, expected):
    assert a + b == expected

This test script uses pytest.mark.parametrize to run the test_addition function with multiple sets of inputs.

The params list includes a boolean flag run_test to indicate if the test case should run by default.

The filtered_params list comprehension filters the parameters based on the run_extended_tests flag. If run_extended_tests is False, only parameters with run_test=True are included.

This way, you can control which test cases run conditionally without changing the test code.

The assertion checks that the sum of a and b equals the expected result.

Common Mistakes - 3 Pitfalls
Hardcoding all parameters without condition
Using if statements inside the test function to skip tests
Not providing descriptive test ids for parameters
Bonus Challenge

Add data-driven testing with 3 different input sets and a condition to run only even sums

Show Hint