2017-06-13 12:39:10 -07:00
|
|
|
package cache
|
|
|
|
|
|
2021-04-05 15:45:28 +02:00
|
|
|
import (
|
|
|
|
|
"testing"
|
|
|
|
|
)
|
2017-06-13 12:39:10 -07:00
|
|
|
|
|
|
|
|
func TestCacheAddAndGet(t *testing.T) {
|
2019-07-19 05:19:03 -04:00
|
|
|
const N = shardSize * 4
|
|
|
|
|
c := New(N)
|
2017-06-13 12:39:10 -07:00
|
|
|
c.Add(1, 1)
|
|
|
|
|
|
|
|
|
|
if _, found := c.Get(1); !found {
|
|
|
|
|
t.Fatal("Failed to find inserted record")
|
|
|
|
|
}
|
2019-07-19 05:19:03 -04:00
|
|
|
|
|
|
|
|
for i := 0; i < N; i++ {
|
|
|
|
|
c.Add(uint64(i), 1)
|
|
|
|
|
}
|
|
|
|
|
for i := 0; i < N; i++ {
|
|
|
|
|
c.Add(uint64(i), 1)
|
|
|
|
|
if c.Len() != N {
|
|
|
|
|
t.Fatal("A item was unnecessarily evicted from the cache")
|
|
|
|
|
}
|
|
|
|
|
}
|
2017-06-13 12:39:10 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestCacheLen(t *testing.T) {
|
|
|
|
|
c := New(4)
|
|
|
|
|
|
|
|
|
|
c.Add(1, 1)
|
|
|
|
|
if l := c.Len(); l != 1 {
|
|
|
|
|
t.Fatalf("Cache size should %d, got %d", 1, l)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
c.Add(1, 1)
|
|
|
|
|
if l := c.Len(); l != 1 {
|
|
|
|
|
t.Fatalf("Cache size should %d, got %d", 1, l)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
c.Add(2, 2)
|
|
|
|
|
if l := c.Len(); l != 2 {
|
|
|
|
|
t.Fatalf("Cache size should %d, got %d", 2, l)
|
|
|
|
|
}
|
|
|
|
|
}
|
2017-10-23 17:24:48 +01:00
|
|
|
|
2019-07-19 05:19:03 -04:00
|
|
|
func TestCacheSharding(t *testing.T) {
|
|
|
|
|
c := New(shardSize)
|
|
|
|
|
for i := 0; i < shardSize*2; i++ {
|
|
|
|
|
c.Add(uint64(i), 1)
|
|
|
|
|
}
|
|
|
|
|
for i, s := range c.shards {
|
|
|
|
|
if s.Len() == 0 {
|
|
|
|
|
t.Errorf("Failed to populate shard: %d", i)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2021-04-05 15:45:28 +02:00
|
|
|
func TestCacheWalk(t *testing.T) {
|
|
|
|
|
c := New(10)
|
|
|
|
|
exp := make([]int, 10*2)
|
|
|
|
|
for i := 0; i < 10*2; i++ {
|
|
|
|
|
c.Add(uint64(i), 1)
|
|
|
|
|
exp[i] = 1
|
|
|
|
|
}
|
|
|
|
|
got := make([]int, 10*2)
|
|
|
|
|
c.Walk(func(items map[uint64]interface{}, key uint64) bool {
|
|
|
|
|
got[key] = items[key].(int)
|
|
|
|
|
return true
|
|
|
|
|
})
|
|
|
|
|
for i := range exp {
|
|
|
|
|
if exp[i] != got[i] {
|
|
|
|
|
t.Errorf("Expected %d, got %d", exp[i], got[i])
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2017-10-23 17:24:48 +01:00
|
|
|
func BenchmarkCache(b *testing.B) {
|
|
|
|
|
b.ReportAllocs()
|
|
|
|
|
|
|
|
|
|
c := New(4)
|
|
|
|
|
for n := 0; n < b.N; n++ {
|
|
|
|
|
c.Add(1, 1)
|
|
|
|
|
c.Get(1)
|
|
|
|
|
}
|
|
|
|
|
}
|