Source file
src/errors/join_test.go
1
2
3
4
5 package errors_test
6
7 import (
8 "errors"
9 "reflect"
10 "testing"
11 )
12
13 func TestJoinReturnsNil(t *testing.T) {
14 if err := errors.Join(); err != nil {
15 t.Errorf("errors.Join() = %v, want nil", err)
16 }
17 if err := errors.Join(nil); err != nil {
18 t.Errorf("errors.Join(nil) = %v, want nil", err)
19 }
20 if err := errors.Join(nil, nil); err != nil {
21 t.Errorf("errors.Join(nil, nil) = %v, want nil", err)
22 }
23 }
24
25 func TestJoin(t *testing.T) {
26 err1 := errors.New("err1")
27 err2 := errors.New("err2")
28 for _, test := range []struct {
29 errs []error
30 want []error
31 }{{
32 errs: []error{err1},
33 want: []error{err1},
34 }, {
35 errs: []error{err1, err2},
36 want: []error{err1, err2},
37 }, {
38 errs: []error{err1, nil, err2},
39 want: []error{err1, err2},
40 }} {
41 got := errors.Join(test.errs...).(interface{ Unwrap() []error }).Unwrap()
42 if !reflect.DeepEqual(got, test.want) {
43 t.Errorf("Join(%v) = %v; want %v", test.errs, got, test.want)
44 }
45 if len(got) != cap(got) {
46 t.Errorf("Join(%v) returns errors with len=%v, cap=%v; want len==cap", test.errs, len(got), cap(got))
47 }
48 }
49 }
50
51 func TestJoinErrorMethod(t *testing.T) {
52 err1 := errors.New("err1")
53 err2 := errors.New("err2")
54 for _, test := range []struct {
55 errs []error
56 want string
57 }{{
58 errs: []error{err1},
59 want: "err1",
60 }, {
61 errs: []error{err1, err2},
62 want: "err1\nerr2",
63 }, {
64 errs: []error{err1, nil, err2},
65 want: "err1\nerr2",
66 }} {
67 got := errors.Join(test.errs...).Error()
68 if got != test.want {
69 t.Errorf("Join(%v).Error() = %q; want %q", test.errs, got, test.want)
70 }
71 }
72 }
73
74 func BenchmarkJoin(b *testing.B) {
75 for _, bb := range []struct {
76 name string
77 errs []error
78 }{
79 {
80 name: "no error",
81 },
82 {
83 name: "single non-nil error",
84 errs: []error{errors.New("err")},
85 },
86 {
87 name: "multiple errors",
88 errs: []error{errors.New("err"), errors.New("newerr"), errors.New("newerr2")},
89 },
90 {
91 name: "unwrappable single error",
92 errs: []error{errors.Join(errors.New("err"))},
93 },
94 {
95 name: "nil first error",
96 errs: []error{nil, errors.New("newerr")},
97 },
98 } {
99 b.Run(bb.name, func(b *testing.B) {
100 b.ReportAllocs()
101 for i := 0; i < b.N; i++ {
102 _ = errors.Join(bb.errs...)
103 }
104 })
105 }
106 }
107
View as plain text