🛍️ 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.
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... │
└─────────────────────────────────────────────────────────────────────────────┘
CatalogFilterComponent. Filter apparel by category (Men, Women, Kids), price threshold, and fabric material, asserting matching card counts.
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()
window.localStorage['cart_items'].
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()
page.route() and fulfill dynamic tier calculations.
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()
en_IN localized generator and validate the structured payload using a typed Pydantic customer schema.
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("""
""")
# 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()
api.whatsapp.com/send intent, decode the URI query parameters, and assert the order invoice structure.
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()
/checkout to execute the final payment click.
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()
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()
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!")
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() │
└──────────────────────────────┴──────────────────────────────────────────┴────────────────────────────────────────────┘