Source file
src/fmt/errors_test.go
Documentation: fmt
1
2
3
4
5 package fmt_test
6
7 import (
8 "errors"
9 "fmt"
10 "testing"
11 )
12
13 func TestErrorf(t *testing.T) {
14
15
16 noVetErrorf := fmt.Errorf
17
18 wrapped := errors.New("inner error")
19 for _, test := range []struct {
20 err error
21 wantText string
22 wantUnwrap error
23 }{{
24 err: fmt.Errorf("%w", wrapped),
25 wantText: "inner error",
26 wantUnwrap: wrapped,
27 }, {
28 err: fmt.Errorf("added context: %w", wrapped),
29 wantText: "added context: inner error",
30 wantUnwrap: wrapped,
31 }, {
32 err: fmt.Errorf("%w with added context", wrapped),
33 wantText: "inner error with added context",
34 wantUnwrap: wrapped,
35 }, {
36 err: fmt.Errorf("%s %w %v", "prefix", wrapped, "suffix"),
37 wantText: "prefix inner error suffix",
38 wantUnwrap: wrapped,
39 }, {
40 err: fmt.Errorf("%[2]s: %[1]w", wrapped, "positional verb"),
41 wantText: "positional verb: inner error",
42 wantUnwrap: wrapped,
43 }, {
44 err: fmt.Errorf("%v", wrapped),
45 wantText: "inner error",
46 }, {
47 err: fmt.Errorf("added context: %v", wrapped),
48 wantText: "added context: inner error",
49 }, {
50 err: fmt.Errorf("%v with added context", wrapped),
51 wantText: "inner error with added context",
52 }, {
53 err: noVetErrorf("%w is not an error", "not-an-error"),
54 wantText: "%!w(string=not-an-error) is not an error",
55 }, {
56 err: noVetErrorf("wrapped two errors: %w %w", errString("1"), errString("2")),
57 wantText: "wrapped two errors: 1 %!w(fmt_test.errString=2)",
58 }, {
59 err: noVetErrorf("wrapped three errors: %w %w %w", errString("1"), errString("2"), errString("3")),
60 wantText: "wrapped three errors: 1 %!w(fmt_test.errString=2) %!w(fmt_test.errString=3)",
61 }, {
62 err: fmt.Errorf("%w", nil),
63 wantText: "%!w(<nil>)",
64 wantUnwrap: nil,
65 }} {
66 if got, want := errors.Unwrap(test.err), test.wantUnwrap; got != want {
67 t.Errorf("Formatted error: %v\nerrors.Unwrap() = %v, want %v", test.err, got, want)
68 }
69 if got, want := test.err.Error(), test.wantText; got != want {
70 t.Errorf("err.Error() = %q, want %q", got, want)
71 }
72 }
73 }
74
75 type errString string
76
77 func (e errString) Error() string { return string(e) }
78
View as plain text