Test addition function with conditional parameters
Preconditions (2)
✅ Expected Result: Tests run only for the parameters that meet the condition, others are skipped or not run
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.
Add data-driven testing with 3 different input sets and a condition to run only even sums
pytest.param with skipif inside @pytest.mark.parametrize?pytest.param with skipifpytest.mark.parametrize?import sys
import pytest
@pytest.mark.parametrize('num', [
pytest.param(1, marks=pytest.mark.skipif(sys.version_info < (3,8), reason='Skip on old Python')),
2,
3
])
def test_numbers(num):
assert num > 0
import pytest
@pytest.mark.parametrize('val', [
pytest.param(10, marks=pytest.mark.skipif('sys.version_info < (3,8)', reason='Old Python')),
20
])
def test_val(val):
assert val > 0
mode set to 'fast', 'slow', and 'medium'. However, you want to skip the 'slow' mode test only if an environment variable SKIP_SLOW is set to '1'. Which is the correct way to write this conditional parametrize in pytest?Pass the test and this pattern moves unknown