sigs.k8s.io/cluster-api@v1.7.1/bootstrap/kubeadm/internal/cloudinit/node_test.go (about) 1 /* 2 Copyright 2021 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 cloudinit 18 19 import ( 20 "fmt" 21 "testing" 22 23 "sigs.k8s.io/yaml" 24 25 bootstrapv1 "sigs.k8s.io/cluster-api/bootstrap/kubeadm/api/v1beta1" 26 ) 27 28 func TestNewNode(t *testing.T) { 29 tests := []struct { 30 name string 31 input *NodeInput 32 check func([]byte) error 33 wantErr bool 34 }{ 35 { 36 "check for duplicated write_files", 37 &NodeInput{ 38 BaseUserData: BaseUserData{ 39 AdditionalFiles: []bootstrapv1.File{ 40 { 41 Path: "/etc/foo.conf", 42 Content: "bar", 43 Owner: "root", 44 Permissions: "0644", 45 }, 46 }, 47 }, 48 }, 49 checkWriteFiles("/etc/foo.conf", "/run/kubeadm/kubeadm-join-config.yaml", "/run/cluster-api/placeholder"), 50 false, 51 }, 52 { 53 "check for existence of /run/kubeadm/kubeadm-join-config.yaml and /run/cluster-api/placeholder", 54 &NodeInput{}, 55 checkWriteFiles("/run/kubeadm/kubeadm-join-config.yaml", "/run/cluster-api/placeholder"), 56 false, 57 }, 58 } 59 for _, tt := range tests { 60 t.Run(tt.name, func(t *testing.T) { 61 got, err := NewNode(tt.input) 62 if (err != nil) != tt.wantErr { 63 t.Errorf("NewNode() error = %v, wantErr %v", err, tt.wantErr) 64 return 65 } 66 if err := tt.check(got); err != nil { 67 t.Errorf("%v: got = %s", err, got) 68 } 69 }) 70 } 71 } 72 73 func checkWriteFiles(files ...string) func(b []byte) error { 74 return func(b []byte) error { 75 var cloudinitData struct { 76 WriteFiles []struct { 77 Path string `json:"path"` 78 } `json:"write_files"` 79 } 80 81 if err := yaml.Unmarshal(b, &cloudinitData); err != nil { 82 return err 83 } 84 85 gotFiles := map[string]bool{} 86 for _, f := range cloudinitData.WriteFiles { 87 gotFiles[f.Path] = true 88 } 89 for _, file := range files { 90 if !gotFiles[file] { 91 return fmt.Errorf("expected %q to exist in CloudInit's write_files", file) 92 } 93 } 94 if len(files) != len(cloudinitData.WriteFiles) { 95 return fmt.Errorf("expected to have %d files generated to CloudInit's write_files, got %d", len(files), len(cloudinitData.WriteFiles)) 96 } 97 98 return nil 99 } 100 }