forked from microsoftarchive/ttlcache
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache_test.go
102 lines (87 loc) · 1.99 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
package ttlcache
import (
"testing"
"time"
)
func TestGet(t *testing.T) {
cache := &Cache{
ttl: time.Second,
items: map[string]*Item{},
}
data, exists := cache.Get("hello")
if exists || data != nil {
t.Errorf("Expected empty cache to return no data")
}
cache.Set("hello", []byte("world"))
data, exists = cache.Get("hello")
if !exists {
t.Errorf("Expected cache to return data for `hello`")
}
if string(data) != "world" {
t.Errorf("Expected cache to return `world` for `hello`")
}
}
func TestEvict(t *testing.T) {
cache := &Cache{
ttl: time.Second,
items: map[string]*Item{},
}
cache.Set("hello", []byte("world"))
cache.Evict("hello")
_, exists := cache.Get("hello")
if exists {
t.Errorf("Expected cache item to be evicted for key `hello`")
}
}
func TestExpiration(t *testing.T) {
cache := &Cache{
ttl: time.Second,
items: map[string]*Item{},
}
cache.Set("x", []byte("1"))
cache.Set("y", []byte("z"))
cache.Set("z", []byte("3"))
cache.startEvictionTimer()
count := cache.Count()
if count != 3 {
t.Errorf("Expected cache to contain 3 items")
}
<-time.After(500 * time.Millisecond)
cache.Lock()
cache.items["y"].touch(time.Second)
item, exists := cache.items["x"]
cache.Unlock()
if !exists || string(item.data) != "1" || item.expired() {
t.Errorf("Expected `x` to not have expired after 200ms")
}
<-time.After(time.Second)
cache.RLock()
_, exists = cache.items["x"]
if exists {
t.Errorf("Expected `x` to have expired")
}
_, exists = cache.items["z"]
if exists {
t.Errorf("Expected `z` to have expired")
}
_, exists = cache.items["y"]
if !exists {
t.Errorf("Expected `y` to not have expired")
}
cache.RUnlock()
count = cache.Count()
if count != 1 {
t.Errorf("Expected cache to contain 1 item")
}
<-time.After(600 * time.Millisecond)
cache.RLock()
_, exists = cache.items["y"]
if exists {
t.Errorf("Expected `y` to have expired")
}
cache.RUnlock()
count = cache.Count()
if count != 0 {
t.Errorf("Expected cache to be empty")
}
}