Files
h/lru/lru_test.go
2024-05-08 18:55:56 +03:00

101 lines
2.1 KiB
Go

package lru
import (
"fmt"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestTtl(t *testing.T) {
cache := New[int](1)
cache.Set("first", 1, 500*time.Millisecond)
value, ok := cache.Get("first")
assert.True(t, ok)
assert.Equal(t, 1, value)
time.Sleep(600 * time.Millisecond)
value, ok = cache.Get("first")
assert.False(t, ok)
assert.Equal(t, 0, value)
}
func TestEvictFirst(t *testing.T) {
cache := New[int](2)
assert.False(t, cache.Set("first", 1, 500*time.Millisecond))
assert.False(t, cache.Set("second", 2, 500*time.Millisecond))
assert.True(t, cache.Set("third", 3, 500*time.Millisecond))
_, ok := cache.Get("first")
assert.False(t, ok)
}
func TestEvictExpired(t *testing.T) {
cache := New[int](2)
assert.False(t, cache.Set("first", 1, 1000*time.Millisecond))
assert.False(t, cache.Set("second", 2, 100*time.Millisecond))
time.Sleep(200 * time.Millisecond)
assert.True(t, cache.Set("third", 3, 1000*time.Millisecond))
var ok bool
_, ok = cache.Get("first")
assert.True(t, ok)
_, ok = cache.Get("third")
assert.True(t, ok)
_, ok = cache.Get("second")
assert.False(t, ok)
}
func TestSetExisted(t *testing.T) {
cache := New[int](2)
assert.False(t, cache.Set("first", 1, 200*time.Millisecond))
assert.False(t, cache.Set("second", 2, 500*time.Millisecond))
time.Sleep(100 * time.Millisecond)
assert.False(t, cache.Set("first", 11, 1000*time.Millisecond))
assert.True(t, cache.Set("third", 3, 1000*time.Millisecond))
value, ok := cache.Get("first") // exists with updated ttl
assert.True(t, ok)
assert.Equal(t, 11, value)
_, ok = cache.Get("third")
assert.True(t, ok)
_, ok = cache.Get("second") // evicted
assert.False(t, ok)
}
func TestDummy(t *testing.T) { // for coverage 100% coverage
cache := New[int](0)
cache.evict()
}
func Benchmark(b *testing.B) {
cache := New[string](10)
ttl := 1000 * time.Millisecond
b.Run("Set", func(b *testing.B) {
for i := 0; i < b.N; i++ {
cache.Set(fmt.Sprintf("item:%d", i), fmt.Sprintf("item:%d", i), ttl)
}
})
b.Run("Get", func(b *testing.B) {
for i := 0; i < b.N; i++ {
value, ok := cache.Get(fmt.Sprintf("item:%d", i))
if ok {
_ = value
}
}
})
}