Package cache contains caching functions.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

102 lines
2.3 KiB

package cache
import (
"fmt"
"reflect"
"strings"
"testing"
"time"
)
func testCache(t *testing.T, c Cache) {
var (
ok bool
err error
)
iterTest := make(map[interface{}]interface{})
for _, testCase := range kvTestCases {
c.Set(testCase.Key, testCase.Value)
iterTest[testCase.Key] = testCase.Value
if ok, err = c.Contains(testCase.Key); err != nil {
t.Fatalf("contains failed: %v", err)
} else if !ok {
t.Fatalf("key %v missing", testCase.Key)
}
var value interface{}
if value, ok, err = c.Get(testCase.Key); err != nil {
t.Fatalf("get failed: %v", err)
} else if !ok {
t.Fatalf("key %v missing", testCase.Key)
} else if !reflect.DeepEqual(value, testCase.Value) {
t.Fatalf("corrupt, expected %+v, got %+v", testCase.Value, value)
}
}
if l := c.Len(); l != len(kvTestCases) {
t.Fatalf("corrupt, expected %d, got %d length", len(kvTestCases), l)
}
}
func TestCache(t *testing.T) {
t.Run("SimpleCache", func(t *testing.T) {
testCache(t, NewCache())
})
t.Run("TTLCache", func(t *testing.T) {
c := NewTTLCache(time.Second, time.Millisecond*100)
defer c.Stop()
testCache(t, c)
})
}
func TestTTLCache(t *testing.T) {
var backends = []Backend{
NewMemoryKV(),
NewMemoryLRU(1),
}
for _, backend := range backends {
t.Run(strings.SplitN(fmt.Sprintf("%T", backend), ".", 2)[1], func(t *testing.T) {
c := NewTTLCache(time.Second, time.Millisecond*100)
c.Backend = backend
defer c.Stop()
c.Set("foo", "bar")
if l := c.Len(); l != 1 {
t.Fatalf("len returned %d, expected 1", l)
}
if v, ok, err := c.Get("foo"); err != nil {
t.Fatalf("get failed: %v", err)
} else if !ok {
t.Fatal("get failed")
} else {
if s, ok := v.(string); !ok {
t.Fatalf("get returned %T, expected string", v)
} else if s != "bar" {
t.Fatalf("get returned %s, expected \"bar\"", s)
}
}
time.Sleep(time.Second)
if ok, err := c.Contains("foo"); err != nil {
t.Fatalf("contains failed: %v", err)
} else if ok {
t.Fatal("contains failed, it should return false")
}
if _, ok, err := c.Get("foo"); err != nil {
t.Fatalf("get failed: %v", err)
} else if ok {
t.Fatal("get failed, it should return false")
}
if l := c.Len(); l != 0 {
t.Fatalf("len returned %d, expected 0", l)
}
})
}
}