-
Notifications
You must be signed in to change notification settings - Fork 0
/
gocache_test.go
106 lines (87 loc) · 2.31 KB
/
gocache_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
package gocache
import (
"testing"
"time"
)
func TestCache_Get(t *testing.T) {
cache := NewCache(time.Second)
cache.Set("key", "value", time.Second)
value, found := cache.Get("key")
if !found {
t.Errorf("Expected key 'key' to be found")
}
if value != "value" {
t.Errorf("Expected value 'value', got %v", value)
}
// Test if it really expired
time.Sleep(time.Second * 2)
value, found = cache.Get("key")
if found || value != nil {
t.Errorf("Expected key 'key' to be expired and not found")
}
// Test a non-existent key
value, found = cache.Get("nonexistent")
if found || value != nil {
t.Errorf("Expected non-existent key to not be found")
}
}
func TestCache_Set(t *testing.T) {
cache := NewCache(time.Second)
// Test setting a key-value pair
cache.Set("key", "value", time.Minute)
// Retrieve the value to verify
value, found := cache.Get("key")
if !found {
t.Errorf("Expected key 'key' to be found")
}
if value != "value" {
t.Errorf("Expected value 'value', got %v", value)
}
// Test updating an existing key
cache.Set("key", "newvalue", time.Minute)
// Retrieve the value to verify the update
value, found = cache.Get("key")
if !found {
t.Errorf("Expected key 'key' to be found")
}
if value != "newvalue" {
t.Errorf("Expected value 'newvalue', got %v", value)
}
}
func TestCache_Delete(t *testing.T) {
cache := NewCache(time.Second)
cache.Set("key", "value", time.Minute)
// Delete an existing key
cache.Delete("key")
// Verify the key is no longer found
_, found := cache.Get("key")
if found {
t.Errorf("Expected key 'key' to be deleted")
}
// Delete a non-existent key
cache.Delete("nonexistent")
}
func TestCache_Clear(t *testing.T) {
cache := NewCache(time.Second)
cache.Set("key1", "value1", time.Minute)
cache.Set("key2", "value2", time.Minute)
// Clear the cache
cache.Clear()
// Verify the cache is empty
if size := cache.Size(); size != 0 {
t.Errorf("Expected cache size 0, got %d", size)
}
}
func TestCache_Size(t *testing.T) {
cache := NewCache(time.Second)
// Empty cache
if size := cache.Size(); size != 0 {
t.Errorf("Expected cache size 0, got %d", size)
}
// Non-empty cache
cache.Set("key1", "value1", time.Minute)
cache.Set("key2", "value2", time.Minute)
if size := cache.Size(); size != 2 {
t.Errorf("Expected cache size 2, got %d", size)
}
}