visual

package
v0.0.0-...-23fd28c Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 12, 2025 License: MIT Imports: 23 Imported by: 0

Documentation

Overview

Package visual provides comprehensive visual regression testing capabilities

Index

Constants

This section is empty.

Variables

View Source
var (
	DefaultViewportSizes = []ViewportSize{
		{Width: 1920, Height: 1080, Name: "Desktop"},
		{Width: 1366, Height: 768, Name: "Laptop"},
		{Width: 768, Height: 1024, Name: "Tablet"},
		{Width: 414, Height: 896, Name: "Mobile"},
		{Width: 375, Height: 667, Name: "iPhone"},
		{Width: 360, Height: 640, Name: "Android"},
	}

	DefaultDeviceEmulations = map[string]*DeviceEmulation{
		"desktop": {
			Name:              "Desktop",
			ViewportSize:      ViewportSize{Width: 1920, Height: 1080, Name: "Desktop"},
			DeviceScaleFactor: 1.0,
			IsMobile:          false,
			HasTouch:          false,
			UserAgent:         "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
			ScreenWidth:       1920,
			ScreenHeight:      1080,
			ScreenOrientation: "landscape",
		},
		"tablet": {
			Name:              "Tablet",
			ViewportSize:      ViewportSize{Width: 768, Height: 1024, Name: "Tablet"},
			DeviceScaleFactor: 2.0,
			IsMobile:          true,
			HasTouch:          true,
			UserAgent:         "Mozilla/5.0 (iPad; CPU OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1",
			ScreenWidth:       768,
			ScreenHeight:      1024,
			ScreenOrientation: "portrait",
		},
		"mobile": {
			Name:              "Mobile",
			ViewportSize:      ViewportSize{Width: 414, Height: 896, Name: "Mobile"},
			DeviceScaleFactor: 3.0,
			IsMobile:          true,
			HasTouch:          true,
			UserAgent:         "Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1",
			ScreenWidth:       414,
			ScreenHeight:      896,
			ScreenOrientation: "portrait",
		},
	}
)

Default values

Functions

func ConvertScreenshotFormat

func ConvertScreenshotFormat(screenshot []byte, targetFormat string) ([]byte, error)

ConvertScreenshotFormat converts a screenshot from one format to another

func GetImageHash

func GetImageHash(img image.Image) (string, error)

GetImageHash calculates a hash of the image for comparison

func SaveConfig

func SaveConfig(config *CLIConfig, configPath string) error

SaveConfig saves CLI configuration to file

func ValidateScreenshotOptions

func ValidateScreenshotOptions(opts *ScreenshotOptions) error

ValidateScreenshotOptions validates screenshot options

Types

type AdvancedComparisonResult

type AdvancedComparisonResult struct {
	PixelComparison      *ComparisonResult
	StructuralSimilarity float64
	HistogramSimilarity  float64
	OverallScore         float64
	Passed               bool
}

AdvancedComparisonResult contains results from advanced comparison

type BaselineComparison

type BaselineComparison struct {
	TestName1            string
	TestName2            string
	Identical            bool
	DifferencePercentage float64
	Metadata1            *BaselineMetadata
	Metadata2            *BaselineMetadata
}

BaselineComparison contains the result of comparing two baselines

type BaselineInfo

type BaselineInfo struct {
	TestName     string
	ImageFile    string
	ImageSize    int64
	ImageModTime time.Time
	Metadata     *BaselineMetadata
}

BaselineInfo contains information about a baseline

type BaselineManager

type BaselineManager struct {
	// contains filtered or unexported fields
}

BaselineManager handles baseline image management

func NewBaselineManager

func NewBaselineManager(verbose bool) *BaselineManager

NewBaselineManager creates a new baseline manager

func (*BaselineManager) BaselineExists

func (bm *BaselineManager) BaselineExists(testName string, config *VisualTestConfig) bool

BaselineExists checks if a baseline exists

func (*BaselineManager) CleanupBaselines

func (bm *BaselineManager) CleanupBaselines(config *VisualTestConfig, olderThan time.Time) error

CleanupBaselines removes old or unused baselines

func (*BaselineManager) CompareBaselines

