Parametrized fixtures in PyTest - 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 @pytest.fixture(params=[ {"username": "user1@example.com", "password": "Pass123!"}, {"username": "user2@example.com", "password": "Pass456!"}, {"username": "user3@example.com", "password": "Pass789!"} ]) def credentials(request): return request.param @pytest.fixture def driver(): driver = webdriver.Chrome() driver.implicitly_wait(5) yield driver driver.quit() def test_login_with_parametrized_credentials(driver, credentials): driver.get("http://example.com/login") # Wait for username field and enter username username_field = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.ID, "username")) ) username_field.clear() username_field.send_keys(credentials["username"]) # Wait for password field and enter password password_field = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.ID, "password")) ) password_field.clear() password_field.send_keys(credentials["password"]) # Wait for login button and click login_button = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.ID, "loginBtn")) ) login_button.click() # Verify URL contains '/dashboard' WebDriverWait(driver, 10).until( EC.url_contains("/dashboard") ) assert "/dashboard" in driver.current_url # Verify logout button is present logout_button = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, "logoutBtn")) ) assert logout_button.is_displayed() # Logout to reset state logout_button.click()
This test uses a pytest parametrized fixture named credentials to supply three different sets of user login data.
The driver fixture sets up the Selenium WebDriver and ensures it quits after the test.
The test function test_login_with_parametrized_credentials uses these fixtures. It opens the login page, waits explicitly for each element to be clickable before interacting, and enters the username and password from the current parameter set.
After clicking login, it waits until the URL contains '/dashboard' to confirm successful login, then asserts this condition.
It also checks that the logout button is visible, confirming the user is logged in.
Finally, it clicks logout to reset the state for the next test iteration.
This approach keeps tests clean, readable, and reliable by using explicit waits and parametrization.
Now add data-driven testing with 3 different sets of invalid credentials and verify login failure message.