sigs.k8s.io/cluster-api@v1.7.1/internal/topology/names/names_test.go (about) 1 /* 2 Copyright 2023 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 names 18 19 import ( 20 "fmt" 21 "testing" 22 23 . "github.com/onsi/gomega" 24 "github.com/onsi/gomega/types" 25 ) 26 27 func Test_templateGenerator_GenerateName(t *testing.T) { 28 tests := []struct { 29 name string 30 template string 31 data map[string]interface{} 32 want []types.GomegaMatcher 33 wantErr bool 34 }{ 35 { 36 name: "simple template", 37 template: "some-simple-{{ .test }}", 38 data: map[string]interface{}{ 39 "test": "testdata", 40 }, 41 want: []types.GomegaMatcher{ 42 Equal("some-simple-testdata"), 43 }, 44 }, 45 { 46 name: "name which gets trimmed and added a random suffix with 5 characters", 47 template: fmt.Sprintf("%064d", 0), 48 want: []types.GomegaMatcher{ 49 HavePrefix(fmt.Sprintf("%058d", 0)), 50 Not(HaveSuffix("00000")), 51 }, 52 }, 53 { 54 name: "name which does not get trimmed", 55 template: fmt.Sprintf("%063d", 0), 56 want: []types.GomegaMatcher{ 57 Equal(fmt.Sprintf("%063d", 0)), 58 }, 59 }, 60 { 61 name: "error on parsing template", 62 template: "some-hardcoded-name-{{ .doesnotexistindata", 63 wantErr: true, 64 }, 65 { 66 name: "error on due to missing key in data", 67 template: "some-hardcoded-name-{{ .doesnotexistindata }}", 68 data: nil, 69 wantErr: true, 70 }, 71 } 72 for _, tt := range tests { 73 t.Run(tt.name, func(t *testing.T) { 74 g := NewWithT(t) 75 generator := &templateGenerator{ 76 template: tt.template, 77 data: tt.data, 78 } 79 got, err := generator.GenerateName() 80 if (err != nil) != tt.wantErr { 81 t.Errorf("templateGenerator.GenerateName() error = %v, wantErr %v", err, tt.wantErr) 82 return 83 } 84 if len(got) > maxNameLength { 85 t.Errorf("generated name should never be longer than %d, got %d", maxNameLength, len(got)) 86 } 87 for _, matcher := range tt.want { 88 g.Expect(got).To(matcher) 89 } 90 }) 91 } 92 }