| 144 | } |
| 145 | |
| 146 | func TestFormat(t *testing.T) { |
| 147 | e1 := errtrace.New("e1") |
| 148 | e2 := errtrace.Errorf("e2: %w", e1) |
| 149 | e3 := errtrace.Wrap(e2) |
| 150 | |
| 151 | tests := []struct { |
| 152 | name string |
| 153 | err error |
| 154 | want string |
| 155 | wantTraces int |
| 156 | }{ |
| 157 | { |
| 158 | name: "new error", |
| 159 | err: e1, |
| 160 | want: "e1", |
| 161 | wantTraces: 1, |
| 162 | }, |
| 163 | { |
| 164 | name: "wrapped with Errorf", |
| 165 | err: e2, |
| 166 | want: "e2: e1", |
| 167 | wantTraces: 2, |
| 168 | }, |
| 169 | { |
| 170 | name: "wrap after Errorf", |
| 171 | err: e3, |
| 172 | want: "e2: e1", |
| 173 | wantTraces: 3, |
| 174 | }, |
| 175 | } |
| 176 | |
| 177 | for _, tt := range tests { |
| 178 | t.Run(tt.name, func(t *testing.T) { |
| 179 | if want, got := tt.want, fmt.Sprintf("%s", tt.err); want != got { |
| 180 | t.Errorf("message: want %q, got: %q", want, got) |
| 181 | } |
| 182 | |
| 183 | withTrace := fmt.Sprintf("%+v", tt.err) |
| 184 | if !strings.HasPrefix(withTrace, tt.want) { |
| 185 | t.Errorf("expected error message %q in trace:\n%s", tt.want, withTrace) |
| 186 | } |
| 187 | if want, got := tt.wantTraces, strings.Count(withTrace, "errtrace_test.TestFormat"); want != got { |
| 188 | t.Errorf("expected traces %v, got %v in:\n%s", want, got, withTrace) |
| 189 | } |
| 190 | }) |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | func BenchmarkWrap(b *testing.B) { |
| 195 | err := errors.New("foo") |