testhelpers

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Feb 7, 2026 License: MIT Imports: 20 Imported by: 0

Documentation

Overview

Package testhelpers provides performance baseline management for testing

Package testhelpers provides shared utilities for testing Lightning Code Index

Package testhelpers provides test performance monitoring and optimization suggestions

Package testhelpers provides shared utilities for testing Lightning Code Index

Index

Constants

This section is empty.

Variables

View Source
var TestData = struct {
	GoSimple   string
	GoComplex  string
	Javascript string
	Python     string
	MultiLang  map[string]string
}{
	GoSimple: `package main

import "fmt"

func hello() {
	fmt.Println("Hello, World!")
}

func main() {
	hello()
}`,

	GoComplex: `package service

import (
	"context"
	"errors"
	"time"
)

type Service struct {
	timeout time.Duration
}

func NewService(timeout time.Duration) *Service {
	return &Service{timeout: timeout}
}

func (s *Service) Process(ctx context.Context, data string) (string, error) {
	if data == "" {
		return "", errors.New("empty data")
	}

	select {
	case <-time.After(s.timeout):
		return "", errors.New("timeout")
	case <-ctx.Done():
		return "", ctx.Err()
	default:
		return "processed: " + data, nil
	}
}`,

	Javascript: `function calculateSum(a, b) {
	return a + b;
}

class Calculator {
	constructor() {
		this.result = 0;
	}

	add(value) {
		this.result += value;
		return this;
	}

	multiply(value) {
		this.result *= value;
		return this;
	}

	getResult() {
		return this.result;
	}
}

const calculator = new Calculator();
export { calculateSum, Calculator };`,

	Python: `def calculate_fibonacci(n):
    """Calculate the nth Fibonacci number."""
    if n <= 1:
        return n
    return calculate_fibonacci(n-1) + calculate_fibonacci(n-2)

class DataProcessor:
    def __init__(self, name):
        self.name = name
        self.data = []

    def add_data(self, item):
        self.data.append(item)

    def process_data(self):
        return [item.upper() for item in self.data if isinstance(item, str)]

    def __str__(self):
        return f"DataProcessor({self.name})"

if __name__ == "__main__":
    processor = DataProcessor("test")
    processor.add_data("hello")
    processor.add_data("world")
    print(processor.process_data())`,
}

TestData provides access to common test data patterns

Functions

func AnalyzeDebugLogs

func AnalyzeDebugLogs(logDir string) error

AnalyzeDebugLogs analyzes debug logs for patterns and issues

func AssertNoLeaks

func AssertNoLeaks(t *testing.T)

AssertNoLeaks verifies no goroutine leaks occurred during the test

func CleanupOldLogs

func CleanupOldLogs(logDir string, maxAge time.Duration) error

CleanupOldLogs removes old debug log files

func ConcurrentSafeTest

func ConcurrentSafeTest(t *testing.T, testName string, testFunc func(t *testing.T))

ConcurrentSafeTest runs a test with proper concurrent safety

func ConcurrentTestWrapper

func ConcurrentTestWrapper(t *testing.T, testName string, numGoroutines int, testFunc func(t *testing.T, goroutineID int))

ConcurrentTestWrapper provides a safe pattern for concurrent testing

func ConfigureTestEnvironment

func ConfigureTestEnvironment(t *testing.T, config IsolatedTestConfig) context.Context

ConfigureTestEnvironment sets up the test environment according to config

func DebugTest

func DebugTest(t *testing.T, level DebugLevel, testFunc func(*TestDebugHelper))

DebugTest is a helper function that runs a test with debugging

func DisablePerformanceDemo

func DisablePerformanceDemo()

DisablePerformanceDemo disables the performance demo that interferes with tests

func FindFlakyTestReports

func FindFlakyTestReports(rootDir string) ([]string, error)

FindFlakyTestReports searches for existing flaky test reports

func GenerateFlakyTestReport

func GenerateFlakyTestReport(flakyTests []*FlakyTest) string

GenerateFlakyTestReport creates a comprehensive report of flaky tests (legacy function)

func GetDebugLogs

func GetDebugLogs(logDir string) ([]string, error)

GetDebugLogs returns paths to all debug log files

func GetGlobalLock

func GetGlobalLock(name string) *sync.RWMutex

GetGlobalLock returns a named global lock for critical sections

func GetMultiLangProject

func GetMultiLangProject() map[string]string

GetMultiLangProject returns a test project with multiple language files

func IsolateTest

func IsolateTest(t *testing.T, testName string, testFunc func(t *testing.T))

IsolateTest creates a new isolated test environment

func IsolatedFileContentStoreTest

func IsolatedFileContentStoreTest(t *testing.T, testName string, testFunc func(t *testing.T, store *core.FileContentStore))

IsolatedFileContentStoreTest provides a pattern for testing FileContentStore in isolation

func IsolatedIndexCoordinatorTest

func IsolatedIndexCoordinatorTest(t *testing.T, testName string, testFunc func(t *testing.T, coordinator *core.DefaultIndexCoordinator))

IsolatedIndexCoordinatorTest provides a pattern for testing IndexCoordinator in isolation

func IsolatedTrigramIndexTest

func IsolatedTrigramIndexTest(t *testing.T, testName string, testFunc func(t *testing.T, index *core.TrigramIndex))

IsolatedTrigramIndexTest provides a pattern for testing TrigramIndex in isolation

func LoadFlakyTestReport

func LoadFlakyTestReport(filepath string) (string, error)

LoadFlakyTestReport loads a flaky test report from a file

func MarkFlaky

func MarkFlaky(t *testing.T, reason string)

MarkFlaky marks a test as flaky with a reason Usage: testhelpers.MarkFlaky(t, "Race condition in cleanup")

