Skip to content

Get started with Keycase automation in Python. Includes Playwright keywords, Page Object Model, and hot-reload support.

License

Notifications You must be signed in to change notification settings

TharassKeycase/keycase-python-quickstart

Repository files navigation

Keycase Python Quickstart

A keyword-driven test automation framework for CRM Demo applications, built with Python, Playwright, and the Keycase Agent SDK.

Overview

This project connects to a Keycase server via WebSocket and executes keyword-driven tests. Keywords are reusable test actions that can be orchestrated from the Keycase platform.

Features

  • Keyword-driven testing - Define reusable test keywords
  • Keycase Agent integration - WebSocket communication with Keycase server
  • Hot reload - Edit keywords and they auto-reload without restart
  • Auto-reconnect - Automatically reconnects if connection is lost
  • Page Object Model - Clean separation of page interactions
  • Multiple browser support - Chromium, Firefox, WebKit

Project Structure

keycase-python-quickstart/
├── config/
│   └── config.py                 # Configuration management (env, browser, test settings)
├── keywords/
│   ├── __init__.py               # Public keyword exports
│   ├── pre_condition.py          # Setup keywords (ConfigBrowser, Login, LogOut, etc.)
│   └── customers.py              # Customer management keywords (AddCustomer, DeleteCustomer)
├── pages/
│   ├── __init__.py
│   ├── base_page.py              # Base page with 27+ reusable methods
│   ├── auth/
│   │   └── login_page.py         # Login page object
│   ├── components/
│   │   ├── navbar.py             # Navigation bar component
│   │   └── sidebar.py            # Sidebar component
│   ├── customer/
│   │   └── customer_page.py      # Customer CRUD page object
│   ├── dashboard/
│   │   └── dashboard_page.py     # Dashboard page object
│   └── settings/
│       └── settings_page.py      # Settings page object
├── scripts/
│   ├── run_keycase_websocket.py              # Basic WebSocket agent
│   ├── run_keycase_websocket_with_reload.py  # WebSocket agent with hot reload
│   ├── run_local.py                          # Local execution from JSON
│   └── run_with_reload.py                    # Local execution with hot reload
├── tests/
│   ├── conftest.py               # Pytest fixtures and session setup
│   ├── test_cases/
│   │   └── test_keywords.py      # Keyword integration tests
│   └── test_data/                # Sample execution plans (JSON)
├── utils/
│   ├── __init__.py
│   ├── helpers.py                # Helper functions (safe_int, safe_float)
│   ├── hot_reload.py             # File watcher for auto-reload
│   └── test_storage.py           # Thread-safe browser session storage
├── .env.example                  # Environment template
├── .gitignore                    # Git ignore patterns
├── LICENSE                       # MIT License
├── pyproject.toml                # Tool configs (mypy, black, ruff)
├── pytest.ini                    # Pytest configuration
├── README.md                     # This file
└── requirements.txt              # Python dependencies

Setup

1. Install Python 3.11 or 3.12

macOS:

# Using Homebrew (install either version)
brew install python@3.11
# or
brew install python@3.12

Windows:

# Download from python.org or use winget (install either version)
winget install Python.Python.3.11
# or
winget install Python.Python.3.12

Linux (Ubuntu/Debian):

sudo apt update
# Install either version
sudo apt install python3.11 python3.11-venv
# or
sudo apt install python3.12 python3.12-venv

Note: Python 3.13+ is not supported yet due to package compatibility issues with pydantic-core and greenlet.

2. Clone and setup virtual environment

git clone <repository-url>
cd keycase-python-quickstart

Verify Python version first:

# macOS / Linux
python3 --version

# Windows
python --version

Make sure it shows Python 3.11.x or Python 3.12.x before proceeding.

macOS / Linux:

# Create virtual environment
python3 -m venv venv

# Activate virtual environment
source venv/bin/activate

Windows (Command Prompt):

# Create virtual environment
python -m venv venv

# Activate virtual environment
venv\Scripts\activate.bat

Windows (PowerShell):

# Create virtual environment
python -m venv venv

# Activate virtual environment
venv\Scripts\Activate.ps1

Tip: You'll know the virtual environment is active when you see (venv) at the beginning of your terminal prompt.

3. Install dependencies

pip install -r requirements.txt

4. Install Playwright browsers

playwright install

5. Configure environment

macOS / Linux:

cp .env.example .env

Windows (Command Prompt):

copy .env.example .env

Windows (PowerShell):

Copy-Item .env.example .env

Edit .env with your configuration:

# Required - Keycase Agent SDK Configuration
HTTP_URL=http://localhost:3000/api    # Keycase API endpoint
AGENT_TOKEN=agt_your_token_here       # Your agent token (starts with agt_)
AGENT_NAME=my-automation-agent        # Unique agent name in your organization

# Optional Agent Configuration
# AGENT_VERSION=1.0.0
# AGENT_CAPABILITIES=browser,playwright
# AGENT_TAGS=automation,testing

