github.com/coyove/common@v0.0.0-20240403014525-f70e643f9de8/lru/lru_test.go (about) 1 package lru 2 3 import ( 4 "strconv" 5 "testing" 6 ) 7 8 func TestCache_Add(t *testing.T) { 9 c := NewCache(10) 10 11 for i := 0; i < 10; i++ { 12 c.Add("key"+strconv.Itoa(i), "value"+strconv.Itoa(i)) 13 } 14 15 for i := 0; i < 10; i++ { 16 v, _ := c.Get("key" + strconv.Itoa(i)) 17 if v.(string) != "value"+strconv.Itoa(i) { 18 t.Error("Add failed") 19 } 20 } 21 22 c.Add("key10", "value10") 23 if _, ok := c.Get("key0"); ok { 24 t.Error("key0 should be removed") 25 } 26 27 c.AddWeight("bigkey", "", 10) 28 for i := 0; i <= 10; i++ { 29 _, ok := c.Get("key" + strconv.Itoa(i)) 30 if ok { 31 t.Errorf("key%d should be removed", i) 32 } 33 } 34 35 if c.Weight() != 10 { 36 t.Error("cache now should weight 10") 37 } 38 39 c.Add("key11", "") 40 if _, ok := c.Get("bigkey"); ok { 41 t.Error("bigkey should be removed") 42 } 43 44 if c.Len() != 1 { 45 t.Error("cache now should contain only one element") 46 } 47 48 if c.AddWeight("reallybigkey", "", 100) != ErrWeightTooBig { 49 t.Error("how can you add a key this big?") 50 } 51 52 if c.Len() != 1 || c.Weight() != 1 { 53 t.Error("cache now should contain only one element") 54 } 55 56 // add 6 keys 57 for i := 0; i < 6; i++ { 58 c.Add("key"+strconv.Itoa(i), "value"+strconv.Itoa(i)) 59 } 60 61 // key5, key4, key3, key2, key1, key0, key11 62 c.AddWeight("keyFive", "", 5) 63 // keyFive, key5, key4, key3, key2, key1 64 65 if _, ok := c.Get("key4"); !ok { 66 t.Error("key4 should exist") 67 } 68 69 if _, ok := c.Get("key11"); ok { 70 t.Error("key11 should not exist") 71 } 72 73 c.AddWeight("keyFive", "", 6) 74 75 if _, ok := c.Get("key1"); ok { 76 t.Error("key1 should not exist") 77 } 78 79 c.AddWeight("keyFive", "", 5) 80 c.AddWeight("keyX", "", 1) 81 // keyX, keyFive, key5, key4, key3, key2 82 if _, ok := c.Get("key2"); !ok { 83 t.Error("key2 should exist") 84 } 85 86 c.AddWeight("keyFive", "", 10) 87 if c.Len() != 1 || c.Weight() != 10 { 88 t.Error("cache now should contain only one element", c.Len(), c.Weight()) 89 } 90 91 if _, ok := c.Get("keyX"); ok { 92 t.Error("keyX should not exist") 93 } 94 }