Automate login functionality test
Preconditions (3)
✅ Expected Result: User is successfully logged in and redirected to the dashboard page with a welcome message displayed.
import unittest 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 TestLoginAutomation(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome() self.driver.maximize_window() self.wait = WebDriverWait(self.driver, 10) def test_login(self): driver = self.driver wait = self.wait # Step 1: Open login page driver.get('https://example.com/login') # Step 2: Enter username username_field = wait.until(EC.visibility_of_element_located((By.ID, 'username'))) username_field.clear() username_field.send_keys('testuser') # Step 3: Enter password password_field = wait.until(EC.visibility_of_element_located((By.ID, 'password'))) password_field.clear() password_field.send_keys('Test@1234') # Step 4: Click login button login_button = wait.until(EC.element_to_be_clickable((By.ID, 'loginBtn'))) login_button.click() # Step 5 & 6: Wait for dashboard URL wait.until(EC.url_to_be('https://example.com/dashboard')) self.assertEqual(driver.current_url, 'https://example.com/dashboard') # Step 7: Verify welcome message welcome_message = wait.until(EC.visibility_of_element_located((By.ID, 'welcomeMsg'))) self.assertEqual(welcome_message.text, 'Welcome, testuser!') def tearDown(self): self.driver.quit() if __name__ == '__main__': unittest.main()
This test script uses Python's unittest framework with Selenium WebDriver.
setUp() initializes the Chrome browser and sets an explicit wait of 10 seconds.
The test_login method automates the manual test steps precisely:
tearDown() closes the browser after the test.
Explicit waits ensure the test waits only as long as needed for elements or conditions, avoiding flaky tests. Using IDs as locators is reliable and maintainable. Assertions verify the expected outcomes clearly.
Now add data-driven testing with 3 different sets of username and password inputs to verify login success or failure.
def test_sum():
total = 0
for i in range(3):
total += i
assert total == 3def test_login():
username = "user"
password = "pass"
assert username = "user"Pass the test and this pattern moves unknown