func (bm *BaselineManager) CompareBaselines(testName1, testName2 string, config *VisualTestConfig) (*BaselineComparison, error)

CompareBaselines compares two baselines

func (*BaselineManager) DeleteBaseline

func (bm *BaselineManager) DeleteBaseline(testName string, config *VisualTestConfig) error

DeleteBaseline deletes a baseline and its metadata

func (*BaselineManager) ExportBaselines

func (bm *BaselineManager) ExportBaselines(config *VisualTestConfig, archivePath string) error

ExportBaselines exports baselines to a tar archive

func (*BaselineManager) GetBaselineInfo

func (bm *BaselineManager) GetBaselineInfo(config *VisualTestConfig) ([]*BaselineInfo, error)

GetBaselineInfo gets detailed information about all baselines

func (*BaselineManager) GetBaselineMetadata

func (bm *BaselineManager) GetBaselineMetadata(testName string, config *VisualTestConfig) (*BaselineMetadata, error)

GetBaselineMetadata gets metadata for a baseline

func (*BaselineManager) ImportBaselines

func (bm *BaselineManager) ImportBaselines(config *VisualTestConfig, archivePath string) error

ImportBaselines imports baselines from a tar archive

func (*BaselineManager) ListBaselines

func (bm *BaselineManager) ListBaselines(config *VisualTestConfig) ([]string, error)

ListBaselines lists all available baselines

func (*BaselineManager) LoadBaseline

func (bm *BaselineManager) LoadBaseline(testName string, config *VisualTestConfig) ([]byte, *BaselineMetadata, error)

LoadBaseline loads a baseline image and its metadata

func (*BaselineManager) SaveBaseline

func (bm *BaselineManager) SaveBaseline(testName string, screenshot []byte, metadata *BaselineMetadata, config *VisualTestConfig) error

SaveBaseline saves a baseline image with metadata

func (*BaselineManager) UpdateBaseline

func (bm *BaselineManager) UpdateBaseline(testName string, screenshot []byte, metadata *BaselineMetadata, config *VisualTestConfig) error

UpdateBaseline updates an existing baseline

func (*BaselineManager) ValidateBaseline

func (bm *BaselineManager) ValidateBaseline(testName string, config *VisualTestConfig) (*BaselineValidation, error)

ValidateBaseline validates a baseline image and metadata

type BaselineMetadata

type BaselineMetadata struct {
	// Version is the baseline version
	Version string
	// CreatedAt is when the baseline was created
	CreatedAt time.Time
	// UpdatedAt is when the baseline was last updated
	UpdatedAt time.Time
	// URL is the URL that was captured
	URL string
	// ViewportSize is the viewport size used
	ViewportSize ViewportSize
	// DeviceEmulation is the device emulation used
	DeviceEmulation *DeviceEmulation
	// BrowserInfo contains browser information
	BrowserInfo BrowserInfo
	// TestName is the name of the test
	TestName string
	// TestSuite is the test suite name
	TestSuite string
	// Environment is the testing environment
	Environment string
	// Branch is the git branch
	Branch string
	// Commit is the git commit hash
	Commit string
	// Tags are additional tags
	Tags []string
	// Notes are additional notes
	Notes string
	// ChecksumMD5 is the MD5 checksum of the image
	ChecksumMD5 string
	// ChecksumSHA256 is the SHA256 checksum of the image
	ChecksumSHA256 string
	// FileSize is the size of the image file
	FileSize int64
	// ImageDimensions contains image dimensions
	ImageDimensions ImageDimensions
}

BaselineMetadata contains metadata for baseline images

type BaselineValidation

type BaselineValidation struct {
	TestName        string
	Valid           bool
	Issues          []string
	ImageDimensions *ImageDimensions
	Metadata        *BaselineMetadata
}

BaselineValidation contains the result of validating a baseline

type BrowserInfo

type BrowserInfo struct {
	Name    string
	Version string
	Major   int
	Minor   int
	Patch   int
	Build   string
}

BrowserInfo contains browser information

type CLIConfig

