testing

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 2, 2025 License: MIT Imports: 14 Imported by: 0

README

Testing Package

Package testing provides testing utilities, performance benchmarking, memory analysis, and snapshot testing capabilities for weft. It offers configurable benchmark runners, memory profilers, filesystem mocks, snapshot management, and a rich set of testing helper functions.

Architecture

The testing package is organized into four main components:

  • Benchmark Testing (benchmarks.go): Performance testing with memory profiling and result comparison
  • Memory Testing (memory.go): In-memory filesystem implementation for testing
  • Mock Testing (mocks.go): Mock filesystem, logger, and renderer implementations
  • Snapshot Testing (snapshots.go): Golden file testing with diff generation and update modes

Basic Usage

Create a Benchmark Runner
runner := testing.NewBenchmarkRunner()
runner.SetMinIterations(100)
runner.SetMaxIterations(10000)
runner.SetMinTime(5 * time.Second)
Run Performance Benchmarks
result := runner.Benchmark("template_render", func() error {
    _, err := template.Execute(data)
    return err
})

fmt.Printf("Average time: %v\n", result.AvgDuration)
fmt.Printf("Memory per op: %d bytes\n", result.BytesPerOp)

Memory Testing

Create in-memory filesystems for testing template operations:

memFS := testing.NewMemoryFS()
memFS.WriteFile("templates/user.tmpl", []byte("Hello {{.Name}}!"))

// Use with template engine
file, err := memFS.Open("templates/user.tmpl")
Memory Filesystem Features
  • File Operations: Read, write, and stat files in memory
  • Directory Support: Create and navigate directory structures
  • fs.FS Interface: Compatible with Go's filesystem interfaces
  • Concurrent Safe: Thread-safe operations for parallel testing

Configuration

The package supports various configuration options:

// Benchmark configuration
runner := testing.NewBenchmarkRunner()
runner.SetWarmupIterations(5)    // Warmup runs before timing
runner.SetMinIterations(50)      // Minimum benchmark iterations
runner.SetMaxIterations(100000)  // Maximum benchmark iterations
runner.SetMinTime(2 * time.Second) // Minimum benchmark duration

// Snapshot configuration
manager := testing.NewSnapshotManager("testdata/snapshots", false)
manager.SetUpdateMode(true)      // Enable snapshot updates

Snapshot Testing

Test template output against saved snapshots:

manager := testing.NewSnapshotManager("testdata/snapshots", false)

// Assert output matches snapshot
output := executeTemplate("user.tmpl", userData)
err := manager.AssertSnapshot("user_template", output)
if err != nil {
    t.Error(err)
}
Snapshot Features
  • Golden File Testing: Compare output against saved reference files
  • Update Mode: Automatically update snapshots when content changes
  • Diff Generation: Detailed line-by-line difference reporting
  • Orphan Cleanup: Remove unused snapshot files

Mock Testing

Use mock implementations for isolated testing:

// Mock filesystem
mockFS := testing.NewMockFS()
mockFS.AddFile("template.tmpl", "Hello {{.Name}}!")

// Mock logger
mockLogger := testing.NewMockLogger()
// ... use logger in code
logs := mockLogger.GetLogs()

// Mock renderer
mockRenderer := testing.NewMockRenderer()
mockRenderer.SetRenderFunc(func(path string, data any) (string, error) {
    return "mocked output", nil
})

Benchmark Results

The package provides detailed benchmark analysis:

Metric Description
Iterations Number of benchmark runs performed
AvgDuration Average execution time per iteration
MinDuration Fastest single iteration time
MaxDuration Slowest single iteration time
MemoryUsed Total memory allocated during benchmark
AllocsPerOp Memory allocations per operation
BytesPerOp Bytes allocated per operation
Performance Comparisons
// Compare two benchmark results
comparison, err := runner.Compare("benchmark1", "benchmark2")
if err == nil {
    fmt.Println(comparison.String())
    // Output: "benchmark1 is 2.34x faster than benchmark2"
}

