blob: 510444a4dec27d5da3e552f9e7c4b8c5a2b9861c [file] [log] [blame]
sslobodrd046be82019-01-16 10:02:22 -05001/*
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)
25
26// CheckCodec makes sure that the codec can encode objects like internalType,
27// decode all of the external types listed, and also decode them into the given
28// object. (Will modify internalObject.) (Assumes JSON serialization.)
29// TODO: verify that the correct external version is chosen on encode...
30func CheckCodec(c Codec, internalType Object, externalTypes ...schema.GroupVersionKind) error {
31 if _, err := Encode(c, internalType); err != nil {
32 return fmt.Errorf("Internal type not encodable: %v", err)
33 }
34 for _, et := range externalTypes {
35 exBytes := []byte(fmt.Sprintf(`{"kind":"%v","apiVersion":"%v"}`, et.Kind, et.GroupVersion().String()))
36 obj, err := Decode(c, exBytes)
37 if err != nil {
38 return fmt.Errorf("external type %s not interpretable: %v", et, err)
39 }
40 if reflect.TypeOf(obj) != reflect.TypeOf(internalType) {
41 return fmt.Errorf("decode of external type %s produced: %#v", et, obj)
42 }
43 if err = DecodeInto(c, exBytes, internalType); err != nil {
44 return fmt.Errorf("external type %s not convertible to internal type: %v", et, err)
45 }
46 }
47 return nil
48}