...
1
16
17 package schema
18
19 import (
20 "math/rand"
21 "reflect"
22 "testing"
23 "time"
24
25 "github.com/google/go-cmp/cmp"
26 fuzz "github.com/google/gofuzz"
27
28 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions"
29 apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
30 "k8s.io/apimachinery/pkg/util/json"
31 )
32
33 func TestStructuralKubeOpenAPIRoundtrip(t *testing.T) {
34 f := fuzz.New()
35 seed := time.Now().UnixNano()
36 t.Logf("seed = %v", seed)
37
38 f.RandSource(rand.New(rand.NewSource(seed)))
39 f.Funcs(
40 func(s *JSON, c fuzz.Continue) {
41 switch c.Intn(7) {
42 case 0:
43 s.Object = float64(42.2)
44 case 1:
45 s.Object = map[string]interface{}{"foo": "bar"}
46 case 2:
47 s.Object = ""
48 case 3:
49 s.Object = []interface{}{}
50 case 4:
51 s.Object = map[string]interface{}{}
52 case 5:
53 s.Object = nil
54 case 6:
55 s.Object = int64(42)
56 }
57 },
58 )
59 f.MaxDepth(3)
60 f.NilChance(0.5)
61
62 for i := 0; i < 10000; i++ {
63 orig := &Structural{}
64 f.Fuzz(orig)
65
66
67 normalizer := Visitor{
68 Structural: func(s *Structural) bool {
69 if s.ValueValidation == nil {
70 s.ValueValidation = &ValueValidation{}
71 return true
72 }
73 return false
74 },
75 }
76 normalizer.Visit(orig)
77
78 kubeOpenAPI := orig.ToKubeOpenAPI()
79 bs, err := json.Marshal(kubeOpenAPI)
80 if err != nil {
81 t.Fatal(err)
82 }
83 v1beta1Schema := &apiextensionsv1beta1.JSONSchemaProps{}
84 err = json.Unmarshal(bs, v1beta1Schema)
85 if err != nil {
86 t.Fatal(err)
87 }
88 internalSchema := &apiextensions.JSONSchemaProps{}
89 err = apiextensionsv1beta1.Convert_v1beta1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(v1beta1Schema, internalSchema, nil)
90 if err != nil {
91 t.Fatal(err)
92 }
93 s, err := NewStructural(internalSchema)
94 if err != nil {
95 t.Fatal(err)
96 }
97
98 if !reflect.DeepEqual(orig, s) {
99 t.Fatalf("original and result differ: %v", cmp.Diff(orig, s))
100 }
101 }
102 }
103
View as plain text