testing

package
v0.20.0 Latest Latest
Warning

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

Go to latest
Published: Dec 18, 2025 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package testing provides utilities for testing cache logic in go-bricks applications. This package follows the design patterns from database/testing and observability/testing, providing fluent APIs and in-memory mocks that eliminate the complexity of setting up real Redis instances for unit tests.

The primary type is MockCache, which implements cache.Cache with configurable behavior for testing various scenarios including failures, delays, and operation tracking.

Basic Usage

MockCache can be used directly in tests without any setup:

mock := testing.NewMockCache()
mock.Set(ctx, "key", []byte("value"), time.Minute)
data, err := mock.Get(ctx, "key")

Configurable Behavior

Chain configuration methods to simulate failures or delays:

mock := testing.NewMockCache().
    WithGetFailure(cache.ErrConnectionError).
    WithDelay(100 * time.Millisecond)

Operation Tracking

Track and assert on cache operations:

mock := testing.NewMockCache()
// ... perform operations ...
AssertOperationCount(t, mock, "Get", 5)
AssertCacheHit(t, mock, "user:123")
AssertCacheMiss(t, mock, "missing:key")

Multi-Tenant Testing

Use multiple mock instances to test tenant isolation:

tenantCaches := map[string]*testing.MockCache{
    "acme":   testing.NewMockCache(),
    "globex": testing.NewMockCache(),
}

deps := &app.ModuleDeps{
    GetCache: func(ctx context.Context) (cache.Cache, error) {
        tenantID := multitenant.GetTenant(ctx)
        return tenantCaches[tenantID], nil
    },
}

For integration tests requiring actual Redis behavior, use testcontainers with cache/redis package instead.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AssertCacheClosed

func AssertCacheClosed(t *testing.T, mock *MockCache)

AssertCacheClosed asserts that the cache has been closed. Only works with MockCache instances.

Example:

mock := NewMockCache()
mock.Close()
AssertCacheClosed(t, mock)

func AssertCacheEmpty

func AssertCacheEmpty(t *testing.T, mock *MockCache)

AssertCacheEmpty asserts that the cache contains no entries. Only works with MockCache instances.

Example:

mock := NewMockCache()
mock.Clear()
AssertCacheEmpty(t, mock)

func AssertCacheHit

func AssertCacheHit(t *testing.T, c cache.Cache, key string)

AssertCacheHit asserts that a key exists in the cache and can be retrieved successfully.

Example:

mock := NewMockCache()
mock.Set(ctx, "user:123", []byte("data"), time.Minute)
AssertCacheHit(t, mock, "user:123")

func AssertCacheMiss

func AssertCacheMiss(t *testing.T, c cache.Cache, key string)

AssertCacheMiss asserts that a key does not exist in the cache.

Example:

mock := NewMockCache()
AssertCacheMiss(t, mock, "missing:key")

func AssertCacheOpen

func AssertCacheOpen(t *testing.T, mock *MockCache)

AssertCacheOpen asserts that the cache has NOT been closed. Only works with MockCache instances.

Example:

mock := NewMockCache()
AssertCacheOpen(t, mock)

func AssertCacheSize

func AssertCacheSize(t *testing.T, mock *MockCache, expected int)

AssertCacheSize asserts that the cache contains a specific number of entries. Only works with MockCache instances.

Example:

mock := NewMockCache()
mock.Set(ctx, "key1", []byte("value1"), time.Minute)
mock.Set(ctx, "key2", []byte("value2"), time.Minute)
AssertCacheSize(t, mock, 2)

func AssertError

func AssertError(t *testing.T, operation func() error, expected error)

AssertError asserts that a cache operation returns a specific error.

Example:

mock := NewMockCache().WithGetFailure(cache.ErrConnectionError)
AssertError(t, func() error {
    _, err := mock.Get(context.Background(), "key")
    return err
}, cache.ErrConnectionError)

func AssertGetValue

func AssertGetValue(t *testing.T, c cache.Cache, key string) []byte

AssertGetValue is a convenience function that combines Get and value assertion.

Example:

mock := NewMockCache()
mock.Set(ctx, "key", []byte("value"), time.Minute)
value := AssertGetValue(t, mock, "key")
// Use value for further assertions...

func AssertKeyExists

func AssertKeyExists(t *testing.T, mock *MockCache, key string)

