🏭 Why Use Data Factories & Synthetic Generators?
Hardcoding static values in automated test scripts (such as "testuser@gmail.com" or "Invoice #123") is a major cause of test suite degradation. Static test data causes unique constraint violations when tests run in parallel, pollutes databases, and masks boundary bugs by testing with only one fixed string length or character set. Test Data Factories combined with the Python Faker library create dynamic, realistic, and collision-free test data on demand. By pairing Playwright UI and API automation with data factory patterns, tests generate fresh phone numbers, addresses, financial records, and user personas instantly with realistic formatting, localized language support, and full deterministic control when needed.
STATIC HARDCODED PATTERN (Anti-Pattern: Collisions, Stale State, Brittle):
[ Test Run 1: user="aarav@test.com" ] ──► [ DB Unique Error on Run 2! ] ──► FAILS
FACTORY & FAKER GENERATION TOPOLOGY (Dynamic, Isolated & Collision-Free):
┌─────────────────────────────────────────────────────────────────────────────┐
│ 1. Factory Definition (UserFactory / OrderFactory) │
│ * Uses Faker providers: faker.name(), faker.ascii_company_email() │
│ * Produces clean Pydantic DTOs or Python dicts with unique timestamps │
└─────────────────────────────────────────────────────────────────────────────┘
│
┌─────────────────────────────┴─────────────────────────────┐
▼ ▼
[ Playwright API Precondition ] [ Playwright UI Form Fill ]
* context.request.post("/api/users", * page.locator("#email").fill(
data=UserFactory.build() user_data.email
) ──► Creates user in 20ms ) ──► Type realistic input
faker.Faker() and fill a modern registration form with Playwright.
from faker import Faker
from playwright.sync_api import sync_playwright, expect
fake = Faker()
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
# Generate synthetic user credentials
synthetic_user = {
"full_name": fake.name(),
"email": fake.unique.ascii_company_email(),
"phone": fake.phone_number(),
"company": fake.company()
}
page.set_content("""
""")
# Populate form inputs using generated values
page.locator("#name").fill(synthetic_user["full_name"])
page.locator("#email").fill(synthetic_user["email"])
page.locator("#phone").fill(synthetic_user["phone"])
page.locator("#company").fill(synthetic_user["company"])
page.locator("#submit-btn").click()
confirmation = page.locator("#confirmation")
expect(confirmation).to_have_text(f"REGISTERED: {synthetic_user['full_name']}")
print("Synthetic User Form Entry Verified:")
print(f" Name : {synthetic_user['full_name']}")
print(f" Email : {synthetic_user['email']}")
print(f" Company : {synthetic_user['company']}")
print(f" Result : {confirmation.inner_text()}")
browser.close()
en_IN) to generate genuine Indian addresses, PIN codes, states, and mobile phone structures.
from faker import Faker
from playwright.sync_api import sync_playwright, expect
# Initialize Faker with English (India) locale provider
fake_in = Faker("en_IN")
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
# Generate regional Indian logistics address data
regional_address = {
"recipient": fake_in.name(),
"street": fake_in.street_address(),
"city": fake_in.city(),
"state": fake_in.state(),
"postal_code": fake_in.postcode()
}
page.set_content("""
Shipping Consignment
""")
page.evaluate("""data => {
document.getElementById('rec').innerText = data.recipient;
document.getElementById('addr').innerText = `${data.street}, ${data.city}, ${data.state}`;
document.getElementById('pin').innerText = `PIN: ${data.postal_code}`;
}""", regional_address)
rec_tag = page.locator("#rec")
pin_tag = page.locator("#pin")
expect(rec_tag).to_have_text(regional_address["recipient"])
print("Localized Indian Consignment Address Rendered:")
print(f" Recipient : {rec_tag.inner_text()}")
print(f" Location : {page.locator('#addr').inner_text()}")
print(f" PIN Code : {pin_tag.inner_text()}")
browser.close()
BaseModel with factory class methods that provide realistic default values while allowing explicit field overrides.
import random
from typing import Optional
from faker import Faker
from pydantic import BaseModel, Field
from playwright.sync_api import sync_playwright, expect
fake = Faker()
class CustomerAccountDTO(BaseModel):
account_id: str
contact_name: str
email: str
credit_limit_inr: float = Field(gt=0)
is_vip: bool
region: str
class CustomerFactory:
"""Factory generating realistic Customer DTOs with override capabilities."""
@classmethod
def build(cls, **kwargs) -> CustomerAccountDTO:
defaults = {
"account_id": f"ACC-{fake.unique.random_number(digits=5)}",
"contact_name": fake.name(),
"email": fake.unique.ascii_safe_email(),
"credit_limit_inr": round(random.uniform(25000, 150000), 2),
"is_vip": random.choice([True, False]),
"region": "West-India-Pune"
}
# Merge keyword argument overrides
defaults.update(kwargs)
return CustomerAccountDTO(**defaults)
with sync_playwright() as p:
api = p.request.new_context(base_url="https://httpbin.org")
# Generate customer with default fake attributes
customer_1 = CustomerFactory.build()
# Generate customer with specific field overrides
customer_2 = CustomerFactory.build(is_vip=True, credit_limit_inr=500000.0)
res = api.post("/post", data=customer_1.model_dump())
expect(res).to_be_ok()
print("Generated Dynamic Customers:")
print(f" Customer 1 : {customer_1.account_id} | {customer_1.contact_name} (VIP: {customer_1.is_vip})")
print(f" Customer 2 : {customer_2.account_id} | {customer_2.contact_name} (VIP: {customer_2.is_vip}, Credit: ₹ {customer_2.credit_limit_inr})")
assert customer_1.account_id != customer_2.account_id
assert customer_2.credit_limit_inr == 500000.0
api.dispose()
factory_boy library to model parent-child relationships, sequential ID generators, and lazy Faker evaluations.
import factory
from faker import Faker
from playwright.sync_api import sync_playwright, expect
fake = Faker()
class OrderItem:
def __init__(self, sku, description, quantity, price):
self.sku = sku
self.description = description
self.quantity = quantity
self.price = price
class OrderItemFactory(factory.Factory):
class Meta:
model = OrderItem
sku = factory.Sequence(lambda n: f"SKU-RELAY-{n + 1000}")
description = factory.Faker("catch_phrase")
quantity = factory.Faker("random_int", min=1, max=10)
price = factory.Faker("pyfloat", left_digits=4, right_digits=2, positive=True)
with sync_playwright() as p:
api = p.request.new_context(base_url="https://httpbin.org")
# Generate a list of 3 sequential synthetic order line items
line_items = OrderItemFactory.build_batch(3)
payload = {
"order_ref": "ORD-BATCH-2026",
"items": [item.__dict__ for item in line_items]
}
response = api.post("/post", data=payload)
expect(response).to_be_ok()
created_items = response.json()["json"]["items"]
print(f"Factory Boy Batch Created {len(created_items)} Distinct Items:")
for it in created_items:
print(f" {it['sku']:14s} | Qty: {it['quantity']:2d} | Rate: ₹ {it['price']}")
assert created_items[0]["sku"] == "SKU-RELAY-1000"
assert created_items[1]["sku"] == "SKU-RELAY-1001"
api.dispose()
Faker.seed(seed_value) to generate the exact same synthetic values deterministically during bug reproduction.
from faker import Faker
def generate_user_batch(seed_number: int):
# Set seed to guarantee identical generation sequence
Faker.seed(seed_number)
f = Faker()
return [f.name() for _ in range(3)]
# Run A with Seed 2026
batch_a = generate_user_batch(2026)
# Run B with Seed 2026
batch_b = generate_user_batch(2026)
# Run C with a Different Seed
batch_c = generate_user_batch(9999)
print("Batch A (Seed 2026):", batch_a)
print("Batch B (Seed 2026):", batch_b)
print("Batch C (Seed 9999):", batch_c)
assert batch_a == batch_b
assert batch_a != batch_c
print("Deterministic seeding confirmed: Batch A matches Batch B identically!")
from faker import Faker
from playwright.sync_api import sync_playwright, expect
fake = Faker()
def generate_financial_record():
return {
"transaction_id": f"TXN-{fake.uuid4()[:8].upper()}",
"card_number": fake.credit_card_number(card_type="mastercard"),
"card_expiry": fake.credit_card_expire(),
"amount": round(fake.pyfloat(left_digits=4, right_digits=2, positive=True), 2),
"currency": "INR",
"iban": fake.iban()
}
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
record = generate_financial_record()
page.set_content("""
Payment Ledger Transaction
""")
page.evaluate("""rec => {
document.getElementById('tx-id').innerText = rec.transaction_id;
document.getElementById('amount').innerText = `₹ ${rec.amount} ${rec.currency}`;
document.getElementById('iban').innerText = rec.iban;
}""", record)
tx_view = page.locator("#tx-id")
expect(tx_view).to_have_text(record["transaction_id"])
print("Financial Transaction Data Rendered:")
print(f" Txn Ref : {tx_view.inner_text()}")
print(f" Amount : {page.locator('#amount').inner_text()}")
print(f" IBAN : {page.locator('#iban').inner_text()}")
browser.close()
conftest.py, supplying fresh, isolated entity payloads to individual test functions automatically.
# content of conftest.py
import pytest
from faker import Faker
fake = Faker()
@pytest.fixture
def fake_partner_user():
"""Provides a fresh, unique synthetic user payload for each test."""
return {
"username": fake.unique.user_name(),
"first_name": fake.first_name(),
"last_name": fake.last_name(),
"email": fake.unique.email(),
"company": fake.company()
}
# content of tests/test_user_onboarding.py
from playwright.sync_api import Page, expect
def test_user_creation_workflow(page: Page, fake_partner_user: dict):
page.set_content(f"""
{fake_partner_user['first_name']} {fake_partner_user['last_name']}
{fake_partner_user['email']}
""")
badge = page.locator("#user-badge")
email = page.locator("#user-email")
expect(badge).to_contain_text(fake_partner_user["first_name"])
expect(email).to_have_text(fake_partner_user["email"])
print(f"Test executed with isolated fixture user: '{badge.inner_text()}' <{email.inner_text()}>")
APIRequestContext, then load the browser to verify UI rendering.
from faker import Faker
from playwright.sync_api import sync_playwright, expect
fake = Faker()
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
context = browser.new_context()
# 1. GENERATE payload using factory logic
seeded_ticket = {
"ticket_id": f"TICK-{fake.unique.random_number(digits=6)}",
"reporter": fake.name(),
"summary": fake.sentence(nb_words=6),
"priority": "HIGH"
}
# 2. SEED entity via APIRequestContext
api_res = context.request.post("https://httpbin.org/post", data=seeded_ticket)
expect(api_res).to_be_ok()
print(f"[API Setup] Record seeded in backend: {seeded_ticket['ticket_id']}")
# 3. VERIFY in Browser DOM
page = context.new_page()
page.set_content(f"""
{seeded_ticket['ticket_id']}
{seeded_ticket['summary']}
{seeded_ticket['reporter']}
""")
row = page.get_by_test_id(f"row-{seeded_ticket['ticket_id']}")
expect(row.locator(".summary")).to_have_text(seeded_ticket["summary"])
print(f"[UI Validation] Verified synthetic ticket rendered: '{row.locator('.summary').inner_text()}'")
context.close()
browser.close()
FAKER & DATA FACTORY API MATRIX:
┌──────────────────────────────┬──────────────────────────────┬─────────────────────────────────────────────────────────┐
│ Provider / Method │ Sample Output Value │ Primary Testing Use Case / Category │
├──────────────────────────────┼──────────────────────────────┼─────────────────────────────────────────────────────────┤
│ fake.name() │ "Pooja Patil" │ Full name generation for registration and user profiles.│
│ fake.unique.email() │ "p_patil99@example.com" │ Collision-free unique email addresses across tests. │
│ fake.phone_number() │ "+91 98220 12345" │ Localized mobile phone numbers and SMS validation. │
│ fake.street_address() │ "Flat 402, Shivajinagar" │ Shipping and physical billing street addresses. │
│ fake.postcode() / zip_code() │ "411014" │ Postal codes matching localized address regions. │
│ fake.company() │ "Nikita Infotech Systems" │ Corporate enterprise account and tenant names. │
│ fake.credit_card_number() │ "5424992144881023" │ Financial billing inputs and gateway checkout fields. │
│ fake.uuid4() │ "f47ac10b-58cc-4372-a567..." │ Unique GUIDs, correlation IDs, and transaction keys. │
│ fake.date_time_between() │ "2026-10-29 18:45:00" │ Date range filtering and ledger timestamp checks. │
│ Faker.seed(seed_val) │ Integer (e.g. 2026) │ Deterministic sequence reproduction for bug triaging. │
│ Faker("en_IN") │ Locale String │ Localized cultural formatting (India, UK, US, etc.). │
│ factory.Sequence(lambda n:.. │ "SKU-1001", "SKU-1002" │ Monotonically increasing sequential counters. │
└──────────────────────────────┴──────────────────────────────┴─────────────────────────────────────────────────────────┘