Scott Baker | e7144bc | 2019-10-01 14:16:47 -0700 | [diff] [blame^] | 1 | /* |
| 2 | Copyright 2016 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 runtime |
| 18 | |
| 19 | import ( |
| 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... |
| 30 | func 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 | } |