Verify login functionality using test functions and classes
Preconditions (2)
✅ Expected Result: User is successfully logged in and redirected to the dashboard page with a welcome message displayed
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 class LoginPage: def __init__(self, driver): self.driver = driver self.username_input = (By.ID, 'username') self.password_input = (By.ID, 'password') self.login_button = (By.ID, 'loginBtn') def load(self): self.driver.get('https://example.com/login') def login(self, username, password): WebDriverWait(self.driver, 10).until( EC.visibility_of_element_located(self.username_input) ).send_keys(username) self.driver.find_element(*self.password_input).send_keys(password) self.driver.find_element(*self.login_button).click() class DashboardPage: def __init__(self, driver): self.driver = driver self.welcome_message = (By.ID, 'welcomeMessage') def wait_for_dashboard(self): WebDriverWait(self.driver, 10).until( EC.url_to_be('https://example.com/dashboard') ) def get_welcome_text(self): return WebDriverWait(self.driver, 10).until( EC.visibility_of_element_located(self.welcome_message) ).text class TestLogin: def setup_method(self): self.driver = webdriver.Chrome() self.driver.maximize_window() def teardown_method(self): self.driver.quit() def test_valid_login(self): login_page = LoginPage(self.driver) dashboard_page = DashboardPage(self.driver) login_page.load() login_page.login('testuser', 'Test@1234') dashboard_page.wait_for_dashboard() assert self.driver.current_url == 'https://example.com/dashboard' assert dashboard_page.get_welcome_text() == 'Welcome, testuser!'
This test script uses pytest and selenium to automate the login test case.
We define two page classes: LoginPage and DashboardPage to separate page actions and locators, following the Page Object Model.
The TestLogin class contains setup and teardown methods to open and close the browser for each test method.
The test method test_valid_login performs the login steps, waits for the dashboard page to load, and asserts the URL and welcome message text.
Explicit waits ensure elements are ready before interacting, improving test reliability.
Now add data-driven testing with 3 different username and password combinations
import unittest
class MyTest(unittest.TestCase):
def test_pass(self):
self.assertEqual(2 + 2, 4)
def test_fail(self):
self.assertTrue(False)
if __name__ == '__main__':
unittest.main(exit=False)import unittest
from selenium import webdriver
class TestLogin(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome()
def test_login(self):
self.driver.get('http://example.com')
self.assertIn('Example', self.driver.title)
def tearDown(self):
self.driver.quit()
if __name__ == '__main__':
unittest.main()Pass the test and this pattern moves unknown