func MonitorTest

func MonitorTest(t *testing.T, monitor *TestPerformanceMonitor, packageName, testName string, testFunc func())

MonitorTest is a helper function that monitors a test execution

func MonitorTestWithBaseline

func MonitorTestWithBaseline(t *testing.T, monitor *TestPerformanceMonitor, packageName, testName string, testFunc func())

MonitorTestWithBaseline is a helper that also compares against baselines

func ParseTestName

func ParseTestName(testIdentifier string) (packageName, testName string)

ParseTestName extracts package and test name from a test identifier

func PerformanceTestWrapper

func PerformanceTestWrapper(t *testing.T, testName string, testFunc func(t *testing.T))

PerformanceTestWrapper provides safe performance testing that doesn't interfere with other tests

func PopulateTestIndexes

func PopulateTestIndexes(symbolIndex, refTracker, fileID, path interface{}, symbols interface{})

PopulateTestIndexes properly indexes symbols in both SymbolIndex and ReferenceTracker This is required for tests that manually create components instead of using SetupTestIndex Usage:

import "github.com/standardbeagle/lci/internal/core"
import "github.com/standardbeagle/lci/internal/types"

symbols := []types.Symbol{...}
testhelpers.PopulateTestIndexes(
	symbolIndex,
	refTracker,
	fileID,
	"test.go",
	symbols,
)

This ensures that ContextLookupEngine.GetContext() can find symbols via ReferenceTracker. The function uses reflection to work with the core types without requiring direct imports here.

func PropertyTestWrapper

func PropertyTestWrapper(t *testing.T, testName string, iterations int, testFunc func(t *testing.T, iteration int))

PropertyTestWrapper provides a pattern for property-based tests with proper isolation

func RegisterCleanup

func RegisterCleanup(cleanup func())

RegisterCleanup adds a cleanup function to be called after test completion

func ReplayTest

func ReplayTest(logPath string) error

ReplayTest replays a test execution from saved debug data

func ReportMetric

func ReportMetric(t *testing.T, baseline *PerformanceBaseline, name string, value float64, unit string)

ReportMetric records a performance metric and compares against baseline

func RetryWithBackoff

func RetryWithBackoff(t *testing.T, opts RetryOptions, fn func() error) error

RetryWithBackoff retries a function with exponential backoff Usage:

err := testhelpers.RetryWithBackoff(t, testhelpers.RetryOptions{
    MaxAttempts: 5,
    BaseDelay:   100 * time.Millisecond,
    MaxDelay:    2 * time.Second,
    Jitter:      true,
}, func() error {
    return performOperation()
})

func SaveBenchmarkResult

func SaveBenchmarkResult(filePath string, result *BenchmarkResult) error

SaveBenchmarkResult saves a benchmark result for later comparison

func SaveFlakyTestReport

func SaveFlakyTestReport(report string, filepath string) error

SaveFlakyTestReport saves the flaky test report to a file

func SkipIfShort

func SkipIfShort(t *testing.T, reason string)

SkipIfShort skips the test if -short flag is provided

func SkipInCI

func SkipInCI(t *testing.T, reason string)

SkipInCI skips the test if running in CI environment

func WaitFor

func WaitFor(t *testing.T, condition func() bool, timeout time.Duration)

WaitFor waits for a condition to become true with timeout Usage:

testhelpers.WaitFor(t, func() bool {
    return index.IsReady()
}, 5*time.Second)

func WaitForCleanup

func WaitForCleanup(t *testing.T, timeout time.Duration)

WaitForCleanup waits for background operations to complete Used in tests that spawn goroutines to ensure proper cleanup

func WaitForWithJitter

func WaitForWithJitter(t *testing.T, opts RetryOptions, condition func() bool) error

WaitForWithJitter waits for a condition with exponential backoff retry Usage:

err := testhelpers.WaitForWithJitter(t, testhelpers.RetryOptions{
    MaxAttempts: 5,
    BaseDelay:   50 * time.Millisecond,
    Jitter:      true,
}, func() bool {
    return checkResourceCleaned()
})

Types

type BaselineMetric

type BaselineMetric struct {
	Name        string    `json:"name"`
	Value       float64   `json:"value"`
	Unit        string    `json:"unit"`
	Threshold   float64   `json:"threshold"` // Acceptable deviation percentage
	Description string    `json:"description"`
	Source      string    `json:"source"` // "best_case", "average", "manual"
	Established time.Time `json:"established"`
	Updated     time.Time `json:"updated"`
}

BaselineMetric represents a performance measurement baseline

type BenchmarkResult

type BenchmarkResult struct {
	Name        string        `json:"name"`
	NsPerOp     int64         `json:"ns_per_op"`
	AllocsPerOp int64         `json:"allocs_per_op"`
	BytesPerOp  int64         `json:"bytes_per_op"`
	Iterations  int64         `json:"iterations"`
	Duration    time.Duration `json:"duration"`
	Timestamp   time.Time     `json:"timestamp"`
}

BenchmarkResult represents a benchmark execution result

func LoadBenchmarkResults

func LoadBenchmarkResults(filePath string) ([]*BenchmarkResult, error)

LoadBenchmarkResults loads benchmark results from file

type CleanupOperation

type CleanupOperation struct {
	Name      string
	Operation func() error
	Timeout   time.Duration
}

CleanupOperation represents a cleanup operation

type CommonTestPatterns

type CommonTestPatterns struct {
	GlobalVarPattern   string
	GlobalConstPattern string
	GlobalTypePattern  string
	GlobalFuncPattern  string
}

CommonTestPatterns provides conversion patterns for common shared state scenarios

func GetCommonPatterns

func GetCommonPatterns() *CommonTestPatterns

