-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrequest_test.go
More file actions
372 lines (338 loc) · 10.1 KB
/
request_test.go
File metadata and controls
372 lines (338 loc) · 10.1 KB
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
package httpsuite
import (
"bytes"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestParseRequest(t *testing.T) {
ClearValidator()
t.Cleanup(ClearValidator)
tests := []struct {
name string
body string
path string
pathParams []string
opts *ParseOptions
want *testRequest
wantErr bool
wantStatus int
wantTitle string
wantDetailContains string
}{
{
name: "successful request",
body: `{"name":"Test"}`,
path: "/test/123",
pathParams: []string{"id"},
want: &testRequest{ID: 123, Name: "Test"},
},
{
name: "body only request",
body: `{"id":42,"name":"OnlyBody"}`,
path: "/test",
pathParams: nil,
want: &testRequest{ID: 42, Name: "OnlyBody"},
},
{
name: "invalid json body",
body: `{invalid-json}`,
path: "/test/123",
pathParams: []string{"id"},
wantErr: true,
wantStatus: http.StatusBadRequest,
wantTitle: "Invalid Request",
wantDetailContains: "invalid character",
},
{
name: "multiple json documents",
body: `{"name":"Test"}{"name":"Again"}`,
path: "/test/123",
pathParams: []string{"id"},
wantErr: true,
wantStatus: http.StatusBadRequest,
wantTitle: "Invalid Request",
wantDetailContains: "single JSON document",
},
{
name: "missing parameter",
body: `{"name":"Test"}`,
path: "/test",
pathParams: []string{"id"},
wantErr: true,
wantStatus: http.StatusBadRequest,
wantTitle: "Missing Parameter",
wantDetailContains: "Parameter id not found",
},
{
name: "invalid parameter",
body: `{"name":"Test"}`,
path: "/test/nope",
pathParams: []string{"id"},
wantErr: true,
wantStatus: http.StatusBadRequest,
wantTitle: "Invalid Parameter",
wantDetailContains: "Failed to bind parameter id",
},
{
name: "body exceeds configured limit",
body: `{"name":"TooLarge"}`,
path: "/test/123",
pathParams: []string{"id"},
opts: &ParseOptions{MaxBodyBytes: 8},
wantErr: true,
wantStatus: http.StatusRequestEntityTooLarge,
wantTitle: "Payload Too Large",
wantDetailContains: "exceeds the limit",
},
{
name: "custom problem config",
body: `{"name":"Test"}`,
path: "/test/123",
pathParams: []string{"id"},
opts: &ParseOptions{
Problems: &ProblemConfig{
BaseURL: "https://api.example.com",
ErrorTypePaths: map[string]string{
"bad_request_error": "/errors/bad-request",
"server_error": "/errors/server-error",
},
},
},
want: &testRequest{ID: 123, Name: "Test"},
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
var body *bytes.Buffer
if tt.body != "" {
body = bytes.NewBufferString(tt.body)
} else {
body = bytes.NewBuffer(nil)
}
req := httptest.NewRequest(http.MethodPost, tt.path, body)
w := httptest.NewRecorder()
got, err := ParseRequest[*testRequest](w, req, testParamExtractor, tt.opts, tt.pathParams...)
if tt.wantErr {
if err == nil {
t.Fatalf("expected error, got nil")
}
if w.Code != tt.wantStatus {
t.Fatalf("expected status %d, got %d", tt.wantStatus, w.Code)
}
var problem ProblemDetails
if decodeErr := json.NewDecoder(w.Body).Decode(&problem); decodeErr != nil {
t.Fatalf("decode problem details: %v", decodeErr)
}
if problem.Title != tt.wantTitle {
t.Fatalf("expected title %q, got %q", tt.wantTitle, problem.Title)
}
if !strings.Contains(problem.Detail, tt.wantDetailContains) {
t.Fatalf("expected detail %q to contain %q", problem.Detail, tt.wantDetailContains)
}
return
}
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got == nil {
t.Fatalf("expected request, got nil")
}
if *got != *tt.want {
t.Fatalf("expected %+v, got %+v", *tt.want, *got)
}
})
}
}
func TestParseRequestWithoutRequestParamSetter(t *testing.T) {
ClearValidator()
t.Cleanup(ClearValidator)
req := httptest.NewRequest(http.MethodPost, "/users", bytes.NewBufferString(`{"name":"Ada","age":36}`))
w := httptest.NewRecorder()
got, err := ParseRequest[*bodyOnlyRequest](w, req, testParamExtractor, nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got == nil {
t.Fatal("expected parsed request, got nil")
}
if got.Name != "Ada" || got.Age != 36 {
t.Fatalf("unexpected parsed request: %#v", got)
}
}
func TestParseRequestInvalidInputs(t *testing.T) {
ClearValidator()
t.Cleanup(ClearValidator)
tests := []struct {
name string
makeReq func() *http.Request
extractor ParamExtractor
pathParams []string
wantErr error
}{
{
name: "nil request",
makeReq: func() *http.Request { return nil },
extractor: testParamExtractor,
wantErr: errNilHTTPRequest,
},
{
name: "nil body",
makeReq: func() *http.Request {
req := httptest.NewRequest(http.MethodPost, "/test/123", nil)
req.Body = nil
return req
},
extractor: testParamExtractor,
wantErr: errNilRequestBody,
},
{
name: "nil extractor with params",
makeReq: func() *http.Request {
return httptest.NewRequest(http.MethodPost, "/test/123", bytes.NewBufferString(`{"name":"Test"}`))
},
pathParams: []string{"id"},
wantErr: errNilParamExtractor,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
w := httptest.NewRecorder()
got, err := ParseRequest[*testRequest](w, tt.makeReq(), tt.extractor, nil, tt.pathParams...)
if !errors.Is(err, tt.wantErr) {
t.Fatalf("expected error %v, got %v", tt.wantErr, err)
}
if got != nil {
t.Fatalf("expected nil request, got %#v", got)
}
if w.Body.Len() != 0 {
t.Fatalf("expected no response body to be written, got %q", w.Body.String())
}
})
}
}
func TestParseRequestUsesDefaultValidator(t *testing.T) {
ClearValidator()
t.Cleanup(ClearValidator)
problem := &ProblemDetails{
Type: GetProblemTypeURL("validation_error"),
Title: "Validation Error",
Status: http.StatusBadRequest,
Detail: "One or more fields failed validation.",
}
SetValidator(stubValidator{problem: problem})
req := httptest.NewRequest(http.MethodPost, "/test/123", bytes.NewBufferString(`{"name":""}`))
w := httptest.NewRecorder()
got, err := ParseRequest[*testRequest](w, req, testParamExtractor, nil, "id")
if err == nil {
t.Fatalf("expected validation error, got nil")
}
if got != nil {
t.Fatalf("expected nil request, got %#v", got)
}
if w.Code != http.StatusBadRequest {
t.Fatalf("expected status %d, got %d", http.StatusBadRequest, w.Code)
}
}
func TestParseRequestValidatorOverride(t *testing.T) {
ClearValidator()
t.Cleanup(ClearValidator)
SetValidator(stubValidator{
problem: &ProblemDetails{
Type: GetProblemTypeURL("validation_error"),
Title: "Validation Error",
Status: http.StatusBadRequest,
Detail: "global validator failed",
},
})
override := stubValidator{
problem: &ProblemDetails{
Type: GetProblemTypeURL("validation_error"),
Title: "Validation Error",
Status: http.StatusBadRequest,
Detail: "override validator failed",
},
}
req := httptest.NewRequest(http.MethodPost, "/test/123", bytes.NewBufferString(`{"name":"ok"}`))
w := httptest.NewRecorder()
_, err := ParseRequest[*testRequest](w, req, testParamExtractor, &ParseOptions{Validator: override}, "id")
if err == nil {
t.Fatalf("expected validation error, got nil")
}
var problem ProblemDetails
if decodeErr := json.NewDecoder(w.Body).Decode(&problem); decodeErr != nil {
t.Fatalf("decode problem details: %v", decodeErr)
}
if problem.Detail != "override validator failed" {
t.Fatalf("expected override validator detail, got %q", problem.Detail)
}
}
func TestParseRequestValidationStatus(t *testing.T) {
ClearValidator()
t.Cleanup(ClearValidator)
tests := []struct {
name string
problem *ProblemDetails
wantStatus int
}{
{
name: "custom status preserved",
problem: &ProblemDetails{
Type: GetProblemTypeURL("validation_error"),
Title: "Validation Error",
Status: http.StatusUnprocessableEntity,
Detail: "unprocessable payload",
},
wantStatus: http.StatusUnprocessableEntity,
},
{
name: "invalid status falls back to bad request",
problem: &ProblemDetails{
Type: GetProblemTypeURL("validation_error"),
Title: "Validation Error",
Status: 0,
Detail: "bad payload",
},
wantStatus: http.StatusBadRequest,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
SetValidator(stubValidator{problem: tt.problem})
req := httptest.NewRequest(http.MethodPost, "/test/123", bytes.NewBufferString(`{"name":"ok"}`))
w := httptest.NewRecorder()
_, err := ParseRequest[*testRequest](w, req, testParamExtractor, nil, "id")
if !errors.Is(err, errValidationFailed) {
t.Fatalf("expected validation error, got %v", err)
}
if w.Code != tt.wantStatus {
t.Fatalf("expected status %d, got %d", tt.wantStatus, w.Code)
}
})
}
}
func TestParseRequestSkipValidation(t *testing.T) {
ClearValidator()
t.Cleanup(ClearValidator)
SetValidator(stubValidator{
problem: &ProblemDetails{
Type: GetProblemTypeURL("validation_error"),
Title: "Validation Error",
Status: http.StatusBadRequest,
Detail: "global validator failed",
},
})
req := httptest.NewRequest(http.MethodPost, "/test/123", bytes.NewBufferString(`{"name":"ok"}`))
w := httptest.NewRecorder()
got, err := ParseRequest[*testRequest](w, req, testParamExtractor, &ParseOptions{SkipValidation: true}, "id")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got == nil || got.ID != 123 {
t.Fatalf("expected parsed request, got %#v", got)
}
}