type CLIConfig struct {
	BaselineDir         string
	ActualDir           string
	DiffDir             string
	ReportDir           string
	ConfigFile          string
	Verbose             bool
	OutputFormat        string
	Headless            bool
	UseProfile          bool
	ProfileName         string
	ChromePath          string
	Timeout             time.Duration
	Retries             int
	Threshold           float64
	IgnoreAntialiasing  bool
	EnableFuzzyMatching bool
	FuzzyThreshold      float64
	MaxDiffPixels       int
	Quality             int
	Format              string
	FullPage            bool
	ViewportWidth       int
	ViewportHeight      int
	DeviceScaleFactor   float64
	EmulateDevice       string
	WaitForFonts        bool
	WaitForImages       bool
	WaitForAnimations   bool
	HideCursor          bool
	HideScrollbars      bool
	CustomCSS           string
	ExcludeSelectors    []string
	MaskSelectors       []string
	MaskColor           string
}

CLIConfig holds configuration for CLI commands

func DefaultCLIConfig

func DefaultCLIConfig() *CLIConfig

DefaultCLIConfig returns default CLI configuration

func LoadConfig

func LoadConfig(configPath string) (*CLIConfig, error)

LoadConfig loads CLI configuration from file

type ComparisonResult

type ComparisonResult struct {
	// Passed indicates if the comparison passed
	Passed bool
	// DiffPixels is the number of different pixels
	DiffPixels int
	// TotalPixels is the total number of pixels
	TotalPixels int
	// DifferencePercentage is the percentage of different pixels
	DifferencePercentage float64
	// DiffImage is the difference image
	DiffImage image.Image
	// MatchingScore is the overall matching score (0-1)
	MatchingScore float64
	// Regions are the different regions
	Regions []DiffRegion
	// Metadata contains comparison metadata
	Metadata map[string]interface{}
}

ComparisonResult represents the result of image comparison

type DeviceEmulation

type DeviceEmulation struct {
	Name              string
	ViewportSize      ViewportSize
	DeviceScaleFactor float64
	IsMobile          bool
	HasTouch          bool
	UserAgent         string
	ScreenWidth       int
	ScreenHeight      int
	ScreenOrientation string
}

DeviceEmulation represents device emulation settings

type DiffRegion

type DiffRegion struct {
	X      int
	Y      int
	Width  int
	Height int
	Score  float64
}

DiffRegion represents a region with differences

type ImageComparison

type ImageComparison struct {
	// contains filtered or unexported fields
}

ImageComparison handles image comparison operations

func NewImageComparison

func NewImageComparison(verbose bool) *ImageComparison

NewImageComparison creates a new image comparison instance

func (*ImageComparison) CalculateStructuralSimilarity

func (ic *ImageComparison) CalculateStructuralSimilarity(baseline, actual image.Image) (float64, error)

CalculateStructuralSimilarity calculates structural similarity between images

func (*ImageComparison) CompareHistograms

func (ic *ImageComparison) CompareHistograms(baseline, actual image.Image) (float64, error)

CompareHistograms compares color histograms of two images

func (*ImageComparison) CompareImages

func (ic *ImageComparison) CompareImages(baseline, actual image.Image, config *VisualTestConfig) (*ComparisonResult, error)

CompareImages compares two images and returns detailed comparison results

func (*ImageComparison) CompareScreenshots

func (ic *ImageComparison) CompareScreenshots(baselineData, actualData []byte, config *VisualTestConfig) (*ComparisonResult, error)

CompareScreenshots compares two screenshots given as byte arrays

func (*ImageComparison) GenerateAnnotatedImage

func (ic *ImageComparison) GenerateAnnotatedImage(actual image.Image, regions []DiffRegion) (image.Image, error)

GenerateAnnotatedImage creates an annotated image with difference regions highlighted

func (*ImageComparison) GenerateDiffImage

func (ic *ImageComparison) GenerateDiffImage(baseline, actual image.Image, config *VisualTestConfig) (image.Image, error)

GenerateDiffImage creates a visual diff image highlighting differences

func (*ImageComparison) GenerateHistogram

func (ic *ImageComparison) GenerateHistogram(img image.Image) map[string]int

GenerateHistogram generates a color histogram for an image

func (*ImageComparison) GenerateSideBySideImage

func (ic *ImageComparison) GenerateSideBySideImage(baseline, actual image.Image, diffImage image.Image) (image.Image, error)

