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:
- It opens the login page URL.
- Waits for username and password fields to be visible, then enters the credentials.
- Waits for the login button to be clickable and clicks it.
- Waits until the URL changes to the dashboard URL and asserts it.
- Waits for the welcome message element and asserts its text.
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.