Conditional parametrize helps run tests with different inputs only when certain conditions are met. It saves time by skipping unnecessary test cases.
0
0
Conditional parametrize in PyTest
Introduction
You want to test a function with multiple inputs but only for specific environments.
You need to run some test cases only if a feature flag is enabled.
You want to skip tests for certain input values based on a condition.
You want to run tests differently depending on the Python version or OS.
Syntax
PyTest
import pytest @pytest.mark.parametrize('input,expected', [ (1, 2), pytest.param(3, 4, marks=pytest.mark.skipif(condition, reason='skip reason')) ]) def test_func(input, expected): assert input + 1 == expected
Use pytest.param to add marks like skipif conditionally.
The condition is a Python expression that returns True or False.
Examples
This example always skips the second test case because the condition is True.
PyTest
import pytest @pytest.mark.parametrize('x,y', [ (1, 2), pytest.param(3, 4, marks=pytest.mark.skipif(True, reason='Always skip')) ]) def test_add(x, y): assert x + 1 == y
This example runs the second test case only on Linux systems.
PyTest
import sys import pytest @pytest.mark.parametrize('x,y', [ (1, 2), pytest.param(3, 4, marks=pytest.mark.skipif(sys.platform != 'linux', reason='Only run on Linux')) ]) def test_add(x, y): assert x + 1 == y
Sample Program
This test runs two cases. The second case runs only if Python version is 3.8 or higher. Otherwise, it is skipped.
PyTest
import sys import pytest @pytest.mark.parametrize('num,expected', [ (1, 2), pytest.param(3, 4, marks=pytest.mark.skipif(sys.version_info < (3, 8), reason='Requires Python 3.8+')) ]) def test_increment(num, expected): assert num + 1 == expected if __name__ == '__main__': pytest.main(['-v', __file__])
OutputSuccess
Important Notes
Use pytest.param to add conditions to individual test cases inside parametrize.
Conditions can check environment, Python version, OS, or any runtime info.
Skipping tests helps keep test runs fast and relevant.
Summary
Conditional parametrize lets you run or skip test cases based on conditions.
Use pytest.param with skipif mark inside parametrize.
This helps test only what matters in your current environment.