Skip to content

Commit cc65373

Browse files
committed
tests(eviction/lfu): add tie-break tests to assert LRU-on-ties behavior (insert order and access order)
1 parent e7320c4 commit cc65373

1 file changed

Lines changed: 61 additions & 0 deletions

File tree

pkg/eviction/lfu_test.go

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package eviction
2+
3+
import "testing"
4+
5+
// Test that when two items have equal frequency, the older (least-recent) is evicted first.
6+
func TestLFU_EvictsOldestOnTie_InsertOrder(t *testing.T) {
7+
lfu, err := NewLFUAlgorithm(2)
8+
if err != nil {
9+
t.Fatalf("NewLFUAlgorithm error: %v", err)
10+
}
11+
12+
lfu.Set("a", 1)
13+
lfu.Set("b", 2)
14+
15+
// Both have count=1, but "a" is older (inserted first), so it should be evicted first.
16+
key, ok := lfu.Evict()
17+
if !ok {
18+
t.Fatalf("expected an eviction, got none")
19+
}
20+
if key != "a" {
21+
t.Fatalf("expected 'a' to be evicted first on tie, got %q", key)
22+
}
23+
24+
// Next eviction should evict the remaining one
25+
key, ok = lfu.Evict()
26+
if !ok {
27+
t.Fatalf("expected a second eviction, got none")
28+
}
29+
if key != "b" {
30+
t.Fatalf("expected 'b' to be evicted second, got %q", key)
31+
}
32+
}
33+
34+
// Test that recency is used to break ties after accesses with equalized frequency.
35+
func TestLFU_EvictsOldestOnTie_AccessOrder(t *testing.T) {
36+
lfu, err := NewLFUAlgorithm(2)
37+
if err != nil {
38+
t.Fatalf("NewLFUAlgorithm error: %v", err)
39+
}
40+
41+
lfu.Set("a", 1)
42+
lfu.Set("b", 2)
43+
44+
// Make both have the same frequency (2) but different recency orders.
45+
// Access sequence: bump "b" first, then "a" -> both count=2, and "a" is more recent.
46+
if _, ok := lfu.Get("b"); !ok {
47+
t.Fatalf("expected to get 'b'")
48+
}
49+
if _, ok := lfu.Get("a"); !ok {
50+
t.Fatalf("expected to get 'a'")
51+
}
52+
53+
// On tie (count=2), the older (least-recent) is "b" now, so it should be evicted first.
54+
key, ok := lfu.Evict()
55+
if !ok {
56+
t.Fatalf("expected an eviction, got none")
57+
}
58+
if key != "b" {
59+
t.Fatalf("expected 'b' to be evicted first on tie after accesses, got %q", key)
60+
}
61+
}

0 commit comments

Comments
 (0)