-
Notifications
You must be signed in to change notification settings - Fork 1
/
sashay_test.go
1434 lines (1386 loc) · 31.8 KB
/
sashay_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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package sashay_test
import (
"bytes"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/rgalanakis/sashay"
"io/ioutil"
"math/rand"
"os"
"strings"
"testing"
"time"
)
func TestSashay(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Sashay Suite")
}
type User struct {
Result struct {
ID int `json:"id"`
Name string `json:"name"`
} `json:"result"`
}
type ErrorModel struct {
Error struct {
Message string `json:"message"`
Code int `json:"code"`
} `json:"error"`
}
var _ = Describe("Sashay", func() {
var (
sw *sashay.Sashay
)
BeforeEach(func() {
sw = sashay.New(
"SwaggerGenAPI",
"Demonstrate auto-generating Swagger",
"0.1.9",
)
})
It("generates the info section", func() {
Expect(sw.BuildYAML()).To(ContainSubstring(`openapi: 3.0.0
info:
title: SwaggerGenAPI
description: Demonstrate auto-generating Swagger
version: 0.1.9
paths:
`))
})
It("can set more fields in the info section", func() {
sw.SetTermsOfService("http://example.com/terms/").
SetContact("API Support", "http://www.example.com/support", "[email protected]").
SetLicense("Apache 2.0", "https://www.apache.org/licenses/LICENSE-2.0.html").
AddTag("tagA", "its a tag")
Expect(sw.BuildYAML()).To(ContainSubstring(`openapi: 3.0.0
info:
title: SwaggerGenAPI
description: Demonstrate auto-generating Swagger
termsOfService: http://example.com/terms/
contact:
name: API Support
url: http://www.example.com/support
email: [email protected]
license:
name: Apache 2.0
url: https://www.apache.org/licenses/LICENSE-2.0.html
version: 0.1.9
tags:
- name: tagA
description: its a tag
`))
})
It("generates a server section", func() {
sw.AddServer("https://api.example.com/v1", "Production server.")
Expect(sw.BuildYAML()).To(ContainSubstring(`servers:
- url: https://api.example.com/v1
description: Production server.
`))
})
It("has no server section if that are no servers", func() {
Expect(sw.BuildYAML()).To(Not(ContainSubstring(`servers:`)))
})
It("can set global security types", func() {
sw.AddBasicAuthSecurity()
sw.AddJWTSecurity()
sw.AddAPIKeySecurity("header", "X-MY-APIKEY")
Expect(sw.BuildYAML()).To(ContainSubstring(`components:
securitySchemes:
basicAuth:
type: http
scheme: basic
bearerAuth:
type: http
bearerFormat: JWT
scheme: bearer
apiKeyAuth:
type: apiKey
in: header
name: X-MY-APIKEY
security:
- basicAuth: []
- bearerAuth: []
- apiKeyAuth: []
`))
})
It("generates paths for routes with no parameters", func() {
sw.Add(sashay.NewOperation(
"GET",
"/users",
"Returns a list of users.",
nil,
[]User{},
ErrorModel{},
))
Expect(sw.BuildYAML()).To(ContainSubstring(`paths:
/users:
get:
operationId: getUsers
summary: Returns a list of users.
responses:
'200':
description: ok response
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/User'
'default':
description: error response
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorModel'
`))
})
It("keeps routes and methods in the same order", func() {
newOp := func(method, path string) sashay.Operation {
return sashay.NewOperation(
method, path, "", nil, nil, nil)
}
ops := []sashay.Operation{
newOp("POST", "/zzz"),
newOp("POST", "/aaa"),
newOp("GET", "/aaa"),
newOp("GET", "/zzz"),
newOp("DELETE", "/aaa"),
newOp("PUT", "/aaa"),
newOp("PATCH", "/aaa"),
}
makeSwagger := func() *sashay.Sashay {
sw := sashay.New("title", "desc", "0.0.1")
list := rand.Perm(len(ops))
for _, i := range list {
sw.Add(ops[i])
}
return sw
}
for i := 0; i < 20; i++ {
Expect(makeSwagger().BuildYAML()).To(ContainSubstring(`paths:
/aaa:
get:
operationId: getAaa
responses:
'204':
description: The operation completed successfully.
'default':
description: error response
post:
operationId: postAaa
responses:
'204':
description: The operation completed successfully.
'default':
description: error response
put:
operationId: putAaa
responses:
'204':
description: The operation completed successfully.
'default':
description: error response
patch:
operationId: patchAaa
responses:
'204':
description: The operation completed successfully.
'default':
description: error response
delete:
operationId: deleteAaa
responses:
'204':
description: The operation completed successfully.
'default':
description: error response
/zzz:
get:
operationId: getZzz
responses:
'204':
description: The operation completed successfully.
'default':
description: error response
post:
operationId: postZzz
responses:
'204':
description: The operation completed successfully.
'default':
description: error response
`))
}
})
It("can uses swagger.Responses for response fields", func() {
type TeapotResponse struct {
Probability float64 `json:"prob"`
}
type TeapotError struct {
Strength float64 `json:"strength"`
}
sw.Add(sashay.NewOperation(
"GET",
"/is_teapot",
"Error if the server is a teapot.",
nil,
sashay.Responses{sashay.NewResponse(203, "I may not be a teapot", TeapotResponse{})},
sashay.Responses{sashay.NewResponse(418, "Yes, I am sure a teapot!", TeapotError{})},
))
Expect(sw.BuildYAML()).To(ContainSubstring(`paths:
/is_teapot:
get:
operationId: getIsTeapot
summary: Error if the server is a teapot.
responses:
'203':
description: I may not be a teapot
content:
application/json:
schema:
$ref: '#/components/schemas/TeapotResponse'
'418':
description: Yes, I am sure a teapot!
content:
application/json:
schema:
$ref: '#/components/schemas/TeapotError'
`))
})
It("can uses swagger.Response for response fields", func() {
type TeapotResponse struct {
Probability float64 `json:"prob"`
}
type TeapotError struct {
Strength float64 `json:"strength"`
}
sw.Add(sashay.NewOperation(
"GET",
"/is_teapot",
"Error if the server is a teapot.",
nil,
sashay.NewResponse(203, "I may not be a teapot", TeapotResponse{}),
sashay.NewResponse(418, "Yes, I am sure a teapot!", TeapotError{}),
))
Expect(sw.BuildYAML()).To(ContainSubstring(`paths:
/is_teapot:
get:
operationId: getIsTeapot
summary: Error if the server is a teapot.
responses:
'203':
description: I may not be a teapot
content:
application/json:
schema:
$ref: '#/components/schemas/TeapotResponse'
'418':
description: Yes, I am sure a teapot!
content:
application/json:
schema:
$ref: '#/components/schemas/TeapotError'
`))
})
It("interprets string responses as text/plain", func() {
sw.Add(sashay.NewOperation(
"GET",
"/plain",
"plain",
nil,
sashay.NewResponse(200, "desc", ""),
""),
)
Expect(sw.BuildYAML()).To(ContainSubstring(`paths:
/plain:
get:
operationId: getPlain
summary: plain
responses:
'200':
description: desc
content:
text/plain:
schema:
type: string
'default':
description: error response
content:
text/plain:
schema:
type: string
`))
})
It("interprets empty structs as plain objects", func() {
sw.Add(sashay.NewOperation(
"GET",
"/plain",
"plain",
nil,
struct{}{},
""),
)
Expect(sw.BuildYAML()).To(ContainSubstring(`paths:
/plain:
get:
operationId: getPlain
summary: plain
responses:
'200':
description: ok response
content:
application/json:
schema:
type: object
'default':
`))
})
It("generates paths with descriptions and tags", func() {
sw.Add(sashay.NewOperation(
"GET",
"/users",
"Returns a list of users.",
nil,
nil,
nil).
WithDescription("CommonMark description.").
AddTags("tagA", "tagB"))
Expect(sw.BuildYAML()).To(ContainSubstring(`paths:
/users:
get:
tags: ["tagA", "tagB"]
operationId: getUsers
summary: Returns a list of users.
description: CommonMark description.
`))
})
It("generates paths for routes with annotated path and query parameters", func() {
sw.Add(sashay.NewOperation(
"GET",
"/users/:id",
"Returns the ID'd user.",
struct {
ID int `path:"id" validate:"min=1" description:"CommonMark description."`
Pretty bool `query:"pretty" default:"true"`
}{},
User{},
ErrorModel{},
))
Expect(sw.BuildYAML()).To(ContainSubstring(`paths:
/users/{id}:
get:
operationId: getUsersId
summary: Returns the ID'd user.
parameters:
- name: id
in: path
required: true
description: CommonMark description.
schema:
type: integer
format: int64
- name: pretty
in: query
schema:
type: boolean
default: true
responses:
'200':
description: ok response
content:
application/json:
schema:
$ref: '#/components/schemas/User'
'default':
description: error response
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorModel'
`))
})
It("can use an alternative global content type", func() {
sw.DefaultContentType = "application/myapp+json+v1"
sw.Add(sashay.NewOperation(
"POST",
"/users/:id",
"Update the user",
struct {
ID string `path:"id"`
Name string `json:"name"`
}{},
User{},
ErrorModel{},
))
Expect(sw.BuildYAML()).To(ContainSubstring(`paths:
/users/{id}:
post:
operationId: postUsersId
summary: Update the user
parameters:
- name: id
in: path
required: true
schema:
type: string
requestBody:
required: true
content:
application/myapp+json+v1:
schema:
type: object
properties:
name:
type: string
responses:
'201':
description: ok response
content:
application/myapp+json+v1:
schema:
$ref: '#/components/schemas/User'
'default':
description: error response
content:
application/myapp+json+v1:
schema:
$ref: '#/components/schemas/ErrorModel'
`))
})
It("generates schemas for return and error types", func() {
sw.Add(sashay.NewOperation(
"GET",
"/users",
"",
nil,
[]User{},
ErrorModel{},
))
Expect(sw.BuildYAML()).To(ContainSubstring(`components:
schemas:
ErrorModel:
type: object
properties:
error:
type: object
properties:
message:
type: string
code:
type: integer
format: int64
User:
type: object
properties:
result:
type: object
properties:
id:
type: integer
format: int64
name:
type: string
`))
})
It("generates schemas for types with simple arrays", func() {
type Tagger struct {
Tags []string `json:"tags"`
}
sw.Add(sashay.NewOperation(
"GET",
"/tags",
"",
nil,
Tagger{},
nil,
))
Expect(sw.BuildYAML()).To(ContainSubstring(`components:
schemas:
Tagger:
type: object
properties:
tags:
type: array
items:
type: string
`))
})
It("generates schemas for named structs under anonymous structs", func() {
type FieldB struct {
FieldC string `json:"fieldC"`
}
type FieldA struct {
Wrapper struct {
FieldB FieldB `json:"fieldB"`
} `json:"wrapper"`
}
type Response struct {
Result struct {
FieldA FieldA `json:"fieldA"`
} `json:"result"`
}
sw.Add(sashay.NewOperation(
"GET",
"/tags",
"",
nil,
Response{},
nil,
))
Expect(sw.BuildYAML()).To(ContainSubstring(`components:
schemas:
FieldA:
type: object
properties:
wrapper:
type: object
properties:
fieldB:
$ref: '#/components/schemas/FieldB'
FieldB:
type: object
properties:
fieldC:
type: string
Response:
type: object
properties:
result:
type: object
properties:
fieldA:
$ref: '#/components/schemas/FieldA'
`))
})
It("generates schemas for embedded structs", func() {
type Inside struct {
nothere int
InsideField string `json:"insideField"`
}
type ExportedBase struct {
hidden bool
ExportedResult struct {
ExportedInside Inside `json:"exportedInside"`
} `json:"exportedResult"`
}
type unexportedBase struct {
unexported string
UnexportedResult struct {
UnexportedInside Inside `json:"unexportedInside"`
} `json:"unexportedResult"`
}
type Response struct {
ExportedBase
unexportedBase
}
sw.Add(sashay.NewOperation(
"GET",
"/tags",
"",
nil,
Response{},
nil,
))
Expect(sw.BuildYAML()).To(HaveSuffix(`components:
schemas:
Inside:
type: object
properties:
insideField:
type: string
Response:
type: object
properties:
exportedResult:
type: object
properties:
exportedInside:
$ref: '#/components/schemas/Inside'
unexportedResult:
type: object
properties:
unexportedInside:
$ref: '#/components/schemas/Inside'
`))
})
It("generates schemas for POSTs with request bodies", func() {
sw.Add(sashay.NewOperation(
"POST",
"/users",
"Creates a new user.",
struct {
Name string `json:"name"`
Pretty bool `query:"pretty"`
}{},
User{},
ErrorModel{},
))
Expect(sw.BuildYAML()).To(ContainSubstring(`paths:
/users:
post:
operationId: postUsers
summary: Creates a new user.
parameters:
- name: pretty
in: query
schema:
type: boolean
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
name:
type: string
responses:
'201':
description: ok response
content:
application/json:
schema:
$ref: '#/components/schemas/User'
'default':
description: error response
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorModel'
`))
})
It("does not include requestBody for POST/PUT with no parameters", func() {
sw.Add(sashay.NewOperation(
"POST",
"/checkin",
"",
nil,
nil,
nil,
))
Expect(sw.BuildYAML()).To(ContainSubstring(`paths:
/checkin:
post:
operationId: postCheckin
responses:
`))
})
It("uses a 204 success if an endpoint has no response struct", func() {
sw.Add(sashay.NewOperation(
"GET",
"/ping",
"Check health.",
nil,
nil,
ErrorModel{},
))
Expect(sw.BuildYAML()).To(ContainSubstring(`paths:
/ping:
get:
operationId: getPing
summary: Check health.
responses:
'204':
description: The operation completed successfully.
'default':
description: error response
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorModel'
`))
})
It("can handle parameters that are slices of objects", func() {
sw.Add(sashay.NewOperation(
"POST",
"/users",
"Create a user.",
struct {
Name string `json:"name"`
Tags []struct {
TagName string `json:"tagName"`
} `json:"tags"`
}{},
nil,
ErrorModel{},
))
Expect(sw.BuildYAML()).To(ContainSubstring(`paths:
/users:
post:
operationId: postUsers
summary: Create a user.
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
name:
type: string
tags:
type: array
items:
type: object
properties:
tagName:
type: string
`))
})
It("handles all supported simple types", func() {
sw.Add(sashay.NewOperation(
"GET",
"/users",
"Get users",
struct {
Boolean bool `query:"pbool"`
Float32 float32 `query:"pfloat32"`
Float64 float64 `query:"pfloat64"`
Int64 int64 `query:"pint64"`
Int32 int32 `query:"pint32"`
}{},
nil,
ErrorModel{},
))
Expect(sw.BuildYAML()).To(ContainSubstring(`paths:
/users:
get:
operationId: getUsers
summary: Get users
parameters:
- name: pbool
in: query
schema:
type: boolean
- name: pfloat32
in: query
schema:
type: number
format: float
- name: pfloat64
in: query
schema:
type: number
format: double
- name: pint64
in: query
schema:
type: integer
format: int64
- name: pint32
in: query
schema:
type: integer
format: int32
`))
})
It("does not duplicate schemas", func() {
sw.Add(sashay.NewOperation(
"GET",
"/users",
"",
nil,
nil,
ErrorModel{},
))
sw.Add(sashay.NewOperation(
"GET",
"/other_users",
"",
nil,
nil,
[]ErrorModel{},
))
yaml := sw.BuildYAML()
cnt := strings.Count(yaml, "ErrorModel:")
if cnt != 1 {
Fail("Duplicate ErrorModel definitions in components:\n" + yaml)
}
})
It("creates refs for struct fields that are themselves exported structs", func() {
type Teacher struct {
FullName string `json:"fullName"`
}
type Class struct {
Subject string `json:"subject"`
Teacher Teacher `json:"teacher"`
}
type School struct {
Mascot string `json:"mascot"`
Classes []Class `json:"classes"`
}
sw.Add(sashay.NewOperation(
"GET",
"/schools",
"Get schools.",
nil,
School{},
nil,
))
Expect(sw.BuildYAML()).To(ContainSubstring(`components:
schemas:
Class:
type: object
properties:
subject:
type: string
teacher:
$ref: '#/components/schemas/Teacher'
School:
type: object
properties:
mascot:
type: string
classes:
type: array
items:
$ref: '#/components/schemas/Class'
Teacher:
type: object
properties:
fullName:
type: string
`))
})
It("does not try to use unexported struct fields", func() {
type MeTime struct {
impl int
X int `json:"x"`
}
type Moment struct {
Time MeTime `json:"time"`
}
sw.Add(sashay.NewOperation(
"GET",
"/now",
"",
nil,
Moment{},
nil,
))
Expect(sw.BuildYAML()).To(ContainSubstring(`components:
schemas:
MeTime:
type: object
properties:
x:
type: integer
format: int64
Moment:
type: object
properties:
time:
$ref: '#/components/schemas/MeTime'
`))
})
It("does not include empty parameters or properties", func() {
type Empty struct {
impl int
}
type Wrapper struct {
E Empty `json:"e"`
}
sw.Add(sashay.NewOperation(
"GET",
"/empty",
"",
struct{}{},
Wrapper{},
nil,
))
yaml := sw.BuildYAML()
Expect(yaml).To(ContainSubstring(`operationId: getEmpty
responses:
`))
Expect(yaml).To(ContainSubstring(`components:
schemas:
Empty:
type: object
Wrapper:
type: object
properties:
e:
$ref: '#/components/schemas/Empty'
`))
})
It("maps Time fields to strings data types", func() {
type Response struct {
Time time.Time `json:"time"`
}
sw.Add(sashay.NewOperation(
"POST",
"/stuff",
"Updates stuff.",
struct {
PTime time.Time `json:"ptime"`
}{},
Response{},
nil,
))
yaml := sw.BuildYAML()
Expect(yaml).To(ContainSubstring(`requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
ptime:
type: string
format: date-time
`))
Expect(yaml).To(ContainSubstring(`Response:
type: object
properties:
time:
type: string
format: date-time
`))
Expect(yaml).To(Not(ContainSubstring("/Time"))) // No $ref link
})
It("can use custom data type definitions", func() {
type Custom struct {
Field string `json:"field"`
}
type Response struct {
Custom Custom `json:"custom"`
}
sw.DefineDataType(Custom{}, sashay.SimpleDataTyper("boolean", ""))
sw.Add(sashay.NewOperation(
"POST",
"/stuff",
"Updates stuff.",
struct {
PCustom Custom `json:"pcustom"`
}{},
Response{},
nil,
))
yaml := sw.BuildYAML()
Expect(yaml).To(ContainSubstring(`requestBody:
required: true
content: