-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache_test.go
More file actions
106 lines (91 loc) · 2.06 KB
/
Copy pathcache_test.go
File metadata and controls
106 lines (91 loc) · 2.06 KB
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 cache
import (
"context"
"testing"
"time"
)
func TestGetOrSet_BasicHitMiss(t *testing.T) {
c, _ := newTestCache(t)
ctx := context.Background()
factory, count := factoryCounter("hello")
// first call, miss -> factory called
val, err := c.GetOrSet(ctx, "key", factory, WithDuration(5*time.Minute))
if err != nil {
t.Fatal(err)
}
if val != "hello" {
t.Fatalf("got %v, want hello", val)
}
if count.Load() != 1 {
t.Fatalf("factory called %d times, want 1", count.Load())
}
// Second call, hit -> factory NOT called
val, err = c.GetOrSet(ctx, "key", factory, WithDuration(5*time.Minute))
if err != nil {
t.Fatal(err)
}
if val != "hello" {
t.Fatalf("got %v, want hello", val)
}
if count.Load() != 1 {
t.Fatalf("factory called %d times, want 1", count.Load())
}
}
func TestGet_ReturnsFalseOnMiss(t *testing.T) {
c, _ := newTestCache(t)
ctx := context.Background()
val, ok, err := c.Get(ctx, "nonexistent")
if err != nil {
t.Fatal(err)
}
if ok {
t.Fatal("expected ok=false for missing key")
}
if val != nil {
t.Fatalf("expected nil value, got %v", val)
}
}
func TestSet_And_Get(t *testing.T) {
c, _ := newTestCache(t)
ctx := context.Background()
err := c.Set(ctx, "key", "world", WithDuration(5*time.Minute))
if err != nil {
t.Fatal(err)
}
val, ok, err := c.Get(ctx, "key")
if err != nil {
t.Fatal(err)
}
if !ok {
t.Fatal("expected ok=true")
}
if val != "world" {
t.Fatalf("got %v, want world", val)
}
}
func TestDelete_RemovesEntry(t *testing.T) {
c, _ := newTestCache(t)
ctx := context.Background()
c.Set(ctx, "key", "value")
c.Delete(ctx, "key")
_, ok, _ := c.Get(ctx, "key")
if ok {
t.Fatal("expected key to be deleted")
}
}
func TestExpiry_MockClock(t *testing.T) {
c, clk := newTestCache(t)
ctx := context.Background()
c.Set(ctx, "key", "value", WithDuration(5*time.Minute))
// Still fresh
_, ok, _ := c.Get(ctx, "key")
if !ok {
t.Fatal("expected hit before expiry")
}
// Advance past expiry
clk.Advance(6 * time.Minute)
_, ok, _ = c.Get(ctx, "key")
if ok {
t.Fatal("expected miss after expiry")
}
}