Implementing Data-Driven Testing with Pytest's Parametrize Decorator

The @pytest.mark.parametrize decorator accepts a string of parameter names and a list of data sets to execute a test function multiple times with different inputs.

The first argument is a comma-separated string of parameter names. The second argument is a list, where each element is a tuple providing values for those parameters.

For a single parameter: @pytest.mark.parametrize('param_name', list). For two parameterss: @pytest.mark.parametrize('param1, param2', [(value1_a, value2_a), (value1_b, value2_b)]).

Single Parameter with Mutliple Values

import pytest

@pytest.mark.parametrize("input_value", [0, 1])
def test_single_param(input_value):
    assert input_value == 1

if __name__ == "__main__":
    pytest.main(["-s", "-v", "test_file.py"])

Multiple Parameters with Multiple Data Sets

import pytest
import time
from selenium import webdriver

@pytest.mark.ui_test
class TestSearch:
    def setup_method(self):
        self.driver = webdriver.Chrome()
        self.base_url = "https://example.com"

    @pytest.mark.parametrize('search_term, expected_result', [
        ('pytest', 'pytest'),
        ('selenium', 'pytest')
    ])
    def test_web_search(self, search_term, expected_result):
        driver = self.driver
        driver.get(self.base_url)
        driver.find_element_by_id("search_box").send_keys(search_term)
        driver.find_element_by_id("search_button").click()
        time.sleep(2)
        result_text = driver.find_element_by_css_selector(".result").text
        assert (expected_result in result_text) is True

    def teardown_method(self):
        self.driver.quit()

if __name__ == "__main__":
    pytest.main(["-m", "ui_test", "-s", "-v", "test_web.py"])

Combining Multiple Parametrize Decorators

Applying multiple @pytest.mark.parametrize decorators creates a Cartesian product of all provided data sets.

import pytest

first_data = [10, 20]
second_data = ["alpha", "beta"]
third_data = ["x", "y", "z"]

@pytest.mark.parametrize("num", first_data)
@pytest.mark.parametrize("text", second_data)
@pytest.mark.parametrize("char", third_data)
def test_combined_parameters(num, text, char):
    print(f"Generated test combination: [{num}, {text}, {char}]")

if __name__ == "__main__":
    pytest.main(["-s", "-v", "test_combinations.py"])

Tags: pytest python testing parametrization data-driven

Posted on Thu, 07 May 2026 21:02:34 +0000 by bulrush