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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
|
package cache
import (
"testing"
)
func TestCacheAddAndGet(t *testing.T) {
const N = shardSize * 4
c := New(N)
c.Add(1, 1)
if _, found := c.Get(1); !found {
t.Fatal("Failed to find inserted record")
}
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")
}
}
}
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)
}
}
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)
}
}
}
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])
}
}
}
func BenchmarkCache(b *testing.B) {
b.ReportAllocs()
c := New(4)
for n := 0; n < b.N; n++ {
c.Add(1, 1)
c.Get(1)
}
}
|