Parameterized tests in Selenium Python - Build an Automation Script
import pytest from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC class LoginPage: def __init__(self, driver): self.driver = driver self.email_input = (By.ID, 'email') self.password_input = (By.ID, 'password') self.login_button = (By.ID, 'loginBtn') def load(self): self.driver.get('https://example.com/login') def login(self, email, password): WebDriverWait(self.driver, 10).until( EC.visibility_of_element_located(self.email_input) ) self.driver.find_element(*self.email_input).clear() self.driver.find_element(*self.email_input).send_keys(email) self.driver.find_element(*self.password_input).clear() self.driver.find_element(*self.password_input).send_keys(password) self.driver.find_element(*self.login_button).click() class DashboardPage: def __init__(self, driver): self.driver = driver def is_loaded(self): return WebDriverWait(self.driver, 10).until( EC.url_to_be('https://example.com/dashboard') ) @pytest.fixture(scope='module') def driver(): driver = webdriver.Chrome() yield driver driver.quit() @pytest.mark.parametrize('email,password', [ ('user1@example.com', 'Password1!'), ('user2@example.com', 'Password2!'), ('user3@example.com', 'Password3!') ]) def test_login(driver, email, password): login_page = LoginPage(driver) dashboard_page = DashboardPage(driver) login_page.load() login_page.login(email, password) assert dashboard_page.is_loaded(), f"Login failed for {email}" # Log out to prepare for next test iteration driver.get('https://example.com/logout')
This test script uses pytest with Selenium WebDriver to automate login tests with multiple user credentials.
The LoginPage class encapsulates the login page elements and actions, following the Page Object Model pattern for cleaner code.
The DashboardPage class checks if the dashboard page is loaded by waiting for the URL to be the expected dashboard URL.
The driver fixture initializes the Chrome browser once per test module and closes it after all tests finish.
The @pytest.mark.parametrize decorator runs the test_login function three times with different email and password pairs.
Explicit waits ensure the test waits for elements to be visible or URL to change before proceeding, avoiding flaky tests.
After each login test, the script navigates to the logout URL to reset the session for the next test.
Now add data-driven testing with 3 different invalid login inputs and verify error messages appear.