testing

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Aug 1, 2025 License: MIT Imports: 22 Imported by: 0

Documentation

Overview

Package testing provides mock implementations for testing

Package testing provides testing utilities and helpers for Typosentinel This package implements comprehensive testing infrastructure for unit, integration, and performance tests

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CleanupTempDirs

func CleanupTempDirs(t *testing.T, dirs ...string)

CleanupTempDirs removes temporary directories created during testing

func CleanupTempFiles

func CleanupTempFiles(t *testing.T, files ...string)

CleanupTempFiles removes temporary files created during testing

func RequireEnvironment

func RequireEnvironment(t *testing.T, envVar string) string

RequireEnvironment skips the test if a required environment variable is not set

func SkipIfShort

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

SkipIfShort skips the test if running in short mode

func WaitForCondition

func WaitForCondition(t *testing.T, condition func() bool, timeout time.Duration, message string)

WaitForCondition waits for a condition to be true with timeout

Types

type BenchmarkHelper

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

BenchmarkHelper provides utilities for benchmark tests

func NewBenchmarkHelper

func NewBenchmarkHelper(b *testing.B) *BenchmarkHelper

NewBenchmarkHelper creates a new benchmark helper

func (*BenchmarkHelper) ReportAllocs

func (bh *BenchmarkHelper) ReportAllocs()

ReportAllocs enables allocation reporting

func (*BenchmarkHelper) RunParallel

func (bh *BenchmarkHelper) RunParallel(operation func())

RunParallel runs a benchmark in parallel

func (*BenchmarkHelper) SetBytes

func (bh *BenchmarkHelper) SetBytes(bytes int64)

SetBytes sets the number of bytes processed per operation

func (*BenchmarkHelper) TimeOperation

func (bh *BenchmarkHelper) TimeOperation(operation func()) time.Duration

TimeOperation measures the time of an operation

type IntegrationTestHelper

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

IntegrationTestHelper provides utilities for integration tests

func NewIntegrationTestHelper

func NewIntegrationTestHelper(t *testing.T, server *gin.Engine, config *config.Config) *IntegrationTestHelper

NewIntegrationTestHelper creates a new integration test helper

func (*IntegrationTestHelper) MakeJSONRequest

func (ith *IntegrationTestHelper) MakeJSONRequest(method, path string, payload interface{}) *httptest.ResponseRecorder

MakeJSONRequest makes a JSON HTTP request

func (*IntegrationTestHelper) MakeRequest

func (ith *IntegrationTestHelper) MakeRequest(method, path string, body io.Reader, headers map[string]string) *httptest.ResponseRecorder

MakeRequest makes an HTTP request to the test server

type LogEntry

type LogEntry struct {
	Level   string
	Message string
	Fields  map[string]interface{}
	Time    time.Time
}

LogEntry represents a log entry

type MockCache

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

MockCache provides a mock implementation of Cache

func NewMockCache

func NewMockCache() *MockCache

NewMockCache creates a new mock cache

func (*MockCache) Clear

func (m *MockCache) Clear(ctx context.Context) error

Clear removes all values from the cache

func (*MockCache) Delete

func (m *MockCache) Delete(ctx context.Context, key string) error

Delete removes a value from the cache

func (*MockCache) Get

func (m *MockCache) Get(ctx context.Context, key string) (interface{}, error)

Get retrieves a value from the cache

func (*MockCache) GetCalls

func (m *MockCache) GetCalls() []string

GetCalls returns all method calls made

func (*MockCache) Set

func (m *MockCache) Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error

Set stores a value in the cache

type MockConfigManager

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

MockConfigManager provides a mock implementation of ConfigManager

func NewMockConfigManager

func NewMockConfigManager() *MockConfigManager

NewMockConfigManager creates a new mock config manager

func (*MockConfigManager) Get

func (m *MockConfigManager) Get(key string) interface{}

Get retrieves a configuration value

func (*MockConfigManager) GetBool

func (m *MockConfigManager) GetBool(key string) bool

GetBool retrieves a boolean configuration value

func (*MockConfigManager) GetCalls

func (m *MockConfigManager) GetCalls() []string

GetCalls returns all method calls made

func (*MockConfigManager) GetDuration

func (m *MockConfigManager) GetDuration(key string) time.Duration

GetDuration retrieves a duration configuration value

func (*MockConfigManager) GetInt

func (m *MockConfigManager) GetInt(key string) int

GetInt retrieves an integer configuration value

func (*MockConfigManager) GetString

func (m *MockConfigManager) GetString(key string) string

GetString retrieves a string configuration value

func (*MockConfigManager) Reload

func (m *MockConfigManager) Reload() error

Reload reloads the configuration

func (*MockConfigManager) Set

func (m *MockConfigManager) Set(key string, value interface{})

Set stores a configuration value

type MockCounter

type MockCounter struct{}

MockCounter implements interfaces.Counter

func (*MockCounter) Add

func (c *MockCounter) Add(value float64)

func (*MockCounter) Inc

func (c *MockCounter) Inc()

type MockDatabase

type MockDatabase struct {
	DB       *sql.DB
	FilePath string
}

MockDatabase provides a mock database for testing

func NewMockDatabase

func NewMockDatabase(t *testing.T) *MockDatabase

NewMockDatabase creates a new mock SQLite database

func (*MockDatabase) Close

func (m *MockDatabase) Close() error

Close closes the mock database

type MockGauge

type MockGauge struct{}

MockGauge implements interfaces.Gauge

func (*MockGauge) Add

func (g *MockGauge) Add(value float64)

func (*MockGauge) Dec

func (g *MockGauge) Dec()

func (*MockGauge) Inc

func (g *MockGauge) Inc()

func (*MockGauge) Set

func (g *MockGauge) Set(value float64)

func (*MockGauge) Sub

func (g *MockGauge) Sub(value float64)

type MockHTTPServer

type MockHTTPServer struct {
	Server   *httptest.Server
	Requests []*http.Request
	// contains filtered or unexported fields
}

MockHTTPServer provides a mock HTTP server for testing

func NewMockHTTPServer

func NewMockHTTPServer() *MockHTTPServer

NewMockHTTPServer creates a new mock HTTP server

func (*MockHTTPServer) ClearRequests

func (m *MockHTTPServer) ClearRequests()

ClearRequests clears all captured requests

func (*MockHTTPServer) Close

func (m *MockHTTPServer) Close()

Close closes the mock server

func (*MockHTTPServer) GetRequests

func (m *MockHTTPServer) GetRequests() []*http.Request

GetRequests returns all captured requests

type MockHistogram

type MockHistogram struct{}

MockHistogram implements interfaces.Histogram

func (*MockHistogram) Observe

func (h *MockHistogram) Observe(value float64)

type MockLogger

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

MockLogger provides a mock implementation of Logger

func NewMockLogger

func NewMockLogger() *MockLogger

NewMockLogger creates a new mock logger

func (*MockLogger) ClearLogs

func (m *MockLogger) ClearLogs()

ClearLogs clears all logged entries

func (*MockLogger) Debug

func (m *MockLogger) Debug(message string, fields ...interfaces.LogField)

Debug logs a debug message

func (*MockLogger) Error

func (m *MockLogger) Error(message string, fields ...interfaces.LogField)

Error logs an error message

func (*MockLogger) Fatal

func (m *MockLogger) Fatal(message string, fields ...interfaces.LogField)

Fatal logs a fatal message

func (*MockLogger) GetLogs

func (m *MockLogger) GetLogs() []LogEntry

GetLogs returns all logged entries

func (*MockLogger) GetLogsByLevel

func (m *MockLogger) GetLogsByLevel(level string) []LogEntry

GetLogsByLevel returns logs filtered by level

func (*MockLogger) HasLog

func (m *MockLogger) HasLog(level, message string) bool

HasLog checks if a log with specific message exists

func (*MockLogger) Info

func (m *MockLogger) Info(message string, fields ...interfaces.LogField)

Info logs an info message

func (*MockLogger) Warn

func (m *MockLogger) Warn(message string, fields ...interfaces.LogField)

Warn logs a warning message

func (*MockLogger) WithContext

func (m *MockLogger) WithContext(ctx context.Context) interfaces.Logger

WithContext returns a logger with context

func (*MockLogger) WithFields

func (m *MockLogger) WithFields(fields ...interfaces.LogField) interfaces.Logger

WithFields returns a logger with additional fields

type MockMLScorer

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

MockMLScorer provides a mock implementation of MLScorer

func NewMockMLScorer

func NewMockMLScorer() *MockMLScorer

NewMockMLScorer creates a new mock ML scorer

func (*MockMLScorer) BatchScore

func (m *MockMLScorer) BatchScore(ctx context.Context, packages []*interfaces.PackageInfo) (map[string]float64, error)

BatchScore scores multiple packages

func (*MockMLScorer) GetCalls

func (m *MockMLScorer) GetCalls() []string

GetCalls returns all method calls made

func (*MockMLScorer) ScorePackage

func (m *MockMLScorer) ScorePackage(ctx context.Context, pkg *interfaces.PackageInfo) (float64, error)

ScorePackage scores a package for suspiciousness

func (*MockMLScorer) SetDelay

func (m *MockMLScorer) SetDelay(delay time.Duration)

SetDelay sets a delay for all operations

func (*MockMLScorer) SetError

func (m *MockMLScorer) SetError(packageName string, err error)

SetError sets an error for a specific package

func (*MockMLScorer) SetScore

func (m *MockMLScorer) SetScore(packageName string, score float64)

SetScore sets a score for a specific package

type MockMetrics

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

MockMetrics provides a mock implementation of Metrics

func NewMockMetrics

func NewMockMetrics() *MockMetrics

NewMockMetrics creates a new mock metrics collector

func (*MockMetrics) ClearMetrics

func (m *MockMetrics) ClearMetrics()

ClearMetrics clears all metrics

func (*MockMetrics) Counter

func (m *MockMetrics) Counter(name string, tags interfaces.MetricTags) interfaces.Counter

Counter creates or retrieves a counter metric

func (*MockMetrics) Gauge

func (m *MockMetrics) Gauge(name string, tags interfaces.MetricTags) interfaces.Gauge

Gauge creates or retrieves a gauge metric

func (*MockMetrics) GetCalls

func (m *MockMetrics) GetCalls() []string

GetCalls returns all method calls made

func (*MockMetrics) GetMetric

func (m *MockMetrics) GetMetric(name string) interface{}

GetMetric returns a metric value

func (*MockMetrics) Histogram

func (m *MockMetrics) Histogram(name string, tags interfaces.MetricTags) interfaces.Histogram

Histogram creates or retrieves a histogram metric

func (*MockMetrics) IncrementCounter

func (m *MockMetrics) IncrementCounter(name string, labels interfaces.MetricTags)

IncrementCounter increments a counter metric

func (*MockMetrics) RecordDuration

func (m *MockMetrics) RecordDuration(name string, duration time.Duration, tags interfaces.MetricTags)

RecordDuration records a duration metric

func (*MockMetrics) RecordHistogram

func (m *MockMetrics) RecordHistogram(name string, value float64, labels interfaces.MetricTags)

RecordHistogram records a histogram metric

func (*MockMetrics) SetGauge

func (m *MockMetrics) SetGauge(name string, value float64, labels interfaces.MetricTags)

SetGauge sets a gauge metric

func (*MockMetrics) Start

func (m *MockMetrics) Start(ctx context.Context) error

Start starts the metrics collector

func (*MockMetrics) Stop

func (m *MockMetrics) Stop() error

Stop stops the metrics collector

func (*MockMetrics) Timer

func (m *MockMetrics) Timer(name string, tags interfaces.MetricTags) interfaces.Timer

Timer creates or retrieves a timer metric

type MockRedis

type MockRedis struct {
	Client *redis.Client
	// contains filtered or unexported fields
}

MockRedis provides a mock Redis client for testing

func NewMockRedis

func NewMockRedis() *MockRedis

NewMockRedis creates a new mock Redis client

func (*MockRedis) Clear

func (m *MockRedis) Clear()

