Documentation
¶
Overview ¶
Package testhelper provides utilities for testing, including goroutine leak detection, resource cleanup helpers, and context management utilities.
The package is designed to help identify and prevent common testing issues such as: - Goroutine leaks that can cause tests to hang or fail intermittently - Resource leaks from unclosed channels, connections, or workers - Context cancellation issues that leave operations running
Example usage:
func TestExample(t *testing.T) { // Detect goroutine leaks defer testhelper.VerifyNoGoroutineLeaks(t) // Use auto-cleanup context ctx := testhelper.NewTestContext(t) // Your test code here }
Index ¶
- Variables
- func AddChan[T any](cc *ChannelCleanup, name string, ch chan T)
- func AssertContextCancelled(t *testing.T, ctx context.Context, timeout time.Duration)
- func AssertContextTimeout(t *testing.T, ctx context.Context, timeout time.Duration)
- func CloseChannel[T any](t *testing.T, ch chan T, name string)
- func CloseConnection(t *testing.T, conn io.Closer, name string)
- func ContextWithValues(parent context.Context, values map[string]interface{}) context.Context
- func DetectBlockedGoroutines(t *testing.T)
- func DrainChannel[T any](t *testing.T, ch chan T, name string, timeout time.Duration)
- func EnsureCleanup(t *testing.T, name string, fn func(), cleanup func())
- func IsCI() bool
- func MonitorGoroutines(t *testing.T, interval time.Duration) func()
- func RunWithContext(t *testing.T, name string, fn func(context.Context) error) error
- func SafeCloseChannelConcurrently[T any](t *testing.T, ch chan T, name string, goroutineCount int)
- func SetGlobalTimeouts(config *TimeoutConfig)
- func StopWorker(t *testing.T, done chan<- struct{}, name string, timeout time.Duration)
- func VerifyNoGoroutineLeaks(t *testing.T)
- func WaitForContext(t *testing.T, ctx context.Context, name string, timeout time.Duration) bool
- func WaitForGoroutines(t *testing.T, expectedDelta int, timeout time.Duration)
- func WaitGroupTimeout(t *testing.T, wg *sync.WaitGroup, timeout time.Duration) bool
- func WithCleanup[T any](acm *AdvancedCleanupManager, name string, fn func() (T, error), ...) (T, error)
- func WithMockServer(t *testing.T, fn func(*MockHTTPServer) error) error
- func WithResource[T any](t *testing.T, name string, create func() (T, func() error, error), ...) error
- func WithTempDir(t *testing.T, prefix string, fn func(string) error) error
- func WithTimeout[T any](t *testing.T, timeout time.Duration, fn func() (T, error)) (T, error)
- type AdvancedCleanupManager
- func (acm *AdvancedCleanupManager) AddCleanup(name string, fn func() error, priority int)
- func (acm *AdvancedCleanupManager) AddCleanupWithTimeout(name string, fn func() error, priority int, timeout time.Duration)
- func (acm *AdvancedCleanupManager) AddSimpleCleanup(name string, fn func())
- func (acm *AdvancedCleanupManager) CleanupAfterDelay(name string, fn func() error, delay time.Duration)
- func (acm *AdvancedCleanupManager) CleanupOnCondition(name string, fn func() error, condition func() bool)
- func (acm *AdvancedCleanupManager) CreateTempDir(prefix string) (string, error)
- func (acm *AdvancedCleanupManager) CreateTempFile(pattern string) (*os.File, error)
- func (acm *AdvancedCleanupManager) ExecuteAllCleanup()
- func (acm *AdvancedCleanupManager) SetErrorHandler(handler func(string, error))
- func (acm *AdvancedCleanupManager) SetParallelCleanup(enabled bool)
- func (acm *AdvancedCleanupManager) TrackResource(resourceType string) *ResourceCounter
- type AutoCleanup
- func (ac *AutoCleanup) CreateMockServer() (*MockHTTPServer, error)
- func (ac *AutoCleanup) CreateTempDir(prefix string) (string, error)
- func (ac *AutoCleanup) MustUse(name string, create func() (interface{}, func() error, error)) interface{}
- func (ac *AutoCleanup) Use(name string, create func() (interface{}, func() error, error)) (interface{}, error)
- type ChannelCleanup
- type CleanupGuard
- type CleanupHelper
- type CleanupManager
- type CleanupOnExit
- type CommonFixtures
- type ConcurrencyTestFixture
- type ConcurrentRunner
- func (cr *ConcurrentRunner) GetRunningCount() int64
- func (cr *ConcurrentRunner) Run(name string, fn func() error)
- func (cr *ConcurrentRunner) RunSimple(name string, fn func())
- func (cr *ConcurrentRunner) Wait() []error
- func (cr *ConcurrentRunner) WaitWithTimeout(timeout time.Duration) ([]error, bool)
- type ContextManager
- type DatabaseCleanup
- type DatabaseTestFixture
- type DeferStack
- type DeferredCleanup
- func (dc *DeferredCleanup) Defer(name string, fn func() error)
- func (dc *DeferredCleanup) DeferCancel(name string, cancel context.CancelFunc)
- func (dc *DeferredCleanup) DeferClose(name string, closer interface{})
- func (dc *DeferredCleanup) DeferSimple(name string, fn func())
- func (dc *DeferredCleanup) ExecuteAll()
- func (dc *DeferredCleanup) WithTimeout(timeout time.Duration) *DeferredCleanup
- type DeferredCloser
- type EventTestFixture
- type FileSystemTestFixture
- type FixtureManager
- type GoroutineLeakDetector
- type HTTPTestFixture
- type HTTPTestSuite
- func (suite *HTTPTestSuite) CreateClient(name string, timeout time.Duration) *http.Client
- func (suite *HTTPTestSuite) CreateHTTPSServer(name string) *MockHTTPServer
- func (suite *HTTPTestSuite) CreateServer(name string) *MockHTTPServer
- func (suite *HTTPTestSuite) GetClient(name string) *http.Client
- func (suite *HTTPTestSuite) GetServer(name string) *MockHTTPServer
- func (suite *HTTPTestSuite) WithTimeouts(timeouts *TimeoutConfig) *HTTPTestSuite
- type MockDialer
- func (m *MockDialer) Dial(network, address string) (net.Conn, error)
- func (m *MockDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error)
- func (m *MockDialer) GetConnection(network, address string) net.Conn
- func (m *MockDialer) SetDialDelay(delay time.Duration)
- func (m *MockDialer) SetDialError(err error)
- func (m *MockDialer) SetDialHandler(handler func(network, address string) (net.Conn, error))
- type MockHTTPRequest
- type MockHTTPResponse
- type MockHTTPServer
- func (m *MockHTTPServer) AddMiddleware(middleware func(http.HandlerFunc) http.HandlerFunc)
- func (m *MockHTTPServer) ClearRequests()
- func (m *MockHTTPServer) Close()
- func (m *MockHTTPServer) GetClient() *http.Client
- func (m *MockHTTPServer) GetLastRequest() *MockHTTPRequest
- func (m *MockHTTPServer) GetRequestCount() int
- func (m *MockHTTPServer) GetRequests() []MockHTTPRequest
- func (m *MockHTTPServer) GetURL() string
- func (m *MockHTTPServer) SetDefaultDelay(delay time.Duration)
- func (m *MockHTTPServer) SetErrorResponse(method, path string, err error)
- func (m *MockHTTPServer) SetJSONResponse(method, path string, statusCode int, data interface{}) error
- func (m *MockHTTPServer) SetRequestHandler(handler func(*http.Request))
- func (m *MockHTTPServer) SetResponse(method, path string, response MockHTTPResponse)
- func (m *MockHTTPServer) SetTextResponse(method, path string, statusCode int, text string)
- func (m *MockHTTPServer) WaitForRequests(count int, timeout time.Duration) bool
- type MockListener
- func (m *MockListener) Accept() (net.Conn, error)
- func (m *MockListener) AddConnection(conn net.Conn)
- func (m *MockListener) Addr() net.Addr
- func (m *MockListener) Close() error
- func (m *MockListener) GetConnectionCount() int64
- func (m *MockListener) SetAcceptDelay(delay time.Duration)
- func (m *MockListener) SetAcceptError(err error)
- type MockMessage
- type MockNetworkConnection
- func (m *MockNetworkConnection) AddReadData(data []byte)
- func (m *MockNetworkConnection) Close() error
- func (m *MockNetworkConnection) GetStats() (bytesRead, bytesWritten int64)
- func (m *MockNetworkConnection) GetWrittenData() []byte
- func (m *MockNetworkConnection) IsClosed() bool
- func (m *MockNetworkConnection) LocalAddr() net.Addr
- func (m *MockNetworkConnection) Read(b []byte) (int, error)
- func (m *MockNetworkConnection) RemoteAddr() net.Addr
- func (m *MockNetworkConnection) SetBlockingBehavior(readBlock, writeBlock time.Duration)
- func (m *MockNetworkConnection) SetCloseHandler(handler func() error)
- func (m *MockNetworkConnection) SetDeadline(t time.Time) error
- func (m *MockNetworkConnection) SetReadDeadline(t time.Time) error
- func (m *MockNetworkConnection) SetReadHandler(handler func([]byte) (int, error))
- func (m *MockNetworkConnection) SetWriteDeadline(t time.Time) error
- func (m *MockNetworkConnection) SetWriteHandler(handler func([]byte) (int, error))
- func (m *MockNetworkConnection) SimulateError(err error)
- func (m *MockNetworkConnection) Write(b []byte) (int, error)
- type MockPacketConn
- func (m *MockPacketConn) AddPacket(data []byte, addr net.Addr)
- func (m *MockPacketConn) Close() error
- func (m *MockPacketConn) LocalAddr() net.Addr
- func (m *MockPacketConn) ReadFrom(p []byte) (int, net.Addr, error)
- func (m *MockPacketConn) SetDeadline(t time.Time) error
- func (m *MockPacketConn) SetReadDeadline(t time.Time) error
- func (m *MockPacketConn) SetWriteDeadline(t time.Time) error
- func (m *MockPacketConn) WriteTo(p []byte, addr net.Addr) (int, error)
- type MockRoundTripper
- type MockWebSocketConn
- func (m *MockWebSocketConn) AddMessage(messageType int, data []byte)
- func (m *MockWebSocketConn) Close() error
- func (m *MockWebSocketConn) GetMessageCount() int
- func (m *MockWebSocketConn) IsClosed() bool
- func (m *MockWebSocketConn) LocalAddr() net.Addr
- func (m *MockWebSocketConn) ReadMessage() (messageType int, p []byte, err error)
- func (m *MockWebSocketConn) RemoteAddr() net.Addr
- func (m *MockWebSocketConn) SetCloseHandler(handler func(code int, text string) error)
- func (m *MockWebSocketConn) SetPingHandler(h func(appData string) error)
- func (m *MockWebSocketConn) SetPongHandler(h func(appData string) error)
- func (m *MockWebSocketConn) SetReadDeadline(t time.Time) error
- func (m *MockWebSocketConn) SetWriteDeadline(t time.Time) error
- func (m *MockWebSocketConn) SetWriteHandler(handler func(messageType int, data []byte) error)
- func (m *MockWebSocketConn) WriteMessage(messageType int, data []byte) error
- type MockWebSocketDialer
- func (d *MockWebSocketDialer) CloseAll()
- func (d *MockWebSocketDialer) Dial(urlStr string, requestHeader http.Header) (*MockWebSocketConn, *http.Response, error)
- func (d *MockWebSocketDialer) DialContext(ctx context.Context, urlStr string, requestHeader http.Header) (*MockWebSocketConn, *http.Response, error)
- func (d *MockWebSocketDialer) GetAllConnections() map[string]*MockWebSocketConn
- func (d *MockWebSocketDialer) GetConnection(urlStr string) *MockWebSocketConn
- func (d *MockWebSocketDialer) SetDialDelay(delay time.Duration)
- func (d *MockWebSocketDialer) SetDialError(err error)
- type MockWebSocketServer
- func (s *MockWebSocketServer) BroadcastMessage(messageType int, data []byte)
- func (s *MockWebSocketServer) GetConnectionCount() int
- func (s *MockWebSocketServer) GetHTTPURL() string
- func (s *MockWebSocketServer) GetURL() string
- func (s *MockWebSocketServer) SetHandlers(onConnect func(*websocket.Conn), onMessage func(*websocket.Conn, int, []byte), ...)
- func (s *MockWebSocketServer) Start() error
- func (s *MockWebSocketServer) Stop() error
- type NetworkCleanup
- type NetworkTestSuite
- func (nts *NetworkTestSuite) CreateConnection(name string, localAddr, remoteAddr net.Addr) *MockNetworkConnection
- func (nts *NetworkTestSuite) CreateDialer(name string) *MockDialer
- func (nts *NetworkTestSuite) CreateListener(name string, addr net.Addr) *MockListener
- func (nts *NetworkTestSuite) GetConnection(name string) *MockNetworkConnection
- func (nts *NetworkTestSuite) GetDialer(name string) *MockDialer
- func (nts *NetworkTestSuite) GetListener(name string) *MockListener
- func (nts *NetworkTestSuite) RestoreNetworkConnectivity(connNames ...string)
- func (nts *NetworkTestSuite) SimulateNetworkPartition(connNames ...string)
- type ParallelContexts
- type PerformanceTestFixture
- type ProcessCleanup
- type ProcessInfo
- type ResourceCounter
- type ResourceTracker
- type SSEMockServer
- type SafeWaitGroup
- func (swg *SafeWaitGroup) Add(delta int)
- func (swg *SafeWaitGroup) Done()
- func (swg *SafeWaitGroup) GetCount() int64
- func (swg *SafeWaitGroup) GetWaitGroup() *sync.WaitGroup
- func (swg *SafeWaitGroup) SetTimeout(timeout time.Duration)
- func (swg *SafeWaitGroup) Wait()
- func (swg *SafeWaitGroup) WaitWithTimeout(timeout time.Duration) bool
- type TestContext
- type TestFixture
- type TimeoutConfig
- type TimeoutGuard
- type TimeoutOption
- type WaitGroupPool
- type WebSocketTestFixture
- type WebSocketTestSuite
- func (suite *WebSocketTestSuite) GetDialer() *MockWebSocketDialer
- func (suite *WebSocketTestSuite) GetServer() *MockWebSocketServer
- func (suite *WebSocketTestSuite) GetServerURL() string
- func (suite *WebSocketTestSuite) Setup() error
- func (suite *WebSocketTestSuite) WithTimeouts(timeouts *TimeoutConfig) *WebSocketTestSuite
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var GlobalTimeouts = NewTimeoutConfig()
Global timeout configuration instance
var WaitGroup *sync.WaitGroup
WaitGroup property for accessing the underlying WaitGroup
Functions ¶
func AddChan ¶
func AddChan[T any](cc *ChannelCleanup, name string, ch chan T)
AddChan registers a typed channel for cleanup
func AssertContextCancelled ¶
AssertContextCancelled verifies a context was cancelled within timeout
func AssertContextTimeout ¶
AssertContextTimeout verifies a context timed out
func CloseChannel ¶
CloseChannel safely closes a channel with panic recovery This function is now idempotent and thread-safe
func CloseConnection ¶
CloseConnection safely closes any io.Closer (connections, files, etc.)
func ContextWithValues ¶
ContextWithValues creates a context with common test values
func DetectBlockedGoroutines ¶
DetectBlockedGoroutines checks for goroutines that might be blocked
func DrainChannel ¶
DrainChannel drains all values from a channel before closing
func EnsureCleanup ¶
EnsureCleanup wraps a function to ensure cleanup happens
func MonitorGoroutines ¶
MonitorGoroutines logs goroutine counts periodically during test execution
func RunWithContext ¶
RunWithContext runs a function with automatic context cleanup
func SafeCloseChannelConcurrently ¶
SafeCloseChannelConcurrently demonstrates safe concurrent channel closure
func SetGlobalTimeouts ¶
func SetGlobalTimeouts(config *TimeoutConfig)
SetGlobalTimeouts allows setting a custom global timeout configuration
func StopWorker ¶
StopWorker stops a worker goroutine using a done channel
func VerifyNoGoroutineLeaks ¶
VerifyNoGoroutineLeaks is a convenience function that checks for leaks at test end
Example ¶
ExampleVerifyNoGoroutineLeaks shows basic usage
// In your test: // func TestSomething(t *testing.T) { // defer VerifyNoGoroutineLeaks(t) // // // Your test code here // }
func WaitForContext ¶
WaitForContext waits for a context to be done or timeout
func WaitForGoroutines ¶
WaitForGoroutines waits for goroutine count to stabilize
func WaitGroupTimeout ¶
WaitGroupTimeout waits for a WaitGroup with timeout
func WithCleanup ¶
func WithCleanup[T any](acm *AdvancedCleanupManager, name string, fn func() (T, error), cleanup func() error) (T, error)
WithCleanup executes a function with automatic cleanup
func WithMockServer ¶
func WithMockServer(t *testing.T, fn func(*MockHTTPServer) error) error
WithMockServer executes a function with a mock HTTP server
func WithResource ¶
func WithResource[T any](t *testing.T, name string, create func() (T, func() error, error), use func(T) error) error
WithResource executes a function with a resource that gets automatically cleaned up
func WithTempDir ¶
WithTempDir executes a function with a temporary directory
Types ¶
type AdvancedCleanupManager ¶
type AdvancedCleanupManager struct {
// contains filtered or unexported fields
}
AdvancedCleanupManager provides enhanced cleanup capabilities
func NewAdvancedCleanupManager ¶
func NewAdvancedCleanupManager(t *testing.T) *AdvancedCleanupManager
NewAdvancedCleanupManager creates an enhanced cleanup manager
func (*AdvancedCleanupManager) AddCleanup ¶
func (acm *AdvancedCleanupManager) AddCleanup(name string, fn func() error, priority int)
AddCleanup adds a cleanup function with priority and timeout
func (*AdvancedCleanupManager) AddCleanupWithTimeout ¶
func (acm *AdvancedCleanupManager) AddCleanupWithTimeout(name string, fn func() error, priority int, timeout time.Duration)
AddCleanupWithTimeout adds a cleanup function with custom timeout
func (*AdvancedCleanupManager) AddSimpleCleanup ¶
func (acm *AdvancedCleanupManager) AddSimpleCleanup(name string, fn func())
AddSimpleCleanup adds a simple cleanup function without error handling
func (*AdvancedCleanupManager) CleanupAfterDelay ¶
func (acm *AdvancedCleanupManager) CleanupAfterDelay(name string, fn func() error, delay time.Duration)
CleanupAfterDelay schedules cleanup to run after a delay
func (*AdvancedCleanupManager) CleanupOnCondition ¶
func (acm *AdvancedCleanupManager) CleanupOnCondition(name string, fn func() error, condition func() bool)
CleanupOnCondition adds conditional cleanup that only runs if condition is true
func (*AdvancedCleanupManager) CreateTempDir ¶
func (acm *AdvancedCleanupManager) CreateTempDir(prefix string) (string, error)
CreateTempDir creates a temporary directory that will be automatically cleaned up
func (*AdvancedCleanupManager) CreateTempFile ¶
func (acm *AdvancedCleanupManager) CreateTempFile(pattern string) (*os.File, error)
CreateTempFile creates a temporary file that will be automatically cleaned up
func (*AdvancedCleanupManager) ExecuteAllCleanup ¶
func (acm *AdvancedCleanupManager) ExecuteAllCleanup()
ExecuteAllCleanup executes all registered cleanup functions
func (*AdvancedCleanupManager) SetErrorHandler ¶
func (acm *AdvancedCleanupManager) SetErrorHandler(handler func(string, error))
SetErrorHandler sets a custom error handler for cleanup failures
func (*AdvancedCleanupManager) SetParallelCleanup ¶
func (acm *AdvancedCleanupManager) SetParallelCleanup(enabled bool)
SetParallelCleanup enables/disables parallel cleanup execution
func (*AdvancedCleanupManager) TrackResource ¶
func (acm *AdvancedCleanupManager) TrackResource(resourceType string) *ResourceCounter
TrackResource starts tracking a resource type
type AutoCleanup ¶
type AutoCleanup struct {
// contains filtered or unexported fields
}
AutoCleanup provides automatic cleanup for resources using defer patterns
func NewAutoCleanup ¶
func NewAutoCleanup(t *testing.T) *AutoCleanup
NewAutoCleanup creates a new auto cleanup manager
func (*AutoCleanup) CreateMockServer ¶
func (ac *AutoCleanup) CreateMockServer() (*MockHTTPServer, error)
CreateMockServer creates a mock server with automatic cleanup
func (*AutoCleanup) CreateTempDir ¶
func (ac *AutoCleanup) CreateTempDir(prefix string) (string, error)
CreateTempDir creates a temporary directory with automatic cleanup
type ChannelCleanup ¶
type ChannelCleanup struct {
// contains filtered or unexported fields
}
ChannelCleanup manages channel cleanup
func NewChannelCleanup ¶
func NewChannelCleanup(t *testing.T) *ChannelCleanup
NewChannelCleanup creates a channel cleanup helper
func (*ChannelCleanup) Add ¶
func (cc *ChannelCleanup) Add(name string, cleanup func())
Add registers a channel for cleanup
func (*ChannelCleanup) CleanupAll ¶
func (cc *ChannelCleanup) CleanupAll()
CleanupAll closes all registered channels
func (*ChannelCleanup) MarkChannelClosed ¶
func (cc *ChannelCleanup) MarkChannelClosed(name string)
MarkChannelClosed allows manual marking of a channel as closed This prevents double-closure when channels are closed manually
type CleanupGuard ¶
type CleanupGuard struct {
// contains filtered or unexported fields
}
CleanupGuard provides automatic cleanup with defer patterns
func NewCleanupGuard ¶
func NewCleanupGuard(acm *AdvancedCleanupManager, name string, cleanup func() error) *CleanupGuard
NewCleanupGuard creates a cleanup guard that can be deferred
func (*CleanupGuard) Cancel ¶
func (cg *CleanupGuard) Cancel()
Cancel cancels the cleanup (prevents execution)
func (*CleanupGuard) Defer ¶
func (cg *CleanupGuard) Defer()
Defer registers the cleanup to be executed later
func (*CleanupGuard) Execute ¶
func (cg *CleanupGuard) Execute() error
Execute immediately executes the cleanup
type CleanupHelper ¶
type CleanupHelper struct {
// contains filtered or unexported fields
}
CleanupHelper provides utilities for cleaning up resources in tests
func NewCleanupHelper ¶
func NewCleanupHelper(t *testing.T) *CleanupHelper
NewCleanupHelper creates a new cleanup helper
func (*CleanupHelper) Add ¶
func (ch *CleanupHelper) Add(cleanup func())
Add registers a cleanup function
func (*CleanupHelper) RunCleanup ¶
func (ch *CleanupHelper) RunCleanup()
RunCleanup executes all cleanup functions in reverse order
type CleanupManager ¶
type CleanupManager struct {
// contains filtered or unexported fields
}
CleanupManager manages multiple cleanup operations
func NewCleanupManager ¶
func NewCleanupManager(t *testing.T) *CleanupManager
NewCleanupManager creates a new cleanup manager
Example ¶
ExampleNewCleanupManager shows cleanup management
// In your test: // func TestSomething(t *testing.T) { // cm := NewCleanupManager(t) // // // Register cleanup operations // cm.Register("database", func() { // db.Close() // }) // // // Cleanup happens automatically // }
func (*CleanupManager) Cleanup ¶
func (cm *CleanupManager) Cleanup(name string)
Cleanup cleans up a specific resource
func (*CleanupManager) CleanupAll ¶
func (cm *CleanupManager) CleanupAll()
CleanupAll cleans up all resources
func (*CleanupManager) Register ¶
func (cm *CleanupManager) Register(name string, cleanup func())
Register adds a named resource for cleanup
type CleanupOnExit ¶
type CleanupOnExit struct {
// contains filtered or unexported fields
}
CleanupOnExit ensures cleanup happens even if test exits unexpectedly
func NewCleanupOnExit ¶
func NewCleanupOnExit(t *testing.T) *CleanupOnExit
NewCleanupOnExit creates a cleanup-on-exit manager
func (*CleanupOnExit) ExecuteAll ¶
func (coe *CleanupOnExit) ExecuteAll()
ExecuteAll executes all registered cleanup functions
func (*CleanupOnExit) Register ¶
func (coe *CleanupOnExit) Register(fn func())
Register adds a cleanup function to be executed on exit
type CommonFixtures ¶
type CommonFixtures struct { HTTP *HTTPTestFixture WebSocket *WebSocketTestFixture FileSystem *FileSystemTestFixture Event *EventTestFixture Concurrency *ConcurrencyTestFixture Performance *PerformanceTestFixture Manager *FixtureManager }
CommonFixtures provides access to commonly used fixtures
func NewCommonFixtures ¶
func NewCommonFixtures(t *testing.T) *CommonFixtures
NewCommonFixtures creates a set of commonly used fixtures
func (*CommonFixtures) SetupAll ¶
func (cf *CommonFixtures) SetupAll() error
SetupAll sets up all fixtures
type ConcurrencyTestFixture ¶
type ConcurrencyTestFixture struct { *TestFixture Context context.Context Cancel context.CancelFunc WaitGroups map[string]*SafeWaitGroup Channels map[string]interface{} }
ConcurrencyTestFixture provides utilities for testing concurrent operations
func NewConcurrencyTestFixture ¶
func NewConcurrencyTestFixture(t *testing.T) *ConcurrencyTestFixture
NewConcurrencyTestFixture creates a concurrency test fixture
func (*ConcurrencyTestFixture) CreateChannel ¶
func (ctf *ConcurrencyTestFixture) CreateChannel(name string, size int) chan interface{}
CreateChannel creates a named channel
func (*ConcurrencyTestFixture) CreateWaitGroup ¶
func (ctf *ConcurrencyTestFixture) CreateWaitGroup(name string) *SafeWaitGroup
CreateWaitGroup creates a named wait group
type ConcurrentRunner ¶
type ConcurrentRunner struct {
// contains filtered or unexported fields
}
ConcurrentRunner helps run multiple goroutines safely with wait groups
func NewConcurrentRunner ¶
func NewConcurrentRunner(t *testing.T) *ConcurrentRunner
NewConcurrentRunner creates a new concurrent runner
func (*ConcurrentRunner) GetRunningCount ¶
func (cr *ConcurrentRunner) GetRunningCount() int64
GetRunningCount returns the number of currently running goroutines
func (*ConcurrentRunner) Run ¶
func (cr *ConcurrentRunner) Run(name string, fn func() error)
Run executes a function in a goroutine
func (*ConcurrentRunner) RunSimple ¶
func (cr *ConcurrentRunner) RunSimple(name string, fn func())
RunSimple executes a simple function in a goroutine
func (*ConcurrentRunner) Wait ¶
func (cr *ConcurrentRunner) Wait() []error
Wait waits for all goroutines to complete and returns any errors
func (*ConcurrentRunner) WaitWithTimeout ¶
func (cr *ConcurrentRunner) WaitWithTimeout(timeout time.Duration) ([]error, bool)
WaitWithTimeout waits with a timeout and returns any errors
type ContextManager ¶
type ContextManager struct {
// contains filtered or unexported fields
}
ContextManager manages multiple contexts in tests
func NewContextManager ¶
func NewContextManager(t *testing.T) *ContextManager
NewContextManager creates a context manager
func (*ContextManager) Cancel ¶
func (cm *ContextManager) Cancel(name string)
Cancel cancels a specific context
func (*ContextManager) CancelAll ¶
func (cm *ContextManager) CancelAll()
CancelAll cancels all managed contexts
func (*ContextManager) Create ¶
func (cm *ContextManager) Create(name string) *TestContext
Create creates a named context
func (*ContextManager) CreateWithTimeout ¶
func (cm *ContextManager) CreateWithTimeout(name string, timeout time.Duration) *TestContext
CreateWithTimeout creates a named context with timeout
func (*ContextManager) Get ¶
func (cm *ContextManager) Get(name string) *TestContext
Get retrieves a named context
type DatabaseCleanup ¶
type DatabaseCleanup struct {
// contains filtered or unexported fields
}
DatabaseCleanup provides database-specific cleanup utilities
func NewDatabaseCleanup ¶
func NewDatabaseCleanup(t *testing.T, db *sql.DB) *DatabaseCleanup
NewDatabaseCleanup creates a database cleanup helper
func (*DatabaseCleanup) AddTable ¶
func (dc *DatabaseCleanup) AddTable(tableName string)
AddTable adds a table to be truncated during cleanup
func (*DatabaseCleanup) AddTransaction ¶
func (dc *DatabaseCleanup) AddTransaction(tx *sql.Tx)
AddTransaction adds a transaction rollback to cleanup
type DatabaseTestFixture ¶
type DatabaseTestFixture struct { *TestFixture ConnectionString string Tables []string }
DatabaseTestFixture provides database testing utilities
func NewDatabaseTestFixture ¶
func NewDatabaseTestFixture(t *testing.T, connectionString string) *DatabaseTestFixture
NewDatabaseTestFixture creates a database test fixture
func (*DatabaseTestFixture) AddTable ¶
func (dtf *DatabaseTestFixture) AddTable(tableName string)
AddTable adds a table to be managed by the fixture
type DeferStack ¶
type DeferStack struct {
// contains filtered or unexported fields
}
DeferStack provides a simple defer-like stack for cleanup
func (*DeferStack) Len ¶
func (ds *DeferStack) Len() int
Len returns the number of functions in the stack
func (*DeferStack) PopAll ¶
func (ds *DeferStack) PopAll()
PopAll executes all functions in LIFO order
func (*DeferStack) Push ¶
func (ds *DeferStack) Push(fn func())
Push adds a function to the defer stack
type DeferredCleanup ¶
type DeferredCleanup struct {
// contains filtered or unexported fields
}
DeferredCleanup provides patterns for automatic resource cleanup using defer
func NewDeferredCleanup ¶
func NewDeferredCleanup(t *testing.T) *DeferredCleanup
NewDeferredCleanup creates a new deferred cleanup manager
func (*DeferredCleanup) Defer ¶
func (dc *DeferredCleanup) Defer(name string, fn func() error)
Defer adds a cleanup function to be executed in LIFO order
func (*DeferredCleanup) DeferCancel ¶
func (dc *DeferredCleanup) DeferCancel(name string, cancel context.CancelFunc)
DeferCancel adds a context cancel function to cleanup
func (*DeferredCleanup) DeferClose ¶
func (dc *DeferredCleanup) DeferClose(name string, closer interface{})
DeferClose adds a closer to be closed during cleanup
func (*DeferredCleanup) DeferSimple ¶
func (dc *DeferredCleanup) DeferSimple(name string, fn func())
DeferSimple adds a simple cleanup function without error handling
func (*DeferredCleanup) ExecuteAll ¶
func (dc *DeferredCleanup) ExecuteAll()
ExecuteAll executes all deferred cleanup functions in LIFO order
func (*DeferredCleanup) WithTimeout ¶
func (dc *DeferredCleanup) WithTimeout(timeout time.Duration) *DeferredCleanup
WithTimeout sets a custom timeout for cleanup operations
type DeferredCloser ¶
type DeferredCloser[T any] struct { // contains filtered or unexported fields }
DeferredCloser wraps a resource with automatic cleanup
func NewDeferredCloser ¶
func NewDeferredCloser[T any](dc *DeferredCleanup, name string, resource T, closer func(T) error) *DeferredCloser[T]
NewDeferredCloser creates a new deferred closer for a resource
func (*DeferredCloser[T]) Close ¶
func (dc_res *DeferredCloser[T]) Close() error
Close manually closes the resource
func (*DeferredCloser[T]) Get ¶
func (dc_res *DeferredCloser[T]) Get() T
Get returns the wrapped resource
func (*DeferredCloser[T]) IsClosed ¶
func (dc_res *DeferredCloser[T]) IsClosed() bool
IsClosed returns whether the resource has been closed
type EventTestFixture ¶
type EventTestFixture struct { *TestFixture EventChan chan interface{} Context context.Context Cancel context.CancelFunc }
EventTestFixture provides event system testing utilities
func NewEventTestFixture ¶
func NewEventTestFixture(t *testing.T) *EventTestFixture
NewEventTestFixture creates an event test fixture
func (*EventTestFixture) SendEvent ¶
func (etf *EventTestFixture) SendEvent(event interface{})
SendEvent sends an event through the fixture
func (*EventTestFixture) WaitForEvent ¶
func (etf *EventTestFixture) WaitForEvent(timeout time.Duration) (interface{}, error)
WaitForEvent waits for an event with timeout
type FileSystemTestFixture ¶
type FileSystemTestFixture struct { *TestFixture TempDir string TempFiles []string }
FileSystemTestFixture provides file system testing utilities
func NewFileSystemTestFixture ¶
func NewFileSystemTestFixture(t *testing.T) *FileSystemTestFixture
NewFileSystemTestFixture creates a file system test fixture
func (*FileSystemTestFixture) CreateTempFile ¶
func (fsf *FileSystemTestFixture) CreateTempFile(name, content string) (string, error)
CreateTempFile creates a temporary file in the fixture's temp directory
type FixtureManager ¶
type FixtureManager struct {
// contains filtered or unexported fields
}
FixtureManager manages multiple test fixtures
func NewFixtureManager ¶
func NewFixtureManager(t *testing.T) *FixtureManager
NewFixtureManager creates a new fixture manager
func (*FixtureManager) GetFixture ¶
func (fm *FixtureManager) GetFixture(name string) *TestFixture
GetFixture returns a fixture by name
func (*FixtureManager) RegisterFixture ¶
func (fm *FixtureManager) RegisterFixture(name string, setup, teardown func() error) *TestFixture
RegisterFixture registers a new test fixture
func (*FixtureManager) SetupAll ¶
func (fm *FixtureManager) SetupAll() error
SetupAll sets up all registered fixtures
type GoroutineLeakDetector ¶
type GoroutineLeakDetector struct {
// contains filtered or unexported fields
}
GoroutineLeakDetector helps detect goroutine leaks in tests
func NewGoroutineLeakDetector ¶
func NewGoroutineLeakDetector(t *testing.T) *GoroutineLeakDetector
NewGoroutineLeakDetector creates a new leak detector
func (*GoroutineLeakDetector) Check ¶
func (d *GoroutineLeakDetector) Check()
Check verifies no goroutine leaks occurred
func (*GoroutineLeakDetector) Start ¶
func (d *GoroutineLeakDetector) Start()
Start captures the initial goroutine state
func (*GoroutineLeakDetector) WithCheckDelay ¶
func (d *GoroutineLeakDetector) WithCheckDelay(delay time.Duration) *GoroutineLeakDetector
WithCheckDelay sets the delay before checking for leaks (to allow cleanup)
func (*GoroutineLeakDetector) WithThreshold ¶
func (d *GoroutineLeakDetector) WithThreshold(threshold int) *GoroutineLeakDetector
WithThreshold sets the allowed goroutine increase threshold
type HTTPTestFixture ¶
type HTTPTestFixture struct { *TestFixture Server *MockHTTPServer Client *http.Client URL string }
HTTPTestFixture provides a complete HTTP testing setup
func NewHTTPTestFixture ¶
func NewHTTPTestFixture(t *testing.T) *HTTPTestFixture
NewHTTPTestFixture creates an HTTP test fixture
func (*HTTPTestFixture) SetupJSONEndpoint ¶
func (htf *HTTPTestFixture) SetupJSONEndpoint(method, path string, statusCode int, data interface{}) error
SetupJSONEndpoint sets up a JSON endpoint on the HTTP server
func (*HTTPTestFixture) SetupTextEndpoint ¶
func (htf *HTTPTestFixture) SetupTextEndpoint(method, path string, statusCode int, text string)
SetupTextEndpoint sets up a text endpoint on the HTTP server
type HTTPTestSuite ¶
type HTTPTestSuite struct {
// contains filtered or unexported fields
}
HTTPTestSuite provides a complete HTTP testing setup
func NewHTTPTestSuite ¶
func NewHTTPTestSuite(t *testing.T) *HTTPTestSuite
NewHTTPTestSuite creates a new HTTP test suite
func (*HTTPTestSuite) CreateClient ¶
CreateClient creates a named HTTP client with custom configuration
func (*HTTPTestSuite) CreateHTTPSServer ¶
func (suite *HTTPTestSuite) CreateHTTPSServer(name string) *MockHTTPServer
CreateHTTPSServer creates a named HTTPS server
func (*HTTPTestSuite) CreateServer ¶
func (suite *HTTPTestSuite) CreateServer(name string) *MockHTTPServer
CreateServer creates a named HTTP server
func (*HTTPTestSuite) GetClient ¶
func (suite *HTTPTestSuite) GetClient(name string) *http.Client
GetClient returns a named client
func (*HTTPTestSuite) GetServer ¶
func (suite *HTTPTestSuite) GetServer(name string) *MockHTTPServer
GetServer returns a named server
func (*HTTPTestSuite) WithTimeouts ¶
func (suite *HTTPTestSuite) WithTimeouts(timeouts *TimeoutConfig) *HTTPTestSuite
WithTimeouts sets custom timeouts for the test suite
type MockDialer ¶
type MockDialer struct {
// contains filtered or unexported fields
}
MockDialer provides a mock dialer for testing
func NewMockDialer ¶
func NewMockDialer(t *testing.T) *MockDialer
NewMockDialer creates a new mock dialer
func (*MockDialer) Dial ¶
func (m *MockDialer) Dial(network, address string) (net.Conn, error)
Dial dials a mock connection
func (*MockDialer) DialContext ¶
DialContext dials a mock connection with context
func (*MockDialer) GetConnection ¶
func (m *MockDialer) GetConnection(network, address string) net.Conn
GetConnection returns a connection for a specific address
func (*MockDialer) SetDialDelay ¶
func (m *MockDialer) SetDialDelay(delay time.Duration)
SetDialDelay sets a delay for dial operations
func (*MockDialer) SetDialError ¶
func (m *MockDialer) SetDialError(err error)
SetDialError sets an error to be returned by dial operations
func (*MockDialer) SetDialHandler ¶
func (m *MockDialer) SetDialHandler(handler func(network, address string) (net.Conn, error))
SetDialHandler sets a custom dial handler
type MockHTTPRequest ¶
type MockHTTPRequest struct { Method string URL string Headers http.Header Body []byte Timestamp time.Time }
MockHTTPRequest represents a captured HTTP request
type MockHTTPResponse ¶
type MockHTTPResponse struct { StatusCode int Headers http.Header Body []byte Delay time.Duration Error error }
MockHTTPResponse represents a configured HTTP response
type MockHTTPServer ¶
type MockHTTPServer struct {
// contains filtered or unexported fields
}
MockHTTPServer provides a mock HTTP server for testing
func NewMockHTTPSServer ¶
func NewMockHTTPSServer(t *testing.T) *MockHTTPServer
NewMockHTTPSServer creates a new mock HTTPS server
func NewMockHTTPServer ¶
func NewMockHTTPServer(t *testing.T) *MockHTTPServer
NewMockHTTPServer creates a new mock HTTP server
func (*MockHTTPServer) AddMiddleware ¶
func (m *MockHTTPServer) AddMiddleware(middleware func(http.HandlerFunc) http.HandlerFunc)
AddMiddleware adds middleware to the server
func (*MockHTTPServer) ClearRequests ¶
func (m *MockHTTPServer) ClearRequests()
ClearRequests clears the request log
func (*MockHTTPServer) GetClient ¶
func (m *MockHTTPServer) GetClient() *http.Client
GetClient returns an HTTP client configured for this server
func (*MockHTTPServer) GetLastRequest ¶
func (m *MockHTTPServer) GetLastRequest() *MockHTTPRequest
GetLastRequest returns the most recent request
func (*MockHTTPServer) GetRequestCount ¶
func (m *MockHTTPServer) GetRequestCount() int
GetRequestCount returns the number of requests received
func (*MockHTTPServer) GetRequests ¶
func (m *MockHTTPServer) GetRequests() []MockHTTPRequest
GetRequests returns all captured requests
func (*MockHTTPServer) GetURL ¶
func (m *MockHTTPServer) GetURL() string
GetURL returns the server URL
func (*MockHTTPServer) SetDefaultDelay ¶
func (m *MockHTTPServer) SetDefaultDelay(delay time.Duration)
SetDefaultDelay sets a default delay for all responses
func (*MockHTTPServer) SetErrorResponse ¶
func (m *MockHTTPServer) SetErrorResponse(method, path string, err error)
SetErrorResponse configures an error response for a specific endpoint
func (*MockHTTPServer) SetJSONResponse ¶
func (m *MockHTTPServer) SetJSONResponse(method, path string, statusCode int, data interface{}) error
SetJSONResponse configures a JSON response for a specific endpoint
func (*MockHTTPServer) SetRequestHandler ¶
func (m *MockHTTPServer) SetRequestHandler(handler func(*http.Request))
SetRequestHandler sets a handler to be called for each request
func (*MockHTTPServer) SetResponse ¶
func (m *MockHTTPServer) SetResponse(method, path string, response MockHTTPResponse)
SetResponse configures a response for a specific endpoint
func (*MockHTTPServer) SetTextResponse ¶
func (m *MockHTTPServer) SetTextResponse(method, path string, statusCode int, text string)
SetTextResponse configures a text response for a specific endpoint
func (*MockHTTPServer) WaitForRequests ¶
func (m *MockHTTPServer) WaitForRequests(count int, timeout time.Duration) bool
WaitForRequests waits for a specific number of requests with timeout
type MockListener ¶
type MockListener struct {
// contains filtered or unexported fields
}
MockListener provides a mock network listener for testing
func NewMockListener ¶
func NewMockListener(t *testing.T, addr net.Addr) *MockListener
NewMockListener creates a new mock listener
func (*MockListener) Accept ¶
func (m *MockListener) Accept() (net.Conn, error)
Accept implements the net.Listener interface
func (*MockListener) AddConnection ¶
func (m *MockListener) AddConnection(conn net.Conn)
AddConnection adds a connection to the accept queue
func (*MockListener) Addr ¶
func (m *MockListener) Addr() net.Addr
Addr implements the net.Listener interface
func (*MockListener) Close ¶
func (m *MockListener) Close() error
Close implements the net.Listener interface
func (*MockListener) GetConnectionCount ¶
func (m *MockListener) GetConnectionCount() int64
GetConnectionCount returns the number of accepted connections
func (*MockListener) SetAcceptDelay ¶
func (m *MockListener) SetAcceptDelay(delay time.Duration)
SetAcceptDelay sets a delay for Accept operations
func (*MockListener) SetAcceptError ¶
func (m *MockListener) SetAcceptError(err error)
SetAcceptError sets an error to be returned by Accept
type MockMessage ¶
MockMessage represents a message in the mock WebSocket
type MockNetworkConnection ¶
type MockNetworkConnection struct {
// contains filtered or unexported fields
}
MockNetworkConnection provides a mock network connection for testing
func NewMockNetworkConnection ¶
func NewMockNetworkConnection(t *testing.T, localAddr, remoteAddr net.Addr) *MockNetworkConnection
NewMockNetworkConnection creates a new mock network connection
func (*MockNetworkConnection) AddReadData ¶
func (m *MockNetworkConnection) AddReadData(data []byte)
AddReadData adds data to be returned by Read calls
func (*MockNetworkConnection) Close ¶
func (m *MockNetworkConnection) Close() error
Close implements the net.Conn interface
func (*MockNetworkConnection) GetStats ¶
func (m *MockNetworkConnection) GetStats() (bytesRead, bytesWritten int64)
GetStats returns connection statistics
func (*MockNetworkConnection) GetWrittenData ¶
func (m *MockNetworkConnection) GetWrittenData() []byte
GetWrittenData returns all data written to the connection
func (*MockNetworkConnection) IsClosed ¶
func (m *MockNetworkConnection) IsClosed() bool
IsClosed returns whether the connection is closed
func (*MockNetworkConnection) LocalAddr ¶
func (m *MockNetworkConnection) LocalAddr() net.Addr
LocalAddr implements the net.Conn interface
func (*MockNetworkConnection) Read ¶
func (m *MockNetworkConnection) Read(b []byte) (int, error)
Read implements the net.Conn interface
func (*MockNetworkConnection) RemoteAddr ¶
func (m *MockNetworkConnection) RemoteAddr() net.Addr
RemoteAddr implements the net.Conn interface
func (*MockNetworkConnection) SetBlockingBehavior ¶
func (m *MockNetworkConnection) SetBlockingBehavior(readBlock, writeBlock time.Duration)
SetBlockingBehavior sets how long Read/Write operations should block
func (*MockNetworkConnection) SetCloseHandler ¶
func (m *MockNetworkConnection) SetCloseHandler(handler func() error)
SetCloseHandler sets a custom close handler
func (*MockNetworkConnection) SetDeadline ¶
func (m *MockNetworkConnection) SetDeadline(t time.Time) error
SetDeadline implements the net.Conn interface
func (*MockNetworkConnection) SetReadDeadline ¶
func (m *MockNetworkConnection) SetReadDeadline(t time.Time) error
SetReadDeadline implements the net.Conn interface
func (*MockNetworkConnection) SetReadHandler ¶
func (m *MockNetworkConnection) SetReadHandler(handler func([]byte) (int, error))
SetReadHandler sets a custom read handler
func (*MockNetworkConnection) SetWriteDeadline ¶
func (m *MockNetworkConnection) SetWriteDeadline(t time.Time) error
SetWriteDeadline implements the net.Conn interface
func (*MockNetworkConnection) SetWriteHandler ¶
func (m *MockNetworkConnection) SetWriteHandler(handler func([]byte) (int, error))
SetWriteHandler sets a custom write handler
func (*MockNetworkConnection) SimulateError ¶
func (m *MockNetworkConnection) SimulateError(err error)
SimulateError sets an error to be returned by Read/Write operations
type MockPacketConn ¶
type MockPacketConn struct {
// contains filtered or unexported fields
}
MockPacketConn provides a mock packet connection for UDP testing
func NewMockPacketConn ¶
func NewMockPacketConn(t *testing.T, localAddr net.Addr) *MockPacketConn
NewMockPacketConn creates a new mock packet connection
func (*MockPacketConn) AddPacket ¶
func (m *MockPacketConn) AddPacket(data []byte, addr net.Addr)
AddPacket adds a packet to be returned by ReadFrom
func (*MockPacketConn) Close ¶
func (m *MockPacketConn) Close() error
Close implements the net.PacketConn interface
func (*MockPacketConn) LocalAddr ¶
func (m *MockPacketConn) LocalAddr() net.Addr
LocalAddr implements the net.PacketConn interface
func (*MockPacketConn) SetDeadline ¶
func (m *MockPacketConn) SetDeadline(t time.Time) error
SetDeadline implements the net.PacketConn interface
func (*MockPacketConn) SetReadDeadline ¶
func (m *MockPacketConn) SetReadDeadline(t time.Time) error
SetReadDeadline implements the net.PacketConn interface
func (*MockPacketConn) SetWriteDeadline ¶
func (m *MockPacketConn) SetWriteDeadline(t time.Time) error
SetWriteDeadline implements the net.PacketConn interface
type MockRoundTripper ¶
type MockRoundTripper struct {
// contains filtered or unexported fields
}
MockRoundTripper provides a mock HTTP transport for testing without a server
func NewMockRoundTripper ¶
func NewMockRoundTripper(t *testing.T) *MockRoundTripper
NewMockRoundTripper creates a new mock round tripper
func (*MockRoundTripper) GetRequests ¶
func (m *MockRoundTripper) GetRequests() []*http.Request
GetRequests returns all captured requests
func (*MockRoundTripper) SetRequestHandler ¶
func (m *MockRoundTripper) SetRequestHandler(handler func(*http.Request))
SetRequestHandler sets a handler to be called for each request
func (*MockRoundTripper) SetResponse ¶
func (m *MockRoundTripper) SetResponse(method, url string, resp *http.Response)
SetResponse sets a response for a specific request
type MockWebSocketConn ¶
type MockWebSocketConn struct {
// contains filtered or unexported fields
}
MockWebSocketConn provides a mock implementation of a WebSocket connection
func NewMockWebSocketConn ¶
func NewMockWebSocketConn(t *testing.T) *MockWebSocketConn
NewMockWebSocketConn creates a new mock WebSocket connection
func (*MockWebSocketConn) AddMessage ¶
func (m *MockWebSocketConn) AddMessage(messageType int, data []byte)
AddMessage adds a message to be returned by ReadMessage
func (*MockWebSocketConn) Close ¶
func (m *MockWebSocketConn) Close() error
Close implements the websocket.Conn interface
func (*MockWebSocketConn) GetMessageCount ¶
func (m *MockWebSocketConn) GetMessageCount() int
GetMessageCount returns the number of pending messages
func (*MockWebSocketConn) IsClosed ¶
func (m *MockWebSocketConn) IsClosed() bool
IsClosed returns whether the connection is closed
func (*MockWebSocketConn) LocalAddr ¶
func (m *MockWebSocketConn) LocalAddr() net.Addr
LocalAddr implements the websocket.Conn interface
func (*MockWebSocketConn) ReadMessage ¶
func (m *MockWebSocketConn) ReadMessage() (messageType int, p []byte, err error)
ReadMessage implements the websocket.Conn interface
func (*MockWebSocketConn) RemoteAddr ¶
func (m *MockWebSocketConn) RemoteAddr() net.Addr
RemoteAddr implements the websocket.Conn interface
func (*MockWebSocketConn) SetCloseHandler ¶
func (m *MockWebSocketConn) SetCloseHandler(handler func(code int, text string) error)
SetCloseHandler sets a handler for Close calls
func (*MockWebSocketConn) SetPingHandler ¶
func (m *MockWebSocketConn) SetPingHandler(h func(appData string) error)
SetPingHandler implements the websocket.Conn interface
func (*MockWebSocketConn) SetPongHandler ¶
func (m *MockWebSocketConn) SetPongHandler(h func(appData string) error)
SetPongHandler implements the websocket.Conn interface
func (*MockWebSocketConn) SetReadDeadline ¶
func (m *MockWebSocketConn) SetReadDeadline(t time.Time) error
SetReadDeadline implements the websocket.Conn interface
func (*MockWebSocketConn) SetWriteDeadline ¶
func (m *MockWebSocketConn) SetWriteDeadline(t time.Time) error
SetWriteDeadline implements the websocket.Conn interface
func (*MockWebSocketConn) SetWriteHandler ¶
func (m *MockWebSocketConn) SetWriteHandler(handler func(messageType int, data []byte) error)
SetWriteHandler sets a handler for WriteMessage calls
func (*MockWebSocketConn) WriteMessage ¶
func (m *MockWebSocketConn) WriteMessage(messageType int, data []byte) error
WriteMessage implements the websocket.Conn interface
type MockWebSocketDialer ¶
type MockWebSocketDialer struct {
// contains filtered or unexported fields
}
MockWebSocketDialer provides a mock dialer for WebSocket connections
func NewMockWebSocketDialer ¶
func NewMockWebSocketDialer(t *testing.T) *MockWebSocketDialer
NewMockWebSocketDialer creates a new mock WebSocket dialer
func (*MockWebSocketDialer) CloseAll ¶
func (d *MockWebSocketDialer) CloseAll()
CloseAll closes all connections
func (*MockWebSocketDialer) Dial ¶
func (d *MockWebSocketDialer) Dial(urlStr string, requestHeader http.Header) (*MockWebSocketConn, *http.Response, error)
Dial implements a mock WebSocket dialer
func (*MockWebSocketDialer) DialContext ¶
func (d *MockWebSocketDialer) DialContext(ctx context.Context, urlStr string, requestHeader http.Header) (*MockWebSocketConn, *http.Response, error)
DialContext implements a mock WebSocket dialer with context
func (*MockWebSocketDialer) GetAllConnections ¶
func (d *MockWebSocketDialer) GetAllConnections() map[string]*MockWebSocketConn
GetAllConnections returns all active connections
func (*MockWebSocketDialer) GetConnection ¶
func (d *MockWebSocketDialer) GetConnection(urlStr string) *MockWebSocketConn
GetConnection returns a connection for a given URL
func (*MockWebSocketDialer) SetDialDelay ¶
func (d *MockWebSocketDialer) SetDialDelay(delay time.Duration)
SetDialDelay sets a delay for Dial operations
func (*MockWebSocketDialer) SetDialError ¶
func (d *MockWebSocketDialer) SetDialError(err error)
SetDialError sets an error to be returned by Dial
type MockWebSocketServer ¶
type MockWebSocketServer struct {
// contains filtered or unexported fields
}
MockWebSocketServer provides a mock WebSocket server for testing
func NewMockWebSocketServer ¶
func NewMockWebSocketServer(t *testing.T) *MockWebSocketServer
NewMockWebSocketServer creates a new mock WebSocket server
func (*MockWebSocketServer) BroadcastMessage ¶
func (s *MockWebSocketServer) BroadcastMessage(messageType int, data []byte)
BroadcastMessage sends a message to all connected clients
func (*MockWebSocketServer) GetConnectionCount ¶
func (s *MockWebSocketServer) GetConnectionCount() int
GetConnectionCount returns the number of active connections
func (*MockWebSocketServer) GetHTTPURL ¶
func (s *MockWebSocketServer) GetHTTPURL() string
GetHTTPURL returns the HTTP URL for the server
func (*MockWebSocketServer) GetURL ¶
func (s *MockWebSocketServer) GetURL() string
GetURL returns the WebSocket URL for the server
func (*MockWebSocketServer) SetHandlers ¶
func (s *MockWebSocketServer) SetHandlers( onConnect func(*websocket.Conn), onMessage func(*websocket.Conn, int, []byte), onClose func(*websocket.Conn, error), )
SetHandlers sets event handlers for the server
func (*MockWebSocketServer) Start ¶
func (s *MockWebSocketServer) Start() error
Start starts the mock WebSocket server
func (*MockWebSocketServer) Stop ¶
func (s *MockWebSocketServer) Stop() error
Stop stops the mock WebSocket server
type NetworkCleanup ¶
type NetworkCleanup struct {
// contains filtered or unexported fields
}
NetworkCleanup helps clean up network resources
func NewNetworkCleanup ¶
func NewNetworkCleanup(t *testing.T) *NetworkCleanup
NewNetworkCleanup creates a network cleanup helper
func (*NetworkCleanup) AddConnection ¶
func (nc *NetworkCleanup) AddConnection(conn net.Conn)
AddConnection registers a connection for cleanup
func (*NetworkCleanup) AddListener ¶
func (nc *NetworkCleanup) AddListener(l net.Listener)
AddListener registers a listener for cleanup
func (*NetworkCleanup) CleanupAll ¶
func (nc *NetworkCleanup) CleanupAll()
CleanupAll closes all network resources
type NetworkTestSuite ¶
type NetworkTestSuite struct {
// contains filtered or unexported fields
}
NetworkTestSuite provides comprehensive network testing utilities
func NewNetworkTestSuite ¶
func NewNetworkTestSuite(t *testing.T) *NetworkTestSuite
NewNetworkTestSuite creates a new network test suite
func (*NetworkTestSuite) CreateConnection ¶
func (nts *NetworkTestSuite) CreateConnection(name string, localAddr, remoteAddr net.Addr) *MockNetworkConnection
CreateConnection creates a named mock connection
func (*NetworkTestSuite) CreateDialer ¶
func (nts *NetworkTestSuite) CreateDialer(name string) *MockDialer
CreateDialer creates a named mock dialer
func (*NetworkTestSuite) CreateListener ¶
func (nts *NetworkTestSuite) CreateListener(name string, addr net.Addr) *MockListener
CreateListener creates a named mock listener
func (*NetworkTestSuite) GetConnection ¶
func (nts *NetworkTestSuite) GetConnection(name string) *MockNetworkConnection
GetConnection returns a named connection
func (*NetworkTestSuite) GetDialer ¶
func (nts *NetworkTestSuite) GetDialer(name string) *MockDialer
GetDialer returns a named dialer
func (*NetworkTestSuite) GetListener ¶
func (nts *NetworkTestSuite) GetListener(name string) *MockListener
GetListener returns a named listener
func (*NetworkTestSuite) RestoreNetworkConnectivity ¶
func (nts *NetworkTestSuite) RestoreNetworkConnectivity(connNames ...string)
RestoreNetworkConnectivity restores network connectivity for connections
func (*NetworkTestSuite) SimulateNetworkPartition ¶
func (nts *NetworkTestSuite) SimulateNetworkPartition(connNames ...string)
SimulateNetworkPartition simulates a network partition between connections
type ParallelContexts ¶
type ParallelContexts struct {
// contains filtered or unexported fields
}
ParallelContexts helps manage contexts in parallel tests
func NewParallelContexts ¶
func NewParallelContexts(t *testing.T) *ParallelContexts
NewParallelContexts creates a parallel context manager
func (*ParallelContexts) Cancel ¶
func (pc *ParallelContexts) Cancel(name string)
Cancel cancels a specific parallel context
func (*ParallelContexts) CancelAll ¶
func (pc *ParallelContexts) CancelAll()
CancelAll cancels all parallel contexts
type PerformanceTestFixture ¶
type PerformanceTestFixture struct { *TestFixture StartTime time.Time Measurements map[string]time.Duration Counters map[string]int64 }
PerformanceTestFixture provides utilities for performance testing
func NewPerformanceTestFixture ¶
func NewPerformanceTestFixture(t *testing.T) *PerformanceTestFixture
NewPerformanceTestFixture creates a performance test fixture
func (*PerformanceTestFixture) GetCounter ¶
func (ptf *PerformanceTestFixture) GetCounter(name string) int64
GetCounter returns the value of a named counter
func (*PerformanceTestFixture) IncrementCounter ¶
func (ptf *PerformanceTestFixture) IncrementCounter(name string)
IncrementCounter increments a named counter
func (*PerformanceTestFixture) StartMeasurement ¶
func (ptf *PerformanceTestFixture) StartMeasurement(name string) func()
StartMeasurement starts measuring performance for a named operation
type ProcessCleanup ¶
type ProcessCleanup struct {
// contains filtered or unexported fields
}
ProcessCleanup manages cleanup for external processes
func NewProcessCleanup ¶
func NewProcessCleanup(t *testing.T) *ProcessCleanup
NewProcessCleanup creates a process cleanup helper
func (*ProcessCleanup) AddProcess ¶
func (pc *ProcessCleanup) AddProcess(name string, pid int, cmd string)
AddProcess adds a process to be terminated during cleanup
type ProcessInfo ¶
type ResourceCounter ¶
type ResourceCounter struct {
// contains filtered or unexported fields
}
ResourceCounter tracks resource usage
func (*ResourceCounter) Allocate ¶
func (rc *ResourceCounter) Allocate(count int64)
Allocate increments the allocation counter for a resource
func (*ResourceCounter) GetCounts ¶
func (rc *ResourceCounter) GetCounts() (allocated, released int64)
GetCounts returns the current allocation and release counts
func (*ResourceCounter) IsBalanced ¶
func (rc *ResourceCounter) IsBalanced() bool
IsBalanced returns true if allocations equal releases
func (*ResourceCounter) Release ¶
func (rc *ResourceCounter) Release(count int64)
Release increments the release counter for a resource
type ResourceTracker ¶
type ResourceTracker struct {
// contains filtered or unexported fields
}
ResourceTracker tracks resource allocation and cleanup
func NewResourceTracker ¶
func NewResourceTracker(t *testing.T) *ResourceTracker
NewResourceTracker creates a resource tracker
func (*ResourceTracker) Allocated ¶
func (rt *ResourceTracker) Allocated(name string)
Allocated marks a resource as allocated
func (*ResourceTracker) Cleaned ¶
func (rt *ResourceTracker) Cleaned(name string)
Cleaned marks a resource as cleaned
func (*ResourceTracker) Report ¶
func (rt *ResourceTracker) Report()
Report logs resource tracking information
type SSEMockServer ¶
type SSEMockServer struct { *MockHTTPServer // contains filtered or unexported fields }
SSEMockServer provides a mock Server-Sent Events server
func NewSSEMockServer ¶
func NewSSEMockServer(t *testing.T) *SSEMockServer
NewSSEMockServer creates a new SSE mock server
func (*SSEMockServer) SendEvent ¶
func (sse *SSEMockServer) SendEvent(event string)
SendEvent sends an event to all connected clients
type SafeWaitGroup ¶
type SafeWaitGroup struct {
// contains filtered or unexported fields
}
SafeWaitGroup provides a safer WaitGroup with leak detection and debugging
func NewNamedSafeWaitGroup ¶
func NewNamedSafeWaitGroup(t *testing.T, name string) *SafeWaitGroup
NewNamedSafeWaitGroup creates a new named safe wait group
func NewSafeWaitGroup ¶
func NewSafeWaitGroup(t *testing.T) *SafeWaitGroup
NewSafeWaitGroup creates a new safe wait group
func (*SafeWaitGroup) Add ¶
func (swg *SafeWaitGroup) Add(delta int)
Add increments the WaitGroup counter and tracks the goroutine
func (*SafeWaitGroup) GetCount ¶
func (swg *SafeWaitGroup) GetCount() int64
GetCount returns the current counter value
func (*SafeWaitGroup) GetWaitGroup ¶
func (swg *SafeWaitGroup) GetWaitGroup() *sync.WaitGroup
GetWaitGroup returns the underlying sync.WaitGroup (for compatibility)
func (*SafeWaitGroup) SetTimeout ¶
func (swg *SafeWaitGroup) SetTimeout(timeout time.Duration)
SetTimeout sets the default timeout for Wait operations
func (*SafeWaitGroup) Wait ¶
func (swg *SafeWaitGroup) Wait()
Wait waits for all goroutines to complete
func (*SafeWaitGroup) WaitWithTimeout ¶
func (swg *SafeWaitGroup) WaitWithTimeout(timeout time.Duration) bool
WaitWithTimeout waits with a custom timeout
type TestContext ¶
TestContext wraps a context with automatic cancellation
func NewTestContext ¶
func NewTestContext(t *testing.T) *TestContext
NewTestContext creates a context that is automatically cancelled at test end
Example ¶
ExampleNewTestContext shows context usage
// In your test: // func TestSomething(t *testing.T) { // ctx := NewTestContext(t) // // // Use ctx in your operations // // It will be automatically cancelled when test ends // }
func NewTestContextWithTimeout ¶
func NewTestContextWithTimeout(t *testing.T, timeout time.Duration) *TestContext
NewTestContextWithTimeout creates a context with timeout that is automatically cancelled
func (*TestContext) Cancel ¶
func (tc *TestContext) Cancel()
Cancel cancels the context (safe to call multiple times)
func (*TestContext) Deadline ¶
func (tc *TestContext) Deadline() (time.Time, bool)
Deadline returns the context deadline if set
func (*TestContext) Done ¶
func (tc *TestContext) Done() <-chan struct{}
Done returns the context's done channel
func (*TestContext) Value ¶
func (tc *TestContext) Value(key interface{}) interface{}
Value returns the value associated with key
type TestFixture ¶
type TestFixture struct {
// contains filtered or unexported fields
}
TestFixture represents a reusable test setup
func QuickFixture ¶
func QuickFixture(t *testing.T, name string, setup func() error, teardown func() error) *TestFixture
QuickFixture provides a simple way to create inline fixtures
func (*TestFixture) GetData ¶
func (tf *TestFixture) GetData(key string) interface{}
GetData retrieves data from the fixture
func (*TestFixture) GetInt ¶
func (tf *TestFixture) GetInt(key string) int
GetInt retrieves integer data from the fixture
func (*TestFixture) GetString ¶
func (tf *TestFixture) GetString(key string) string
GetString retrieves string data from the fixture
func (*TestFixture) SetData ¶
func (tf *TestFixture) SetData(key string, value interface{})
SetData stores data in the fixture
func (*TestFixture) Teardown ¶
func (tf *TestFixture) Teardown() error
Teardown tears down the fixture
type TimeoutConfig ¶
type TimeoutConfig struct { // Short timeout for quick operations (default: 5s) Short time.Duration // Medium timeout for moderate operations (default: 10s) Medium time.Duration // Long timeout for extended operations (default: 30s, only for exceptional cases) Long time.Duration // Context timeout for context-based operations (default: 8s) Context time.Duration // Network timeout for network operations (default: 6s) Network time.Duration // Cleanup timeout for resource cleanup (default: 3s) Cleanup time.Duration }
TimeoutConfig provides configurable timeout values for tests
func DefaultTimeouts ¶
func DefaultTimeouts() *TimeoutConfig
DefaultTimeouts returns the default timeout configuration
func FastTimeouts ¶
func FastTimeouts() *TimeoutConfig
FastTimeouts returns a configuration optimized for speed (shorter timeouts)
func GetCITimeouts ¶
func GetCITimeouts() *TimeoutConfig
GetCITimeouts returns timeouts appropriate for CI environments
func NewCustomTimeouts ¶
func NewCustomTimeouts(options ...TimeoutOption) *TimeoutConfig
NewCustomTimeouts creates a TimeoutConfig with custom options
func NewTimeoutConfig ¶
func NewTimeoutConfig() *TimeoutConfig
NewTimeoutConfig creates a timeout configuration with environment variable overrides
func SlowTimeouts ¶
func SlowTimeouts() *TimeoutConfig
SlowTimeouts returns a configuration for slower environments (longer timeouts)
func (*TimeoutConfig) GetTimeout ¶
func (tc *TimeoutConfig) GetTimeout(operation string) time.Duration
GetTimeout returns appropriate timeout based on the operation type
func (*TimeoutConfig) WithScale ¶
func (tc *TimeoutConfig) WithScale(scale float64) *TimeoutConfig
WithScale returns a new TimeoutConfig scaled by the given factor
type TimeoutGuard ¶
type TimeoutGuard struct {
// contains filtered or unexported fields
}
TimeoutGuard provides timeout protection for operations
func NewTimeoutGuard ¶
func NewTimeoutGuard(t *testing.T, timeout time.Duration) *TimeoutGuard
NewTimeoutGuard creates a timeout guard
func (*TimeoutGuard) Run ¶
func (tg *TimeoutGuard) Run(name string, fn func() error) error
Run executes a function with timeout protection
func (*TimeoutGuard) RunWithContext ¶
RunWithContext executes a function with timeout protection and context cancellation
type TimeoutOption ¶
type TimeoutOption func(*TimeoutConfig)
TimeoutOption represents a function for configuring timeouts
func WithCleanupTimeout ¶
func WithCleanupTimeout(d time.Duration) TimeoutOption
WithCleanupTimeout sets the cleanup timeout
func WithMediumTimeout ¶
func WithMediumTimeout(d time.Duration) TimeoutOption
WithMediumTimeout sets the medium timeout
func WithNetworkTimeout ¶
func WithNetworkTimeout(d time.Duration) TimeoutOption
WithNetworkTimeout sets the network timeout
func WithShortTimeout ¶
func WithShortTimeout(d time.Duration) TimeoutOption
WithShortTimeout sets the short timeout
type WaitGroupPool ¶
type WaitGroupPool struct {
// contains filtered or unexported fields
}
WaitGroupPool manages a pool of SafeWaitGroups
func NewWaitGroupPool ¶
func NewWaitGroupPool(t *testing.T) *WaitGroupPool
NewWaitGroupPool creates a new wait group pool
func (*WaitGroupPool) Get ¶
func (wgp *WaitGroupPool) Get(name string) *SafeWaitGroup
Get gets or creates a named wait group
func (*WaitGroupPool) GetActiveCount ¶
func (wgp *WaitGroupPool) GetActiveCount() int
GetActiveCount returns the number of active wait groups
func (*WaitGroupPool) Remove ¶
func (wgp *WaitGroupPool) Remove(name string)
Remove removes a wait group from the pool
func (*WaitGroupPool) Reset ¶
func (wgp *WaitGroupPool) Reset()
Reset clears all wait groups from the pool
func (*WaitGroupPool) WaitAll ¶
func (wgp *WaitGroupPool) WaitAll()
WaitAll waits for all wait groups in the pool
func (*WaitGroupPool) WaitAllWithTimeout ¶
func (wgp *WaitGroupPool) WaitAllWithTimeout(timeout time.Duration) bool
WaitAllWithTimeout waits for all wait groups with a timeout
type WebSocketTestFixture ¶
type WebSocketTestFixture struct { *TestFixture Server *MockWebSocketServer Suite *WebSocketTestSuite URL string }
WebSocketTestFixture provides a complete WebSocket testing setup
func NewWebSocketTestFixture ¶
func NewWebSocketTestFixture(t *testing.T) *WebSocketTestFixture
NewWebSocketTestFixture creates a WebSocket test fixture
type WebSocketTestSuite ¶
type WebSocketTestSuite struct {
// contains filtered or unexported fields
}
WebSocketTestSuite provides a complete test setup for WebSocket testing
func NewWebSocketTestSuite ¶
func NewWebSocketTestSuite(t *testing.T) *WebSocketTestSuite
NewWebSocketTestSuite creates a new WebSocket test suite
func (*WebSocketTestSuite) GetDialer ¶
func (suite *WebSocketTestSuite) GetDialer() *MockWebSocketDialer
GetDialer returns the mock dialer
func (*WebSocketTestSuite) GetServer ¶
func (suite *WebSocketTestSuite) GetServer() *MockWebSocketServer
GetServer returns the mock server
func (*WebSocketTestSuite) GetServerURL ¶
func (suite *WebSocketTestSuite) GetServerURL() string
GetServerURL returns the WebSocket server URL
func (*WebSocketTestSuite) Setup ¶
func (suite *WebSocketTestSuite) Setup() error
Setup initializes the test suite
func (*WebSocketTestSuite) WithTimeouts ¶
func (suite *WebSocketTestSuite) WithTimeouts(timeouts *TimeoutConfig) *WebSocketTestSuite
WithTimeouts sets custom timeouts for the test suite