github.com/hcolde/cache@v0.0.0-20210313054632-9cc2efb53741/cache_test.go (about) 1 // Copyright (c) 2021 hcolde. 2 // https://github.com/hcolde/cache. 3 // Use of this source code is governed by a MIT license found in the LICENSE file. 4 5 package cache 6 7 import ( 8 "context" 9 "math/rand" 10 "strconv" 11 "testing" 12 "time" 13 ) 14 15 func newCache(size uint64) (*Cache, error) { 16 opt := Options{ 17 MaxSize: size, 18 RefreshTTL: true, 19 } 20 21 return New(context.Background(), opt) 22 } 23 24 func TestCache(t *testing.T) { 25 c, err := newCache(2) 26 if err != nil { 27 t.Fatal(err) 28 } 29 30 v := c.Get("a") 31 if v != nil { 32 t.Fatalf("get value %v but not set", v) 33 } 34 35 c.Set("a", 1, 2 * time.Second) 36 c.Set("b", 2, 2 * time.Second) 37 38 v = c.Get("a") 39 if v != 1 { 40 t.Fatalf("%v is not equal 1", v) 41 } 42 43 v = c.Get("b") 44 if v != 2 { 45 t.Fatalf("%v is not equal 1", v) 46 } 47 48 t.Log("test success") 49 } 50 51 func BenchmarkCache_Set(b *testing.B) { 52 n := b.N 53 c, err := newCache(uint64(n)) 54 if err != nil { 55 b.Fatal(err) 56 } 57 58 m := make(map[string]int) 59 60 for i := 0; i < n; i++ { 61 k := strconv.Itoa(i) 62 c.Set(k, i, 0) 63 m[k] = i 64 } 65 66 for i := 0; i < n; i++ { 67 k := strconv.Itoa(i) 68 v1 := m[k] 69 v2 := c.Get(k) 70 if v1 != v2 { 71 b.Fatalf("%v is not equal %v", v1, v2) 72 } 73 } 74 75 b.Logf("Set test success(bench N:%v)", n) 76 } 77 78 func BenchmarkCache_SetOnPool(b *testing.B) { 79 n := 10000 80 c, err := newCache(uint64(n)) 81 if err != nil { 82 b.Fatal(err) 83 } 84 85 m := make(map[string]int) 86 r := rand.New(rand.NewSource(time.Now().UnixNano())) 87 num := r.Intn(n) 88 89 for i := 0; i < n; i++ { 90 k := strconv.Itoa(i) 91 if i == num { 92 c.Set(k, i, 1000 * time.Millisecond) 93 continue 94 } 95 m[k] = i 96 c.Set(k, i, 0) 97 } 98 99 time.Sleep(1 * time.Second) 100 for i := 0; i < n; i++ { 101 k := strconv.Itoa(i) 102 if i == num { 103 if c.Get(k) != nil { 104 b.Fatal("timed remove failed") 105 } 106 continue 107 } 108 109 v1 := m[k] 110 v2 := c.Get(k) 111 if v1 != v2 { 112 b.Fatalf("%v is not equal %v", v1, v2) 113 } 114 } 115 116 c.Set("a", "aaa", 0) 117 if c.ring[num] != "a" { 118 b.Fatal("cache index pool not malfunction") 119 } 120 121 if c.Get("a") != "aaa" { 122 b.Fatal("value error") 123 } 124 125 b.Logf("Set on pool test success(bench N:%v)", n) 126 }