-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbatch_test.go
More file actions
449 lines (384 loc) · 11 KB
/
batch_test.go
File metadata and controls
449 lines (384 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
package gencache
import (
"context"
"sync"
"testing"
"time"
gencacheerrors "github.com/gozephyr/gencache/errors"
"github.com/stretchr/testify/require"
)
// mockCache implements Cache interface for testing
type mockCache[K comparable, V any] struct {
store map[K]V
mu sync.RWMutex
stats *Stats
}
func newMockCache[K comparable, V any]() *mockCache[K, V] {
return &mockCache[K, V]{
store: make(map[K]V),
stats: &Stats{},
}
}
func (m *mockCache[K, V]) Get(key K) (V, error) {
m.mu.RLock()
defer m.mu.RUnlock()
val, ok := m.store[key]
if !ok {
var zero V
return zero, gencacheerrors.ErrKeyNotFound
}
return val, nil
}
func (m *mockCache[K, V]) GetWithContext(ctx context.Context, key K) (V, error) {
select {
case <-ctx.Done():
var zero V
return zero, gencacheerrors.ErrContextCanceled
default:
return m.Get(key)
}
}
func (m *mockCache[K, V]) Set(key K, value V, ttl time.Duration) error {
m.mu.Lock()
defer m.mu.Unlock()
m.store[key] = value
return nil
}
func (m *mockCache[K, V]) SetWithContext(ctx context.Context, key K, value V, ttl time.Duration) error {
select {
case <-ctx.Done():
return gencacheerrors.ErrContextCanceled
default:
return m.Set(key, value, ttl)
}
}
func (m *mockCache[K, V]) Delete(key K) error {
m.mu.Lock()
defer m.mu.Unlock()
delete(m.store, key)
return nil
}
func (m *mockCache[K, V]) DeleteWithContext(ctx context.Context, key K) error {
select {
case <-ctx.Done():
return gencacheerrors.ErrContextCanceled
default:
return m.Delete(key)
}
}
func (m *mockCache[K, V]) Close() error {
return nil
}
func (m *mockCache[K, V]) Capacity() int64 {
m.mu.RLock()
defer m.mu.RUnlock()
return int64(len(m.store))
}
func (m *mockCache[K, V]) Clear() error {
m.mu.Lock()
defer m.mu.Unlock()
m.store = make(map[K]V)
return nil
}
func (m *mockCache[K, V]) ClearWithContext(ctx context.Context) error {
select {
case <-ctx.Done():
return gencacheerrors.ErrContextCanceled
default:
return m.Clear()
}
}
func (m *mockCache[K, V]) DeleteMany(ctx context.Context, keys []K) error {
m.mu.Lock()
defer m.mu.Unlock()
for _, key := range keys {
select {
case <-ctx.Done():
return ctx.Err()
default:
delete(m.store, key)
}
}
return nil
}
func (m *mockCache[K, V]) GetMany(ctx context.Context, keys []K) map[K]V {
result := make(map[K]V)
m.mu.RLock()
defer m.mu.RUnlock()
for _, key := range keys {
select {
case <-ctx.Done():
return result
default:
if val, ok := m.store[key]; ok {
result[key] = val
}
}
}
return result
}
func (m *mockCache[K, V]) MaxMemory() int64 {
return 0 // Mock implementation returns 0 for unlimited memory
}
func (m *mockCache[K, V]) MemoryUsage() int64 {
return 0 // Mock implementation returns 0 for memory usage
}
func (m *mockCache[K, V]) RegisterCallback(callback CacheCallback[K, V]) {
// Mock implementation does nothing
}
func (m *mockCache[K, V]) ResetStats() {
// Mock implementation does nothing
}
func (m *mockCache[K, V]) SetMany(ctx context.Context, entries map[K]V, ttl time.Duration) error {
m.mu.Lock()
defer m.mu.Unlock()
for key, value := range entries {
select {
case <-ctx.Done():
return ctx.Err()
default:
m.store[key] = value
}
}
return nil
}
func (m *mockCache[K, V]) Size() int {
m.mu.RLock()
defer m.mu.RUnlock()
return len(m.store)
}
func (m *mockCache[K, V]) UnregisterCallback(callback CacheCallback[K, V]) {
// Mock implementation does nothing
}
func (m *mockCache[K, V]) GetAll() map[K]V {
m.mu.RLock()
defer m.mu.RUnlock()
result := make(map[K]V, len(m.store))
for k, v := range m.store {
result[k] = v
}
return result
}
func (m *mockCache[K, V]) GetStats() StatsSnapshot {
return StatsSnapshot{
Size: int64(len(m.store)),
Capacity: 0,
Hits: 0,
Misses: 0,
Evictions: 0,
PanicCount: 0,
LastPanic: time.Time{},
LastOperationDuration: 0,
}
}
func (m *mockCache[K, V]) OnEvent(callback CacheCallback[K, V]) {
// No-op for mock cache
}
func (m *mockCache[K, V]) RemoveEventCallback(callback CacheCallback[K, V]) {
// No-op for mock cache
}
func (m *mockCache[K, V]) SetCapacity(capacity int64) {
// No-op for mock cache
}
func (m *mockCache[K, V]) Stats() *Stats {
return m.stats
}
func TestNewBatchCache(t *testing.T) {
mock := newMockCache[string, int]()
config := DefaultBatchConfig()
bc := NewBatchCache[string, int](mock, config)
require.NotNil(t, bc, "NewBatchCache should not return nil")
}
func TestGetMany(t *testing.T) {
mock := newMockCache[string, int]()
bc := NewBatchCache[string, int](mock, DefaultBatchConfig())
// Setup test data
testData := map[string]int{
"key1": 1,
"key2": 2,
"key3": 3,
}
for k, v := range testData {
err := mock.Set(k, v, 0)
require.NoError(t, err)
}
// Test successful retrieval
ctx := context.Background()
keys := []string{"key1", "key2", "key3"}
result := bc.GetMany(ctx, keys)
require.Equal(t, len(testData), len(result), "Expected correct number of results")
for k, v := range testData {
val, err := mock.Get(k)
require.NoError(t, err)
require.Equal(t, v, val, "Value for key %s should match", k)
}
// Test with non-existent keys
nonExistentKeys := []string{"key4", "key5"}
result = bc.GetMany(ctx, nonExistentKeys)
require.Empty(t, result, "Result should be empty for non-existent keys")
// Test batch size limit
largeKeys := make([]string, 2000)
for i := range largeKeys {
largeKeys[i] = "key" + string(rune(i))
}
result = bc.GetMany(ctx, largeKeys)
require.LessOrEqual(t, len(result), DefaultBatchConfig().MaxBatchSize, "Result size should not exceed MaxBatchSize")
}
func TestSetMany(t *testing.T) {
mock := newMockCache[string, int]()
bc := NewBatchCache[string, int](mock, DefaultBatchConfig())
// Test successful batch set
ctx := context.Background()
entries := map[string]int{
"key1": 1,
"key2": 2,
"key3": 3,
}
err := bc.SetMany(ctx, entries, time.Second)
require.NoError(t, err, "SetMany should not return error")
// Verify values were set
for k, v := range entries {
val, err := mock.Get(k)
require.NoError(t, err)
require.Equal(t, v, val, "Value for key %s should match", k)
}
// Test batch size limit
largeEntries := make(map[string]int, 2000)
for i := 0; i < 2000; i++ {
largeEntries["key"+string(rune(i))] = i
}
err = bc.SetMany(ctx, largeEntries, time.Second)
require.NoError(t, err, "SetMany with large batch should not return error")
}
func TestDeleteMany(t *testing.T) {
mock := newMockCache[string, int]()
bc := NewBatchCache[string, int](mock, DefaultBatchConfig())
// Setup test data
testData := map[string]int{
"key1": 1,
"key2": 2,
"key3": 3,
}
for k, v := range testData {
err := mock.Set(k, v, 0)
require.NoError(t, err)
}
// Test successful batch delete
ctx := context.Background()
keys := []string{"key1", "key2"}
err := bc.DeleteMany(ctx, keys)
require.NoError(t, err, "DeleteMany should not return error")
// Verify keys were deleted
for _, k := range keys {
_, err := mock.Get(k)
require.ErrorIs(t, err, gencacheerrors.ErrKeyNotFound, "Key %s should be deleted", k)
}
// Verify other keys still exist
val, err := mock.Get("key3")
require.NoError(t, err)
require.Equal(t, 3, val, "Key3's value should be unchanged")
}
func TestBatchMetrics(t *testing.T) {
mock := newMockCache[string, int]()
bc := NewBatchCache[string, int](mock, DefaultBatchConfig())
// Perform some operations
ctx := context.Background()
bc.GetMany(ctx, []string{"key1", "key2"})
err := bc.SetMany(ctx, map[string]int{"key1": 1}, time.Second)
require.NoError(t, err, "SetMany should not return error")
err = bc.DeleteMany(ctx, []string{"key1"})
require.NoError(t, err, "DeleteMany should not return error")
// Check metrics
metrics := bc.GetBatchMetrics()
require.Equal(t, int64(3), metrics.TotalOperations.Load(), "Expected 3 total operations")
require.Equal(t, int64(4), metrics.TotalItems.Load(), "Expected 4 total items")
// Test reset metrics
bc.ResetBatchMetrics()
metrics = bc.GetBatchMetrics()
require.Equal(t, int64(0), metrics.TotalOperations.Load(), "Expected 0 total operations after reset")
}
func TestContextCancellation(t *testing.T) {
mock := newMockCache[string, int]()
bc := NewBatchCache[string, int](mock, DefaultBatchConfig())
// Test GetMany with cancelled context
ctx, cancel := context.WithCancel(context.Background())
cancel()
result := bc.GetMany(ctx, []string{"key1", "key2"})
require.Empty(t, result, "Result should be empty with cancelled context")
// Test SetMany with cancelled context
err := bc.SetMany(ctx, map[string]int{"key1": 1}, time.Second)
require.ErrorIs(t, err, context.Canceled, "Expected context.Canceled error")
// Test DeleteMany with cancelled context
err = bc.DeleteMany(ctx, []string{"key1"})
require.ErrorIs(t, err, context.Canceled, "Expected context.Canceled error")
}
func TestBatchConcurrency(t *testing.T) {
mock := newMockCache[string, int]()
bc := NewBatchCache[string, int](mock, DefaultBatchConfig())
var wg sync.WaitGroup
concurrency := 10
iterations := 100
// Test concurrent GetMany operations
for i := 0; i < concurrency; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
ctx := context.Background()
keys := make([]string, iterations)
for j := 0; j < iterations; j++ {
keys[j] = "key" + string(rune(id)) + string(rune(j))
}
_ = bc.GetMany(ctx, keys)
}(i)
}
// Test concurrent SetMany operations
for i := 0; i < concurrency; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
ctx := context.Background()
entries := make(map[string]int, iterations)
for j := 0; j < iterations; j++ {
entries["key"+string(rune(id))+string(rune(j))] = id*iterations + j
}
_ = bc.SetMany(ctx, entries, time.Second)
}(i)
}
// Test concurrent DeleteMany operations
for i := 0; i < concurrency; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
ctx := context.Background()
keys := make([]string, iterations)
for j := 0; j < iterations; j++ {
keys[j] = "key" + string(rune(id)) + string(rune(j))
}
_ = bc.DeleteMany(ctx, keys)
}(i)
}
wg.Wait()
}
func TestBatchTimeout(t *testing.T) {
mock := newMockCache[string, int]()
bc := NewBatchCache[string, int](mock, DefaultBatchConfig())
// Test GetMany with timeout
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
result := bc.GetMany(ctx, []string{"key1", "key2"})
require.Empty(t, result, "Result should be empty with timeout")
// Test SetMany with timeout
err := bc.SetMany(ctx, map[string]int{"key1": 1}, time.Second)
if err != nil {
require.ErrorIs(t, err, context.DeadlineExceeded, "Expected context.DeadlineExceeded error")
} else {
require.NoError(t, err, "SetMany should not return error if completed before timeout")
}
// Test DeleteMany with timeout
err = bc.DeleteMany(ctx, []string{"key1"})
if err != nil {
require.ErrorIs(t, err, context.DeadlineExceeded, "Expected context.DeadlineExceeded error")
} else {
require.NoError(t, err, "DeleteMany should not return error if completed before timeout")
}
}