github.com/auttaja/go-tlru@v0.0.0-20200823214418-2a1d18ce6d93/cache_test.go (about) 1 package tlru 2 3 import ( 4 "sync" 5 "testing" 6 "time" 7 ) 8 9 func TestCacheGetSet(t *testing.T) { 10 c := NewCache(1, 0, time.Second) 11 c.Set("a", true) 12 r, ok := c.Get("a") 13 if !ok { 14 t.Fatal("should be ok") 15 return 16 } 17 if r != true { 18 t.Fatal("should be true") 19 } 20 } 21 22 func TestCacheMemoryEviction(t *testing.T) { 23 c := NewCache(10, 1, time.Millisecond*3) 24 c.Set("a", true) 25 _, ok := c.Get("a") 26 if !ok { 27 t.Fatal("should be ok") 28 } 29 c.Set("b", true) 30 _, ok = c.Get("b") 31 if !ok { 32 t.Fatal("should be ok") 33 } 34 _, ok = c.Get("a") 35 if ok { 36 t.Fatal("should be not ok") 37 } 38 time.Sleep(time.Millisecond * 5) 39 if c.totalBytes != 0 { 40 t.Fatal("total bytes hasn't reset") 41 } 42 } 43 44 func TestCacheNoItemFound(t *testing.T) { 45 c := NewCache(1, 0, time.Second) 46 c.Set("a", true) 47 _, ok := c.Get("b") 48 if ok { 49 t.Fatal("should be not ok") 50 } 51 } 52 53 func TestCacheExpiry(t *testing.T) { 54 c := NewCache(1, 0, time.Millisecond) 55 c.Set("a", true) 56 time.Sleep(time.Millisecond * 3) 57 _, ok := c.Get("a") 58 if ok { 59 t.Fatal("should be not ok") 60 } 61 } 62 63 func TestCacheFilling(t *testing.T) { 64 c := NewCache(1, 0, time.Second) 65 c.Set("a", true) 66 c.Set("b", true) 67 _, ok := c.Get("a") 68 if ok { 69 t.Fatal("should be not ok") 70 return 71 } 72 r, ok := c.Get("b") 73 if !ok { 74 t.Fatal("should be ok") 75 return 76 } 77 if r != true { 78 t.Fatal("should be true") 79 } 80 } 81 82 func TestCacheRaceConditionsGetSet(t *testing.T) { 83 c := NewCache(2, 0, time.Second) 84 for i := 0; i < 100000; i++ { 85 go func(index int) { 86 c.Set(1, 1) 87 c.Set(index, 1) 88 c.Get(1) 89 }(i) 90 } 91 } 92 93 func BenchmarkCache_Get50000Eviction(b *testing.B) { 94 c := NewCache(10000, 0, time.Second*5) 95 wg := sync.WaitGroup{} 96 wg.Add(9999) 97 for i := 0; i < 9999; i++ { 98 go func(index int) { 99 c.Set(index, 1) 100 wg.Done() 101 }(i) 102 } 103 wg.Wait() 104 c.Set("a", 1) 105 b.ResetTimer() 106 wg.Add(50000) 107 for i := 0; i < 50000; i++ { 108 go func(index int) { 109 defer wg.Done() 110 c.Get("a") 111 }(i) 112 } 113 wg.Wait() 114 } 115 116 func BenchmarkCache_SetIdeal(b *testing.B) { 117 c := NewCache(10000, 0, time.Second) 118 wg := sync.WaitGroup{} 119 wg.Add(9999) 120 for i := 0; i < 9999; i++ { 121 go func(index int) { 122 defer wg.Done() 123 c.Set(index, 1) 124 }(i) 125 } 126 wg.Wait() 127 b.ResetTimer() 128 c.Set("a", 1) 129 } 130 131 func BenchmarkCache_SetUnideal(b *testing.B) { 132 c := NewCache(10000, 0, time.Second) 133 wg := sync.WaitGroup{} 134 wg.Add(5000) 135 for i := 0; i < 5000; i++ { 136 go func(index int) { 137 defer wg.Done() 138 c.Set(index, 1) 139 }(i) 140 } 141 wg.Wait() 142 c.Set("a", 1) 143 wg.Add(4999) 144 for i := 0; i < 4999; i++ { 145 go func(index int) { 146 defer wg.Done() 147 c.Set(index, 1) 148 }(i) 149 } 150 wg.Wait() 151 b.ResetTimer() 152 c.Set("a", 1) 153 }