...
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 TestStructuralRoundtripOrError(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 *apiextensions.JSON, c fuzz.Continue) {
41 *s = apiextensions.JSON(map[string]interface{}{"foo": float64(42.2)})
42 },
43 func(s *apiextensions.JSONSchemaPropsOrArray, c fuzz.Continue) {
44 c.FuzzNoCustom(s)
45 if s.Schema != nil {
46 s.JSONSchemas = nil
47 } else if s.JSONSchemas == nil {
48 s.Schema = &apiextensions.JSONSchemaProps{}
49 }
50 },
51 func(s *apiextensions.JSONSchemaPropsOrBool, c fuzz.Continue) {
52 c.FuzzNoCustom(s)
53 if s.Schema != nil {
54 s.Allows = false
55 }
56 },
57 func(s **string, c fuzz.Continue) {
58 c.FuzzNoCustom(s)
59 if *s != nil && **s == "" {
60 *s = nil
61 }
62 },
63 )
64
65 f.MaxDepth(2)
66 f.NilChance(0.5)
67
68 for i := 0; i < 10000; i++ {
69
70 origSchema := &apiextensions.JSONSchemaProps{}
71 x := reflect.ValueOf(origSchema).Elem()
72 n := rand.Intn(x.NumField())
73 if name := x.Type().Field(n).Name; name == "Example" || name == "ExternalDocs" {
74
75 continue
76 }
77 f.Fuzz(x.Field(n).Addr().Interface())
78
79
80 orig, err := NewStructural(origSchema)
81 if err != nil {
82 continue
83 }
84
85
86 goOpenAPI := orig.ToKubeOpenAPI()
87 bs, err := json.Marshal(goOpenAPI)
88 if err != nil {
89 t.Fatal(err)
90 }
91 v1beta1Schema := &apiextensionsv1beta1.JSONSchemaProps{}
92 err = json.Unmarshal([]byte(bs), v1beta1Schema)
93 if err != nil {
94 t.Fatal(err)
95 }
96 internalSchema := &apiextensions.JSONSchemaProps{}
97 err = apiextensionsv1beta1.Convert_v1beta1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(v1beta1Schema, internalSchema, nil)
98 if err != nil {
99 t.Fatal(err)
100 }
101
102 if !reflect.DeepEqual(origSchema, internalSchema) {
103 t.Fatalf("original and result differ: %v", cmp.Diff(origSchema, internalSchema))
104 }
105 }
106 }
107
View as plain text