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, 'login-btn')
def open(self, url):
self.driver.get(url)
def enter_email(self, email):
WebDriverWait(self.driver, 10).until(
EC.visibility_of_element_located(self.email_input)
).send_keys(email)
def enter_password(self, password):
WebDriverWait(self.driver, 10).until(
EC.visibility_of_element_located(self.password_input)
).send_keys(password)
def click_login(self):
WebDriverWait(self.driver, 10).until(
EC.element_to_be_clickable(self.login_button)
).click()
class DashboardPage:
def __init__(self, driver):
self.driver = driver
self.welcome_message = (By.ID, 'welcome-msg')
def is_loaded(self):
return WebDriverWait(self.driver, 10).until(
EC.visibility_of_element_located(self.welcome_message)
) is not None
import unittest
class TestLogin(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome()
self.login_page = LoginPage(self.driver)
self.dashboard_page = DashboardPage(self.driver)
def test_valid_login(self):
self.login_page.open('https://example.com/login')
self.login_page.enter_email('user@example.com')
self.login_page.enter_password('Password123')
self.login_page.click_login()
self.assertIn('/dashboard', self.driver.current_url, 'URL does not contain /dashboard')
self.assertTrue(self.dashboard_page.is_loaded(), 'Dashboard welcome message not found')
def tearDown(self):
self.driver.quit()
if __name__ == '__main__':
unittest.main()This code uses Selenium WebDriver with Python to automate the login test using a modular framework design called the Page Object Model (POM).
We created two classes: LoginPage and DashboardPage. Each class holds locators and methods related to that page.
The test class TestLogin uses unittest framework. It sets up the browser, uses the page objects to perform actions, and asserts the expected results.
Explicit waits ensure elements are ready before interacting.
This structure keeps code clean, reusable, and easy to maintain.