util.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. /*
  2. Copyright 2017 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package test
  14. import (
  15. "fmt"
  16. "html/template"
  17. "io/ioutil"
  18. "os"
  19. "path/filepath"
  20. "testing"
  21. "github.com/lithammer/dedent"
  22. kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm"
  23. kubeadmapiv1beta2 "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/v1beta2"
  24. kubeadmconstants "k8s.io/kubernetes/cmd/kubeadm/app/constants"
  25. certtestutil "k8s.io/kubernetes/cmd/kubeadm/app/util/certs"
  26. configutil "k8s.io/kubernetes/cmd/kubeadm/app/util/config"
  27. "k8s.io/kubernetes/cmd/kubeadm/app/util/pkiutil"
  28. )
  29. // SetupTempDir is a utility function for kubeadm testing, that creates a temporary directory
  30. // NB. it is up to the caller to cleanup the folder at the end of the test with defer os.RemoveAll(tmpdir)
  31. func SetupTempDir(t *testing.T) string {
  32. tmpdir, err := ioutil.TempDir("", "")
  33. if err != nil {
  34. t.Fatalf("Couldn't create tmpdir")
  35. }
  36. return tmpdir
  37. }
  38. // SetupInitConfigurationFile is a utility function for kubeadm testing that writes a InitConfiguration file
  39. // into /config subfolder of a given temporary directory.
  40. // The function returns the path of the created InitConfiguration file.
  41. func SetupInitConfigurationFile(t *testing.T, tmpdir string, cfg *kubeadmapi.InitConfiguration) string {
  42. cfgPath := filepath.Join(tmpdir, "config/masterconfig.yaml")
  43. if err := os.MkdirAll(filepath.Dir(cfgPath), os.FileMode(0755)); err != nil {
  44. t.Fatalf("Couldn't create cfgDir")
  45. }
  46. cfgTemplate := template.Must(template.New("init").Parse(dedent.Dedent(fmt.Sprintf(`
  47. apiVersion: kubeadm.k8s.io/v1beta2
  48. kind: InitConfiguration
  49. apiEndpoint:
  50. advertiseAddress: {{.LocalAPIEndpoint.AdvertiseAddress}}
  51. bindPort: {{.LocalAPIEndpoint.BindPort}}
  52. nodeRegistration:
  53. name: {{.NodeRegistration.Name}}
  54. ---
  55. apiVersion: kubeadm.k8s.io/v1beta2
  56. kind: ClusterConfiguration
  57. certificatesDir: {{.CertificatesDir}}
  58. kubernetesVersion: %s
  59. `, kubeadmconstants.MinimumControlPlaneVersion))))
  60. f, err := os.Create(cfgPath)
  61. if err != nil {
  62. t.Fatalf("error creating masterconfig file %s: %v", cfgPath, err)
  63. }
  64. err = cfgTemplate.Execute(f, cfg)
  65. if err != nil {
  66. t.Fatalf("error generating masterconfig file %s: %v", cfgPath, err)
  67. }
  68. f.Close()
  69. return cfgPath
  70. }
  71. // SetupEmptyFiles is a utility function for kubeadm testing that creates one or more empty files (touch)
  72. func SetupEmptyFiles(t *testing.T, tmpdir string, fileNames ...string) {
  73. for _, fileName := range fileNames {
  74. newFile, err := os.Create(filepath.Join(tmpdir, fileName))
  75. if err != nil {
  76. t.Fatalf("Error creating file %s in %s: %v", fileName, tmpdir, err)
  77. }
  78. newFile.Close()
  79. }
  80. }
  81. // SetupPkiDirWithCertificateAuthority is a utility function for kubeadm testing that creates a
  82. // CertificateAuthority cert/key pair into /pki subfolder of a given temporary directory.
  83. // The function returns the path of the created pki.
  84. func SetupPkiDirWithCertificateAuthority(t *testing.T, tmpdir string) string {
  85. caCert, caKey := certtestutil.SetupCertificateAuthority(t)
  86. certDir := filepath.Join(tmpdir, "pki")
  87. if err := pkiutil.WriteCertAndKey(certDir, kubeadmconstants.CACertAndKeyBaseName, caCert, caKey); err != nil {
  88. t.Fatalf("failure while saving CA certificate and key: %v", err)
  89. }
  90. return certDir
  91. }
  92. // AssertFilesCount is a utility function for kubeadm testing that asserts if the given folder contains
  93. // count files.
  94. func AssertFilesCount(t *testing.T, dirName string, count int) {
  95. files, err := ioutil.ReadDir(dirName)
  96. if err != nil {
  97. t.Fatalf("Couldn't read files from tmpdir: %s", err)
  98. }
  99. countFiles := 0
  100. for _, f := range files {
  101. if !f.IsDir() {
  102. countFiles++
  103. }
  104. }
  105. if countFiles != count {
  106. t.Errorf("dir does contains %d, %d expected", len(files), count)
  107. for _, f := range files {
  108. t.Error(f.Name())
  109. }
  110. }
  111. }
  112. // AssertFileExists is a utility function for kubeadm testing that asserts if the given folder contains
  113. // the given files.
  114. func AssertFileExists(t *testing.T, dirName string, fileNames ...string) {
  115. for _, fileName := range fileNames {
  116. path := filepath.Join(dirName, fileName)
  117. if _, err := os.Stat(path); os.IsNotExist(err) {
  118. t.Errorf("file %s does not exist", fileName)
  119. }
  120. }
  121. }
  122. // AssertError checks that the provided error matches the expected output
  123. func AssertError(t *testing.T, err error, expected string) {
  124. if err == nil {
  125. t.Errorf("no error was found, but '%s' was expected", expected)
  126. return
  127. }
  128. if err.Error() != expected {
  129. t.Errorf("error '%s' does not match expected error: '%s'", err.Error(), expected)
  130. }
  131. }
  132. // GetDefaultInternalConfig returns a defaulted kubeadmapi.InitConfiguration
  133. func GetDefaultInternalConfig(t *testing.T) *kubeadmapi.InitConfiguration {
  134. internalcfg, err := configutil.DefaultedInitConfiguration(&kubeadmapiv1beta2.InitConfiguration{}, &kubeadmapiv1beta2.ClusterConfiguration{})
  135. if err != nil {
  136. t.Fatalf("unexpected error getting default config: %v", err)
  137. }
  138. return internalcfg
  139. }