GetCommonPatterns returns common patterns for converting shared state

type ComparisonResult

type ComparisonResult struct {
	Name        string  `json:"name"`
	Passed      bool    `json:"passed"`
	Message     string  `json:"message"`
	Value       float64 `json:"value"`
	Unit        string  `json:"unit"`
	Baseline    float64 `json:"baseline"`
	Deviation   float64 `json:"deviation"`
	Threshold   float64 `json:"threshold"`
	Description string  `json:"description"`
}

ComparisonResult represents the result of comparing against a baseline

type CompletionSignal

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

CompletionSignal is a reusable signal for operation completion.

func NewCompletionSignal

func NewCompletionSignal() *CompletionSignal

NewCompletionSignal creates a new completion signal.

func (*CompletionSignal) Complete

func (cs *CompletionSignal) Complete()

Complete signals that the operation is complete. Safe to call multiple times (only first call takes effect).

func (*CompletionSignal) Done

func (cs *CompletionSignal) Done() <-chan struct{}

Done returns the completion channel for use in select statements.

func (*CompletionSignal) Wait

func (cs *CompletionSignal) Wait(timeout time.Duration) bool

Wait waits for completion or timeout. Returns true if completed, false if timeout.

func (*CompletionSignal) WaitCtx

func (cs *CompletionSignal) WaitCtx(ctx context.Context) bool

WaitCtx waits for completion or context cancellation. Returns true if completed, false if context cancelled.

type ComprehensiveTestRunner

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

ComprehensiveTestRunner provides a complete test execution environment

func NewComprehensiveTestRunner

func NewComprehensiveTestRunner(t *testing.T) *ComprehensiveTestRunner

NewComprehensiveTestRunner creates a comprehensive test runner

func (*ComprehensiveTestRunner) AddCleanup

func (ctr *ComprehensiveTestRunner) AddCleanup(name string, cleanup func() error) *ComprehensiveTestRunner

AddCleanup adds cleanup operations

func (*ComprehensiveTestRunner) AddTestData

AddTestData adds test data to the runner

func (*ComprehensiveTestRunner) AddValidation

AddValidation adds validation checks

func (*ComprehensiveTestRunner) Run

func (ctr *ComprehensiveTestRunner) Run(testFunc func(*IsolatedTestData, *testing.T))

Run executes a test with comprehensive isolation and validation

func (*ComprehensiveTestRunner) RunParallel

func (ctr *ComprehensiveTestRunner) RunParallel(testFunc func(*IsolatedTestData, *testing.T))

RunParallel executes a test in parallel with comprehensive isolation

type ConditionType

type ConditionType string

ConditionType defines when optimization rules apply

const (
	ConditionSlowExecution ConditionType = "slow_execution"
	ConditionMemoryLeak    ConditionType = "memory_leak"
	ConditionGoroutineLeak ConditionType = "goroutine_leak"
	ConditionLargeSetup    ConditionType = "large_setup"
	ConditionNoCleanup     ConditionType = "no_cleanup"
	ConditionExpensiveOps  ConditionType = "expensive_ops"
)

type ConstDefinition

type ConstDefinition struct {
	Name  string
	Type  string
	Value string
}

ConstDefinition represents a constant declaration

type ConstElement

type ConstElement struct {
	Name  string
	Type  string
	Value string
}

ConstElement represents a constant declaration

func (ConstElement) Generate

func (c ConstElement) Generate() string

type CountdownLatch

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

CountdownLatch allows waiting for N operations to complete.

func NewCountdownLatch

func NewCountdownLatch(count int) *CountdownLatch

NewCountdownLatch creates a latch that waits for count operations.

func (*CountdownLatch) CountDown

func (cl *CountdownLatch) CountDown()

CountDown decrements the latch count. When count reaches zero, all waiters are released.

func (*CountdownLatch) Done

func (cl *CountdownLatch) Done() <-chan struct{}

Done returns the completion channel.

func (*CountdownLatch) GetCount

func (cl *CountdownLatch) GetCount() int

GetCount returns the current count (for debugging).

func (*CountdownLatch) Wait

func (cl *CountdownLatch) Wait(timeout time.Duration) bool

Wait waits for the count to reach zero or timeout. Returns true if completed, false if timeout.

func (*CountdownLatch) WaitCtx

func (cl *CountdownLatch) WaitCtx(ctx context.Context) bool

WaitCtx waits for the count to reach zero or context cancellation.

type DebugConfig

type DebugConfig struct {
	Level             DebugLevel
	LogToFile         bool
	LogDirectory      string
	IncludeStack      bool
	IncludeMemory     bool
	IncludeGoroutines bool
	MaxLogSize        int64 // Max log file size in bytes
}

DebugConfig configures debugging behavior

type DebugLevel

type DebugLevel int

DebugLevel represents different levels of debugging verbosity

const (
	DebugNone DebugLevel = iota
	DebugBasic
	DebugVerbose
	DebugTrace
)

type EventBus

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

EventBus provides a simple event notification system for tests. Components can emit events when state changes occur, allowing tests to synchronize without arbitrary sleeps.

func NewEventBus

func NewEventBus() *EventBus

NewEventBus creates a new event bus for test synchronization.

func (*EventBus) Emit

func (eb *EventBus) Emit(eventType string)

Emit fires an event, notifying all subscribers.

func (*EventBus) Subscribe

func (eb *EventBus) Subscribe(eventType string) <-chan struct{}

Subscribe registers a listener for a specific event type. Returns a channel that will be closed when the event fires.

func (*EventBus) WaitFor

func (eb *EventBus) WaitFor(ctx context.Context, eventType string, timeout time.Duration) bool

WaitFor waits for an event with a timeout. Returns true if event occurred, false if timeout.

func (*EventBus) WaitForAll

