ποΈ Clean Architecture: Encapsulating UI Logic & Locators
Writing automation scripts that intermingle selectors, actions, waits, and assertions directly inside test functions produces brittle, unmaintainable test code. Whenever a web designer updates a button ID or refactors a layout, dozens of tests break simultaneously. The Page Object Model (POM) is an industry-standard structural design pattern that abstracts web pages into reusable Python classes. In Playwright with Python, Page Objects thrive because Playwright's Locator objects are evaluated lazily. Locators stored as instance attributes inside __init__ do not trigger immediate DOM queries, eliminating stale element exceptions and ensuring that selector maintenance is centralized in one file.
TEST SPECIFICATION LAYER (tests/test_checkout.py):
* Expresses pure business workflows and domain assertions
* Interacts ONLY with Page Object methods; zero raw CSS/XPath selectors
* Example: login_page.login("user", "pass") -> inventory_page.add_item("Relay")
β calls methods & queries states
βΌ
PAGE OBJECT LAYER (pages/login_page.py, pages/inventory_page.py):
* Encapsulates Page instance, Locators, and user action methods
* Exposes high-level intent: submit_credentials(), get_error_message()
* Holds lazy Locators: self.user_input = page.locator("#username")
β delegates commands & lazy resolutions
βΌ
PLAYWRIGHT ENGINE LAYER (Core Browser Execution):
* Executes DOM operations, auto-waits, retries, and network routing
LoginPage class in Python. Store locators as attributes inside __init__ and expose intuitive business action methods.
from playwright.sync_api import Page, Locator
class LoginPage:
"""Page Object encapsulating the corporate sign-in interface."""
def __init__(self, page: Page):
self.page = page
# Lazy Locators: Stored without triggering immediate DOM lookup
self.username_input: Locator = page.locator("#user-name")
self.password_input: Locator = page.locator("#password")
self.login_button: Locator = page.locator("#login-button")
self.error_message: Locator = page.locator("[data-test='error']")
def navigate(self, url: str = "https://www.saucedemo.com/"):
self.page.goto(url)
return self
def login(self, username: str, password: str) -> None:
"""Executes full login sequence with automated auto-waiting."""
self.username_input.fill(username)
self.password_input.fill(password)
self.login_button.click()
def get_error_text(self) -> str:
return self.error_message.inner_text()
expect assertions on public page properties.
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
# Provide HTML mock for deterministic verification
page.set_content("""
""")
# Instantiate Page Object
login_page = LoginPage(page)
# 1. Negative Scenario: Attempt login with empty credentials
login_page.login("", "")
# Web-first assertion on Page Object locator
expect(login_page.error_message).to_be_visible()
expect(login_page.error_message).to_contain_text("Username is required")
print(f"Verified Error Diagnostic via POM: '{login_page.get_error_text()}'")
browser.close()
BasePage class from which specific page models inherit.
from playwright.sync_api import Page, Locator, expect
class BasePage:
"""Universal root class providing shared elements and common utilities."""
def __init__(self, page: Page):
self.page = page
self.nav_menu: Locator = page.locator("nav.main-navigation")
self.user_badge: Locator = page.locator("#user-profile-badge")
self.toast_alert: Locator = page.locator(".toast-notification")
def get_title(self) -> str:
return self.page.title()
def get_current_url(self) -> str:
return self.page.url
class InventoryPage(BasePage):
"""Subclass inheriting core navigation while managing inventory catalog."""
def __init__(self, page: Page):
super().__init__(page)
self.item_cards: Locator = page.locator(".inventory-item")
self.cart_badge: Locator = page.locator(".shopping-cart-badge")
def add_first_item_to_cart(self) -> None:
self.item_cards.first.locator("button.add-to-cart").click()
def get_cart_count(self) -> int:
count_text = self.cart_badge.inner_text()
return int(count_text) if count_text else 0
from playwright.sync_api import Locator, Page, sync_playwright, expect
class ConfirmationModalComponent:
"""Component Object encapsulating a reusable confirmation popup."""
def __init__(self, root: Locator):
self.root = root
self.title: Locator = root.locator("h3.modal-title")
self.confirm_btn: Locator = root.locator("button.confirm")
self.cancel_btn: Locator = root.locator("button.cancel")
def confirm(self) -> None:
self.confirm_btn.click()
def cancel(self) -> None:
self.cancel_btn.click()
class UserManagementPage:
"""Page composing both page-level actions and component widgets."""
def __init__(self, page: Page):
self.page = page
self.delete_user_btn = page.locator("#delete-user-1")
# Sub-component scoped to modal container
self.confirm_dialog = ConfirmationModalComponent(page.locator("#confirm-modal"))
def trigger_user_deletion(self) -> None:
self.delete_user_btn.click()
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
page.set_content("""
Active
""")
user_admin = UserManagementPage(page)
user_admin.trigger_user_deletion()
expect(user_admin.confirm_dialog.title).to_have_text("Confirm Deletion")
user_admin.confirm_dialog.confirm()
expect(page.locator("#res")).to_have_text("DELETED")
print("Component Object Model interaction verified successfully!")
browser.close()
from playwright.sync_api import Page, sync_playwright, expect
class CheckoutStepTwoPage:
def __init__(self, page: Page):
self.page = page
self.summary_title = page.locator("h2.summary")
class CheckoutStepOnePage:
def __init__(self, page: Page):
self.page = page
self.first_name = page.locator("#first-name")
self.postal_code = page.locator("#postal-code")
self.continue_btn = page.locator("#continue")
def fill_shipping_details(self, name: str, zip_code: str) -> CheckoutStepTwoPage:
self.first_name.fill(name)
self.postal_code.fill(zip_code)
self.continue_btn.click()
# Returns subsequent page object
return CheckoutStepTwoPage(self.page)
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
page.set_content("""
""")
step_one = CheckoutStepOnePage(page)
# Fluent transition: returns CheckoutStepTwoPage
step_two = step_one.fill_shipping_details("Pooja Patil", "411014")
expect(step_two.summary_title).to_have_text("Order Overview")
print(f"Fluent transition successful! Arrived at: '{step_two.summary_title.inner_text()}'")
browser.close()
conftest.py, eliminating manual instantiation in test bodies.
# content of conftest.py
import pytest
from playwright.sync_api import Page
# Assuming LoginPage and InventoryPage are in pages/ directory
@pytest.fixture
def login_page(page: Page) -> LoginPage:
"""Provides a fresh LoginPage instance ready for test execution."""
return LoginPage(page)
@pytest.fixture
def authenticated_inventory_page(page: Page) -> InventoryPage:
"""Pre-authenticates the session and returns an InventoryPage instance."""
login = LoginPage(page)
login.navigate()
login.login("standard_user", "secret_sauce")
return InventoryPage(page)
# content of tests/test_inventory.py
def test_add_item_to_cart(authenticated_inventory_page: InventoryPage):
# Test function receives pre-authenticated Page Object directly!
authenticated_inventory_page.add_first_item_to_cart()
assert authenticated_inventory_page.get_cart_count() == 1
time.sleep() pauses inside Page Object methods.
import time
from playwright.sync_api import Page, Locator
class SearchWidgetPage:
def __init__(self, page: Page):
self.page = page
self.search_box = page.locator("#global-search")
self.results_dropdown = page.locator(".search-autocomplete-list")
self.first_result = self.results_dropdown.locator("li.result-item").first
# β ANTI-PATTERN: Brittle, slow static sleep
def bad_search(self, query: str):
self.search_box.fill(query)
time.sleep(3) # Arbitrary pause, wastes time or fails on slow CI
self.first_result.click()
# β
PLAYWRIGHT IDIOMATIC: Built-in auto-waiting
def search_and_select_first(self, query: str):
self.search_box.fill(query)
# click() automatically waits for the element to be visible and stable!
self.first_result.click()
AUTOMATION_FRAMEWORK_ROOT/
βββ pages/
β βββ __init__.py
β βββ base_page.py # Root class with common navigation, URL, toasts
β βββ login_page.py # Authentication locators & sign-in actions
β βββ dashboard_page.py # Analytics metrics & dashboard widgets
β βββ checkout_page.py # Multi-step checkout wizard models
βββ components/
β βββ __init__.py
β βββ navigation_bar.py # Top header navigation & profile dropdown
β βββ data_table.py # Generic sorting, filtering, row locator helper
β βββ modal_dialog.py # Shared confirmation & alert popups
βββ tests/
β βββ conftest.py # Pytest fixtures injecting page objects
β βββ test_authentication.py # Login, logout, password reset tests
β βββ test_checkout_flow.py # End-to-end purchasing test suites
βββ data/
β βββ test_payloads.json # External JSON fixtures & mock datasets
βββ pytest.ini # Pytest configuration flags (-v, -n auto)
βββ requirements.txt # playwright, pytest, pytest-xdist
PLAYWRIGHT PAGE OBJECT MODEL MATRIX:
ββββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββββββ
β Architectural Dimension β Recommended Best Practice β Anti-Pattern to Avoid β
ββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββββββββββ€
β Locator Storage β Store as Locator objects in __init__ β Querying raw page.$() / page.query_... β
β Assertion Placement β Assert in test functions via expect() β Hardcoding assertions inside POM methods β
β Timing & Synchronization β Rely on Playwright auto-waiting β Inserting time.sleep() or manual pauses β
β Element Scope & Reusability β Break complex widgets into Components β Bloating single Page class to 1000+ linesβ
β Type Safety & Readability β Add Python type hints (page: Page) β Untyped code causing missing IDE auto-comβ
β Action Method Returns β Return self or new destination Page β Returning raw internal implementation locβ
β Fixture Integration β Inject POM instances via Pytest fixtures β Manual object instantiation in every testβ
ββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββββββ