testing

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Feb 27, 2026 License: MIT Imports: 15 Imported by: 0

README

testing — 测试辅助工具

提供 HTTP 测试上下文、性能基准测试套件等测试辅助工具,简化 Go 单元测试与集成测试编写。

主要组件

TestContext — HTTP 集成测试上下文
import frameTesting "github.com/leeforge/framework/testing"

func TestCreateUser(t *testing.T) {
    tc := frameTesting.NewTestContext(t)
    defer tc.Cleanup()

    // 创建测试 HTTP 服务
    handler := setupTestHandler()
    server := tc.NewServer(handler)

    // 发起 POST 请求
    resp := tc.POST(server, "/users", map[string]any{
        "name": "Alice",
        "email": "alice@test.com",
    })

    tc.AssertStatus(resp, http.StatusCreated)
    tc.AssertJSONField(resp, "data.name", "Alice")
}
HTTP 测试辅助
// 构建测试请求
req := tc.NewRequest("GET", "/users/123", nil)
req.Header.Set("Authorization", "Bearer "+token)

// 记录响应
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)

// 断言
tc.AssertStatus(rec, http.StatusOK)
tc.AssertJSON(rec, `{"data": {"id": "123"}}`)
性能测试套件
suite := frameTesting.NewPerformanceTestSuite("UserAPI")

suite.Add("CreateUser", func(pc *frameTesting.PerformanceContext) *frameTesting.BenchmarkResult {
    start := time.Now()
    err := createUser(pc.Ctx())
    return pc.Result(time.Since(start), err)
})

results := suite.Run(frameTesting.PerformanceConfig{
    Iterations:  1000,
    Concurrency: 10,
    WarmupRuns:  50,
})

suite.Report(results)
// 输出:平均耗时、P99、最大并发、成功率等
组件注册(测试 Mock)
tc := frameTesting.NewTestContext(t)

// 注册测试用 Mock 组件
tc.Register("db", mockDB)
tc.Register("cache", mockCache)

// 获取组件
db := tc.Get("db").(MockDB)

常用断言

tc.AssertStatus(resp, http.StatusOK)
tc.AssertStatus(resp, http.StatusNotFound)

// 断言 JSON 响应字段
tc.AssertJSONField(resp, "data.email", "alice@test.com")
tc.AssertJSONField(resp, "error", nil)

注意事项

  • TestContext 内置 30 秒超时,单个测试超时会自动取消
  • NewServer 创建的 httptest.Server 会在 Cleanup 时自动关闭
  • 性能测试的 Concurrency 值不应超过机器 CPU 核心数 × 2,避免测试结果失真

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AnalysisReport

type AnalysisReport struct {
	Analyses map[string]*MetricAnalysis
}

AnalysisReport represents an analysis report

type BenchmarkConfig

type BenchmarkConfig struct {
	Iterations int
	Duration   time.Duration
	Warmup     int
	CPUProfile bool
	MemProfile bool
}

BenchmarkConfig represents benchmark configuration

func DefaultBenchmarkConfig

func DefaultBenchmarkConfig() BenchmarkConfig

DefaultBenchmarkConfig creates a default benchmark configuration

type BenchmarkContext

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

BenchmarkContext provides context for benchmarks

func NewBenchmarkContext

func NewBenchmarkContext() *BenchmarkContext

NewBenchmarkContext creates a new benchmark context

func (*BenchmarkContext) Increment

func (bc *BenchmarkContext) Increment()

Increment increments iteration count

func (*BenchmarkContext) Iterations

func (bc *BenchmarkContext) Iterations() int64

Iterations returns the iteration count

type BenchmarkExecutor

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

BenchmarkExecutor executes benchmarks with configuration

func NewBenchmarkExecutor

func NewBenchmarkExecutor(config BenchmarkConfig) *BenchmarkExecutor

NewBenchmarkExecutor creates a new benchmark executor

func (*BenchmarkExecutor) Execute

func (be *BenchmarkExecutor) Execute(name string, fn func() error) *BenchmarkResult

Execute executes a benchmark

type BenchmarkFunc

type BenchmarkFunc func() error

BenchmarkFunc is a function that can be benchmarked

type BenchmarkResult