Memory Profiling

Track memory usage and system resources:

profiler := testing.NewPerformanceProfiler()
profiler.StartProfile("template_execution")

// ... execute templates

profiler.EndProfile("template_execution")
profile, _ := profiler.GetProfile("template_execution")
fmt.Printf("Memory delta: %d bytes\n", profile.MemoryProfile.HeapAllocDelta)
Profiling Metrics
Field Description Usage
AllocsDelta Change in allocation count Memory allocation tracking
HeapAllocDelta Heap memory change Memory usage analysis
SysDelta System memory change Overall memory impact
Duration Total execution time Performance measurement

Mock Components

Available Mocks
Component Description Example
MockFS Mock filesystem implementation mockFS.AddFile("test.txt", "content")
MockLogger Mock logger with call tracking mockLogger.Info("message")
MockRenderer Mock template renderer mockRenderer.Render("tmpl", data)
Mock Usage Examples
// Mock filesystem operations
mockFS := testing.NewMockFS()
mockFS.AddFile("config.json", `{"key": "value"}`)
content, _ := mockFS.ReadFile("config.json")

// Mock logger verification
mockLogger := testing.NewMockLogger()
mockLogger.Error("test error")
errorLogs := mockLogger.GetLogsByLevel("ERROR")
assert.Equal(t, 1, len(errorLogs))

// Mock renderer behavior
mockRenderer := testing.NewMockRenderer()
result, _ := mockRenderer.Render("template.tmpl", map[string]string{"name": "test"})
assert.True(t, mockRenderer.WasCalled("template.tmpl"))

Performance Considerations

Optimization Tips
  1. Benchmark Warmup: Use warmup iterations to eliminate JIT overhead
  2. Memory Profiling: Monitor allocations to identify memory hotspots
  3. Snapshot Efficiency: Use update mode judiciously to avoid unnecessary file I/O
  4. Mock Performance: Mocks are lightweight but still add overhead in tight loops
Performance Settings
// Production-optimized benchmark settings
runner := testing.NewBenchmarkRunner()
runner.SetWarmupIterations(2)  // Minimal warmup
runner.SetMinIterations(10)    // Fewer minimum iterations
runner.SetMaxIterations(1000)  // Lower maximum for faster results
runner.SetMinTime(500 * time.Millisecond) // Shorter minimum time
Memory Management
// Clear benchmark results to free memory
runner.Clear()

// Clear mock state
mockLogger.Clear()
mockRenderer.Clear()

// Clear profiler data
profiler.Clear()

Security Notes

Test Data Protection
  • Mock components isolate test data from production systems
  • In-memory filesystems prevent accidental file system modifications
  • Snapshot directories should be properly secured in CI/CD environments
Security Best Practices
  1. Isolate test environments from production data
  2. Sanitize test data to avoid exposing sensitive information
  3. Use temporary directories for snapshot storage during testing
  4. Regular cleanup of test artifacts and temporary files
Sensitive Data Handling
// Avoid storing sensitive data in snapshots
sensitiveData := map[string]string{
    "password": "secret123",
    "api_key":  "key_abc123",
}

// Use mock data instead
mockData := map[string]string{
    "password": "[REDACTED]",
    "api_key":  "[REDACTED]",
}

Thread Safety

All public functions and types in this package are thread-safe and can be used concurrently from multiple goroutines.

Concurrent Usage Examples
// Safe concurrent benchmark runs
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
    wg.Add(1)
    go func(id int) {
        defer wg.Done()
        runner.Benchmark(fmt.Sprintf("test_%d", id), testFunc)
    }(i)
}
wg.Wait()

// Safe concurrent mock usage
go func() {
    mockLogger.Info("Goroutine 1 message")
}()

go func() {
    mockLogger.Error("Goroutine 2 message")
}()

Advanced Features

Custom Benchmark Analysis
runner := testing.NewBenchmarkRunner()
// ... run benchmarks

