diff --git a/pkg/conversion/decode.go b/pkg/conversion/decode.go index 81be6bb5bef..fe90bbe44e0 100644 --- a/pkg/conversion/decode.go +++ b/pkg/conversion/decode.go @@ -97,9 +97,6 @@ func (s *Scheme) DecodeInto(data []byte, obj interface{}) error { // correct type. dataKind = objKind } - if dataKind != objKind { - return fmt.Errorf("data of kind '%v', obj of type '%v'", dataKind, objKind) - } if dataVersion == "" { // Assume objects with unset Version fields are being unmarshalled into the // correct type. diff --git a/pkg/conversion/scheme.go b/pkg/conversion/scheme.go index a42c83ed32e..84e05b8bd87 100644 --- a/pkg/conversion/scheme.go +++ b/pkg/conversion/scheme.go @@ -75,10 +75,12 @@ func (s *Scheme) Log(l DebugLogger) { // nameFunc returns the name of the type that we wish to use for encoding. Defaults to // the go name of the type if the type is not registered. func (s *Scheme) nameFunc(t reflect.Type) string { - if kind, ok := s.typeToKind[t]; ok { - return kind[0] + // find the preferred names for this type + names, ok := s.typeToKind[t] + if !ok { + return t.Name() } - return t.Name() + return names[0] } // AddKnownTypes registers all types passed in 'types' as being members of version 'version. diff --git a/pkg/conversion/scheme_test.go b/pkg/conversion/scheme_test.go index b9a38bfa37a..3d2c3bbc5cf 100644 --- a/pkg/conversion/scheme_test.go +++ b/pkg/conversion/scheme_test.go @@ -228,6 +228,43 @@ func TestMultipleNames(t *testing.T) { } } +func TestConvertTypesWhenDefaultNamesMatch(t *testing.T) { + s := NewScheme() + // create two names internally, with TestType1 being preferred + s.AddKnownTypeWithName("", "TestType1", &TestType1{}) + s.AddKnownTypeWithName("", "OtherType1", &TestType1{}) + // create two names externally, with TestType1 being preferred + s.AddKnownTypeWithName("v1", "TestType1", &ExternalTestType1{}) + s.AddKnownTypeWithName("v1", "OtherType1", &ExternalTestType1{}) + s.MetaFactory = testMetaFactory{} + + ext := &ExternalTestType1{} + ext.APIVersion = "v1" + ext.ObjectKind = "OtherType1" + ext.A = "test" + data, err := json.Marshal(ext) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + expect := &TestType1{A: "test"} + + obj, err := s.Decode(data) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if !reflect.DeepEqual(expect, obj) { + t.Errorf("unexpected object: %#v", obj) + } + + into := &TestType1{} + if err := s.DecodeInto(data, into); err != nil { + t.Fatalf("unexpected error: %v", err) + } + if !reflect.DeepEqual(expect, obj) { + t.Errorf("unexpected object: %#v", obj) + } +} + func TestKnownTypes(t *testing.T) { s := GetTestScheme() if len(s.KnownTypes("v2")) != 0 {