-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopenapi_test.go
More file actions
3150 lines (2798 loc) · 84.6 KB
/
openapi_test.go
File metadata and controls
3150 lines (2798 loc) · 84.6 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
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
// SPDX-License-Identifier: EUPL-1.2
package api_test
import (
"encoding/json"
"iter"
"net/http"
"testing"
"time"
"github.com/gin-gonic/gin"
api "dappco.re/go/core/api"
)
// ── Test helpers ──────────────────────────────────────────────────────────
type specStubGroup struct {
name string
basePath string
hidden bool
descs []api.RouteDescription
}
func (s *specStubGroup) Name() string { return s.name }
func (s *specStubGroup) BasePath() string { return s.basePath }
func (s *specStubGroup) RegisterRoutes(rg *gin.RouterGroup) {}
func (s *specStubGroup) Describe() []api.RouteDescription { return s.descs }
func (s *specStubGroup) Hidden() bool { return s.hidden }
type plainStubGroup struct{}
func (plainStubGroup) Name() string { return "plain" }
func (plainStubGroup) BasePath() string { return "/plain" }
func (plainStubGroup) RegisterRoutes(rg *gin.RouterGroup) {}
type iterStubGroup struct {
name string
basePath string
descs []api.RouteDescription
}
func (s *iterStubGroup) Name() string { return s.name }
func (s *iterStubGroup) BasePath() string { return s.basePath }
func (s *iterStubGroup) RegisterRoutes(rg *gin.RouterGroup) {}
func (s *iterStubGroup) Describe() []api.RouteDescription { return nil }
func (s *iterStubGroup) DescribeIter() iter.Seq[api.RouteDescription] {
return func(yield func(api.RouteDescription) bool) {
for _, rd := range s.descs {
if !yield(rd) {
return
}
}
}
}
type iterNilFallbackGroup struct {
name string
basePath string
descs []api.RouteDescription
}
func (s *iterNilFallbackGroup) Name() string { return s.name }
func (s *iterNilFallbackGroup) BasePath() string { return s.basePath }
func (s *iterNilFallbackGroup) RegisterRoutes(rg *gin.RouterGroup) {}
func (s *iterNilFallbackGroup) Describe() []api.RouteDescription { return s.descs }
func (s *iterNilFallbackGroup) DescribeIter() iter.Seq[api.RouteDescription] {
return nil
}
type countingIterGroup struct {
name string
basePath string
descs []api.RouteDescription
describeCalls int
}
func (s *countingIterGroup) Name() string { return s.name }
func (s *countingIterGroup) BasePath() string { return s.basePath }
func (s *countingIterGroup) RegisterRoutes(rg *gin.RouterGroup) {}
func (s *countingIterGroup) Describe() []api.RouteDescription { return nil }
func (s *countingIterGroup) DescribeIter() iter.Seq[api.RouteDescription] {
s.describeCalls++
return func(yield func(api.RouteDescription) bool) {
for _, rd := range s.descs {
if !yield(rd) {
return
}
}
}
}
type mutatingIterGroup struct {
name string
basePath string
descs []api.RouteDescription
}
func (s *mutatingIterGroup) Name() string { return s.name }
func (s *mutatingIterGroup) BasePath() string { return s.basePath }
func (s *mutatingIterGroup) RegisterRoutes(rg *gin.RouterGroup) {}
func (s *mutatingIterGroup) Describe() []api.RouteDescription { return nil }
func (s *mutatingIterGroup) DescribeIter() iter.Seq[api.RouteDescription] {
return func(yield func(api.RouteDescription) bool) {
for i, rd := range s.descs {
if !yield(rd) {
return
}
s.descs[i].Response["mutated"] = true
s.descs[i].RequestBody["mutated"] = true
s.descs[i].Parameters[0].Schema["mutated"] = true
s.descs[i].ResponseHeaders["X-Mutated"] = "yes"
}
}
}
type snapshottingGroup struct {
nameCalls int
basePathCalls int
descs []api.RouteDescription
}
func (s *snapshottingGroup) Name() string {
s.nameCalls++
if s.nameCalls == 1 {
return "alpha"
}
return "beta"
}
func (s *snapshottingGroup) BasePath() string {
s.basePathCalls++
if s.basePathCalls == 1 {
return "/alpha"
}
return "/beta"
}
func (s *snapshottingGroup) RegisterRoutes(rg *gin.RouterGroup) {}
func (s *snapshottingGroup) Describe() []api.RouteDescription { return s.descs }
// ── SpecBuilder tests ─────────────────────────────────────────────────────
func TestSpecBuilder_Good_EmptyGroups(t *testing.T) {
sb := &api.SpecBuilder{
Title: "Test",
Description: "Empty test",
Version: "0.0.1",
}
data, err := sb.Build(nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
var spec map[string]any
if err := json.Unmarshal(data, &spec); err != nil {
t.Fatalf("invalid JSON: %v", err)
}
// Verify OpenAPI version.
if spec["openapi"] != "3.1.0" {
t.Fatalf("expected openapi=3.1.0, got %v", spec["openapi"])
}
if spec["jsonSchemaDialect"] != "https://spec.openapis.org/oas/3.1/dialect/base" {
t.Fatalf("expected jsonSchemaDialect to use the OpenAPI 3.1 base dialect, got %v", spec["jsonSchemaDialect"])
}
// Verify /health path exists.
paths := spec["paths"].(map[string]any)
if _, ok := paths["/health"]; !ok {
t.Fatal("expected /health path in spec")
}
health := paths["/health"].(map[string]any)["get"].(map[string]any)
healthResponses := health["responses"].(map[string]any)
if _, ok := healthResponses["429"]; !ok {
t.Fatal("expected 429 response on /health")
}
if _, ok := healthResponses["504"]; !ok {
t.Fatal("expected 504 response on /health")
}
if _, ok := healthResponses["500"]; !ok {
t.Fatal("expected 500 response on /health")
}
rateLimit429 := healthResponses["429"].(map[string]any)
headers := rateLimit429["headers"].(map[string]any)
if _, ok := headers["Retry-After"]; !ok {
t.Fatal("expected Retry-After header on /health 429 response")
}
if _, ok := headers["X-Request-ID"]; !ok {
t.Fatal("expected X-Request-ID header on /health 429 response")
}
if _, ok := headers["X-RateLimit-Limit"]; !ok {
t.Fatal("expected X-RateLimit-Limit header on /health 429 response")
}
if _, ok := headers["X-RateLimit-Remaining"]; !ok {
t.Fatal("expected X-RateLimit-Remaining header on /health 429 response")
}
if _, ok := headers["X-RateLimit-Reset"]; !ok {
t.Fatal("expected X-RateLimit-Reset header on /health 429 response")
}
health504 := healthResponses["504"].(map[string]any)
health504Headers := health504["headers"].(map[string]any)
if _, ok := health504Headers["X-Request-ID"]; !ok {
t.Fatal("expected X-Request-ID header on /health 504 response")
}
if _, ok := health504Headers["X-RateLimit-Limit"]; !ok {
t.Fatal("expected X-RateLimit-Limit header on /health 504 response")
}
if _, ok := health504Headers["X-RateLimit-Remaining"]; !ok {
t.Fatal("expected X-RateLimit-Remaining header on /health 504 response")
}
if _, ok := health504Headers["X-RateLimit-Reset"]; !ok {
t.Fatal("expected X-RateLimit-Reset header on /health 504 response")
}
health200 := health["responses"].(map[string]any)["200"].(map[string]any)
health200Headers := health200["headers"].(map[string]any)
if _, ok := health200Headers["X-Cache"]; !ok {
t.Fatal("expected X-Cache header on /health 200 response")
}
// Verify system tag exists.
tags := spec["tags"].([]any)
found := false
for _, tag := range tags {
tm := tag.(map[string]any)
if tm["name"] == "system" {
found = true
break
}
}
if !found {
t.Fatal("expected system tag in spec")
}
components := spec["components"].(map[string]any)
schemas := components["schemas"].(map[string]any)
if _, ok := schemas["Response"]; !ok {
t.Fatal("expected Response component schema in spec")
}
securitySchemes := components["securitySchemes"].(map[string]any)
bearerAuth := securitySchemes["bearerAuth"].(map[string]any)
if bearerAuth["type"] != "http" {
t.Fatalf("expected bearerAuth.type=http, got %v", bearerAuth["type"])
}
if bearerAuth["scheme"] != "bearer" {
t.Fatalf("expected bearerAuth.scheme=bearer, got %v", bearerAuth["scheme"])
}
if _, ok := spec["security"]; ok {
t.Fatal("expected no global security requirement in the document")
}
if _, ok := spec["x-swagger-enabled"]; ok {
t.Fatal("expected no swagger enabled flag in the document when swagger is disabled")
}
if _, ok := spec["x-graphql-enabled"]; ok {
t.Fatal("expected no graphql enabled flag in the document when graphql is disabled")
}
}
func TestSpecBuilder_Good_NilReceiverIsZeroValueSafe(t *testing.T) {
var sb *api.SpecBuilder
data, err := sb.Build(nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
var spec map[string]any
if err := json.Unmarshal(data, &spec); err != nil {
t.Fatalf("invalid JSON: %v", err)
}
if spec["openapi"] != "3.1.0" {
t.Fatalf("expected openapi=3.1.0, got %v", spec["openapi"])
}
paths, ok := spec["paths"].(map[string]any)
if !ok {
t.Fatalf("expected paths object, got %T", spec["paths"])
}
if _, ok := paths["/health"]; !ok {
t.Fatal("expected /health path to be present")
}
}
func TestSpecBuilder_Good_CustomSecuritySchemesAreMerged(t *testing.T) {
sb := &api.SpecBuilder{
Title: "Test",
Version: "1.0.0",
SecuritySchemes: map[string]any{
"apiKeyAuth": map[string]any{
"type": "apiKey",
"in": "header",
"name": "X-API-Key",
},
},
}
data, err := sb.Build(nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
var spec map[string]any
if err := json.Unmarshal(data, &spec); err != nil {
t.Fatalf("invalid JSON: %v", err)
}
components := spec["components"].(map[string]any)
schemes := components["securitySchemes"].(map[string]any)
bearerAuth, ok := schemes["bearerAuth"].(map[string]any)
if !ok {
t.Fatal("expected default bearerAuth security scheme to remain present")
}
if bearerAuth["scheme"] != "bearer" {
t.Fatalf("expected bearerAuth scheme to stay bearer, got %v", bearerAuth["scheme"])
}
apiKeyAuth, ok := schemes["apiKeyAuth"].(map[string]any)
if !ok {
t.Fatal("expected custom apiKeyAuth security scheme to be merged")
}
if apiKeyAuth["type"] != "apiKey" {
t.Fatalf("expected apiKeyAuth.type=apiKey, got %v", apiKeyAuth["type"])
}
if apiKeyAuth["in"] != "header" {
t.Fatalf("expected apiKeyAuth.in=header, got %v", apiKeyAuth["in"])
}
if apiKeyAuth["name"] != "X-API-Key" {
t.Fatalf("expected apiKeyAuth.name=X-API-Key, got %v", apiKeyAuth["name"])
}
}
func TestSpecBuilder_Good_CommonResponseComponentsArePublished(t *testing.T) {
sb := &api.SpecBuilder{
Title: "Test",
Version: "1.0.0",
}
data, err := sb.Build(nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
var spec map[string]any
if err := json.Unmarshal(data, &spec); err != nil {
t.Fatalf("invalid JSON: %v", err)
}
components := spec["components"].(map[string]any)
responses := components["responses"].(map[string]any)
for _, name := range []string{
"BadRequest",
"Unauthorized",
"Forbidden",
"RateLimitExceeded",
"GatewayTimeout",
"InternalServerError",
"Gone",
} {
if _, ok := responses[name]; !ok {
t.Fatalf("expected %s response component in spec", name)
}
}
}
func TestSpecBuilder_Good_NormalisesMetadataAtBuild(t *testing.T) {
sb := &api.SpecBuilder{
Title: " Test API ",
Summary: " ",
Description: " Trimmed description ",
Version: " 1.2.3 ",
TermsOfService: " https://example.com/terms ",
ContactName: " API Support ",
ContactURL: " https://example.com/support ",
ContactEmail: " support@example.com ",
LicenseName: " EUPL-1.2 ",
LicenseURL: " https://eupl.eu/1.2/en/ ",
ExternalDocsURL: " https://example.com/docs ",
ExternalDocsDescription: " Developer guide ",
SwaggerPath: " /docs/ ",
}
data, err := sb.Build(nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
var spec map[string]any
if err := json.Unmarshal(data, &spec); err != nil {
t.Fatalf("invalid JSON: %v", err)
}
info := spec["info"].(map[string]any)
if info["title"] != "Test API" {
t.Fatalf("expected trimmed title, got %v", info["title"])
}
if _, ok := info["summary"]; ok {
t.Fatal("expected blank summary to be omitted")
}
if info["description"] != "Trimmed description" {
t.Fatalf("expected trimmed description, got %v", info["description"])
}
if info["version"] != "1.2.3" {
t.Fatalf("expected trimmed version, got %v", info["version"])
}
if info["termsOfService"] != "https://example.com/terms" {
t.Fatalf("expected trimmed termsOfService, got %v", info["termsOfService"])
}
contact := info["contact"].(map[string]any)
if contact["name"] != "API Support" {
t.Fatalf("expected trimmed contact name, got %v", contact["name"])
}
if contact["url"] != "https://example.com/support" {
t.Fatalf("expected trimmed contact url, got %v", contact["url"])
}
if contact["email"] != "support@example.com" {
t.Fatalf("expected trimmed contact email, got %v", contact["email"])
}
license := info["license"].(map[string]any)
if license["name"] != "EUPL-1.2" {
t.Fatalf("expected trimmed licence name, got %v", license["name"])
}
if license["url"] != "https://eupl.eu/1.2/en/" {
t.Fatalf("expected trimmed licence url, got %v", license["url"])
}
externalDocs := spec["externalDocs"].(map[string]any)
if externalDocs["description"] != "Developer guide" {
t.Fatalf("expected trimmed external docs description, got %v", externalDocs["description"])
}
if externalDocs["url"] != "https://example.com/docs" {
t.Fatalf("expected trimmed external docs url, got %v", externalDocs["url"])
}
if got := spec["x-swagger-ui-path"]; got != "/docs" {
t.Fatalf("expected trimmed swagger path, got %v", got)
}
}
func TestSpecBuilder_Good_SwaggerUIPathExtension(t *testing.T) {
sb := &api.SpecBuilder{
Title: "Test",
Description: "Swagger path test",
Version: "1.0.0",
SwaggerPath: "/docs/",
}
data, err := sb.Build(nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
var spec map[string]any
if err := json.Unmarshal(data, &spec); err != nil {
t.Fatalf("invalid JSON: %v", err)
}
if got := spec["x-swagger-ui-path"]; got != "/docs" {
t.Fatalf("expected x-swagger-ui-path=/docs, got %v", got)
}
}
func TestSpecBuilder_Good_CacheAndI18nExtensions(t *testing.T) {
sb := &api.SpecBuilder{
Title: "Test",
Description: "Runtime config test",
Version: "1.0.0",
CacheEnabled: true,
CacheTTL: (5 * time.Minute).String(),
CacheMaxEntries: 42,
CacheMaxBytes: 8192,
I18nDefaultLocale: "en-GB",
I18nSupportedLocales: []string{"en-GB", "fr"},
}
data, err := sb.Build(nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
var spec map[string]any
if err := json.Unmarshal(data, &spec); err != nil {
t.Fatalf("invalid JSON: %v", err)
}
if got := spec["x-cache-enabled"]; got != true {
t.Fatalf("expected x-cache-enabled=true, got %v", got)
}
if got := spec["x-cache-ttl"]; got != "5m0s" {
t.Fatalf("expected x-cache-ttl=5m0s, got %v", got)
}
if got := spec["x-cache-max-entries"]; got != float64(42) {
t.Fatalf("expected x-cache-max-entries=42, got %v", got)
}
if got := spec["x-cache-max-bytes"]; got != float64(8192) {
t.Fatalf("expected x-cache-max-bytes=8192, got %v", got)
}
if got := spec["x-i18n-default-locale"]; got != "en-GB" {
t.Fatalf("expected x-i18n-default-locale=en-GB, got %v", got)
}
locales, ok := spec["x-i18n-supported-locales"].([]any)
if !ok {
t.Fatalf("expected x-i18n-supported-locales array, got %T", spec["x-i18n-supported-locales"])
}
if len(locales) != 2 || locales[0] != "en-GB" || locales[1] != "fr" {
t.Fatalf("expected supported locales [en-GB fr], got %v", locales)
}
}
func TestSpecBuilder_Good_OmitsNonPositiveCacheTTLExtension(t *testing.T) {
sb := &api.SpecBuilder{
Title: "Test",
Description: "Cache TTL test",
Version: "1.0.0",
CacheTTL: "0s",
}
data, err := sb.Build(nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
var spec map[string]any
if err := json.Unmarshal(data, &spec); err != nil {
t.Fatalf("invalid JSON: %v", err)
}
if _, ok := spec["x-cache-ttl"]; ok {
t.Fatal("expected non-positive cache TTL to be omitted from spec")
}
}
func TestSpecBuilder_Good_GraphQLEndpoint(t *testing.T) {
sb := &api.SpecBuilder{
Title: "Test",
Description: "GraphQL test",
Version: "1.0.0",
GraphQLPath: "/graphql",
}
data, err := sb.Build(nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
var spec map[string]any
if err := json.Unmarshal(data, &spec); err != nil {
t.Fatalf("invalid JSON: %v", err)
}
tags := spec["tags"].([]any)
found := false
for _, tag := range tags {
tm := tag.(map[string]any)
if tm["name"] == "graphql" {
found = true
break
}
}
if !found {
t.Fatal("expected graphql tag in spec")
}
if _, ok := spec["x-graphql-playground"]; ok {
t.Fatal("expected x-graphql-playground to be omitted when playground is disabled")
}
paths := spec["paths"].(map[string]any)
pathItem, ok := paths["/graphql"].(map[string]any)
if !ok {
t.Fatal("expected /graphql path in spec")
}
getOp := pathItem["get"].(map[string]any)
if getOp["operationId"] != "get_graphql" {
t.Fatalf("expected GraphQL GET operationId to be get_graphql, got %v", getOp["operationId"])
}
getParams := getOp["parameters"].([]any)
if len(getParams) != 3 {
t.Fatalf("expected 3 GraphQL GET query parameters, got %d", len(getParams))
}
if getParams[0].(map[string]any)["name"] != "query" {
t.Fatalf("expected first GraphQL GET parameter to be query, got %v", getParams[0])
}
if getParams[0].(map[string]any)["required"] != true {
t.Fatal("expected GraphQL GET query parameter to be required")
}
postOp := pathItem["post"].(map[string]any)
if postOp["operationId"] != "post_graphql" {
t.Fatalf("expected GraphQL operationId to be post_graphql, got %v", postOp["operationId"])
}
responses := postOp["responses"].(map[string]any)
successHeaders := responses["200"].(map[string]any)["headers"].(map[string]any)
if _, ok := successHeaders["X-Cache"]; !ok {
t.Fatal("expected X-Cache header on GraphQL 200 response")
}
requestBody := postOp["requestBody"].(map[string]any)
schema := requestBody["content"].(map[string]any)["application/json"].(map[string]any)["schema"].(map[string]any)
properties := schema["properties"].(map[string]any)
if _, ok := properties["query"]; !ok {
t.Fatal("expected GraphQL request schema to include query field")
}
if _, ok := properties["variables"]; !ok {
t.Fatal("expected GraphQL request schema to include variables field")
}
if _, ok := properties["operationName"]; !ok {
t.Fatal("expected GraphQL request schema to include operationName field")
}
}
func TestSpecBuilder_Good_GraphQLPlaygroundEndpoint(t *testing.T) {
sb := &api.SpecBuilder{
Title: "Test",
Version: "1.0.0",
GraphQLPath: "/graphql",
GraphQLPlayground: true,
GraphQLPlaygroundPath: "/graphql/playground",
}
data, err := sb.Build(nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
var spec map[string]any
if err := json.Unmarshal(data, &spec); err != nil {
t.Fatalf("invalid JSON: %v", err)
}
paths := spec["paths"].(map[string]any)
pathItem, ok := paths["/graphql/playground"].(map[string]any)
if !ok {
t.Fatal("expected /graphql/playground path in spec")
}
getOp := pathItem["get"].(map[string]any)
if getOp["operationId"] != "get_graphql_playground" {
t.Fatalf("expected playground operationId to be get_graphql_playground, got %v", getOp["operationId"])
}
if got := spec["x-graphql-playground-path"]; got != "/graphql/playground" {
t.Fatalf("expected x-graphql-playground-path=/graphql/playground, got %v", got)
}
responses := getOp["responses"].(map[string]any)
success := responses["200"].(map[string]any)
content := success["content"].(map[string]any)
if _, ok := content["text/html"]; !ok {
t.Fatal("expected text/html content type for GraphQL playground response")
}
}
func TestSpecBuilder_Good_GraphQLPlaygroundDefaultsToGraphQLPath(t *testing.T) {
sb := &api.SpecBuilder{
Title: "Test",
Version: "1.0.0",
GraphQLPlayground: true,
}
data, err := sb.Build(nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
var spec map[string]any
if err := json.Unmarshal(data, &spec); err != nil {
t.Fatalf("invalid JSON: %v", err)
}
paths := spec["paths"].(map[string]any)
if _, ok := paths["/graphql"].(map[string]any); !ok {
t.Fatal("expected default /graphql path when playground is enabled")
}
if _, ok := paths["/graphql/playground"].(map[string]any); !ok {
t.Fatal("expected default /graphql/playground path when playground is enabled")
}
}
func TestSpecBuilder_Good_GraphQLPlaygroundDefaultsToGraphQLTag(t *testing.T) {
sb := &api.SpecBuilder{
Title: "Test",
Version: "1.0.0",
GraphQLPlayground: true,
}
data, err := sb.Build(nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
var spec map[string]any
if err := json.Unmarshal(data, &spec); err != nil {
t.Fatalf("invalid JSON: %v", err)
}
tags := spec["tags"].([]any)
found := false
for _, tag := range tags {
tm := tag.(map[string]any)
if tm["name"] == "graphql" {
found = true
break
}
}
if !found {
t.Fatal("expected graphql tag when playground enables the default GraphQL path")
}
}
func TestSpecBuilder_Good_EnabledTransportsUseDefaultPaths(t *testing.T) {
sb := &api.SpecBuilder{
Title: "Test",
Version: "1.0.0",
SwaggerEnabled: true,
GraphQLEnabled: true,
WSEnabled: true,
SSEEnabled: true,
}
data, err := sb.Build(nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
var spec map[string]any
if err := json.Unmarshal(data, &spec); err != nil {
t.Fatalf("invalid JSON: %v", err)
}
if got := spec["x-swagger-ui-path"]; got != "/swagger" {
t.Fatalf("expected default swagger path, got %v", got)
}
if got := spec["x-graphql-path"]; got != "/graphql" {
t.Fatalf("expected default graphql path, got %v", got)
}
if got := spec["x-ws-path"]; got != "/ws" {
t.Fatalf("expected default websocket path, got %v", got)
}
if got := spec["x-sse-path"]; got != "/events" {
t.Fatalf("expected default sse path, got %v", got)
}
paths := spec["paths"].(map[string]any)
for _, path := range []string{"/graphql", "/ws", "/events"} {
if _, ok := paths[path].(map[string]any); !ok {
t.Fatalf("expected %s path in spec", path)
}
}
tags := spec["tags"].([]any)
foundGraphQL := false
foundEvents := false
for _, tag := range tags {
tm := tag.(map[string]any)
switch tm["name"] {
case "graphql":
foundGraphQL = true
case "events":
foundEvents = true
}
}
if !foundGraphQL {
t.Fatal("expected graphql tag when GraphQL is enabled")
}
if !foundEvents {
t.Fatal("expected events tag when SSE is enabled")
}
}
func TestSpecBuilder_Good_WebSocketEndpoint(t *testing.T) {
sb := &api.SpecBuilder{
Title: "Test",
Version: "1.0.0",
WSPath: "/ws",
}
data, err := sb.Build(nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
var spec map[string]any
if err := json.Unmarshal(data, &spec); err != nil {
t.Fatalf("invalid JSON: %v", err)
}
tags := spec["tags"].([]any)
found := false
for _, tag := range tags {
tm := tag.(map[string]any)
if tm["name"] == "system" {
found = true
break
}
}
if !found {
t.Fatal("expected system tag in spec")
}
paths := spec["paths"].(map[string]any)
pathItem, ok := paths["/ws"].(map[string]any)
if !ok {
t.Fatal("expected /ws path in spec")
}
getOp := pathItem["get"].(map[string]any)
if getOp["operationId"] != "get_ws" {
t.Fatalf("expected WebSocket operationId to be get_ws, got %v", getOp["operationId"])
}
if getOp["summary"] != "WebSocket connection" {
t.Fatalf("expected WebSocket summary, got %v", getOp["summary"])
}
responses := getOp["responses"].(map[string]any)
if _, ok := responses["101"]; !ok {
t.Fatal("expected 101 response on /ws")
}
if _, ok := responses["429"]; !ok {
t.Fatal("expected 429 response on /ws")
}
}
func TestSpecBuilder_Good_ServerSentEventsEndpoint(t *testing.T) {
sb := &api.SpecBuilder{
Title: "Test",
Version: "1.0.0",
SSEPath: "/events",
}
data, err := sb.Build(nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
var spec map[string]any
if err := json.Unmarshal(data, &spec); err != nil {
t.Fatalf("invalid JSON: %v", err)
}
tags := spec["tags"].([]any)
found := false
for _, tag := range tags {
tm := tag.(map[string]any)
if tm["name"] == "events" {
found = true
break
}
}
if !found {
t.Fatal("expected events tag in spec")
}
paths := spec["paths"].(map[string]any)
pathItem, ok := paths["/events"].(map[string]any)
if !ok {
t.Fatal("expected /events path in spec")
}
getOp := pathItem["get"].(map[string]any)
if getOp["operationId"] != "get_events" {
t.Fatalf("expected SSE operationId to be get_events, got %v", getOp["operationId"])
}
params := getOp["parameters"].([]any)
if len(params) != 1 {
t.Fatalf("expected one SSE query parameter, got %d", len(params))
}
param := params[0].(map[string]any)
if param["name"] != "channel" || param["in"] != "query" {
t.Fatalf("expected channel query parameter, got %+v", param)
}
responses := getOp["responses"].(map[string]any)
success := responses["200"].(map[string]any)
content := success["content"].(map[string]any)
if _, ok := content["text/event-stream"]; !ok {
t.Fatal("expected text/event-stream content type for SSE response")
}
headers := success["headers"].(map[string]any)
for _, name := range []string{"Cache-Control", "Connection", "X-Accel-Buffering"} {
if _, ok := headers[name]; !ok {
t.Fatalf("expected %s header in SSE response", name)
}
}
}
func TestSpecBuilder_Good_InfoIncludesLicenseMetadata(t *testing.T) {
sb := &api.SpecBuilder{
Title: "Test",
Description: "Licensed test API",
Version: "1.2.3",
LicenseName: "EUPL-1.2",
LicenseURL: "https://eupl.eu/1.2/en/",
}
data, err := sb.Build(nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
var spec map[string]any
if err := json.Unmarshal(data, &spec); err != nil {
t.Fatalf("invalid JSON: %v", err)
}
info := spec["info"].(map[string]any)
license, ok := info["license"].(map[string]any)
if !ok {
t.Fatal("expected license metadata in spec info")
}
if license["name"] != "EUPL-1.2" {
t.Fatalf("expected license name EUPL-1.2, got %v", license["name"])
}
if license["url"] != "https://eupl.eu/1.2/en/" {
t.Fatalf("expected license url to be preserved, got %v", license["url"])
}
}
func TestSpecBuilder_Good_InfoIncludesSummary(t *testing.T) {
sb := &api.SpecBuilder{
Title: "Test",
Summary: "Concise API overview",
Description: "Summary test API",
Version: "1.2.3",
}
data, err := sb.Build(nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
var spec map[string]any
if err := json.Unmarshal(data, &spec); err != nil {
t.Fatalf("invalid JSON: %v", err)
}
info := spec["info"].(map[string]any)
if info["summary"] != "Concise API overview" {
t.Fatalf("expected summary to be preserved, got %v", info["summary"])
}
}
func TestSpecBuilder_Good_InfoIncludesContactMetadata(t *testing.T) {
sb := &api.SpecBuilder{
Title: "Test",
Description: "Contact test API",
Version: "1.2.3",
ContactName: "API Support",
ContactURL: "https://example.com/support",
ContactEmail: "support@example.com",
}
data, err := sb.Build(nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
var spec map[string]any
if err := json.Unmarshal(data, &spec); err != nil {
t.Fatalf("invalid JSON: %v", err)
}
info := spec["info"].(map[string]any)
contact, ok := info["contact"].(map[string]any)
if !ok {
t.Fatal("expected contact metadata in spec info")
}
if contact["name"] != "API Support" {
t.Fatalf("expected contact name API Support, got %v", contact["name"])
}
if contact["url"] != "https://example.com/support" {
t.Fatalf("expected contact url to be preserved, got %v", contact["url"])
}
if contact["email"] != "support@example.com" {
t.Fatalf("expected contact email to be preserved, got %v", contact["email"])
}
}
func TestSpecBuilder_Good_InfoIncludesTermsOfService(t *testing.T) {
sb := &api.SpecBuilder{
Title: "Test",
Description: "Terms test API",
Version: "1.2.3",
TermsOfService: "https://example.com/terms",
}
data, err := sb.Build(nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
var spec map[string]any
if err := json.Unmarshal(data, &spec); err != nil {
t.Fatalf("invalid JSON: %v", err)
}
info := spec["info"].(map[string]any)