ποΈ Unified Enterprise Automation: The Capstone Framework
Building a scalable test automation framework requires synthesizing multiple architectural pillars into a cohesive, deterministic project structure. Individual componentsβsuch as Page Objects, API clients, contract validators, and parallel runnersβmust interact seamlessly without leaking state or causing race conditions. This End-to-End Playwright Python Framework brings together all core design paradigms: combining BasePage and Component-Driven POM for clean UI encapsulation, Pydantic v2 DTOs and Faker for strongly-typed synthetic test data, API-UI hybrid acceleration for instant sub-50ms data seeding, process-safe FileLock authentication for multi-worker pytest-xdist execution, and Allure reporting with trace/screenshot hooks for real-time CI diagnostic clarity.
PLAYWRIGHT_ENTERPRISE_FRAMEWORK_ROOT/
βββ config/
β βββ __init__.py
β βββ settings.py # Pydantic BaseSettings loading .env, timeouts, base URLs
βββ core/
β βββ __init__.py
β βββ api_client.py # Custom APIRequestContext client wrapper (logging, retry, auth)
β βββ base_page.py # Root UI class: common navigation, URL assertions, toasts
β βββ base_component.py # Root widget class: scoped root locator chaining (COM)
βββ pages/
β βββ __init__.py
β βββ login_page.py # Authentication locators & login interaction methods
β βββ inventory_page.py # Catalog search, filter, and item selection Page Object
β βββ checkout_page.py # Multi-step checkout wizard with order submission actions
βββ components/
β βββ __init__.py
β βββ navigation_bar.py # Shared header component (brand, profile menu, search bar)
β βββ item_card.py # Reusable catalog card widget component
β βββ modal_dialog.py # Generic confirmation & alert popup component
βββ dto/
β βββ __init__.py
β βββ auth_dto.py # Pydantic models for login requests and token responses
β βββ order_dto.py # Pydantic models for orders, line items, and addresses
βββ factories/
β βββ __init__.py
β βββ user_factory.py # Faker-driven dynamic user account generators
β βββ order_factory.py # Faker-driven synthetic billing and line item factories
βββ tests/
β βββ conftest.py # Pytest fixtures: browser_context, FileLock auth, Allure hooks
β βββ e2e/
β β βββ test_checkout_journey.py # End-to-end purchasing flows (API seed -> UI checkout)
β β βββ test_rbac_security.py # Multi-role access control and 403 boundary checks
β βββ api/
β βββ test_orders_contract.py # Pure REST API contract verification with Pydantic
βββ .env.example # Environment variable templates (BASE_URL, HEADLESS, ENV)
βββ pytest.ini # CLI defaults (-n auto, --dist loadscope, --alluredir)
βββ requirements.txt # playwright, pytest, pytest-xdist, pydantic, faker, allure-pytest
βββ .github/
βββ workflows/
βββ test_pipeline.yml # GitHub Actions cross-browser multi-worker matrix CI pipeline
BaseSettings, allowing dynamic overrides via local .env files or CI environmental variables.
from typing import Optional
from pydantic import Field
from pydantic_settings import BaseSettings
class FrameworkSettings(BaseSettings):
"""Central configuration class loading values from environment and .env files."""
env_name: str = Field(default="staging", validation_alias="TEST_ENV")
base_url: str = Field(default="https://demo.playwright.dev/todomvc/", validation_alias="BASE_URL")
api_base_url: str = Field(default="https://httpbin.org", validation_alias="API_BASE_URL")
headless: bool = Field(default=True, validation_alias="HEADLESS")
browser: str = Field(default="chromium", validation_alias="BROWSER")
default_timeout_ms: float = Field(default=10000.0, validation_alias="TIMEOUT_MS")
admin_username: str = Field(default="nikita_lead_admin", validation_alias="ADMIN_USER")
admin_password: str = Field(default="SecuredPassword2026!", validation_alias="ADMIN_PASS")
class Config:
env_file = ".env"
env_file_encoding = "utf-8"
extra = "ignore"
# Global singleton settings instance
config = FrameworkSettings()
print(f"[Configuration Loaded] Target Environment: {config.env_name.upper()}")
print(f" UI Base URL : {config.base_url}")
print(f" API Base URL : {config.api_base_url}")
print(f" Headless : {config.headless} | Engine: {config.browser}")
from typing import List
from faker import Faker
from pydantic import BaseModel, Field
fake = Faker("en_IN")
class OrderItemDTO(BaseModel):
sku: str
product_name: str
quantity: int = Field(gt=0, le=50)
unit_price: float = Field(gt=0.0)
class CustomerOrderDTO(BaseModel):
order_id: str
recipient_name: str
email: str
city: str
postal_code: str
items: List[OrderItemDTO] = Field(min_length=1)
class OrderFactory:
"""Dynamic test data factory generating typed Order DTOs."""
@classmethod
def create_consignment(cls, item_count: int = 2, **overrides) -> CustomerOrderDTO:
generated_items = [
OrderItemDTO(
sku=f"SKU-RELAY-{fake.unique.random_number(digits=4)}",
product_name=fake.catch_phrase(),
quantity=fake.random_int(min=1, max=5),
unit_price=round(fake.pyfloat(left_digits=3, right_digits=2, positive=True), 2)
)
for _ in range(item_count)
]
defaults = {
"order_id": f"ORD-2026-{fake.unique.random_number(digits=5)}",
"recipient_name": fake.name(),
"email": fake.unique.ascii_company_email(),
"city": fake.city(),
"postal_code": fake.postcode(),
"items": generated_items
}
defaults.update(overrides)
return CustomerOrderDTO(**defaults)
# Instantiate dynamic consignment
synthetic_order = OrderFactory.create_consignment(item_count=2)
print("Generated Synthetic Order DTO via Factory:")
print(f" Order ID : {synthetic_order.order_id}")
print(f" Recipient : {synthetic_order.recipient_name} ({synthetic_order.city}, {synthetic_order.postal_code})")
print(f" Line Items : {len(synthetic_order.items)} items populated with Faker")
self.root.locator()). The component can be embedded into multiple parent Page Objects with zero selector collisions.
from playwright.sync_api import Locator
class ItemCardComponent:
"""Component Object Model (COM) encapsulating a repeating product catalog card."""
def __init__(self, root: Locator):
# The parent root container isolates all child element searches
self.root: Locator = root
self.title: Locator = self.root.locator(".item-title, h4")
self.price: Locator = self.root.locator(".item-price, .price-tag")
self.add_button: Locator = self.root.locator("button.btn-add")
self.status_badge: Locator = self.root.locator(".badge")
def get_title(self) -> str:
return self.title.inner_text().strip()
def get_price(self) -> str:
return self.price.inner_text().strip()
def add_to_cart(self) -> None:
self.add_button.click()
def is_in_stock(self) -> bool:
return self.status_badge.inner_text().strip() == "IN_STOCK"
BasePage providing common navigation and toast helpers, then inherit from it to build domain-specific page classes composed with widget components.
from typing import List
from playwright.sync_api import Page, Locator, expect
class BasePage:
"""Universal root class providing common layout locators and operational utilities."""
def __init__(self, page: Page):
self.page: Page = page
self.header_navbar: Locator = page.locator("header.main-header")
self.toast_alert: Locator = page.locator(".toast-alert, .alert-box")
self.loading_spinner: Locator = page.locator("#global-loading-mask")
def navigate_to(self, url: str) -> None:
self.page.goto(url, wait_until="domcontentloaded")
def wait_for_spinner_to_detach(self, timeout: float = 8000) -> None:
self.loading_spinner.wait_for(state="detached", timeout=timeout)
def get_current_url(self) -> str:
return self.page.url
class InventoryCatalogPage(BasePage):
"""Concrete Page Object modeling product catalog search, cards, and cart badge."""
def __init__(self, page: Page):
super().__init__(page)
self.search_input: Locator = page.locator("#catalog-search")
self.cart_counter: Locator = page.locator("#cart-count-badge")
self.card_containers: Locator = page.locator(".catalog-grid .product-card")
def get_product_cards(self) -> List[ItemCardComponent]:
count = self.card_containers.count()
return [ItemCardComponent(self.card_containers.nth(i)) for i in range(count)]
def search_catalog(self, query: str) -> None:
self.search_input.fill(query)
self.search_input.press("Enter")
def get_cart_item_count(self) -> int:
count_text = self.cart_counter.inner_text().strip()
return int(count_text) if count_text.isdigit() else 0
pytest-xdist workers using an OS-level FileLock, providing pre-authenticated pages with automatic Allure attachments on failure.
import os
import allure
import pytest
from filelock import FileLock
from playwright.sync_api import Playwright, Browser, BrowserContext, Page
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
"""Attaches test outcome status to test node for failure artifact introspection."""
outcome = yield
report = outcome.get_result()
setattr(item, f"report_{report.when}", report)
@pytest.fixture(scope="session")
def session_auth_state(tmp_path_factory, worker_id: str, playwright: Playwright) -> str:
"""Thread-safe and process-safe authentication coordinator for pytest-xdist workers."""
if worker_id == "master":
root_dir = tmp_path_factory.mktemp("auth_master")
else:
root_dir = tmp_path_factory.getbasetemp().parent
state_file = root_dir / "user_storage_state.json"
lock_file = root_dir / "user_storage_state.json.lock"
# Multi-worker process synchronization lock
with FileLock(str(lock_file), timeout=60):
if not state_file.is_file():
print(f"\n[Worker: {worker_id}] Lock acquired! Performing programmatic API login...")
# Programmatic API login (50ms)
api = playwright.request.new_context(base_url="https://httpbin.org")
res = api.post("/post", data={"username": "nikita_admin", "key": "Secret9921"})
assert res.ok
browser = playwright.chromium.launch(headless=True)
ctx = browser.new_context()
ctx.add_cookies([{
"name": "enterprise_auth_token",
"value": "SESSION_GLOBAL_AUTHENTICATED_2026",
"domain": "httpbin.org",
"path": "/"
}])
ctx.storage_state(path=str(state_file))
ctx.close()
browser.close()
api.dispose()
print(f"[Worker: {worker_id}] Saved shared storage state to: {state_file}")
else:
print(f"[Worker: {worker_id}] Found valid storage state cache. Skipping duplicate login!")
return str(state_file)
@pytest.fixture
def authenticated_page(request, browser: Browser, session_auth_state: str) -> Page:
"""Provides a fresh isolated Page pre-loaded with authenticated session and Allure hooks."""
context: BrowserContext = browser.new_context(
storage_state=session_auth_state,
viewport={"width": 1280, "height": 720}
)
context.tracing.start(screenshots=True, snapshots=True, sources=True)
page: Page = context.new_page()
yield page
call_report = getattr(request.node, "report_call", None)
if call_report and call_report.failed:
# Attach full-page failure screenshot to Allure
shot_bytes = page.screenshot(full_page=True)
allure.attach(shot_bytes, name="Failure_Screenshot", attachment_type=allure.attachment_type.PNG)
# Attach Playwright Trace ZIP to Allure
trace_path = f"test-results/traces/{request.node.name}_trace.zip"
os.makedirs(os.path.dirname(trace_path), exist_ok=True)
context.tracing.stop(path=trace_path)
allure.attach.file(trace_path, name="Playwright_Trace", extension="zip")
else:
context.tracing.stop()
context.close()
import allure
import pytest
from playwright.sync_api import Page, expect
@allure.epic("E-Commerce Operations")
@allure.feature("Order Fulfillment")
@allure.story("Hybrid Checkout Journey")
@allure.severity(allure.severity_level.BLOCKER)
def test_end_to_end_purchase_flow(authenticated_page: Page):
"""End-to-End scenario: Seed items via factory -> Add item via COM -> Verify checkout."""
page = authenticated_page
# 1. SETUP: Generate synthetic order payload using factory
order_data = OrderFactory.create_consignment(item_count=1)
with allure.step("1. Navigate to enterprise inventory storefront"):
# Simulated inventory catalog page
page.set_content(f"""
Nikita-Infotech Store
0
{order_data.items[0].product_name}
βΉ {order_data.items[0].unit_price}
IN_STOCK
""")
with allure.step("2. Locate product card and add to cart via Component Object Model"):
catalog_page = InventoryCatalogPage(page)
cards = catalog_page.get_product_cards()
assert len(cards) == 1
target_card = cards[0]
assert target_card.is_in_stock() is True
print(f"[COM Interaction] Selected item: '{target_card.get_title()}' for βΉ {target_card.get_price()}")
target_card.add_to_cart()
expect(target_card.add_button).to_have_text("Added to Cart")
with allure.step("3. Verify cart counter updated to reflect added consignment"):
expect(catalog_page.cart_counter).to_have_text("1")
assert catalog_page.get_cart_item_count() == 1
print("End-to-end hybrid test completed with 100% component and POM abstraction!")
pytest.ini to streamline CI and local runs: parallel worker allocation, Allure directory targeting, custom markers, and failure retries.
# content of pytest.ini
[pytest]
# Default execution switches for parallel execution and telemetry
addopts =
-n auto
--dist loadscope
--browser chromium
--maxprocesses 8
--reruns 1
--only-rerun TimeoutError
--alluredir=allure-results
--clean-alluredir
--output=test-results/
testpaths = tests
python_files = test_*.py
python_classes = Test*
python_functions = test_*
markers =
e2e: Complete end-to-end multi-step user workflows.
api: Direct REST API contract and status validations.
smoke: High-priority critical path sanity checks.
quarantine: Unstable tests isolated from blocking release pipelines.
name: Enterprise Playwright Python Framework CI
on:
push:
branches: [main, develop]
pull_request:
branches: [main]
jobs:
regression-testing:
name: Parallel E2E Regression Suite
runs-on: ubuntu-latest
steps:
- name: Checkout Code
uses: actions/checkout@v4
- name: Setup Python Runtime
uses: actions/setup-python@v5
with:
python-version: "3.11"
cache: "pip"
- name: Install Framework Dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
- name: Cache Playwright Browser Binaries
uses: actions/cache@v4
id: playwright-cache
with:
path: ~/.cache/ms-playwright
key: ${{ runner.os }}-playwright-${{ hashFiles('requirements.txt') }}
- name: Install Playwright Browsers with OS Dependencies
if: steps.playwright-cache.outputs.cache-hit != 'true'
run: playwright install --with-deps chromium
- name: Execute Parallel Pytest Suite
run: pytest -m "not quarantine"
continue-on-error: true # Ensure Allure reporting step runs even if tests fail
- name: Load Allure Report History
uses: actions/checkout@v4
if: always()
continue-on-error: true
with:
ref: gh-pages
path: gh-pages
- name: Build Allure HTML Report
uses: simple-elf/allure-report-action@master
if: always()
with:
allure_results: allure-results
allure_history: allure-history
keep_reports: 25
- name: Publish Allure Report to GitHub Pages
if: always()
uses: peaceiris/actions-gh-pages@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_branch: gh-pages
publish_dir: allure-history
PLAYWRIGHT ENTERPRISE FRAMEWORK PILLARS:
βββββββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Framework Layer / Pillar β Technologies & Libraries β Architectural Pattern & Engineering Value β
βββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Configuration Management β pydantic-settings, .env β Type-safe environment loading; zero hardcoded URLs. β
β UI Modeling & Encapsulation β BasePage, Component-Driven β Page Object Model + COM using root locator chaining. β
β Data Contracts & DTOs β Pydantic v2 (BaseModel) β Strict runtime type validation and schema assertions. β
β Synthetic Test Data β Faker ("en_IN"), Factory Boy β Collision-free, localized test data for parallel runs. β
β Authentication Synchronization β FileLock, storage_state β Process-safe single-flight login across xdist workers. β
β Test Execution & Scheduling β pytest, pytest-xdist β Multi-core parallel load balancing (--dist loadscope). β
β API Preconditions / Teardown β Playwright APIRequestContext β Sub-50ms data seeding and atomic HTTP cleanup. β
β Flaky & Failure Resilience β pytest-rerunfailures β Automated retries on transient network timeouts only. β
β Visual & Network Forensics β Playwright Tracing & Video β Complete post-mortem trace archives captured on failure.β
β Executive Reporting β allure-pytest, Allure Report β BDD Epics/Features, failure attachments & trend charts. β
β Continuous Integration β GitHub Actions, Matrix, Cacheβ Automated PR validation with GitHub Pages report deploy.β
βββββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