-
Notifications
You must be signed in to change notification settings - Fork 10
/
dataloader_test.go
602 lines (534 loc) · 15.6 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
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
package dataloadgen_test
import (
"context"
"errors"
"fmt"
"reflect"
"strconv"
"sync"
"testing"
"github.com/vikstrous/dataloadgen"
)
// copied and adapted from github.com/graph-gophers/dataloader
func BenchmarkLoaderFromDataloader(b *testing.B) {
a := &Avg{}
ctx := context.Background()
dl := dataloadgen.NewLoader(func(_ context.Context, keys []string) (results []string, errs []error) {
a.Add(len(keys))
results = make([]string, 0, len(keys))
results = append(results, keys...)
return results, nil
})
b.ResetTimer()
for i := 0; i < b.N; i++ {
dl.LoadThunk(ctx, strconv.Itoa(i))
}
b.Logf("avg: %f", a.Avg())
}
type Avg struct {
total float64
length float64
lock sync.RWMutex
}
func (a *Avg) Add(v int) {
a.lock.Lock()
a.total += float64(v)
a.length++
a.lock.Unlock()
}
func (a *Avg) Avg() float64 {
a.lock.RLock()
defer a.lock.RUnlock()
if a.total == 0 {
return 0
} else if a.length == 0 {
return 0
}
return a.total / a.length
}
func TestLoader(t *testing.T) {
ctx := context.Background()
t.Run("test Load method", func(t *testing.T) {
t.Parallel()
identityLoader, _ := IDLoader(0)
value, err := identityLoader.Load(ctx, "1")
if err != nil {
t.Error(err.Error())
}
if value != "1" {
t.Error("load didn't return the right value")
}
})
t.Run("test thunk does not contain race conditions", func(t *testing.T) {
t.Parallel()
identityLoader, _ := IDLoader(0)
future := identityLoader.LoadThunk(ctx, "1")
go future()
go future()
})
t.Run("test Load Method Panic Safety", func(t *testing.T) {
t.Skip("not supported yet")
t.Parallel()
defer func() {
r := recover()
if r != nil {
t.Error("Panic Loader's panic should have been handled'")
}
}()
panicLoader, _ := PanicLoader(0)
_, err := panicLoader.Load(ctx, "1")
if err == nil || err.Error() != "Panic received in batch function: Programming error" {
t.Error("Panic was not propagated as an error.")
}
})
t.Run("test Load Method Panic Safety in multiple keys", func(t *testing.T) {
t.Skip("not supported yet")
t.Parallel()
defer func() {
r := recover()
if r != nil {
t.Error("Panic Loader's panic should have been handled'")
}
}()
panicLoader, _ := PanicLoader(0)
futures := []func() (string, error){}
for i := 0; i < 3; i++ {
futures = append(futures, panicLoader.LoadThunk(ctx, strconv.Itoa(i)))
}
for _, f := range futures {
_, err := f()
if err == nil || err.Error() != "Panic received in batch function: Programming error" {
t.Error("Panic was not propagated as an error.")
}
}
})
t.Run("test LoadAll returns errors", func(t *testing.T) {
t.Parallel()
errorLoader, _ := ErrorLoader(0)
_, err := errorLoader.LoadAll(ctx, []string{"1", "2", "3"})
if len(err.(dataloadgen.ErrorSlice)) != 3 {
t.Error("LoadAll didn't return right number of errors")
}
})
t.Run("test LoadAll returns len(errors) == len(keys)", func(t *testing.T) {
t.Parallel()
loader, _ := OneErrorLoader(3)
_, errs := loader.LoadAll(ctx, []string{"1", "2", "3"})
if len(errs.(dataloadgen.ErrorSlice)) != 3 {
t.Errorf("LoadAll didn't return right number of errors (should match size of input)")
}
var errCount int = 0
var nilCount int = 0
for _, err := range errs.(dataloadgen.ErrorSlice) {
if err == nil {
nilCount++
} else {
errCount++
}
}
if errCount != 1 {
t.Error("Expected an error on only one of the items loaded")
}
if nilCount != 2 {
t.Error("Expected second and third errors to be nil")
}
})
t.Run("test LoadAll returns nil []error when no errors occurred", func(t *testing.T) {
t.Parallel()
loader, _ := IDLoader(0)
_, errs := loader.LoadAll(ctx, []string{"1", "2", "3"})
if errs != nil {
t.Errorf("Expected LoadAll(ctx,) to return nil error slice when no errors occurred")
}
})
t.Run("test thunkmany does not contain race conditions", func(t *testing.T) {
t.Parallel()
identityLoader, _ := IDLoader(0)
future := identityLoader.LoadAllThunk(ctx, []string{"1", "2", "3"})
go future()
go future()
})
t.Run("test Load Many Method Panic Safety", func(t *testing.T) {
t.Skip("not supported yet")
t.Parallel()
defer func() {
r := recover()
if r != nil {
t.Error("Panic Loader's panic should have been handled'")
}
}()
panicLoader, _ := PanicLoader(0)
_, err := panicLoader.LoadAll(ctx, []string{"1"})
if err == nil || err.Error() != "Panic received in batch function: Programming error" {
t.Error("Panic was not propagated as an error.")
}
})
t.Run("test LoadAll method", func(t *testing.T) {
t.Parallel()
identityLoader, _ := IDLoader(0)
results, _ := identityLoader.LoadAll(ctx, []string{"1", "2", "3"})
if results[0] != "1" || results[1] != "2" || results[2] != "3" {
t.Error("LoadAll didn't return the right value")
}
})
t.Run("batches many requests", func(t *testing.T) {
t.Parallel()
identityLoader, loadCalls := IDLoader(0)
future1 := identityLoader.LoadThunk(ctx, "1")
future2 := identityLoader.LoadThunk(ctx, "2")
_, err := future1()
if err != nil {
t.Error(err.Error())
}
_, err = future2()
if err != nil {
t.Error(err.Error())
}
calls := *loadCalls
inner := []string{"1", "2"}
expected := [][]string{inner}
if !reflect.DeepEqual(calls, expected) {
t.Errorf("did not call batchFn in right order. Expected %#v, got %#v", expected, calls)
}
})
t.Run("number of results matches number of keys", func(t *testing.T) {
t.Parallel()
faultyLoader, _ := FaultyLoader()
n := 10
reqs := []func() (string, error){}
for i := 0; i < n; i++ {
key := strconv.Itoa(i)
reqs = append(reqs, faultyLoader.LoadThunk(ctx, key))
}
for _, future := range reqs {
_, err := future()
if err == nil {
t.Error("if number of results doesn't match keys, all keys should contain error")
}
}
})
t.Run("responds to max batch size", func(t *testing.T) {
t.Parallel()
identityLoader, loadCalls := IDLoader(2)
future1 := identityLoader.LoadThunk(ctx, "1")
future2 := identityLoader.LoadThunk(ctx, "2")
future3 := identityLoader.LoadThunk(ctx, "3")
_, err := future1()
if err != nil {
t.Error(err.Error())
}
_, err = future2()
if err != nil {
t.Error(err.Error())
}
_, err = future3()
if err != nil {
t.Error(err.Error())
}
calls := *loadCalls
inner1 := []string{"1", "2"}
inner2 := []string{"3"}
expected := [][]string{inner1, inner2}
if !reflect.DeepEqual(calls, expected) {
t.Errorf("did not respect max batch size. Expected %#v, got %#v", expected, calls)
}
})
t.Run("caches repeated requests", func(t *testing.T) {
t.Parallel()
identityLoader, loadCalls := IDLoader(0)
future1 := identityLoader.LoadThunk(ctx, "1")
future2 := identityLoader.LoadThunk(ctx, "1")
_, err := future1()
if err != nil {
t.Error(err.Error())
}
_, err = future2()
if err != nil {
t.Error(err.Error())
}
calls := *loadCalls
inner := []string{"1"}
expected := [][]string{inner}
if !reflect.DeepEqual(calls, expected) {
t.Errorf("did not respect max batch size. Expected %#v, got %#v", expected, calls)
}
})
t.Run("allows primed cache", func(t *testing.T) {
t.Parallel()
identityLoader, loadCalls := IDLoader(0)
identityLoader.Prime("A", "Cached")
future1 := identityLoader.LoadThunk(ctx, "1")
future2 := identityLoader.LoadThunk(ctx, "A")
_, err := future1()
if err != nil {
t.Error(err.Error())
}
value, err := future2()
if err != nil {
t.Error(err.Error())
}
calls := *loadCalls
inner := []string{"1"}
expected := [][]string{inner}
if !reflect.DeepEqual(calls, expected) {
t.Errorf("did not respect max batch size. Expected %#v, got %#v", expected, calls)
}
if value != "Cached" {
t.Errorf("did not use primed cache value. Expected '%#v', got '%#v'", "Cached", value)
}
})
t.Run("allows clear value in cache", func(t *testing.T) {
t.Parallel()
identityLoader, loadCalls := IDLoader(0)
identityLoader.Prime("A", "Cached")
identityLoader.Prime("B", "B")
future1 := identityLoader.LoadThunk(ctx, "1")
identityLoader.Clear("A")
future2 := identityLoader.LoadThunk(ctx, "A")
future3 := identityLoader.LoadThunk(ctx, "B")
_, err := future1()
if err != nil {
t.Error(err.Error())
}
value, err := future2()
if err != nil {
t.Error(err.Error())
}
_, err = future3()
if err != nil {
t.Error(err.Error())
}
calls := *loadCalls
inner := []string{"1", "A"}
expected := [][]string{inner}
if !reflect.DeepEqual(calls, expected) {
t.Errorf("did not respect max batch size. Expected %#v, got %#v", expected, calls)
}
if value != "A" {
t.Errorf("did not use primed cache value. Expected '%#v', got '%#v'", "Cached", value)
}
})
t.Run("clears cache on batch with WithClearCacheOnBatch", func(t *testing.T) {
t.Skip("not supported yet")
t.Parallel()
batchOnlyLoader, loadCalls := BatchOnlyLoader(0)
future1 := batchOnlyLoader.LoadThunk(ctx, "1")
future2 := batchOnlyLoader.LoadThunk(ctx, "1")
_, err := future1()
if err != nil {
t.Error(err.Error())
}
_, err = future2()
if err != nil {
t.Error(err.Error())
}
calls := *loadCalls
inner := []string{"1"}
expected := [][]string{inner}
if !reflect.DeepEqual(calls, expected) {
t.Errorf("did not batch queries. Expected %#v, got %#v", expected, calls)
}
//if _, found := batchOnlyLoader.cache.Get("1"); found {
// t.Errorf("did not clear cache after batch. Expected %#v, got %#v", false, found)
//}
})
t.Run("allows clearAll values in cache", func(t *testing.T) {
t.Skip("not supported yet")
t.Parallel()
identityLoader, loadCalls := IDLoader(0)
identityLoader.Prime("A", "Cached")
identityLoader.Prime("B", "B")
// identityLoader.ClearAll()
future1 := identityLoader.LoadThunk(ctx, "1")
future2 := identityLoader.LoadThunk(ctx, "A")
future3 := identityLoader.LoadThunk(ctx, "B")
_, err := future1()
if err != nil {
t.Error(err.Error())
}
_, err = future2()
if err != nil {
t.Error(err.Error())
}
_, err = future3()
if err != nil {
t.Error(err.Error())
}
calls := *loadCalls
inner := []string{"1", "A", "B"}
expected := [][]string{inner}
if !reflect.DeepEqual(calls, expected) {
t.Errorf("did not respect max batch size. Expected %#v, got %#v", expected, calls)
}
})
t.Run("all methods on NoCache are Noops", func(t *testing.T) {
t.Skip("not supported yet")
t.Parallel()
identityLoader, loadCalls := NoCacheLoader(0)
identityLoader.Prime("A", "Cached")
identityLoader.Prime("B", "B")
// identityLoader.ClearAll()
identityLoader.Clear("1")
future1 := identityLoader.LoadThunk(ctx, "1")
future2 := identityLoader.LoadThunk(ctx, "A")
future3 := identityLoader.LoadThunk(ctx, "B")
_, err := future1()
if err != nil {
t.Error(err.Error())
}
_, err = future2()
if err != nil {
t.Error(err.Error())
}
_, err = future3()
if err != nil {
t.Error(err.Error())
}
calls := *loadCalls
inner := []string{"1", "A", "B"}
expected := [][]string{inner}
if !reflect.DeepEqual(calls, expected) {
t.Errorf("did not respect max batch size. Expected %#v, got %#v", expected, calls)
}
})
t.Run("no cache does not cache anything", func(t *testing.T) {
t.Skip("not supported yet")
t.Parallel()
identityLoader, loadCalls := NoCacheLoader(0)
identityLoader.Prime("A", "Cached")
identityLoader.Prime("B", "B")
future1 := identityLoader.LoadThunk(ctx, "1")
future2 := identityLoader.LoadThunk(ctx, "A")
future3 := identityLoader.LoadThunk(ctx, "B")
_, err := future1()
if err != nil {
t.Error(err.Error())
}
_, err = future2()
if err != nil {
t.Error(err.Error())
}
_, err = future3()
if err != nil {
t.Error(err.Error())
}
calls := *loadCalls
inner := []string{"1", "A", "B"}
expected := [][]string{inner}
if !reflect.DeepEqual(calls, expected) {
t.Errorf("did not respect max batch size. Expected %#v, got %#v", expected, calls)
}
})
}
// test helpers
func IDLoader(max int) (*dataloadgen.Loader[string, string], *[][]string) {
var mu sync.Mutex
var loadCalls [][]string
identityLoader := dataloadgen.NewLoader(func(_ context.Context, keys []string) (results []string, errs []error) {
mu.Lock()
loadCalls = append(loadCalls, keys)
mu.Unlock()
results = append(results, keys...)
return results, nil
}, dataloadgen.WithBatchCapacity(max))
return identityLoader, &loadCalls
}
func BatchOnlyLoader(max int) (*dataloadgen.Loader[string, string], *[][]string) {
var mu sync.Mutex
var loadCalls [][]string
identityLoader := dataloadgen.NewLoader(func(_ context.Context, keys []string) (results []string, errs []error) {
mu.Lock()
loadCalls = append(loadCalls, keys)
mu.Unlock()
results = append(results, keys...)
return results, nil
}, dataloadgen.WithBatchCapacity(max)) // dataloadgen.WithClearCacheOnBatch())
return identityLoader, &loadCalls
}
func ErrorLoader(max int) (*dataloadgen.Loader[string, string], *[][]string) {
var mu sync.Mutex
var loadCalls [][]string
identityLoader := dataloadgen.NewLoader(func(_ context.Context, keys []string) (results []string, errs []error) {
mu.Lock()
loadCalls = append(loadCalls, keys)
mu.Unlock()
for _, key := range keys {
results = append(results, key)
errs = append(errs, fmt.Errorf("this is a test error"))
}
return results, errs
}, dataloadgen.WithBatchCapacity(max))
return identityLoader, &loadCalls
}
func OneErrorLoader(max int) (*dataloadgen.Loader[string, string], *[][]string) {
var mu sync.Mutex
var loadCalls [][]string
identityLoader := dataloadgen.NewLoader(func(_ context.Context, keys []string) (results []string, errs []error) {
results = make([]string, max)
errs = make([]error, max)
mu.Lock()
loadCalls = append(loadCalls, keys)
mu.Unlock()
for i := range keys {
var err error
if i == 0 {
err = errors.New("always error on the first key")
}
results[i] = keys[i]
errs[i] = err
}
return results, errs
}, dataloadgen.WithBatchCapacity(max))
return identityLoader, &loadCalls
}
func PanicLoader(max int) (*dataloadgen.Loader[string, string], *[][]string) {
var loadCalls [][]string
panicLoader := dataloadgen.NewLoader(func(_ context.Context, keys []string) (results []string, errs []error) {
panic("Programming error")
}, dataloadgen.WithBatchCapacity(max)) //, withSilentLogger())
return panicLoader, &loadCalls
}
func BadLoader(max int) (*dataloadgen.Loader[string, string], *[][]string) {
var mu sync.Mutex
var loadCalls [][]string
identityLoader := dataloadgen.NewLoader(func(_ context.Context, keys []string) (results []string, errs []error) {
mu.Lock()
loadCalls = append(loadCalls, keys)
mu.Unlock()
results = append(results, keys[0])
return results, nil
}, dataloadgen.WithBatchCapacity(max))
return identityLoader, &loadCalls
}
func NoCacheLoader(max int) (*dataloadgen.Loader[string, string], *[][]string) {
var mu sync.Mutex
var loadCalls [][]string
// cache := &NoCache{}
identityLoader := dataloadgen.NewLoader(func(_ context.Context, keys []string) (results []string, errs []error) {
mu.Lock()
loadCalls = append(loadCalls, keys)
mu.Unlock()
results = append(results, keys...)
return results, nil
}, /*dataloadgen.WithCache(cache),*/ dataloadgen.WithBatchCapacity(max))
return identityLoader, &loadCalls
}
// FaultyLoader gives len(keys)-1 results.
func FaultyLoader() (*dataloadgen.Loader[string, string], *[][]string) {
var mu sync.Mutex
var loadCalls [][]string
loader := dataloadgen.NewLoader(func(_ context.Context, keys []string) (results []string, errs []error) {
mu.Lock()
loadCalls = append(loadCalls, keys)
mu.Unlock()
lastKeyIndex := len(keys) - 1
for i, key := range keys {
if i == lastKeyIndex {
break
}
results = append(results, key)
}
return results, nil
})
return loader, &loadCalls
}