-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patherrhandler_test.go
103 lines (93 loc) · 2.58 KB
/
errhandler_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package errhandler
import (
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
// TestWrap_ServeHTTP tests the ServeHTTP method of the Wrap type.
func TestWrap_ServeHTTP(t *testing.T) {
tests := []struct {
name string
body string
handler Wrap
expectedStatus int
expectedBody string
}{
{
name: "parse json without error",
body: `{"a": 1}`,
handler: Wrap(func(w http.ResponseWriter, r *http.Request) error {
m := map[string]int{}
return ParseJSON(r, &m)
}),
expectedStatus: http.StatusOK,
expectedBody: "",
},
{
name: "parse json with error",
body: "a",
handler: Wrap(func(w http.ResponseWriter, r *http.Request) error {
m := map[string]int{}
return ParseJSON(r, &m)
}),
expectedStatus: http.StatusInternalServerError,
expectedBody: "invalid character 'a' looking for beginning of value\n",
},
{
name: "send string without error",
handler: Wrap(func(w http.ResponseWriter, r *http.Request) error {
return SendString(w, "test")
}),
expectedStatus: http.StatusOK,
expectedBody: "test",
},
{
name: "send json without error",
handler: Wrap(func(w http.ResponseWriter, r *http.Request) error {
return SendJSON(w, map[string]int{"a": 1})
}),
expectedStatus: http.StatusOK,
expectedBody: "{\"a\":1}\n",
},
{
name: "send error",
handler: Wrap(func(w http.ResponseWriter, r *http.Request) error {
return Error(http.StatusUnprocessableEntity, fmt.Errorf("error doing stuff: %w", errors.New("database error")))
}),
expectedStatus: http.StatusUnprocessableEntity,
expectedBody: "error doing stuff: database error\n",
},
{
name: "error",
handler: Wrap(func(w http.ResponseWriter, r *http.Request) error {
return fmt.Errorf("error doing stuff: %w", errors.New("database error"))
}),
expectedStatus: http.StatusInternalServerError,
expectedBody: "error doing stuff: database error\n",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var body io.Reader
if tt.body != "" {
body = strings.NewReader(tt.body)
}
req := httptest.NewRequest(http.MethodGet, "http://example.com/foo", body)
w := httptest.NewRecorder()
tt.handler.ServeHTTP(w, req)
res := w.Result()
defer res.Body.Close()
if res.StatusCode != tt.expectedStatus {
t.Errorf("expected status %d, got %d", tt.expectedStatus, res.StatusCode)
}
actualBody := w.Body.String()
if actualBody != tt.expectedBody {
t.Errorf("expected body %q, got %q", tt.expectedBody, actualBody)
}
})
}
}