0
0
Selenium Pythontesting~7 mins

Parameterize with test data in Selenium Python

Choose your learning style9 modes available
Introduction

Parameterizing tests means running the same test with different data. This helps check many cases without writing many tests.

When you want to test a login form with multiple usernames and passwords.
When you need to check a search feature with different keywords.
When you want to verify form validation with various input values.
When testing a calculator app with many number pairs.
When you want to run the same test on different browsers or devices.
Syntax
Selenium Python
from pytest import mark

@mark.parametrize("input,expected", [
    ("data1", "result1"),
    ("data2", "result2"),
])
def test_example(input, expected):
    assert function_to_test(input) == expected

Use @pytest.mark.parametrize decorator to pass multiple sets of data.

Each tuple in the list represents one test run with its inputs and expected output.

Examples
Test login with two sets of username and password.
Selenium Python
from pytest import mark

@mark.parametrize("username,password", [
    ("user1", "pass1"),
    ("user2", "pass2"),
])
def test_login(username, password):
    assert login(username, password) == True
Test search function with three different keywords.
Selenium Python
from pytest import mark

@mark.parametrize("search_term", ["apple", "banana", "cherry"])
def test_search(search_term):
    assert search(search_term) != []
Sample Program

This test opens a login page, enters username and password from the parameterized data, clicks submit, and checks the success message.

It runs twice with two different username-password pairs.

Selenium Python
from selenium import webdriver
from selenium.webdriver.common.by import By
import pytest

@pytest.mark.parametrize("username,password", [
    ("user1", "pass1"),
    ("user2", "pass2"),
])
def test_login(username, password):
    driver = webdriver.Chrome()
    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()
    message = driver.find_element(By.ID, "message").text
    driver.quit()
    assert message == "Login successful"

# Run this with pytest to see two tests run with different data.
OutputSuccess
Important Notes

Always use clear and meaningful test data for better understanding.

Parameterizing helps avoid repeating similar test code.

Make sure your test cleans up after each run to avoid side effects.

Summary

Parameterize tests to run the same test with different data easily.

Use @pytest.mark.parametrize decorator in Python Selenium tests.

This saves time and finds more bugs by testing many cases.