|
| 1 | +package index |
| 2 | + |
| 3 | +import ( |
| 4 | + "testing" |
| 5 | +) |
| 6 | + |
| 7 | +func TestLRUCache_Basic(t *testing.T) { |
| 8 | + cache := NewLRUCache[string, int](2) |
| 9 | + |
| 10 | + // Add and Get |
| 11 | + cache.Add("a", 1) |
| 12 | + cache.Add("b", 2) |
| 13 | + if v, ok := cache.Get("a"); !ok || v != 1 { |
| 14 | + t.Errorf("expected 1, got %v", v) |
| 15 | + } |
| 16 | + if v, ok := cache.Get("b"); !ok || v != 2 { |
| 17 | + t.Errorf("expected 2, got %v", v) |
| 18 | + } |
| 19 | + |
| 20 | + // Add triggers eviction |
| 21 | + cache.Add("c", 3) |
| 22 | + if _, ok := cache.Get("a"); ok { |
| 23 | + t.Errorf("expected 'a' to be evicted") |
| 24 | + } |
| 25 | + if v, ok := cache.Get("b"); !ok || v != 2 { |
| 26 | + t.Errorf("expected 2, got %v", v) |
| 27 | + } |
| 28 | + if v, ok := cache.Get("c"); !ok || v != 3 { |
| 29 | + t.Errorf("expected 3, got %v", v) |
| 30 | + } |
| 31 | + |
| 32 | + // Access order updates |
| 33 | + cache.Get("b") |
| 34 | + cache.Add("d", 4) |
| 35 | + if _, ok := cache.Get("c"); ok { |
| 36 | + t.Errorf("expected 'c' to be evicted after 'b' was used") |
| 37 | + } |
| 38 | + if v, ok := cache.Get("b"); !ok || v != 2 { |
| 39 | + t.Errorf("expected 2, got %v", v) |
| 40 | + } |
| 41 | + if v, ok := cache.Get("d"); !ok || v != 4 { |
| 42 | + t.Errorf("expected 4, got %v", v) |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +func TestLRUCache_Remove(t *testing.T) { |
| 47 | + cache := NewLRUCache[string, int](2) |
| 48 | + cache.Add("a", 1) |
| 49 | + cache.Add("b", 2) |
| 50 | + cache.Remove("a") |
| 51 | + if _, ok := cache.Get("a"); ok { |
| 52 | + t.Errorf("expected 'a' to be removed") |
| 53 | + } |
| 54 | + if v, ok := cache.Get("b"); !ok || v != 2 { |
| 55 | + t.Errorf("expected 2, got %v", v) |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +func TestLRUCache_Len(t *testing.T) { |
| 60 | + cache := NewLRUCache[string, int](2) |
| 61 | + if cache.Len() != 0 { |
| 62 | + t.Errorf("expected len 0, got %d", cache.Len()) |
| 63 | + } |
| 64 | + cache.Add("a", 1) |
| 65 | + if cache.Len() != 1 { |
| 66 | + t.Errorf("expected len 1, got %d", cache.Len()) |
| 67 | + } |
| 68 | + cache.Add("b", 2) |
| 69 | + if cache.Len() != 2 { |
| 70 | + t.Errorf("expected len 2, got %d", cache.Len()) |
| 71 | + } |
| 72 | + cache.Add("c", 3) |
| 73 | + if cache.Len() != 2 { |
| 74 | + t.Errorf("expected len 2 after eviction, got %d", cache.Len()) |
| 75 | + } |
| 76 | +} |
0 commit comments