GenerateSideBySideImage creates a side-by-side comparison image

func (*ImageComparison) PerformAdvancedComparison

func (ic *ImageComparison) PerformAdvancedComparison(baseline, actual image.Image, config *VisualTestConfig) (*AdvancedComparisonResult, error)

PerformAdvancedComparison performs advanced image comparison with multiple metrics

func (*ImageComparison) SaveDiffImage

func (ic *ImageComparison) SaveDiffImage(diffImage image.Image, filename string) error

SaveDiffImage saves a diff image to a file

type ImageDimensions

type ImageDimensions struct {
	Width  int
	Height int
}

ImageDimensions contains image dimensions

func GetScreenshotDimensions

func GetScreenshotDimensions(screenshot []byte) (*ImageDimensions, error)

GetScreenshotDimensions returns the dimensions of a screenshot

type ResponsiveTest

type ResponsiveTest struct {
	Name     string
	URL      string
	Setup    func(ctx context.Context, page *browser.Page) error
	Action   func(ctx context.Context, page *browser.Page) error
	Cleanup  func(ctx context.Context, page *browser.Page) error
	Tags     []string
	Metadata map[string]interface{}
}

ResponsiveTest represents a responsive visual test

type ResponsiveTestConfig

type ResponsiveTestConfig struct {
	// BaseConfig is the base visual test configuration
	BaseConfig *VisualTestConfig
	// Viewports are the viewports to test
	Viewports []ViewportSize
	// Devices are the devices to emulate
	Devices []string
	// OrientationTest enables orientation testing
	OrientationTest bool
	// PixelDensities are the pixel densities to test
	PixelDensities []float64
	// BreakpointTest enables breakpoint testing
	BreakpointTest bool
	// Breakpoints are custom breakpoints to test
	Breakpoints []int
}

ResponsiveTestConfig configures responsive visual testing

func CreateResponsiveTestConfig

func CreateResponsiveTestConfig(baseConfig *VisualTestConfig) *ResponsiveTestConfig

CreateResponsiveTestConfig creates a default responsive test configuration

type ResponsiveTestResult

type ResponsiveTestResult struct {
	TestName  string
	URL       string
	Results   map[string]*TestResult // keyed by viewport/device name
	Summary   ResponsiveTestSummary
	Timestamp time.Time
	Duration  time.Duration
	Passed    bool
	Config    *ResponsiveTestConfig
	Metadata  map[string]interface{}
}

ResponsiveTestResult contains results from responsive testing

type ResponsiveTestSuiteResult

type ResponsiveTestSuiteResult struct {
	SuiteName string
	Results   []*ResponsiveTestResult
	Summary   ResponsiveTestSuiteSummary
	Timestamp time.Time
	Duration  time.Duration
	Passed    bool
	Config    *ResponsiveTestConfig
	Metadata  map[string]interface{}
}

ResponsiveTestSuiteResult contains results from a responsive test suite

func (*ResponsiveTestSuiteResult) GetViewportFailures

func (rtsr *ResponsiveTestSuiteResult) GetViewportFailures() map[string]int

GetViewportFailures returns viewports that failed across all tests

func (*ResponsiveTestSuiteResult) GetWorstViewports

func (rtsr *ResponsiveTestSuiteResult) GetWorstViewports(limit int) []ViewportFailure

GetWorstViewports returns the viewports with the highest failure rate

type ResponsiveTestSuiteSummary

type ResponsiveTestSuiteSummary struct {
	TotalTests      int
	PassedTests     int
	FailedTests     int
	PassRate        float64
	TotalDuration   time.Duration
	AverageDuration time.Duration
}

ResponsiveTestSuiteSummary contains summary statistics for a responsive test suite

type ResponsiveTestSummary

type ResponsiveTestSummary struct {
	TotalViewports    int
	PassedViewports   int
	FailedViewports   int
	WorstViewport     string
	WorstDifference   float64
	BestViewport      string
	BestDifference    float64
	AverageDifference float64
}

ResponsiveTestSummary contains summary statistics for responsive testing

type ResponsiveVisualTester

type ResponsiveVisualTester struct {
	// contains filtered or unexported fields
}

