A comprehensive, enterprise-grade Python Playwright automation framework with modern features, type safety, and production-ready capabilities.
π New to the framework? Start with DOCS_STRUCTURE.md for a complete guide on finding the right documentation for your needs.
- Advanced Base Classes: Professional page object model with type-safe element interactions
- Parallel Execution: Run tests concurrently with configurable worker pools
- Comprehensive Reporting: HTML, JSON, JUnit XML, and Allure reports
- CI/CD Integration: Native support for GitHub Actions, GitLab CI, Jenkins
- Performance Monitoring: Built-in performance metrics and thresholds
- Accessibility Testing: WCAG compliance checking
- Visual Regression: Screenshot comparison and diff detection
- Security Testing: Basic security scans and vulnerability checks
- API Testing: REST/GraphQL/SOAP API testing capabilities
- Database Testing: PostgreSQL, MongoDB, Redis integration
- Mobile Testing: Appium integration for mobile automation
- Cross-browser Support: Chromium, Firefox, WebKit, Safari
- Data-driven Testing: CSV, JSON, Excel test data support
- Advanced Decorators: Retry, screenshot, performance, logging decorators
- Type Safety: Full Pydantic configuration validation
- Logging: Structured logging with multiple levels and formats
- Error Handling: Comprehensive error handling and recovery
- Notifications: Slack, Teams, Email notifications
- Cloud Integration: AWS, Azure, GCP support
- Docker Support: Containerized execution
- Monitoring: Real-time test execution monitoring
- Security: Secure credential management
- Python 3.12+
- Playwright browsers (auto-installed)
- Dependencies listed in
requirements.txt
- Clone the repository:
git clone <repository-url>
cd playwright-framework- Create virtual environment:
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate- Install dependencies:
pip install -r requirements.txt- Install Playwright browsers:
playwright install- Configure environment:
cp .env.example .env
# Edit .env with your configurationplaywright-framework/
βββ core/ # Core framework modules
β βββ __init__.py # Framework constants and metadata
β βββ base.py # Base classes (BaseTest, BasePage, BaseElement)
β βββ config.py # Configuration management (Pydantic)
β βββ runner.py # Advanced test runner
β βββ utils.py # Utility functions
βββ decorators/ # Test decorators
β βββ __init__.py # Professional decorators
βββ pages/ # Page object classes
β βββ __init__.py # Example page classes
βββ tests/ # Test files
β βββ test_examples.py # Example test cases
βββ config/ # Configuration files
βββ data/ # Test data files
βββ reports/ # Test reports and screenshots
βββ logs/ # Log files
βββ scripts/ # Utility scripts
βββ Dockerfile # Docker configuration
βββ docker-compose.yml # Docker Compose setup
βββ pytest.ini # Pytest configuration
βββ requirements.txt # Python dependencies
βββ .env.example # Environment variables template
βββ README.md # This file
# Application Settings
BASE_URL=https://example.com
ENVIRONMENT=staging
HEADLESS=false
# Browser Configuration
BROWSER_NAME=chromium
BROWSER_SLOW_MO=100
TIMEOUT=30000
# Test Execution
PARALLEL_WORKERS=4
RETRY_MAX_ATTEMPTS=3
SCREENSHOT_ON_FAILURE=true
VIDEO_ON_FAILURE=false
# Reporting
REPORTS_DIR=reports
LOG_LEVEL=INFO
# API Configuration
API_BASE_URL=https://api.example.com
API_TIMEOUT=10000
# Database Configuration
DB_HOST=localhost
DB_PORT=5432
DB_NAME=testdb
DB_USER=testuser
DB_PASSWORD=testpass
# Notifications
SLACK_WEBHOOK=https://hooks.slack.com/...
EMAIL_SMTP=smtp.gmail.com
EMAIL_USER=your-email@gmail.com
EMAIL_PASSWORD=your-password
# Cloud Configuration
AWS_REGION=us-east-1
AZURE_SUBSCRIPTION_ID=your-subscription-id
GCP_PROJECT_ID=your-project-idThe framework uses Pydantic for type-safe configuration. See core/config.py for all available options.
from core.base import BaseTest
from pages import LoginPage, DashboardPage
class TestLogin(BaseTest):
async def run_test(self):
# Navigate to login page
login_page = await self.navigate_to_page(LoginPage)
# Perform login
await login_page.login("user@example.com", "password")
# Verify dashboard
dashboard_page = DashboardPage(self.page)
assert await dashboard_page.is_loaded()from decorators import screenshot_on_failure, retry_on_failure, performance_monitor
class TestExample(BaseTest):
@screenshot_on_failure
@retry_on_failure(max_retries=3)
@performance_monitor
async def run_test(self):
# Your test code here
passfrom decorators import data_driven
class TestDataDriven(BaseTest):
@data_driven([
{"input": "value1", "expected": "result1"},
{"input": "value2", "expected": "result2"},
])
async def run_test(self, test_data):
# Test code using test_data
passfrom core.base import BasePage
class LoginPage(BasePage):
def _init_elements(self):
self.add_element("username", "#username")
self.add_element("password", "#password")
self.add_element("login_btn", "#login")
async def login(self, username, password):
await self.get_element("username").fill(username)
await self.get_element("password").fill(password)
await self.get_element("login_btn").click()# Sequential execution
python -m pytest tests/
# Parallel execution
python -m pytest tests/ -n 4
# Using the advanced runner
python core/runner.pypython -m pytest tests/test_login.py -vpython -m pytest tests/ -m "smoke"python core/runner.py --config config/test_config.json# HTML Report
python -m pytest tests/ --html=reports/html-report/index.html
# JUnit XML for CI/CD
python -m pytest tests/ --junitxml=reports/junit-xml/results.xml
# Allure Report
python -m pytest tests/ --alluredir=reports/allure-results
allure serve reports/allure-resultsfrom core.runner import TestSuiteConfig, AdvancedTestRunner
config = TestSuiteConfig(
name="Parallel Test Suite",
parallel_workers=4,
browser="chromium"
)
runner = AdvancedTestRunner(config)
results = await runner.run_suite()from core.utils import performance_utils
@performance_utils.measure_execution_time
async def my_test_function():
# Your test code
pass
# Check thresholds
performance_utils.check_performance_threshold(
actual_time, threshold, "page_load"
)from core.utils import APIUtilities
api = APIUtilities("https://api.example.com")
# Make requests
response = await api.get("/users/1")
assert response["status_code"] == 200
# POST request
data = {"name": "John", "email": "john@example.com"}
response = await api.post("/users", data)from core.utils import DatabaseUtilities
db = DatabaseUtilities("postgresql://user:pass@localhost/db")
# Execute queries
users = await db.execute_query("SELECT * FROM users")
assert len(users) > 0from core.utils import data_generator
# Generate test data
user = data_generator.generate_user()
product = data_generator.generate_product()
credit_card = data_generator.generate_credit_card()- Interactive test results with screenshots
- Performance metrics visualization
- Timeline view of test execution
- Detailed error information
- Machine-readable test results
- Performance data export
- CI/CD integration data
- Standard CI/CD format
- Test management tool integration
- Historical trend analysis
- Beautiful, detailed reports
- Test step visualization
- Historical trends
- Attachment support
- Environment variables for sensitive data
- Secure credential storage
- No hardcoded secrets
from decorators import security_scan
class TestSecurity(BaseTest):
@security_scan
async def run_test(self):
# Security test code
passfrom core.config import config
# Configure for mobile
config.device.viewport = {"width": 375, "height": 667}
config.device.user_agent = "iPhone Safari"
# Use Appium for native mobile apps
# (Requires Appium server setup)# Configure AWS credentials
config.cloud.aws.region = "us-east-1"
config.cloud.aws.device_farm_project = "your-project"config.browser.remote_url = "https://hub-cloud.browserstack.com/wd/hub"
config.browser.capabilities = {
"browserstack.user": "your-user",
"browserstack.key": "your-key",
}docker build -t playwright-framework .docker run --rm -v $(pwd)/reports:/app/reports playwright-frameworkdocker-compose up test-runnerThe framework includes a comprehensive GitHub Actions workflow. See .github/workflows/tests.yml for full configuration.
Features:
- β Automated testing on push/PR to main and develop branches
- β Multi-browser testing (Chromium, Firefox, WebKit)
- β Parallel test execution across browsers
- β Code coverage reporting with Codecov integration
- β Security scanning with Bandit
- β Code quality checks (Black, isort, flake8, mypy)
- β Performance benchmarking
- β Artifact collection (reports, screenshots, coverage)
Quick integration:
# Just push to GitHub and the workflow runs automatically!
git push origin main(For detailed setup, see .github/workflows/tests.yml)
stages:
- test
playwright_tests:
stage: test
image: python:3.12
before_script:
- pip install -r requirements.txt
- playwright install
script:
- python -m pytest tests/ --junitxml=reports/results.xml
artifacts:
reports:
junit: reports/results.xml
paths:
- reports/- Test execution progress
- Performance metrics dashboard
- Failure rate tracking
- Resource usage monitoring
# Slack notifications
config.notifications.slack_webhook = "https://hooks.slack.com/..."
# Email notifications
config.notifications.email_smtp = "smtp.gmail.com"
config.notifications.email_user = "your-email@gmail.com"- Create feature branch
- Implement changes
- Add tests
- Update documentation
- Create pull request
# Run linting
flake8 core/ tests/
# Run type checking
mypy core/ tests/
# Run tests with coverage
pytest --cov=core --cov-report=html- Fork the repository
- Create feature branch
- Make changes
- Add tests
- Submit pull request
See tests/test_examples.py for comprehensive test examples including:
- Login functionality tests
- E2E checkout flow
- Performance monitoring
- Accessibility testing
- Visual regression
- API testing patterns
- Browser not found: Run
playwright install - Import errors: Check virtual environment activation
- Timeout errors: Increase timeout in configuration
- Screenshot failures: Check write permissions on reports directory
# Enable debug logging
export LOG_LEVEL=DEBUG
# Run with verbose output
python -m pytest tests/ -v -sThis project is licensed under the MIT License - see the LICENSE file for details.
For support and questions:
- Create an issue on GitHub
- Check the documentation
- Review example tests
- Join our community discussions
- Advanced visual regression with pixel-perfect comparison
- Machine learning-based test failure prediction
- Integration with test management tools (TestRail, Zephyr)
- Advanced API testing with GraphQL support
- Mobile native app testing enhancements
- Performance profiling and optimization tools
- AI-powered test generation
- Advanced security testing modules
Happy Testing! π
- Buat Page Object (dalam
src/pages/jika Anda membuat folder baru):
from src.base import BasePage
from src.locators import LoginPageLocators
class LoginPage(BasePage):
async def login(self, username: str, password: str):
await self.fill(LoginPageLocators.USERNAME_INPUT, username)
await self.fill(LoginPageLocators.PASSWORD_INPUT, password)
await self.click(LoginPageLocators.LOGIN_BUTTON)- Buat Test Case:
import pytest
from src.base import BaseTest
class TestLogin(BaseTest):
@pytest.mark.asyncio
async def test_login_success(self):
# Your test code here
pass# Run all tests
pytest
# Run specific test file
pytest tests/test_example.py
# Run dengan verbose
pytest -v
# Run dengan markers
pytest -m "slow"
# Generate HTML report
pytest --html=reports/report.html --self-contained-htmlβ Async Support - Menggunakan async/await untuk performa test yang lebih baik β Page Object Model - Struktur yang clean dan maintainable β Base Classes - BaseTest dan BasePage untuk kurangi code duplication β Configuration Management - Settings management dengan .env β Screenshots & Videos - Automatic screenshot dan video recording β Multiple Browsers - Support Chromium, Firefox, WebKit β Pytest Integration - Full pytest support dengan markers dan fixtures
Ubah settings di .env file:
HEADLESS- Run browser dalam headless mode (true/false)BROWSER_TYPE- Pilih browser: chromium, firefox, webkitTIMEOUT- Default timeout dalam millisecondsBASE_URL- Base URL untuk aplikasi AndaSCREENSHOT_ON_FAILURE- Auto screenshot saat test gagalRECORD_VIDEO- Record video untuk setiap test
Manage semua locators within your page objects in core/ atau pages/:
from core.base import BasePage
class LoginPage(BasePage):
USERNAME_INPUT = 'input[name="username"]'
PASSWORD_INPUT = 'input[name="password"]'
LOGIN_BUTTON = 'button:has-text("Login")'
async def login(self, username: str, password: str):
await self.fill(self.USERNAME_INPUT, username)
await self.fill(self.PASSWORD_INPUT, password)
await self.click(self.LOGIN_BUTTON)- Selalu gunakan async/await dalam test methods
- Organize locators dalam class page objects (using core/base.py)
- Use Page Objects untuk better maintainability
- Add waits untuk handle timing issues
- Use fixtures untuk setup dan cleanup
- Document your tests dengan docstrings
playwright install --with-depsIncrease TIMEOUT di .env file
Pastikan Anda sudah activate virtual environment dan install requirements
MIT