-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache_test.go
133 lines (110 loc) · 2.22 KB
/
cache_test.go
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
package fscache
import (
"bytes"
"io/ioutil"
"math/rand"
"os"
"testing"
"time"
)
func randBytes(n int) []byte {
rst := make([]byte, n)
_, err := rand.Read(rst)
if err != nil {
panic(err)
}
return rst
}
func TestMain(m *testing.M) {
rand.Seed(time.Now().UnixNano())
m.Run()
}
func newCache() (cache *Cache, cancel func()) {
cacheDir, err := ioutil.TempDir("", "fscache")
if err != nil {
panic(err)
}
gcStopCh := make(chan struct{})
cacheI, err := New(
WithCacheDir(cacheDir),
WithMaxBytes(3*1024),
WithGcInterval(2*time.Second),
WithGcStopCh(gcStopCh),
)
if err != nil {
panic(err)
}
cache = cacheI.(*Cache)
cancel = func() {
close(gcStopCh)
if err := os.RemoveAll(cacheDir); err != nil {
panic(err)
}
}
return
}
func TestSetHasGet(t *testing.T) {
cache, cancel := newCache()
defer cancel()
key := "key"
val := randBytes(1024)
if err := cache.Set(key, val); err != nil {
panic(err)
}
valFromCache, err := cache.Get(key, nil)
if err != nil {
panic(err)
}
if !bytes.Equal(val, valFromCache) {
t.Errorf("valFromCache not equals to val")
}
val = randBytes(1024)
if err := cache.Set(key, val); err != nil {
panic(err)
}
valFromCache, err = cache.Get(key, nil)
if err != nil {
panic(err)
}
if !bytes.Equal(val, valFromCache) {
t.Errorf("valFromCache not equals to val")
}
_, err = cache.Get("notFound", nil)
if err != ErrNotFound {
t.Errorf("expected not found error")
}
if !cache.Has(key) {
t.Errorf("expected Has() returning true")
}
if cache.Has("notFound") {
t.Errorf("expected Has() returning false")
}
}
func TestGc(t *testing.T) {
cache, cancel := newCache()
defer cancel()
cm := map[string][]byte{
"key1": randBytes(3 * 1024),
"key2": randBytes(1024),
"key3": randBytes(1024),
}
for key, val := range cm {
if err := cache.Set(key, val); err != nil {
panic(err)
}
}
// to update atime of key1
if _, err := cache.Get("key1", nil); err != nil {
panic(err)
}
time.Sleep(3 * time.Second)
if !cache.Has("key1") {
t.Errorf("expected Has() returning true for key1")
}
if cache.Has("key2") {
t.Errorf("expected Has() returning false for key2")
}
if cache.Has("key3") {
t.Errorf("expected Has() returning false for key3")
}
}