Command Palette

Search for a command to run...

UnylyUnyly
Browse all

Playwright Babyrefil

FreeNot checked

A production-ready, professional E2E test automation framework built with Playwright and Pytest.

GitHubEmbed

About

A production-ready, professional E2E test automation framework built with Playwright and Pytest.

README

Python Version Playwright Pytest License

A production-ready, professional E2E test automation framework built with Playwright and Pytest. Includes best practices, proper fixtures, and a complete test suite for the web application Babyrefil.

📋 Table of Contents

📋 Prerequisites

  • Python 3.11+ - Download here
  • pip - Comes with Python
  • Git - For cloning the repository

🚀 Quick Start

1. Clone & Setup

# Clone the repository
git clone https://github.com/TestBeyond/playwright-pytest.git
cd playwright-pytest

# Create virtual environment (recommended)
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt

# Install Playwright browsers (one-time setup)
python -m playwright install

2. Run Your First Test

# Run all E2E tests
pytest -m e2e

# Run a specific test
pytest tests/e2e/test_home.py::test_home_loads_successfully

📁 Project Structure

playwright-pytest/
├── tests/                          # Test suite root
│   ├── conftest.py                # Pytest configuration & fixtures
│   ├── __init__.py                # Package marker
│   └── e2e/                       # End-to-end tests
│       ├── __init__.py            # Package marker
│       ├── flows.py               # Shared test helpers & navigation flows
│       ├── test_home.py           # Home page tests
│       ├── test_navigation.py     # Navigation & back button tests
│       ├── test_subscription_success.py    # Successful subscription flows
│       ├── test_payment_failure.py         # Payment error handling
│       ├── test_required_fields_validation.py  # Required field validation
│       ├── test_format_validation.py           # Format & input validation
│       └── test_error_recovery.py             # Error recovery flows
├── Support/                       # Test utilities & data
│   ├── __init__.py               # Package marker
│   └── test_data.py              # Centralized test constants
├── requirements.txt              # Python dependencies
├── pytest.ini                    # Pytest configuration
├── IMPROVEMENTS.md               # Detailed cleanup report
└── README.md                     # This file

Key Components

File Purpose
tests/conftest.py Pytest fixtures providing page instance for each test
tests/e2e/flows.py Reusable helper functions for common test scenarios
Support/test_data.py Centralized test constants (URLs, card numbers, etc.)
pytest.ini Pytest settings, test discovery, markers

🤖 MCP Usage

This project includes a Playwright MCP (Model Context Protocol) integration for AI-assisted test automation. The MCP workflow provides a structured approach to test development:

MCP Workflow Overview

Phase 1: Manual Exploration

  • Execute test scenarios step-by-step using Playwright MCP tools
  • Analyze HTML structure and interactive elements
  • Document accessible attributes (roles, labels, text content)
  • Identify element relationships and behaviors
  • No code is written during this phase

Phase 2: Implementation

  • Create Playwright + PyTest tests based on MCP observations
  • Use semantic selectors discovered during exploration
  • Execute and iterate until tests pass
  • Document test cases with clear docstrings

Key MCP Principles

Locator Priority:

  1. get_by_role() - Accessible names (preferred)
  2. get_by_label() - Form labels
  3. get_by_placeholder() - Input placeholders
  4. get_by_text() - Visible text
  5. get_by_test_id() - Last resort only

Assertion Rules:

  • Use native Playwright assertions with auto-retry
  • Trust Playwright's auto-waiting mechanism
  • Never use Python assert directly
  • Avoid unnecessary timeouts

Test Independence:

  • Each test creates its own initial state
  • Tests run in any order
  • No dependencies between tests
  • Complete isolation

MCP Configuration

The project includes a standardized prompt at prompts/sdet-automator.prompt.md that guides AI agents through proper test development:

# Reference the SDET Playwright MCP prompt
cat prompts/sdet-automator.prompt.md

This ensures consistent, high-quality test automation across the project.

🧪 Running Tests

Basic Commands

# Run all E2E tests
pytest -m e2e

# Run specific test file
pytest tests/e2e/test_subscription_success.py

# Run specific test function
pytest tests/e2e/test_subscription_success.py::test_ct001_successful_subscription

# Run tests matching a pattern
pytest -k "payment"

Advanced Options

# Verbose output
pytest -m e2e -v

# Show print statements
pytest -m e2e -s

# Stop on first failure
pytest -m e2e -x

# Run last failed tests
pytest -m e2e --lf

# Headed mode (visual browser)
pytest -m e2e --headed

# Specific browser
pytest -m e2e --browser firefox

# Headed + specific browser
pytest -m e2e --headed --browser firefox

# Generate HTML report
pytest -m e2e --html=report.html

� Test Organization

