blob: 00022806171f6a7856866c70921d9bd29055b43e [file] [log] [blame]
Matteo Scandoloa4285862020-12-01 18:10:10 -08001/*
2Copyright 2016 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 runtime
18
19import (
20 "fmt"
21 "reflect"
22
23 "k8s.io/apimachinery/pkg/runtime/schema"
24 "k8s.io/apimachinery/pkg/util/json"
25)
26
27// CheckCodec makes sure that the codec can encode objects like internalType,
28// decode all of the external types listed, and also decode them into the given
29// object. (Will modify internalObject.) (Assumes JSON serialization.)
30// TODO: verify that the correct external version is chosen on encode...
31func CheckCodec(c Codec, internalType Object, externalTypes ...schema.GroupVersionKind) error {
32 if _, err := Encode(c, internalType); err != nil {
33 return fmt.Errorf("Internal type not encodable: %v", err)
34 }
35 for _, et := range externalTypes {
36 typeMeta := TypeMeta{
37 Kind: et.Kind,
38 APIVersion: et.GroupVersion().String(),
39 }
40 exBytes, err := json.Marshal(&typeMeta)
41 if err != nil {
42 return err
43 }
44 obj, err := Decode(c, exBytes)
45 if err != nil {
46 return fmt.Errorf("external type %s not interpretable: %v", et, err)
47 }
48 if reflect.TypeOf(obj) != reflect.TypeOf(internalType) {
49 return fmt.Errorf("decode of external type %s produced: %#v", et, obj)
50 }
51 if err = DecodeInto(c, exBytes, internalType); err != nil {
52 return fmt.Errorf("external type %s not convertible to internal type: %v", et, err)
53 }
54 }
55 return nil
56}