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.

118 lines
2.4 KiB

package cache
import (
"os"
"path/filepath"
"reflect"
"testing"
)
var lruTestCases = []kv{
{"a", "b"},
{"b", "c"},
{"c", "d"},
{"d", "e"},
{"e", "a"},
}
func testLRU(t *testing.T, c Backend) {
var (
ok bool
err error
)
iterTest := make(map[interface{}]interface{})
for i, testCase := range lruTestCases {
c.Set(testCase.Key, testCase.Value)
iterTest[testCase.Key] = testCase.Value
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 != (i + 1) {
t.Fatalf("size is %d, expected %d", l, i+1)
}
}
c.Iter(func(key, value interface{}) {
if !reflect.DeepEqual(value, iterTest[key]) {
t.Fatalf("expected %v, got %v", iterTest[key], value)
}
})
// Set already existing entry
c.Set("e", "e")
if ok, err = c.Replace("e", "f"); err != nil {
t.Fatalf("replace failed: %v", err)
} else if !ok {
t.Fatal("key missing")
}
if ok, err = c.Replace("f", "g"); err != nil {
t.Fatalf("replace failed: %v", err)
} else if ok {
t.Fatal("replace of missing entry returned true")
}
if ok, err = c.Contains("e"); err != nil {
t.Fatalf("contains failed: %v", err)
} else if !ok {
t.Fatal("key missing")
}
if ok, err = c.Delete("e"); err != nil {
t.Fatalf("delete failed: %v", err)
} else if !ok {
t.Fatal("delete failed")
}
if ok, err = c.Delete("e"); err != nil {
t.Fatalf("delete failed: %v", err)
} else if ok {
t.Fatal("delete of missing entry returned true")
}
if _, ok, err = c.Get("missing"); err != nil {
t.Fatalf("get failed: %v", err)
} else if ok {
t.Fatal("get returned true for missing key")
}
}
func testLRUOverflow(t *testing.T, c Backend) {
for _, testCase := range lruTestCases {
c.Set(testCase.Key, testCase.Value)
}
if l := c.Len(); l != 3 {
t.Fatalf("size is %d, expected 3", l)
}
}
func TestLRU(t *testing.T) {
t.Run("MemoryLRU", func(t *testing.T) {
testLRU(t, NewMemoryLRU(5))
testLRUOverflow(t, NewMemoryLRU(3))
})
t.Run("DiskLRU", func(t *testing.T) {
p := filepath.Join("testdata", "lru")
d, err := NewDiskLRU(p, 0750, 5)
if err != nil {
t.Fatal(err)
}
testLRU(t, d)
os.RemoveAll(p)
})
}
var (
_ Backend = (*MemoryLRU)(nil)
_ Backend = (*DiskLRU)(nil)
)