k8s.io/kubernetes@v1.29.3/pkg/apis/resource/v1alpha2/defaults_test.go (about) 1 /* 2 Copyright 2022 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 v1alpha2_test 18 19 import ( 20 "reflect" 21 "testing" 22 23 v1alpha2 "k8s.io/api/resource/v1alpha2" 24 "k8s.io/apimachinery/pkg/runtime" 25 26 // ensure types are installed 27 "k8s.io/kubernetes/pkg/api/legacyscheme" 28 _ "k8s.io/kubernetes/pkg/apis/resource/install" 29 ) 30 31 func TestSetDefaultAllocationMode(t *testing.T) { 32 claim := &v1alpha2.ResourceClaim{} 33 34 // field should be defaulted 35 defaultMode := v1alpha2.AllocationModeWaitForFirstConsumer 36 output := roundTrip(t, runtime.Object(claim)).(*v1alpha2.ResourceClaim) 37 outMode := output.Spec.AllocationMode 38 if outMode != defaultMode { 39 t.Errorf("Expected AllocationMode to be defaulted to: %+v, got: %+v", defaultMode, outMode) 40 } 41 42 // field should not change 43 nonDefaultMode := v1alpha2.AllocationModeImmediate 44 claim = &v1alpha2.ResourceClaim{ 45 Spec: v1alpha2.ResourceClaimSpec{ 46 AllocationMode: nonDefaultMode, 47 }, 48 } 49 output = roundTrip(t, runtime.Object(claim)).(*v1alpha2.ResourceClaim) 50 outMode = output.Spec.AllocationMode 51 if outMode != v1alpha2.AllocationModeImmediate { 52 t.Errorf("Expected AllocationMode to remain %+v, got: %+v", nonDefaultMode, outMode) 53 } 54 } 55 56 func roundTrip(t *testing.T, obj runtime.Object) runtime.Object { 57 codec := legacyscheme.Codecs.LegacyCodec(v1alpha2.SchemeGroupVersion) 58 data, err := runtime.Encode(codec, obj) 59 if err != nil { 60 t.Errorf("%v\n %#v", err, obj) 61 return nil 62 } 63 obj2, err := runtime.Decode(codec, data) 64 if err != nil { 65 t.Errorf("%v\nData: %s\nSource: %#v", err, string(data), obj) 66 return nil 67 } 68 obj3 := reflect.New(reflect.TypeOf(obj).Elem()).Interface().(runtime.Object) 69 err = legacyscheme.Scheme.Convert(obj2, obj3, nil) 70 if err != nil { 71 t.Errorf("%v\nSource: %#v", err, obj2) 72 return nil 73 } 74 return obj3 75 }