Note: The WebSocket URL and Agent ID are now obtained automatically from the authentication response. You only need to provide the AGENT_TOKEN from the Keycase platform.

Running the Agent

Start the Keycase WebSocket agent:

python scripts/run_keycase_websocket_with_reload.py

You'll see:

======================================================================
   KEYCASE WEBSOCKET AGENT - ADVANCED MODE
======================================================================
   Features:
      - Hot reload - Edit keywords and they auto-reload
      - Auto-reconnect - Automatically reconnects if disconnected
      - Real-time monitoring - See all keyword changes instantly
======================================================================
   Commands:
      - Ctrl+C - Stop the agent
======================================================================

Loading keywords...
Loaded 8 keywords: ['ConfigBrowser', 'Login', 'ResetData', 'LogOut', ...]
Watching: keywords, pages, utils
Connecting to Keycase WebSocket...

The agent will:

  1. Connect to the Keycase server
  2. Register available keywords
  3. Wait for test execution commands
  4. Execute keywords as requested

Available Keywords

Pre-condition Keywords

Keyword Parameters Description
ConfigBrowser url, browser Configure browser and target URL
Login username, password, persist, strategy Login to the application
LogOut - Log out of the application
ResetData - Reset application data
GetCurrentPage - Get current page instance
CloseBrowser - Close browser session

Customer Keywords

Keyword Parameters Description
AddCustomer name, email, address, city, country, phone Create a new customer
DeleteCustomer id Delete customer by ID
VerifyCustomerErrorFields field, expected_message Verify form validation errors

Hot Reload

The agent watches for file changes in:

  • keywords/ - Keyword definitions
  • pages/ - Page objects
  • utils/ - Utility functions

When you save a file, keywords automatically reload without restarting the agent.

Creating New Keywords

  1. Create or edit a file in keywords/
  2. Import the decorator: from keycase_agent.decorators import keyword
  3. Define your keyword:
from keycase_agent.decorators import keyword
from keywords.pre_condition import ensure_browser_session
from utils.test_storage import get_browser_config

@keyword("MyNewKeyword")
def my_new_keyword(param1: str, param2: str) -> None:
    """Description of what this keyword does."""
    page = ensure_browser_session()
    config = get_browser_config()

    # Your automation logic here
    page.goto(f"{config['base_url']}/some-path")
    page.fill("#input", param1)
    page.click("#button")
  1. Save the file - the keyword will auto-register

Creating Page Objects

  1. Create a new file in pages/
  2. Inherit from BasePage:
from pages.base_page import BasePage
from playwright.sync_api import Page

class MyPage(BasePage):
    def __init__(self, page: Page, base_url: str) -> None:
        super().__init__(page, base_url)
        self.path = "/my-page"

        # Locators
        self.my_button = "#my-button"
        self.my_input = "#my-input"

    def navigate(self) -> None:
        super().navigate(self.path)
        self.wait_for_page_load()

    def do_something(self, value: str) -> None:
        self.fill(self.my_input, value)
        self.click(self.my_button)

Troubleshooting

Connection Issues

  • Verify HTTP_URL in .env points to the correct Keycase API endpoint
  • Ensure your AGENT_TOKEN is valid and starts with agt_
  • Check that your AGENT_NAME is unique within your organization
  • If authentication fails, verify the token hasn't been revoked on the Keycase platform
  • Ensure network allows WebSocket connections

Browser Not Launching

playwright install

Package Installation Errors

Python 3.13+ Not Supported

If you see errors like:

error: the configured Python interpreter version (3.14) is newer than PyO3's maximum supported version (3.13)
ERROR: Failed building wheel for pydantic-core
ERROR: Failed building wheel for greenlet

This means you're using Python 3.13 or newer, which is not yet supported by key dependencies (pydantic-core, greenlet). These packages use Rust/C extensions that haven't been updated.

Solution: Install and use Python 3.11 or 3.12 instead:

macOS / Linux:

# Remove existing venv if created with wrong Python version
rm -rf venv

# Create new venv (ensure python3 points to 3.11 or 3.12)
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt

Windows:

# Remove existing venv
Remove-Item -Recurse -Force venv

# Create new venv (ensure python points to 3.11 or 3.12)
python -m venv venv
venv\Scripts\Activate.ps1
pip install -r requirements.txt

Check your Python version:

# macOS / Linux
python3 --version  # Should show 3.11.x or 3.12.x

# Windows
python --version   # Should show 3.11.x or 3.12.x

Keyword Not Found

  • Check the keyword is decorated with @keyword("KeywordName")
  • Verify the file is in the keywords/ directory
  • Check console for syntax errors during hot reload

Dependencies

  • keycase-agent-sdk - Keycase platform communication (token-based auth, WebSocket)
  • playwright - Browser automation
  • python-dotenv - Environment configuration
  • watchdog - File system monitoring for hot reload
  • pydantic - Data validation

Links

About

Get started with Keycase automation in Python. Includes Playwright keywords, Page Object Model, and hot-reload support.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages