-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdataloader_test.go
238 lines (198 loc) · 7.22 KB
/
dataloader_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
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
package dataloader_test
import (
"context"
"strconv"
"testing"
"time"
"github.com/andy9775/dataloader"
"github.com/stretchr/testify/assert"
)
// ============================================== test constants =============================================
const TEST_TIMEOUT time.Duration = time.Millisecond * 500
// ==================================== implement concrete keys interface ====================================
type PrimaryKey int
func (p PrimaryKey) String() string {
return strconv.Itoa(int(p))
}
func (p PrimaryKey) Raw() interface{} {
return p
}
// =============================================== test helpers ==============================================
// getBatchFunction returns a generic batch function which returns the provided result and calls the provided
// callback function
func getBatchFunction(cb func(), result dataloader.Result) dataloader.BatchFunction {
return func(ctx context.Context, keys dataloader.Keys) *dataloader.ResultMap {
cb()
m := dataloader.NewResultMap(1)
m.Set(keys.Keys()[0].(PrimaryKey).String(), result)
return &m
}
}
// ========================= mock cache =========================
type mockCache struct {
r map[string]dataloader.Result
}
func newMockCache(cap int) dataloader.Cache {
return &mockCache{r: make(map[string]dataloader.Result, cap)}
}
func (c *mockCache) SetResult(ctx context.Context, key dataloader.Key, result dataloader.Result) {
c.r[key.String()] = result
}
func (c *mockCache) SetResultMap(ctx context.Context, resultMap dataloader.ResultMap) {
for _, k := range resultMap.Keys() {
c.r[k] = resultMap.GetValueForString(k)
}
}
func (c *mockCache) GetResult(ctx context.Context, key dataloader.Key) (dataloader.Result, bool) {
r, ok := c.r[key.String()]
return r, ok
}
func (c *mockCache) GetResultMap(ctx context.Context, keys ...dataloader.Key) (dataloader.ResultMap, bool) {
result := dataloader.NewResultMap(len(keys))
for _, k := range keys {
r, ok := c.r[k.String()]
if !ok {
return dataloader.NewResultMap(len(keys)), false
}
result.Set(k.String(), r)
}
return result, true
}
func (c *mockCache) Delete(ctx context.Context, key dataloader.Key) bool {
_, ok := c.r[key.String()]
if ok {
delete(c.r, key.String())
return true
}
return false
}
func (c *mockCache) ClearAll(ctx context.Context) bool {
c.r = make(map[string]dataloader.Result, len(c.r))
return true
}
// ========================= mock strategy =========================
type mockStrategy struct {
batchFunc dataloader.BatchFunction
}
func newMockStrategy() func(int, dataloader.BatchFunction) dataloader.Strategy {
return func(capacity int, batch dataloader.BatchFunction) dataloader.Strategy {
return &mockStrategy{
batchFunc: batch,
}
}
}
func (s *mockStrategy) Load(ctx context.Context, key dataloader.Key) dataloader.Thunk {
return func() (dataloader.Result, bool) {
keys := dataloader.NewKeys(1)
keys.Append(key)
r := s.batchFunc(ctx, keys)
return (*r).GetValue(key)
}
}
func (s *mockStrategy) LoadMany(ctx context.Context, keyArr ...dataloader.Key) dataloader.ThunkMany {
return func() dataloader.ResultMap {
keys := dataloader.NewKeys(len(keyArr))
for _, k := range keyArr {
keys.Append(k)
}
r := s.batchFunc(ctx, keys)
return *r
}
}
func (s *mockStrategy) LoadNoOp(ctx context.Context) {}
// ================================================== tests ==================================================
/*
NOTE: cache is not go routine safe. Hence mock strategy executes
*/
// ============================================= test cache hits =============================================
// TestLoadCacheHit tests to ensure that a cache hit doesn't call the callback function.
func TestLoadCacheHit(t *testing.T) {
// setup
callCount := 0
result := dataloader.Result{Result: "cache_miss", Err: nil}
expectedResult := dataloader.Result{Result: "cache_hit", Err: nil}
cb := func() { callCount += 1 }
cache := newMockCache(1)
key := PrimaryKey(1)
cache.SetResult(context.Background(), key, expectedResult)
batch := getBatchFunction(cb, result)
strategy := newMockStrategy()
loader := dataloader.NewDataLoader(1, batch, strategy, dataloader.WithCache(cache))
// invoke / assert
thunk := loader.Load(context.Background(), key)
r, ok := thunk()
assert.True(t, ok, "Expected result to have been found")
assert.Equal(t, expectedResult.Result.(string), r.Result.(string), "Expected result from thunk")
assert.Equal(t, 0, callCount, "Expected batch function to not be called")
}
// TestLoadManyCacheHit tests to ensure that a cache hit doesn't call the callback function.
func TestLoadManyCacheHit(t *testing.T) {
// setup
callCount := 0
result := dataloader.Result{Result: "cache_miss", Err: nil}
expectedResult := dataloader.Result{Result: "cache_hit", Err: nil}
expectedResult2 := dataloader.Result{Result: "cache_hit_2", Err: nil}
cb := func() { callCount += 1 }
cache := newMockCache(2)
key := PrimaryKey(1)
key2 := PrimaryKey(2)
cache.SetResult(context.Background(), key, expectedResult)
cache.SetResult(context.Background(), key2, expectedResult2)
batch := getBatchFunction(cb, result)
strategy := newMockStrategy()
loader := dataloader.NewDataLoader(1, batch, strategy, dataloader.WithCache(cache))
// invoke / assert
thunk := loader.LoadMany(context.Background(), key, key2)
r := thunk()
returned, ok := r.GetValue(key)
assert.True(t, ok, "Expected result to have been found")
assert.Equal(t,
expectedResult.Result.(string),
returned.Result.(string),
"Expected result from thunk",
)
assert.Equal(t, 2, r.Length(), "Expected 2 result from cache")
assert.Equal(t, 0, callCount, "Expected batch function to not be called")
}
// ============================================= test cache miss =============================================
// TestLoadCacheMiss ensures the batch function is called on a cache miss
func TestLoadCacheMiss(t *testing.T) {
// setup
callCount := 0
result := dataloader.Result{Result: "cache_miss", Err: nil}
cb := func() { callCount += 1 }
cache := newMockCache(1)
key := PrimaryKey(1)
batch := getBatchFunction(cb, result)
strategy := newMockStrategy()
loader := dataloader.NewDataLoader(1, batch, strategy, dataloader.WithCache(cache))
// invoke / assert
thunk := loader.Load(context.Background(), key)
r, ok := thunk()
assert.True(t, ok, "Expected result to have been found")
assert.Equal(t, result.Result.(string), r.Result.(string), "Expected result from thunk")
assert.Equal(t, 1, callCount, "Expected batch function to be called")
}
// TestLoadManyCacheMiss ensures the batch function is called on a cache miss
func TestLoadManyCacheMiss(t *testing.T) {
// setup
callCount := 0
result := dataloader.Result{Result: "cache_miss", Err: nil}
cb := func() { callCount += 1 }
cache := newMockCache(1)
key := PrimaryKey(1)
batch := getBatchFunction(cb, result)
strategy := newMockStrategy()
loader := dataloader.NewDataLoader(1, batch, strategy, dataloader.WithCache(cache))
// invoke / assert
thunk := loader.LoadMany(context.Background(), key)
r := thunk()
returned, ok := r.GetValue(key)
assert.True(t, ok, "Expected result to have been found")
assert.Equal(t,
result.Result.(string),
returned.Result.(string),
"Expected result from thunk",
)
assert.Equal(t, 1, callCount, "Expected batch function to be called")
}