viperconfig_test.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. Copyright 2019 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 e2e
  14. import (
  15. "flag"
  16. "io/ioutil"
  17. "os"
  18. "testing"
  19. "time"
  20. "github.com/stretchr/testify/require"
  21. "k8s.io/kubernetes/test/e2e/framework/config"
  22. )
  23. func TestViperConfig(t *testing.T) {
  24. flags := flag.NewFlagSet("test", 0)
  25. type Context struct {
  26. Bool bool `default:"true"`
  27. Duration time.Duration `default:"1ms"`
  28. Float64 float64 `default:"1.23456789"`
  29. String string `default:"hello world"`
  30. Int int `default:"-1" usage:"some number"`
  31. Int64 int64 `default:"-1234567890123456789"`
  32. Uint uint `default:"1"`
  33. Uint64 uint64 `default:"1234567890123456789"`
  34. }
  35. var context Context
  36. require.NotPanics(t, func() {
  37. config.AddOptionsToSet(flags, &context, "")
  38. })
  39. viperConfig := `
  40. bool: false
  41. duration: 1s
  42. float64: -1.23456789
  43. string: pong
  44. int: -2
  45. int64: -9123456789012345678
  46. uint: 2
  47. uint64: 9123456789012345678
  48. `
  49. tmpfile, err := ioutil.TempFile("", "viperconfig-*.yaml")
  50. require.NoError(t, err, "temp file")
  51. defer os.Remove(tmpfile.Name())
  52. if _, err := tmpfile.Write([]byte(viperConfig)); err != nil {
  53. require.NoError(t, err, "write config")
  54. }
  55. require.NoError(t, tmpfile.Close(), "close temp file")
  56. require.NoError(t, viperizeFlags(tmpfile.Name(), "", flags), "read config file")
  57. require.Equal(t,
  58. Context{false, time.Second, -1.23456789, "pong",
  59. -2, -9123456789012345678, 2, 9123456789012345678,
  60. },
  61. context,
  62. "values from viper must match")
  63. }