github.com/spotmaxtech/k8s-apimachinery-v0260@v0.0.1/pkg/runtime/serializer/sparse_test.go (about) 1 /* 2 Copyright 2018 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package serializer 18 19 import ( 20 "testing" 21 22 "github.com/spotmaxtech/k8s-apimachinery-v0260/pkg/api/equality" 23 metav1 "github.com/spotmaxtech/k8s-apimachinery-v0260/pkg/apis/meta/v1" 24 "github.com/spotmaxtech/k8s-apimachinery-v0260/pkg/runtime" 25 "github.com/spotmaxtech/k8s-apimachinery-v0260/pkg/runtime/schema" 26 "github.com/spotmaxtech/k8s-apimachinery-v0260/pkg/util/diff" 27 ) 28 29 type FakeV1Obj struct { 30 metav1.TypeMeta 31 metav1.ObjectMeta 32 } 33 34 func (*FakeV1Obj) DeepCopyObject() runtime.Object { 35 panic("not supported") 36 } 37 38 type FakeV2DifferentObj struct { 39 metav1.TypeMeta 40 metav1.ObjectMeta 41 } 42 43 func (*FakeV2DifferentObj) DeepCopyObject() runtime.Object { 44 panic("not supported") 45 } 46 func TestSparse(t *testing.T) { 47 v1 := schema.GroupVersion{Group: "mygroup", Version: "v1"} 48 v2 := schema.GroupVersion{Group: "mygroup", Version: "v2"} 49 50 scheme := runtime.NewScheme() 51 scheme.AddKnownTypes(v1, &FakeV1Obj{}) 52 scheme.AddKnownTypes(v2, &FakeV2DifferentObj{}) 53 codecs := NewCodecFactory(scheme) 54 55 srcObj1 := &FakeV1Obj{ObjectMeta: metav1.ObjectMeta{Name: "foo"}} 56 srcObj2 := &FakeV2DifferentObj{ObjectMeta: metav1.ObjectMeta{Name: "foo"}} 57 58 encoder := codecs.LegacyCodec(v2, v1) 59 decoder := codecs.UniversalDecoder(v2, v1) 60 61 srcObj1Bytes, err := runtime.Encode(encoder, srcObj1) 62 if err != nil { 63 t.Fatal(err) 64 } 65 t.Log(string(srcObj1Bytes)) 66 srcObj2Bytes, err := runtime.Encode(encoder, srcObj2) 67 if err != nil { 68 t.Fatal(err) 69 } 70 t.Log(string(srcObj2Bytes)) 71 72 uncastDstObj1, err := runtime.Decode(decoder, srcObj1Bytes) 73 if err != nil { 74 t.Fatal(err) 75 } 76 uncastDstObj2, err := runtime.Decode(decoder, srcObj2Bytes) 77 if err != nil { 78 t.Fatal(err) 79 } 80 81 // clear typemeta 82 uncastDstObj1.(*FakeV1Obj).TypeMeta = metav1.TypeMeta{} 83 uncastDstObj2.(*FakeV2DifferentObj).TypeMeta = metav1.TypeMeta{} 84 85 if !equality.Semantic.DeepEqual(srcObj1, uncastDstObj1) { 86 t.Fatal(diff.ObjectDiff(srcObj1, uncastDstObj1)) 87 } 88 if !equality.Semantic.DeepEqual(srcObj2, uncastDstObj2) { 89 t.Fatal(diff.ObjectDiff(srcObj2, uncastDstObj2)) 90 } 91 }