Clear clears all data

func (*MockRedis) Delete

func (m *MockRedis) Delete(key string)

Delete deletes a key

func (*MockRedis) Get

func (m *MockRedis) Get(key string) (string, bool)

Get gets a value by key

func (*MockRedis) Set

func (m *MockRedis) Set(key, value string)

Set sets a key-value pair

type MockRegistryClient

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

MockRegistryClient provides a mock implementation of RegistryClient

func NewMockRegistryClient

func NewMockRegistryClient() *MockRegistryClient

NewMockRegistryClient creates a new mock registry client

func (*MockRegistryClient) ClearCalls

func (m *MockRegistryClient) ClearCalls()

ClearCalls clears all recorded calls

func (*MockRegistryClient) GetCalls

func (m *MockRegistryClient) GetCalls() []string

GetCalls returns all method calls made

func (*MockRegistryClient) GetPackageInfo

func (m *MockRegistryClient) GetPackageInfo(ctx context.Context, packageName string) (*interfaces.PackageInfo, error)

GetPackageInfo returns package information

func (*MockRegistryClient) SearchPackages

func (m *MockRegistryClient) SearchPackages(ctx context.Context, query string, limit int) ([]*interfaces.PackageInfo, error)

SearchPackages searches for packages

func (*MockRegistryClient) SetDelay

func (m *MockRegistryClient) SetDelay(delay time.Duration)

SetDelay sets a delay for all operations

func (*MockRegistryClient) SetError

func (m *MockRegistryClient) SetError(packageName string, err error)

SetError sets an error for a specific package

func (*MockRegistryClient) SetPackage

func (m *MockRegistryClient) SetPackage(name string, pkg *interfaces.PackageInfo)

SetPackage sets a package for testing

type MockThreatDatabase

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

MockThreatDatabase provides a mock implementation of ThreatDatabase

func NewMockThreatDatabase

func NewMockThreatDatabase() *MockThreatDatabase

NewMockThreatDatabase creates a new mock threat database

func (*MockThreatDatabase) CheckThreat

func (m *MockThreatDatabase) CheckThreat(ctx context.Context, packageName string) (*interfaces.ThreatInfo, error)

CheckThreat checks if a package is a known threat

func (*MockThreatDatabase) GetCalls

func (m *MockThreatDatabase) GetCalls() []string

GetCalls returns all method calls made

func (*MockThreatDatabase) SetDelay

func (m *MockThreatDatabase) SetDelay(delay time.Duration)

SetDelay sets a delay for all operations

func (*MockThreatDatabase) SetError

func (m *MockThreatDatabase) SetError(packageName string, err error)

SetError sets an error for a specific package

func (*MockThreatDatabase) SetThreat

func (m *MockThreatDatabase) SetThreat(packageName string, threat *interfaces.ThreatInfo)

SetThreat sets a threat for testing

func (*MockThreatDatabase) UpdateThreat

func (m *MockThreatDatabase) UpdateThreat(ctx context.Context, threat *interfaces.ThreatInfo) error

UpdateThreat updates threat information

type MockTimer

type MockTimer struct{}

MockTimer implements interfaces.Timer

func (*MockTimer) Record

func (t *MockTimer) Record(duration time.Duration)

func (*MockTimer) Time

func (t *MockTimer) Time() func()

type MockValidator

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

MockValidator provides a mock implementation of Validator

func NewMockValidator

func NewMockValidator() *MockValidator

NewMockValidator creates a new mock validator

func (*MockValidator) GetCalls

func (m *MockValidator) GetCalls() []string

GetCalls returns all method calls made

func (*MockValidator) SetError

func (m *MockValidator) SetError(packageName string, err error)

SetError sets an error for a specific package

func (*MockValidator) SetResult

func (m *MockValidator) SetResult(packageName string, valid bool)

SetResult sets a validation result for a package

func (*MockValidator) ValidateConfig

func (m *MockValidator) ValidateConfig(config interface{}) error

ValidateConfig validates configuration

func (*MockValidator) ValidatePackageName

func (m *MockValidator) ValidatePackageName(packageName string) error

