Parameterized tests help you run the same test with different data easily. This saves time and avoids repeating code.
0
0
Parameterized tests in Selenium Python
Introduction
When you want to check a login form with multiple usernames and passwords.
When you need to test a search feature with different keywords.
When you want to verify a calculator app with many input values.
When you want to test form validation with various input combinations.
Syntax
Selenium Python
from pytest import mark @mark.parametrize("input,expected", [ (value1, expected1), (value2, expected2), # ... add more test cases ]) def test_function(input, expected): # test steps using input assert actual_result == expected
Use @mark.parametrize decorator from pytest to pass multiple data sets.
Each tuple in the list represents one test case with inputs and expected results.
Examples
This test checks if the square of a number matches the expected value.
Selenium Python
from pytest import mark @mark.parametrize("number,expected", [ (2, 4), (3, 9), (4, 16) ]) def test_square(number, expected): assert number * number == expected
This test tries to log in with different usernames and passwords using Selenium WebDriver.
Selenium Python
from pytest import mark from selenium.webdriver.common.by import By @mark.parametrize("username,password", [ ("user1", "pass1"), ("user2", "pass2") ]) def test_login(username, password, driver): driver.get("https://example.com/login") driver.find_element(By.ID, "username").send_keys(username) driver.find_element(By.ID, "password").send_keys(password) driver.find_element(By.ID, "submit").click() assert "Welcome" in driver.page_source
Sample Program
This test opens a website and searches for different fruits. It checks if the search term appears in the page title after searching.
Selenium Python
from selenium import webdriver from selenium.webdriver.common.by import By from pytest import mark @mark.parametrize("search_term", ["apple", "banana", "cherry"]) def test_search_function(search_term): driver = webdriver.Chrome() driver.get("https://www.example.com") search_box = driver.find_element(By.NAME, "q") search_box.clear() search_box.send_keys(search_term) search_box.submit() assert search_term in driver.title.lower() driver.quit()
OutputSuccess
Important Notes
Always close the browser after each test to avoid resource leaks.
Use clear and meaningful parameter names for readability.
Parameterized tests help find bugs with different inputs quickly.
Summary
Parameterized tests run the same test with many data sets.
They reduce repeated code and save time.
Use pytest's @mark.parametrize decorator for easy implementation.