type BenchmarkResult struct {
	Name        string
	Duration    time.Duration
	Operations  int64
	Bytes       int64
	Allocations int64
	Memory      uint64
	Extra       map[string]interface{}
}

BenchmarkResult represents a benchmark result

func Measure

func Measure(fn BenchmarkFunc, iterations int) *BenchmarkResult

Measure measures a function

func (*BenchmarkResult) Latency

func (br *BenchmarkResult) Latency() time.Duration

Latency returns average latency per operation

func (*BenchmarkResult) MemoryPerOp

func (br *BenchmarkResult) MemoryPerOp() float64

MemoryPerOp returns memory allocated per operation

func (*BenchmarkResult) String

func (br *BenchmarkResult) String() string

String returns a string representation

func (*BenchmarkResult) Throughput

func (br *BenchmarkResult) Throughput() float64

Throughput returns operations per second

type BenchmarkRunner

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

BenchmarkRunner runs benchmarks with setup and teardown

func NewBenchmarkRunner

func NewBenchmarkRunner() *BenchmarkRunner

NewBenchmarkRunner creates a new benchmark runner

func (*BenchmarkRunner) Add

func (br *BenchmarkRunner) Add(name string, fn func(*TestContext, *testing.B)) *BenchmarkRunner

Add adds a benchmark

func (*BenchmarkRunner) Run

func (br *BenchmarkRunner) Run(b *testing.B)

Run runs all benchmarks

func (*BenchmarkRunner) Setup

func (br *BenchmarkRunner) Setup(fn func(*TestContext) error) *BenchmarkRunner

Setup sets up the benchmark runner

func (*BenchmarkRunner) Teardown

func (br *BenchmarkRunner) Teardown(fn func(*TestContext) error) *BenchmarkRunner

Teardown sets up the teardown

type Call

type Call struct {
	Method string
	Args   []interface{}
	Result interface{}
	Error  error
}

Call represents a service call

type HTTPTestClient

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

HTTPTestClient is a test HTTP client

func NewHTTPTestClient

func NewHTTPTestClient(handler http.Handler) *HTTPTestClient

NewHTTPTestClient creates a new HTTP test client

func (*HTTPTestClient) Close

func (c *HTTPTestClient) Close()

Close closes the test server

func (*HTTPTestClient) Delete

func (c *HTTPTestClient) Delete(path string, headers map[string]string) (*http.Response, string, error)

Delete makes a DELETE request

func (*HTTPTestClient) Get

func (c *HTTPTestClient) Get(path string, headers map[string]string) (*http.Response, string, error)

Get makes a GET request

func (*HTTPTestClient) Post

func (c *HTTPTestClient) Post(path string, body interface{}, headers map[string]string) (*http.Response, string, error)

Post makes a POST request

func (*HTTPTestClient) Put

func (c *HTTPTestClient) Put(path string, body interface{}, headers map[string]string) (*http.Response, string, error)

Put makes a PUT request

type LatencyTest

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

LatencyTest measures latency

func NewLatencyTest

func NewLatencyTest(iterations int, workload func() error) *LatencyTest

NewLatencyTest creates a new latency test

func (*LatencyTest) Run

func (lt *LatencyTest) Run() *BenchmarkResult

Run executes the latency test

type LoadTest

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

LoadTest runs a load test

func NewLoadTest

func NewLoadTest(config LoadTestConfig, workload func() error) *LoadTest

NewLoadTest creates a new load test

func (*LoadTest) Run

func (lt *LoadTest) Run() *LoadTestResult

Run executes the load test

type LoadTestConfig

type LoadTestConfig struct {
	Concurrency   int
	TotalRequests int64
	Duration      time.Duration
	RampUp        time.Duration
	TargetRPS     float64
}

LoadTestConfig represents load test configuration

func DefaultLoadTestConfig

func DefaultLoadTestConfig() LoadTestConfig

DefaultLoadTestConfig creates a default load test configuration

type LoadTestResult

type LoadTestResult struct {
	Config         LoadTestConfig
	TotalRequests  int64
	Successful     int64
	Failed         int64
	TotalDuration  time.Duration
	AverageLatency time.Duration
	MinLatency     time.Duration
	MaxLatency     time.Duration
	RequestsPerSec float64
	StatusCodes    map[int]int64
	Errors         []string
}

