forked from graph-gophers/dataloader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dataloader_test.go
641 lines (570 loc) · 16.3 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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
package dataloader
import (
"context"
"errors"
"fmt"
"log"
"reflect"
"strconv"
"sync"
"testing"
)
///////////////////////////////////////////////////
// Tests
///////////////////////////////////////////////////
func TestLoader(t *testing.T) {
t.Run("test Load method", func(t *testing.T) {
t.Parallel()
identityLoader, _ := IDLoader(0)
ctx := context.Background()
future := identityLoader.Load(ctx, "1")
value, err := future()
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)
ctx := context.Background()
future := identityLoader.Load(ctx, "1")
go future()
go future()
})
t.Run("test Load Method Panic Safety", func(t *testing.T) {
t.Parallel()
defer func() {
r := recover()
if r != nil {
t.Error("Panic Loader's panic should have been handled'")
}
}()
panicLoader, _ := PanicLoader(0)
ctx := context.Background()
future := panicLoader.Load(ctx, "1")
_, err := future()
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.Parallel()
defer func() {
r := recover()
if r != nil {
t.Error("Panic Loader's panic should have been handled'")
}
}()
panicLoader, _ := PanicLoader(0)
futures := []Thunk[string]{}
ctx := context.Background()
for i := 0; i < 3; i++ {
futures = append(futures, panicLoader.Load(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 LoadMany returns errors", func(t *testing.T) {
t.Parallel()
errorLoader, _ := ErrorLoader(0)
ctx := context.Background()
future := errorLoader.LoadMany(ctx, []string{"1", "2", "3"})
_, err := future()
if len(err) != 3 {
t.Error("LoadMany didn't return right number of errors")
}
})
t.Run("test LoadMany returns len(errors) == len(keys)", func(t *testing.T) {
t.Parallel()
loader, _ := OneErrorLoader(3)
ctx := context.Background()
future := loader.LoadMany(ctx, []string{"1", "2", "3"})
_, errs := future()
if len(errs) != 3 {
t.Errorf("LoadMany didn't return right number of errors (should match size of input)")
}
var errCount int = 0
var nilCount int = 0
for _, err := range errs {
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 LoadMany returns nil []error when no errors occurred", func(t *testing.T) {
t.Parallel()
loader, _ := IDLoader(0)
ctx := context.Background()
_, err := loader.LoadMany(ctx, []string{"1", "2", "3"})()
if err != nil {
t.Errorf("Expected LoadMany() 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)
ctx := context.Background()
future := identityLoader.LoadMany(ctx, []string{"1", "2", "3"})
go future()
go future()
})
t.Run("test Load Many Method Panic Safety", func(t *testing.T) {
t.Parallel()
defer func() {
r := recover()
if r != nil {
t.Error("Panic Loader's panic should have been handled'")
}
}()
panicLoader, _ := PanicLoader(0)
ctx := context.Background()
future := panicLoader.LoadMany(ctx, []string{"1"})
_, errs := future()
if len(errs) < 1 || errs[0].Error() != "Panic received in batch function: Programming error" {
t.Error("Panic was not propagated as an error.")
}
})
t.Run("test LoadMany method", func(t *testing.T) {
t.Parallel()
identityLoader, _ := IDLoader(0)
ctx := context.Background()
future := identityLoader.LoadMany(ctx, []string{"1", "2", "3"})
results, _ := future()
if results[0] != "1" || results[1] != "2" || results[2] != "3" {
t.Error("loadmany didn't return the right value")
}
})
t.Run("batches many requests", func(t *testing.T) {
t.Parallel()
identityLoader, loadCalls := IDLoader(0)
ctx := context.Background()
future1 := identityLoader.Load(ctx, "1")
future2 := identityLoader.Load(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()
ctx := context.Background()
n := 10
reqs := []Thunk[string]{}
keys := []string{}
for i := 0; i < n; i++ {
key := strconv.Itoa(i)
reqs = append(reqs, faultyLoader.Load(ctx, key))
keys = append(keys, 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")
}
}
// TODO: expect to get some kind of warning
})
t.Run("responds to max batch size", func(t *testing.T) {
t.Parallel()
identityLoader, loadCalls := IDLoader(2)
ctx := context.Background()
future1 := identityLoader.Load(ctx, "1")
future2 := identityLoader.Load(ctx, "2")
future3 := identityLoader.Load(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)
ctx := context.Background()
future1 := identityLoader.Load(ctx, "1")
future2 := identityLoader.Load(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)
ctx := context.Background()
identityLoader.Prime(ctx, "A", "Cached")
future1 := identityLoader.Load(ctx, "1")
future2 := identityLoader.Load(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)
ctx := context.Background()
identityLoader.Prime(ctx, "A", "Cached")
identityLoader.Prime(ctx, "B", "B")
future1 := identityLoader.Load(ctx, "1")
future2 := identityLoader.Clear(ctx, "A").Load(ctx, "A")
future3 := identityLoader.Load(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.Parallel()
batchOnlyLoader, loadCalls := BatchOnlyLoader(0)
ctx := context.Background()
future1 := batchOnlyLoader.Load(ctx, "1")
future2 := batchOnlyLoader.Load(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(ctx, "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.Parallel()
identityLoader, loadCalls := IDLoader(0)
ctx := context.Background()
identityLoader.Prime(ctx, "A", "Cached")
identityLoader.Prime(ctx, "B", "B")
identityLoader.ClearAll()
future1 := identityLoader.Load(ctx, "1")
future2 := identityLoader.Load(ctx, "A")
future3 := identityLoader.Load(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.Parallel()
identityLoader, loadCalls := NoCacheLoader(0)
ctx := context.Background()
identityLoader.Prime(ctx, "A", "Cached")
identityLoader.Prime(ctx, "B", "B")
identityLoader.ClearAll()
future1 := identityLoader.Clear(ctx, "1").Load(ctx, "1")
future2 := identityLoader.Load(ctx, "A")
future3 := identityLoader.Load(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.Parallel()
identityLoader, loadCalls := NoCacheLoader(0)
ctx := context.Background()
identityLoader.Prime(ctx, "A", "Cached")
identityLoader.Prime(ctx, "B", "B")
future1 := identityLoader.Load(ctx, "1")
future2 := identityLoader.Load(ctx, "A")
future3 := identityLoader.Load(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) (*Loader[string, string], *[][]string) {
var mu sync.Mutex
var loadCalls [][]string
identityLoader := NewBatchedLoader(func(_ context.Context, keys []string) []*Result[string] {
var results []*Result[string]
mu.Lock()
loadCalls = append(loadCalls, keys)
mu.Unlock()
for _, key := range keys {
results = append(results, &Result[string]{key, nil})
}
return results
}, WithBatchCapacity[string, string](max))
return identityLoader, &loadCalls
}
func BatchOnlyLoader(max int) (*Loader[string, string], *[][]string) {
var mu sync.Mutex
var loadCalls [][]string
identityLoader := NewBatchedLoader(func(_ context.Context, keys []string) []*Result[string] {
var results []*Result[string]
mu.Lock()
loadCalls = append(loadCalls, keys)
mu.Unlock()
for _, key := range keys {
results = append(results, &Result[string]{key, nil})
}
return results
}, WithBatchCapacity[string, string](max), WithClearCacheOnBatch[string, string]())
return identityLoader, &loadCalls
}
func ErrorLoader(max int) (*Loader[string, string], *[][]string) {
var mu sync.Mutex
var loadCalls [][]string
identityLoader := NewBatchedLoader(func(_ context.Context, keys []string) []*Result[string] {
var results []*Result[string]
mu.Lock()
loadCalls = append(loadCalls, keys)
mu.Unlock()
for _, key := range keys {
results = append(results, &Result[string]{key, fmt.Errorf("this is a test error")})
}
return results
}, WithBatchCapacity[string, string](max))
return identityLoader, &loadCalls
}
func OneErrorLoader(max int) (*Loader[string, string], *[][]string) {
var mu sync.Mutex
var loadCalls [][]string
identityLoader := NewBatchedLoader(func(_ context.Context, keys []string) []*Result[string] {
results := make([]*Result[string], 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] = &Result[string]{keys[i], err}
}
return results
}, WithBatchCapacity[string, string](max))
return identityLoader, &loadCalls
}
func PanicLoader(max int) (*Loader[string, string], *[][]string) {
var loadCalls [][]string
panicLoader := NewBatchedLoader(func(_ context.Context, keys []string) []*Result[string] {
panic("Programming error")
}, WithBatchCapacity[string, string](max))
return panicLoader, &loadCalls
}
func BadLoader(max int) (*Loader[string, string], *[][]string) {
var mu sync.Mutex
var loadCalls [][]string
identityLoader := NewBatchedLoader(func(_ context.Context, keys []string) []*Result[string] {
var results []*Result[string]
mu.Lock()
loadCalls = append(loadCalls, keys)
mu.Unlock()
results = append(results, &Result[string]{keys[0], nil})
return results
}, WithBatchCapacity[string, string](max))
return identityLoader, &loadCalls
}
func NoCacheLoader(max int) (*Loader[string, string], *[][]string) {
var mu sync.Mutex
var loadCalls [][]string
cache := &NoCache[string, string]{}
_ = cache
identityLoader := NewBatchedLoader(func(_ context.Context, keys []string) []*Result[string] {
var results []*Result[string]
mu.Lock()
loadCalls = append(loadCalls, keys)
mu.Unlock()
for _, key := range keys {
results = append(results, &Result[string]{key, nil})
}
return results
}, WithCache[string, string](cache), WithBatchCapacity[string, string](max))
return identityLoader, &loadCalls
}
// FaultyLoader gives len(keys)-1 results.
func FaultyLoader() (*Loader[string, string], *[][]string) {
var mu sync.Mutex
var loadCalls [][]string
loader := NewBatchedLoader(func(_ context.Context, keys []string) []*Result[string] {
var results []*Result[string]
mu.Lock()
loadCalls = append(loadCalls, keys)
mu.Unlock()
lastKeyIndex := len(keys) - 1
for i, key := range keys {
if i == lastKeyIndex {
break
}
results = append(results, &Result[string]{key, nil})
}
return results
})
return loader, &loadCalls
}
///////////////////////////////////////////////////
// Benchmarks
///////////////////////////////////////////////////
var a = &Avg{}
func batchIdentity(_ context.Context, keys []string) (results []*Result[string]) {
a.Add(len(keys))
for _, key := range keys {
results = append(results, &Result[string]{key, nil})
}
return
}
var _ctx = context.Background()
func BenchmarkLoader(b *testing.B) {
UserLoader := NewBatchedLoader(batchIdentity)
b.ResetTimer()
for i := 0; i < b.N; i++ {
UserLoader.Load(_ctx, strconv.Itoa(i))
}
log.Printf("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
}