1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| package lru
import ( "reflect" "testing" )
type String string
func (s String) Len() int { return len(s) }
func TestGet(t *testing.T) { c := New(0, nil) c.Add("key1", String("val1")) if v, ok := c.Get("key1"); !ok string(v.(String)) != "val1" { t.Fatalf("cache hit key1=val1 failed") } if _, ok := c.Get("key2"); ok { t.Fatalf("cache miss key2 failed") } }
func TestRemoveOldEle(t *testing.T) { k1, k2, k3 := "key1", "key2", "key3" v1, v2, v3 := "val1", "val2", "val3" maxBytes := len(k1 + k2 + v1 + v2) c := New(int64(maxBytes), nil) c.Add(k1, String(v1)) c.Add(k2, String(v2)) c.Add(k3, String(v3))
if _, ok := c.Get("key1"); ok c.Len() != 2 { t.Fatalf("removeoldele key1 failed") } }
func TestOnRemoved(t *testing.T) { keys := make([]string, 0) callback := func(key string, value Value) { keys = append(keys, key) } c := New(int64(10), callback) c.Add("k1", String("v1")) c.Add("k2", String("v2")) c.Add("k3", String("v3")) c.Add("k4", String("k4"))
expect := []string{"k1", "k2"} if !reflect.DeepEqual(expect, keys) { t.Fatalf("call onremoved failed, expect keys equals to %s, get %s", expect, keys) } }
|