-
Notifications
You must be signed in to change notification settings - Fork 1
/
rungroup_test.go
366 lines (319 loc) · 8.63 KB
/
rungroup_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
package rungroup_test
import (
"context"
"errors"
"fmt"
"github.com/bharat-rajani/rungroup/pkg/concurrent"
"math/rand"
"strconv"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/bharat-rajani/rungroup"
)
type testArg struct {
f func() error
interrupter bool
id string
}
type testWant struct {
id string
err error
ok bool
}
func prepareRandomTestArgs(n int, pIntr int, pErr int, err error) []testArg {
if pIntr < 0 || pIntr > 100 {
pIntr = 0
}
if pErr < 0 || pErr > 100 {
pErr = 0
}
testArgs := make([]testArg, n)
getSleepDuration := func(rand int) time.Duration {
// 20 percent goroutine will sleep for 2 sec
// 30 percent goroutine will sleep for 1 sec
// 50 percent goroutine will sleep for 0.5 sec
if rand <= 20 {
return time.Duration(2) * time.Second
} else if rand <= 50 {
return time.Duration(1) * time.Second
} else {
return time.Duration(500) * time.Millisecond
}
}
for i := 0; i < n; i++ {
rand.Seed(time.Now().UnixNano())
testArgs[i].id = fmt.Sprintf("%d", i)
ir := rand.Intn(n-1) + 1
fir := float64(ir) / float64(n)
// if its interrupter goroutine it must return a specified error (err in args)
if fir <= (float64(pIntr) / float64(100)) {
testArgs[i].interrupter = true
testArgs[i].f = func() error {
time.Sleep(getSleepDuration(ir))
return err
}
} else {
// it may or may not give error
// rest of the percentage of pErr will go here
testArgs[i].interrupter = false
er := rand.Intn(101-1) + 1
// percent specifies percentage of goroutine returning an error
if er <= pErr {
testArgs[i].f = func() error {
time.Sleep(getSleepDuration(er))
return err
}
} else {
testArgs[i].f = func() error {
time.Sleep(getSleepDuration(er))
return nil
}
}
}
}
return testArgs
}
func TestWithContext(t *testing.T) {
errBomb := errors.New("group_test: fBombed")
cases := []struct {
name string
goRoutineId string
interrupter bool
errs []error
want error
}{
{name: "NoErrorsWhenAnyIntrpt", interrupter: true, want: nil},
{name: "NoErrorsWhenNoIntrpt", interrupter: false, want: nil},
{name: "NilErrorWhenAnyIntrpt", interrupter: true, errs: []error{nil}, want: nil},
{name: "NilErrorWhenNoIntrpt", interrupter: false, errs: []error{nil}, want: nil},
{name: "ErrorBombWhenNoIntrpt", interrupter: false, errs: []error{errBomb}, want: nil},
{name: "ErrorBombWhenAllIntrpt", errs: []error{errBomb, nil}, interrupter: true, want: errBomb},
{name: "ErrorBombsWhenAllIntrptCheckDataRace", errs: []error{errBomb, nil, errBomb, nil, errBomb, errBomb, errBomb, nil}, interrupter: true, want: errBomb},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
g, ctx := rungroup.WithContext(context.Background())
for id, err := range tc.errs {
id, err := id, err
g.Go(func() error { return err }, tc.interrupter, strconv.Itoa(id))
}
if err := g.Wait(); err != tc.want {
t.Errorf("after %T.Go(func() error { return err }) for err in %v\n"+
"g.Wait() = %v; want %v",
g, tc.errs, err, tc.want)
}
canceled := false
select {
case <-ctx.Done():
canceled = true
default:
}
if !canceled {
t.Errorf("after %T.Go(func() error { return err }) for err in %v\n"+
"ctx.Done() was not closed",
g, tc.errs)
}
})
}
}
func TestWithContext_GoWithFunc(t *testing.T) {
errBomb := errors.New("group_test: fBombed in GoWithFunc")
testCases := []struct {
name string
want error
args []testArg
n uint64
}{
{
name: "HundredRoutines_WithAllIntrptAllErr",
want: errBomb,
args: prepareRandomTestArgs(100, 100, 100, errBomb),
n: 100,
},
{
name: "HundredRoutines_WithNoIntrptAllErr",
// since no interrupt hence nil error as an outcome
want: nil,
args: prepareRandomTestArgs(100, 0, 100, errBomb),
n: 100,
},
{
name: "HundredRoutines_WithNoIntrptNoErr",
want: nil,
args: prepareRandomTestArgs(100, 0, 0, errBomb),
n: 100,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
g, ctx := rungroup.WithContext(context.Background())
errorChan := make(chan error, tc.n)
totalChan := make(chan uint64, 1)
go func() {
total := uint64(0)
for range errorChan {
atomic.AddUint64(&total, 1)
}
totalChan <- total
}()
for _, testArg := range tc.args {
testArg := testArg // https://golang.org/doc/faq#closures_and_goroutines , freaking :)
g.GoWithFunc(func(ctx context.Context) error {
err := testArg.f()
errorChan <- err
return err
}, ctx, testArg.interrupter, testArg.id)
}
if err := g.Wait(); err != tc.want {
t.Errorf("after %T.Go() g.Wait() = %v; want %v",
g, err, tc.want)
}
close(errorChan)
totalErrs := <-totalChan
if totalErrs != tc.n {
t.Errorf("number of errors don't match with all func executed(error returned) .\n"+
"Total Err Received: %d, Total Err Expected %d", totalErrs, tc.n)
}
})
}
}
func TestWithContextErrorMap(t *testing.T) {
errorBomb := errors.New("random error bomb")
testCases := []struct {
name string
want error
args []testArg
errorMap concurrent.ConcurrentMap
}{
{
name: "HundredRoutines_WithThirtyPercentWrites_InRWMutexMap",
want: errorBomb,
args: prepareRandomTestArgs(100, 30, 30, errorBomb),
errorMap: concurrent.NewRWMutexMap(),
},
{
name: "HundredRoutines_WithThirtyPercentWrites_InSyncMap",
want: errorBomb,
args: prepareRandomTestArgs(100, 30, 30, errorBomb),
errorMap: new(sync.Map),
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
g, ctx := rungroup.WithContextErrorMap(context.Background(), tc.errorMap)
for _, testArg := range tc.args {
g.Go(testArg.f, testArg.interrupter, testArg.id)
}
if err := g.Wait(); err != tc.want {
t.Errorf("after %T.Go() g.Wait() = %v; want %v",
g, err, tc.want)
}
canceled := false
select {
case <-ctx.Done():
canceled = true
default:
}
if !canceled {
t.Errorf("after %T.Go()"+
"ctx.Done() was not closed",
g)
}
})
}
}
//func prepareArgsWithError() (testWant, testArg) {
// err := errors.New("Error 1")
// want := testWant{
// err: err,
// ok: true,
// }
//}
func TestGroup_GetErrById_GroupNilMapError(t *testing.T) {
want := testWant{
id: "1",
err: rungroup.ErrGroupNilMap,
ok: false,
}
arg := testArg{
f: func() error {
time.Sleep(time.Duration(3) * time.Second)
return nil
},
interrupter: false,
id: "1",
}
g, ctx := rungroup.WithContext(context.Background())
ticker := time.NewTicker(50 * time.Millisecond)
done := make(chan bool)
go func() {
select {
case <-done:
return
case <-ticker.C:
err, ok := g.GetErrByID(want.id)
//fmt.Println(tc.want.err,tc.want.ok, err, ok)
if err != want.err && ok != want.ok {
t.Errorf("%T.GetErrByID returned unexpected error and ok\n"+
"Expected err: %v, Expected ok: %v"+
"Got err: %v, Got ok: %v", g, err, ok, want.err, want.ok)
t.Fail()
ticker.Stop()
done <- true
ctx.Done()
return
}
}
}()
g.Go(arg.f, arg.interrupter, arg.id)
err := g.Wait()
if err != nil {
t.Errorf("unexpected error: %v", err)
}
ticker.Stop()
close(done)
}
func BenchmarkWithContext(b *testing.B) {
for n := 0; n < b.N; n++ {
errorBomb := errors.New("random error bomb")
args := prepareRandomTestArgs(1000, 30, 30, errorBomb)
b.ResetTimer()
g, ctx := rungroup.WithContext(context.Background())
for _, testArg := range args {
g.Go(testArg.f, testArg.interrupter, testArg.id)
}
if err := g.Wait(); err != errorBomb {
b.Errorf("after %T.Go() g.Wait() = %v; want %v",
g, err, err)
}
<-ctx.Done()
}
}
func BenchmarkWithContextErrorMap_RWSafeMap(b *testing.B) {
errorBomb := errors.New("random error bomb")
args := prepareRandomTestArgs(1000, 30, 30, errorBomb)
b.ResetTimer()
benchmarkWithContextErrorMap(concurrent.NewRWMutexMap(), args, errorBomb, b)
}
func BenchmarkWithContextErrorMap_SyncMap(b *testing.B) {
var errMap sync.Map
errorBomb := errors.New("random error bomb")
args := prepareRandomTestArgs(1000, 30, 30, errorBomb)
b.ResetTimer()
benchmarkWithContextErrorMap(&errMap, args, errorBomb, b)
}
func benchmarkWithContextErrorMap(errMap concurrent.ConcurrentMap, args []testArg, errBomb error, b *testing.B) {
for n := 0; n < b.N; n++ {
g, ctx := rungroup.WithContextErrorMap(context.Background(), errMap)
for _, testArg := range args {
g.Go(testArg.f, testArg.interrupter, testArg.id)
}
if err := g.Wait(); err != errBomb {
b.Errorf("after %T.Go() g.Wait() = %v; want %v",
g, err, err)
}
<-ctx.Done()
}
}