LoadTestResult represents a load test result

func (*LoadTestResult) String

func (lr *LoadTestResult) String() string

String returns a string representation

type LogEntry

type LogEntry struct {
	Level  string
	Msg    string
	Fields map[string]interface{}
}

LogEntry represents a log entry

type MemoryDiff

type MemoryDiff struct {
	Alloc      uint64
	TotalAlloc uint64
	Mallocs    uint64
	Frees      uint64
	HeapAlloc  uint64
	HeapInuse  uint64
	StackInuse uint64
	NumGC      uint32
}

MemoryDiff represents memory differences

func (*MemoryDiff) String

func (md *MemoryDiff) String() string

String returns a string representation

type MemoryTracker

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

MemoryTracker tracks memory usage

func NewMemoryTracker

func NewMemoryTracker() *MemoryTracker

NewMemoryTracker creates a new memory tracker

func (*MemoryTracker) Start

func (mt *MemoryTracker) Start()

Start starts tracking

func (*MemoryTracker) Stop

func (mt *MemoryTracker) Stop() *MemoryDiff

Stop stops tracking and returns diff

type MetricAnalysis

type MetricAnalysis struct {
	Name        string
	Throughput  float64
	Latency     time.Duration
	Operations  int64
	Memory      uint64
	Allocations int64
	Level       string
}

MetricAnalysis represents analysis for a metric

func (*MetricAnalysis) String

func (ma *MetricAnalysis) String() string

String returns a string representation

type MetricData

type MetricData struct {
	Values []float64
	Sum    float64
	Count  int64
	Min    float64
	Max    float64
}

MetricData holds metric data

type MetricStats

type MetricStats struct {
	Name    string
	Count   int64
	Sum     float64
	Average float64
	Min     float64
	Max     float64
}

MetricStats represents statistics for a metric

func (*MetricStats) String

func (ms *MetricStats) String() string

String returns a string representation

type MockCache

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

MockCache is a mock cache for testing

func NewMockCache

func NewMockCache() *MockCache

NewMockCache creates a new mock cache

func (*MockCache) Clear

func (m *MockCache) Clear()

Clear clears all data

func (*MockCache) Delete

func (m *MockCache) Delete(key string)

Delete deletes a value

func (*MockCache) Get

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

Get gets a value

func (*MockCache) Set

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

Set sets a value with TTL

type MockDB

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

MockDB is a mock database for testing

func NewMockDB

func NewMockDB() *MockDB

NewMockDB creates a new mock database

func (*MockDB) Clear

func (m *MockDB) Clear(table string)

Clear clears a table

func (*MockDB) ClearAll

func (m *MockDB) ClearAll()

ClearAll clears all tables

func (*MockDB) Delete

func (m *MockDB) Delete(table string, filter func(map[string]interface{}) bool) int

Delete deletes records

func (*MockDB) Find

func (m *MockDB) Find(table string, filter func(map[string]interface{}) bool) []map[string]interface{}

Find finds records

func (*MockDB) FindOne

func (m *MockDB) FindOne(table string, filter func(map[string]interface{}) bool) map[string]interface{}

FindOne finds one record

func (*MockDB) Insert

func (m *MockDB) Insert(table string, record map[string]interface{})

Insert inserts a record

type MockHTTPHandler

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

MockHTTPHandler is a mock HTTP handler for testing

func NewMockHTTPHandler

func NewMockHTTPHandler() *MockHTTPHandler

NewMockHTTPHandler creates a new mock HTTP handler

func (*MockHTTPHandler) Clear

func (m *MockHTTPHandler) Clear()

Clear clears all requests

func (*MockHTTPHandler) GetRequests

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

GetRequests returns all requests

func (*MockHTTPHandler) ServeHTTP

