package util import ( "testing" "time" ) func TestCacheEvictsInInsertionOrder(t *testing.T) { c := NewCache[string, int](2, 0) c.Set("a", 1) c.Set("b", 2) c.Set("c", 3) if _, ok := c.Get("a"); ok { t.Error("oldest entry was not evicted") } if v, ok := c.Get("c"); !ok || v != 3 { t.Error("newest entry missing") } if c.Len() != 2 { t.Errorf("cache holds %d entries, want 2", c.Len()) } } func TestCacheTTLAndDelete(t *testing.T) { c := NewCache[int, string](4, time.Millisecond) c.Set(1, "x") if _, ok := c.Get(1); !ok { t.Fatal("fresh entry missing") } time.Sleep(2 * time.Millisecond) if _, ok := c.Get(1); ok { t.Error("expired entry was returned") } if c.Len() != 0 { t.Error("expired entry was not dropped") } c2 := NewCache[int, string](4, 0) c2.Set(1, "x") c2.Delete(1) if _, ok := c2.Get(1); ok { t.Error("deleted entry was returned") } c2.SetTTL(3, "short", time.Millisecond) time.Sleep(2 * time.Millisecond) if _, ok := c2.Get(3); ok { t.Error("per-entry ttl was ignored") } c2.Set(2, "y") c2.Set(2, "z") if v, _ := c2.Get(2); v != "z" { t.Errorf("Set did not refresh the value, got %q", v) } } func TestCacheEvictsByBytes(t *testing.T) { c := NewSizedCache[string, string](10, 5, 0, func(s string) int64 { return int64(len(s)) }) c.Set("a", "xx") c.Set("b", "yy") c.Set("c", "zz") if _, ok := c.Get("a"); ok { t.Error("oldest entry was not evicted by the byte limit") } if _, ok := c.Get("b"); !ok { t.Error("entry within the byte limit was evicted") } c.Set("big", "123456") if _, ok := c.Get("big"); ok { t.Error("entry larger than the byte limit was cached") } c.Set("b", "12345") if c.Len() != 1 { t.Errorf("cache holds %d entries, want 1", c.Len()) } }