-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patherrutil_test.go
476 lines (444 loc) · 10.1 KB
/
errutil_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
package errutil_test
import (
"errors"
"fmt"
"io/fs"
"net"
"os"
"slices"
"testing"
"github.com/jub0bs/errutil"
)
func TestAsPanicsForNonNilErrAndNilTarget(t *testing.T) {
err := errors.New("oh no!")
var target *simpleError
defer func() {
if r := recover(); r == nil {
const tmpl = "As(%v, %T(%v)) did not panic"
t.Errorf(tmpl, err, target, target)
}
}()
errutil.As(err, target)
}
func TestAs(t *testing.T) {
for _, tc := range cases {
f := func(t *testing.T) {
match := errutil.As(tc.err, tc.target)
if match != tc.match {
const tmpl = "errutil.As(err, %[1]T(%[1]v)): got %t; want %t"
t.Fatalf(tmpl, tc.target, match, tc.match)
}
if !match {
return
}
if got := *tc.target; got != tc.want {
t.Fatalf("*target: got %#v; want %#v", got, tc.want)
}
if match != errors.As(tc.err, tc.target) { // sanity check
const tmpl = "errutil.As(err, %[1]T(%[1]v)) != errors.As(err, %[1]T(%[1]v))"
t.Fatalf(tmpl, tc.target)
}
}
t.Run(tc.desc, f)
}
}
// see https://github.com/golang/go/issues/66455#issuecomment-2018372473
func TestAsTargetWiderThanError(t *testing.T) {
err := new(net.DNSError)
type timeouter interface {
Timeout() bool
error
}
var _ timeouter = err
target := new(timeouter)
match := errutil.As(err, target)
if !match {
const tmpl = "errutil.As(err, %[1]T(%[1]v)): got false; want true"
t.Fatalf(tmpl, target)
}
if got := *target; got != err {
t.Fatalf("*target: got %#v; want %#v", got, err)
}
if match != errors.As(err, target) { // sanity check
const tmpl = "errutil.As(err, %[1]T(%[1]v)) != errors.As(err, %[1]T(%[1]v))"
t.Fatalf(tmpl, target)
}
}
func ExampleAs() {
if _, err := os.Open("non-existing"); err != nil {
var pathError *fs.PathError
if errutil.As(err, &pathError) {
fmt.Println("Failed at path:", pathError.Path)
} else {
fmt.Println(err)
}
}
// Output:
// Failed at path: non-existing
}
// In this example, the target's desired type is an interface type other than
// error:
//
// interface { Timeout() bool }
//
// A simple workaround for coaxing [As] into accepting such a target simply
// consists in [embedding] error in the target's desired type.
//
// [embedding]: https://go.dev/ref/spec#Embedded_interfaces
func ExampleAs_interface() {
fakeLookupIP := func(_ string) ([]net.IP, error) {
return nil, &net.DNSError{IsTimeout: true}
}
if _, err := fakeLookupIP("invalid-TLD.123"); err != nil {
var to interface {
Timeout() bool
error // for errutil.As to accept &to as its second argument
}
if errutil.As(err, &to) {
fmt.Printf("Timed out: %t\n", to.Timeout())
} else {
fmt.Println(err)
}
}
// Output:
// Timed out: true
}
func BenchmarkAs(b *testing.B) {
for _, bc := range cases {
f := func(b *testing.B) {
b.ReportAllocs()
for range b.N {
errutil.As(bc.err, bc.target)
}
}
b.Run(bc.desc, f)
}
}
func BenchmarkAsAgainstErrorsPkg(b *testing.B) {
for _, bc := range cases {
f := func(b *testing.B) {
b.ReportAllocs()
for range b.N {
errors.As(bc.err, bc.target)
}
}
b.Run("v=errors/"+bc.desc, f)
f = func(b *testing.B) {
b.ReportAllocs()
for range b.N {
errutil.As(bc.err, bc.target)
}
}
b.Run("v=errutil/"+bc.desc, f)
}
}
func TestFind(t *testing.T) {
for _, tc := range cases {
f := func(t *testing.T) {
got, match := errutil.Find[simpleError](tc.err)
if match != tc.match || got != tc.want {
const tmpl = "errutil.Find(err): got %#v, %t; want %#v, %t"
t.Fatalf(tmpl, got, match, tc.want, tc.match)
}
}
t.Run(tc.desc, f)
}
}
// see https://github.com/golang/go/issues/66455#issuecomment-2018372473
func TestFindTargetWiderThanError(t *testing.T) {
err := new(net.DNSError)
type timeouter interface {
Timeout() bool
error
}
var _ timeouter = err
got, match := errutil.Find[timeouter](err)
want := timeouter(err)
if !match || got != want {
const tmpl = "errutil.Find(err): got %#v, %t; want %#v, true"
t.Fatalf(tmpl, got, match, want)
}
}
func ExampleFind() {
if _, err := os.Open("non-existing"); err != nil {
if pathError, ok := errutil.Find[*fs.PathError](err); ok {
fmt.Println("Failed at path:", pathError.Path)
} else {
fmt.Println(err)
}
}
// Output:
// Failed at path: non-existing
}
// In this example, the result's desired type is an interface type other than
// error:
//
// interface { Timeout() bool }
//
// A simple workaround for coaxing [Find] into accepting such a type argument
// simply consists in [embedding] error in the result's desired type.
//
// [embedding]: https://go.dev/ref/spec#Embedded_interfaces
func ExampleFind_interface() {
fakeLookupIP := func(_ string) ([]net.IP, error) {
return nil, &net.DNSError{IsTimeout: true}
}
if _, err := fakeLookupIP("invalid-TLD.123"); err != nil {
type timeouter interface {
Timeout() bool
error // for errutil.Find to accept timeouter as its type argument
}
if to, ok := errutil.Find[timeouter](err); ok {
fmt.Printf("Timed out: %t\n", to.Timeout())
} else {
fmt.Println(err)
}
}
// Output:
// Timed out: true
}
func BenchmarkFind(b *testing.B) {
for _, bc := range cases {
f := func(b *testing.B) {
b.ReportAllocs()
for range b.N {
errutil.Find[simpleError](bc.err)
}
}
b.Run(bc.desc, f)
}
}
func BenchmarkFindAgainstErrorsPkg(b *testing.B) {
for _, bc := range cases {
f := func(b *testing.B) {
b.ReportAllocs()
for range b.N {
findErrorsPkg[simpleError](bc.err)
}
}
b.Run("v=errors/"+bc.desc, f)
f = func(b *testing.B) {
b.ReportAllocs()
for range b.N {
errutil.Find[simpleError](bc.err)
}
}
b.Run("v=errutil/"+bc.desc, f)
}
}
// A version of errors.Find implemented in terms of errors.As;
// useful for benchmarks.
func findErrorsPkg[T error](err error) (T, bool) {
if err == nil {
var zero T
return zero, false
}
target := new(T)
ok := errors.As(err, target)
return *target, ok
}
type TestCase[T error] struct {
desc string
err error
target *T
match bool
want T
}
var cases = []TestCase[simpleError]{
{
desc: "nil error, nil target",
err: nil,
target: nil,
match: false,
}, {
desc: "nil error, non-nil target",
err: nil,
target: new(simpleError),
match: false,
}, {
desc: "no match",
err: errors.New("oh no!"),
target: new(simpleError),
}, {
desc: "simple match",
err: simpleError{msg: "foo"},
target: new(simpleError),
match: true,
want: simpleError{msg: "foo"},
}, {
desc: "aser",
err: aser{msg: "foo", f: masqueradeAsSimpleError},
target: new(simpleError),
match: true,
want: simpleError{msg: "foo"},
}, {
desc: "wrapper that wraps nil error",
err: wrapper{},
target: new(simpleError),
match: false,
}, {
desc: "wrapper that contains match",
err: wrapper{
simpleError{msg: "foo"},
},
target: new(simpleError),
match: true,
want: simpleError{msg: "foo"},
}, {
desc: "deeply nested wrapper that contains match",
err: wrapper{
wrapper{
wrapper{simpleError{msg: "foo"}},
},
},
target: new(simpleError),
match: true,
want: simpleError{msg: "foo"},
}, {
desc: "wrapper that contains aser",
err: wrapper{
aser{msg: "foo", f: masqueradeAsSimpleError},
},
target: new(simpleError),
match: true,
want: simpleError{msg: "foo"},
}, {
desc: "empty joiner",
err: joiner{},
target: new(simpleError),
match: false,
}, {
desc: "joiner that contains nil",
err: joiner{nil},
target: new(simpleError),
match: false,
}, {
desc: "joiner that contains nil and match",
err: joiner{
nil,
simpleError{msg: "foo"},
},
target: new(simpleError),
match: true,
want: simpleError{msg: "foo"},
}, {
desc: "joiner that contains non-nil and match",
err: joiner{
errors.New("oh no!"),
simpleError{msg: "foo"},
},
target: new(simpleError),
match: true,
want: simpleError{msg: "foo"},
}, {
desc: "joiner that contains match and non-nil",
err: joiner{
simpleError{msg: "foo"},
errors.New("oh no!"),
},
target: new(simpleError),
match: true,
want: simpleError{msg: "foo"},
}, {
desc: "joiner that contains two matches",
err: joiner{
simpleError{msg: "foo"},
simpleError{msg: "bar"},
},
target: new(simpleError),
match: true,
want: simpleError{msg: "foo"},
}, {
desc: "deeply nested joiner that contains non-nil and three matches",
err: joiner{
simpleError{msg: "foo"},
joiner{
errors.New("oh no!"),
simpleError{msg: "bar"},
simpleError{msg: "baz"},
},
},
target: new(simpleError),
match: true,
want: simpleError{msg: "foo"},
}, {
desc: "mix of wrappers and joiners",
err: joiner{
wrapper{
simpleError{msg: "foo"},
},
joiner{
errors.New("oh no!"),
wrapper{simpleError{msg: "bar"}},
simpleError{msg: "baz"},
},
},
target: new(simpleError),
match: true,
want: simpleError{msg: "foo"},
}, {
desc: "mix of wrappers and joiners that contains asers",
err: joiner{
wrapper{
aser{msg: "foo", f: masqueradeAsSimpleError},
},
joiner{
errors.New("oh no!"),
wrapper{aser{msg: "bar", f: masqueradeAsSimpleError}},
aser{msg: "baz", f: masqueradeAsSimpleError},
},
},
target: new(simpleError),
match: true,
want: simpleError{msg: "foo"},
}, {
desc: "joiner that contains many false asers",
err: joiner(slices.Repeat([]error{aser{msg: "foo"}}, 16)),
target: new(simpleError),
match: false,
},
}
type simpleError struct {
msg string
}
func (s simpleError) Error() string {
return s.msg
}
type wrapper struct {
err error
}
func (w wrapper) Error() string {
return ""
}
func (w wrapper) Unwrap() error {
return w.err
}
type joiner []error
func (j joiner) Error() string {
return ""
}
func (j joiner) Unwrap() []error {
return j
}
type aser struct {
msg string
f func(aser, any) bool
}
func (a aser) Error() string {
return a.msg
}
func (a aser) As(target any) bool {
if a.f == nil {
return false
}
return a.f(a, target)
}
func masqueradeAsSimpleError(a aser, target any) bool {
switch x := target.(type) {
case *simpleError:
*x = simpleError{msg: a.msg}
return true
default:
return false
}
}