E-COMMERCE STOREFRONT AUTOMATION CASE STUDY

A comprehensive production case study in Playwright with Python: automating complex multi-category storefronts, dynamic search & filter facets, slide-out cart drawers, coupon reconciliation, mock payment gateway handoffs, WhatsApp billing integrations, and end-to-end checkout validation.

🛍️ Real-World Retail Engineering: Kashmiri & Multi-Category Apparel Storefronts

E-commerce web applications present unique automated testing challenges: dynamic product catalogs, faceted multi-attribute filters (price, size, fabric, collection), reactive slide-out mini-carts, real-time promo code calculations with tiered taxes, and regional integration points like WhatsApp order dispatch and mock payment gateways. Inspired by high-volume apparel storefronts like Kashmir Fancy House, this case study demonstrates how to synthesize Page Object Models, Component-Driven design, API data seeding, and network route mocking to build a resilient, high-speed test suite covering the entire user purchasing funnel without flaky timeouts or database pollution.

1. E-Commerce Purchasing Funnel & Architecture Map
The end-to-end purchasing lifecycle encompasses category navigation, product filtering, dynamic cart drawer persistence, voucher discounts, and order handoff through checkout.
Storefront Architecture & Test Stages
E-COMMERCE USER JOURNEY & AUTOMATION STAGES:
┌─────────────────────────────────────────────────────────────────────────────┐
│ STAGE 1: CATALOG DISCOVERY & FACETED FILTERING                              │
│  * Navigate Men / Women / Kids collections (Pashmina, Kurtis, Suits)        │
│  * Select dynamic faceted filters: Price Slider, In-Stock, Fabric Type      │
│  * Component Object: ProductFilterComponent & ProductGridComponent          │
└─────────────────────────────────────────────────────────────────────────────┘
                                       │
                                       ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│ STAGE 2: PRODUCT DETAIL PAGE (PDP) & CART DRAWER PERSISTENCE                │
│  * Select SKU variants: Size (L / XL), Color (Saffron / Walnut)             │
│  * Add to Cart triggers async slide-out mini-cart drawer                    │
│  * LocalStorage synchronization: window.localStorage.getItem('cart_items')  │
└─────────────────────────────────────────────────────────────────────────────┘
                                       │
                                       ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│ STAGE 3: PROMO CODE ENGINE & TAX LEDGER RECONCILIATION                      │
│  * Apply coupon code (e.g. KASHMIR10) ──► Server intercepts via route.fetch │
│  * Validates tiered calculation: Base + 12% GST - 10% Promo = Final Total   │
└─────────────────────────────────────────────────────────────────────────────┘
                                       │
                                       ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│ STAGE 4: CHECKOUT DISPATCH & WHATSAPP BILLING HANDOFF                       │
│  * Fills localized Indian shipping address (Pune, Maharashtra, 411014)      │
│  * Validates WhatsApp API deep-link payload generation:                     │
│    https://api.whatsapp.com/send?phone=...&text=Order%20ORD-9921...         │
└─────────────────────────────────────────────────────────────────────────────┘
Case Study Goal: Build a fast, maintainable suite testing the entire retail customer funnel from category search to order dispatch in under 2 seconds per scenario.
Real-Time Example 1: Dynamic Product Catalog & Faceted Filter Component
Model faceted category filtering using a CatalogFilterComponent. Filter apparel by category (Men, Women, Kids), price threshold, and fabric material, asserting matching card counts.
Python (components/catalog_filter.py)
from typing import List
from playwright.sync_api import Locator, Page, sync_playwright, expect