func (eb *EventBus) WaitForAll(ctx context.Context, timeout time.Duration, eventTypes ...string) bool

WaitForAll waits for multiple events with a timeout. Returns true if all events occurred, false if timeout.

type FlakyDetectorConfig

type FlakyDetectorConfig struct {
	MinimumRuns             int           `json:"minimum_runs"`
	FlakinessThreshold      float64       `json:"flakiness_threshold"`
	RecentRunsWindow        time.Duration `json:"recent_runs_window"`
	PatternDetectionEnabled bool          `json:"pattern_detection_enabled"`
	Environment             string        `json:"environment"`
}

FlakyDetectorConfig configures the flaky detection algorithm

func DefaultFlakyDetectorConfig

func DefaultFlakyDetectorConfig() FlakyDetectorConfig

DefaultFlakyDetectorConfig returns a sensible default configuration

type FlakyPattern

type FlakyPattern struct {
	Name        string                 `json:"name"`
	Description string                 `json:"description"`
	Detector    func(*TestResult) bool `json:"-"`
	Weight      float64                `json:"weight"`
}

FlakyPattern represents a common flaky test pattern

type FlakyStatus

type FlakyStatus string

FlakyStatus represents the current status of a flaky test

const (
	StatusActive   FlakyStatus = "active"
	StatusIsolated FlakyStatus = "isolated"
	StatusFixed    FlakyStatus = "fixed"
	StatusIgnored  FlakyStatus = "ignored"
)

type FlakyTest

type FlakyTest struct {
	PackageName    string      `json:"package_name"`
	TestName       string      `json:"test_name"`
	FirstDetected  time.Time   `json:"first_detected"`
	LastOccurrence time.Time   `json:"last_occurrence"`
	TotalRuns      int         `json:"total_runs"`
	FailureCount   int         `json:"failure_count"`
	FailureRate    float64     `json:"failure_rate"`
	Status         FlakyStatus `json:"status"`
	Notes          string      `json:"notes"`
	Patterns       []string    `json:"patterns"`
}

FlakyTest represents a test with inconsistent behavior

func RunFlakyTestDetection

func RunFlakyTestDetection(t *testing.T, testResults []*TestResult) ([]*FlakyTest, error)

RunFlakyTestDetection runs the flaky test detection algorithm on test results

func RunMultipleTestAttempts

func RunMultipleTestAttempts(t *testing.T, testName string, attempts int, testFunc func(t *testing.T)) (*FlakyTest, error)

RunMultipleTestAttempts runs a test multiple times to detect flakiness

type FlakyTestCategoryReport

type FlakyTestCategoryReport struct {
	Name  string       `json:"name"`
	Count int          `json:"count"`
	Tests []*FlakyTest `json:"tests"`
}

FlakyTestCategoryReport represents a category of flaky tests

type FlakyTestDetector

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

FlakyTestDetector analyzes test results to detect flaky behavior

func NewFlakyTestDetector

func NewFlakyTestDetector(config FlakyDetectorConfig) *FlakyTestDetector

NewFlakyTestDetector creates a new flaky test detector

func (*FlakyTestDetector) AnalyzeTestResult

func (ftd *FlakyTestDetector) AnalyzeTestResult(result *TestResult)

AnalyzeTestResult processes a test result and updates flaky test information

func (*FlakyTestDetector) CalculateFlakinessScore

func (ftd *FlakyTestDetector) CalculateFlakinessScore(flaky *FlakyTest) float64

CalculateFlakinessScore computes a comprehensive flakiness score for a test

func (*FlakyTestDetector) GenerateFlakyTestReport

func (ftd *FlakyTestDetector) GenerateFlakyTestReport() FlakyTestReport

GenerateFlakyTestReport generates a comprehensive report

func (*FlakyTestDetector) GetFlakyTestCategories

func (ftd *FlakyTestDetector) GetFlakyTestCategories() map[string][]*FlakyTest

GetFlakyTestCategories categorizes flaky tests by their patterns

func (*FlakyTestDetector) GetFlakyTestRecommendations

func (ftd *FlakyTestDetector) GetFlakyTestRecommendations() []FlakyTestRecommendation

GetFlakyTestRecommendations provides recommendations for all flaky tests

func (*FlakyTestDetector) GetFlakyTestRecommendationsForTest

func (ftd *FlakyTestDetector) GetFlakyTestRecommendationsForTest(flaky *FlakyTest) []string

GetFlakyTestRecommendationsForTest provides recommendations for a specific flaky test

func (*FlakyTestDetector) GetFlakyTests

func (ftd *FlakyTestDetector) GetFlakyTests() []*FlakyTest

GetFlakyTests returns all detected flaky tests

func (*FlakyTestDetector) IsTestFlaky

func (ftd *FlakyTestDetector) IsTestFlaky(packageName, testName string) bool

IsTestFlaky checks if a test is currently considered flaky

func (*FlakyTestDetector) LoadState

func (ftd *FlakyTestDetector) LoadState(filename string) error

LoadState loads the detector state from a file

func (*FlakyTestDetector) SaveState

func (ftd *FlakyTestDetector) SaveState(filename string) error

SaveState saves the detector state to a file

type FlakyTestOccurrence

type FlakyTestOccurrence struct {
	PackageName   string        `json:"package_name"`
	TestName      string        `json:"test_name"`
	TestRunID     string        `json:"test_run_id"`
	ErrorMessage  string        `json:"error_message"`
	PassedOnRetry bool          `json:"passed_on_retry"`
	Environment   string        `json:"environment"`
	Timestamp     time.Time     `json:"timestamp"`
	Duration      time.Duration `json:"duration"`
}

FlakyTestOccurrence represents an individual instance of flaky behavior

