-
Notifications
You must be signed in to change notification settings - Fork 0
/
jhttp_test.go
232 lines (200 loc) · 6.71 KB
/
jhttp_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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
package jhttp
import (
"bytes"
"context"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/require"
"github.com/s12chung/text2anki/pkg/util/test"
"github.com/s12chung/text2anki/pkg/util/test/fixture/flog"
)
func init() {
SetLog(flog.FixtureUpdateNoWrite())
}
type testContextKey string
const contextKey testContextKey = "key"
func TestRequestWrap(t *testing.T) {
var testVal string
var testStatus int
var testErr error
handler := RequestWrap(func(r *http.Request) (*http.Request, *HTTPError) {
r = r.WithContext(context.WithValue(r.Context(), contextKey, testVal))
if testStatus != http.StatusOK {
return nil, Error(testStatus, testErr)
}
return r, nil
})(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
val, ok := r.Context().Value(contextKey).(string)
if !ok {
http.Error(w, "bad string", http.StatusInternalServerError)
}
if _, err := fmt.Fprint(w, val); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}))
testCases := []struct {
name string
val string
status int
err error
expectedBody string
}{
{name: "normal", val: "123", status: http.StatusOK, expectedBody: "123"},
{name: "err", status: http.StatusUnprocessableEntity, err: errors.New("unprocessible"),
expectedBody: "{\"error\":\"unprocessible\",\"code\":422,\"status_text\":\"Unprocessable Entity\"}\n"},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
require := require.New(t)
testVal, testStatus, testErr = tc.val, tc.status, tc.err
resp := httptest.NewRecorder()
handler.ServeHTTP(resp, httptest.NewRequest(http.MethodGet, "/", nil))
require.Equal(tc.status, resp.Code)
require.Equal(tc.expectedBody, resp.Body.String())
})
}
}
type testObj struct {
Val string `json:"val,omitempty"`
}
func TestRespondJSONWrap(t *testing.T) {
var testVal string
var testStatus int
var testErr error
handlerFunc := ResponseWrap(func(r *http.Request) (any, *HTTPError) {
if r.Method != http.MethodGet {
return nil, Error(http.StatusInternalServerError, errors.New("not a GET"))
}
if testStatus != http.StatusOK {
return nil, Error(testStatus, testErr)
}
return testObj{Val: testVal}, nil
})
testCases := []struct {
name string
method string
val string
status int
err error
expectedBody string
}{
{name: "normal", val: "123", status: http.StatusOK, expectedBody: "{\"val\":\"123\"}\n"},
{name: "post", method: http.MethodPost, status: http.StatusInternalServerError,
expectedBody: "{\"error\":\"not a GET\",\"code\":500,\"status_text\":\"Internal Server Error\"}\n"},
{name: "err", status: http.StatusUnprocessableEntity, err: errors.New("unprocessible"),
expectedBody: "{\"error\":\"unprocessible\",\"code\":422,\"status_text\":\"Unprocessable Entity\"}\n"},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
require := require.New(t)
testVal, testStatus, testErr = tc.val, tc.status, tc.err
resp := httptest.NewRecorder()
handlerFunc(resp, httptest.NewRequest(tc.method, "/", nil))
require.Equal(tc.status, resp.Code)
require.Equal(tc.expectedBody, resp.Body.String())
})
}
}
func TestRespondError(t *testing.T) {
require := require.New(t)
resp := httptest.NewRecorder()
httpError := Error(http.StatusInternalServerError, errors.New("my error"))
RespondError(resp, httpError)
require.Equal(httpError.Code, resp.Code)
require.Equal("{\"error\":\"my error\",\"code\":500,\"status_text\":\"Internal Server Error\"}\n", resp.Body.String())
require.Equal(JSONContentType, resp.Header().Get("Content-Type"))
require.Equal("nosniff", resp.Header().Get("X-Content-Type-Options"))
}
func TestRespondJSON(t *testing.T) {
require := require.New(t)
resp := httptest.NewRecorder()
RespondJSON(resp, testObj{Val: "my test"})
require.Equal(http.StatusOK, resp.Code)
require.Equal("{\"val\":\"my test\"}\n", resp.Body.String())
require.Equal(JSONContentType, resp.Header().Get("Content-Type"))
}
func TestExtractJSON(t *testing.T) {
testCases := []struct {
name string
data []byte
extractTo any
expectedValue string
expectedCode int
expectedError string
}{
{name: "normal", data: test.JSON(t, testObj{Val: "testy"}), extractTo: &testObj{}, expectedValue: "testy"},
{name: "empty data", data: []byte("{}"), extractTo: &testObj{}, expectedValue: ""},
{name: "not applicable data", data: []byte("{ \"ok\": \"me\" }"), extractTo: &testObj{}, expectedValue: ""},
{name: "bad data", data: nil, extractTo: &testObj{}, expectedCode: http.StatusBadRequest,
expectedError: "unexpected end of JSON input"},
{name: "non-json", data: []byte("abc"), extractTo: &testObj{}, expectedCode: http.StatusBadRequest,
expectedError: "invalid character 'a' looking for beginning of value"},
{name: "empty bind", data: []byte("{}"), extractTo: nil, expectedCode: http.StatusBadRequest,
expectedError: "json: Unmarshal(nil)"},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
require := require.New(t)
req := httptest.NewRequest("", "/", bytes.NewBuffer(tc.data))
httpError := ExtractJSON(req, tc.extractTo)
if tc.expectedError == "" {
require.Nil(httpError)
bindTo, ok := tc.extractTo.(*testObj)
require.True(ok)
require.Equal(tc.expectedValue, bindTo.Val)
} else {
require.Equal(tc.expectedCode, httpError.Code)
require.Equal(tc.expectedError, httpError.Cause.Error())
}
})
}
}
func TestReturnModelOr500(t *testing.T) {
httpErr := &HTTPError{Code: http.StatusInternalServerError, Cause: errors.New("waka")}
testCases := []struct {
name string
model any
err error
expectedModel any
expectedErr *HTTPError
}{
{name: "success", model: "model", expectedModel: "model"},
{name: "err", err: httpErr.Cause, expectedErr: httpErr},
{name: "http_error", err: httpErr, expectedErr: httpErr},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
require := require.New(t)
model, err := ReturnModelOr500(func() (any, error) {
return tc.model, tc.err
})
require.Equal(tc.expectedModel, model)
require.Equal(tc.expectedErr, err)
})
}
}
func TestReturnSliceOr500(t *testing.T) {
testCases := []struct {
name string
model []any
err error
expectedModel any
expectedErr *HTTPError
}{
{name: "nil", model: nil, expectedModel: []any{}},
{name: "empty", model: []any{}, expectedModel: []any{}},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
require := require.New(t)
model, err := ReturnSliceOr500(func() ([]any, error) {
return tc.model, tc.err
})
require.Equal(tc.expectedModel, model)
require.Equal(tc.expectedErr, err)
})
}
}