-
Notifications
You must be signed in to change notification settings - Fork 120
/
item_test.go
112 lines (90 loc) · 2.54 KB
/
item_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
package ttlcache
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func Test_NewItem(t *testing.T) {
item := NewItem("key", 123, time.Hour, false)
require.NotNil(t, item)
assert.Equal(t, "key", item.key)
assert.Equal(t, 123, item.value)
assert.Equal(t, time.Hour, item.ttl)
assert.Equal(t, int64(-1), item.version)
assert.WithinDuration(t, time.Now().Add(time.Hour), item.expiresAt, time.Minute)
}
func Test_Item_update(t *testing.T) {
item := Item[string, string]{
expiresAt: time.Now().Add(-time.Hour),
value: "hello",
version: 0,
}
item.update("test", time.Hour)
assert.Equal(t, "test", item.value)
assert.Equal(t, time.Hour, item.ttl)
assert.Equal(t, int64(1), item.version)
assert.WithinDuration(t, time.Now().Add(time.Hour), item.expiresAt, time.Minute)
item.update("previous ttl", PreviousOrDefaultTTL)
assert.Equal(t, "previous ttl", item.value)
assert.Equal(t, time.Hour, item.ttl)
assert.Equal(t, int64(2), item.version)
assert.WithinDuration(t, time.Now().Add(time.Hour), item.expiresAt, time.Minute)
item.update("hi", NoTTL)
assert.Equal(t, "hi", item.value)
assert.Equal(t, NoTTL, item.ttl)
assert.Equal(t, int64(3), item.version)
assert.Zero(t, item.expiresAt)
}
func Test_Item_touch(t *testing.T) {
var item Item[string, string]
item.touch()
assert.Equal(t, int64(0), item.version)
assert.Zero(t, item.expiresAt)
item.ttl = time.Hour
item.touch()
assert.Equal(t, int64(0), item.version)
assert.WithinDuration(t, time.Now().Add(time.Hour), item.expiresAt, time.Minute)
}
func Test_Item_IsExpired(t *testing.T) {
// no ttl
item := Item[string, string]{
expiresAt: time.Now().Add(-time.Hour),
}
assert.False(t, item.IsExpired())
// expired
item.ttl = time.Hour
assert.True(t, item.IsExpired())
// not expired
item.expiresAt = time.Now().Add(time.Hour)
assert.False(t, item.IsExpired())
}
func Test_Item_Key(t *testing.T) {
item := Item[string, string]{
key: "test",
}
assert.Equal(t, "test", item.Key())
}
func Test_Item_Value(t *testing.T) {
item := Item[string, string]{
value: "test",
}
assert.Equal(t, "test", item.Value())
}
func Test_Item_TTL(t *testing.T) {
item := Item[string, string]{
ttl: time.Hour,
}
assert.Equal(t, time.Hour, item.TTL())
}
func Test_Item_ExpiresAt(t *testing.T) {
now := time.Now()
item := Item[string, string]{
expiresAt: now,
}
assert.Equal(t, now, item.ExpiresAt())
}
func Test_Item_Version(t *testing.T) {
item := Item[string, string]{version: 5}
assert.Equal(t, int64(5), item.Version())
}