Test Categories (19 Total)

The test suite is organized by functionality:

✅ Subscription Success (4 tests)

  • test_ct001 - Successful subscription with Essential plan
  • test_ct003 - Successful subscription with Conforto (popular) plan
  • test_ct004 - Successful subscription with biweekly recurrence
  • test_ct009 - Successful subscription with Completo plan

❌ Payment Failure (1 test)

  • test_ct002 - Payment declined due to insufficient funds

🔙 Navigation (1 test)

  • test_ct007 - Back button navigation between steps

✔️ Format Validation (8 tests)

  • test_ct006 - Invalid postal code handling
  • test_ct008 - Invalid email format validation
  • test_ct010 - Invalid card number validation
  • test_ct011 - Invalid CVV validation
  • test_ct012 - Invalid card expiry validation
  • test_ct013 - Invalid phone format validation
  • test_ct014 - Invalid CPF validation

📋 Required Fields (4 tests)

  • test_ct005 - Required fields validation (personal data)
  • test_ct015 - Required address number validation
  • test_ct016 - Required baby age validation
  • test_ct017 - Empty card fields validation

🔄 Error Recovery (1 test)

  • test_ct018 - Multiple payment attempts after error

✍️ Writing Tests

Basic Test Pattern

import pytest
from playwright.sync_api import expect
from Support.test_data import BASE_URL
from tests.e2e.flows import go_to_plan_selection

@pytest.mark.e2e
def test_my_feature(page):
    """
    Test description following pytest conventions.
    Use docstrings to explain what's being tested.
    """
    # Arrange
    page.goto(BASE_URL)
    
    # Act
    go_to_plan_selection(page)
    
    # Assert
    expect(page).to_have_title("BabyRefil - Clube de Assinatura de Fraldas")

Using Shared Helpers

Reuse functions from tests/e2e/flows.py to avoid duplication:

from tests.e2e.flows import (
    go_to_personal_data_with_essential_plan,
    fill_personal_data,
    advance_to_payment,
    fill_valid_card,
    submit_payment,
)

@pytest.mark.e2e
def test_complete_subscription_flow(page):
    """Test complete subscription from plan selection to payment."""
    # Navigate to personal data step with essential plan
    go_to_personal_data_with_essential_plan(page)
    
    # Fill personal information
    fill_personal_data(
        page,
        full_name="João Silva",
        email="[email protected]",
        phone="11999999999",
        baby_name="Maria Silva",
    )
    
    # Complete payment
    advance_to_payment(page)
    fill_valid_card(page, holder_name="João Silva")
    submit_payment(page)
    
    # Verify success
    expect(page.get_by_text("Assinatura confirmada!")).to_be_visible()

Test Data Constants

Always use centralized constants from Support/test_data.py:

from Support.test_data import (
    BASE_URL,
    POSTAL_CODE,
    ADDRESS_NUMBER,
    VALID_CARD,
    CVV,
    CPF,
)

# ❌ Don't hardcode
page.goto("https://babyrefil.vercel.app")

# ✅ Do use constants
page.goto(BASE_URL)

Assertion Patterns

Use Playwright's locators and expectations:

from playwright.sync_api import expect

# Page-level assertions
expect(page).to_have_title("Expected Title")
expect(page).to_have_url("https://example.com")

# Element visibility
expect(page.get_by_role("button", name="Submit")).to_be_visible()

# Input values
expect(page.get_by_role("textbox", name="Email")).to_have_value("[email protected]")

# Text content
expect(page.get_by_text("Success Message")).to_be_visible()

# Multiple conditions
expect(page.get_by_role("button", name="Submit")).to_be_enabled()
expect(page.get_by_role("button", name="Submit")).to_be_visible()

🐛 Debugging

Interactive Inspector

Stop test execution and inspect elements in real-time:

# Run test with Playwright Inspector
PWDEBUG=1 pytest tests/e2e/test_home.py::test_home_loads_successfully

# Or
pwdebug=true pytest -k test_name

Pausing Execution

Add pause points in your test code:

@pytest.mark.e2e
def test_with_pause(page):
    page.goto(BASE_URL)
    page.pause()  # Execution pauses here - inspect the browser
    # ... rest of test

Screenshots & Trace

# Take screenshot
page.screenshot(path="screenshot.png")

# Start trace recording
page.context.tracing.start(screenshots=True, snapshots=True)
# ... test code ...
page.context.tracing.stop(path="trace.zip")

Verbose Output

# Show print statements and detailed info
pytest -m e2e -s -v

# Show network requests (requires additional setup)
# See Playwright documentation for more details

Common Debugging Commands

# Run with detailed error messages
pytest -m e2e -vv

# Run single test with pause
pytest tests/e2e/test_home.py::test_home_loads_successfully -s

