1
2
3
4
5
6
7
8
9
10
11
12
13 package errors
14
15 import (
16 "encoding/json"
17 "errors"
18 "fmt"
19 "net/http"
20 "regexp"
21 "testing"
22
23 "gitlab.com/flimzy/testy"
24 )
25
26 func TestFormatError(t *testing.T) {
27 type tst struct {
28 err error
29 str string
30 std string
31 full string
32 }
33 tests := testy.NewTable()
34 tests.Add("standard error", tst{
35 err: errors.New("foo"),
36 str: "foo",
37 std: "foo",
38 full: "foo",
39 })
40 tests.Add("not from server", tst{
41 err: &Error{Status: http.StatusNotFound, Err: errors.New("not found")},
42 str: "not found",
43 std: "not found",
44 full: `404 / Not Found: not found`,
45 })
46 tests.Add("with message", tst{
47 err: &Error{Status: http.StatusNotFound, Message: "It's missing", Err: errors.New("not found")},
48 str: "It's missing: not found",
49 std: "It's missing: not found",
50 full: `It's missing: 404 / Not Found: not found`,
51 })
52 tests.Add("embedded error", func() interface{} {
53 _, err := json.Marshal(func() {})
54 return tst{
55 err: &Error{Status: http.StatusBadRequest, Err: err},
56 str: "json: unsupported type: func()",
57 std: "json: unsupported type: func()",
58 full: `400 / Bad Request: json: unsupported type: func()`,
59 }
60 })
61 tests.Add("embedded network error", func() interface{} {
62 client := testy.HTTPClient(func(_ *http.Request) (*http.Response, error) {
63 _, err := json.Marshal(func() {})
64 return nil, &Error{Status: http.StatusBadRequest, Err: err}
65 })
66 req, _ := http.NewRequest(http.MethodGet, "/", nil)
67 _, err := client.Do(req)
68 return tst{
69 err: err,
70 str: "Get /: json: unsupported type: func()",
71 std: "Get /: json: unsupported type: func()",
72 full: "Get /: json: unsupported type: func()",
73 }
74 })
75
76 re := testy.Replacement{
77 Regexp: regexp.MustCompile(`"/"`),
78 Replacement: "/",
79 }
80
81 tests.Run(t, func(t *testing.T, test tst) {
82 if d := testy.DiffText(test.str, test.err.Error(), re); d != nil {
83 t.Errorf("Error():\n%s", d)
84 }
85 if d := testy.DiffText(test.std, fmt.Sprintf("%v", test.err), re); d != nil {
86 t.Errorf("Standard:\n%s", d)
87 }
88 if d := testy.DiffText(test.full, fmt.Sprintf("%+v", test.err), re); d != nil {
89 t.Errorf("Full:\n%s", d)
90 }
91 })
92 }
93
View as plain text