AssertKeyExists asserts that a key exists in the cache storage (ignoring expiration). Only works with MockCache instances.

Example:

mock := NewMockCache()
mock.Set(ctx, "key", []byte("value"), time.Nanosecond)
time.Sleep(time.Millisecond)
AssertKeyExists(t, mock, "key") // Still exists even if expired

func AssertKeyNotExists

func AssertKeyNotExists(t *testing.T, mock *MockCache, key string)

AssertKeyNotExists asserts that a key does not exist in cache storage. Only works with MockCache instances.

Example:

mock := NewMockCache()
AssertKeyNotExists(t, mock, "missing:key")

func AssertNoError

func AssertNoError(t *testing.T, operation func() error)

AssertNoError asserts that a cache operation succeeds without error.

Example:

mock := NewMockCache()
AssertNoError(t, func() error {
    return mock.Set(context.Background(), "key", []byte("value"), time.Minute)
})

func AssertNoOperations

func AssertNoOperations(t *testing.T, mock *MockCache)

AssertNoOperations asserts that no cache operations were performed. Only works with MockCache instances.

Example:

mock := NewMockCache()
// ... test code that should NOT use cache ...
AssertNoOperations(t, mock)

func AssertOperationCount

func AssertOperationCount(t *testing.T, mock *MockCache, operation string, expected int64)

AssertOperationCount asserts that a specific operation was called a certain number of times. Only works with MockCache instances.

Supported operations: "Get", "Set", "Delete", "GetOrSet", "CompareAndSet", "Health", "Stats", "Close"

Example:

mock := NewMockCache()
// ... perform operations ...
AssertOperationCount(t, mock, "Get", 5)

func AssertOperationCountAtLeast

func AssertOperationCountAtLeast(t *testing.T, mock *MockCache, operation string, minimum int64)

AssertOperationCountAtLeast asserts that a specific operation was called at least a certain number of times. Only works with MockCache instances.

Example:

mock := NewMockCache()
// ... perform operations ...
AssertOperationCountAtLeast(t, mock, "Get", 10)

func AssertOperationCountGreaterThan deprecated

func AssertOperationCountGreaterThan(t *testing.T, mock *MockCache, operation string, minimum int64)

Deprecated: Use AssertOperationCountAtLeast instead. AssertOperationCountGreaterThan is kept for backward compatibility.

func AssertStatsContains

func AssertStatsContains(t *testing.T, stats map[string]any, key string, expected any)

AssertStats asserts that cache stats contain expected key-value pairs. Only works with MockCache instances.

Example:

mock := NewMockCacheWithID("test-cache")
stats, _ := mock.Stats()
AssertStatsContains(t, stats, "id", "test-cache")

func AssertValue

func AssertValue(t *testing.T, c cache.Cache, key string, expected []byte)

AssertValue asserts that a cache key contains a specific value.

Example:

mock := NewMockCache()
mock.Set(ctx, "user:123", []byte("Alice"), time.Minute)
AssertValue(t, mock, "user:123", []byte("Alice"))

func DumpCache

func DumpCache(mock *MockCache) string

DumpCache returns a formatted string of cache contents for debugging. Only works with MockCache instances.

Example:

mock := NewMockCache()
// ... test operations ...
t.Log(DumpCache(mock))  // Print cache state

func OperationCounts added in v0.19.0

func OperationCounts(mock *MockCache) map[string]int64

OperationCounts returns a map of all operation counts for debugging. Only works with MockCache instances.

Example:

mock := NewMockCache()
// ... test operations ...
counts := OperationCounts(mock)
fmt.Printf("Operations: %+v\n", counts)

func ResetMock

func ResetMock(mock *MockCache)

ResetMock resets a MockCache to initial state (clears data and counters). Only works with MockCache instances.

Example:

mock := NewMockCache()
// ... test operations ...
ResetMock(mock)  // Clean slate for next test

Types

type MockCache

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

MockCache is an in-memory cache implementation for testing. It implements cache.Cache with configurable behavior for simulating failures and delays.

MockCache is thread-safe and tracks all operations for assertion purposes.

Example usage:

mock := NewMockCache()
mock.Set(ctx, "key", []byte("value"), time.Minute)
data, err := mock.Get(ctx, "key")

func NewMockCache

func NewMockCache() *MockCache

NewMockCache creates a new MockCache with default behavior.

