1/* 2Copyright 2020 The Kubernetes Authors. 3 4Licensed under the Apache License, Version 2.0 (the "License"); 5you may not use this file except in compliance with the License. 6You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10Unless required by applicable law or agreed to in writing, software 11distributed under the License is distributed on an "AS IS" BASIS, 12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13See the License for the specific language governing permissions and 14limitations under the License. 15*/ 16 17package defaulting 18 19import ( 20 "bytes" 21 "reflect" 22 "testing" 23 24 structuralschema "k8s.io/apiextensions-apiserver/pkg/apiserver/schema" 25 "k8s.io/apimachinery/pkg/util/json" 26) 27 28func TestPruneNonNullableNullsWithoutDefaults(t *testing.T) { 29 tests := []struct { 30 name string 31 json string 32 schema *structuralschema.Structural 33 expected string 34 }{ 35 {"empty", "null", nil, "null"}, 36 {"scalar", "4", &structuralschema.Structural{ 37 Generic: structuralschema.Generic{ 38 Default: structuralschema.JSON{"foo"}, 39 }, 40 }, "4"}, 41 {"scalar array", "[1,null]", nil, "[1,null]"}, 42 {"object array", `[{"a":null},{"b":null},{"c":null},{"d":null},{"e":null}]`, &structuralschema.Structural{ 43 Items: &structuralschema.Structural{ 44 Properties: map[string]structuralschema.Structural{ 45 "a": { 46 Generic: structuralschema.Generic{ 47 Default: structuralschema.JSON{"A"}, 48 }, 49 }, 50 "b": { 51 Generic: structuralschema.Generic{ 52 Nullable: true, 53 }, 54 }, 55 "c": { 56 Generic: structuralschema.Generic{ 57 Default: structuralschema.JSON{"C"}, 58 Nullable: true, 59 }, 60 }, 61 "d": { 62 Generic: structuralschema.Generic{}, 63 }, 64 }, 65 }, 66 }, `[{"a":null},{"b":null},{"c":null},{},{"e":null}]`}, 67 } 68 for _, tt := range tests { 69 t.Run(tt.name, func(t *testing.T) { 70 var in interface{} 71 if err := json.Unmarshal([]byte(tt.json), &in); err != nil { 72 t.Fatal(err) 73 } 74 75 var expected interface{} 76 if err := json.Unmarshal([]byte(tt.expected), &expected); err != nil { 77 t.Fatal(err) 78 } 79 80 PruneNonNullableNullsWithoutDefaults(in, tt.schema) 81 if !reflect.DeepEqual(in, expected) { 82 var buf bytes.Buffer 83 enc := json.NewEncoder(&buf) 84 enc.SetIndent("", " ") 85 err := enc.Encode(in) 86 if err != nil { 87 t.Fatalf("unexpected result mashalling error: %v", err) 88 } 89 t.Errorf("expected: %s\ngot: %s", tt.expected, buf.String()) 90 } 91 }) 92 } 93} 94