-
Notifications
You must be signed in to change notification settings - Fork 1
/
conc_test.go
432 lines (359 loc) · 10.8 KB
/
conc_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
package gg_test
import (
"context"
e "errors"
"sync"
"testing"
"github.com/mitranim/gg"
"github.com/mitranim/gg/grepr"
"github.com/mitranim/gg/gtest"
)
const (
testErrUntracedA = gg.ErrStr(`test err untraced A`)
testErrUntracedB = gg.ErrStr(`test err untraced B`)
testErrUntracedC = gg.ErrStr(`test err untraced C`)
)
var (
testErrTraced0 = error(gg.Errf(`test err traced 0`))
testErrTraced1 = error(gg.Errf(`test err traced 1`))
testErrTraced2 = error(gg.Errf(`test err traced 2`))
)
func testPanicUntracedA() { panic(testErrUntracedA) }
func testPanicUntracedB() { panic(testErrUntracedB) }
func testPanicTraced0() { panic(testErrTraced0) }
func testPanicTraced1() { panic(testErrTraced1) }
func testNopCtx(context.Context) {}
func testPanicCtxUntracedA(context.Context) { panic(testErrUntracedA) }
func testPanicCtxTraced0(context.Context) { panic(testErrTraced0) }
func testPanicCtxTraced1(context.Context) { panic(testErrTraced1) }
func testPanicCtxTraced2(context.Context) { panic(testErrTraced2) }
func TestConc(t *testing.T) {
defer gtest.Catch(t)
t.Run(`no_panic`, func(t *testing.T) {
defer gtest.Catch(t)
gtest.Zero(gg.ConcCatch())
gtest.Equal(gg.ConcCatch(nil, nil, nil), []error{nil, nil, nil})
gtest.Equal(
gg.ConcCatch(gg.Nop),
[]error{nil},
)
gtest.Equal(
gg.ConcCatch(gg.Nop, gg.Nop),
[]error{nil, nil},
)
gtest.Equal(
gg.ConcCatch(gg.Nop, nil, gg.Nop),
[]error{nil, nil, nil},
)
gtest.Equal(
gg.ConcCatch(nil, gg.Nop, nil, gg.Nop, nil),
[]error{nil, nil, nil, nil, nil},
)
})
t.Run(`only_panic`, func(t *testing.T) {
defer gtest.Catch(t)
testWrappedErrs(
gg.ConcCatch(testPanicUntracedA),
[]error{testErrUntracedA},
)
gtest.Equal(
gg.ConcCatch(testPanicTraced0),
[]error{testErrTraced0},
`when only one function is provided and it panics with a traced error, that error must be preserved as-is without redundant wrapping`,
)
testWrappedErrs(
gg.ConcCatch(testPanicUntracedA, testPanicUntracedB),
[]error{testErrUntracedA, testErrUntracedB},
)
testWrappedErrs(
gg.ConcCatch(testPanicTraced0, testPanicTraced1),
[]error{testErrTraced0, testErrTraced1},
)
})
t.Run(`mixed`, func(t *testing.T) {
defer gtest.Catch(t)
testWrappedErrs(
gg.ConcCatch(gg.Nop, testPanicUntracedA, gg.Nop, testPanicTraced1, gg.Nop),
gg.Errs{nil, testErrUntracedA, nil, testErrTraced1, nil},
)
})
}
func testWrappedErr(act, exp error, opt ...any) {
gtest.ErrIs(act, exp, opt...)
gtest.NotIs(act, exp, opt...)
if act != nil && !gg.IsErrTraced(act) {
panic(gg.Errv(gg.JoinLines(
`unexpected lack of stack trace in error:`,
grepr.StringIndent(act, 1),
gtest.MsgExtra(opt...),
)))
}
}
func testWrappedErrs(act, exp []error, opt ...any) {
gtest.Len(act, len(exp))
msgAll := gg.JoinLinesOpt(
`all errors:`,
grepr.StringIndent(act, 1),
gtest.MsgExtra(opt...),
)
for ind, val := range act {
if val != nil && !gg.IsErrTraced(val) {
panic(gg.Errv(gg.JoinLinesOpt(
gg.Str(`expected every error to be traced, found untraced at index `, ind),
msgAll,
)))
}
}
for ind, valAct := range act {
valExp := exp[ind]
if valExp == nil {
if valAct != nil {
panic(gg.JoinLinesOpt(
gg.Str(`unexpected non-nil error at index `, ind),
msgAll,
))
}
continue
}
if !e.Is(valAct, valExp) {
panic(gg.JoinLinesOpt(
gtest.MsgErrIsMismatch(valAct, valExp),
msgAll,
))
}
if gg.Is(valAct, valExp) {
panic(gg.JoinLinesOpt(
gg.Str(`unexpected unwrapped error at index `, ind),
msgAll,
))
}
}
}
func BenchmarkConcCatch_one(b *testing.B) {
for ind := 0; ind < b.N; ind++ {
_ = gg.ConcCatch(testPanicTraced0)
}
}
func BenchmarkConcCatch_multi(b *testing.B) {
for ind := 0; ind < b.N; ind++ {
_ = gg.ConcCatch(gg.Nop, testPanicTraced0, gg.Nop, testPanicTraced1, gg.Nop)
}
}
// Needs more test cases.
func TestConcMapCatch(t *testing.T) {
defer gtest.Catch(t)
src := []int{10, 20, 30}
vals, errs := gg.ConcMapCatch(src, testConcMapFunc)
gtest.Len(vals, len(src))
gtest.Len(errs, len(src))
gtest.Equal(vals, []string{`10`, ``, `30`})
testWrappedErrs(errs, []error{nil, testErrTraced1, nil})
}
func testConcMapFunc(src int) string {
if src == 20 {
panic(testErrTraced1)
}
return gg.String(src)
}
// Needs more test cases.
func TestConcRace(t *testing.T) {
defer gtest.Catch(t)
//nolint:staticcheck
gtest.Zero(gg.ConcRace().RunCatch(nil))
//nolint:staticcheck
gtest.Zero(gg.ConcRace(nil).RunCatch(nil))
//nolint:staticcheck
gtest.Zero(gg.ConcRace(testNopCtx).RunCatch(nil))
ctx := context.Background()
gtest.Zero(gg.ConcRace().RunCatch(ctx))
gtest.Zero(gg.ConcRace(nil).RunCatch(ctx))
gtest.Zero(gg.ConcRace(nil, nil).RunCatch(ctx))
gtest.Zero(gg.ConcRace(nil, nil, nil).RunCatch(ctx))
gtest.Zero(gg.ConcRace(testNopCtx).RunCatch(ctx))
gtest.Zero(gg.ConcRace(testNopCtx, testNopCtx).RunCatch(ctx))
gtest.Zero(gg.ConcRace(testNopCtx, testNopCtx, testNopCtx).RunCatch(ctx))
gtest.Is(
//nolint:staticcheck
gg.ConcRace(testPanicCtxTraced0).RunCatch(nil),
testErrTraced0,
)
testWrappedErr(
gg.ConcRace(testPanicCtxUntracedA).RunCatch(ctx),
testErrUntracedA,
`when only one function is provided and it panics with an untraced error, that error must be wrapped with a trace`,
)
gtest.Is(
gg.ConcRace(testPanicCtxTraced0).RunCatch(ctx),
testErrTraced0,
`when only one function is provided and it panics with a traced error, that error must be returned as-is`,
)
testWrappedErr(
gg.ConcRace(testPanicCtxUntracedA, testNopCtx).RunCatch(ctx),
testErrUntracedA,
`when multiple functions are provided and one panics with an untraced error, that error must be wrapped with a trace`,
)
testWrappedErr(
gg.ConcRace(testPanicCtxTraced0, testNopCtx).RunCatch(ctx),
testErrTraced0,
`when multiple functions are provided and one panics with a traced error, that error must be wrapped with an additional trace`,
)
testWrappedErr(
gg.ConcRace(testNopCtx, testPanicCtxTraced0).RunCatch(ctx),
testErrTraced0,
)
testWrappedErr(
gg.ConcRace(testNopCtx, testPanicCtxTraced0, testNopCtx).RunCatch(ctx),
testErrTraced0,
)
testWrappedErr(
gg.ConcRace(testPanicCtxTraced0, testPanicCtxTraced0).RunCatch(ctx),
testErrTraced0,
)
testWrappedErr(
gg.ConcRace(testPanicCtxTraced0, testPanicCtxTraced0, testPanicCtxTraced0).RunCatch(ctx),
testErrTraced0,
)
// TODO: would be ideal to also verify wrapping via `testWrappedErr`.
gtest.Has(
[]string{testErrTraced0.Error(), testErrTraced1.Error(), testErrTraced2.Error()},
gg.ConcRace(testPanicCtxTraced0, testPanicCtxTraced1, testPanicCtxTraced2).RunCatch(ctx).Error(),
)
/**
Every function must receive the same cancelable context, and the context
must be canceled after completion, regardless if we have full success,
partial success, or full failure.
*/
{
test := func(funs ...func(context.Context)) {
conc := make(gg.ConcRaceSlice, len(funs))
ctxs := make([]context.Context, len(funs))
// This test requires additional syncing because `.Run` or `.RunCatch`
// terminate on the first panic, without waiting for the termination
// of the remaining functions. This is by design, but in this test,
// we must wait for their termination to ensure that the slice of
// contexts is fully mutated.
var gro sync.WaitGroup
for ind, fun := range funs {
ind, fun := ind, fun
gro.Add(1)
conc.Add(func(ctx context.Context) {
defer gro.Add(-1)
ctxs[ind] = ctx
fun(ctx)
})
}
gg.Nop1(conc.RunCatch(ctx))
gro.Wait()
testIsContextConsistent(ctxs...)
testIsCtxCanceled(ctxs[0])
}
test(testNopCtx)
test(testNopCtx, testNopCtx)
test(testNopCtx, testNopCtx, testNopCtx)
test(testPanicCtxTraced0, testNopCtx, testNopCtx)
test(testNopCtx, testPanicCtxTraced0, testNopCtx)
test(testNopCtx, testNopCtx, testPanicCtxTraced0)
test(testPanicCtxTraced0, testNopCtx, testPanicCtxTraced0)
test(testPanicCtxTraced0, testPanicCtxTraced0, testPanicCtxTraced0)
}
/**
On the first panic, we must immediately cancel the context before returning
the caught error. Some of the concurrently launched functions may still
continue running in the background. They're expected to respect context
cancelation and terminate as soon as reasonably possible, but that's up
to the user of the library. Our responsibility is to terminate and cancel
as soon as the first panic is found.
*/
{
var gro0 sync.WaitGroup
var gro1 sync.WaitGroup
var state0 CtxState
var state1 CtxState
var state2 CtxState
gro0.Add(1)
gro1.Add(2)
testWrappedErr(
/**
This must terminate and return the error even though some inner functions
are still blocked on the wait group, which is unblocked AFTER this test
phase. This ensures that the concurrent run terminates on the first
panic without waiting for all functions. Otherwise, the test would
deadlock and eventually time out.
*/
gg.ConcRace(
func(ctx context.Context) {
defer gro1.Add(-1)
gro0.Wait()
state0 = ToCtxState(ctx)
},
func(ctx context.Context) {
state1 = ToCtxState(ctx)
panic(testErrTraced0)
},
func(ctx context.Context) {
defer gro1.Add(-1)
gro0.Wait()
state2 = ToCtxState(ctx)
},
).RunCatch(ctx),
testErrTraced0,
)
// This should unblock the inner functions, whose context must now be
// canceled.
gro0.Add(-1)
gro1.Wait()
gtest.Equal(state0, CtxState{true, context.Canceled})
gtest.Equal(state1, CtxState{false, nil})
gtest.Equal(state2, CtxState{true, context.Canceled})
}
}
/*
Caution: this operation is prone to race conditions, and may produce
"corrupted" states, such as `{Done: false, Err: context.Canceled}`,
depending on the execution timing. Our tests ensure that we always
see very specific results, and anything else is considered a test
failure. Avoid this pattern in actual code.
*/
func ToCtxState(ctx context.Context) CtxState {
return CtxState{isCtxDone(ctx), ctx.Err()}
}
type CtxState struct {
Done bool
Err error
}
func testIsContextConsistent(vals ...context.Context) {
if len(vals) <= 1 {
return
}
exp := vals[0]
gtest.NotZero(exp)
for _, val := range vals {
if exp != val {
panic(gtest.ErrLines(
`unexpected difference between context values`,
gtest.MsgEqDetailed(val, exp),
))
}
}
}
func testIsCtxCanceled(ctx context.Context) {
if !isCtxDone(ctx) {
panic(`expected context to be done`)
}
gtest.ErrIs(ctx.Err(), context.Canceled)
}
/*
Warning: the output is correct only when it's `true`. When the output is
`false`, then sometimes it's incorrect and the actual result is UNKNOWN
because the channel may be concurrently closed before your next line of code.
In other words, the return type of this function isn't exactly a boolean.
It's a union of "true" and "unknowable".
*/
func isCtxDone(ctx context.Context) bool {
select {
case <-ctx.Done():
return true
default:
return false
}
}