github.com/blend/go-sdk@v1.20220411.3/async/batch_test.go (about) 1 /* 2 3 Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file. 5 6 */ 7 8 package async 9 10 import ( 11 "context" 12 "fmt" 13 "strconv" 14 "sync/atomic" 15 "testing" 16 17 "github.com/blend/go-sdk/assert" 18 ) 19 20 func Test_Batch(t *testing.T) { 21 t.Parallel() 22 its := assert.New(t) 23 24 workItems := 32 25 26 items := make(chan interface{}, workItems) 27 for x := 0; x < workItems; x++ { 28 items <- "hello" + strconv.Itoa(x) 29 } 30 31 var processed int32 32 action := func(_ context.Context, v interface{}) error { 33 atomic.AddInt32(&processed, 1) 34 return fmt.Errorf("this is only a test") 35 } 36 37 errors := make(chan error, workItems) 38 NewBatch( 39 items, 40 action, 41 OptBatchErrors(errors), 42 OptBatchParallelism(4), 43 ).Process(context.Background()) 44 45 its.Equal(workItems, processed) 46 its.Equal(workItems, len(errors)) 47 } 48 49 func Test_Batch_empty(t *testing.T) { 50 t.Parallel() 51 its := assert.New(t) 52 53 items := make(chan interface{}, 32) 54 55 var processed int32 56 action := func(_ context.Context, v interface{}) error { 57 atomic.AddInt32(&processed, 1) 58 return fmt.Errorf("this is only a test") 59 } 60 61 errors := make(chan error, 32) 62 NewBatch( 63 items, 64 action, 65 OptBatchErrors(errors), 66 OptBatchParallelism(4), 67 ).Process(context.Background()) 68 69 its.Equal(0, processed) 70 its.Equal(0, len(errors)) 71 } 72 73 func Test_Batch_panic(t *testing.T) { 74 t.Parallel() 75 its := assert.New(t) 76 77 workItems := 32 78 79 items := make(chan interface{}, workItems) 80 for x := 0; x < workItems; x++ { 81 items <- "hello" + strconv.Itoa(x) 82 } 83 84 var processed int32 85 action := func(_ context.Context, v interface{}) error { 86 if result := atomic.AddInt32(&processed, 1); result == 1 { 87 panic("this is only a test") 88 } 89 return nil 90 } 91 92 errors := make(chan error, workItems) 93 NewBatch(items, action, OptBatchErrors(errors)).Process(context.Background()) 94 95 its.Equal(workItems, processed) 96 its.Equal(1, len(errors)) 97 }