ResponsiveVisualTester handles responsive visual regression testing

func NewResponsiveVisualTester

func NewResponsiveVisualTester(verbose bool) *ResponsiveVisualTester

NewResponsiveVisualTester creates a new responsive visual tester

func (*ResponsiveVisualTester) RunResponsiveTest

func (rvt *ResponsiveVisualTester) RunResponsiveTest(ctx context.Context, testName, url string, config *ResponsiveTestConfig) (*ResponsiveTestResult, error)

RunResponsiveTest runs a responsive visual test across multiple viewports

func (*ResponsiveVisualTester) RunResponsiveTestSuite

func (rvt *ResponsiveVisualTester) RunResponsiveTestSuite(ctx context.Context, suiteName string, tests []ResponsiveTest, config *ResponsiveTestConfig) (*ResponsiveTestSuiteResult, error)

RunResponsiveTestSuite runs a suite of responsive tests

type ScreenshotCapture

type ScreenshotCapture struct {
	// contains filtered or unexported fields
}

ScreenshotCapture handles advanced screenshot capture functionality

func NewScreenshotCapture

func NewScreenshotCapture(verbose bool) *ScreenshotCapture

NewScreenshotCapture creates a new screenshot capture instance

func (*ScreenshotCapture) CaptureElementScreenshots

func (sc *ScreenshotCapture) CaptureElementScreenshots(ctx context.Context, page *browser.Page, selectors []string, opts *ScreenshotOptions) (map[string][]byte, error)

CaptureElementScreenshots captures screenshots of multiple elements

func (*ScreenshotCapture) CaptureMultipleViewports

func (sc *ScreenshotCapture) CaptureMultipleViewports(ctx context.Context, page *browser.Page, viewports []ViewportSize, opts *ScreenshotOptions) (map[string][]byte, error)

CaptureMultipleViewports captures screenshots at multiple viewport sizes

func (*ScreenshotCapture) CaptureScreenshot

func (sc *ScreenshotCapture) CaptureScreenshot(ctx context.Context, page *browser.Page, opts *ScreenshotOptions) ([]byte, error)

CaptureScreenshot captures a screenshot with advanced options

func (*ScreenshotCapture) CaptureWithDeviceEmulation

func (sc *ScreenshotCapture) CaptureWithDeviceEmulation(ctx context.Context, page *browser.Page, devices []string, opts *ScreenshotOptions) (map[string][]byte, error)

CaptureWithDeviceEmulation captures screenshots with device emulation

type ScreenshotOptions

type ScreenshotOptions struct {
	// FullPage captures the entire page
	FullPage bool
	// Selector captures only the specified element
	Selector string
	// ViewportWidth sets the viewport width
	ViewportWidth int
	// ViewportHeight sets the viewport height
	ViewportHeight int
	// Quality is the image quality (1-100)
	Quality int
	// Format is the image format (png, jpg, webp)
	Format string
	// HideCursor hides the mouse cursor
	HideCursor bool
	// HideScrollbars hides scrollbars
	HideScrollbars bool
	// WaitForFonts waits for fonts to load
	WaitForFonts bool
	// WaitForImages waits for images to load
	WaitForImages bool
	// WaitForAnimations waits for animations to complete
	WaitForAnimations bool
	// AnimationWaitTime is the time to wait for animations
	AnimationWaitTime time.Duration
	// StabilityWaitTime is the time to wait for page stability
	StabilityWaitTime time.Duration
	// DeviceScaleFactor sets the device scale factor
	DeviceScaleFactor float64
	// EmulateDevice emulates a specific device
	EmulateDevice string
	// ClipToViewport clips the screenshot to the viewport
	ClipToViewport bool
	// OmitBackground omits the background
	OmitBackground bool
	// CustomCSS injects custom CSS before taking screenshot
	CustomCSS string
	// ExcludeSelectors excludes elements from the screenshot
	ExcludeSelectors []string
	// MaskSelectors masks elements in the screenshot
	MaskSelectors []string
	// MaskColor is the color to use for masking
	MaskColor string
}

ScreenshotOptions configures screenshot capture

func DefaultScreenshotOptions

func DefaultScreenshotOptions() *ScreenshotOptions