report := runner.GenerateReport()
fmt.Printf("Success rate: %.2f%%\n", 
    float64(report.Summary.SuccessfulRuns)/float64(report.Summary.TotalBenchmarks)*100)

// Export detailed results
err := runner.ExportReport("benchmark_results.json")
Snapshot Test Suites
suite := testing.NewSnapshotTestSuite("testdata/snapshots", false)
suite.AddTestCase("user_profile", "templates/user.tmpl", map[string]any{
    "Name":  "John Doe",
    "Email": "[email protected]",
})

// Load test cases from file
err := suite.LoadTestCases("testdata/test_cases.json")

// Save test cases for reuse
err = suite.SaveTestCases("testdata/updated_cases.json")
Performance Profiling
profiler := testing.NewPerformanceProfiler()

// Profile multiple operations
profiler.StartProfile("template_parsing")
// ... parsing operations
profiler.EndProfile("template_parsing")

profiler.StartProfile("template_rendering")  
// ... rendering operations
profiler.EndProfile("template_rendering")

// Analyze all profiles
profiles := profiler.GetAllProfiles()
for name, profile := range profiles {
    fmt.Printf("%s: %v (memory: %d bytes)\n", 
        name, profile.Duration, profile.MemoryProfile.HeapAllocDelta)
}

Integration Examples

With Standard Testing
func TestTemplateRendering(t *testing.T) {
    runner := testing.NewBenchmarkRunner()
    
    result := runner.Benchmark("user_template", func() error {
        return renderUserTemplate(userData)
    })
    
    if !result.Success {
        t.Errorf("Benchmark failed: %s", result.Error)
    }
    
    if result.AvgDuration > 10*time.Millisecond {
        t.Errorf("Template rendering too slow: %v", result.AvgDuration)
    }
}
With Snapshot Testing
func TestTemplateSnapshots(t *testing.T) {
    manager := testing.NewSnapshotManager("testdata/snapshots", 
        os.Getenv("UPDATE_SNAPSHOTS") == "true")
    
    testCases := []struct {
        name string
        tmpl string  
        data map[string]any
    }{
        {"user_card", "templates/user_card.tmpl", userData},
        {"product_list", "templates/products.tmpl", productData},
    }
    
    for _, tc := range testCases {
        t.Run(tc.name, func(t *testing.T) {
            output, err := renderTemplate(tc.tmpl, tc.data)
            if err != nil {
                t.Fatal(err)
            }
            
            if err := manager.AssertSnapshot(tc.name, output); err != nil {
                t.Error(err)
            }
        })
    }
}
With Mock Testing
func TestWithMocks(t *testing.T) {
    // Setup mocks
    mockFS := testing.NewMockFS()
    mockFS.AddFile("template.tmpl", "Hello {{.Name}}!")
    
    mockLogger := testing.NewMockLogger()
    mockRenderer := testing.NewMockRenderer()
    
    // Configure mock behavior
    mockRenderer.SetRenderFunc(func(path string, data any) (string, error) {
        if path == "error.tmpl" {
            return "", fmt.Errorf("template error")
        }
        return fmt.Sprintf("rendered: %s", path), nil
    })
    
    // Test with mocks
    result, err := mockRenderer.Render("template.tmpl", map[string]string{"Name": "Test"})
    
    // Verify mock interactions
    assert.NoError(t, err)
    assert.True(t, mockRenderer.WasCalled("template.tmpl"))
    assert.Equal(t, 1, mockRenderer.GetCallCount())
}

Documentation

Overview

Package testing provides utilities for testing and benchmarking.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BenchmarkComparison

type BenchmarkComparison struct {
	Name1               string  `json:"name1"`
	Name2               string  `json:"name2"`
	SpeedRatio          float64 `json:"speed_ratio"`
	MemoryRatio         float64 `json:"memory_ratio"`
	AllocRatio          float64 `json:"alloc_ratio"`
	Result1Faster       bool    `json:"result1_faster"`
	Result1MemEfficient bool    `json:"result1_mem_efficient"`
}

