-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathopenapi3_test.go
More file actions
464 lines (430 loc) · 15.9 KB
/
openapi3_test.go
File metadata and controls
464 lines (430 loc) · 15.9 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
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
// Copyright © 2024 Kaleido, Inc.
//
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package ffapi
import (
"context"
"fmt"
"github.com/stretchr/testify/require"
"net/http"
"testing"
"github.com/getkin/kin-openapi/openapi3"
"github.com/ghodss/yaml"
"github.com/hyperledger/firefly-common/pkg/config"
"github.com/hyperledger/firefly-common/pkg/fftypes"
"github.com/hyperledger/firefly-common/pkg/i18n"
"github.com/stretchr/testify/assert"
"golang.org/x/text/language"
)
type TestEnum fftypes.FFEnum
var (
TestEnumVal1 = fftypes.FFEnumValue("ut", "val1")
TestEnumVal2 = fftypes.FFEnumValue("ut", "val2")
)
type TestStruct1 struct {
TestEmbedded1
ID *fftypes.UUID `ffstruct:"ut1" json:"id"`
Time *fftypes.FFTime `ffstruct:"ut1" json:"time"`
Hash *fftypes.Bytes32 `ffstruct:"ut1" json:"hash"`
Amount *fftypes.FFBigInt `ffstruct:"ut1" json:"amount"`
}
type TestEmbedded1 struct {
Enum1 TestEnum `ffstruct:"ut1" json:"enum1" ffenum:"ut"`
String1 string `ffstruct:"ut1" json:"string1"`
String2 string `ffstruct:"ut1" json:"string2"`
JSONAny1 *fftypes.JSONAny `ffstruct:"ut1" json:"jsonAny1,omitempty"`
Number1 int64 `ffstruct:"ut1" json:"number1"`
Struct2 TestStruct2 `ffstruct:"ut1" json:"struct2"`
}
type TestStruct2 struct {
Enum1 TestEnum `ffstruct:"ut1" json:"enum1" ffenum:"ut"`
String1 string `ffstruct:"ut1" json:"string1"`
String2 string `ffstruct:"ut1" json:"string2"`
JSONAny1 *fftypes.JSONAny `ffstruct:"ut1" json:"jsonAny1,omitempty"`
}
var ExampleDesc = i18n.FFM(language.AmericanEnglish, "TestKey", "Test Description")
var testRoutes = []*Route{
{
Name: "op1",
Path: "namespaces/{ns}/example1/{id}/things",
Method: http.MethodGet,
PathParams: []*PathParam{
{Name: "lang", ExampleFromConf: config.Lang, Description: ExampleDesc},
{Name: "id", Example: "id12345", Description: ExampleDesc},
},
FilterFactory: TestQueryFactory,
QueryParams: nil,
Description: ExampleDesc,
JSONInputValue: func() interface{} { return &TestStruct1{} },
JSONOutputValue: func() interface{} { return &TestStruct2{} },
JSONOutputCodes: []int{http.StatusOK},
},
{
Name: "op2",
Path: "example2",
Method: http.MethodPatch,
PathParams: nil,
QueryParams: nil,
Description: ExampleDesc,
JSONInputValue: func() interface{} { return nil },
JSONInputSchema: func(ctx context.Context, schemaGen SchemaGenerator) (*openapi3.SchemaRef, error) {
s1, _ := schemaGen(&TestStruct1{})
s2, _ := schemaGen(&TestStruct2{})
return &openapi3.SchemaRef{
Value: openapi3.NewAnyOfSchema(s1.Value, s2.Value),
}, nil
},
JSONOutputSchema: func(ctx context.Context, schemaGen SchemaGenerator) (*openapi3.SchemaRef, error) {
return schemaGen(&TestStruct1{})
},
JSONOutputCodes: []int{http.StatusOK},
},
{
Name: "op3",
Path: "example2",
Method: http.MethodPut,
PathParams: nil,
QueryParams: []*QueryParam{
{Name: "lang", ExampleFromConf: config.Lang, Description: ExampleDesc},
{Name: "myfield", Default: "val1", Description: ExampleDesc},
},
Description: ExampleDesc,
JSONInputValue: func() interface{} { return &TestStruct1{} },
JSONOutputValue: func() interface{} { return nil },
JSONOutputCodes: []int{http.StatusNoContent},
FormParams: []*FormParam{
{Name: "metadata", Description: ExampleDesc},
},
FormUploadHandler: func(r *APIRequest) (output interface{}, err error) { return nil, nil },
},
{
Name: "op4",
Path: "example2/{id}",
Method: http.MethodDelete,
PathParams: []*PathParam{
{Name: "id", Description: ExampleDesc},
},
QueryParams: nil,
Description: ExampleDesc,
JSONInputValue: func() interface{} { return nil },
JSONOutputValue: func() interface{} { return nil },
JSONOutputCodes: []int{http.StatusNoContent},
},
{
Name: "op5",
Path: "example2",
Method: http.MethodPost,
PathParams: nil,
QueryParams: nil,
Description: ExampleDesc,
JSONInputValue: func() interface{} { return &TestStruct1{} },
JSONOutputValue: func() interface{} { return &TestStruct1{} },
JSONOutputCodes: []int{http.StatusOK},
},
{
Name: "op6",
Path: "example3",
Method: http.MethodGet,
PathParams: nil,
QueryParams: []*QueryParam{
{Name: "scope", IsArray: true},
},
Description: ExampleDesc,
JSONInputValue: func() interface{} { return &TestStruct1{} },
JSONOutputValue: func() interface{} { return &TestStruct1{} },
JSONOutputCodes: []int{http.StatusOK},
},
}
type TestInOutType struct {
Length float64 `ffstruct:"TestInOutType" json:"length"`
Width float64 `ffstruct:"TestInOutType" json:"width"`
Height float64 `ffstruct:"TestInOutType" json:"height" ffexcludeoutput:"true"`
Volume fftypes.FFBigInt `ffstruct:"TestInOutType" json:"volume" ffexcludeinput:"true"`
Secret string `ffstruct:"TestInOutType" json:"secret" ffexclude:"true"`
Conditional string `ffstruct:"TestInOutType" json:"conditional" ffexclude:"PostTagTest"`
ConditionalInput string `ffstruct:"TestInOutType" json:"conditionalInput" ffexcludeinput:"PostTagTest"`
}
type TestNonTaggedType struct {
NoFFStructTag string `json:"noFFStructTag"`
}
func TestOpenAPI3SwaggerGen(t *testing.T) {
doc := NewSwaggerGen(&SwaggerGenOptions{
Title: "UnitTest",
Version: "1.0",
BaseURL: "http://localhost:12345/api/v1",
RouteCustomizations: func(ctx context.Context, sg *SwaggerGen, route *Route, op *openapi3.Operation) {
sg.AddParam(ctx, op, "header", "x-my-param", "thing", "stuff", ExampleDesc, false)
},
SupportFieldRedaction: true,
}).Generate(context.Background(), testRoutes)
sl := openapi3.NewLoader()
b, err := yaml.Marshal(doc)
assert.NoError(t, err)
doc, err = sl.LoadFromData(b)
assert.NoError(t, err)
err = doc.Validate(sl.Context)
assert.NoError(t, err)
fmt.Print(string(b))
}
func TestBadCustomInputSchemaFail(t *testing.T) {
routes := []*Route{
{
Name: "op6",
Path: "namespaces/{ns}/example1/{id}",
Method: http.MethodPost,
JSONInputValue: func() interface{} { return &TestStruct1{} },
JSONInputMask: []string{"id"},
JSONOutputCodes: []int{http.StatusOK},
JSONInputSchema: func(ctx context.Context, schemaGen SchemaGenerator) (*openapi3.SchemaRef, error) {
return nil, fmt.Errorf("pop")
},
},
}
assert.Panics(t, func() {
_ = NewSwaggerGen(&SwaggerGenOptions{
Title: "UnitTest",
Version: "1.0",
BaseURL: "http://localhost:12345/api/v1",
}).Generate(context.Background(), routes)
})
}
func TestBadCustomOutputSchemaFail(t *testing.T) {
routes := []*Route{
{
Name: "op7",
Path: "namespaces/{ns}/example1/{id}",
Method: http.MethodGet,
JSONInputValue: func() interface{} { return &TestStruct1{} },
JSONInputMask: []string{"id"},
JSONOutputSchema: func(ctx context.Context, schemaGen SchemaGenerator) (*openapi3.SchemaRef, error) {
return nil, fmt.Errorf("pop")
},
},
}
assert.Panics(t, func() {
_ = NewSwaggerGen(&SwaggerGenOptions{
Title: "UnitTest",
Version: "1.0",
BaseURL: "http://localhost:12345/api/v1",
}).Generate(context.Background(), routes)
})
}
func TestDuplicateOperationIDCheck(t *testing.T) {
routes := []*Route{
{Name: "op1"}, {Name: "op1"},
}
assert.PanicsWithValue(t, "Duplicate/invalid name (used as operation ID in swagger): op1", func() {
_ = NewSwaggerGen(&SwaggerGenOptions{
Title: "UnitTest",
Version: "1.0",
BaseURL: "http://localhost:12345/api/v1",
}).Generate(context.Background(), routes)
})
}
func TestWildcards(t *testing.T) {
routes := []*Route{
{
Name: "op1",
Path: "namespaces/{ns}/example1/{id:.*wildcard.*}",
Method: http.MethodPost,
JSONInputValue: func() interface{} { return &TestStruct1{} },
JSONOutputCodes: []int{http.StatusOK},
},
}
swagger := NewSwaggerGen(&SwaggerGenOptions{
Title: "UnitTest",
Version: "1.0",
BaseURL: "http://localhost:12345/api/v1",
}).Generate(context.Background(), routes)
assert.NotNil(t, swagger.Paths.Find("/namespaces/{ns}/example1/{id}"))
assert.NotNil(t, swagger.Paths.Value("/namespaces/{ns}/example1/{id}"))
}
func TestFFExcludeTag(t *testing.T) {
routes := []*Route{
{
Name: "PostTagTest",
Path: "namespaces/{ns}/example1/test",
Method: http.MethodPost,
JSONInputValue: func() interface{} { return &TestInOutType{} },
JSONOutputValue: func() interface{} { return &TestInOutType{} },
JSONOutputCodes: []int{http.StatusOK},
},
}
swagger := NewSwaggerGen(&SwaggerGenOptions{
Title: "UnitTest",
Version: "1.0",
BaseURL: "http://localhost:12345/api/v1",
}).Generate(context.Background(), routes)
assert.NotNil(t, swagger.Paths.Find("/namespaces/{ns}/example1/test").Post.RequestBody.Value)
length, err := swagger.Paths.Find("/namespaces/{ns}/example1/test").Post.RequestBody.Value.Content.Get("application/json").Schema.Value.Properties.JSONLookup("length")
assert.NoError(t, err)
assert.NotNil(t, length)
width, err := swagger.Paths.Find("/namespaces/{ns}/example1/test").Post.RequestBody.Value.Content.Get("application/json").Schema.Value.Properties.JSONLookup("width")
assert.NoError(t, err)
assert.NotNil(t, width)
_, err = swagger.Paths.Find("/namespaces/{ns}/example1/test").Post.RequestBody.Value.Content.Get("application/json").Schema.Value.Properties.JSONLookup("secret")
assert.Regexp(t, "no schema", err)
_, err = swagger.Paths.Find("/namespaces/{ns}/example1/test").Post.RequestBody.Value.Content.Get("application/json").Schema.Value.Properties.JSONLookup("conditional")
assert.Regexp(t, "no schema", err)
_, err = swagger.Paths.Find("/namespaces/{ns}/example1/test").Post.RequestBody.Value.Content.Get("application/json").Schema.Value.Properties.JSONLookup("conditionalInput")
assert.Regexp(t, "no schema", err)
}
func TestCustomResponseRefs(t *testing.T) {
routes := []*Route{
{
Name: "CustomResponseRefTest",
Path: "/test",
Method: http.MethodGet,
CustomResponseRefs: map[string]*openapi3.ResponseRef{
"200": {
Value: &openapi3.Response{
Content: openapi3.Content{
"text/plain": &openapi3.MediaType{},
},
},
},
},
},
}
swagger := NewSwaggerGen(&SwaggerGenOptions{
Title: "UnitTest",
Version: "1.0",
BaseURL: "http://localhost:12345/api/v1",
}).Generate(context.Background(), routes)
assert.Nil(t, swagger.Paths.Find("/test").Get.RequestBody)
require.NotEmpty(t, swagger.Paths.Find("/test").Get.Responses)
require.NotNil(t, swagger.Paths.Find("/test").Get.Responses.Value("200"))
require.NotNil(t, swagger.Paths.Find("/test").Get.Responses.Value("200").Value)
assert.NotNil(t, swagger.Paths.Find("/test").Get.Responses.Value("200").Value.Content.Get("text/plain"))
assert.Nil(t, swagger.Paths.Find("/test").Get.Responses.Value("201"))
}
func TestPanicOnMissingDescription(t *testing.T) {
routes := []*Route{
{
Name: "PostPanicOnMissingDescription",
Path: "namespaces/{ns}/example1/test",
Method: http.MethodPost,
Description: "this is fine",
JSONInputValue: func() interface{} { return &TestInOutType{} },
JSONOutputValue: func() interface{} { return &TestInOutType{} },
JSONOutputCodes: []int{http.StatusOK},
},
}
assert.PanicsWithValue(t, "invalid schema: FF00158: Field description missing for 'TestInOutType.conditional' on route 'PostPanicOnMissingDescription'", func() {
_ = NewSwaggerGen(&SwaggerGenOptions{
Title: "UnitTest",
Version: "1.0",
BaseURL: "http://localhost:12345/api/v1",
PanicOnMissingDescription: true,
}).Generate(context.Background(), routes)
})
}
func TestPanicOnMissingFFStructTag(t *testing.T) {
routes := []*Route{
{
Name: "GetPanicOnMissingFFStructTag",
Path: "namespaces/{ns}/example1/test",
Method: http.MethodGet,
Description: "this is fine",
JSONOutputValue: func() interface{} { return &TestNonTaggedType{} },
JSONOutputCodes: []int{http.StatusOK},
},
}
assert.PanicsWithValue(t, "invalid schema: FF00160: ffstruct tag is missing for 'noFFStructTag' on route 'GetPanicOnMissingFFStructTag'", func() {
_ = NewSwaggerGen(&SwaggerGenOptions{
Title: "UnitTest",
Version: "1.0",
BaseURL: "http://localhost:12345/api/v1",
PanicOnMissingDescription: true,
}).Generate(context.Background(), routes)
})
}
func TestPanicOnMissingRouteDescription(t *testing.T) {
routes := []*Route{
{
Name: "GetPanicOnMissingRouteDescription",
Path: "namespaces/{ns}/example1/test",
Method: http.MethodGet,
JSONOutputValue: func() interface{} { return &TestNonTaggedType{} },
JSONOutputCodes: []int{http.StatusOK},
},
}
assert.PanicsWithValue(t, "FF00159: API route description missing for route 'GetPanicOnMissingRouteDescription'", func() {
_ = NewSwaggerGen(&SwaggerGenOptions{
Title: "UnitTest",
Version: "1.0",
BaseURL: "http://localhost:12345/api/v1",
PanicOnMissingDescription: true,
}).Generate(context.Background(), routes)
})
}
func TestPreTranslatedRouteDescription(t *testing.T) {
routes := []*Route{
{
Name: "PostTagTest",
Path: "namespaces/{ns}/example1/test",
Method: http.MethodPost,
JSONInputValue: func() interface{} { return &TestInOutType{} },
JSONOutputValue: func() interface{} { return &TestInOutType{} },
JSONOutputCodes: []int{http.StatusOK},
PreTranslatedDescription: "this is a description",
},
}
swagger := NewSwaggerGen(&SwaggerGenOptions{
Title: "UnitTest",
Version: "1.0",
BaseURL: "http://localhost:12345/api/v1",
}).Generate(context.Background(), routes)
assert.NotNil(t, swagger.Paths.Find("/namespaces/{ns}/example1/test").Post.RequestBody.Value)
description := swagger.Paths.Find("/namespaces/{ns}/example1/test").Post.Description
assert.NotNil(t, swagger.Paths.Value("/namespaces/{ns}/example1/test").Post.RequestBody.Value)
description = swagger.Paths.Value("/namespaces/{ns}/example1/test").Post.Description
assert.Equal(t, "this is a description", description)
}
func TestBaseURLVariables(t *testing.T) {
doc := NewSwaggerGen(&SwaggerGenOptions{
Title: "UnitTest",
Version: "1.0",
BaseURL: "http://localhost:12345/api/v1/{param}",
BaseURLVariables: map[string]BaseURLVariable{
"param": {
Default: "default-value",
},
},
}).Generate(context.Background(), testRoutes)
sl := openapi3.NewLoader()
b, err := yaml.Marshal(doc)
assert.NoError(t, err)
doc, err = sl.LoadFromData(b)
assert.NoError(t, err)
// Validate doesn't like references
// so LoadFromData resolves those references
// before we validate
err = doc.Validate(sl.Context)
assert.NoError(t, err)
server := doc.Servers[0]
if assert.Contains(t, server.Variables, "param") {
assert.Equal(t, "default-value", server.Variables["param"].Default)
}
}
func TestCheckObjectDocumented(t *testing.T) {
type Undocumented struct {
Field1 string `ffstruct:"ThisDoesNotHaveDocs" json:"field1"`
}
defer func() {
assert.Regexp(t, "FF00158.*ThisDoesNotHaveDocs.field1", recover())
}()
CheckObjectDocumented(&Undocumented{})
}