type FlakyTestRecommendation

type FlakyTestRecommendation struct {
	TestName        string   `json:"test_name"`
	PackageName     string   `json:"package_name"`
	FailureRate     float64  `json:"failure_rate"`
	Patterns        []string `json:"patterns"`
	Recommendations []string `json:"recommendations"`
	Priority        int      `json:"priority"`
}

FlakyTestRecommendation represents a recommendation for fixing a flaky test

type FlakyTestReport

type FlakyTestReport struct {
	GeneratedAt     time.Time                 `json:"generated_at"`
	TotalFlakyTests int                       `json:"total_flaky_tests"`
	Categories      []FlakyTestCategoryReport `json:"categories"`
	TopFlakyTests   []*FlakyTest              `json:"top_flaky_tests"`
	AllFlakyTests   []*FlakyTest              `json:"all_flaky_tests"`
}

FlakyTestReport represents a comprehensive flaky test report

type FuncDefinition

type FuncDefinition struct {
	Name       string
	Parameters []string
	ReturnType string
	Body       string
	Exported   bool
}

FuncDefinition represents a function declaration

type FunctionDecl

type FunctionDecl struct {
	Name       string
	Parameters []string
	ReturnType string
	Body       string
	Exported   bool
}

FunctionDecl creates a function declaration

func (FunctionDecl) Generate

func (f FunctionDecl) Generate() string

type GlobalVar

type GlobalVar struct {
	Name  string
	Type  string
	Value string
}

GlobalVar creates a global variable declaration

func (GlobalVar) Generate

func (gv GlobalVar) Generate() string

type GoFileElement

type GoFileElement interface {
	Generate() string
}

GoFileElement represents an element in a Go file

type ImportDecl

type ImportDecl struct {
	Imports []string
}

ImportDecl creates an import declaration

func (ImportDecl) Generate

func (i ImportDecl) Generate() string

type IsolatedTestConfig

type IsolatedTestConfig struct {
	MaxGoroutines      int
	TestTimeout        time.Duration
	EnableRaceDetector bool
	DisablePerformance bool
	IsolateMemory      bool
}

IsolatedTestConfig provides configuration for isolated tests

func DefaultIsolationConfig

func DefaultIsolationConfig() IsolatedTestConfig

DefaultIsolationConfig returns sensible defaults for test isolation

type IsolatedTestData

type IsolatedTestData struct {
	FileStore    *core.FileContentStore
	Files        []*TestFile
	FileInfos    []*types.FileInfo
	AllSymbols   []*types.EnhancedSymbol
	FileContents map[string][]byte
}

IsolatedTestData represents isolated test data

func (*IsolatedTestData) Close

func (itd *IsolatedTestData) Close()

Close cleans up the FileContentStore

func (*IsolatedTestData) GetFile

func (itd *IsolatedTestData) GetFile(name string) *TestFile

GetFile returns a file by name

func (*IsolatedTestData) GetFileInfo

func (itd *IsolatedTestData) GetFileInfo(name string) *types.FileInfo

GetFileInfo returns FileInfo for a file by name

type MemoryTracker

type MemoryTracker interface {
	GetMemoryUsage() int64
}

MemoryTracker interface for memory tracking in tests

type MemoryValidationResult

type MemoryValidationResult struct {
	ContentSize       int64
	GlobalHeapBytes   int64
	StoreMemoryBytes  int64
	GlobalMultiplier  float64
	StoreMultiplier   float64
	BackgroundRunning bool
}

MemoryValidationResult holds the results of a memory validation check

func ValidateFileContentStoreMemory

func ValidateFileContentStoreMemory(t *testing.T, store MemoryTracker, content []byte, maxMultiplier float64) *MemoryValidationResult

ValidateFileContentStoreMemory performs a two-tier memory validation: 1. Quick global MemStats check (can detect obvious issues) 2. Accurate store-specific memory tracking (isolated from background operations) Returns detailed results for test logging and assertion

type MonitorConfig

type MonitorConfig struct {
	SlowTestThresholds    []SlowTestDefinition `json:"slow_test_thresholds"`
	EnableDetailedLogging bool                 `json:"enable_detailed_logging"`
	HistoryRetentionDays  int                  `json:"history_retention_days"`
	BaselineFile          string               `json:"baseline_file"`
	OutputDir             string               `json:"output_dir"`
	AutoSaveInterval      time.Duration        `json:"auto_save_interval"`
}

MonitorConfig configures the performance monitor

type OptimizationRule

type OptimizationRule struct {
	Pattern       string        `json:"pattern"`        // Test name or package pattern
	Category      string        `json:"category"`       // "setup", "execution", "cleanup", "resource"
	Condition     ConditionType `json:"condition"`      // When to apply this rule
	Suggestion    string        `json:"suggestion"`     // Human-readable suggestion
	CodeExample   string        `json:"code_example"`   // Example code fix
	Severity      string        `json:"severity"`       // Impact level
	EstimatedGain time.Duration `json:"estimated_gain"` // Expected improvement
}

OptimizationRule provides suggestions for improving test performance

type PackageDecl

type PackageDecl struct {
	Name string
}

PackageDecl creates a package declaration

func (PackageDecl) Generate

func (p PackageDecl) Generate() string

type PackageDefinition

type PackageDefinition struct {
	Name     string
	Imports  []string
	Vars     []VarDefinition
	Consts   []ConstDefinition
	Types    []TypeDefinition
	Funcs    []FuncDefinition
	Comments []string
}

PackageDefinition represents a Go package structure

type PerformanceBaseline

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

PerformanceBaseline manages performance baselines for operations

func LoadBaseline

func LoadBaseline(filePath string) (*PerformanceBaseline, error)

LoadBaseline loads baselines from file or creates defaults

