1 package errwrap
2
3 import (
4 "errors"
5 "fmt"
6 "testing"
7 )
8
9 func TestWrappedError_impl(t *testing.T) {
10 var _ error = new(wrappedError)
11 }
12
13 func TestGetAll(t *testing.T) {
14 cases := []struct {
15 Err error
16 Msg string
17 Len int
18 }{
19 {},
20 {
21 fmt.Errorf("foo"),
22 "foo",
23 1,
24 },
25 {
26 fmt.Errorf("bar"),
27 "foo",
28 0,
29 },
30 {
31 Wrapf("bar", fmt.Errorf("foo")),
32 "foo",
33 1,
34 },
35 {
36 Wrapf("{{err}}", fmt.Errorf("foo")),
37 "foo",
38 2,
39 },
40 {
41 Wrapf("bar", Wrapf("baz", fmt.Errorf("foo"))),
42 "foo",
43 1,
44 },
45 {
46 fmt.Errorf("foo: %w", fmt.Errorf("bar")),
47 "foo: bar",
48 1,
49 },
50 {
51 fmt.Errorf("foo: %w", fmt.Errorf("bar")),
52 "bar",
53 1,
54 },
55 }
56
57 for i, tc := range cases {
58 actual := GetAll(tc.Err, tc.Msg)
59 if len(actual) != tc.Len {
60 t.Fatalf("%d: bad: %#v", i, actual)
61 }
62 for _, v := range actual {
63 if v.Error() != tc.Msg {
64 t.Fatalf("%d: bad: %#v", i, actual)
65 }
66 }
67 }
68 }
69
70 func TestGetAllType(t *testing.T) {
71 cases := []struct {
72 Err error
73 Type interface{}
74 Len int
75 }{
76 {},
77 {
78 fmt.Errorf("foo"),
79 "foo",
80 0,
81 },
82 {
83 fmt.Errorf("bar"),
84 fmt.Errorf("foo"),
85 1,
86 },
87 {
88 Wrapf("bar", fmt.Errorf("foo")),
89 fmt.Errorf("baz"),
90 2,
91 },
92 {
93 Wrapf("bar", Wrapf("baz", fmt.Errorf("foo"))),
94 Wrapf("", nil),
95 0,
96 },
97 {
98 fmt.Errorf("one: %w", fmt.Errorf("two: %w", fmt.Errorf("three"))),
99 fmt.Errorf("%w", errors.New("")),
100 2,
101 },
102 }
103
104 for i, tc := range cases {
105 actual := GetAllType(tc.Err, tc.Type)
106 if len(actual) != tc.Len {
107 t.Fatalf("%d: bad: %#v", i, actual)
108 }
109 }
110 }
111
112 func TestWrappedError_IsCompatibleWithErrorsUnwrap(t *testing.T) {
113 inner := errors.New("inner error")
114 err := Wrap(errors.New("outer"), inner)
115 actual := errors.Unwrap(err)
116 if actual != inner {
117 t.Fatal("wrappedError did not unwrap to inner")
118 }
119 }
120
View as plain text