github.com/oam-dev/kubevela@v1.9.11/pkg/webhook/core.oam.dev/v1beta1/traitdefinition/validator_test.go (about) 1 /* 2 Copyright 2021 The KubeVela 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 traitdefinition 18 19 import ( 20 "context" 21 "fmt" 22 "testing" 23 24 "github.com/crossplane/crossplane-runtime/pkg/test" 25 "github.com/google/go-cmp/cmp" 26 "github.com/pkg/errors" 27 28 "github.com/oam-dev/kubevela/pkg/oam/util" 29 ) 30 31 func TestValidateDefinitionReference(t *testing.T) { 32 cases := map[string]struct { 33 reason string 34 template string 35 want error 36 }{ 37 "NoExtension": { 38 reason: "An error should be returned if extension is omitted", 39 template: "", 40 want: errors.New(failInfoDefRefOmitted), 41 }, 42 "HaveExtentsion_NoTemplate": { 43 reason: "An error should be returned if extension template is omitted", 44 template: ` 45 extension: 46 notemplate: |- 47 fakefield: fakefieldvalue`, 48 want: errors.New(failInfoDefRefOmitted), 49 }, 50 "HaveExtension_HaveTemplate": { 51 reason: "No error should be returned if have CUE template", 52 template: ` 53 extension: 54 template: |- 55 patch: { 56 spec: replicas: parameter.replicas 57 }`, 58 want: nil, 59 }, 60 } 61 62 for caseName, tc := range cases { 63 t.Run(caseName, func(t *testing.T) { 64 tdStr := traitDefStringWithTemplate(tc.template) 65 td, err := util.UnMarshalStringToTraitDefinition(tdStr) 66 if err != nil { 67 t.Fatal("error occurs in generating TraitDefinition string", err.Error()) 68 } 69 err = ValidateDefinitionReference(context.Background(), *td) 70 if diff := cmp.Diff(tc.want, err, test.EquateErrors()); diff != "" { 71 t.Errorf("\n%s\nValidateDefinitionReference: -want , +got \n%s\n", tc.reason, diff) 72 } 73 }) 74 } 75 } 76 77 func traitDefStringWithTemplate(t string) string { 78 return fmt.Sprintf(` 79 apiVersion: core.oam.dev/v1beta1 80 kind: TraitDefinition 81 metadata: 82 name: scaler 83 spec: 84 %s`, t) 85 }