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 ¶
- func AssertCacheClosed(t *testing.T, mock *MockCache)
- func AssertCacheEmpty(t *testing.T, mock *MockCache)
- func AssertCacheHit(t *testing.T, c cache.Cache, key string)
- func AssertCacheMiss(t *testing.T, c cache.Cache, key string)
- func AssertCacheOpen(t *testing.T, mock *MockCache)
- func AssertCacheSize(t *testing.T, mock *MockCache, expected int)
- func AssertError(t *testing.T, operation func() error, expected error)
- func AssertGetValue(t *testing.T, c cache.Cache, key string) []byte
- func AssertKeyExists(t *testing.T, mock *MockCache, key string)
- func AssertKeyNotExists(t *testing.T, mock *MockCache, key string)
- func AssertNoError(t *testing.T, operation func() error)
- func AssertNoOperations(t *testing.T, mock *MockCache)
- func AssertOperationCount(t *testing.T, mock *MockCache, operation string, expected int64)
- func AssertOperationCountAtLeast(t *testing.T, mock *MockCache, operation string, minimum int64)
- func AssertOperationCountGreaterThan(t *testing.T, mock *MockCache, operation string, minimum int64)deprecated
- func AssertStatsContains(t *testing.T, stats map[string]any, key string, expected any)
- func AssertValue(t *testing.T, c cache.Cache, key string, expected []byte)
- func DumpCache(mock *MockCache) string
- func OperationCounts(mock *MockCache) map[string]int64
- func ResetMock(mock *MockCache)
- type MockCache
- func (m *MockCache) AllKeys() []string
- func (m *MockCache) Clear()
- func (m *MockCache) Close() error
- func (m *MockCache) CompareAndSet(ctx context.Context, key string, expectedValue, newValue []byte, ...) (bool, error)
- func (m *MockCache) Delete(ctx context.Context, key string) error
- func (m *MockCache) Dump() string
- func (m *MockCache) Get(ctx context.Context, key string) ([]byte, error)
- func (m *MockCache) GetOrSet(ctx context.Context, key string, value []byte, ttl time.Duration) (storedValue []byte, wasSet bool, err error)
- func (m *MockCache) Has(key string) bool
- func (m *MockCache) Health(ctx context.Context) error
- func (m *MockCache) ID() string
- func (m *MockCache) IsClosed() bool
- func (m *MockCache) OperationCount(operation string) int64
- func (m *MockCache) ResetCounters()
- func (m *MockCache) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error
- func (m *MockCache) Stats() (map[string]any, error)
- func (m *MockCache) WithCloseCallback(callback func(string)) *MockCache
- func (m *MockCache) WithCloseFailure(err error) *MockCache
- func (m *MockCache) WithCompareAndSetFailure(err error) *MockCache
- func (m *MockCache) WithDelay(delay time.Duration) *MockCache
- func (m *MockCache) WithDeleteFailure(err error) *MockCache
- func (m *MockCache) WithGetFailure(err error) *MockCache
- func (m *MockCache) WithGetOrSetFailure(err error) *MockCache
- func (m *MockCache) WithHealthFailure(err error) *MockCache
- func (m *MockCache) WithSetFailure(err error) *MockCache
- func (m *MockCache) WithStatsFailure(err error) *MockCache
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AssertCacheClosed ¶
AssertCacheClosed asserts that the cache has been closed. Only works with MockCache instances.
Example:
mock := NewMockCache() mock.Close() AssertCacheClosed(t, mock)
func AssertCacheEmpty ¶
AssertCacheEmpty asserts that the cache contains no entries. Only works with MockCache instances.
Example:
mock := NewMockCache() mock.Clear() AssertCacheEmpty(t, mock)
func AssertCacheHit ¶
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 ¶
AssertCacheMiss asserts that a key does not exist in the cache.
Example:
mock := NewMockCache() AssertCacheMiss(t, mock, "missing:key")
func AssertCacheOpen ¶
AssertCacheOpen asserts that the cache has NOT been closed. Only works with MockCache instances.
Example:
mock := NewMockCache() AssertCacheOpen(t, mock)
func AssertCacheSize ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 AssertStatsContains ¶
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 ¶
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 ¶
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
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)
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 ¶
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
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) 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) 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) OperationCount ¶ added in v0.19.0
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) WithCloseCallback ¶
WithCloseCallback registers a callback that gets called when Close() succeeds. Useful for tracking cache lifecycle in tests.
func (*MockCache) WithCloseFailure ¶
WithCloseFailure configures Close operations to return an error.
func (*MockCache) WithCompareAndSetFailure ¶
WithCompareAndSetFailure configures CompareAndSet operations to return an error.
func (*MockCache) WithDelay ¶
WithDelay configures a delay for all operations. Useful for testing timeout behavior.
func (*MockCache) WithDeleteFailure ¶
WithDeleteFailure configures Delete operations to return an error.
func (*MockCache) WithGetFailure ¶
WithGetFailure configures Get operations to return an error.
func (*MockCache) WithGetOrSetFailure ¶
WithGetOrSetFailure configures GetOrSet operations to return an error.
func (*MockCache) WithHealthFailure ¶
WithHealthFailure configures Health operations to return an error.
func (*MockCache) WithSetFailure ¶
WithSetFailure configures Set operations to return an error.
func (*MockCache) WithStatsFailure ¶
WithStatsFailure configures Stats operations to return an error.