ValidatePackageName validates a package name

type PerformanceTest

type PerformanceTest struct {
	StartTime time.Time
	EndTime   time.Time
	// contains filtered or unexported fields
}

PerformanceTest provides utilities for performance testing

func NewPerformanceTest

func NewPerformanceTest(t *testing.T) *PerformanceTest

NewPerformanceTest creates a new performance test

func (*PerformanceTest) AssertMaxDuration

func (p *PerformanceTest) AssertMaxDuration(maxDuration time.Duration, msgAndArgs ...interface{})

AssertMaxDuration asserts that the measured duration is below a threshold

func (*PerformanceTest) AssertMinDuration

func (p *PerformanceTest) AssertMinDuration(minDuration time.Duration, msgAndArgs ...interface{})

AssertMinDuration asserts that the measured duration is above a threshold

func (*PerformanceTest) Duration

func (p *PerformanceTest) Duration() time.Duration

Duration returns the measured duration

func (*PerformanceTest) Start

func (p *PerformanceTest) Start()

Start starts the performance measurement

func (*PerformanceTest) Stop

func (p *PerformanceTest) Stop()

Stop stops the performance measurement

type TestHelper

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

TestHelper provides common test helper functions

func NewTestHelper

func NewTestHelper(t *testing.T) *TestHelper

NewTestHelper creates a new test helper

func (*TestHelper) AssertDuration

func (h *TestHelper) AssertDuration(actual, min, max time.Duration, msgAndArgs ...interface{})

AssertDuration asserts that a duration is within expected bounds

func (*TestHelper) AssertError

func (h *TestHelper) AssertError(err error, msgAndArgs ...interface{})

AssertError asserts that an error is not nil

func (*TestHelper) AssertErrorCode

func (h *TestHelper) AssertErrorCode(err error, expectedCode errors.ErrorCode, msgAndArgs ...interface{})

AssertErrorCode asserts that an error has a specific error code

func (*TestHelper) AssertFileExists

func (h *TestHelper) AssertFileExists(filePath string, msgAndArgs ...interface{})

AssertFileExists asserts that a file exists

func (*TestHelper) AssertFileNotExists

func (h *TestHelper) AssertFileNotExists(filePath string, msgAndArgs ...interface{})

AssertFileNotExists asserts that a file does not exist

func (*TestHelper) AssertHTTPStatus

func (h *TestHelper) AssertHTTPStatus(response *httptest.ResponseRecorder, expectedStatus int, msgAndArgs ...interface{})

AssertHTTPStatus asserts that an HTTP response has a specific status code

func (*TestHelper) AssertJSONResponse

func (h *TestHelper) AssertJSONResponse(response *httptest.ResponseRecorder, msgAndArgs ...interface{})

AssertJSONResponse asserts that an HTTP response contains valid JSON

func (*TestHelper) AssertNoError

func (h *TestHelper) AssertNoError(err error, msgAndArgs ...interface{})

AssertNoError asserts that an error is nil

func (*TestHelper) CreateTempDir

func (h *TestHelper) CreateTempDir(prefix string) string

CreateTempDir creates a temporary directory

func (*TestHelper) CreateTempFile

func (h *TestHelper) CreateTempFile(content string, suffix string) string

CreateTempFile creates a temporary file with content

type TestSuite

type TestSuite struct {
	suite.Suite
	Config    *config.Config
	Logger    interfaces.Logger
	Metrics   interfaces.Metrics
	Container *container.Container
	TempDir   string
	Cleanup   []func() error
	// contains filtered or unexported fields
}

TestSuite provides a base test suite with common setup and teardown

func (*TestSuite) AddCleanup

func (ts *TestSuite) AddCleanup(cleanup func() error)

AddCleanup adds a cleanup function to be called during teardown

func (*TestSuite) SetupSuite

func (ts *TestSuite) SetupSuite()

SetupSuite runs before all tests in the suite

func (*TestSuite) TearDownSuite

func (ts *TestSuite) TearDownSuite()

TearDownSuite runs after all tests in the suite

Jump to

Keyboard shortcuts

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