cache_test.go
| 1 | package util |
| 2 | |
| 3 | import ( |
| 4 | "testing" |
| 5 | "time" |
| 6 | ) |
| 7 | |
| 8 | func TestCacheEvictsInInsertionOrder(t *testing.T) { |
| 9 | c := NewCache[string, int](2, 0) |
| 10 | c.Set("a", 1) |
| 11 | c.Set("b", 2) |
| 12 | c.Set("c", 3) |
| 13 | if _, ok := c.Get("a"); ok { |
| 14 | t.Error("oldest entry was not evicted") |
| 15 | } |
| 16 | if v, ok := c.Get("c"); !ok || v != 3 { |
| 17 | t.Error("newest entry missing") |
| 18 | } |
| 19 | if c.Len() != 2 { |
| 20 | t.Errorf("cache holds %d entries, want 2", c.Len()) |
| 21 | } |
| 22 | } |
| 23 | |
| 24 | func TestCacheTTLAndDelete(t *testing.T) { |
| 25 | c := NewCache[int, string](4, time.Millisecond) |
| 26 | c.Set(1, "x") |
| 27 | if _, ok := c.Get(1); !ok { |
| 28 | t.Fatal("fresh entry missing") |
| 29 | } |
| 30 | time.Sleep(2 * time.Millisecond) |
| 31 | if _, ok := c.Get(1); ok { |
| 32 | t.Error("expired entry was returned") |
| 33 | } |
| 34 | if c.Len() != 0 { |
| 35 | t.Error("expired entry was not dropped") |
| 36 | } |
| 37 | |
| 38 | c2 := NewCache[int, string](4, 0) |
| 39 | c2.Set(1, "x") |
| 40 | c2.Delete(1) |
| 41 | if _, ok := c2.Get(1); ok { |
| 42 | t.Error("deleted entry was returned") |
| 43 | } |
| 44 | c2.SetTTL(3, "short", time.Millisecond) |
| 45 | time.Sleep(2 * time.Millisecond) |
| 46 | if _, ok := c2.Get(3); ok { |
| 47 | t.Error("per-entry ttl was ignored") |
| 48 | } |
| 49 | c2.Set(2, "y") |
| 50 | c2.Set(2, "z") |
| 51 | if v, _ := c2.Get(2); v != "z" { |
| 52 | t.Errorf("Set did not refresh the value, got %q", v) |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | func TestCacheEvictsByBytes(t *testing.T) { |
| 57 | c := NewSizedCache[string, string](10, 5, 0, func(s string) int64 { return int64(len(s)) }) |
| 58 | c.Set("a", "xx") |
| 59 | c.Set("b", "yy") |
| 60 | c.Set("c", "zz") |
| 61 | if _, ok := c.Get("a"); ok { |
| 62 | t.Error("oldest entry was not evicted by the byte limit") |
| 63 | } |
| 64 | if _, ok := c.Get("b"); !ok { |
| 65 | t.Error("entry within the byte limit was evicted") |
| 66 | } |
| 67 | c.Set("big", "123456") |
| 68 | if _, ok := c.Get("big"); ok { |
| 69 | t.Error("entry larger than the byte limit was cached") |
| 70 | } |
| 71 | c.Set("b", "12345") |
| 72 | if c.Len() != 1 { |
| 73 | t.Errorf("cache holds %d entries, want 1", c.Len()) |
| 74 | } |
| 75 | } |
| 76 |