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
import unittest
class TestLogin(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome()
self.driver.maximize_window()
self.wait = WebDriverWait(self.driver, 10)
def test_login_success(self):
driver = self.driver
wait = self.wait
driver.get('https://example.com/login')
# Enter username
username_field = wait.until(EC.visibility_of_element_located((By.ID, 'username')))
username_field.clear()
username_field.send_keys('testuser')
# Enter password
password_field = wait.until(EC.visibility_of_element_located((By.ID, 'password')))
password_field.clear()
password_field.send_keys('Test@1234')
# Click login button
login_button = wait.until(EC.element_to_be_clickable((By.ID, 'loginBtn')))
login_button.click()
# Verify URL
wait.until(EC.url_to_be('https://example.com/dashboard'))
current_url = driver.current_url
self.assertEqual(current_url, 'https://example.com/dashboard', 'URL after login should be dashboard URL')
# Verify welcome message
welcome_message = wait.until(EC.visibility_of_element_located((By.ID, 'welcomeMsg')))
self.assertEqual(welcome_message.text, 'Welcome, testuser!', 'Welcome message text should match')
def tearDown(self):
self.driver.quit()
if __name__ == '__main__':
unittest.main()This test script uses Selenium WebDriver with Python's unittest framework.
setUp: Initializes the Chrome browser and sets an explicit wait of 10 seconds.
test_login_success: Automates the login steps precisely as per the manual test case:
- Opens the login page URL.
- Waits for username and password fields to be visible, then enters 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.
Explicit waits ensure the test waits only as long as needed for elements or URL changes, avoiding flaky tests.
tearDown: Closes the browser after the test finishes.
Locators use By.ID for reliability and readability. Assertions have clear messages to help identify failures.