-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy patherrc_test.go
502 lines (466 loc) · 11.6 KB
/
errc_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
package errc
import (
"bytes"
"errors"
"fmt"
"io"
"strings"
"testing"
)
const (
success = iota
deferError
deferPanic
retError
bodyPanic
numAction
)
func actionStr(action int) string {
switch action {
case success:
return "success"
case deferError:
return "closeErr"
case retError:
return "retErr"
case bodyPanic:
return "panic"
case deferPanic:
return "panicInDefer"
}
panic("ex: unreachable")
}
var (
testCases = [][]int{
{success},
{deferError},
{deferPanic},
{retError},
{bodyPanic},
}
retErrors, deferErrors, panicErrors, deferPanicErrors []error
)
func init() {
// Add new test cases, each time adding one of two digits to each existing
// one.
for i := 0; i < 3; i++ {
prev := testCases
for j := success; j < retError; j++ {
for _, tc := range prev {
testCases = append(testCases, append([]int{j}, tc...))
}
}
}
// pre-allocate sufficient return and close errors
for id := 0; id < 10; id++ {
retErrors = append(retErrors, fmt.Errorf("return-err:%d", id))
deferErrors = append(deferErrors, fmt.Errorf("close-err:%d", id))
panicErrors = append(panicErrors, fmt.Errorf("panic-err:%d", id))
deferPanicErrors = append(deferPanicErrors, fmt.Errorf("defer-panic-err:%d", id))
}
}
type idCloser struct {
id int
action int
w io.Writer
}
func (c *idCloser) Close() error {
if c.w != nil {
fmt.Fprintln(c.w, "closed", c.id)
}
switch c.action {
case deferError:
return deferErrors[c.id]
case deferPanic:
panic(deferPanicErrors[c.id])
}
return nil
}
func (c *idCloser) CloseWithError(err error) error {
if c.w != nil {
if err == nil {
fmt.Fprintln(c.w, "closed", c.id)
} else {
fmt.Fprint(c.w, "closed with error: ", c.id)
fmt.Fprintln(c.w, ":", err)
}
}
switch c.action {
case deferError:
return deferErrors[c.id]
case deferPanic:
panic(deferPanicErrors[c.id])
}
return nil
}
type errFunc func() error
// TestConformance simulates 1 or more blocks of creating values and handling
// errors and defers and compares the result of using the traditional style Go
// and using package errd.
func TestConformanceDefer(t *testing.T) {
for _, tc := range testCases {
t.Run(key(tc), func(t *testing.T) {
want := simulate(tc, properTraditionalDefer)
got := simulate(tc, errdClosureDefer)
if got != want {
t.Errorf("\n=== got:\n%s=== want:\n%s", got, want)
}
})
}
}
// idiomaticTraditionalDefer is how error handling is usually done manually for
// the case described in TestConformance. However, this approach may miss
// detecting and returning errors and is not correct in the general case.
// We include this set for illustrative purposes, including benchmarks, where
// it can be used to show the cost of doing things more properly.
func idiomaticTraditionalDefer(w io.Writer, actions []int) errFunc {
closers := make([]idCloser, len(actions))
return func() error {
for i, a := range actions {
c, err := retDefer(w, closers, i, a)
if err != nil {
return err
}
defer c.Close()
}
return nil
}
}
// properTraditionalDefer goes beyond the common ways in which errors are
// handled and also detects errors resulting from close.
func properTraditionalDefer(w io.Writer, actions []int) errFunc {
closers := make([]idCloser, len(actions))
return func() (errOut error) {
for i, a := range actions {
c, err := retDefer(w, closers, i, a)
if err != nil {
return err
}
defer func() {
if err := c.Close(); err != nil && errOut == nil {
errOut = err
}
}()
}
return nil
}
}
func errdClosureDefer(w io.Writer, actions []int) errFunc {
closers := make([]idCloser, len(actions))
return func() (err error) {
e := Catch(&err)
defer e.Handle()
for i, a := range actions {
c, err := retDefer(w, closers, i, a)
e.Must(err)
e.Defer(c.Close)
}
return err
}
}
func errdFuncDefer(w io.Writer, actions []int) errFunc {
closers := make([]idCloser, len(actions))
return func() (err error) {
e := Catch(&err)
defer e.Handle()
for i, a := range actions {
c, err := retDefer(w, closers, i, a)
e.Must(err)
e.deferFunc(c, close)
}
return err
}
}
// TestConformanceWithError simulates 1 or more blocks of creating values and
// handling errors and defers, where the deferred function needs to be passed
// *any* earlier occurring error, including those from panics and those
// originating in other defer blocks.
func TestConformanceDeferWithError(t *testing.T) {
for _, tc := range testCases {
t.Run(key(tc), func(t *testing.T) {
want := simulate(tc, pedanticTraditionalDeferWithError)
got := simulate(tc, errdClosureDeferWithError)
if got != want {
t.Errorf("\n=== got:\n%s=== want:\n%s", got, want)
}
})
}
}
// pedanticTraditionalDeferWithError implements a way to catch ALL errors
// preceding a call to CloseWithError, including panics in the body and
// other defers, without using the errd package.
func pedanticTraditionalDeferWithError(w io.Writer, actions []int) errFunc {
closers := make([]idCloser, len(actions))
return func() (errOut error) {
var isPanic bool
defer func() {
// We may still have a panic after our last call to defer so catch.
if r := recover(); r != nil {
panic(r)
}
// Panic again for panics we caught earlier to pass to defers.
if isPanic {
panic(errOut)
}
}()
for i, a := range actions {
c, err := retDeferWithErr(w, closers, i, a)
if err != nil {
return err
}
defer func() {
// We need to recover any possible panic to not miss out on
// passing the panic. Panics override any previous error.
if r := recover(); r != nil {
switch v := r.(type) {
case error:
errOut = v
default:
errOut = fmt.Errorf("%v", v)
}
isPanic = true
}
if errOut != nil {
c.CloseWithError(errOut)
} else {
if err := c.Close(); err != nil && errOut == nil {
errOut = err
}
}
}()
}
return nil
}
}
func errdClosureDeferWithError(w io.Writer, actions []int) errFunc {
closers := make([]idCloser, len(actions))
return func() (err error) {
e := Catch(&err)
defer e.Handle()
for i, a := range actions {
c, err := retDeferWithErr(w, closers, i, a)
e.Must(err, identity)
e.Defer(c.CloseWithError)
}
return nil
}
}
func errdFuncDeferWithError(w io.Writer, actions []int) errFunc {
closers := make([]idCloser, len(actions))
return func() (err error) {
e := Catch(&err)
defer e.Handle()
for i, a := range actions {
c, err := retDeferWithErr(w, closers, i, a)
e.Must(err, identity)
e.deferFunc(c, closeWithErrorFunc)
}
return nil
}
}
type benchCase struct {
name string
f func(w io.Writer, actions []int) errFunc
}
var testFuncsDeferClose = []benchCase{
{"idiomatic traditional", idiomaticTraditionalDefer},
{"proper traditional", properTraditionalDefer},
{"errd/closer", errdClosureDefer},
}
var testFuncsDeferCloseWithError = []benchCase{
{"traditional/closerwe", pedanticTraditionalDeferWithError},
{"errd/closerwe", errdClosureDeferWithError},
}
var testFuncsNoDefer = []benchCase{
{"traditional", traditionalCheck},
{"errd", errdClosureCheck},
}
func traditionalCheck(w io.Writer, actions []int) errFunc {
return func() (err error) {
for i, a := range actions {
err := retNoDefer(w, i, a)
if err != nil {
return err
}
}
return nil
}
}
func errdClosureCheck(w io.Writer, actions []int) errFunc {
return func() (err error) {
e := Catch(&err)
defer e.Handle()
for i, a := range actions {
e.Must(retNoDefer(w, i, a))
}
return nil
}
}
func retDefer(w io.Writer, closers []idCloser, id, action int) (io.Closer, error) {
// pre-allocate io.Closers. This is not realistice, but eliminates this
// allocation from the measurements.
closers[id] = idCloser{id, action, w}
switch action {
case success, deferError, deferPanic:
return &closers[id], nil
case retError:
return nil, retErrors[id]
case bodyPanic:
panic(panicErrors[id])
}
panic("errd: unreachable")
}
func retDeferWithErr(w io.Writer, closers []idCloser, id, action int) (closerWithError, error) {
// pre-allocate io.Closers. This is not realistice, but eliminates this
// allocation from the measurements.
closers[id] = idCloser{id, action, w}
switch action {
case success, deferError, deferPanic:
return &closers[id], nil
case retError:
return nil, retErrors[id]
case bodyPanic:
panic(panicErrors[id])
}
panic("errd: unreachable")
}
func retNoDefer(w io.Writer, id, action int) error {
// pre-allocate io.Closers. This is not realistice, but eliminates this
// allocation from the measurements.
switch action {
case success:
return nil
case retError:
return retErrors[id]
case bodyPanic:
panic(panicErrors[id])
}
panic("errd: unreachable")
}
func key(test []int) (key string) {
s := []string{}
for _, a := range test {
s = append(s, actionStr(a))
}
return strings.Join(s, "-")
}
func simulate(actions []int, f func(w io.Writer, actions []int) errFunc) (result string) {
w := &bytes.Buffer{}
defer func() {
if err := recover(); err != nil {
fmt.Fprintf(w, "P:%v\n", err)
}
result = w.String()
}()
fmt.Fprintln(w, f(w, actions)())
return "" // set in defer
}
var benchCases = []struct {
allocs int // number of extra allocs
actions []int
}{
{0, []int{success}},
{0, []int{success, success}},
{0, []int{success, success, success}},
{1, []int{success, success, success, success}},
// Uncomment these for more benchmarks.
// {1, []int{success, success, success, success, success}},
// {0, []int{retError}},
// {0, []int{success, retError}},
// {0, []int{success, success, retError}},
// {0, []int{success, success, success, retError}},
// {1, []int{success, success, success, success, retError}},
}
func runBenchCases(b *testing.B, bf []benchCase) {
for _, bc := range benchCases {
for _, bf := range bf {
b.Run(key(bc.actions)+"/"+bf.name, func(b *testing.B) {
f := bf.f(nil, bc.actions)
for i := 0; i < b.N; i++ {
f()
}
})
}
}
}
func BenchmarkNoDefer(b *testing.B) {
runBenchCases(b, testFuncsNoDefer)
}
func BenchmarkDeferClose(b *testing.B) {
runBenchCases(b, testFuncsDeferClose)
}
func BenchmarkDeferCloseWithError(b *testing.B) {
runBenchCases(b, testFuncsDeferCloseWithError)
}
func TestPanic(t *testing.T) {
errFoo := errors.New("foo")
testCases := []struct {
f func(e *Catcher)
p interface{}
err string
noPanic bool
}{{
f: func(e *Catcher) {
},
p: nil,
noPanic: true,
}, {
f: func(e *Catcher) {
panic("bar")
},
p: "bar",
err: "errd: paniced: bar",
}, {
f: func(e *Catcher) {
panic(errFoo)
},
p: errFoo,
err: "foo",
}, {
f: func(e *Catcher) {
panic(2)
},
p: 2,
err: "errd: paniced: 2",
}, {
f: func(e *Catcher) {
e.deferFunc(nil, nil) // panic: nil func
},
p: errNilFunc,
err: errNilFunc.Error(),
}, {
f: func(e *Catcher) {
e.Defer(1) // panic: not supported
},
err: "errd: type int not supported by Defer",
}}
for _, tc := range testCases {
paniced := false
panicHandler := HandlerFunc(func(s State, err error) error {
paniced = s.Panicking()
return err
})
t.Run("", func(t *testing.T) {
defer func() {
r := recover()
if tc.p != nil && (r == nil || r != nil && r != tc.p) {
t.Errorf("got %v; want %v", r, tc.p)
}
if paniced != !tc.noPanic {
t.Errorf("got %v; want %v", paniced, !tc.noPanic)
}
}()
var err error
e := Catch(&err, panicHandler)
defer e.Handle()
e.deferFunc(nil, func(s State, x interface{}) error {
err := s.Err()
if err == nil && tc.err != "" || err != nil && err.Error() != tc.err {
t.Errorf("got %q; want %q", err, tc.err)
}
return err
})
tc.f(&e)
})
}
}