func (BenchmarkComparison) String

func (bc BenchmarkComparison) String() string

type BenchmarkFunc

type BenchmarkFunc func() error

type BenchmarkReport

type BenchmarkReport struct {
	GeneratedAt time.Time         `json:"generated_at"`
	Results     []BenchmarkResult `json:"results"`
	Summary     BenchmarkSummary  `json:"summary"`
	SystemInfo  SystemInfo        `json:"system_info"`
}

type BenchmarkResult

type BenchmarkResult struct {
	Name          string        `json:"name"`
	Iterations    int           `json:"iterations"`
	TotalDuration time.Duration `json:"total_duration"`
	AvgDuration   time.Duration `json:"avg_duration"`
	MinDuration   time.Duration `json:"min_duration"`
	MaxDuration   time.Duration `json:"max_duration"`
	MemoryUsed    int64         `json:"memory_used"`
	AllocsPerOp   int64         `json:"allocs_per_op"`
	BytesPerOp    int64         `json:"bytes_per_op"`
	Timestamp     time.Time     `json:"timestamp"`
	Success       bool          `json:"success"`
	Error         string        `json:"error,omitempty"`
}

type BenchmarkRunner

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

func NewBenchmarkRunner

func NewBenchmarkRunner() *BenchmarkRunner

func (*BenchmarkRunner) Benchmark

func (br *BenchmarkRunner) Benchmark(name string, fn BenchmarkFunc) BenchmarkResult

func (*BenchmarkRunner) Clear

func (br *BenchmarkRunner) Clear()

func (*BenchmarkRunner) Compare

func (br *BenchmarkRunner) Compare(name1, name2 string) (BenchmarkComparison, error)

func (*BenchmarkRunner) ExportReport

func (br *BenchmarkRunner) ExportReport(filename string) error

func (*BenchmarkRunner) GenerateReport

func (br *BenchmarkRunner) GenerateReport() BenchmarkReport

func (*BenchmarkRunner) GetResult

func (br *BenchmarkRunner) GetResult(name string) (BenchmarkResult, bool)

func (*BenchmarkRunner) GetResults

func (br *BenchmarkRunner) GetResults() []BenchmarkResult

func (*BenchmarkRunner) PrintResults

func (br *BenchmarkRunner) PrintResults()

func (*BenchmarkRunner) SetMaxIterations

func (br *BenchmarkRunner) SetMaxIterations(n int)

func (*BenchmarkRunner) SetMinIterations

func (br *BenchmarkRunner) SetMinIterations(n int)

func (*BenchmarkRunner) SetMinTime

func (br *BenchmarkRunner) SetMinTime(d time.Duration)

func (*BenchmarkRunner) SetWarmupIterations

func (br *BenchmarkRunner) SetWarmupIterations(n int)

type BenchmarkSummary

type BenchmarkSummary struct {
	TotalBenchmarks int           `json:"total_benchmarks"`
	SuccessfulRuns  int           `json:"successful_runs"`
	FailedRuns      int           `json:"failed_runs"`
	TotalDuration   time.Duration `json:"total_duration"`
	AvgDuration     time.Duration `json:"avg_duration"`
	FastestBench    string        `json:"fastest_bench"`
	SlowestBench    string        `json:"slowest_bench"`
}

type MemoryFS

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

func NewMemoryFS

func NewMemoryFS() *MemoryFS

func (*MemoryFS) Open

func (mfs *MemoryFS) Open(name string) (fs.File, error)

func (*MemoryFS) ReadDir

func (mfs *MemoryFS) ReadDir(name string) ([]fs.DirEntry, error)

func (*MemoryFS) WalkDir

func (mfs *MemoryFS) WalkDir(root string, fn fs.WalkDirFunc) error

func (*MemoryFS) WriteFile

func (mfs *MemoryFS) WriteFile(name string, data []byte)

type MemoryFile

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

func (*MemoryFile) IsDir

