-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathttlcache_test.go
113 lines (88 loc) · 1.81 KB
/
ttlcache_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
package ttlcache
import (
"testing"
"time"
)
func TestCache_GetSet(t *testing.T) {
ttl := 2 * time.Millisecond
key := StringKey("key")
value := "value"
c := New(time.Millisecond)
c.Set(key, value, ttl)
val, ok := c.Get(key)
if !ok {
t.Error("storage missed expected value")
}
v, ok2 := val.(string)
if !ok2 {
t.Error("type assertion failed")
}
if v != value {
t.Errorf("incorret value: got: %v expected: %v", v, value)
}
time.Sleep(4 * time.Millisecond)
_, ok3 := c.Get(key)
if ok3 {
t.Error("record was not cleaned up")
}
}
func TestCache_Delete(t *testing.T) {
key := StringKey("key")
value := "value"
c := New(time.Second) // Cleanup should not be triggered.
c.Set(key, value, 0)
val, ok := c.Get(key)
if !ok {
t.Error("storage missed expected value")
}
v, ok2 := val.(string)
if !ok2 {
t.Error("type assertion failed")
}
if v != value {
t.Errorf("incorret value: got: %v expected: %v", v, value)
}
c.Delete(key)
_, ok3 := c.Get(key)
if ok3 {
t.Error("record was not removed")
}
}
func TestCache_Clear(t *testing.T) {
c := New(time.Millisecond)
for i := 1; i < 5; i++ {
c.Set(IntKey(i), i, 0)
}
c.Clear()
for i := 1; i < 5; i++ {
_, ok := c.Get(IntKey(i))
if ok {
t.Error("Storage was not cleaned up")
}
}
// Verify that the cleanup manager is still running
ttl := 2 * time.Millisecond
key := StringKey("key")
value := "value"
c.Set(key, value, ttl)
time.Sleep(4 * time.Millisecond)
_, ok := c.Get(key)
if ok {
t.Error("record was not cleaned up")
}
}
func TestClose(t *testing.T) {
c := New(time.Second)
c.Set(IntKey(1), 1, 0)
c.Set(IntKey(2), 2, 0)
c.Set(IntKey(3), 3, 0)
c.Set(IntKey(4), 4, 0)
err := c.Close()
if err != nil {
t.Error("Unexpected error")
}
_, ok := c.Get(IntKey(1))
if ok {
t.Error("Storage was not cleaned up")
}
}