Skip to content

Commit 248290e

Browse files
committed
Added tests for LRU cache
1 parent baa7d46 commit 248290e

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

internal/common/cache/lru_test.go

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import (
2626
"time"
2727

2828
"github.com/stretchr/testify/assert"
29+
"github.com/stretchr/testify/require"
2930
)
3031

3132
func TestLRU(t *testing.T) {
@@ -62,6 +63,79 @@ func TestLRU(t *testing.T) {
6263
assert.Nil(t, cache.Get("A"))
6364
}
6465

66+
func TestExist(t *testing.T) {
67+
cache := NewLRUWithInitialCapacity(5, 5)
68+
69+
assert.False(t, cache.Exist("A"))
70+
71+
cache.Put("A", "Foo")
72+
assert.True(t, cache.Exist("A"))
73+
assert.False(t, cache.Exist("B"))
74+
75+
cache.Put("B", "Bar")
76+
assert.True(t, cache.Exist("B"))
77+
78+
cache.Delete("A")
79+
assert.False(t, cache.Exist("A"))
80+
}
81+
82+
func TestPutIfNotExistSuccess(t *testing.T) {
83+
cache := New(2, nil)
84+
85+
existing, err := cache.PutIfNotExist("A", "Foo")
86+
assert.NoError(t, err)
87+
assert.Equal(t, "Foo", existing)
88+
89+
existing, err = cache.PutIfNotExist("A", "Bar")
90+
assert.NoError(t, err)
91+
assert.Equal(t, "Foo", existing)
92+
93+
assert.Equal(t, "Foo", cache.Get("A"))
94+
}
95+
96+
func TestNoPutInPin(t *testing.T) {
97+
cache := New(2, &Options{
98+
Pin: true,
99+
})
100+
101+
assert.Panics(t, func() {
102+
cache.Put("A", "Foo")
103+
})
104+
}
105+
106+
func TestPinningTTL(t *testing.T) {
107+
cache := New(3, &Options{
108+
Pin: true,
109+
TTL: time.Millisecond * 100,
110+
}).(*lru)
111+
112+
currentTime := time.UnixMilli(123)
113+
cache.now = func() time.Time { return currentTime }
114+
115+
// Add two elements so the cache is full
116+
_, err := cache.PutIfNotExist("A", "Foo")
117+
require.NoError(t, err)
118+
_, err = cache.PutIfNotExist("B", "Bar")
119+
require.NoError(t, err)
120+
121+
// Release B so it can be evicted
122+
cache.Release("B")
123+
124+
currentTime = currentTime.Add(time.Millisecond * 300)
125+
assert.Equal(t, "Foo", cache.Get("A"))
126+
127+
// B can be evicted, so we can add another element
128+
_, err = cache.PutIfNotExist("C", "Baz")
129+
require.NoError(t, err)
130+
131+
// A cannot be evicted since it's pinned, so we can't add another element
132+
_, err = cache.PutIfNotExist("D", "Qux")
133+
assert.ErrorContains(t, err, "Cache capacity is fully occupied with pinned elements")
134+
135+
// B is gone
136+
assert.Nil(t, cache.Get("B"))
137+
}
138+
65139
func TestLRUWithTTL(t *testing.T) {
66140
cache := New(5, &Options{
67141
TTL: time.Millisecond * 100,

0 commit comments

Comments
 (0)