# Debug mode with inspector
PWDEBUG=1 pytest tests/e2e/test_home.py -s

# Keep browser open after test (for headed mode)
pytest -m e2e --headed

✨ Best Practices

1. Use Semantic Selectors

# ❌ Brittle - depends on structure
page.locator("div.container > button:nth-child(2)").click()

# ✅ Robust - semantic and stable
page.get_by_role("button", name="Subscribe").click()
page.get_by_label("Email").fill("[email protected]")

2. Organize Tests Logically

@pytest.mark.e2e
def test_feature_happy_path(page):
    """Test the successful/happy path."""
    pass

@pytest.mark.e2e
def test_feature_error_handling(page):
    """Test error scenarios."""
    pass

3. Use Helper Functions

# In tests/e2e/flows.py
def navigate_to_checkout(page: Page) -> None:
    """Navigate to checkout page."""
    page.goto(BASE_URL)
    page.get_by_role("button", name="Checkout").click()
    expect(page).to_have_url(f"{BASE_URL}/checkout")

# In test file
def test_checkout_flow(page):
    navigate_to_checkout(page)
    # Continue with test

4. Centralize Test Data

All static test data should live in Support/test_data.py:

# Support/test_data.py
BASE_URL = "https://babyrefil.vercel.app"
VALID_CARD = "4242424242424242"
INVALID_CARD = "5555555555554444"

# Then use in tests
from Support.test_data import VALID_CARD, INVALID_CARD

5. Clear Test Names

Use descriptive names following the pattern: test_ct{number}_{feature}_{scenario}

# ❌ Vague
def test_form():
    pass

# ✅ Clear
def test_ct001_successful_subscription():
    pass

6. Add Docstrings

@pytest.mark.e2e
def test_ct001_successful_subscription(page):
    """
    CT001: Successful Subscription (Complete Flow)
    
    Validate the successful subscription flow from plan selection
    to payment confirmation. Verifies all steps complete without errors.
    """
    pass

7. Wait for Elements Properly

from playwright.sync_api import expect

# Playwright handles waits automatically with expect
expect(page.get_by_text("Loaded")).to_be_visible()

# Or explicit timeout
page.get_by_role("button").click(timeout=5000)

🔧 Configuration

pytest.ini

[pytest]
pythonpath = .
testpaths = tests
markers =
    e2e: end-to-end test

conftest.py Fixtures

The tests/conftest.py provides:

  • page - Chromium page instance with automatic lifecycle management
    • Automatically creates browser instance before each test
    • Automatically closes page and browser after each test
    • Type-hinted for IDE support

📦 Dependencies

Current dependencies in requirements.txt:

pytest>=8.0.0       # Test framework
playwright>=1.40.0  # Browser automation

Update dependencies:

pip install --upgrade -r requirements.txt

🆘 Troubleshooting

"ModuleNotFoundError: No module named 'playwright'"

pip install playwright
python -m playwright install

"ModuleNotFoundError: No module named 'tests.e2e'"

# Ensure pythonpath is set in pytest.ini
# Run pytest from project root directory
cd playwright-pytest
pytest -m e2e

Tests Won't Run

# Check if tests are discovered
pytest --collect-only -q

# Run with verbose error output
pytest -m e2e -vv

Browser Not Launching

# Reinstall Playwright and browsers
pip uninstall playwright
pip install playwright
python -m playwright install

� Additional Resources

📄 Project Info

  • Framework: Playwright + Pytest
  • Language: Python 3.11+
  • Browser: Chromium (default, supports Firefox, WebKit)
  • Status: Production Ready ✅
  • Tests: 19 comprehensive E2E tests
  • Last Updated: November 2025

Developed by Rafael Manso

from github.com/rafaeltmanso/playwright-babyrefil

Installing Playwright Babyrefil

This server has no published package — it is built from source. Open the repository and follow its README.

▸ github.com/rafaeltmanso/playwright-babyrefil

FAQ

Is Playwright Babyrefil MCP free?

Yes, Playwright Babyrefil MCP is free — one-click install via Unyly at no cost.

Does Playwright Babyrefil need an API key?

No, Playwright Babyrefil runs without API keys or environment variables.

Is Playwright Babyrefil hosted or self-hosted?

Self-hosted: the server runs locally on your machine via the install command above.

How do I install Playwright Babyrefil in Claude Desktop, Claude Code or Cursor?

Open Playwright Babyrefil on unyly.org, pick your client tab (Claude Desktop, Claude Code, Cursor) and press Install — the config is generated automatically, no JSON editing.

Related MCPs

Compare Playwright Babyrefil with

Not sure what to pick?

Find your stack in 60 seconds

Author?

Embed badge for your README

Browse similar

All browse MCPs