48 lines
1.0 KiB
Go
48 lines
1.0 KiB
Go
package cache
|
|
|
|
import (
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
func TestGetPut(t *testing.T) {
|
|
c := New[string, int](2, time.Minute)
|
|
if _, ok := c.Get("a"); ok {
|
|
t.Fatal("empty cache returned a hit")
|
|
}
|
|
c.Put("a", 1)
|
|
got, ok := c.Get("a")
|
|
if !ok || got != 1 {
|
|
t.Fatalf("get after put: ok=%v val=%v", ok, got)
|
|
}
|
|
}
|
|
|
|
func TestTTL(t *testing.T) {
|
|
c := New[string, int](8, 10*time.Millisecond)
|
|
c.Put("a", 1)
|
|
if _, ok := c.Get("a"); !ok {
|
|
t.Fatal("fresh entry missing")
|
|
}
|
|
time.Sleep(20 * time.Millisecond)
|
|
if _, ok := c.Get("a"); ok {
|
|
t.Fatal("expired entry still served")
|
|
}
|
|
}
|
|
|
|
func TestLRUEviction(t *testing.T) {
|
|
c := New[string, int](2, time.Minute)
|
|
c.Put("a", 1)
|
|
c.Put("b", 2)
|
|
_, _ = c.Get("a") // make "a" most-recently-used so "b" is the eviction victim
|
|
c.Put("c", 3) // exceeds cap → evict LRU ("b")
|
|
if _, ok := c.Get("b"); ok {
|
|
t.Fatal("LRU victim 'b' not evicted")
|
|
}
|
|
if _, ok := c.Get("a"); !ok {
|
|
t.Fatal("recently-used 'a' was evicted")
|
|
}
|
|
if _, ok := c.Get("c"); !ok {
|
|
t.Fatal("freshly-put 'c' missing")
|
|
}
|
|
}
|