-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcustom_errors_test.go
More file actions
380 lines (316 loc) · 13.7 KB
/
Copy pathcustom_errors_test.go
File metadata and controls
380 lines (316 loc) · 13.7 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
373
374
375
376
377
378
379
380
package fiberoapi
import (
"encoding/json"
"io"
"net/http/httptest"
"strings"
"testing"
"github.com/gofiber/fiber/v3"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// AppError is the shared shape used across these tests, mirroring the pattern
// the example in _examples/simple_error demonstrates.
type AppError struct {
Code int `json:"code"`
Message string `json:"message"`
Type string `json:"type"`
Details string `json:"details,omitempty"`
}
func (e *AppError) Error() string { return e.Message }
func appConflict(msg string) *AppError {
return &AppError{Code: 409, Message: msg, Type: "Conflict", Details: "Duplicate resource"}
}
func appNotFound(msg string) *AppError {
return &AppError{Code: 404, Message: msg, Type: "NotFound"}
}
func appForbidden(msg string) *AppError {
return &AppError{Code: 403, Message: msg, Type: "Forbidden"}
}
type customErrInput struct {
Name string `uri:"name" validate:"required,min=2"`
}
type customErrOutput struct {
Message string `json:"message"`
}
func TestCustomErrors_SpecListsEachDeclaredStatus(t *testing.T) {
app := fiber.New()
oapi := New(app)
Post(oapi, "/items/:name", func(c fiber.Ctx, input customErrInput) (customErrOutput, error) {
return customErrOutput{Message: "ok"}, nil
}, OpenAPIOptions{
OperationID: "createItem",
Errors: []any{
appConflict("already exists"),
appNotFound("missing"),
appForbidden("not yours"),
},
})
spec := oapi.GenerateOpenAPISpec()
post := spec["paths"].(map[string]any)["/items/{name}"].(map[string]any)["post"].(map[string]any)
responses := post["responses"].(map[string]any)
for _, code := range []string{"403", "404", "409"} {
r, ok := responses[code].(map[string]any)
require.True(t, ok, "missing %s response", code)
content := r["content"].(map[string]any)["application/json"].(map[string]any)
require.NotNil(t, content["schema"], "%s missing schema", code)
require.NotNil(t, content["example"], "%s missing example", code)
}
}
func TestCustomErrors_SchemaIsDeduplicatedViaRef(t *testing.T) {
app := fiber.New()
oapi := New(app)
Post(oapi, "/items/:name", func(c fiber.Ctx, input customErrInput) (customErrOutput, error) {
return customErrOutput{Message: "ok"}, nil
}, OpenAPIOptions{
OperationID: "createItem",
Errors: []any{
appConflict("a"),
appNotFound("b"),
appForbidden("c"),
},
})
spec := oapi.GenerateOpenAPISpec()
schemas := spec["components"].(map[string]any)["schemas"].(map[string]any)
_, hasAppError := schemas["AppError"]
assert.True(t, hasAppError, "shared AppError schema should be in components.schemas")
post := spec["paths"].(map[string]any)["/items/{name}"].(map[string]any)["post"].(map[string]any)
responses := post["responses"].(map[string]any)
for _, code := range []string{"403", "404", "409"} {
schema := responses[code].(map[string]any)["content"].(map[string]any)["application/json"].(map[string]any)["schema"].(map[string]any)
assert.Equal(t, "#/components/schemas/AppError", schema["$ref"], "all entries should $ref the shared schema")
}
}
func TestCustomErrors_DescriptionFallback(t *testing.T) {
app := fiber.New()
oapi := New(app)
type noMessage struct {
Code int `json:"code"`
}
Post(oapi, "/items/:name", func(c fiber.Ctx, input customErrInput) (customErrOutput, error) {
return customErrOutput{Message: "ok"}, nil
}, OpenAPIOptions{
OperationID: "createItem",
Errors: []any{
&noMessage{Code: 418}, // no Message field — fallback to HTTP reason
appConflict("custom msg"),
},
})
spec := oapi.GenerateOpenAPISpec()
post := spec["paths"].(map[string]any)["/items/{name}"].(map[string]any)["post"].(map[string]any)
responses := post["responses"].(map[string]any)
assert.Equal(t, "I'm a teapot", responses["418"].(map[string]any)["description"], "should fall back to HTTP reason phrase")
assert.Equal(t, "custom msg", responses["409"].(map[string]any)["description"], "should use Message field")
}
type explicitDescriber struct {
Code int `json:"code"`
}
func (e *explicitDescriber) Description() string { return "explicit override wins" }
func (e *explicitDescriber) HTTPStatus() int { return 451 }
func TestCustomErrors_MethodsTakePriorityOverFields(t *testing.T) {
app := fiber.New()
oapi := New(app)
Post(oapi, "/items/:name", func(c fiber.Ctx, input customErrInput) (customErrOutput, error) {
return customErrOutput{Message: "ok"}, nil
}, OpenAPIOptions{
OperationID: "createItem",
Errors: []any{&explicitDescriber{Code: 999 /* ignored */}},
})
spec := oapi.GenerateOpenAPISpec()
post := spec["paths"].(map[string]any)["/items/{name}"].(map[string]any)["post"].(map[string]any)
responses := post["responses"].(map[string]any)
_, has451 := responses["451"]
assert.True(t, has451, "HTTPStatus() method should win over Code field")
_, has999 := responses["999"]
assert.False(t, has999, "the Code field should be ignored when HTTPStatus() is implemented")
assert.Equal(t, "explicit override wins", responses["451"].(map[string]any)["description"])
}
func TestCustomErrors_HandlerReturnEmitsRightStatusAndBody(t *testing.T) {
app := fiber.New()
oapi := New(app)
Post(oapi, "/items/:name", func(c fiber.Ctx, input customErrInput) (customErrOutput, error) {
switch input.Name {
case "dup":
return customErrOutput{}, appConflict("already exists")
case "missing":
return customErrOutput{}, appNotFound("not found")
}
return customErrOutput{Message: "ok"}, nil
}, OpenAPIOptions{
OperationID: "createItem",
Errors: []any{appConflict("a"), appNotFound("b")},
})
cases := []struct {
path string
status int
bodyHas string
}{
{"/items/dup", 409, "already exists"},
{"/items/missing", 404, "not found"},
{"/items/alice", 200, "ok"},
}
for _, tc := range cases {
t.Run(tc.path, func(t *testing.T) {
req := httptest.NewRequest("POST", tc.path, strings.NewReader(""))
req.Header.Set("Content-Type", "application/json")
resp, err := app.Test(req)
require.NoError(t, err)
assert.Equal(t, tc.status, resp.StatusCode)
raw, _ := io.ReadAll(resp.Body)
assert.Contains(t, string(raw), tc.bodyHas)
})
}
}
func TestCustomErrors_NilErrorReturnsSuccess(t *testing.T) {
// Regression check for the isZero hardening: a nil `error` interface must
// not panic — it must take the success branch.
app := fiber.New()
oapi := New(app)
Post(oapi, "/items/:name", func(c fiber.Ctx, input customErrInput) (customErrOutput, error) {
return customErrOutput{Message: "ok"}, nil
}, OpenAPIOptions{OperationID: "createItem"})
resp, err := app.Test(httptest.NewRequest("POST", "/items/alice", strings.NewReader("")))
require.NoError(t, err)
require.Equal(t, 200, resp.StatusCode)
raw, _ := io.ReadAll(resp.Body)
var out customErrOutput
require.NoError(t, json.Unmarshal(raw, &out))
assert.Equal(t, "ok", out.Message)
}
// legacyTError is a non-empty struct used to exercise the TError catch-all
// behaviour in the next two tests.
type legacyTError struct {
Code int `json:"code"`
Message string `json:"message"`
}
func TestCustomErrors_Suppresses4XXWhenErrorsDeclared(t *testing.T) {
// When OpenAPIOptions.Errors is populated, the legacy 4XX catch-all is
// redundant — the user has explicitly enumerated which status codes their
// handler can emit. The spec should list ONLY those concrete codes.
app := fiber.New()
oapi := New(app)
Post(oapi, "/items/:name", func(c fiber.Ctx, input customErrInput) (customErrOutput, *legacyTError) {
return customErrOutput{Message: "ok"}, nil
}, OpenAPIOptions{
OperationID: "createItem",
Errors: []any{appConflict("a"), appNotFound("b")},
})
spec := oapi.GenerateOpenAPISpec()
responses := spec["paths"].(map[string]any)["/items/{name}"].(map[string]any)["post"].(map[string]any)["responses"].(map[string]any)
_, has4xx := responses["4XX"]
assert.False(t, has4xx, "4XX must be suppressed when Errors[] is non-empty")
// Sanity: the explicit codes are still there.
_, has409 := responses["409"]
_, has404 := responses["404"]
assert.True(t, has409 && has404, "the explicit Errors entries must still surface")
}
func TestCustomErrors_4XXStillEmittedWhenErrorsSliceOnlyContainsNils(t *testing.T) {
// Edge case: Errors: []any{nil} should be treated as "nothing declared",
// not as "errors declared". The downstream emission loop skips nil entries,
// so if we suppressed the 4XX based on slice length the route would end up
// with zero documented error responses at all.
app := fiber.New()
oapi := New(app)
Post(oapi, "/items/:name", func(c fiber.Ctx, input customErrInput) (customErrOutput, *legacyTError) {
return customErrOutput{Message: "ok"}, nil
}, OpenAPIOptions{
OperationID: "createItem",
Errors: []any{nil, nil},
})
spec := oapi.GenerateOpenAPISpec()
responses := spec["paths"].(map[string]any)["/items/{name}"].(map[string]any)["post"].(map[string]any)["responses"].(map[string]any)
_, has4xx := responses["4XX"]
assert.True(t, has4xx, "4XX must still be emitted when the Errors slice contains only nil entries")
}
func TestCustomErrors_4XXStillEmittedWhenNoErrorsDeclared(t *testing.T) {
// Backwards compatibility: routes whose handler declares a non-empty TError
// but provides no Errors[] entries still get the legacy 4XX catch-all so
// existing integrations are not silently broken.
app := fiber.New()
oapi := New(app)
Post(oapi, "/items/:name", func(c fiber.Ctx, input customErrInput) (customErrOutput, *legacyTError) {
return customErrOutput{Message: "ok"}, nil
}, OpenAPIOptions{OperationID: "createItem"})
spec := oapi.GenerateOpenAPISpec()
responses := spec["paths"].(map[string]any)["/items/{name}"].(map[string]any)["post"].(map[string]any)["responses"].(map[string]any)
_, has4xx := responses["4XX"]
assert.True(t, has4xx, "4XX must still be emitted when no Errors[] is declared (legacy behaviour)")
}
func TestCustomErrors_EmptyErrorsSliceSuppressesAllDefaults(t *testing.T) {
// Passing Errors: []any{} (non-nil, length 0) is the explicit opt-out
// signal. The route should expose ONLY its 200 success response — no
// framework-emitted 400 / 422 / 404 / 4XX. Useful for /health-style
// endpoints that have no error contract.
app := fiber.New()
oapi := New(app)
Post(oapi, "/health", func(c fiber.Ctx, _ struct{}) (customErrOutput, *legacyTError) {
return customErrOutput{Message: "alive"}, nil
}, OpenAPIOptions{
OperationID: "health",
Errors: []any{},
})
oapi.UseNotFoundHandler() // would normally add 404 — must NOT for this route
spec := oapi.GenerateOpenAPISpec()
responses := spec["paths"].(map[string]any)["/health"].(map[string]any)["post"].(map[string]any)["responses"].(map[string]any)
_, has200 := responses["200"]
assert.True(t, has200, "200 success response must remain")
for _, code := range []string{"400", "404", "422", "4XX"} {
_, has := responses[code]
assert.False(t, has, "%s must be suppressed when Errors is an explicit empty slice", code)
}
assert.Len(t, responses, 1, "only 200 should appear, got %d responses", len(responses))
}
func TestCustomErrors_NilErrorsKeepsAllDefaults(t *testing.T) {
// Sanity / regression: the OPT-OUT behaviour is gated on a non-nil empty
// slice. Leaving Errors at its zero value (nil) keeps every framework
// default — this is what every existing user expects.
app := fiber.New()
oapi := New(app)
Post(oapi, "/items/:name", func(c fiber.Ctx, input customErrInput) (customErrOutput, *legacyTError) {
return customErrOutput{Message: "ok"}, nil
}, OpenAPIOptions{OperationID: "createItem"})
spec := oapi.GenerateOpenAPISpec()
responses := spec["paths"].(map[string]any)["/items/{name}"].(map[string]any)["post"].(map[string]any)["responses"].(map[string]any)
for _, code := range []string{"200", "400", "422", "4XX"} {
_, has := responses[code]
assert.True(t, has, "%s must remain when Errors is nil", code)
}
}
func TestCustomErrors_OnlyNilEntriesKeepsDefaults(t *testing.T) {
// Edge case revisited: `Errors: []any{nil, nil}` — a non-empty slice with
// no real entries — is still treated as "nothing declared", same as nil.
// Only an explicitly empty []any{} triggers the suppression.
app := fiber.New()
oapi := New(app)
Post(oapi, "/items/:name", func(c fiber.Ctx, input customErrInput) (customErrOutput, *legacyTError) {
return customErrOutput{Message: "ok"}, nil
}, OpenAPIOptions{
OperationID: "createItem",
Errors: []any{nil, nil},
})
spec := oapi.GenerateOpenAPISpec()
responses := spec["paths"].(map[string]any)["/items/{name}"].(map[string]any)["post"].(map[string]any)["responses"].(map[string]any)
_, has422 := responses["422"]
_, has4XX := responses["4XX"]
assert.True(t, has422, "422 default must remain when Errors contains only nil entries")
assert.True(t, has4XX, "4XX legacy must remain when Errors contains only nil entries")
}
func TestCustomErrors_PrecedenceOverDefault404Envelope(t *testing.T) {
// When the user declares a 404 in Errors AND has called UseNotFoundHandler(),
// the declared shape (their AppError) wins for the per-route spec entry —
// the not-found envelope is for routing misses, not for handler-emitted 404s.
app := fiber.New()
oapi := New(app)
Post(oapi, "/items/:name", func(c fiber.Ctx, input customErrInput) (customErrOutput, error) {
return customErrOutput{Message: "ok"}, nil
}, OpenAPIOptions{
OperationID: "createItem",
Errors: []any{appNotFound("not found")},
})
oapi.UseNotFoundHandler()
spec := oapi.GenerateOpenAPISpec()
post := spec["paths"].(map[string]any)["/items/{name}"].(map[string]any)["post"].(map[string]any)
resp404 := post["responses"].(map[string]any)["404"].(map[string]any)
schema := resp404["content"].(map[string]any)["application/json"].(map[string]any)["schema"].(map[string]any)
assert.Equal(t, "#/components/schemas/AppError", schema["$ref"], "Errors entry should override the default ErrorEnvelope 404")
}