helpers_test.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. Copyright 2016 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 componentconfig
  14. import (
  15. "strings"
  16. "testing"
  17. "github.com/spf13/pflag"
  18. )
  19. func TestIPVar(t *testing.T) {
  20. defaultIP := "0.0.0.0"
  21. cases := []struct {
  22. argc string
  23. expectErr bool
  24. expectVal string
  25. }{
  26. {
  27. argc: "blah --ip=1.2.3.4",
  28. expectVal: "1.2.3.4",
  29. },
  30. {
  31. argc: "blah --ip=1.2.3.4a",
  32. expectErr: true,
  33. expectVal: defaultIP,
  34. },
  35. }
  36. for _, c := range cases {
  37. fs := pflag.NewFlagSet("blah", pflag.PanicOnError)
  38. ip := defaultIP
  39. fs.Var(IPVar{&ip}, "ip", "the ip")
  40. var err error
  41. func() {
  42. defer func() {
  43. if r := recover(); r != nil {
  44. err = r.(error)
  45. }
  46. }()
  47. fs.Parse(strings.Split(c.argc, " "))
  48. }()
  49. if c.expectErr && err == nil {
  50. t.Errorf("did not observe an expected error")
  51. continue
  52. }
  53. if !c.expectErr && err != nil {
  54. t.Errorf("observed an unexpected error")
  55. continue
  56. }
  57. if c.expectVal != ip {
  58. t.Errorf("unexpected ip: expected %q, saw %q", c.expectVal, ip)
  59. }
  60. }
  61. }