|
| 1 | +package eviction |
| 2 | + |
| 3 | +import "testing" |
| 4 | + |
| 5 | +func TestLRU_EvictsLeastRecentlyUsedOnSet(t *testing.T) { |
| 6 | + lru, err := NewLRUAlgorithm(2) |
| 7 | + if err != nil { |
| 8 | + t.Fatalf("NewLRUAlgorithm error: %v", err) |
| 9 | + } |
| 10 | + |
| 11 | + lru.Set("a", 1) |
| 12 | + lru.Set("b", 2) |
| 13 | + |
| 14 | + // Access "a" so that "b" becomes the least recently used |
| 15 | + if _, ok := lru.Get("a"); !ok { |
| 16 | + t.Fatalf("expected to get 'a'") |
| 17 | + } |
| 18 | + |
| 19 | + // Insert "c"; should evict "b" |
| 20 | + lru.Set("c", 3) |
| 21 | + if _, ok := lru.Get("b"); ok { |
| 22 | + t.Fatalf("expected 'b' to be evicted") |
| 23 | + } |
| 24 | + if _, ok := lru.Get("a"); !ok { |
| 25 | + t.Fatalf("expected 'a' to remain in cache") |
| 26 | + } |
| 27 | + if v, ok := lru.Get("c"); !ok || v.(int) != 3 { |
| 28 | + t.Fatalf("expected 'c'=3 in cache, got %v, ok=%v", v, ok) |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +func TestLRU_EvictMethodOrder(t *testing.T) { |
| 33 | + lru, err := NewLRUAlgorithm(2) |
| 34 | + if err != nil { |
| 35 | + t.Fatalf("NewLRUAlgorithm error: %v", err) |
| 36 | + } |
| 37 | + |
| 38 | + lru.Set("a", 1) |
| 39 | + lru.Set("b", 2) |
| 40 | + |
| 41 | + // After two inserts, tail should be "a" |
| 42 | + key, ok := lru.Evict() |
| 43 | + if !ok || key != "a" { |
| 44 | + t.Fatalf("expected to evict 'a' first, got %q ok=%v", key, ok) |
| 45 | + } |
| 46 | + key, ok = lru.Evict() |
| 47 | + if !ok || key != "b" { |
| 48 | + t.Fatalf("expected to evict 'b' second, got %q ok=%v", key, ok) |
| 49 | + } |
| 50 | +} |
0 commit comments