0
0
Selenium Pythontesting~10 mins

Page factory pattern in Selenium Python - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test uses the Page Factory pattern to locate and interact with a login page's username, password fields, and login button. It verifies that after login, the page shows a welcome message.

Test Code - Selenium
Selenium Python
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
from selenium.webdriver.support.page_factory import PageFactory
import unittest

class LoginPage:
    username = (By.ID, "username")
    password = (By.ID, "password")
    login_button = (By.ID, "loginBtn")

    def __init__(self, driver):
        self.driver = driver
        PageFactory.init_elements(self.driver, self)

    def login(self, user, pwd):
        self.username.clear()
        self.username.send_keys(user)
        self.password.clear()
        self.password.send_keys(pwd)
        self.login_button.click()

class TestLogin(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Chrome()
        self.driver.get("https://example.com/login")
        self.login_page = LoginPage(self.driver)

    def test_valid_login(self):
        self.login_page.login("testuser", "testpass")
        # Wait for welcome message
        welcome = WebDriverWait(self.driver, 10).until(
            EC.presence_of_element_located((By.ID, "welcomeMsg"))
        )
        self.assertEqual(welcome.text, "Welcome, testuser!")

    def tearDown(self):
        self.driver.quit()

if __name__ == "__main__":
    unittest.main()
Execution Trace - 5 Steps
StepActionSystem StateAssertionResult
1Test starts and Chrome browser opensBrowser window is open at https://example.com/login-PASS
2LoginPage object initializes and locates username, password, and login button elements using PageFactoryUsername, password fields and login button are found on the page-PASS
3Test inputs 'testuser' in username field and 'testpass' in password field, then clicks login buttonLogin form is submitted-PASS
4Waits up to 10 seconds for welcome message element with ID 'welcomeMsg' to appearWelcome message element appears with text 'Welcome, testuser!'Check that welcome message text equals 'Welcome, testuser!'PASS
5Test ends and browser closesBrowser window is closed-PASS
Failure Scenario
Failing Condition: Welcome message element with ID 'welcomeMsg' does not appear after login
Execution Trace Quiz - 3 Questions
Test your understanding
What does the Page Factory pattern help with in this test?
ALocating and initializing web elements once for reuse
BAutomatically generating test data
CRunning tests in parallel
DCapturing screenshots on failure
Key Result
Using the Page Factory pattern helps keep element locators organized and reusable, making tests easier to maintain and read.