-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache_test.go
More file actions
326 lines (290 loc) · 9.51 KB
/
cache_test.go
File metadata and controls
326 lines (290 loc) · 9.51 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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
package the_cachex
import (
"context"
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
var httpClient http.Client
func FetchData(ctx context.Context, url string) ([]byte, error) {
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
return nil, err
}
resp, err := httpClient.Do(req)
if err != nil {
return nil, err
}
// We assume that any status code which is not 200 is an error
if resp.StatusCode != 200 {
_ = resp.Body.Close()
return nil, fmt.Errorf("unexpected status code %d", resp.StatusCode)
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
slog.Warn(fmt.Sprintf("failed to close response body for %s", url))
}
}(resp.Body)
bytes, err := ReadAll(ctx, resp.Body)
return bytes, err
}
// TestCache_Fetch ensures cache fetching works
func TestCache_Fetch(t *testing.T) {
t.Run("test fetch caches entry", func(t *testing.T) {
// Given
serverCallCounter := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
serverCallCounter += 1
_, _ = w.Write([]byte("Hello World"))
}))
defer server.Close()
leCache := NewCache[[]byte](10 * time.Minute)
// Then
for range 100 {
data, err := leCache.Cache(context.Background(), server.URL, func(ctx2 context.Context) ([]byte, error) {
return FetchData(ctx2, server.URL)
})
assert.NoError(t, err)
assert.Equal(t, "Hello World", string(data))
assert.Equal(t, 1, serverCallCounter)
}
})
t.Run("test fetch with context", func(t *testing.T) {
// Given
serverCallCounter := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
serverCallCounter += 1
_, _ = w.Write([]byte("Hello World"))
}))
defer server.Close()
leCache := NewCache[[]byte](10 * time.Minute)
// Then
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Nanosecond)
_, err := leCache.Cache(ctx, server.URL, func(ctx2 context.Context) ([]byte, error) {
return FetchData(ctx2, server.URL)
})
assert.Error(t, err, "context deadline did not exceed")
cancel()
})
t.Run("test fetch error not being cached", func(t *testing.T) {
// Setup
serverCallCounter := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if serverCallCounter == 0 {
w.WriteHeader(http.StatusInternalServerError)
} else {
w.WriteHeader(http.StatusOK)
}
serverCallCounter += 1
_, _ = w.Write([]byte("Hello World"))
}))
defer server.Close()
leCache := NewCache[[]byte](10 * time.Minute)
// Test error is not cached
data, err := leCache.Cache(context.Background(), server.URL, func(ctx2 context.Context) ([]byte, error) {
return FetchData(ctx2, server.URL)
})
assert.Error(t, err)
assert.Equal(t, "", string(data))
assert.Equal(t, 1, serverCallCounter)
// Test no error
data, err = leCache.Cache(context.Background(), server.URL, func(ctx2 context.Context) ([]byte, error) {
return FetchData(ctx2, server.URL)
})
assert.NoError(t, err)
assert.Equal(t, "Hello World", string(data))
assert.Equal(t, 2, serverCallCounter)
})
}
// TestCache_Stats ensures cache stats reporting works.
func TestCache_Stats(t *testing.T) {
// Setup
serverCallCounter := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
serverCallCounter += 1
_, _ = w.Write([]byte("Hello world"))
}))
defer server.Close()
leCache := NewCache[[]byte](10 * time.Minute)
// Test
var wg sync.WaitGroup
for range 100 {
wg.Add(1)
go func() {
_, err := leCache.Cache(context.Background(), server.URL, func(ctx2 context.Context) ([]byte, error) {
return FetchData(ctx2, server.URL)
})
if err != nil {
t.Errorf("Unknown error occured: %v", err)
}
wg.Done()
}()
}
wg.Wait()
hits, misses, entries := leCache.Stats()
// Assert
assert.Equal(t, 99, hits, "the number of hits differ")
assert.Equal(t, 1, misses, "the number of misses differ")
assert.Equal(t, 1, entries, "the number of entries differ")
assert.Equal(t, 1, serverCallCounter, "the server calls differ")
}
// TestCache_Concurrency ensures cache behaves as expected in concurrent scenarios.
func TestCache_Concurrency(t *testing.T) {
t.Run("test concurrency happy path", func(t *testing.T) {
// Setup
serverCallCounter := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
serverCallCounter += 1
_, _ = w.Write([]byte("Hello world"))
}))
defer server.Close()
leCache := NewCache[[]byte](5 * time.Second)
// Test
var wg sync.WaitGroup
for range 200 {
wg.Add(1)
go func() {
_, err := leCache.Cache(context.Background(), server.URL, func(ctx2 context.Context) ([]byte, error) {
return FetchData(ctx2, server.URL)
})
if err != nil {
t.Errorf("Unknown error occured: %v", err)
}
wg.Done()
}()
}
wg.Wait()
hits, misses, entries := leCache.Stats()
// Assert
assert.Equal(t, 199, hits, "the number of hits differ")
assert.Equal(t, 1, misses, "the number of misses differ")
assert.Equal(t, 1, entries, "the number of entries differ")
assert.Equal(t, 1, serverCallCounter, "the server calls differ")
})
t.Run("test concurrency entry expires before being fetched", func(t *testing.T) {
// Setup
serverCallCounter := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if serverCallCounter == 0 {
time.Sleep(500 * time.Millisecond)
}
w.WriteHeader(http.StatusOK)
serverCallCounter += 1
_, _ = w.Write([]byte("Hello world"))
}))
defer server.Close()
leCache := NewCache[[]byte](10 * time.Millisecond)
// Test
var wg sync.WaitGroup
for range 200 {
wg.Add(1)
go func() {
data, err := leCache.Cache(context.Background(), server.URL, func(ctx2 context.Context) ([]byte, error) {
return FetchData(ctx2, server.URL)
})
assert.NoError(t, err)
assert.Equal(t, string(data), "Hello world")
wg.Done()
}()
}
wg.Wait()
hits, misses, entries := leCache.Stats()
// Assert
assert.Equal(t, 199, hits, "the number of hits differ")
assert.Equal(t, 1, misses, "the number of misses differ")
assert.Equal(t, 1, entries, "the number of cache entries differ")
assert.Equal(t, 1, serverCallCounter, "the server call counter is different")
})
t.Run("test concurrency slow fetch", func(t *testing.T) {
// Setup
serverCallCounter := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if serverCallCounter == 0 {
time.Sleep(1000 * time.Millisecond)
}
w.WriteHeader(http.StatusOK)
serverCallCounter += 1
_, _ = w.Write([]byte("Hello world"))
}))
defer server.Close()
leCache := NewCache[[]byte](10 * time.Minute)
// Test
var wg sync.WaitGroup
for range 200 {
wg.Add(1)
go func() {
data, err := leCache.Cache(context.Background(), server.URL, func(ctx2 context.Context) ([]byte, error) {
return FetchData(ctx2, server.URL)
})
assert.NoError(t, err)
assert.Equal(t, string(data), "Hello world")
wg.Done()
}()
}
wg.Wait()
hits, misses, entries := leCache.Stats()
// Assert
assert.Equal(t, 199, hits, "the number of hits differ")
assert.Equal(t, 1, misses, "the number of misses differ")
assert.Equal(t, 1, entries, "the number of cache entries differ")
assert.Equal(t, 1, serverCallCounter, "the server call counter is different")
})
}
// TestCacheTTL ensures cache handles per entry TTL correctly.
func TestCacheTTL(t *testing.T) {
serverCallCounter := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
serverCallCounter += 1
_, _ = fmt.Fprintf(w, "Hello world %d", serverCallCounter)
}))
defer server.Close()
leCache := NewCache[[]byte](100 * time.Millisecond)
cacheFunction := func(ctx2 context.Context) ([]byte, error) {
return FetchData(ctx2, server.URL)
}
// Test first request, it should fetch the same URL as ttl is not expired
serverUrl := server.URL
data, err := leCache.Cache(context.Background(), serverUrl, cacheFunction)
assert.NoError(t, err)
assert.Equal(t, "Hello world 1", string(data))
data, err = leCache.Cache(context.Background(), serverUrl, cacheFunction)
assert.NoError(t, err)
assert.Equal(t, "Hello world 1", string(data))
assert.Equal(t, 1, serverCallCounter)
time.Sleep(100 * time.Millisecond)
// Test second fetch
data, err = leCache.Cache(context.Background(), serverUrl, cacheFunction, 250*time.Millisecond)
assert.NoError(t, err)
assert.Equal(t, "Hello world 2", string(data))
assert.Equal(t, 2, serverCallCounter)
for range 100 {
data, err = leCache.Cache(context.Background(), serverUrl, cacheFunction, 250*time.Millisecond)
assert.NoError(t, err)
assert.Equal(t, "Hello world 2", string(data))
assert.Equal(t, 2, serverCallCounter)
}
// Sleep to pass TTL override time
time.Sleep(100 * time.Millisecond)
data, err = leCache.Cache(context.Background(), serverUrl, cacheFunction, 250*time.Millisecond)
assert.NoError(t, err)
assert.Equal(t, "Hello world 2", string(data))
assert.Equal(t, 2, serverCallCounter)
// Final result test
time.Sleep(150 * time.Millisecond)
data, err = leCache.Cache(context.Background(), serverUrl, cacheFunction, 250*time.Millisecond)
assert.NoError(t, err)
assert.Equal(t, "Hello world 3", string(data))
assert.Equal(t, 3, serverCallCounter)
}