cache_test.go
⎇
Raw
1package util
2
3import (
4 "testing"
5 "time"
6)
7
8func 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
24func 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.Set(2, "y")
45 c2.Set(2, "z")
46 if v, _ := c2.Get(2); v != "z" {
47 t.Errorf("Set did not refresh the value, got %q", v)
48 }
49}
50