func NewPerformanceBaseline

func NewPerformanceBaseline(filePath string) *PerformanceBaseline

NewPerformanceBaseline creates a new performance baseline manager

func (*PerformanceBaseline) CompareMetric

func (pb *PerformanceBaseline) CompareMetric(name string, value float64, unit string) *ComparisonResult

CompareMetric compares a measurement against baseline

func (*PerformanceBaseline) GetAllMetrics

func (pb *PerformanceBaseline) GetAllMetrics() map[string]*BaselineMetric

GetAllMetrics returns all baseline metrics

func (*PerformanceBaseline) GetMetric

func (pb *PerformanceBaseline) GetMetric(name string) (*BaselineMetric, bool)

GetMetric returns a specific baseline metric

func (*PerformanceBaseline) SaveBaseline

func (pb *PerformanceBaseline) SaveBaseline() error

SaveBaseline saves baselines to file

func (*PerformanceBaseline) UpdateMetric

func (pb *PerformanceBaseline) UpdateMetric(name string, value float64, unit, source string)

UpdateMetric updates a baseline with new measurement

type PerformanceReport

type PerformanceReport struct {
	GeneratedAt             time.Time                `json:"generated_at"`
	TotalTests              int                      `json:"total_tests"`
	SlowTests               int                      `json:"slow_tests"`
	SlowTestPercentage      float64                  `json:"slow_test_percentage"`
	AverageTestDuration     time.Duration            `json:"average_test_duration"`
	TotalMemoryAllocated    int64                    `json:"total_memory_allocated"`
	GoroutineLeaks          int                      `json:"goroutine_leaks"`
	SlowTestDetails         []*TestPerformanceResult `json:"slow_test_details"`
	OptimizationSuggestions []string                 `json:"optimization_suggestions"`
}

PerformanceReport represents a comprehensive test performance report

type RetryOptions

type RetryOptions struct {
	MaxAttempts int           // Maximum number of attempts
	BaseDelay   time.Duration // Base delay for exponential backoff
	MaxDelay    time.Duration // Maximum delay between attempts
	Jitter      bool          // Add random jitter to delays
	Timeout     time.Duration // Total timeout for all attempts
}

RetryOptions configures retry behavior

func NoRetry

func NoRetry() RetryOptions

NoRetry is a convenience function for WaitFor without retry

type SharedStateConverter

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

SharedStateConverter helps convert shared package-level variables to isolated test data

func NewSharedStateConverter

func NewSharedStateConverter() *SharedStateConverter

NewSharedStateConverter creates a new converter for shared state

func (*SharedStateConverter) ConvertSharedStateFile

func (ssc *SharedStateConverter) ConvertSharedStateFile(content string, packageName string) *TestDataBuilder

ConvertSharedStateFile converts shared state content to isolated test data builder

func (*SharedStateConverter) ConvertTestFile

func (ssc *SharedStateConverter) ConvertTestFile(testContent string, sharedStateContent string) string

ConvertTestFile converts an existing test file that uses shared state to use isolated test data

func (*SharedStateConverter) GenerateIsolatedTestTemplate

func (ssc *SharedStateConverter) GenerateIsolatedTestTemplate(originalTestName string, sharedVars []string) string

GenerateIsolatedTestTemplate creates a template for converting a specific test

type SlowTestDefinition

type SlowTestDefinition struct {
	Name        string        `json:"name"`
	Description string        `json:"description"`
	Threshold   time.Duration `json:"threshold"`
	Unit        string        `json:"unit"`
	Severity    string        `json:"severity"` // "warning", "critical", "info"
	Category    string        `json:"category"` // "setup", "execution", "cleanup", "resource"
}

SlowTestDefinition defines criteria for identifying slow tests

type StringElement

type StringElement string

StringElement represents a raw string element

func (StringElement) Generate

func (s StringElement) Generate() string

type TestCleanupManager

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

TestCleanupManager provides comprehensive cleanup management

func NewTestCleanupManager

func NewTestCleanupManager(t *testing.T) *TestCleanupManager

NewTestCleanupManager creates a new cleanup manager

func (*TestCleanupManager) AddCleanup

func (tcm *TestCleanupManager) AddCleanup(name string, cleanup func() error)

AddCleanup adds a cleanup operation

func (*TestCleanupManager) AddCleanupWithTimeout

func (tcm *TestCleanupManager) AddCleanupWithTimeout(name string, cleanup func() error, timeout time.Duration)

AddCleanupWithTimeout adds a cleanup operation with a custom timeout

func (*TestCleanupManager) AddFileCleanup

func (tcm *TestCleanupManager) AddFileCleanup(filePaths ...string)

AddFileCleanup adds file cleanup operations

func (*TestCleanupManager) AddGoroutineCleanup

func (tcm *TestCleanupManager) AddGoroutineCleanup(stopFuncs ...func())

AddGoroutineCleanup adds goroutine cleanup operations

func (*TestCleanupManager) Execute

func (tcm *TestCleanupManager) Execute()

Execute executes all cleanup operations

type TestConfigBuilder

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

TestConfigBuilder provides a fluent API for building test configs with safe defaults This is intentionally in a separate file to avoid circular dependencies with indexing tests Usage:

cfg := testhelpers.NewTestConfigBuilder(projectPath).
	WithExclusions(".git/**", "vendor/**").
	WithIncludePatterns("*.go", "*.ts").
	Build()

func NewTestConfigBuilder

func NewTestConfigBuilder(projectRoot string) *TestConfigBuilder

NewTestConfigBuilder creates a config builder with safe defaults for a project path

func (*TestConfigBuilder) AddIncludePatterns

func (b *TestConfigBuilder) AddIncludePatterns(patterns ...string) *TestConfigBuilder