func NewMockCacheWithID

func NewMockCacheWithID(id string) *MockCache

NewMockCacheWithID creates a new MockCache with a specific ID. Useful for multi-tenant testing or tracking multiple cache instances.

func (*MockCache) AllKeys added in v0.19.0

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

AllKeys returns all keys currently stored (including expired). Useful for debugging test failures.

func (*MockCache) Clear

func (m *MockCache) Clear()

Clear removes all entries from the cache. Useful for resetting state between test cases.

func (*MockCache) Close

func (m *MockCache) Close() error

Close closes the cache.

func (*MockCache) CompareAndSet

func (m *MockCache) CompareAndSet(ctx context.Context, key string, expectedValue, newValue []byte, ttl time.Duration) (bool, error)

CompareAndSet atomically compares and sets a value.

func (*MockCache) Delete

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

Delete removes a value from the cache.

func (*MockCache) Dump

func (m *MockCache) Dump() string

Dump returns a string representation of cache contents for debugging.

func (*MockCache) Get

func (m *MockCache) Get(ctx context.Context, key string) ([]byte, error)

Get retrieves a value from the cache.

func (*MockCache) GetOrSet

func (m *MockCache) GetOrSet(ctx context.Context, key string, value []byte, ttl time.Duration) (storedValue []byte, wasSet bool, err error)

GetOrSet atomically gets a value or sets it if not present.

func (*MockCache) Has

func (m *MockCache) Has(key string) bool

Has returns whether a key exists in the cache (ignoring expiration).

func (*MockCache) Health

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

Health checks cache health.

func (*MockCache) ID added in v0.19.0

func (m *MockCache) ID() string

ID returns the mock cache ID.

func (*MockCache) IsClosed

func (m *MockCache) IsClosed() bool

IsClosed returns whether the cache has been closed.

func (*MockCache) OperationCount added in v0.19.0

func (m *MockCache) OperationCount(operation string) int64

OperationCount returns the number of times a specific operation was called. Supported operations: "Get", "Set", "Delete", "GetOrSet", "CompareAndSet", "Health", "Stats", "Close"

func (*MockCache) ResetCounters

func (m *MockCache) ResetCounters()

ResetCounters resets all operation counters to zero. Useful for testing specific code paths without previous noise.

func (*MockCache) Set

func (m *MockCache) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error

Set stores a value in the cache with TTL.

func (*MockCache) Stats

func (m *MockCache) Stats() (map[string]any, error)

Stats returns mock cache statistics.

func (*MockCache) WithCloseCallback

func (m *MockCache) WithCloseCallback(callback func(string)) *MockCache

WithCloseCallback registers a callback that gets called when Close() succeeds. Useful for tracking cache lifecycle in tests.

func (*MockCache) WithCloseFailure

func (m *MockCache) WithCloseFailure(err error) *MockCache

WithCloseFailure configures Close operations to return an error.

func (*MockCache) WithCompareAndSetFailure

func (m *MockCache) WithCompareAndSetFailure(err error) *MockCache

WithCompareAndSetFailure configures CompareAndSet operations to return an error.

func (*MockCache) WithDelay

func (m *MockCache) WithDelay(delay time.Duration) *MockCache

WithDelay configures a delay for all operations. Useful for testing timeout behavior.

func (*MockCache) WithDeleteFailure

func (m *MockCache) WithDeleteFailure(err error) *MockCache

WithDeleteFailure configures Delete operations to return an error.

func (*MockCache) WithGetFailure

func (m *MockCache) WithGetFailure(err error) *MockCache

WithGetFailure configures Get operations to return an error.

func (*MockCache) WithGetOrSetFailure

func (m *MockCache) WithGetOrSetFailure(err error) *MockCache

WithGetOrSetFailure configures GetOrSet operations to return an error.

func (*MockCache) WithHealthFailure

func (m *MockCache) WithHealthFailure(err error) *MockCache

WithHealthFailure configures Health operations to return an error.

func (*MockCache) WithSetFailure

func (m *MockCache) WithSetFailure(err error) *MockCache

WithSetFailure configures Set operations to return an error.

func (*MockCache) WithStatsFailure

func (m *MockCache) WithStatsFailure(err error) *MockCache

WithStatsFailure configures Stats operations to return an error.

Jump to

Keyboard shortcuts

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