-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmemory_test.go
More file actions
1094 lines (899 loc) · 23 KB
/
memory_test.go
File metadata and controls
1094 lines (899 loc) · 23 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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package fido
import (
"fmt"
"sync"
"sync/atomic"
"testing"
"time"
)
func TestCache_Basic(t *testing.T) {
cache := New[string, int]()
// Test Set and Get
cache.Set("key1", 42)
val, found := cache.Get("key1")
if !found {
t.Fatal("key1 not found")
}
if val != 42 {
t.Errorf("Get value = %d; want 42", val)
}
// Test miss
_, found = cache.Get("missing")
if found {
t.Error("missing key should not be found")
}
// Test delete
cache.Delete("key1")
_, found = cache.Get("key1")
if found {
t.Error("deleted key should not be found")
}
}
func TestCache_WithTTL(t *testing.T) {
cache := New[string, string]()
// Set with short TTL (minimum 1 second granularity)
cache.SetTTL("temp", "value", 1*time.Second)
// Should be available immediately
val, found := cache.Get("temp")
if !found || val != "value" {
t.Error("temp should be found immediately")
}
// Wait for expiration
time.Sleep(2 * time.Second)
// Should be expired
_, found = cache.Get("temp")
if found {
t.Error("temp should be expired")
}
}
func TestCache_DefaultTTL(t *testing.T) {
cache := New[string, int](TTL(1 * time.Second))
// Set without explicit TTL (ttl=0 uses default)
cache.Set("key", 100)
// Should be available immediately
_, found := cache.Get("key")
if !found {
t.Error("key should be found immediately")
}
// Wait for default TTL expiration
time.Sleep(2 * time.Second)
// Should be expired
_, found = cache.Get("key")
if found {
t.Error("key should be expired after default TTL")
}
}
func TestCache_Concurrent(t *testing.T) {
cache := New[int, int](Size(1000))
var wg sync.WaitGroup
// Concurrent writers
for i := range 10 {
wg.Add(1)
go func(offset int) {
defer wg.Done()
for j := range 100 {
cache.Set(offset*100+j, j)
}
}(i)
}
// Concurrent readers
for range 10 {
wg.Go(func() {
for j := range 100 {
cache.Get(j)
}
})
}
wg.Wait()
// Cache should be at or near capacity
if cache.Len() > 1000 {
t.Errorf("cache length = %d; should not exceed capacity", cache.Len())
}
}
func TestCache_Len(t *testing.T) {
cache := New[string, int]()
if cache.Len() != 0 {
t.Errorf("initial length = %d; want 0", cache.Len())
}
cache.Set("a", 1)
cache.Set("b", 2)
cache.Set("c", 3)
if cache.Len() != 3 {
t.Errorf("length = %d; want 3", cache.Len())
}
cache.Delete("b")
if cache.Len() != 2 {
t.Errorf("length after delete = %d; want 2", cache.Len())
}
}
func BenchmarkCache_Set(b *testing.B) {
cache := New[int, int]()
b.ResetTimer()
for i := range b.N {
cache.Set(i%10000, i)
}
}
func BenchmarkCache_Get_Hit(b *testing.B) {
cache := New[int, int]()
// Populate cache
for i := range 10000 {
cache.Set(i, i)
}
b.ResetTimer()
for i := range b.N {
cache.Get(i % 10000)
}
}
func BenchmarkCache_Get_Miss(b *testing.B) {
cache := New[int, int]()
b.ResetTimer()
for i := range b.N {
cache.Get(i)
}
}
func BenchmarkCache_Mixed(b *testing.B) {
cache := New[int, int]()
b.ResetTimer()
for i := range b.N {
if i%3 == 0 {
cache.Set(i%10000, i)
} else {
cache.Get(i % 10000)
}
}
}
func TestCache_WithOptions(t *testing.T) {
// Test Size
cache := New[string, int](Size(500))
if cache.memory == nil {
t.Error("memory should be initialized")
}
// Test TTL
cache = New[string, int](TTL(5 * time.Minute))
if cache.defaultTTL != 5*time.Minute {
t.Errorf("default TTL = %v; want 5m", cache.defaultTTL)
}
}
func TestCache_DeleteNonExistent(t *testing.T) {
cache := New[string, int]()
// Delete non-existent key should not panic
cache.Delete("does-not-exist")
// Cache should still work
cache.Set("key1", 42)
val, found := cache.Get("key1")
if !found || val != 42 {
t.Error("cache should still work after deleting non-existent key")
}
}
func TestCache_EvictFromMain(t *testing.T) {
// Cache with 20000 capacity (approx 10 per shard with 2048 shards)
cache := New[int, int](Size(20000))
// Fill cache and promote items to main by accessing them
for i := range 25000 {
cache.Set(i, i)
// Access immediately to promote to main
cache.Get(i)
}
// Add more items to force eviction from main queue
for i := range 10000 {
cache.Set(i+30000, i+30000)
cache.Get(i + 30000)
}
// Cache should not exceed configured capacity by more than shard overhead
// With 2048 shards and rounding, effective capacity is ~20480
if cache.Len() > 20480 {
t.Errorf("cache length = %d; should not exceed 20480", cache.Len())
}
}
func TestCache_GetExpired(t *testing.T) {
cache := New[string, int]()
// Set with short TTL (1 second granularity)
cache.SetTTL("key1", 42, 1*time.Second)
// Wait for expiration
time.Sleep(2 * time.Second)
// Get should return not found
_, found := cache.Get("key1")
if found {
t.Error("expired key should not be found")
}
}
func TestCache_SetUpdateExisting(t *testing.T) {
cache := New[string, int]()
// Set initial value
cache.Set("key1", 42)
// Update value
cache.Set("key1", 100)
// Should have new value
val, found := cache.Get("key1")
if !found {
t.Error("key1 should be found")
}
if val != 100 {
t.Errorf("Get value = %d; want 100", val)
}
}
func TestCache_Flush(t *testing.T) {
cache := New[string, int]()
// Add entries
for i := range 10 {
cache.Set(fmt.Sprintf("key%d", i), i)
}
if cache.Len() != 10 {
t.Errorf("cache length = %d; want 10", cache.Len())
}
// Flush
removed := cache.Flush()
if removed != 10 {
t.Errorf("Flush removed %d items; want 10", removed)
}
// Cache should be empty
if cache.Len() != 0 {
t.Errorf("cache length after flush = %d; want 0", cache.Len())
}
// All keys should be gone
for i := range 10 {
_, found := cache.Get(fmt.Sprintf("key%d", i))
if found {
t.Errorf("key%d should not be found after flush", i)
}
}
}
func TestCache_FlushEmpty(t *testing.T) {
cache := New[string, int]()
// Flush empty cache
removed := cache.Flush()
if removed != 0 {
t.Errorf("Flush removed %d items; want 0", removed)
}
}
func TestCache_GhostQueue(t *testing.T) {
// Small capacity to force ghost queue usage
cache := New[string, int](Size(10))
// Fill small queue (10% of 10 = 1)
// Insert items to trigger ghost queue
for i := range 20 {
cache.Set(fmt.Sprintf("key%d", i), i)
}
// Access some items to create hot items
for i := range 5 {
cache.Get(fmt.Sprintf("key%d", i))
}
// Insert more to trigger evictions from small queue to ghost queue
for i := range 15 {
cache.Set(fmt.Sprintf("key%d", i+20), i+20)
}
// Test should complete without panic
t.Logf("Cache length: %d", cache.Len())
}
func TestCache_MainQueueEviction(t *testing.T) {
// Create cache with 20000 capacity (approx 10 per shard with 2048 shards)
cache := New[string, int](Size(20000))
// Insert and access items to get them into Main queue
for i := range 25000 {
key := fmt.Sprintf("key%d", i)
cache.Set(key, i)
// Access to promote to Main
cache.Get(key)
}
// Insert more items to trigger eviction from Main queue
for i := range 10000 {
key := fmt.Sprintf("key%d", i+30000)
cache.Set(key, i+30000)
cache.Get(key)
}
// Verify cache is at capacity (with 2048 shards, effective capacity is ~20480)
if cache.Len() > 20480 {
t.Errorf("Cache length %d exceeds capacity 20480", cache.Len())
}
}
func TestCache_SetTTL(t *testing.T) {
cache := New[string, int](TTL(time.Hour))
// Set uses default TTL (1 hour, won't expire during test)
cache.Set("default-ttl", 1)
if _, found := cache.Get("default-ttl"); !found {
t.Error("default-ttl should be found")
}
// SetTTL uses explicit short TTL (1 second granularity)
cache.SetTTL("short-ttl", 2, 1*time.Second)
if _, found := cache.Get("short-ttl"); !found {
t.Error("short-ttl should be found immediately")
}
// SetTTL with zero TTL - should never expire
cache.SetTTL("zero-ttl", 3, 0)
if _, found := cache.Get("zero-ttl"); !found {
t.Error("zero-ttl should be found")
}
// SetTTL with negative TTL - should never expire
cache.SetTTL("neg-ttl", 4, -1*time.Second)
if _, found := cache.Get("neg-ttl"); !found {
t.Error("neg-ttl should be found")
}
// Wait for short TTL to expire
time.Sleep(2 * time.Second)
// short-ttl should be expired, others should still exist
if _, found := cache.Get("short-ttl"); found {
t.Error("short-ttl should be expired")
}
if _, found := cache.Get("default-ttl"); !found {
t.Error("default-ttl should still exist (1 hour TTL)")
}
if _, found := cache.Get("zero-ttl"); !found {
t.Error("zero-ttl should still exist (no expiry)")
}
if _, found := cache.Get("neg-ttl"); !found {
t.Error("neg-ttl should still exist (no expiry)")
}
}
func TestCache_Set_NoDefaultTTL(t *testing.T) {
cache := New[string, int]() // No default TTL
// Set without TTL - should never expire
cache.Set("no-expiry", 42)
// Wait a bit
time.Sleep(100 * time.Millisecond)
// Should still exist
val, found := cache.Get("no-expiry")
if !found || val != 42 {
t.Error("no-expiry should still exist (no TTL means no expiry)")
}
}
func TestCache_Fetch_Basic(t *testing.T) {
cache := New[string, int]()
loaderCalls := 0
loader := func() (int, error) {
loaderCalls++
return 42, nil
}
// First call - should call loader
val, err := cache.Fetch("key1", loader)
if err != nil {
t.Fatalf("Fetch error: %v", err)
}
if val != 42 {
t.Errorf("Fetch value = %d; want 42", val)
}
if loaderCalls != 1 {
t.Errorf("loader calls = %d; want 1", loaderCalls)
}
// Second call - should use cached value, not call loader
val, err = cache.Fetch("key1", loader)
if err != nil {
t.Fatalf("Fetch error: %v", err)
}
if val != 42 {
t.Errorf("Fetch value = %d; want 42", val)
}
if loaderCalls != 1 {
t.Errorf("loader calls = %d; want 1 (should use cache)", loaderCalls)
}
}
func TestCache_Fetch_LoaderError(t *testing.T) {
cache := New[string, int]()
loader := func() (int, error) {
return 0, fmt.Errorf("loader error")
}
_, err := cache.Fetch("key1", loader)
if err == nil {
t.Fatal("Fetch should return error from loader")
}
// Value should not be cached
_, found := cache.Get("key1")
if found {
t.Error("failed loader should not cache a value")
}
}
func TestCache_Fetch_ThunderingHerd(t *testing.T) {
cache := New[string, int]()
var loaderCalls int32
var mu sync.Mutex
loader := func() (int, error) {
mu.Lock()
loaderCalls++
count := loaderCalls // Capture for potential error simulation
mu.Unlock()
time.Sleep(50 * time.Millisecond) // Simulate slow operation
// Return error on hypothetical second call (won't happen due to singleflight)
if count > 1 {
return 0, fmt.Errorf("unexpected second call")
}
return 42, nil
}
// Launch many concurrent Fetch calls for the same key
var wg sync.WaitGroup
results := make([]int, 100)
errors := make([]error, 100)
for i := range 100 {
wg.Add(1)
go func(idx int) {
defer wg.Done()
results[idx], errors[idx] = cache.Fetch("key1", loader)
}(i)
}
wg.Wait()
// All goroutines should get the same result
for i := range 100 {
if errors[i] != nil {
t.Errorf("goroutine %d error: %v", i, errors[i])
}
if results[i] != 42 {
t.Errorf("goroutine %d result = %d; want 42", i, results[i])
}
}
// Loader should only be called once (thundering herd prevented)
if loaderCalls != 1 {
t.Errorf("loader calls = %d; want 1 (thundering herd prevention failed)", loaderCalls)
}
}
func TestCache_Fetch_WithTTL(t *testing.T) {
cache := New[string, int]()
loaderCalls := 0
loader := func() (int, error) {
loaderCalls++
return loaderCalls * 10, nil
}
// First call with short TTL (1 second granularity)
val, err := cache.FetchTTL("key1", 1*time.Second, loader)
if err != nil {
t.Fatalf("Fetch error: %v", err)
}
if val != 10 {
t.Errorf("first Fetch value = %d; want 10", val)
}
// Wait for TTL to expire
time.Sleep(2 * time.Second)
// Second call - should call loader again (cache expired)
val, err = cache.FetchTTL("key1", 1*time.Second, loader)
if err != nil {
t.Fatalf("Fetch error: %v", err)
}
if val != 20 {
t.Errorf("second Fetch value = %d; want 20", val)
}
if loaderCalls != 2 {
t.Errorf("loader calls = %d; want 2", loaderCalls)
}
}
func TestCache_Fetch_IntKeys(t *testing.T) {
cache := New[int, int](Size(1000))
var loaderCalls int32
loader := func() (int, error) { //nolint:unparam // error is always nil in test
atomic.AddInt32(&loaderCalls, 1)
time.Sleep(10 * time.Millisecond)
return 42, nil
}
// Test thundering herd with int keys (uses different flightShard path)
var wg sync.WaitGroup
for i := range 50 {
wg.Go(func() {
// All goroutines request the same key
val, err := cache.Fetch(123, loader)
if err != nil {
t.Errorf("Fetch error: %v", err)
}
if val != 42 {
t.Errorf("Fetch value = %d; want 42", val)
}
})
// Stagger slightly to ensure overlap
if i%10 == 0 {
time.Sleep(time.Millisecond)
}
}
wg.Wait()
if loaderCalls != 1 {
t.Errorf("loader calls = %d; want 1", loaderCalls)
}
// Verify different int keys work independently
loaderCalls = 0
for i := range 10 {
_, err := cache.Fetch(i, func() (int, error) {
atomic.AddInt32(&loaderCalls, 1)
return i * 10, nil
})
if err != nil {
t.Fatalf("Fetch key %d error: %v", i, err)
}
}
if loaderCalls != 10 {
t.Errorf("loader calls = %d; want 10 (one per unique key)", loaderCalls)
}
}
func TestCache_CapacityEfficiency(t *testing.T) {
// Test that cache stores exactly the requested capacity.
// Global capacity tracking ensures 100% efficiency regardless of
// hash distribution across shards.
sizes := []int{1000, 16384, 65536}
for _, size := range sizes {
t.Run(fmt.Sprintf("size_%d", size), func(t *testing.T) {
cache := New[int, int](Size(size))
// Fill to capacity
for i := range size {
cache.Set(i, i)
}
stored := cache.Len()
if stored != size {
t.Errorf("stored %d entries; want exactly %d (100%% efficiency)", stored, size)
}
})
}
}
func TestCache_CapacityEfficiency_StringKeys(t *testing.T) {
// String keys have different hash distribution - verify 100% efficiency.
sizes := []int{1000, 16384}
for _, size := range sizes {
t.Run(fmt.Sprintf("size_%d", size), func(t *testing.T) {
cache := New[string, int](Size(size))
// Fill to capacity with string keys
for i := range size {
cache.Set(fmt.Sprintf("user:%d:profile", i), i)
}
stored := cache.Len()
if stored != size {
t.Errorf("stored %d entries; want exactly %d (100%% efficiency)", stored, size)
}
})
}
}
// TestCache_Fetch_CacheHitDuringSingleflight is in memory_race_test.go
// It tests concurrent cache access which triggers seqlock races.
func TestCache_Fetch_RaceCondition(t *testing.T) {
// Test the path where cache is populated between first check and singleflight
cache := New[string, int](Size(1000))
var wg sync.WaitGroup
// Run many concurrent Fetchs with a mix of slow and fast loaders
for i := range 20 {
wg.Add(1)
go func(idx int) {
defer wg.Done()
key := fmt.Sprintf("key%d", idx%5) // Only 5 unique keys
val, err := cache.Fetch(key, func() (int, error) {
if idx%3 == 0 {
time.Sleep(10 * time.Millisecond)
}
return idx * 10, nil
})
if err != nil {
t.Errorf("Fetch error: %v", err)
}
if val < 0 {
t.Errorf("unexpected value: %d", val)
}
}(i)
}
wg.Wait()
}
// TestCache_Fetch_MemoryHitAfterSingleflightAcquire tests the path where
// the cache is populated between winning singleflight and checking cache again.
func TestCache_Fetch_MemoryHitAfterSingleflightAcquire(t *testing.T) {
// This is tricky to test because the window is very small.
// We use a contrived scenario with concurrent access.
cache := New[string, int](Size(100))
// Key that will be set by another goroutine
const key = "contested"
var started sync.WaitGroup
started.Add(1)
var done sync.WaitGroup
done.Add(2)
// First goroutine: slow loader
go func() {
defer done.Done()
started.Done() // Signal that we've started
if _, err := cache.Fetch(key, func() (int, error) {
// Wait long enough for the second Set to happen
time.Sleep(50 * time.Millisecond)
return 1, nil
}); err != nil {
t.Errorf("Fetch error: %v", err)
}
}()
// Wait for first goroutine to start
started.Wait()
time.Sleep(5 * time.Millisecond)
// Second goroutine: direct Set while first is in loader
go func() {
defer done.Done()
cache.Set(key, 99)
}()
done.Wait()
// Value should be either 99 (from Set) or 1 (from loader)
if val, ok := cache.Get(key); !ok {
t.Error("key should exist")
} else if val != 99 && val != 1 {
t.Errorf("unexpected value: %d", val)
}
}
// TestCache_Fetch_WithDefaultTTL tests Fetch using the default TTL.
func TestCache_Fetch_WithDefaultTTL(t *testing.T) {
cache := New[string, int](TTL(time.Hour))
val, err := cache.Fetch("key1", func() (int, error) {
return 42, nil
})
if err != nil {
t.Fatalf("Fetch error: %v", err)
}
if val != 42 {
t.Errorf("Fetch value = %d; want 42", val)
}
}
// TestCache_Fetch_DoubleCheckPath attempts to hit the double-check cache hit path.
// This path is triggered when:
// 1. First check misses (no cache hit)
// 2. We win the singleflight (not loaded)
// 3. Another call populated the cache before our double-check
// 4. Double-check finds the value
func TestCache_Fetch_DoubleCheckPath(t *testing.T) {
var hitCount int
for iteration := range 1000 {
cache := New[string, int](Size(100))
key := fmt.Sprintf("key%d", iteration)
var loaderCalled atomic.Bool
var wg sync.WaitGroup
wg.Add(2)
// Goroutine 1: Will try to win singleflight
go func() {
defer wg.Done()
if _, err := cache.Fetch(key, func() (int, error) {
loaderCalled.Store(true)
return 1, nil
}); err != nil {
t.Errorf("Fetch error: %v", err)
}
}()
// Goroutine 2: Directly sets value, racing with goroutine 1
go func() {
defer wg.Done()
cache.Set(key, 99)
}()
wg.Wait()
// If loader wasn't called, we hit the double-check path
if !loaderCalled.Load() {
hitCount++
}
}
if hitCount > 0 {
t.Logf("Hit double-check path %d times out of 1000", hitCount)
} else {
t.Log("Could not reliably hit double-check path (race dependent)")
}
}
func TestCache_Range_Empty(t *testing.T) {
cache := New[string, int]()
count := 0
for range cache.Range() {
count++
}
if count != 0 {
t.Errorf("Range on empty cache yielded %d items; want 0", count)
}
}
func TestCache_Range_Single(t *testing.T) {
cache := New[string, int]()
cache.Set("key1", 42)
count := 0
var gotKey string
var gotVal int
for k, v := range cache.Range() {
count++
gotKey = k
gotVal = v
}
if count != 1 {
t.Errorf("Range yielded %d items; want 1", count)
}
if gotKey != "key1" {
t.Errorf("Range key = %q; want %q", gotKey, "key1")
}
if gotVal != 42 {
t.Errorf("Range value = %d; want 42", gotVal)
}
}
func TestCache_Range_Multiple(t *testing.T) {
cache := New[string, int]()
// Add entries
expected := map[string]int{
"a": 1,
"b": 2,
"c": 3,
}
for k, v := range expected {
cache.Set(k, v)
}
// Collect via Range
got := make(map[string]int)
for k, v := range cache.Range() {
got[k] = v
}
// Verify all expected entries were yielded
if len(got) != len(expected) {
t.Errorf("Range yielded %d items; want %d", len(got), len(expected))
}
for k, want := range expected {
if got[k] != want {
t.Errorf("Range[%q] = %d; want %d", k, got[k], want)
}
}
}
func TestCache_Range_SkipsExpired(t *testing.T) {
cache := New[string, int]()
// Set with short TTL (1 second granularity)
cache.SetTTL("expired", 1, 1*time.Second)
cache.Set("valid", 2) // no TTL
// Wait for first key to expire
time.Sleep(2 * time.Second)
// Range should only yield valid entry
count := 0
for k, v := range cache.Range() {
count++
if k == "expired" {
t.Error("Range yielded expired entry")
}
if k == "valid" && v != 2 {
t.Errorf("Range[valid] = %d; want 2", v)
}
}
if count != 1 {
t.Errorf("Range yielded %d items; want 1 (expired should be skipped)", count)
}
}
func TestCache_Range_EarlyTermination(t *testing.T) {
cache := New[int, int]()
// Add 100 entries
for i := range 100 {
cache.Set(i, i*10)
}
// Stop after 10 entries
count := 0
for range cache.Range() {
count++
if count >= 10 {
break
}
}
if count != 10 {
t.Errorf("Range with early break yielded %d items; want 10", count)
}
}
func TestCache_Range_KeysOnly(t *testing.T) {
cache := New[string, int]()
expected := []string{"a", "b", "c"}
for _, k := range expected {
cache.Set(k, 999) // value doesn't matter
}
// Iterate keys only (ignore value)
got := make(map[string]bool)
for k := range cache.Range() {
got[k] = true
}
if len(got) != len(expected) {
t.Errorf("Range keys-only yielded %d items; want %d", len(got), len(expected))
}
for _, k := range expected {
if !got[k] {
t.Errorf("Range keys-only missing key %q", k)
}
}
}
func TestCache_Range_ConcurrentModification(t *testing.T) {
cache := New[int, int](Size(1000))
// Populate cache
for i := range 100 {
cache.Set(i, i)
}
var wg sync.WaitGroup
// Start iteration
wg.Add(1)
go func() {
defer wg.Done()
count := 0
for range cache.Range() {
count++
time.Sleep(time.Millisecond) // slow iteration
}
}()
// Concurrent modifications during iteration
wg.Add(1)
go func() {
defer wg.Done()
for i := 100; i < 200; i++ {
cache.Set(i, i)
time.Sleep(500 * time.Microsecond)
}
}()
wg.Add(1)
go func() {
defer wg.Done()
for i := range 50 {
cache.Delete(i)
time.Sleep(time.Millisecond)
}
}()
wg.Wait()
// Should complete without panic
}
func TestCache_Range_IntKeys(t *testing.T) {
cache := New[int, string]()
expected := map[int]string{
1: "one",
2: "two",
3: "three",
}
for k, v := range expected {
cache.Set(k, v)
}