func (f *MemoryFile) IsDir() bool

func (*MemoryFile) ModTime

func (f *MemoryFile) ModTime() time.Time

func (*MemoryFile) Mode

func (f *MemoryFile) Mode() fs.FileMode

func (*MemoryFile) Name

func (f *MemoryFile) Name() string

func (*MemoryFile) Size

func (f *MemoryFile) Size() int64

func (*MemoryFile) Sys

func (f *MemoryFile) Sys() any

type MemoryProfile

type MemoryProfile struct {
	StartAllocs    uint64 `json:"start_allocs"`
	EndAllocs      uint64 `json:"end_allocs"`
	AllocsDelta    uint64 `json:"allocs_delta"`
	StartHeapAlloc uint64 `json:"start_heap_alloc"`
	EndHeapAlloc   uint64 `json:"end_heap_alloc"`
	HeapAllocDelta int64  `json:"heap_alloc_delta"`
	StartSys       uint64 `json:"start_sys"`
	EndSys         uint64 `json:"end_sys"`
	SysDelta       int64  `json:"sys_delta"`
}

type MockDir

type MockDir struct {
	Name    string
	Entries []fs.DirEntry
	ModTime time.Time
	Mode    fs.FileMode
}

type MockDirEntry

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

func (MockDirEntry) Info

func (mde MockDirEntry) Info() (fs.FileInfo, error)

func (MockDirEntry) IsDir

func (mde MockDirEntry) IsDir() bool

func (MockDirEntry) Name

func (mde MockDirEntry) Name() string

func (MockDirEntry) Type

func (mde MockDirEntry) Type() fs.FileMode

type MockDirHandle

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

func (*MockDirHandle) Close

func (mdh *MockDirHandle) Close() error

func (*MockDirHandle) Read

func (mdh *MockDirHandle) Read([]byte) (int, error)

func (*MockDirHandle) Stat

func (mdh *MockDirHandle) Stat() (fs.FileInfo, error)

type MockFS

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

func NewMockFS

func NewMockFS() *MockFS

func (*MockFS) AddDir

func (mfs *MockFS) AddDir(path string)

func (*MockFS) AddFile

func (mfs *MockFS) AddFile(path string, content string)

func (*MockFS) AddFileWithMode

func (mfs *MockFS) AddFileWithMode(path string, content string, mode fs.FileMode)

func (*MockFS) Open

func (mfs *MockFS) Open(name string) (fs.File, error)

func (*MockFS) ReadDir

func (mfs *MockFS) ReadDir(name string) ([]fs.DirEntry, error)

func (*MockFS) ReadFile

func (mfs *MockFS) ReadFile(name string) ([]byte, error)

func (*MockFS) RemoveDir

func (mfs *MockFS) RemoveDir(path string)

func (*MockFS) RemoveFile

func (mfs *MockFS) RemoveFile(path string)

func (*MockFS) Stat

func (mfs *MockFS) Stat(name string) (fs.FileInfo, error)

func (*MockFS) WalkDir

func (mfs *MockFS) WalkDir(root string, fn fs.WalkDirFunc) error

type MockFile

type MockFile struct {
	Name    string
	Content []byte
	ModTime time.Time
	Mode    fs.FileMode
}

type MockFileHandle

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

func (*MockFileHandle) Close

func (mfh *MockFileHandle) Close() error

func (*MockFileHandle) Read

func (mfh *MockFileHandle) Read(b []byte) (int, error)

func (*MockFileHandle) Stat

func (mfh *MockFileHandle) Stat() (fs.FileInfo, error)

type MockFileInfo

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

func (MockFileInfo) IsDir

func (mfi MockFileInfo) IsDir() bool

func (MockFileInfo) ModTime

func (mfi MockFileInfo) ModTime() time.Time

func (MockFileInfo) Mode

func (mfi MockFileInfo) Mode() fs.FileMode

func (MockFileInfo) Name

func (mfi MockFileInfo) Name() string