DefaultScreenshotOptions returns default screenshot options

type TestReport

type TestReport struct {
	// Title is the report title
	Title string
	// SuiteResults are the suite results
	SuiteResults []*TestSuiteResult
	// Summary is the overall summary
	Summary TestSummary
	// GeneratedAt is when the report was generated
	GeneratedAt time.Time
	// Environment is the testing environment
	Environment string
	// Config is the configuration used
	Config *VisualTestConfig
	// Metadata contains additional metadata
	Metadata map[string]interface{}
}

TestReport represents a visual test report

type TestResult

type TestResult struct {
	// TestName is the name of the test
	TestName string
	// TestSuite is the test suite name
	TestSuite string
	// Passed indicates if the test passed
	Passed bool
	// ComparisonResult is the detailed comparison result
	ComparisonResult *ComparisonResult
	// BaselineMetadata is the baseline metadata
	BaselineMetadata *BaselineMetadata
	// ActualScreenshot is the actual screenshot data
	ActualScreenshot []byte
	// BaselineScreenshot is the baseline screenshot data
	BaselineScreenshot []byte
	// DiffScreenshot is the diff screenshot data
	DiffScreenshot []byte
	// Error is any error that occurred
	Error error
	// Duration is how long the test took
	Duration time.Duration
	// Timestamp is when the test was run
	Timestamp time.Time
	// Retries is the number of retries performed
	Retries int
	// Environment is the testing environment
	Environment string
	// URL is the URL that was tested
	URL string
	// Config is the test configuration used
	Config *VisualTestConfig
	// ScreenshotOptions are the options used for screenshot
	ScreenshotOptions *ScreenshotOptions
	// Metadata contains additional metadata
	Metadata map[string]interface{}
}

TestResult represents the result of a visual test

type TestSuiteResult

type TestSuiteResult struct {
	// SuiteName is the name of the test suite
	SuiteName string
	// Results are the individual test results
	Results []*TestResult
	// Passed indicates if all tests passed
	Passed bool
	// Duration is the total duration
	Duration time.Duration
	// Timestamp is when the suite was run
	Timestamp time.Time
	// Environment is the testing environment
	Environment string
	// Summary contains summary statistics
	Summary TestSummary
	// Config is the suite configuration
	Config *VisualTestConfig
	// Metadata contains additional metadata
	Metadata map[string]interface{}
}

TestSuiteResult represents the result of a test suite

type TestSummary

type TestSummary struct {
	// TotalTests is the total number of tests
	TotalTests int
	// PassedTests is the number of passed tests
	PassedTests int
	// FailedTests is the number of failed tests
	FailedTests int
	// SkippedTests is the number of skipped tests
	SkippedTests int
	// PassRate is the pass rate (0-1)
	PassRate float64
	// TotalDuration is the total duration
	TotalDuration time.Duration
	// AverageDuration is the average duration per test
	AverageDuration time.Duration
}

TestSummary contains summary statistics

type ViewportFailure

type ViewportFailure struct {
	Viewport     string
	FailureCount int
	FailureRate  float64
}

ViewportFailure represents viewport failure statistics

type ViewportSize

type ViewportSize struct {
	Width  int
	Height int
	Name   string
}

ViewportSize represents a viewport size configuration

type VisualCLI

type VisualCLI struct {
	// contains filtered or unexported fields
}

VisualCLI provides CLI interface for visual regression testing

func NewVisualCLI

func NewVisualCLI(config *CLIConfig) *VisualCLI

NewVisualCLI creates a new visual CLI instance

func (*VisualCLI) CaptureCommand

func (vcli *VisualCLI) CaptureCommand(ctx context.Context, testName, url string) error

CaptureCommand captures a screenshot and saves it as a baseline

func (*VisualCLI) CompareCommand

func (vcli *VisualCLI) CompareCommand(ctx context.Context, baseline, actual string) error

CompareCommand compares two screenshots

func (*VisualCLI) DeleteCommand

func (vcli *VisualCLI) DeleteCommand(ctx context.Context, testName string) error

DeleteCommand deletes a baseline

func (*VisualCLI) ListCommand

func (vcli *VisualCLI) ListCommand(ctx context.Context) error

