Percy Python Client

2.0.2 · active · verified Fri Apr 17

The `percy` library provides a Python client for integrating visual regression testing with Percy (https://percy.io). It enables capturing snapshots of web pages during tests and uploading them to the Percy platform for visual comparison. It is currently at version 2.0.2, with an active development cycle that frequently includes minor improvements and occasional major versions for breaking changes.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates the basic lifecycle for using the Percy Python client: initialize `PercyRunner`, start a build, take one or more snapshots using a WebDriver instance, and then finalize the build. It requires a `PERCY_TOKEN` environment variable to successfully upload snapshots to Percy. A mock WebDriver is used to make the example runnable without a full browser setup.

import os
from percy.runner import PercyRunner
from percy.snapshot import percy_snapshot

# Percy requires a WebDriver instance (e.g., from Selenium or Playwright).
# For this example, we'll use a mock driver.
class MockWebDriver:
    def __init__(self):
        self.title = "Mock Page Title"
        self.current_url = "http://localhost:8000/mock-page"

    def execute_script(self, script):
        # Simulate returning page HTML or other script results
        if "document.documentElement.outerHTML" in script:
            return "<html><body><h1>Hello from Percy!</h1></body></html>"
        return None

# Ensure PERCY_TOKEN is set in your environment variables for actual uploads.
# Example: export PERCY_TOKEN="YOUR_PERCY_TOKEN"
percy_token = os.environ.get('PERCY_TOKEN', 'YOUR_PERCY_TOKEN_IF_MISSING')
if percy_token == 'YOUR_PERCY_TOKEN_IF_MISSING':
    print("Warning: PERCY_TOKEN environment variable is not set. Snapshots will not be uploaded.")

runner = PercyRunner()
try:
    # Start a Percy build
    runner.start_build()
    print("Percy build started.")

    # Instantiate the mock driver
    driver = MockWebDriver()

    # Take a snapshot
    percy_snapshot(driver, name="Example Snapshot 1", widths=[768, 1280])
    print("Snapshot 'Example Snapshot 1' taken.")

    # You can take multiple snapshots in a single build
    # percy_snapshot(driver, name="Example Snapshot 2", fullscreen=True)

finally:
    # Finalize the Percy build
    runner.finalize_build()
    print("Percy build finalized.")

view raw JSON →