class CatalogFilterComponent:
    """Component Object encapsulating multi-attribute sidebar filters."""

    def __init__(self, root: Locator):
        self.root: Locator = root
        self.category_select: Locator = self.root.locator("select#filter-category")
        self.fabric_checkboxes: Locator = self.root.locator("input[name='fabric']")
        self.price_slider: Locator = self.root.locator("input#max-price")
        self.apply_button: Locator = self.root.locator("button#apply-filters")

    def filter_by(self, category: str, fabric: str, max_price: int) -> None:
        self.category_select.select_option(label=category)
        self.root.locator(f"input[name='fabric'][value='{fabric}']").check()
        self.price_slider.fill(str(max_price))
        self.apply_button.click()

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()

    page.set_content("""
        
All Products
12 Products Found
""") filters = CatalogFilterComponent(page.locator("#sidebar-filters")) filters.filter_by(category="Women", fabric="Pashmina", max_price=5000) expect(page.locator("#result-badge")).to_have_text("Filtered: Women | Pashmina | Max ₹5000") expect(page.locator("#card-count")).to_have_text("4 Products Found") print(f"Filter successfully applied: '{page.locator('#result-badge').inner_text()}'") browser.close()
Output: Filter successfully applied: 'Filtered: Women | Pashmina | Max ₹5000'
Real-Time Example 2: Slide-Out Mini-Cart Drawer & LocalStorage State Verification
Test modern retail slide-out cart drawers: adding product variants updates the DOM slide-out drawer, recomputes subtotal, and serializes state to window.localStorage['cart_items'].
Python (Slide-Out Cart & LocalStorage Sync)
import json
from playwright.sync_api import sync_playwright, expect

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()

    page.set_content("""
        

Authentic Kashmiri Embroidered Shawl

₹ 4,500
""") # 1. Trigger Add to Cart page.locator("#add-to-cart-btn").click() # 2. Verify Slide-Out Drawer rendered with auto-waiting cart_drawer = page.locator("#cart-drawer") expect(cart_drawer).to_be_visible() expect(cart_drawer.locator("#drawer-subtotal")).to_have_text("₹ 4,500") # 3. Assert LocalStorage persistence raw_storage = page.evaluate("() => localStorage.getItem('cart_items')") cart_data = json.loads(raw_storage) print(f"Cart Drawer Opened: Subtotal = '{cart_drawer.locator('#drawer-subtotal').inner_text()}'") print(f"LocalStorage Verified: SKU={cart_data[0]['id']} | Qty={cart_data[0]['qty']}") assert cart_data[0]["id"] == "SKU-KASH-01" assert cart_data[0]["price"] == 4500 browser.close()
Output: Cart Drawer Opened: Subtotal = '₹ 4,500' LocalStorage Verified: SKU=SKU-KASH-01 | Qty=1
Real-Time Example 3: Promo Code Engine with Network Route Mocking
Validate coupon discount logic without touching production billing backends: intercept promo validation endpoints using page.route() and fulfill dynamic tier calculations.
Python (Promo Code Validation & Route Mocking)
import json
from playwright.sync_api import sync_playwright, expect

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()

    # Intercept coupon validation API
    def handle_coupon_validation(route):
        payload = json.loads(route.request.post_data)
        coupon = payload.get("coupon", "").upper()

        if coupon == "KASHMIR15":
            route.fulfill(
                status=200,
                content_type="application/json",
                body=json.dumps({"valid": True, "discount_pct": 15, "code": "KASHMIR15"})
            )
        else:
            route.fulfill(
                status=400,
                content_type="application/json",
                body=json.dumps({"valid": False, "message": "Invalid or expired promo code"})
            )

    page.route("**/api/checkout/validate-coupon", handle_coupon_validation)

    page.set_content("""
        

Order Summary

Subtotal: ₹ 10,000
Final: ₹ 10,000
""") # Apply valid promo code page.locator("#coupon-input").fill("KASHMIR15") page.locator("#apply-btn").click() expect(page.locator("#discount-label")).to_have_text("Discount (15%): -₹ 1,500") expect(page.locator("#final-total")).to_have_text("Final: ₹ 8,500") print(f"Promo Engine Verified: '{page.locator('#discount-label').inner_text()}' -> {page.locator('#final-total').inner_text()}") browser.close()
Output: Promo Engine Verified: 'Discount (15%): -₹ 1,500' -> Final: ₹ 8,500
Real-Time Example 4: Localized Indian Checkout Form with Faker & Pydantic DTO
Populate checkout shipping details using Faker's en_IN localized generator and validate the structured payload using a typed Pydantic customer schema.
Python (Localized Checkout Form Submission)
from faker import Faker
from pydantic import BaseModel, Field
from playwright.sync_api import sync_playwright, expect

fake = Faker("en_IN")

class ShippingDetailsDTO(BaseModel):
    full_name: str
    phone: str = Field(min_length=10)
    address_line: str
    city: str
    state: str
    pin_code: str = Field(pattern=r"^\d{6}$")

# Generate synthetic localized Indian customer data
customer_address = ShippingDetailsDTO(
    full_name=fake.name(),
    phone="+91 98220 12345",
    address_line=fake.street_address(),
    city="Pune",
    state="Maharashtra",
    pin_code="411014"
)

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()

    page.set_content("""
        

Shipping Destination













""") # Fill form fields from strongly typed DTO page.locator("#name").fill(customer_address.full_name) page.locator("#phone").fill(customer_address.phone) page.locator("#address").fill(customer_address.address_line) page.locator("#city").fill(customer_address.city) page.locator("#state").fill(customer_address.state) page.locator("#pin").fill(customer_address.pin_code) page.locator("#save-btn").click() confirmed_display = page.locator("#confirmed-view") expect(confirmed_display).to_contain_text(customer_address.city) expect(confirmed_display).to_contain_text(customer_address.pin_code) print(f"Address Confirmed: '{confirmed_display.inner_text()}'") browser.close()
Output: Address Confirmed: 'Delivering to: Pooja Patil, Pune - 411014'
Real-Time Example 5: WhatsApp Direct Billing Link & Payload Verification
Many retail businesses dispatch orders via WhatsApp messaging links. Catch the generated api.whatsapp.com/send intent, decode the URI query parameters, and assert the order invoice structure.
Python (WhatsApp Order Handoff Assertion)
import urllib.parse
from playwright.sync_api import sync_playwright, expect

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()

    order_id = "ORD-KASHMIR-9921"
    item_title = "Traditional Silk Pashmina"
    final_amount = "₹ 4,500"

    page.set_content(f"""
        

Order Placed Successfully!

{order_id}

Complete your booking and confirm sizing directly on WhatsApp:

Order via WhatsApp
""") whatsapp_link = page.locator("#whatsapp-order-link") href_value = whatsapp_link.get_attribute("href") # Parse and decode URL parameters parsed_url = urllib.parse.urlparse(href_value) query_params = urllib.parse.parse_qs(parsed_url.query) message_text = query_params["text"][0] print("WhatsApp Order Dispatch Link Verified:") print(f" Target Phone : +{query_params['phone'][0]}") print(f" Decoded Message: '{message_text}'") assert "919876543210" in query_params["phone"][0] assert order_id in message_text assert "Traditional Silk Pashmina" in message_text browser.close()
Output: WhatsApp Order Dispatch Link Verified: Target Phone : +919876543210 Decoded Message: 'Hello Kashmir Fancy House, I placed order ORD-KASHMIR-9921 for Traditional Silk Pashmina worth ₹ 4,500.'
Real-Time Example 6: Fast-Track Checkout: API Cart Seeding + Targeted UI Purchase
Apply the API-UI hybrid pattern: seed 3 items into the customer's cart in 40ms via direct REST API, then launch the browser directly at /checkout to execute the final payment click.
Python (API Cart Seeding + Direct Checkout UI)
from playwright.sync_api import sync_playwright, expect

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    context = browser.new_context()

    # 1. API PRECONDITION: Seed cart directly via context.request in 40ms
    seed_res = context.request.post(
        "https://httpbin.org/post",
        data={
            "user_id": "CUST-9921",
            "cart": [
                {"sku": "SUIT-01", "name": "Kashmiri Tilla Suit", "price": 6500},
                {"sku": "SHAWL-02", "name": "Pure Wool Shawl", "price": 3500}
            ],
            "subtotal": 10000
        }
    )
    expect(seed_res).to_be_ok()
    print("[API Seed] Cart seeded with 2 apparel items in 35ms.")

    # 2. UI LAUNCH: Navigate directly to checkout page (zero form navigation)
    page = context.new_page()
    page.set_content("""
        

Checkout Overview

2 Items in Cart
Total: ₹ 10,000
""") # 3. Complete purchase page.locator("#pay-btn").click() confirmation = page.locator("#confirmation-card h3") expect(confirmation).to_have_text("Order #ORD-SUCCESS-8841 Placed!") print(f"[UI Finalized] Purchase complete: '{confirmation.inner_text()}'") context.close() browser.close()
Output: [API Seed] Cart seeded with 2 apparel items in 35ms. [UI Finalized] Purchase complete: 'Order #ORD-SUCCESS-8841 Placed!'
Real-Time Example 7: Inventory Concurrency & Out-of-Stock Edge Case
Test inventory race conditions: when two concurrent users attempt to purchase the last available apparel item, verify that User B receives a clean out-of-stock notification banner.
Python (Inventory Race Condition Simulation)
from playwright.sync_api import sync_playwright, expect

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)

    # USER A (Purchases last item)
    ctx_a = browser.new_context()
    page_a = ctx_a.new_page()

    # USER B (Attempts to purchase immediately after)
    ctx_b = browser.new_context()
    page_b = ctx_b.new_page()

    inventory_html = """
        

Exclusive Pashmina Shawl (Last 1 in Stock)

Available
""" page_a.set_content(inventory_html) page_b.set_content(inventory_html) # Initialize shared stock in both contexts page_a.evaluate("() => { window.STOCK_COUNT = 1; }") page_b.evaluate("() => { window.STOCK_COUNT = 0; }") # Stock depleted by User A # User A clicks Buy Now page_a.locator("#buy-btn").click() expect(page_a.locator("#msg")).to_have_text("PURCHASE_SUCCESSFUL") print(f"User A Transaction: '{page_a.locator('#msg').inner_text()}'") # User B attempts to click Buy Now page_b.locator("#buy-btn").click() expect(page_b.locator("#msg")).to_have_text("OUT_OF_STOCK_ERROR") print(f"User B Concurrency Guard: '{page_b.locator('#msg').inner_text()}'") ctx_a.close() ctx_b.close() browser.close()
Output: User A Transaction: 'PURCHASE_SUCCESSFUL' User B Concurrency Guard: 'OUT_OF_STOCK_ERROR'
Real-Time Example 8: Allure BDD Test Suite for Retail Storefronts
Organize retail purchasing tests with Allure BDD annotations, mapping test cases to Epics (Storefront Sales), Features (Order Placement), and Stories (WhatsApp Handoff).
Python (tests/e2e/test_storefront_bdd.py)
import allure
import pytest
from playwright.sync_api import Page, expect

@allure.epic("E-Commerce Storefront Operations")
@allure.feature("Customer Checkout")
class TestStorefrontCheckout:

    @allure.story("WhatsApp Order Billing Integration")
    @allure.severity(allure.severity_level.CRITICAL)
    @allure.title("Verify customer order generates valid WhatsApp dispatch link")
    def test_whatsapp_order_integration(self, page: Page):
        with allure.step("1. Seed apparel items and navigate to checkout summary"):
            page.set_content("""
                

Kashmir Fancy House Order #9942

WhatsApp Order
""") with allure.step("2. Assert WhatsApp dispatch link target and phone payload"): wa_btn = page.locator("#wa-btn") expect(wa_btn).to_be_visible() href = wa_btn.get_attribute("href") assert "api.whatsapp.com" in href assert "919876543210" in href with allure.step("3. Attach verified WhatsApp intent link to Allure report"): allure.attach(href, name="Verified_WhatsApp_Intent_URL", attachment_type=allure.attachment_type.TEXT) print("Allure BDD Retail Story executed and logged with step attachments!")
Allure Dashboard Result: Epic: E-Commerce Storefront Operations -> Feature: Customer Checkout * Story: WhatsApp Order Billing Integration [Severity: CRITICAL] -> PASSED * Attachment: Verified_WhatsApp_Intent_URL
Real-Time Example 9: E-Commerce Automation Patterns Reference Matrix
A comprehensive reference summary contrasting common retail automation challenges with Playwright Python best practice solutions.
Retail Testing Patterns Reference Matrix
E-COMMERCE AUTOMATION CHALLENGES & PLAYWRIGHT SOLUTIONS:
┌──────────────────────────────┬──────────────────────────────────────────┬────────────────────────────────────────────┐
│ Retail Testing Challenge     │ Anti-Pattern (Slow / Brittle)            │ Recommended Playwright Solution            │
├──────────────────────────────┼──────────────────────────────────────────┼────────────────────────────────────────────┤
│ Pre-populating User Cart     │ Clicking 10 search & add forms in UI     │ Seed via APIRequestContext in 40ms         │
│ Slide-out Mini-Cart Timing   │ Inserting arbitrary time.sleep(3) pauses │ Auto-waiting: expect(drawer).to_be_visible │
│ Promo Code & Tax Calculation │ Relying on unstable live promo gateways  │ Mock response via page.route()             │
│ Regional Shipping Address    │ Static hardcoded "123 Main St" strings   │ Localized Faker("en_IN") + Pydantic DTO    │
│ Third-Party WhatsApp Billing │ Trying to automate WhatsApp Web UI       │ Assert generated deep-link & query text    │
│ Out-of-Stock Race Conditions │ Untested concurrency assumptions         │ Simulate two BrowserContexts in parallel   │
│ Visual Variant Badging       │ Fragile CSS color string checks          │ expect(card).to_have_screenshot()          │
└──────────────────────────────┴──────────────────────────────────────────┴────────────────────────────────────────────┘
Engineering Best Practice: Fast-track retail testing by seeding shopping carts via API, isolating mini-cart components via root locator chaining, and validating external messaging handoffs (like WhatsApp or payment gateways) through URL parameter assertion.