-
-
Notifications
You must be signed in to change notification settings - Fork 64
/
document_test.go
1457 lines (1200 loc) · 42.1 KB
/
document_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
// Copyright 2022 Princess B33f Heavy Industries / Dave Shanley
// SPDX-License-Identifier: MIT
package libopenapi
import (
"bytes"
"fmt"
"log/slog"
"net/http"
"net/url"
"os"
"runtime"
"strconv"
"strings"
"testing"
"time"
"github.com/pb33f/libopenapi/datamodel"
"github.com/pb33f/libopenapi/datamodel/high/base"
v3high "github.com/pb33f/libopenapi/datamodel/high/v3"
"github.com/pb33f/libopenapi/orderedmap"
"github.com/pb33f/libopenapi/utils"
"github.com/pb33f/libopenapi/what-changed/model"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestLoadDocument_Simple_V2(t *testing.T) {
yml := `swagger: 2.0.1`
doc, err := NewDocument([]byte(yml))
assert.NoError(t, err)
assert.Equal(t, "2.0.1", doc.GetVersion())
v2Doc, docErr := doc.BuildV2Model()
assert.Len(t, docErr, 0)
assert.NotNil(t, v2Doc)
assert.NotNil(t, doc.GetSpecInfo())
fmt.Print()
}
func TestLoadDocument_Simple_V2_Error(t *testing.T) {
yml := `swagger: 2.0`
doc, err := NewDocument([]byte(yml))
assert.NoError(t, err)
v2Doc, docErr := doc.BuildV3Model()
assert.Len(t, docErr, 1)
assert.Nil(t, v2Doc)
}
func TestLoadDocument_Simple_V2_Error_BadSpec(t *testing.T) {
yml := `swagger: 2.0
definitions:
thing:
$ref: bork`
doc, err := NewDocument([]byte(yml))
assert.NoError(t, err)
v2Doc, docErr := doc.BuildV2Model()
assert.Len(t, docErr, 3)
assert.Nil(t, v2Doc)
}
func TestLoadDocument_WrongDoc(t *testing.T) {
yml := `IAmNotAnOpenAPI: 3.1.0`
doc, err := NewDocument([]byte(yml))
assert.Error(t, err)
assert.Nil(t, doc)
}
func TestLoadDocument_Simple_V3_Error(t *testing.T) {
yml := `openapi: 3.0.1`
doc, err := NewDocument([]byte(yml))
assert.NoError(t, err)
v2Doc, docErr := doc.BuildV2Model()
assert.Len(t, docErr, 1)
assert.Nil(t, v2Doc)
}
func TestLoadDocument_Error_V2NoSpec(t *testing.T) {
doc := new(document) // not how this should be instantiated.
_, err := doc.BuildV2Model()
assert.Len(t, err, 1)
}
func TestLoadDocument_Error_V3NoSpec(t *testing.T) {
doc := new(document) // not how this should be instantiated.
_, err := doc.BuildV3Model()
assert.Len(t, err, 1)
}
func TestLoadDocument_Empty(t *testing.T) {
yml := ``
_, err := NewDocument([]byte(yml))
assert.Error(t, err)
}
func TestLoadDocument_Simple_V3(t *testing.T) {
yml := `openapi: 3.0.1`
doc, err := NewDocument([]byte(yml))
assert.NoError(t, err)
assert.Equal(t, "3.0.1", doc.GetVersion())
v3Doc, docErr := doc.BuildV3Model()
assert.Len(t, docErr, 0)
assert.NotNil(t, v3Doc)
}
func TestLoadDocument_Simple_V3_Error_BadSpec_BuildModel(t *testing.T) {
yml := `openapi: 3.0
paths:
"/some":
$ref: bork`
doc, err := NewDocument([]byte(yml))
assert.NoError(t, err)
doc.BuildV3Model()
rolo := doc.GetRolodex()
assert.Len(t, rolo.GetCaughtErrors(), 1)
}
func TestDocument_Serialize_Error(t *testing.T) {
doc := new(document) // not how this should be instantiated.
_, err := doc.Serialize()
assert.Error(t, err)
}
func TestDocument_Serialize(t *testing.T) {
yml := `openapi: 3.0
info:
title: The magic API
`
doc, _ := NewDocument([]byte(yml))
serial, err := doc.Serialize()
assert.NoError(t, err)
assert.Equal(t, yml, string(serial))
}
func TestDocument_Serialize_Modified(t *testing.T) {
yml := `openapi: 3.0
info:
title: The magic API
`
ymlModified := `openapi: 3.0
info:
title: The magic API - but now, altered!
`
doc, _ := NewDocument([]byte(yml))
v3Doc, _ := doc.BuildV3Model()
v3Doc.Model.Info.GoLow().Title.Mutate("The magic API - but now, altered!")
serial, err := doc.Serialize()
assert.NoError(t, err)
assert.Equal(t, ymlModified, string(serial))
}
func TestDocument_RoundTrip_JSON(t *testing.T) {
bs, _ := os.ReadFile("test_specs/roundtrip.json")
doc, err := NewDocument(bs)
require.NoError(t, err)
m, errs := doc.BuildV3Model()
require.Empty(t, errs)
out, _ := m.Model.RenderJSON(" ")
// windows has to be different, it does not add carriage returns.
if runtime.GOOS != "windows" {
assert.Equal(t, string(bs), string(out))
}
}
func TestDocument_RoundTrip_YAML(t *testing.T) {
bs, _ := os.ReadFile("test_specs/roundtrip.yaml")
doc, err := NewDocument(bs)
require.NoError(t, err)
_, errs := doc.BuildV3Model()
require.Empty(t, errs)
out, err := doc.Render()
require.NoError(t, err)
if runtime.GOOS != "windows" {
assert.Equal(t, string(bs), string(out))
}
}
func TestDocument_RoundTrip_YAML_To_JSON(t *testing.T) {
y, _ := os.ReadFile("test_specs/roundtrip.yaml")
j, _ := os.ReadFile("test_specs/roundtrip.json")
doc, err := NewDocument(y)
require.NoError(t, err)
m, errs := doc.BuildV3Model()
require.Empty(t, errs)
out, _ := m.Model.RenderJSON(" ")
require.NoError(t, err)
if runtime.GOOS != "windows" {
assert.Equal(t, string(j), string(out))
}
}
func TestDocument_RenderAndReload_ChangeCheck_Burgershop(t *testing.T) {
bs, _ := os.ReadFile("test_specs/burgershop.openapi.yaml")
doc, _ := NewDocument(bs)
doc.BuildV3Model()
rend, newDoc, _, _ := doc.RenderAndReload()
// compare documents
compReport, errs := CompareDocuments(doc, newDoc)
// should not be nil.
assert.Nil(t, errs)
assert.Nil(t, errs)
assert.NotNil(t, rend)
assert.Nil(t, compReport)
}
func TestDocument_RenderAndReload_ChangeCheck_Stripe(t *testing.T) {
bs, _ := os.ReadFile("test_specs/stripe.yaml")
doc, _ := NewDocument(bs)
doc.BuildV3Model()
_, newDoc, _, _ := doc.RenderAndReload()
// compare documents
compReport, errs := CompareDocuments(doc, newDoc)
// get flat list of changes.
flatChanges := compReport.GetAllChanges()
// remove everything that is a description change (stripe has a lot of those from having 519 empty descriptions)
var filtered []*model.Change
for i := range flatChanges {
if flatChanges[i].Property != "description" {
filtered = append(filtered, flatChanges[i])
}
}
assert.Nil(t, errs)
tc := compReport.TotalChanges()
bc := compReport.TotalBreakingChanges()
assert.Equal(t, 0, bc)
assert.Equal(t, 819, tc)
// there should be no other changes than the 519 descriptions.
assert.Equal(t, 0, len(filtered))
}
func TestDocument_ResolveStripe(t *testing.T) {
bs, _ := os.ReadFile("test_specs/stripe.yaml")
docConfig := datamodel.NewDocumentConfiguration()
docConfig.SkipCircularReferenceCheck = true
docConfig.BasePath = "."
docConfig.AllowRemoteReferences = true
docConfig.AllowFileReferences = true
doc, _ := NewDocumentWithConfiguration(bs, docConfig)
model, _ := doc.BuildV3Model()
rolo := model.Index.GetRolodex()
rolo.Resolve()
assert.Equal(t, 1, len(model.Index.GetRolodex().GetCaughtErrors()))
}
func TestDocument_RenderAndReload_ChangeCheck_Asana(t *testing.T) {
bs, _ := os.ReadFile("test_specs/asana.yaml")
doc, _ := NewDocument(bs)
doc.BuildV3Model()
dat, newDoc, _, _ := doc.RenderAndReload()
assert.NotNil(t, dat)
if runtime.GOOS != "windows" {
assert.Equal(t, string(bs), string(dat))
}
// compare documents
compReport, errs := CompareDocuments(doc, newDoc)
// get flat list of changes.
flatChanges := compReport.GetAllChanges()
assert.Nil(t, errs)
tc := compReport.TotalChanges()
assert.Equal(t, 0, tc)
// there are some properties re-rendered that trigger changes.
assert.Equal(t, 0, len(flatChanges))
}
func TestDocument_RenderAndReload(t *testing.T) {
// load an OpenAPI 3 specification from bytes
petstore, _ := os.ReadFile("test_specs/petstorev3.json")
// create a new document from specification bytes
doc, err := NewDocument(petstore)
// if anything went wrong, an error is thrown
if err != nil {
panic(fmt.Sprintf("cannot create new document: %e", err))
}
// because we know this is a v3 spec, we can build a ready to go model from it.
m, _ := doc.BuildV3Model()
// mutate the model
h := m.Model
h.Paths.PathItems.GetOrZero("/pet/findByStatus").Get.OperationId = "findACakeInABakery"
h.Paths.PathItems.GetOrZero("/pet/findByStatus").Get.Responses.Codes.GetOrZero("400").Description = "a nice bucket of mice"
h.Paths.PathItems.GetOrZero("/pet/findByTags").Get.Tags = append(h.Paths.PathItems.GetOrZero("/pet/findByTags").Get.Tags, "gurgle", "giggle")
h.Paths.PathItems.GetOrZero("/pet/{petId}").Delete.Security = append(h.Paths.PathItems.GetOrZero("/pet/{petId}").Delete.Security,
&base.SecurityRequirement{Requirements: orderedmap.ToOrderedMap(map[string][]string{
"pizza-and-cake": {"read:abook", "write:asong"},
})},
)
h.Components.Schemas.GetOrZero("Order").Schema().Properties.GetOrZero("status").Schema().Example = utils.CreateStringNode("I am a teapot, filled with love.")
h.Components.SecuritySchemes.GetOrZero("petstore_auth").Flows.Implicit.AuthorizationUrl = "https://pb33f.io"
bytes, _, newDocModel, e := doc.RenderAndReload()
assert.Nil(t, e)
assert.NotNil(t, bytes)
h = newDocModel.Model
assert.Equal(t, "findACakeInABakery", h.Paths.PathItems.GetOrZero("/pet/findByStatus").Get.OperationId)
assert.Equal(t, "a nice bucket of mice",
h.Paths.PathItems.GetOrZero("/pet/findByStatus").Get.Responses.Codes.GetOrZero("400").Description)
assert.Len(t, h.Paths.PathItems.GetOrZero("/pet/findByTags").Get.Tags, 3)
assert.Len(t, h.Paths.PathItems.GetOrZero("/pet/findByTags").Get.Tags, 3)
yu := h.Paths.PathItems.GetOrZero("/pet/{petId}").Delete.Security
assert.Equal(t, "read:abook", yu[len(yu)-1].Requirements.GetOrZero("pizza-and-cake")[0])
var example string
_ = h.Components.Schemas.GetOrZero("Order").Schema().Properties.GetOrZero("status").Schema().Example.Decode(&example)
assert.Equal(t, "I am a teapot, filled with love.", example)
assert.Equal(t, "https://pb33f.io",
h.Components.SecuritySchemes.GetOrZero("petstore_auth").Flows.Implicit.AuthorizationUrl)
}
func TestDocument_RenderAndReload_WithErrors(t *testing.T) {
// load an OpenAPI 3 specification from bytes
petstore, _ := os.ReadFile("test_specs/petstorev3.json")
// create a new document from specification bytes
doc, err := NewDocument(petstore)
// if anything went wrong, an error is thrown
if err != nil {
panic(fmt.Sprintf("cannot create new document: %e", err))
}
// because we know this is a v3 spec, we can build a ready to go model from it.
m, _ := doc.BuildV3Model()
// Remove a schema to make the model invalid
_, present := m.Model.Components.Schemas.Delete("Pet")
assert.True(t, present, "expected schema Pet to exist")
_, _, _, errors := doc.RenderAndReload()
assert.Len(t, errors, 2)
assert.Equal(t, errors[0].Error(), "component `#/components/schemas/Pet` does not exist in the specification")
}
func TestDocument_Render(t *testing.T) {
// load an OpenAPI 3 specification from bytes
petstore, _ := os.ReadFile("test_specs/petstorev3.json")
// create a new document from specification bytes
doc, err := NewDocument(petstore)
// if anything went wrong, an error is thrown
if err != nil {
panic(fmt.Sprintf("cannot create new document: %e", err))
}
// because we know this is a v3 spec, we can build a ready to go model from it.
m, _ := doc.BuildV3Model()
// mutate the model
h := m.Model
h.Paths.PathItems.GetOrZero("/pet/findByStatus").Get.OperationId = "findACakeInABakery"
h.Paths.PathItems.GetOrZero("/pet/findByStatus").
Get.Responses.Codes.GetOrZero("400").Description = "a nice bucket of mice"
h.Paths.PathItems.GetOrZero("/pet/findByTags").Get.Tags = append(h.Paths.PathItems.GetOrZero("/pet/findByTags").Get.Tags, "gurgle", "giggle")
h.Paths.PathItems.GetOrZero("/pet/{petId}").Delete.Security = append(h.Paths.PathItems.GetOrZero("/pet/{petId}").Delete.Security,
&base.SecurityRequirement{Requirements: orderedmap.ToOrderedMap(map[string][]string{
"pizza-and-cake": {"read:abook", "write:asong"},
})},
)
h.Components.Schemas.GetOrZero("Order").Schema().Properties.GetOrZero("status").Schema().Example = utils.CreateStringNode("I am a teapot, filled with love.")
h.Components.SecuritySchemes.GetOrZero("petstore_auth").Flows.Implicit.AuthorizationUrl = "https://pb33f.io"
bytes, e := doc.Render()
assert.NoError(t, e)
assert.NotNil(t, bytes)
newDoc, docErr := NewDocument(bytes)
assert.NoError(t, docErr)
newDocModel, docErrs := newDoc.BuildV3Model()
assert.Len(t, docErrs, 0)
h = newDocModel.Model
assert.Equal(t, "findACakeInABakery", h.Paths.PathItems.GetOrZero("/pet/findByStatus").Get.OperationId)
assert.Equal(t, "a nice bucket of mice",
h.Paths.PathItems.GetOrZero("/pet/findByStatus").Get.Responses.Codes.GetOrZero("400").Description)
assert.Len(t, h.Paths.PathItems.GetOrZero("/pet/findByTags").Get.Tags, 3)
assert.Len(t, h.Paths.PathItems.GetOrZero("/pet/findByTags").Get.Tags, 3)
yu := h.Paths.PathItems.GetOrZero("/pet/{petId}").Delete.Security
assert.Equal(t, "read:abook", yu[len(yu)-1].Requirements.GetOrZero("pizza-and-cake")[0])
var example string
_ = h.Components.Schemas.GetOrZero("Order").Schema().Properties.GetOrZero("status").Schema().Example.Decode(&example)
assert.Equal(t, "I am a teapot, filled with love.", example)
assert.Equal(t, "https://pb33f.io",
h.Components.SecuritySchemes.GetOrZero("petstore_auth").Flows.Implicit.AuthorizationUrl)
}
func TestDocument_Render_Missing_Model_Error(t *testing.T) {
// load an OpenAPI 3 specification from bytes
petstore, _ := os.ReadFile("test_specs/petstorev3.json")
// create a new document from specification bytes
doc, err := NewDocument(petstore)
assert.NoError(t, err)
// instead of building the model, we will render the doc immediately - therefore no underlying v3 model exists on render
_, e := doc.Render()
assert.Error(t, e)
assert.Equal(t, "unable to render, no openapi model has been built for the document", e.Error())
}
func TestDocument_Render_Missing_Info_Error(t *testing.T) {
doc := &document{
// set the highOpenAPI3Model to a non-nil model to mock an existing model
highOpenAPI3Model: &DocumentModel[v3high.Document]{},
// do not set the info property
info: nil,
}
_, e := doc.Render()
assert.Error(t, e)
assert.Equal(t, "unable to render, no specification has been loaded", e.Error())
}
func TestDocument_RenderWithLargeIndention(t *testing.T) {
json := `{
"openapi": "3.0"
}`
doc, _ := NewDocument([]byte(json))
doc.BuildV3Model()
bytes, _ := doc.Render()
assert.Equal(t, json, string(bytes))
}
func TestDocument_Render_ChangeCheck_Burgershop(t *testing.T) {
bs, _ := os.ReadFile("test_specs/burgershop.openapi.yaml")
doc, _ := NewDocument(bs)
doc.BuildV3Model()
rend, _ := doc.Render()
newDoc, _ := NewDocument(rend)
// compare documents
compReport, errs := CompareDocuments(doc, newDoc)
// should not be nil.
assert.Nil(t, errs)
assert.NotNil(t, rend)
assert.Nil(t, compReport)
}
func TestDocument_RenderAndReload_Swagger(t *testing.T) {
petstore, _ := os.ReadFile("test_specs/petstorev2.json")
doc, _ := NewDocument(petstore)
doc.BuildV2Model()
doc.BuildV2Model()
_, _, _, e := doc.RenderAndReload()
assert.Len(t, e, 1)
assert.Equal(t, "this method only supports OpenAPI 3 documents, not Swagger", e[0].Error())
}
func TestDocument_Render_Swagger(t *testing.T) {
petstore, _ := os.ReadFile("test_specs/petstorev2.json")
doc, _ := NewDocument(petstore)
doc.BuildV2Model()
doc.BuildV2Model()
_, e := doc.Render()
assert.Error(t, e)
assert.Equal(t, "this method only supports OpenAPI 3 documents, not Swagger", e.Error())
}
func TestDocument_BuildModelPreBuild(t *testing.T) {
petstore, _ := os.ReadFile("test_specs/petstorev3.json")
doc, e := NewDocument(petstore)
assert.NoError(t, e)
doc.BuildV3Model()
doc.BuildV3Model()
_, _, _, er := doc.RenderAndReload()
assert.Len(t, er, 0)
}
func TestDocument_AnyDoc(t *testing.T) {
anything := []byte(`{"chickens": "3.0.0", "burgers": {"title": "hello"}}`)
_, e := NewDocumentWithTypeCheck(anything, true)
assert.NoError(t, e)
}
func TestDocument_AnyDocWithConfig(t *testing.T) {
anything := []byte(`{"chickens": "3.0.0", "burgers": {"title": "hello"}}`)
_, e := NewDocumentWithConfiguration(anything, &datamodel.DocumentConfiguration{
BypassDocumentCheck: true,
})
assert.NoError(t, e)
}
func TestDocument_BuildModelCircular(t *testing.T) {
petstore, _ := os.ReadFile("test_specs/circular-tests.yaml")
doc, _ := NewDocument(petstore)
doc.BuildV3Model()
assert.Len(t, doc.GetRolodex().GetCaughtErrors(), 3)
}
func TestDocument_BuildModelBad(t *testing.T) {
petstore, _ := os.ReadFile("test_specs/badref-burgershop.openapi.yaml")
doc, _ := NewDocument(petstore)
doc.BuildV3Model()
assert.Len(t, doc.GetRolodex().GetCaughtErrors(), 6)
}
func TestDocument_Serialize_JSON_Modified(t *testing.T) {
json := `{ 'openapi': '3.0',
'info': {
'title': 'The magic API'
}
}
`
jsonModified := `{"info":{"title":"The magic API - but now, altered!"},"openapi":"3.0"}`
doc, _ := NewDocument([]byte(json))
v3Doc, _ := doc.BuildV3Model()
// eventually this will be encapsulated up high.
// mutation does not replace low model, eventually pointers will be used.
newTitle := v3Doc.Model.Info.GoLow().Title.Mutate("The magic API - but now, altered!")
v3Doc.Model.Info.GoLow().Title = newTitle
assert.Equal(t, "The magic API - but now, altered!", v3Doc.Model.Info.GoLow().Title.GetValue())
serial, err := doc.Serialize()
assert.NoError(t, err)
assert.Equal(t, jsonModified, string(serial))
}
func TestExtractReference(t *testing.T) {
data := `
openapi: "3.1"
components:
parameters:
Param1:
description: "I am a param"
paths:
/something:
get:
parameters:
- $ref: '#/components/parameters/Param1'`
doc, err := NewDocument([]byte(data))
if err != nil {
panic(err)
}
result, errs := doc.BuildV3Model()
if len(errs) > 0 {
panic(errs)
}
// extract operation.
operation := result.Model.Paths.PathItems.GetOrZero("/something").Get
// print it out.
fmt.Printf("param1: %s, is reference? %t, original reference %s",
operation.Parameters[0].Description, operation.GoLow().Parameters.Value[0].IsReference(),
operation.GoLow().Parameters.Value[0].GetReference())
}
func TestDocument_BuildModel_CompareDocsV3_LeftError(t *testing.T) {
burgerShopOriginal, _ := os.ReadFile("test_specs/badref-burgershop.openapi.yaml")
burgerShopUpdated, _ := os.ReadFile("test_specs/burgershop.openapi-modified.yaml")
originalDoc, _ := NewDocument(burgerShopOriginal)
updatedDoc, _ := NewDocument(burgerShopUpdated)
changes, errors := CompareDocuments(originalDoc, updatedDoc)
assert.Len(t, errors, 6)
assert.Nil(t, changes)
}
func TestDocument_BuildModel_CompareDocsV3_RightError(t *testing.T) {
burgerShopOriginal, _ := os.ReadFile("test_specs/badref-burgershop.openapi.yaml")
burgerShopUpdated, _ := os.ReadFile("test_specs/burgershop.openapi-modified.yaml")
originalDoc, _ := NewDocument(burgerShopOriginal)
updatedDoc, _ := NewDocument(burgerShopUpdated)
changes, errors := CompareDocuments(updatedDoc, originalDoc)
assert.Len(t, errors, 6)
assert.Nil(t, changes)
}
func TestDocument_BuildModel_CompareDocsV2_Error(t *testing.T) {
burgerShopOriginal, _ := os.ReadFile("test_specs/petstorev2-badref.json")
burgerShopUpdated, _ := os.ReadFile("test_specs/petstorev2-badref.json")
originalDoc, _ := NewDocument(burgerShopOriginal)
updatedDoc, _ := NewDocument(burgerShopUpdated)
changes, errors := CompareDocuments(updatedDoc, originalDoc)
assert.Len(t, errors, 14)
assert.Nil(t, changes)
}
func TestDocument_BuildModel_CompareDocsV2V3Mix_Error(t *testing.T) {
burgerShopOriginal, _ := os.ReadFile("test_specs/petstorev2.json")
burgerShopUpdated, _ := os.ReadFile("test_specs/petstorev3.json")
originalDoc, _ := NewDocument(burgerShopOriginal)
updatedDoc, _ := NewDocument(burgerShopUpdated)
changes, errors := CompareDocuments(updatedDoc, originalDoc)
assert.Len(t, errors, 1)
assert.Nil(t, changes)
}
func TestSchemaRefIsFollowed(t *testing.T) {
petstore, _ := os.ReadFile("test_specs/ref-followed.yaml")
// create a new document from specification bytes
document, err := NewDocument(petstore)
// if anything went wrong, an error is thrown
if err != nil {
panic(fmt.Sprintf("cannot create new document: %e", err))
}
// because we know this is a v3 spec, we can build a ready to go model from it.
v3Model, errors := document.BuildV3Model()
// if anything went wrong when building the v3 model, a slice of errors will be returned
if len(errors) > 0 {
for i := range errors {
fmt.Printf("error: %e\n", errors[i])
}
panic(fmt.Sprintf("cannot create v3 model from document: %d errors reported", len(errors)))
}
// get a count of the number of paths and schemas.
schemas := v3Model.Model.Components.Schemas
assert.Equal(t, 4, orderedmap.Len(schemas))
fp := schemas.GetOrZero("FP")
fbsref := schemas.GetOrZero("FBSRef")
assert.Equal(t, fp.Schema().Pattern, fbsref.Schema().Pattern)
assert.Equal(t, fp.Schema().Example, fbsref.Schema().Example)
byte := schemas.GetOrZero("Byte")
uint64 := schemas.GetOrZero("UInt64")
assert.Equal(t, uint64.Schema().Format, byte.Schema().Format)
assert.Equal(t, uint64.Schema().Type, byte.Schema().Type)
assert.Equal(t, uint64.Schema().Nullable, byte.Schema().Nullable)
assert.Equal(t, uint64.Schema().Example, byte.Schema().Example)
assert.Equal(t, uint64.Schema().Minimum, byte.Schema().Minimum)
}
func TestDocument_ParamsAndRefsRender(t *testing.T) {
d := `openapi: "3.1"
components:
parameters:
limit:
description: I am a param
offset:
description: I am a param
paths:
/webhooks:
get:
description: Get the compact representation of all webhooks your app has registered for the authenticated user in the given workspace.
operationId: getWebhooks
parameters:
- $ref: '#/components/parameters/limit'
- $ref: '#/components/parameters/offset'
- description: The workspace to query for webhooks in.
example: "1331"
in: query
name: workspace
required: true
schema:
type: string
- description: Only return webhooks for the given resource.
example: "51648"
in: query
name: resource
schema:
type: string`
doc, err := NewDocument([]byte(d))
if err != nil {
panic(err)
}
result, errs := doc.BuildV3Model()
if len(errs) > 0 {
panic(errs)
}
// render the document.
rend, _ := result.Model.Render()
assert.Equal(t, d, strings.TrimSpace(string(rend)))
}
// disabled for now as the host is timing out
//func TestDocument_RemoteWithoutBaseURL(t *testing.T) {
//
// // This test will push the index to do try and locate remote references that use relative references
// spec := `openapi: 3.0.2
//info:
// title: Test
// version: 1.0.0
//paths:
// /test:
// get:
// parameters:
// - $ref: "https://schemas.opengis.net/ogcapi/features/part2/1.0/openapi/ogcapi-features-2.yaml#/components/parameters/crs"`
//
// config := datamodel.NewDocumentConfiguration()
//
// doc, err := NewDocumentWithConfiguration([]byte(spec), config)
// if err != nil {
// panic(err)
// }
//
// result, errs := doc.BuildV3Model()
// if len(errs) > 0 {
// panic(errs)
// }
//
// assert.Equal(t, "crs", result.Model.Paths.PathItems.GetOrZero("/test").Get.Parameters[0].Name)
//}
func TestDocument_ExampleMap(t *testing.T) {
d := `openapi: "3.1"
components:
schemas:
ProjectRequest:
allOf:
- properties:
custom_fields:
additionalProperties:
description: '"{custom_field_gid}" => Value (Can be text, number, etc.)'
type: string
description: An object where each key is a Custom Field gid and each value is an enum gid, string, or number.
example:
"4578152156": Not Started
"5678904321": On Hold
type: object
`
doc, err := NewDocument([]byte(d))
if err != nil {
panic(err)
}
result, errs := doc.BuildV3Model()
if len(errs) > 0 {
panic(errs)
}
// render the document.
rend, _ := result.Model.Render()
assert.Len(t, rend, len(d))
}
func TestDocument_OperationsAsRefs(t *testing.T) {
ae := `operationId: thisIsAnOperationId
summary: a test thing
description: this is a test, that does a test.`
_ = os.WriteFile("test-operation.yaml", []byte(ae), 0o644)
defer os.Remove("test-operation.yaml")
d := `openapi: "3.1"
paths:
/an/operation:
get:
$ref: test-operation.yaml`
cf := datamodel.NewDocumentConfiguration()
cf.BasePath = "."
cf.FileFilter = []string{"test-operation.yaml"}
doc, err := NewDocumentWithConfiguration([]byte(d), cf)
if err != nil {
panic(err)
}
assert.NotNil(t, doc.GetConfiguration())
assert.Equal(t, doc.GetConfiguration(), cf)
result, errs := doc.BuildV3Model()
if len(errs) > 0 {
panic(errs)
}
// render the document.
rend, _ := result.Model.Render()
assert.Equal(t, d, strings.TrimSpace(string(rend)))
}
func TestDocument_InputAsJSON(t *testing.T) {
d := `{
"openapi": "3.1",
"paths": {
"/an/operation": {
"get": {
"operationId": "thisIsAnOperationId"
}
}
}
}`
doc, err := NewDocumentWithConfiguration([]byte(d), datamodel.NewDocumentConfiguration())
if err != nil {
panic(err)
}
_, _ = doc.BuildV3Model()
// render the document.
rend, _, _, _ := doc.RenderAndReload()
assert.Equal(t, d, strings.TrimSpace(string(rend)))
}
func TestDocument_InputAsJSON_LargeIndent(t *testing.T) {
d := `{
"openapi": "3.1",
"paths": {
"/an/operation": {
"get": {
"operationId": "thisIsAnOperationId"
}
}
}
}`
doc, err := NewDocumentWithConfiguration([]byte(d), datamodel.NewDocumentConfiguration())
if err != nil {
panic(err)
}
_, _ = doc.BuildV3Model()
// render the document.
rend, _, _, _ := doc.RenderAndReload()
assert.Equal(t, d, strings.TrimSpace(string(rend)))
}
func TestDocument_RenderWithIndention(t *testing.T) {
spec := `openapi: "3.1.0"
info:
title: Test
version: 1.0.0
paths:
/test:
get:
operationId: 'test'`
config := datamodel.NewDocumentConfiguration()
doc, err := NewDocumentWithConfiguration([]byte(spec), config)
if err != nil {
panic(err)
}
_, _ = doc.BuildV3Model()
rend, _, _, _ := doc.RenderAndReload()
assert.Equal(t, spec, strings.TrimSpace(string(rend)))
}
func TestDocument_IgnorePolymorphicCircularReferences(t *testing.T) {
d := `openapi: 3.1.0
components:
schemas:
ProductCategory:
type: "object"
properties:
name:
type: "string"
children:
type: "object"
anyOf:
- $ref: "#/components/schemas/ProductCategory"
description: "Array of sub-categories in the same format."
required:
- "name"
- "children"`
config := datamodel.NewDocumentConfiguration()
config.IgnorePolymorphicCircularReferences = true
doc, err := NewDocumentWithConfiguration([]byte(d), config)
if err != nil {
panic(err)
}
m, errs := doc.BuildV3Model()
assert.Len(t, errs, 0)
assert.Len(t, m.Index.GetCircularReferences(), 0)
assert.Len(t, m.Index.GetResolver().GetIgnoredCircularPolyReferences(), 1)
}
func TestDocument_IgnoreArrayCircularReferences(t *testing.T) {
d := `openapi: 3.1.0
components:
schemas:
ProductCategory:
type: "object"
properties:
name:
type: "string"
children:
type: "array"
items:
$ref: "#/components/schemas/ProductCategory"
description: "Array of sub-categories in the same format."
required:
- "name"
- "children"`
config := datamodel.NewDocumentConfiguration()
config.IgnoreArrayCircularReferences = true
doc, err := NewDocumentWithConfiguration([]byte(d), config)
if err != nil {
panic(err)
}
m, errs := doc.BuildV3Model()
assert.Len(t, errs, 0)
assert.Len(t, m.Index.GetCircularReferences(), 0)
assert.Len(t, m.Index.GetResolver().GetIgnoredCircularArrayReferences(), 1)
}
func TestDocument_TestMixedReferenceOrigin(t *testing.T) {
bs, _ := os.ReadFile("test_specs/mixedref-burgershop.openapi.yaml")
config := datamodel.NewDocumentConfiguration()
config.AllowRemoteReferences = true
config.AllowFileReferences = true
config.SkipCircularReferenceCheck = true
config.BasePath = "test_specs"
config.Logger = slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Level: slog.LevelDebug,
}))
doc, _ := NewDocumentWithConfiguration(bs, config)
m, _ := doc.BuildV3Model()
// extract something that can only exist after being located by the rolodex.
mediaType := m.Model.Paths.PathItems.GetOrZero("/burgers/{burgerId}/dressings").
Get.Responses.Codes.GetOrZero("200").Content.GetOrZero("application/json").Schema.Schema().Items
items := mediaType.A.Schema()
origin := items.ParentProxy.GetReferenceOrigin()
assert.NotNil(t, origin)
sep := string(os.PathSeparator)
assert.True(t, strings.HasSuffix(origin.AbsoluteLocation, "test_specs"+sep+"burgershop.openapi.yaml"))
}
func BenchmarkReferenceOrigin(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {