current_context_test.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*
  2. Copyright 2014 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 config
  14. import (
  15. "bytes"
  16. "io/ioutil"
  17. "os"
  18. "strings"
  19. "testing"
  20. "k8s.io/client-go/tools/clientcmd"
  21. clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
  22. )
  23. type currentContextTest struct {
  24. startingConfig clientcmdapi.Config
  25. expectedError string
  26. }
  27. func newFederalContextConfig() clientcmdapi.Config {
  28. return clientcmdapi.Config{
  29. CurrentContext: "federal-context",
  30. }
  31. }
  32. func TestCurrentContextWithSetContext(t *testing.T) {
  33. test := currentContextTest{
  34. startingConfig: newFederalContextConfig(),
  35. expectedError: "",
  36. }
  37. test.run(t)
  38. }
  39. func TestCurrentContextWithUnsetContext(t *testing.T) {
  40. test := currentContextTest{
  41. startingConfig: *clientcmdapi.NewConfig(),
  42. expectedError: "current-context is not set",
  43. }
  44. test.run(t)
  45. }
  46. func (test currentContextTest) run(t *testing.T) {
  47. fakeKubeFile, err := ioutil.TempFile("", "")
  48. if err != nil {
  49. t.Fatalf("unexpected error: %v", err)
  50. }
  51. defer os.Remove(fakeKubeFile.Name())
  52. err = clientcmd.WriteToFile(test.startingConfig, fakeKubeFile.Name())
  53. if err != nil {
  54. t.Fatalf("unexpected error: %v", err)
  55. }
  56. pathOptions := clientcmd.NewDefaultPathOptions()
  57. pathOptions.GlobalFile = fakeKubeFile.Name()
  58. pathOptions.EnvVar = ""
  59. options := CurrentContextOptions{
  60. ConfigAccess: pathOptions,
  61. }
  62. buf := bytes.NewBuffer([]byte{})
  63. err = RunCurrentContext(buf, &options)
  64. if len(test.expectedError) != 0 {
  65. if err == nil {
  66. t.Errorf("Did not get %v", test.expectedError)
  67. } else {
  68. if !strings.Contains(err.Error(), test.expectedError) {
  69. t.Errorf("Expected %v, but got %v", test.expectedError, err)
  70. }
  71. }
  72. return
  73. }
  74. if err != nil {
  75. t.Errorf("Unexpected error: %v", err)
  76. }
  77. }