-
Notifications
You must be signed in to change notification settings - Fork 0
/
schema_test.go
521 lines (482 loc) · 12.7 KB
/
schema_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
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
package rest
import (
"embed"
"encoding/json"
"fmt"
"net/http"
"reflect"
"sync"
"testing"
"time"
_ "embed"
"github.com/getkin/kin-openapi/openapi3"
"github.com/google/go-cmp/cmp"
"gopkg.in/yaml.v2"
)
//go:embed tests/*
var testFiles embed.FS
type TestRequestType struct {
IntField int
}
// TestResponseType description.
type TestResponseType struct {
// IntField description.
IntField int
}
type AllBasicDataTypes struct {
Int int
Int8 int8
Int16 int16
Int32 int32
Int64 int64
Uint uint
Uint8 uint8
Uint16 uint16
Uint32 uint32
Uint64 uint64
Uintptr uintptr
Float32 float32
Float64 float64
Byte byte
Rune rune
String string
Bool bool
}
type AllBasicDataTypesPointers struct {
Int *int
Int8 *int8
Int16 *int16
Int32 *int32
Int64 *int64
Uint *uint
Uint8 *uint8
Uint16 *uint16
Uint32 *uint32
Uint64 *uint64
Uintptr *uintptr
Float32 *float32
Float64 *float64
Byte *byte
Rune *rune
String *string
Bool *bool
}
type OmitEmptyFields struct {
A string
B string `json:",omitempty"`
C *string
D *string `json:",omitempty"`
}
type EmbeddedStructA struct {
A string
}
type EmbeddedStructB struct {
B string
OptionalB string `json:",omitempty"`
PointerB *string
OptionalPointerB *string `json:",omitempty"`
}
type WithEmbeddedStructs struct {
EmbeddedStructA
EmbeddedStructB
C string
}
type WithNameStructTags struct {
// FirstName of something.
FirstName string `json:"firstName"`
// LastName of something.
LastName string
// FullName of something.
// Deprecated: Use FirstName and LastName
FullName string
// MiddleName of something. Deprecated: This deprecation flag is not valid so this field should
// not be marked as deprecated.
MiddleName string
}
type KnownTypes struct {
Time time.Time `json:"time"`
TimePtr *time.Time `json:"timePtr"`
}
type User struct {
ID int `json:"id"`
Name string `json:"name"`
}
type OK struct {
OK bool `json:"ok"`
}
type StringEnum string
const (
StringEnumA StringEnum = "A"
StringEnumB StringEnum = "B"
StringEnumC StringEnum = "B"
)
type IntEnum int64
const (
IntEnum1 IntEnum = 1
IntEnum2 IntEnum = 2
IntEnum3 IntEnum = 3
)
type WithEnums struct {
S StringEnum `json:"s"`
SS []StringEnum `json:"ss"`
I IntEnum `json:"i"`
V string `json:"v"`
}
type Pence int64
type WithMaps struct {
Amounts map[string]Pence `json:"amounts"`
}
type MultipleDateFieldsWithComments struct {
// DateField is a field containing a date
DateField time.Time `json:"dateField"`
// DateFieldA is another field containing a date
DateFieldA time.Time `json:"dateFieldA"`
}
type StructWithCustomisation struct {
A string `json:"a"`
B FieldWithCustomisation `json:"b"`
C *FieldWithCustomisation `json:"c"`
}
func (*StructWithCustomisation) ApplyCustomSchema(s *openapi3.Schema) {
s.Properties["a"].Value.Description = "A string"
s.Properties["a"].Value.Example = "test"
s.Properties["b"].Value.Description = "A custom field"
}
type FieldWithCustomisation string
func (*FieldWithCustomisation) ApplyCustomSchema(s *openapi3.Schema) {
s.Format = "custom"
s.Example = "model_field_customisation"
}
type StructWithTags struct {
A string `json:"a" rest:"A is a string."`
}
func TestSchema(t *testing.T) {
tests := []struct {
name string
opts []APIOpts
setup func(api *API) error
}{
{
name: "test000.yaml",
setup: func(api *API) error { return nil },
},
{
name: "test001.yaml",
setup: func(api *API) error {
api.Post("/test").
HasRequestModel(ModelOf[TestRequestType]()).
HasResponseModel(http.StatusOK, ModelOf[TestResponseType]()).
HasDescription("Test request type description").
HasTags([]string{"TestRequest"})
return nil
},
},
{
name: "basic-data-types.yaml",
setup: func(api *API) error {
api.Post("/test").
HasRequestModel(ModelOf[AllBasicDataTypes]()).
HasResponseModel(http.StatusOK, ModelOf[AllBasicDataTypes]()).
HasOperationID("postAllBasicDataTypes").
HasTags([]string{"BasicData"}).
HasDescription("Post all basic data types description")
return nil
},
},
{
name: "basic-data-types-pointers.yaml",
setup: func(api *API) error {
api.Post("/test").
HasRequestModel(ModelOf[AllBasicDataTypesPointers]()).
HasResponseModel(http.StatusOK, ModelOf[AllBasicDataTypesPointers]())
return nil
},
},
{
name: "omit-empty-fields.yaml",
setup: func(api *API) error {
api.Post("/test").
HasRequestModel(ModelOf[OmitEmptyFields]()).
HasResponseModel(http.StatusOK, ModelOf[OmitEmptyFields]())
return nil
},
},
{
name: "anonymous-type.yaml",
setup: func(api *API) error {
api.Post("/test").
HasRequestModel(ModelOf[struct{ A string }]()).
HasResponseModel(http.StatusOK, ModelOf[struct{ B string }]())
return nil
},
},
{
name: "embedded-structs.yaml",
setup: func(api *API) error {
api.Get("/embedded").
HasResponseModel(http.StatusOK, ModelOf[EmbeddedStructA]())
api.Post("/test").
HasRequestModel(ModelOf[WithEmbeddedStructs]()).
HasResponseModel(http.StatusOK, ModelOf[WithEmbeddedStructs]())
return nil
},
},
{
name: "with-name-struct-tags.yaml",
setup: func(api *API) error {
api.Post("/test").
HasRequestModel(ModelOf[WithNameStructTags]()).
HasResponseModel(http.StatusOK, ModelOf[WithNameStructTags]())
return nil
},
},
{
name: "known-types.yaml",
setup: func(api *API) error {
api.Route(http.MethodGet, "/test").
HasResponseModel(http.StatusOK, ModelOf[KnownTypes]())
return nil
},
},
{
name: "all-methods.yaml",
setup: func(api *API) (err error) {
api.Get("/get").HasResponseModel(http.StatusOK, ModelOf[OK]())
api.Head("/head").HasResponseModel(http.StatusOK, ModelOf[OK]())
api.Post("/post").HasResponseModel(http.StatusOK, ModelOf[OK]())
api.Put("/put").HasResponseModel(http.StatusOK, ModelOf[OK]())
api.Patch("/patch").HasResponseModel(http.StatusOK, ModelOf[OK]())
api.Delete("/delete").HasResponseModel(http.StatusOK, ModelOf[OK]())
api.Connect("/connect").HasResponseModel(http.StatusOK, ModelOf[OK]())
api.Options("/options").HasResponseModel(http.StatusOK, ModelOf[OK]())
api.Trace("/trace").HasResponseModel(http.StatusOK, ModelOf[OK]())
return
},
},
{
name: "enums.yaml",
setup: func(api *API) (err error) {
// Register the enums and values.
api.RegisterModel(ModelOf[StringEnum](), WithEnumValues(StringEnumA, StringEnumB, StringEnumC))
api.RegisterModel(ModelOf[IntEnum](), WithEnumValues(IntEnum1, IntEnum2, IntEnum3))
api.Get("/get").HasResponseModel(http.StatusOK, ModelOf[WithEnums]())
return
},
},
{
name: "enum-constants.yaml",
setup: func(api *API) (err error) {
// Register the enums and values.
api.RegisterModel(ModelOf[StringEnum](), WithEnumConstants[StringEnum]())
api.RegisterModel(ModelOf[IntEnum](), WithEnumConstants[IntEnum]())
api.Get("/get").HasResponseModel(http.StatusOK, ModelOf[WithEnums]())
return
},
},
{
name: "with-maps.yaml",
setup: func(api *API) (err error) {
api.Get("/get").HasResponseModel(http.StatusOK, ModelOf[WithMaps]())
return
},
},
{
name: "route-params.yaml",
setup: func(api *API) (err error) {
api.Get(`/organisation/{orgId:\d+}/user/{userId}`).
HasPathParameter("orgId", PathParam{
Description: "Organisation ID",
Regexp: `\d+`,
}).
HasPathParameter("userId", PathParam{
Description: "User ID",
}).
HasResponseModel(http.StatusOK, ModelOf[User]())
return
},
},
{
name: "route-params.yaml",
setup: func(api *API) (err error) {
api.Get(`/organisation/{orgId:\d+}/user/{userId}`).
HasPathParameter("orgId", PathParam{
Regexp: `\d+`,
ApplyCustomSchema: func(s *openapi3.Parameter) {
s.Description = "Organisation ID"
},
}).
HasPathParameter("userId", PathParam{
Description: "User ID",
}).
HasResponseModel(http.StatusOK, ModelOf[User]())
return
},
},
{
name: "query-params.yaml",
setup: func(api *API) (err error) {
api.Get(`/users?orgId=123&orderBy=field`).
HasQueryParameter("orgId", QueryParam{
Description: "ID of the organisation",
Required: true,
Type: PrimitiveTypeInteger,
}).
HasQueryParameter("orderBy", QueryParam{
Description: "The field to order the results by",
Required: false,
Type: PrimitiveTypeString,
Regexp: `field|otherField`,
}).
HasResponseModel(http.StatusOK, ModelOf[User]())
return
},
},
{
name: "query-params.yaml",
setup: func(api *API) (err error) {
api.Get(`/users?orgId=123&orderBy=field`).
HasQueryParameter("orgId", QueryParam{
Required: true,
Type: PrimitiveTypeInteger,
ApplyCustomSchema: func(s *openapi3.Parameter) {
s.Description = "ID of the organisation"
},
}).
HasQueryParameter("orderBy", QueryParam{
Required: false,
Type: PrimitiveTypeString,
Regexp: `field|otherField`,
ApplyCustomSchema: func(s *openapi3.Parameter) {
s.Description = "The field to order the results by"
},
}).
HasResponseModel(http.StatusOK, ModelOf[User]())
return
},
},
{
name: "multiple-dates-with-comments.yaml",
setup: func(api *API) (err error) {
api.Get("/dates").
HasResponseModel(http.StatusOK, ModelOf[MultipleDateFieldsWithComments]())
return
},
},
{
name: "custom-models.yaml",
setup: func(api *API) (err error) {
api.Get("/struct-with-customisation").
HasResponseModel(http.StatusOK, ModelOf[StructWithCustomisation]())
api.Get("/struct-ptr-with-customisation").
HasResponseModel(http.StatusOK, ModelOf[*StructWithCustomisation]())
return
},
},
{
name: "global-customisation.yaml",
opts: []APIOpts{
WithApplyCustomSchemaToType(func(t reflect.Type, s *openapi3.Schema) {
if t != reflect.TypeOf(StructWithTags{}) {
return
}
for fi := 0; fi < t.NumField(); fi++ {
// Get the field name.
var name string
name = t.Field(fi).Tag.Get("json")
if name == "" {
name = t.Field(fi).Name
}
// Get the custom description from the struct tag.
desc := t.Field(fi).Tag.Get("rest")
if desc == "" {
continue
}
if s.Properties == nil {
s.Properties = make(map[string]*openapi3.SchemaRef)
}
if s.Properties[name] == nil {
s.Properties[name] = &openapi3.SchemaRef{
Value: &openapi3.Schema{},
}
}
s.Properties[name].Value.Description = desc
}
}),
},
setup: func(api *API) error {
api.Get("/").
HasResponseModel(http.StatusOK, ModelOf[StructWithTags]())
return nil
},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
var expected, actual []byte
var wg sync.WaitGroup
wg.Add(2)
errs := make([]error, 2)
// Validate the test file.
go func() {
defer wg.Done()
// Load test file.
expectedYAML, err := testFiles.ReadFile("tests/" + test.name)
if err != nil {
errs[0] = fmt.Errorf("could not read file %q: %v", test.name, err)
return
}
expectedSpec, err := openapi3.NewLoader().LoadFromData(expectedYAML)
if err != nil {
errs[0] = fmt.Errorf("error in expected YAML: %w", err)
return
}
expected, errs[0] = specToYAML(expectedSpec)
}()
go func() {
defer wg.Done()
// Create the API.
api := NewAPI(test.name, test.opts...)
api.StripPkgPaths = []string{"github.com/a-h/rest"}
// Configure it.
test.setup(api)
// Create the actual spec.
spec, err := api.Spec()
if err != nil {
t.Errorf("failed to generate spec: %v", err)
}
actual, errs[1] = specToYAML(spec)
}()
wg.Wait()
var setupFailed bool
for _, err := range errs {
if err != nil {
setupFailed = true
t.Error(err)
}
}
if setupFailed {
t.Fatal("test setup failed")
}
// Compare the JSON marshalled output to ignore unexported fields and internal state.
if diff := cmp.Diff(expected, actual); diff != "" {
t.Error(diff)
t.Error("\n\n" + string(actual))
}
})
}
}
func specToYAML(spec *openapi3.T) (out []byte, err error) {
// Use JSON, because kin-openapi doesn't customise the YAML output.
// For example, AdditionalProperties only has a MarshalJSON capability.
out, err = json.Marshal(spec)
if err != nil {
err = fmt.Errorf("could not marshal spec to JSON: %w", err)
return
}
var m map[string]interface{}
err = json.Unmarshal(out, &m)
if err != nil {
return
}
return yaml.Marshal(m)
}