func (MockFileInfo) Size

func (mfi MockFileInfo) Size() int64

func (MockFileInfo) Sys

func (mfi MockFileInfo) Sys() any

type MockLogEntry

type MockLogEntry struct {
	Level   string    `json:"level"`
	Message string    `json:"message"`
	Args    []any     `json:"args"`
	Time    time.Time `json:"time"`
}

type MockLogger

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

func NewMockLogger

func NewMockLogger() *MockLogger

func (*MockLogger) Clear

func (ml *MockLogger) Clear()

func (*MockLogger) CountByLevel

func (ml *MockLogger) CountByLevel(level string) int

func (*MockLogger) Debug

func (ml *MockLogger) Debug(msg string, args ...any)

func (*MockLogger) Error

func (ml *MockLogger) Error(msg string, args ...any)

func (*MockLogger) GetLogs

func (ml *MockLogger) GetLogs() []MockLogEntry

func (*MockLogger) GetLogsByLevel

func (ml *MockLogger) GetLogsByLevel(level string) []MockLogEntry

func (*MockLogger) HasMessage

func (ml *MockLogger) HasMessage(message string) bool

func (*MockLogger) Info

func (ml *MockLogger) Info(msg string, args ...any)

func (*MockLogger) Warn

func (ml *MockLogger) Warn(msg string, args ...any)

type MockRenderCall

type MockRenderCall struct {
	TemplatePath string    `json:"template_path"`
	Data         any       `json:"data"`
	Result       string    `json:"result"`
	Error        string    `json:"error,omitempty"`
	Timestamp    time.Time `json:"timestamp"`
}

type MockRenderer

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

func NewMockRenderer

func NewMockRenderer() *MockRenderer

func (*MockRenderer) Clear

func (mr *MockRenderer) Clear()

func (*MockRenderer) GetCallCount

func (mr *MockRenderer) GetCallCount() int

func (*MockRenderer) GetCalls

func (mr *MockRenderer) GetCalls() []MockRenderCall

func (*MockRenderer) GetCallsForTemplate

func (mr *MockRenderer) GetCallsForTemplate(templatePath string) []MockRenderCall

func (*MockRenderer) Render

func (mr *MockRenderer) Render(templatePath string, data any) (string, error)

func (*MockRenderer) SetRenderFunc

func (mr *MockRenderer) SetRenderFunc(fn func(templatePath string, data any) (string, error))

func (*MockRenderer) WasCalled

func (mr *MockRenderer) WasCalled(templatePath string) bool

type OperationProfile

type OperationProfile struct {
	Name      string        `json:"name"`
	Count     int           `json:"count"`
	TotalTime time.Duration `json:"total_time"`
	AvgTime   time.Duration `json:"avg_time"`
	MinTime   time.Duration `json:"min_time"`
	MaxTime   time.Duration `json:"max_time"`
}

type PerformanceProfile

type PerformanceProfile struct {
	Name            string                 `json:"name"`
	StartTime       time.Time              `json:"start_time"`
	EndTime         time.Time              `json:"end_time"`
	Duration        time.Duration          `json:"duration"`
	Operations      []OperationProfile     `json:"operations"`
	MemoryProfile   MemoryProfile          `json:"memory_profile"`
	SystemResources SystemResourcesProfile `json:"system_resources"`
}

type PerformanceProfiler

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

func NewPerformanceProfiler

func NewPerformanceProfiler() *PerformanceProfiler

func (*PerformanceProfiler) Clear

func (pp *PerformanceProfiler) Clear()

func (*PerformanceProfiler) EndProfile

func (pp *PerformanceProfiler) EndProfile(name string)

func (*PerformanceProfiler) GetAllProfiles

func (pp *PerformanceProfiler) GetAllProfiles() map[string]PerformanceProfile

func (*PerformanceProfiler) GetProfile

func (pp *PerformanceProfiler) GetProfile(name string) (PerformanceProfile, bool)

func (*PerformanceProfiler) StartProfile

