Repository navigation
Expand file tree
/
Copy pathproblem_test.go
More file actions
360 lines (284 loc) · 8.97 KB
/
Copy pathproblem_test.go
File metadata and controls
360 lines (284 loc) · 8.97 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
package httputil
import (
"encoding/json"
"errors"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/require"
"go.uber.org/mock/gomock"
)
func TestNewProblem(t *testing.T) {
t.Parallel()
tests := []struct {
name string
statusCode int
typeURI string
title string
detail string
want Problem
}{
{
name: "empty type defaults to about:blank",
statusCode: http.StatusNotFound,
title: "Missing",
detail: "no such user",
want: Problem{
Type: ProblemTypeBlank,
Title: "Missing",
Status: http.StatusNotFound,
Detail: "no such user",
},
},
{
name: "empty title defaults to the status text",
statusCode: http.StatusConflict,
typeURI: "https://example.invalid/probs/conflict",
detail: "slot already booked",
want: Problem{
Type: "https://example.invalid/probs/conflict",
Title: http.StatusText(http.StatusConflict),
Status: http.StatusConflict,
Detail: "slot already booked",
},
},
{
name: "both supplied pass through unchanged",
statusCode: http.StatusForbidden,
typeURI: "https://example.invalid/probs/forbidden",
title: "Not allowed",
detail: "insufficient credit",
want: Problem{
Type: "https://example.invalid/probs/forbidden",
Title: "Not allowed",
Status: http.StatusForbidden,
Detail: "insufficient credit",
},
},
{
name: "both empty with an unknown status code",
statusCode: 799,
want: Problem{
Type: ProblemTypeBlank,
Status: 799,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
got := NewProblem(tt.statusCode, tt.typeURI, tt.title, tt.detail)
require.Equal(t, tt.want, got)
require.Empty(t, got.Instance, "Instance is set by the caller")
})
}
}
func TestSendProblem(t *testing.T) {
t.Parallel()
res := NewHTTPResp(slog.Default())
p := NewProblem(http.StatusNotFound, "", "", "invalid endpoint")
p.Instance = "/missing"
rr := httptest.NewRecorder()
res.SendProblem(t.Context(), rr, http.StatusNotFound, p)
resp := rr.Result()
require.NotNil(t, resp)
defer func() {
require.NoError(t, resp.Body.Close())
}()
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Equal(t, http.StatusNotFound, resp.StatusCode)
require.Equal(t, MimeApplicationProblemJSON, resp.Header.Get(HeaderContentType)) //nolint:testifylint
require.Equal(t, "no-cache, no-store, must-revalidate", resp.Header.Get("Cache-Control"))
require.Equal(t, "nosniff", resp.Header.Get("X-Content-Type-Options"))
// Compared byte for byte to pin the member order and the trailing newline.
want := `{"type":"about:blank","title":"Not Found","status":404,` +
`"detail":"invalid endpoint","instance":"/missing"}` + "\n"
require.Equal(t, want, string(body))
}
func TestSendProblem_unknownStatusCodeOmitsTitle(t *testing.T) {
t.Parallel()
res := NewHTTPResp(slog.Default())
rr := httptest.NewRecorder()
res.SendProblem(t.Context(), rr, 499, NewProblem(499, "", "", "client closed request"))
resp := rr.Result()
require.NotNil(t, resp)
defer func() {
require.NoError(t, resp.Body.Close())
}()
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
want := `{"type":"about:blank","status":499,"detail":"client closed request"}` + "\n"
require.Equal(t, want, string(body))
}
func TestSendProblem_extensionMembers(t *testing.T) {
t.Parallel()
// Extension members are promoted to the top level because Problem has no
// MarshalJSON method.
type conflict struct {
Problem
ConflictingBookingID string `json:"conflicting_booking_id"`
}
res := NewHTTPResp(slog.Default())
rr := httptest.NewRecorder()
res.SendProblem(t.Context(), rr, http.StatusConflict, conflict{
Problem: NewProblem(http.StatusConflict, "", "", "slot already booked"),
ConflictingBookingID: "b-17",
})
resp := rr.Result()
require.NotNil(t, resp)
defer func() {
require.NoError(t, resp.Body.Close())
}()
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
var got map[string]any
require.NoError(t, json.Unmarshal(body, &got))
require.Equal(t, http.StatusConflict, resp.StatusCode)
require.Equal(t, "b-17", got["conflicting_booking_id"])
require.Equal(t, ProblemTypeBlank, got["type"])
require.Equal(t, http.StatusText(http.StatusConflict), got["title"])
require.Len(t, got, 5, "the extension member sits next to the standard members, not nested")
}
func TestSendProblem_marshalError(t *testing.T) {
t.Parallel()
res := NewHTTPResp(slog.Default())
rr := httptest.NewRecorder()
// A channel cannot be marshaled to JSON, so the encode fails before any
// header is written and the response falls back to a clean 500.
res.SendProblem(t.Context(), rr, http.StatusBadRequest, make(chan int))
resp := rr.Result()
require.NotNil(t, resp)
defer func() {
require.NoError(t, resp.Body.Close())
}()
require.Equal(t, http.StatusInternalServerError, resp.StatusCode)
require.Equal(t, MimeTextPlain, resp.Header.Get(HeaderContentType))
}
func TestSendProblem_writeError(t *testing.T) {
t.Parallel()
res := NewHTTPResp(slog.Default())
mockWriter := NewMockTestHTTPResponseWriter(gomock.NewController(t))
mockWriter.EXPECT().Header().AnyTimes().Return(http.Header{})
mockWriter.EXPECT().WriteHeader(http.StatusBadRequest)
mockWriter.EXPECT().Write(gomock.Any()).Return(0, errors.New("io error"))
res.SendProblem(t.Context(), mockWriter, http.StatusBadRequest, NewProblem(http.StatusBadRequest, "", "", ""))
}
func TestSendJSONType(t *testing.T) {
t.Parallel()
const contentType = "application/vnd.example.v1+json"
res := NewHTTPResp(slog.Default())
rr := httptest.NewRecorder()
res.SendJSONType(t.Context(), rr, http.StatusOK, contentType, map[string]int{"count": 3})
resp := rr.Result()
require.NotNil(t, resp)
defer func() {
require.NoError(t, resp.Body.Close())
}()
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)
require.Equal(t, contentType, resp.Header.Get(HeaderContentType))
require.Equal(t, "{\"count\":3}\n", string(body))
}
func TestHTTPResp_problemHandlerFuncs(t *testing.T) {
t.Parallel()
const typeURI = "https://example.invalid/probs/generic"
res := NewHTTPResp(slog.Default())
tests := []struct {
name string
handler func() http.HandlerFunc
statusCode int
wantDetail string
}{
{
name: "not found",
handler: func() http.HandlerFunc { return res.ProblemNotFoundHandlerFunc(typeURI) },
statusCode: http.StatusNotFound,
wantDetail: "invalid endpoint",
},
{
name: "method not allowed",
handler: func() http.HandlerFunc { return res.ProblemMethodNotAllowedHandlerFunc(typeURI) },
statusCode: http.StatusMethodNotAllowed,
wantDetail: "the request cannot be routed",
},
{
name: "panic",
handler: func() http.HandlerFunc { return res.ProblemPanicHandlerFunc(typeURI) },
statusCode: http.StatusInternalServerError,
wantDetail: "internal error",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
rr := httptest.NewRecorder()
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/some/path?q=1", nil)
tt.handler().ServeHTTP(rr, req)
resp := rr.Result()
require.NotNil(t, resp)
defer func() {
require.NoError(t, resp.Body.Close())
}()
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
var got Problem
require.NoError(t, json.Unmarshal(body, &got))
require.Equal(t, tt.statusCode, resp.StatusCode)
require.Equal(t, MimeApplicationProblemJSON, resp.Header.Get(HeaderContentType)) //nolint:testifylint
require.Equal(t, Problem{
Type: typeURI,
Title: http.StatusText(tt.statusCode),
Status: tt.statusCode,
Detail: tt.wantDetail,
Instance: "/some/path",
}, got)
})
}
}
func TestHTTPResp_problemHandlerFuncs_escapedInstance(t *testing.T) {
t.Parallel()
res := NewHTTPResp(slog.Default())
tests := []struct {
name string
target string
wantInstance string
}{
{
name: "encoded separator stays encoded",
target: "/orders/a%2Fb",
wantInstance: "/orders/a%2Fb",
},
{
name: "space stays percent-encoded",
target: "/orders/a%20b",
wantInstance: "/orders/a%20b",
},
{
name: "unencoded path is unchanged",
target: "/orders/42",
wantInstance: "/orders/42",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
rr := httptest.NewRecorder()
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, tt.target, nil)
res.ProblemNotFoundHandlerFunc("").ServeHTTP(rr, req)
resp := rr.Result()
require.NotNil(t, resp)
defer func() {
require.NoError(t, resp.Body.Close())
}()
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
var got Problem
require.NoError(t, json.Unmarshal(body, &got))
require.Equal(t, tt.wantInstance, got.Instance)
})
}
}