| 59 | } |
| 60 | |
| 61 | func TestCacheEviction(t *testing.T) { |
| 62 | ctx := context.Background() |
| 63 | config := DefaultConfig() |
| 64 | config.MaxItems = 5 |
| 65 | cache := New(config) |
| 66 | defer cache.Close() |
| 67 | |
| 68 | // Add 5 items (max capacity) |
| 69 | for i := 0; i < 5; i++ { |
| 70 | key := fmt.Sprintf("key%d", i) |
| 71 | cache.Set(ctx, key, i) |
| 72 | } |
| 73 | |
| 74 | // Verify all 5 items are in the cache |
| 75 | for i := 0; i < 5; i++ { |
| 76 | key := fmt.Sprintf("key%d", i) |
| 77 | if _, ok := cache.Get(ctx, key); !ok { |
| 78 | t.Errorf("Key '%s' should be in the cache", key) |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | // Add 2 more items to trigger eviction |
| 83 | cache.Set(ctx, "keyA", "valueA") |
| 84 | cache.Set(ctx, "keyB", "valueB") |
| 85 | |
| 86 | // Verify size is still within limits |
| 87 | if cache.Size() > int64(config.MaxItems) { |
| 88 | t.Errorf("Cache size %d exceeds limit %d", cache.Size(), config.MaxItems) |
| 89 | } |
| 90 | |
| 91 | // Some of the original keys should have been evicted |
| 92 | evictedCount := 0 |
| 93 | for i := 0; i < 5; i++ { |
| 94 | key := fmt.Sprintf("key%d", i) |
| 95 | if _, ok := cache.Get(ctx, key); !ok { |
| 96 | evictedCount++ |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | if evictedCount == 0 { |
| 101 | t.Error("No keys were evicted despite exceeding max items") |
| 102 | } |
| 103 | |
| 104 | // The newer keys should still be present |
| 105 | if _, ok := cache.Get(ctx, "keyA"); !ok { |
| 106 | t.Error("Key 'keyA' should be in the cache") |
| 107 | } |
| 108 | if _, ok := cache.Get(ctx, "keyB"); !ok { |
| 109 | t.Error("Key 'keyB' should be in the cache") |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | func TestCacheConcurrency(t *testing.T) { |
| 114 | ctx := context.Background() |