func (pp *PerformanceProfiler) StartProfile(name string)

type SnapshotManager

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

func NewSnapshotManager

func NewSnapshotManager(snapshotDir string, updateMode bool) *SnapshotManager

func (*SnapshotManager) AssertSnapshot

func (sm *SnapshotManager) AssertSnapshot(testName, actual string) error

func (*SnapshotManager) CleanOrphanSnapshots

func (sm *SnapshotManager) CleanOrphanSnapshots(activeTests []string) error

func (*SnapshotManager) Clear

func (sm *SnapshotManager) Clear()

func (*SnapshotManager) GetResults

func (sm *SnapshotManager) GetResults() map[string]SnapshotResult

func (*SnapshotManager) GetSummary

func (sm *SnapshotManager) GetSummary() SnapshotSummary

func (*SnapshotManager) SetUpdateMode

func (sm *SnapshotManager) SetUpdateMode(update bool)

type SnapshotReporter

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

func NewSnapshotReporter

func NewSnapshotReporter() *SnapshotReporter

func (*SnapshotReporter) AddResult

func (sr *SnapshotReporter) AddResult(result SnapshotResult)

func (*SnapshotReporter) ExportJSON

func (sr *SnapshotReporter) ExportJSON(filename string) error

func (*SnapshotReporter) GenerateReport

func (sr *SnapshotReporter) GenerateReport() string

type SnapshotResult

type SnapshotResult struct {
	TestName     string    `json:"test_name"`
	Expected     string    `json:"expected"`
	Actual       string    `json:"actual"`
	Passed       bool      `json:"passed"`
	Hash         string    `json:"hash"`
	Timestamp    time.Time `json:"timestamp"`
	FilePath     string    `json:"file_path"`
	UpdatedCount int       `json:"updated_count"`
}

type SnapshotSummary

type SnapshotSummary struct {
	TotalTests   int  `json:"total_tests"`
	PassedTests  int  `json:"passed_tests"`
	FailedTests  int  `json:"failed_tests"`
	UpdatedTests int  `json:"updated_tests"`
	UpdateMode   bool `json:"update_mode"`
}

func (SnapshotSummary) String

func (ss SnapshotSummary) String() string

type SnapshotTestCase

type SnapshotTestCase struct {
	Name     string         `json:"name"`
	Template string         `json:"template"`
	Data     map[string]any `json:"data"`
	Expected string         `json:"expected"`
}

type SnapshotTestSuite

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

func NewSnapshotTestSuite

func NewSnapshotTestSuite(snapshotDir string, updateMode bool) *SnapshotTestSuite

func (*SnapshotTestSuite) AddTestCase

func (sts *SnapshotTestSuite) AddTestCase(name, template string, data map[string]any)

func (*SnapshotTestSuite) GetManager

func (sts *SnapshotTestSuite) GetManager() *SnapshotManager

func (*SnapshotTestSuite) GetTestCases

func (sts *SnapshotTestSuite) GetTestCases() []SnapshotTestCase

func (*SnapshotTestSuite) LoadTestCases

func (sts *SnapshotTestSuite) LoadTestCases(testFile string) error

func (*SnapshotTestSuite) SaveTestCases

func (sts *SnapshotTestSuite) SaveTestCases(testFile string) error

type SystemInfo

type SystemInfo struct {
	NumCPU       int              `json:"num_cpu"`
	NumGoroutine int              `json:"num_goroutine"`
	GOOS         string           `json:"goos"`
	GOARCH       string           `json:"goarch"`
	GoVersion    string           `json:"go_version"`
	MemStats     runtime.MemStats `json:"mem_stats"`
}

type SystemResourcesProfile

type SystemResourcesProfile struct {
	NumGoroutines int    `json:"num_goroutines"`
	NumCPU        int    `json:"num_cpu"`
	GOOS          string `json:"goos"`
	GOARCH        string `json:"goarch"`
}

Jump to

Keyboard shortcuts

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