ListCommand lists all available baselines

func (*VisualCLI) ReportCommand

func (vcli *VisualCLI) ReportCommand(ctx context.Context, reportPath string) error

ReportCommand generates a visual regression report

func (*VisualCLI) ResponsiveCommand

func (vcli *VisualCLI) ResponsiveCommand(ctx context.Context, testName, url string) error

ResponsiveCommand runs responsive visual tests

func (*VisualCLI) TestCommand

func (vcli *VisualCLI) TestCommand(ctx context.Context, testName, url string) error

TestCommand runs a visual regression test

func (*VisualCLI) UpdateCommand

func (vcli *VisualCLI) UpdateCommand(ctx context.Context, testName, url string) error

UpdateCommand updates a baseline

type VisualRegressionTester

type VisualRegressionTester struct {
	// contains filtered or unexported fields
}

VisualRegressionTester implements the main visual regression testing functionality

func NewVisualRegressionTester

func NewVisualRegressionTester(verbose bool) *VisualRegressionTester

NewVisualRegressionTester creates a new visual regression tester

func (*VisualRegressionTester) CaptureScreenshot

func (vrt *VisualRegressionTester) CaptureScreenshot(ctx context.Context, page *browser.Page, opts *ScreenshotOptions) ([]byte, error)

CaptureScreenshot captures a screenshot with the given options

func (*VisualRegressionTester) CompareImages

func (vrt *VisualRegressionTester) CompareImages(baseline, actual []byte, config *VisualTestConfig) (*ComparisonResult, error)

CompareImages compares two images and returns the result

func (*VisualRegressionTester) DeleteBaseline

func (vrt *VisualRegressionTester) DeleteBaseline(testName string, config *VisualTestConfig) error

DeleteBaseline deletes a baseline image

func (*VisualRegressionTester) GenerateReport

func (vrt *VisualRegressionTester) GenerateReport(results []*TestResult, config *VisualTestConfig) (*TestReport, error)

GenerateReport generates a visual test report

func (*VisualRegressionTester) GetBaselineMetadata

func (vrt *VisualRegressionTester) GetBaselineMetadata(testName string, config *VisualTestConfig) (*BaselineMetadata, error)

GetBaselineMetadata gets metadata for a baseline

func (*VisualRegressionTester) ListBaselines

func (vrt *VisualRegressionTester) ListBaselines(config *VisualTestConfig) ([]string, error)

ListBaselines lists all baselines

func (*VisualRegressionTester) LoadBaseline

func (vrt *VisualRegressionTester) LoadBaseline(testName string, config *VisualTestConfig) ([]byte, *BaselineMetadata, error)

LoadBaseline loads a baseline image

func (*VisualRegressionTester) RunTestSuite

func (vrt *VisualRegressionTester) RunTestSuite(ctx context.Context, suiteName string, tests []VisualTest, config *VisualTestConfig) (*TestSuiteResult, error)

RunTestSuite runs a suite of visual regression tests

func (*VisualRegressionTester) RunVisualTest

func (vrt *VisualRegressionTester) RunVisualTest(ctx context.Context, testName string, page *browser.Page, config *VisualTestConfig, opts *ScreenshotOptions) (*TestResult, error)

RunVisualTest runs a single visual regression test

func (*VisualRegressionTester) SaveBaseline

func (vrt *VisualRegressionTester) SaveBaseline(testName string, screenshot []byte, metadata *BaselineMetadata, config *VisualTestConfig) error

SaveBaseline saves a baseline image

func (*VisualRegressionTester) UpdateBaseline

func (vrt *VisualRegressionTester) UpdateBaseline(testName string, screenshot []byte, metadata *BaselineMetadata, config *VisualTestConfig) error

UpdateBaseline updates a baseline image

type VisualTest