AddIncludePatterns adds to the existing include patterns

func (*TestConfigBuilder) Build

func (b *TestConfigBuilder) Build() *config.Config

Build creates the final test config with all settings

func (*TestConfigBuilder) WithExclusions

func (b *TestConfigBuilder) WithExclusions(patterns ...string) *TestConfigBuilder

WithExclusions adds additional exclusion patterns

func (*TestConfigBuilder) WithIncludePatterns

func (b *TestConfigBuilder) WithIncludePatterns(patterns ...string) *TestConfigBuilder

WithIncludePatterns sets the include patterns (replaces defaults)

type TestDataBuilder

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

TestDataBuilder provides isolated test data creation without shared state

func GoFileWithFunctions

func GoFileWithFunctions(name, packageName string, functions []FunctionDecl) *TestDataBuilder

GoFileWithFunctions creates a Go file with multiple functions

func GoFileWithGlobals

func GoFileWithGlobals(name, packageName string, globals []GlobalVar) *TestDataBuilder

GoFileWithGlobals creates a Go file with global variables

func NewTestDataBuilder

func NewTestDataBuilder() *TestDataBuilder

NewTestDataBuilder creates a new test data builder

func SimpleGoFile

func SimpleGoFile(name, packageName string) *TestDataBuilder

SimpleGoFile creates a simple Go file with basic elements

func (*TestDataBuilder) AddFile

func (tdb *TestDataBuilder) AddFile(name, content string) *TestDataBuilder

AddFile adds a file with the given name and content

func (*TestDataBuilder) AddFileWithSymbols

func (tdb *TestDataBuilder) AddFileWithSymbols(name, content string, symbols []*types.EnhancedSymbol) *TestDataBuilder

AddFileWithSymbols adds a file with symbol information

func (*TestDataBuilder) AddGoFile

func (tdb *TestDataBuilder) AddGoFile(name string, elements ...GoFileElement) *TestDataBuilder

AddGoFile creates a Go file with common patterns

func (*TestDataBuilder) Build

func (tdb *TestDataBuilder) Build() *IsolatedTestData

Build creates the final test data

func (*TestDataBuilder) Close

func (tdb *TestDataBuilder) Close()

Close cleans up the FileContentStore to prevent goroutine leaks

type TestDebugHelper

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

TestDebugHelper provides convenient debugging methods for tests

func NewTestDebugHelper

func NewTestDebugHelper(t *testing.T, level DebugLevel) *TestDebugHelper

NewTestDebugHelper creates a new debug helper for a test

func (*TestDebugHelper) CaptureState

func (tdh *TestDebugHelper) CaptureState(label string)

CaptureState delegates to the underlying debugger

func (*TestDebugHelper) EndOperation

func (tdh *TestDebugHelper) EndOperation(name string, err error)

EndOperation delegates to the underlying debugger

func (*TestDebugHelper) FailWithDebug

func (tdh *TestDebugHelper) FailWithDebug(format string, args ...interface{})

FailWithDebug logs debug information before failing the test

func (*TestDebugHelper) Logf

func (tdh *TestDebugHelper) Logf(format string, args ...interface{})

Log delegates to the underlying debugger

func (*TestDebugHelper) StartOperation

func (tdh *TestDebugHelper) StartOperation(name string)

StartOperation delegates to the underlying debugger

func (*TestDebugHelper) TraceOperation

func (tdh *TestDebugHelper) TraceOperation(name string, operation func() error) error

TraceOperation delegates to the underlying debugger

type TestDebugger

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

TestDebugger provides debugging utilities for test execution

func NewTestDebugger

func NewTestDebugger(testName string, config DebugConfig) *TestDebugger

NewTestDebugger creates a new test debugger instance

func (*TestDebugger) CaptureState

func (td *TestDebugger) CaptureState(label string)

CaptureState captures the current system state

func (*TestDebugger) Close

func (td *TestDebugger) Close() error

Close cleans up debugger resources

func (*TestDebugger) DumpOutputs

func (td *TestDebugger) DumpOutputs() (string, error)

DumpOutputs dumps all captured outputs to JSON

func (*TestDebugger) EndOperation

func (td *TestDebugger) EndOperation(name string, err error)

EndOperation marks the end of an operation

func (*TestDebugger) Logf

func (td *TestDebugger) Logf(format string, args ...interface{})

Logf writes a formatted log message

func (*TestDebugger) SaveReport

func (td *TestDebugger) SaveReport() error

SaveReport saves a detailed debug report

func (*TestDebugger) StartOperation

func (td *TestDebugger) StartOperation(name string)

StartOperation marks the beginning of an operation

func (*TestDebugger) TraceOperation

func (td *TestDebugger) TraceOperation(name string, operation func() error) error

TraceOperation traces an operation with detailed timing

type TestFile

type TestFile struct {
	Name            string
	Content         []byte
	ID              types.FileID
	EnhancedSymbols []*types.EnhancedSymbol
}

TestFile represents a test file with isolated content

type TestIsolationManager

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

TestIsolationManager provides comprehensive test isolation

type TestPerformanceMonitor

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

TestPerformanceMonitor tracks test execution performance and generates optimization suggestions

func NewTestPerformanceMonitor

func NewTestPerformanceMonitor(config MonitorConfig) *TestPerformanceMonitor

NewTestPerformanceMonitor creates a new test performance monitor

func (*TestPerformanceMonitor) CleanupOldData

func (tpm *TestPerformanceMonitor) CleanupOldData()

CleanupOldData removes performance data older than the retention period

func (*TestPerformanceMonitor) GeneratePerformanceReport

func (tpm *TestPerformanceMonitor) GeneratePerformanceReport() *PerformanceReport

