-
-
Notifications
You must be signed in to change notification settings - Fork 47
/
option_test.go
412 lines (322 loc) · 12.5 KB
/
option_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
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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
package fuego_test
import (
"log/slog"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/require"
"github.com/thejerf/slogassert"
"github.com/go-fuego/fuego"
"github.com/go-fuego/fuego/param"
)
// dummyMiddleware sets the X-Test header on the request and the X-Test-Response header on the response.
func dummyMiddleware(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.Header.Set("X-Test", "test")
w.Header().Set("X-Test-Response", "response")
handler.ServeHTTP(w, r)
})
}
func helloWorld(ctx *fuego.ContextNoBody) (string, error) {
return "hello world", nil
}
type ReqBody struct {
A string
B int
}
type Resp struct {
Message string `json:"message"`
}
func dummyController(_ *fuego.ContextWithBody[ReqBody]) (Resp, error) {
return Resp{Message: "hello world"}, nil
}
// orderMiddleware sets the X-Test-Order Header on the request and
// X-Test-Response header on the response. It is
// used to test the order execution of our middleware
func orderMiddleware(s string) func(http.Handler) http.Handler {
return func(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.Header.Add("X-Test-Order", s)
w.Header().Set("X-Test-Response", "response")
handler.ServeHTTP(w, r)
})
}
}
func TestPerRouteMiddleware(t *testing.T) {
s := fuego.NewServer()
fuego.Get(s, "/withMiddleware", func(ctx *fuego.ContextNoBody) (string, error) {
return "withmiddleware", nil
}, fuego.OptionMiddleware(dummyMiddleware))
fuego.Get(s, "/withoutMiddleware", func(ctx *fuego.ContextNoBody) (string, error) {
return "withoutmiddleware", nil
})
t.Run("withMiddleware", func(t *testing.T) {
r := httptest.NewRequest(http.MethodGet, "/withMiddleware", nil)
w := httptest.NewRecorder()
s.Mux.ServeHTTP(w, r)
require.Equal(t, "withmiddleware", w.Body.String())
require.Equal(t, "response", w.Header().Get("X-Test-Response"))
})
t.Run("withoutMiddleware", func(t *testing.T) {
r := httptest.NewRequest(http.MethodGet, "/withoutMiddleware", nil)
w := httptest.NewRecorder()
s.Mux.ServeHTTP(w, r)
require.Equal(t, "withoutmiddleware", w.Body.String())
require.Equal(t, "", w.Header().Get("X-Test-Response"))
})
}
func TestUse(t *testing.T) {
t.Run("base", func(t *testing.T) {
s := fuego.NewServer()
fuego.Use(s, orderMiddleware("First!"))
fuego.Get(s, "/test", func(ctx *fuego.ContextNoBody) (string, error) {
return "test", nil
})
r := httptest.NewRequest(http.MethodGet, "/test", nil)
r.Header.Set("X-Test-Order", "Start!")
w := httptest.NewRecorder()
s.Mux.ServeHTTP(w, r)
require.Equal(t, []string{"Start!", "First!"}, r.Header["X-Test-Order"])
})
t.Run("multiple uses of Use", func(t *testing.T) {
s := fuego.NewServer()
fuego.Use(s, orderMiddleware("First!"))
fuego.Use(s, orderMiddleware("Second!"))
fuego.Get(s, "/test", func(ctx *fuego.ContextNoBody) (string, error) {
return "test", nil
})
r := httptest.NewRequest(http.MethodGet, "/test", nil)
r.Header.Set("X-Test-Order", "Start!")
w := httptest.NewRecorder()
s.Mux.ServeHTTP(w, r)
require.Equal(t, []string{"Start!", "First!", "Second!"}, r.Header["X-Test-Order"])
})
t.Run("variadic use of Use", func(t *testing.T) {
s := fuego.NewServer()
fuego.Use(s, orderMiddleware("First!"))
fuego.Use(s, orderMiddleware("Second!"), orderMiddleware("Third!"))
fuego.Get(s, "/test", func(ctx *fuego.ContextNoBody) (string, error) {
return "test", nil
})
r := httptest.NewRequest(http.MethodGet, "/test", nil)
r.Header.Set("X-Test-Order", "Start!")
w := httptest.NewRecorder()
s.Mux.ServeHTTP(w, r)
require.Equal(t, []string{"Start!", "First!", "Second!", "Third!"}, r.Header["X-Test-Order"])
})
t.Run("variadic use of Route Get", func(t *testing.T) {
s := fuego.NewServer()
fuego.Use(s, orderMiddleware("First!"))
fuego.Use(s, orderMiddleware("Second!"), orderMiddleware("Third!"))
fuego.Get(s, "/test", func(ctx *fuego.ContextNoBody) (string, error) {
return "test", nil
},
fuego.OptionMiddleware(orderMiddleware("Fourth!")),
fuego.OptionMiddleware(orderMiddleware("Fifth!")),
)
r := httptest.NewRequest(http.MethodGet, "/test", nil)
r.Header.Set("X-Test-Order", "Start!")
w := httptest.NewRecorder()
s.Mux.ServeHTTP(w, r)
require.Equal(t, []string{"Start!", "First!", "Second!", "Third!", "Fourth!", "Fifth!"}, r.Header["X-Test-Order"])
})
}
type ans struct{}
func TestOptions(t *testing.T) {
t.Run("warn if param is not found in openAPI config but called in controller (possibly typo)", func(t *testing.T) {
handler := slogassert.New(t, slog.LevelWarn, nil)
s := fuego.NewServer(
fuego.WithLogHandler(handler),
)
fuego.Get(s, "/correct", func(c fuego.ContextNoBody) (ans, error) {
c.QueryParam("quantity")
return ans{}, nil
},
fuego.OptionQuery("quantity", "some description"),
fuego.OptionQueryInt("number", "some description", param.Example("3", 3)),
fuego.OptionQueryBool("is_active", "some description"),
)
fuego.Get(s, "/typo", func(c fuego.ContextNoBody) (ans, error) {
c.QueryParam("quantityy-with-a-typo")
return ans{}, nil
},
fuego.OptionQuery("quantity", "some description"),
)
t.Run("correct param", func(t *testing.T) {
r := httptest.NewRequest("GET", "/correct", nil)
w := httptest.NewRecorder()
s.Mux.ServeHTTP(w, r)
// all log messages have been accounted for
handler.AssertEmpty()
})
t.Run("typo param", func(t *testing.T) {
r := httptest.NewRequest("GET", "/typo", nil)
w := httptest.NewRecorder()
s.Mux.ServeHTTP(w, r)
handler.AssertMessage("query parameter not expected in OpenAPI spec")
// all log messages have been accounted for
handler.AssertEmpty()
})
})
}
func TestHeader(t *testing.T) {
t.Run("Declare a header parameter for the route", func(t *testing.T) {
s := fuego.NewServer()
fuego.Get(s, "/test", helloWorld,
fuego.OptionHeader("X-Test", "test header", param.Required(), param.Example("test", "My Header"), param.Default("test")),
)
r := httptest.NewRequest(http.MethodGet, "/test", nil)
w := httptest.NewRecorder()
s.Mux.ServeHTTP(w, r)
require.Equal(t, "hello world", w.Body.String())
})
}
func TestOpenAPI(t *testing.T) {
t.Run("Declare a openapi parameters for the route", func(t *testing.T) {
s := fuego.NewServer()
route := fuego.Get(s, "/test", helloWorld,
fuego.OptionSummary("test summary"),
fuego.OptionDescription("test description"),
fuego.OptionTags("first-tag", "second-tag"),
fuego.OptionDeprecated(),
fuego.OptionOperationID("test-operation-id"),
)
require.Equal(t, "test summary", route.Operation.Summary)
require.Equal(t, "controller: `github.com/go-fuego/fuego_test.helloWorld`\n\n---\n\ntest description", route.Operation.Description)
require.Equal(t, []string{"first-tag", "second-tag"}, route.Operation.Tags)
require.True(t, route.Operation.Deprecated)
})
}
func TestGroup(t *testing.T) {
paramsGroup := fuego.GroupOptions(
fuego.OptionHeader("X-Test", "test header", param.Required(), param.Example("test", "My Header"), param.Default("test")),
fuego.OptionQuery("name", "Filter by name", param.Example("cat name", "felix"), param.Nullable()),
fuego.OptionCookie("session", "Session cookie", param.Example("session", "1234"), param.Nullable()),
)
t.Run("Declare a group parameter for the route", func(t *testing.T) {
s := fuego.NewServer()
route := fuego.Get(s, "/test", helloWorld, paramsGroup)
require.NotNil(t, route)
require.NotNil(t, route.Params)
require.Len(t, route.Params, 3)
require.Equal(t, "test header", route.Params["X-Test"].Description)
require.Equal(t, "My Header", route.Operation.Parameters.GetByInAndName("header", "X-Test").Examples["test"].Value.Value)
})
}
func TestQuery(t *testing.T) {
t.Run("panics if example is not the correct type", func(t *testing.T) {
s := fuego.NewServer()
require.Panics(t, func() {
fuego.Get(s, "/test", helloWorld,
fuego.OptionQueryInt("age", "Filter by age (in years)", param.Example("3 years old", "3 but string"), param.Nullable()),
)
})
require.Panics(t, func() {
fuego.Get(s, "/test", helloWorld,
fuego.OptionQueryBool("is_active", "Filter by active status", param.Example("true", 3), param.Nullable()),
)
})
})
t.Run("panics if default value is not the correct type", func(t *testing.T) {
s := fuego.NewServer()
require.Panics(t, func() {
fuego.Get(s, "/test", helloWorld,
fuego.OptionQuery("name", "Filter by name", param.Default(3), param.Nullable()),
)
})
})
}
func TestRequestContentType(t *testing.T) {
t.Run("Declare a request content type for the route", func(t *testing.T) {
s := fuego.NewServer()
route := fuego.Get(s, "/test", dummyController, fuego.OptionRequestContentType("application/json"))
r := httptest.NewRequest(http.MethodGet, "/test", nil)
w := httptest.NewRecorder()
s.Mux.ServeHTTP(w, r)
require.Equal(t, "{\"message\":\"hello world\"}\n", w.Body.String())
require.Len(t, route.AcceptedContentTypes, 1)
require.Equal(t, "application/json", route.AcceptedContentTypes[0])
})
t.Run("base", func(t *testing.T) {
s := fuego.NewServer()
route := fuego.Post(s, "/base", dummyController,
fuego.OptionRequestContentType("application/json"),
)
t.Log("route.Operation", route.Operation)
content := route.Operation.RequestBody.Value.Content
require.NotNil(t, content.Get("application/json"))
require.Nil(t, content.Get("application/xml"))
require.Equal(t, "#/components/schemas/ReqBody", content.Get("application/json").Schema.Ref)
_, ok := s.OpenApiSpec.Components.RequestBodies["ReqBody"]
require.False(t, ok)
})
t.Run("variadic", func(t *testing.T) {
s := fuego.NewServer()
route := fuego.Post(s, "/test", dummyController,
fuego.OptionRequestContentType("application/json", "my/content-type"),
)
content := route.Operation.RequestBody.Value.Content
require.NotNil(t, content.Get("application/json"))
require.NotNil(t, content.Get("my/content-type"))
require.Nil(t, content.Get("application/xml"))
require.Equal(t, "#/components/schemas/ReqBody", content.Get("application/json").Schema.Ref)
require.Equal(t, "#/components/schemas/ReqBody", content.Get("my/content-type").Schema.Ref)
_, ok := s.OpenApiSpec.Components.RequestBodies["ReqBody"]
require.False(t, ok)
})
t.Run("override server", func(t *testing.T) {
s := fuego.NewServer(fuego.WithRequestContentType("application/json", "application/xml"))
route := fuego.Post(
s, "/test", dummyController,
fuego.OptionRequestContentType("my/content-type"),
)
content := route.Operation.RequestBody.Value.Content
require.Nil(t, content.Get("application/json"))
require.Nil(t, content.Get("application/xml"))
require.NotNil(t, content.Get("my/content-type"))
require.Equal(t, "#/components/schemas/ReqBody", content.Get("my/content-type").Schema.Ref)
_, ok := s.OpenApiSpec.Components.RequestBodies["ReqBody"]
require.False(t, ok)
})
}
func TestAddError(t *testing.T) {
t.Run("Declare an error for the route", func(t *testing.T) {
s := fuego.NewServer()
route := fuego.Get(s, "/test", helloWorld, fuego.OptionAddError(409, "Conflict: Pet with the same name already exists"))
t.Log("route.Operation.Responses", route.Operation.Responses)
require.Equal(t, 5, route.Operation.Responses.Len()) // 200, 400, 409, 500, default
resp := route.Operation.Responses.Value("409")
require.NotNil(t, resp)
require.Equal(t, "Conflict: Pet with the same name already exists", *route.Operation.Responses.Value("409").Value.Description)
})
t.Run("should be fatal", func(t *testing.T) {
s := fuego.NewServer()
require.Panics(t, func() {
fuego.Get(s, "/test", helloWorld, fuego.OptionAddError(409, "err", Resp{}, Resp{}))
})
})
}
func TestHide(t *testing.T) {
s := fuego.NewServer()
fuego.Get(s, "/hidden", helloWorld, fuego.OptionHide())
fuego.Get(s, "/visible", helloWorld)
spec := s.OutputOpenAPISpec()
pathItemVisible := spec.Paths.Find("/visible")
require.NotNil(t, pathItemVisible)
pathItemHidden := spec.Paths.Find("/hidden")
require.Nil(t, pathItemHidden)
t.Run("visible route works normally", func(t *testing.T) {
r := httptest.NewRequest(http.MethodGet, "/visible", nil)
w := httptest.NewRecorder()
s.Mux.ServeHTTP(w, r)
require.Equal(t, 200, w.Code)
require.Equal(t, "hello world", w.Body.String())
})
t.Run("hidden route still accessible even if not in openAPI spec", func(t *testing.T) {
r := httptest.NewRequest(http.MethodGet, "/hidden", nil)
w := httptest.NewRecorder()
s.Mux.ServeHTTP(w, r)
require.Equal(t, 200, w.Code)
require.Equal(t, "hello world", w.Body.String())
})
}