func (m *MockHTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler

func (*MockHTTPHandler) SetResponse

func (m *MockHTTPHandler) SetResponse(status int, body string, headers map[string]string)

SetResponse sets the response

type MockLogger

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

MockLogger is a mock logger for testing

func NewMockLogger

func NewMockLogger() *MockLogger

NewMockLogger creates a new mock logger

func (*MockLogger) Clear

func (m *MockLogger) Clear()

Clear clears all entries

func (*MockLogger) CountEntries

func (m *MockLogger) CountEntries(level string) int

CountEntries counts entries with a level

func (*MockLogger) Debug

func (m *MockLogger) Debug(msg string, fields ...interface{})

Debug logs debug level

func (*MockLogger) Debugf

func (m *MockLogger) Debugf(format string, args ...interface{})

Debugf logs debug level with format

func (*MockLogger) Error

func (m *MockLogger) Error(msg string, fields ...interface{})

Error logs error level

func (*MockLogger) Errorf

func (m *MockLogger) Errorf(format string, args ...interface{})

Errorf logs error level with format

func (*MockLogger) Fatal

func (m *MockLogger) Fatal(msg string, fields ...interface{})

Fatal logs fatal level

func (*MockLogger) Fatalf

func (m *MockLogger) Fatalf(format string, args ...interface{})

Fatalf logs fatal level with format

func (*MockLogger) FindEntry

func (m *MockLogger) FindEntry(msg string) *LogEntry

FindEntry finds an entry by message

func (*MockLogger) GetEntries

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

GetEntries returns all log entries

func (*MockLogger) Info

func (m *MockLogger) Info(msg string, fields ...interface{})

Info logs info level

func (*MockLogger) Infof

func (m *MockLogger) Infof(format string, args ...interface{})

Infof logs info level with format

func (*MockLogger) Warn

func (m *MockLogger) Warn(msg string, fields ...interface{})

Warn logs warn level

func (*MockLogger) Warnf

func (m *MockLogger) Warnf(format string, args ...interface{})

Warnf logs warn level with format

type MockRepository

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

MockRepository is a mock repository for testing

func NewMockRepository

func NewMockRepository() *MockRepository

NewMockRepository creates a new mock repository

func (*MockRepository) Clear

func (m *MockRepository) Clear()

Clear clears all data

func (*MockRepository) Delete

func (m *MockRepository) Delete(key string)

Delete deletes a value

func (*MockRepository) Get

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

Get gets a value

func (*MockRepository) Set

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

Set sets a value

type MockService

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

MockService is a mock service for testing

func NewMockService

func NewMockService() *MockService

NewMockService creates a new mock service

func (*MockService) Call

func (m *MockService) Call(method string, args ...interface{}) (interface{}, error)

Call records a call

func (*MockService) Clear

func (m *MockService) Clear()

Clear clears all calls

func (*MockService) GetCall

func (m *MockService) GetCall(index int) *Call

GetCall gets a specific call

func (*MockService) GetCalls

func (m *MockService) GetCalls() []Call

GetCalls returns all calls

type MockValidator

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

MockValidator is a mock validator for testing

func NewMockValidator

func NewMockValidator() *MockValidator

NewMockValidator creates a new mock validator

func (*MockValidator) Clear

func (m *MockValidator) Clear()

Clear clears all errors

func (*MockValidator) SetError

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

SetError sets an error for a key

func (*MockValidator) Validate

func (m *MockValidator) Validate(key string, value interface{}) error

Validate validates a value

type PerformanceAnalyzer

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

PerformanceAnalyzer analyzes performance results

func NewPerformanceAnalyzer

func NewPerformanceAnalyzer(results map[string]*BenchmarkResult) *PerformanceAnalyzer

NewPerformanceAnalyzer creates a new performance analyzer

func (*PerformanceAnalyzer) Analyze

func (pa *PerformanceAnalyzer) Analyze() *AnalysisReport

Analyze analyzes the results

func (*PerformanceAnalyzer) GetOptimizations

func (pa *PerformanceAnalyzer) GetOptimizations() []PerformanceOptimization

GetOptimizations gets optimization suggestions

type PerformanceBenchmarkRunner

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

PerformanceBenchmarkRunner runs benchmarks

func NewPerformanceBenchmarkRunner

func NewPerformanceBenchmarkRunner() *PerformanceBenchmarkRunner

NewPerformanceBenchmarkRunner creates a new benchmark runner

func (*PerformanceBenchmarkRunner) Add

Add adds a benchmark

func (*PerformanceBenchmarkRunner) Run

Run runs all benchmarks

type PerformanceContext

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

PerformanceContext provides context for performance tests

func NewPerformanceContext

func NewPerformanceContext() *PerformanceContext

NewPerformanceContext creates a new performance context

func (*PerformanceContext) Context

func (pc *PerformanceContext) Context() context.Context

Context returns the context

func (*PerformanceContext) Elapsed

func (pc *PerformanceContext) Elapsed() time.Duration

Elapsed returns elapsed time

func (*PerformanceContext) GetMetric

func (pc *PerformanceContext) GetMetric(key string) interface{}

GetMetric gets a metric

func (*PerformanceContext) SetMetric

func (pc *PerformanceContext) SetMetric(key string, value interface{})

SetMetric sets a metric

func (*PerformanceContext) Start

func (pc *PerformanceContext) Start()

Start starts a timer

type PerformanceMonitor

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

PerformanceMonitor monitors performance metrics

func NewPerformanceMonitor

func NewPerformanceMonitor() *PerformanceMonitor

NewPerformanceMonitor creates a new performance monitor

func (*PerformanceMonitor) Clear

func (pm *PerformanceMonitor) Clear()

Clear clears all metrics

func (*PerformanceMonitor) GetAllStats

func (pm *PerformanceMonitor) GetAllStats() map[string]*MetricStats

GetAllStats gets all statistics

func (*PerformanceMonitor) GetStats

func (pm *PerformanceMonitor) GetStats(name string) *MetricStats

GetStats gets statistics for a metric

func (*PerformanceMonitor) Record

func (pm *PerformanceMonitor) Record(name string, value float64)

Record records a metric value

type PerformanceOptimization

type PerformanceOptimization struct {
	Metric     string
	Current    string
	Suggestion string
	Priority   string
}

PerformanceOptimization represents optimization suggestions

type PerformanceReport

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

PerformanceReport generates performance reports

func NewPerformanceReport

func NewPerformanceReport(results map[string]*BenchmarkResult) *PerformanceReport

NewPerformanceReport creates a new performance report

func (*PerformanceReport) Compare

func (pr *PerformanceReport) Compare(other *PerformanceReport) string

Compare compares two sets of results

func (*PerformanceReport) Generate

func (pr *PerformanceReport) Generate() string

Generate generates a report string

type PerformanceReportFormat

type PerformanceReportFormat struct{}

PerformanceReportFormat formats performance reports

func NewPerformanceReportFormat

func NewPerformanceReportFormat() *PerformanceReportFormat

NewPerformanceReportFormat creates a new performance report formatter

func (*PerformanceReportFormat) ToCSV

func (f *PerformanceReportFormat) ToCSV(results map[string]*BenchmarkResult) string

ToCSV converts results to CSV

func (*PerformanceReportFormat) ToJSON

func (f *PerformanceReportFormat) ToJSON(results map[string]*BenchmarkResult) string

ToJSON converts results to JSON

func (*PerformanceReportFormat) ToMarkdown

func (f *PerformanceReportFormat) ToMarkdown(results map[string]*BenchmarkResult) string

ToMarkdown converts results to Markdown

type PerformanceSuite

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

PerformanceSuite is a collection of performance tests

func NewPerformanceSuite

func NewPerformanceSuite(name string) *PerformanceSuite

NewPerformanceSuite creates a new performance suite

func (*PerformanceSuite) Add

func (ps *PerformanceSuite) Add(name string, fn func() *BenchmarkResult) *PerformanceSuite

Add adds a test to the suite

func (*PerformanceSuite) Run

func (ps *PerformanceSuite) Run() map[string]*BenchmarkResult

Run runs all tests in the suite

type PerformanceTestHelper

type PerformanceTestHelper struct{}

PerformanceTestHelper provides helper methods for performance testing

func NewPerformanceTestHelper

func NewPerformanceTestHelper() *PerformanceTestHelper

NewPerformanceTestHelper creates a new performance test helper

func (*PerformanceTestHelper) CompareResults

func (h *PerformanceTestHelper) CompareResults(a, b *BenchmarkResult) string

CompareResults compares two benchmark results

func (*PerformanceTestHelper) IsRegression

func (h *PerformanceTestHelper) IsRegression(current, baseline *BenchmarkResult, threshold float64) bool

IsRegression checks if there's a performance regression

func (*PerformanceTestHelper) MeasureDuration

func (h *PerformanceTestHelper) MeasureDuration(fn func()) time.Duration

MeasureDuration measures duration of a function

func (*PerformanceTestHelper) MeasureMemory

func (h *PerformanceTestHelper) MeasureMemory(fn func()) *MemoryDiff

MeasureMemory measures memory usage of a function

func (*PerformanceTestHelper) MeasureThroughput

func (h *PerformanceTestHelper) MeasureThroughput(fn func(), duration time.Duration) float64

MeasureThroughput measures throughput of a function

type PerformanceTestSuite

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

PerformanceTestSuite is a suite for performance testing

func NewPerformanceTestSuite

func NewPerformanceTestSuite(name string) *PerformanceTestSuite

NewPerformanceTestSuite creates a new performance test suite

func (*PerformanceTestSuite) Add

Add adds a benchmark to the suite

func (*PerformanceTestSuite) Run

Run runs all benchmarks in the suite

type Stage

type Stage struct {
	Name        string
	Concurrency int
	Duration    time.Duration
	TargetRPS   float64
}

Stage represents a stress test stage

type StageResult

type StageResult struct {
	Stage
	LoadTestResult *LoadTestResult
}

StageResult represents a stage result

type StressTest

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

StressTest runs a stress test

func NewStressTest

func NewStressTest(config StressTestConfig, workload func() error) *StressTest

NewStressTest creates a new stress test

func (*StressTest) Run

func (st *StressTest) Run() *StressTestResult

Run executes the stress test

type StressTestConfig

type StressTestConfig struct {
	Stages []Stage
}

StressTestConfig represents stress test configuration

type StressTestResult

type StressTestResult struct {
	Stages []StageResult
}

StressTestResult represents a stress test result

type TestConfig

type TestConfig struct {
	Timeout    time.Duration
	RetryCount int
	RetryDelay time.Duration
	Verbose    bool
}

TestConfig holds test configuration

func DefaultTestConfig

func DefaultTestConfig() TestConfig

DefaultTestConfig creates a default test configuration

type TestContext

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

TestContext holds test context and utilities

func NewTestContext

func NewTestContext(t *testing.T) *TestContext

NewTestContext creates a new test context

func (*TestContext) AssertContains

func (tc *TestContext) AssertContains(s, substr string, msg string)

AssertContains asserts string contains substring

func (*TestContext) AssertEqual

func (tc *TestContext) AssertEqual(expected, actual interface{}, msg string)

AssertEqual asserts two values are equal

func (*TestContext) AssertError

func (tc *TestContext) AssertError(err error, msg string)

AssertError asserts error is not nil

func (*TestContext) AssertFalse

func (tc *TestContext) AssertFalse(value bool, msg string)

AssertFalse asserts value is false

func (*TestContext) AssertLen

func (tc *TestContext) AssertLen(value interface{}, expected int, msg string)

AssertLen asserts length

func (*TestContext) AssertNil

func (tc *TestContext) AssertNil(value interface{}, msg string)

AssertNil asserts value is nil

func (*TestContext) AssertNoError

func (tc *TestContext) AssertNoError(err error, msg string)

AssertNoError asserts error is nil

func (*TestContext) AssertNotEqual

func (tc *TestContext) AssertNotEqual(expected, actual interface{}, msg string)

AssertNotEqual asserts two values are not equal

func (*TestContext) AssertNotNil

func (tc *TestContext) AssertNotNil(value interface{}, msg string)

AssertNotNil asserts value is not nil

func (*TestContext) AssertTrue

func (tc *TestContext) AssertTrue(value bool, msg string)

AssertTrue asserts value is true

func (*TestContext) Cleanup

func (tc *TestContext) Cleanup()

Cleanup cleans up resources

func (*TestContext) Context

func (tc *TestContext) Context() context.Context

Context returns the context

func (*TestContext) Get

func (tc *TestContext) Get(name string) interface{}

Get retrieves a component

func (*TestContext) MustGet

func (tc *TestContext) MustGet(name string) interface{}

MustGet retrieves a component or fails the test

func (*TestContext) Set

func (tc *TestContext) Set(name string, component interface{})

Set stores a component

type TestHelper

type TestHelper struct{}

TestHelper provides common test helpers

func NewTestHelper

func NewTestHelper() *TestHelper

NewTestHelper creates a new test helper

func (*TestHelper) CaptureOutput

func (h *TestHelper) CaptureOutput(fn func()) (stdout, stderr string)

CaptureOutput captures stdout/stderr

func (*TestHelper) Diff

func (h *TestHelper) Diff(a, b string) string

Diff returns the difference between two JSON strings

func (*TestHelper) Eventually

func (h *TestHelper) Eventually(fn func() bool, timeout time.Duration, interval time.Duration) error

Eventually waits for a condition to be true

func (*TestHelper) JSONEquals

func (h *TestHelper) JSONEquals(a, b string) bool

JSONEquals compares two JSON strings

func (*TestHelper) Retry

func (h *TestHelper) Retry(fn func() error, maxAttempts int, delay time.Duration) error

Retry retries a function until it succeeds or max attempts reached

func (*TestHelper) TempDir

func (h *TestHelper) TempDir() (string, func())

TempDir creates a temporary directory

func (*TestHelper) TempFile

func (h *TestHelper) TempFile(content string) (*os.File, func())

TempFile creates a temporary file

type TestReporter

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

TestReporter is a custom test reporter

func NewTestReporter

func NewTestReporter() *TestReporter

NewTestReporter creates a new test reporter

func (*TestReporter) Clear

func (tr *TestReporter) Clear()

Clear clears all results

func (*TestReporter) GetResults

func (tr *TestReporter) GetResults() []TestResult

GetResults returns all results

func (*TestReporter) Report

func (tr *TestReporter) Report(name string, pass bool, err error, duration time.Duration)

Report records a test result

func (*TestReporter) Summary

func (tr *TestReporter) Summary() (passed, failed int)

Summary returns a summary

type TestResult

type TestResult struct {
	Name     string
	Pass     bool
	Error    string
	Duration time.Duration
}

TestResult represents a test result

type TestRunner

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

TestRunner runs tests with setup and teardown

func NewTestRunner

func NewTestRunner() *TestRunner

NewTestRunner creates a new test runner

func (*TestRunner) Add

func (tr *TestRunner) Add(name string, fn func(*TestContext)) *TestRunner

Add adds a test

func (*TestRunner) Run

func (tr *TestRunner) Run(t *testing.T)

Run runs all tests

func (*TestRunner) Setup

func (tr *TestRunner) Setup(fn func(*TestContext) error) *TestRunner

Setup sets up the test runner

func (*TestRunner) Teardown

func (tr *TestRunner) Teardown(fn func(*TestContext) error) *TestRunner

Teardown sets up the teardown

type TestRunnerV2

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

TestRunnerV2 runs tests with configuration

func NewTestRunnerV2

func NewTestRunnerV2(config TestConfig) *TestRunnerV2

NewTestRunnerV2 creates a new test runner v2

func (*TestRunnerV2) Add

func (tr *TestRunnerV2) Add(name string, fn func(*TestContext) error) *TestRunnerV2

Add adds a test

func (*TestRunnerV2) Run

func (tr *TestRunnerV2) Run(t *testing.T)

Run runs all tests

type TestSuite

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

TestSuite is a collection of tests

func NewTestSuite

func NewTestSuite(name string) *TestSuite

NewTestSuite creates a new test suite

func (*TestSuite) Add

func (ts *TestSuite) Add(name string, fn func(*testing.T)) *TestSuite

Add adds a test to the suite

func (*TestSuite) Run

func (ts *TestSuite) Run(t *testing.T)

Run runs all tests in the suite

type ThroughputTest

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

ThroughputTest measures throughput

func NewThroughputTest

func NewThroughputTest(duration time.Duration, workload func()) *ThroughputTest

NewThroughputTest creates a new throughput test

func (*ThroughputTest) Run

func (tt *ThroughputTest) Run() *BenchmarkResult

Run executes the throughput test

Jump to

Keyboard shortcuts

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