GeneratePerformanceReport creates a comprehensive performance report

func (*TestPerformanceMonitor) GetAllTestResults

func (tpm *TestPerformanceMonitor) GetAllTestResults() map[string]*TestPerformanceResult

GetAllTestResults returns all recorded test performance data

func (*TestPerformanceMonitor) GetPerformanceSummary

func (tpm *TestPerformanceMonitor) GetPerformanceSummary() string

GetPerformanceSummary returns a concise summary of test performance

func (*TestPerformanceMonitor) GetSlowTests

func (tpm *TestPerformanceMonitor) GetSlowTests() []*TestPerformanceResult

GetSlowTests returns all tests identified as slow

func (*TestPerformanceMonitor) GetTestResult

func (tpm *TestPerformanceMonitor) GetTestResult(packageName, testName string) (*TestPerformanceResult, bool)

GetTestResult returns performance data for a specific test

func (*TestPerformanceMonitor) LoadState

func (tpm *TestPerformanceMonitor) LoadState(filePath string) error

LoadState loads the monitor state from a file

func (*TestPerformanceMonitor) SaveReport

func (tpm *TestPerformanceMonitor) SaveReport(report *PerformanceReport, filePath string) error

SaveReport saves the performance report to a file

func (*TestPerformanceMonitor) SaveState

func (tpm *TestPerformanceMonitor) SaveState(filePath string) error

SaveState saves the monitor state to a file

func (*TestPerformanceMonitor) StartMonitoring

func (tpm *TestPerformanceMonitor) StartMonitoring(packageName, testName string) *TestSession

StartMonitoring begins monitoring a test

type TestPerformanceResult

type TestPerformanceResult struct {
	PackageName             string        `json:"package_name"`
	TestName                string        `json:"test_name"`
	ExecutionCount          int           `json:"execution_count"`
	TotalDuration           time.Duration `json:"total_duration"`
	AverageDuration         time.Duration `json:"average_duration"`
	MinDuration             time.Duration `json:"min_duration"`
	MaxDuration             time.Duration `json:"max_duration"`
	LastExecution           time.Time     `json:"last_execution"`
	SlowestExecution        time.Duration `json:"slowest_execution"`
	MemoryAllocated         int64         `json:"memory_allocated"`
	GoroutineDelta          int           `json:"goroutine_delta"`
	IsSlow                  bool          `json:"is_slow"`
	SlowReason              []string      `json:"slow_reason"`
	OptimizationSuggestions []string      `json:"optimization_suggestions"`
}

TestPerformanceResult represents performance data for a single test

type TestResult

type TestResult struct {
	PackageName     string        `json:"package_name"`
	TestName        string        `json:"test_name"`
	Status          TestStatus    `json:"status"`
	Duration        time.Duration `json:"duration"`
	StartTime       time.Time     `json:"start_time"`
	EndTime         time.Time     `json:"end_time"`
	ErrorMessage    string        `json:"error_message"`
	StackTrace      string        `json:"stack_trace"`
	MemoryUsed      int64         `json:"memory_used"`
	GoroutinesStart int           `json:"goroutines_start"`
	GoroutinesEnd   int           `json:"goroutines_end"`
	Allocations     int64         `json:"allocations"`
}

TestResult represents a single test execution result

type TestSession

type TestSession struct {
	StartTime        time.Time
	EndTime          time.Time
	PackageName      string
	TestName         string
	MemoryBefore     int64
	MemoryAfter      int64
	GoroutinesBefore int
	GoroutinesAfter  int
	// contains filtered or unexported fields
}

TestSession represents a single test execution session

func (*TestSession) FinishMonitoring

func (ts *TestSession) FinishMonitoring(t *testing.T)

FinishMonitoring ends monitoring and records the test performance

type TestStatus

type TestStatus string

TestStatus represents the outcome of a test

const (
	StatusPass  TestStatus = "pass"
	StatusFail  TestStatus = "fail"
	StatusSkip  TestStatus = "skip"
	StatusPanic TestStatus = "panic"
)

type TestValidator

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

TestValidator provides comprehensive test validation and cleanup verification

func NewTestValidator

func NewTestValidator(t *testing.T) *TestValidator

NewTestValidator creates a new test validator

func (*TestValidator) AddCustomCheck

func (tv *TestValidator) AddCustomCheck(name string, check func() error, critical bool)

AddCustomCheck adds a custom validation check

func (*TestValidator) AddGlobalStateCheck

func (tv *TestValidator) AddGlobalStateCheck()

AddGlobalStateCheck adds a global state validation check

func (*TestValidator) AddGoroutineCheck

func (tv *TestValidator) AddGoroutineCheck()

AddGoroutineCheck adds a goroutine leak check

func (*TestValidator) AddMemoryCheck

func (tv *TestValidator) AddMemoryCheck()

AddMemoryCheck adds a memory leak check

func (*TestValidator) Validate

func (tv *TestValidator) Validate()

Validate performs all registered validation checks

type TypeDefinition

type TypeDefinition struct {
	Name string
	Def  string
}

TypeDefinition represents a type declaration

type TypeElement

type TypeElement struct {
	Name string
	Def  string
}

TypeElement represents a type declaration

func (TypeElement) Generate

func (te TypeElement) Generate() string

type ValidationCheck

type ValidationCheck struct {
	Name     string
	Check    func() error
	Critical bool
}

ValidationCheck represents a validation check to be performed

type ValidationError

type ValidationError struct {
	Type    string
	Message string
}

ValidationError represents a validation error

func (*ValidationError) Error

func (ve *ValidationError) Error() string

type VarDefinition

type VarDefinition struct {
	Name  string
	Type  string
	Value string
}

VarDefinition represents a variable declaration

Jump to

Keyboard shortcuts

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