Skip to content

Commit d1b5a29

Browse files
committed
chore: add test
1 parent c0ab614 commit d1b5a29

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

7-lfu-cache/cache_test.go

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package main
22

33
import (
4+
"fmt"
45
"slices"
56
"testing"
67
)
@@ -34,3 +35,44 @@ func TestCache(t *testing.T) {
3435
t.Errorf("keys should not contain luan")
3536
}
3637
}
38+
39+
func TestCache1(t *testing.T) {
40+
cache, err := NewLFUCache(3, func(key string) (string, error) {
41+
return "", nil
42+
})
43+
if err != nil {
44+
t.Fatal(err)
45+
}
46+
47+
err = cache.Set("vu", "10")
48+
err = cache.Set("nghia", "20")
49+
err = cache.Set("luan", "5")
50+
51+
for i := 0; i < 10; i++ {
52+
cache.Get("vu")
53+
}
54+
55+
for i := 0; i < 9; i++ {
56+
cache.Get("nghia")
57+
}
58+
59+
for i := 0; i < 8; i++ {
60+
cache.Get("luan")
61+
}
62+
63+
i := 8
64+
for e := cache.GetBuckets().Front(); e != nil; e = e.Next() {
65+
fmt.Printf("Value: %v (Type: %T)\n", e.Value, e.Value)
66+
bucketFreq := cache.GetFreq(e)
67+
if bucketFreq != i {
68+
t.Errorf("bucketFreq should be %d, got %d", i, bucketFreq)
69+
}
70+
i += 1
71+
}
72+
73+
err = cache.Set("xanh", "30")
74+
keys := cache.GetKeys()
75+
if slices.Contains(keys, "luan") {
76+
t.Errorf("keys should not contain luan")
77+
}
78+
}

7-lfu-cache/main.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,15 @@ func NewLFUCache(size int, loaderFunc LoaderFunc) (*LFUCache, error) {
6161
return cache, nil
6262
}
6363

64+
// For testing
65+
func (cache *LFUCache) GetBuckets() *list.List {
66+
return cache.list
67+
}
68+
69+
func (cache *LFUCache) GetFreq(buckets *list.Element) int {
70+
return buckets.Value.(*lruEntry).freq
71+
}
72+
6473
func (cache *LFUCache) Get(key string) (string, error) {
6574
if item, ok := cache.cache[key]; ok {
6675
// Move item to the higher bucket

0 commit comments

Comments
 (0)