type VisualTest struct {
	// Name is the test name
	Name string
	// URL is the URL to test
	URL string
	// Setup is a function to set up the test (optional)
	Setup func(ctx context.Context, page *browser.Page) error
	// Action is a function to perform actions before screenshot (optional)
	Action func(ctx context.Context, page *browser.Page) error
	// Cleanup is a function to clean up after the test (optional)
	Cleanup func(ctx context.Context, page *browser.Page) error
	// Options are the screenshot options
	Options *ScreenshotOptions
	// Viewport is the viewport size
	Viewport *ViewportSize
	// DeviceEmulation is the device emulation
	DeviceEmulation *DeviceEmulation
	// Timeout is the test timeout
	Timeout time.Duration
	// Retries is the number of retries
	Retries int
	// Skip indicates if the test should be skipped
	Skip bool
	// SkipReason is the reason for skipping
	SkipReason string
	// Tags are test tags
	Tags []string
	// Metadata contains additional metadata
	Metadata map[string]interface{}
}

VisualTest represents a single visual test

func CreateElementVisualTest

func CreateElementVisualTest(name, url, selector string) VisualTest

CreateElementVisualTest creates a visual test for a specific element

func CreateResponsiveVisualTest

func CreateResponsiveVisualTest(name, url string, viewports []ViewportSize) []VisualTest

CreateResponsiveVisualTest creates a visual test that runs on multiple viewports

func CreateVisualTestFromURL

func CreateVisualTestFromURL(name, url string, opts *ScreenshotOptions) VisualTest

CreateVisualTestFromURL creates a visual test from a URL

type VisualTestConfig

type VisualTestConfig struct {
	// BaselineDir is the directory where baseline images are stored
	BaselineDir string
	// ActualDir is the directory where actual screenshots are stored
	ActualDir string
	// DiffDir is the directory where diff images are stored
	DiffDir string
	// Threshold is the pixel difference threshold (0-1)
	Threshold float64
	// IgnoreAntialiasing ignores antialiasing differences
	IgnoreAntialiasing bool
	// EnableFuzzyMatching enables fuzzy matching for tolerance
	EnableFuzzyMatching bool
	// FuzzyThreshold is the fuzzy matching threshold (0-1)
	FuzzyThreshold float64
	// MaxDiffPixels is the maximum allowed different pixels
	MaxDiffPixels int
	// Quality is the screenshot quality (1-100)
	Quality int
	// Format is the screenshot format (png, jpg, webp)
	Format string
	// RetryCount is the number of retries for flaky tests
	RetryCount int
	// RetryDelay is the delay between retries
	RetryDelay time.Duration
}

VisualTestConfig holds configuration for visual regression testing

func DefaultConfig

func DefaultConfig() *VisualTestConfig

DefaultConfig returns a default visual test configuration

type VisualTester

type VisualTester interface {
	// CaptureScreenshot captures a screenshot with the given options
	CaptureScreenshot(ctx context.Context, page *browser.Page, opts *ScreenshotOptions) ([]byte, error)

	// CompareImages compares two images and returns the result
	CompareImages(baseline, actual image.Image, config *VisualTestConfig) (*ComparisonResult, error)

	// RunVisualTest runs a visual test
	RunVisualTest(ctx context.Context, testName string, page *browser.Page, config *VisualTestConfig, opts *ScreenshotOptions) (*TestResult, error)

	// RunTestSuite runs a test suite
	RunTestSuite(ctx context.Context, suiteName string, tests []VisualTest, config *VisualTestConfig) (*TestSuiteResult, error)

	// SaveBaseline saves a baseline image
	SaveBaseline(testName string, screenshot []byte, metadata *BaselineMetadata, config *VisualTestConfig) error

	// LoadBaseline loads a baseline image
	LoadBaseline(testName string, config *VisualTestConfig) ([]byte, *BaselineMetadata, error)

	// GetBaselineMetadata gets metadata for a baseline
	GetBaselineMetadata(testName string, config *VisualTestConfig) (*BaselineMetadata, error)

	// UpdateBaseline updates a baseline image
	UpdateBaseline(testName string, screenshot []byte, metadata *BaselineMetadata, config *VisualTestConfig) error

	// DeleteBaseline deletes a baseline image
	DeleteBaseline(testName string, config *VisualTestConfig) error

	// ListBaselines lists all baselines
	ListBaselines(config *VisualTestConfig) ([]string, error)

	// GenerateReport generates a visual test report
	GenerateReport(results []*TestResult, config *VisualTestConfig) (*TestReport, error)
}

VisualTester is the main interface for visual regression testing

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL