flags_test.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. Copyright 2016 The Rook Authors. All rights reserved.
  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 flags
  14. import (
  15. "testing"
  16. "github.com/spf13/cobra"
  17. "github.com/stretchr/testify/assert"
  18. )
  19. func TestStringFlags(t *testing.T) {
  20. cmd := &cobra.Command{
  21. Use: "test",
  22. Short: "Creates a test arg",
  23. }
  24. var arg1 string
  25. var arg2 string
  26. cmd.Flags().StringVar(&arg1, "foo", "", "test 1")
  27. cmd.Flags().StringVar(&arg2, "bar", "", "test 2")
  28. // both arguments are missing
  29. err := VerifyRequiredFlags(cmd, []string{"foo", "bar"})
  30. assert.Equal(t, "foo,bar are required for test", err.Error())
  31. // one argument is missing
  32. err = cmd.Flags().Set("foo", "fooval")
  33. assert.NoError(t, err)
  34. err = VerifyRequiredFlags(cmd, []string{"foo", "bar"})
  35. assert.Equal(t, "bar is required for test", err.Error())
  36. // no arguments are missing
  37. err = cmd.Flags().Set("bar", "barval")
  38. assert.NoError(t, err)
  39. err = VerifyRequiredFlags(cmd, []string{"foo", "bar"})
  40. assert.Nil(t, err)
  41. }
  42. func TestGetFlagsAndValues(t *testing.T) {
  43. cmd := &cobra.Command{
  44. Use: "test",
  45. Short: "Creates a test arg",
  46. }
  47. var arg1 string
  48. var arg2 string
  49. cmd.Flags().StringVar(&arg1, "foo-data", "", "test 1")
  50. cmd.Flags().StringVar(&arg2, "bar-secret", "", "test 2")
  51. err := cmd.Flags().Set("foo-data", "1234")
  52. assert.NoError(t, err)
  53. err = cmd.Flags().Set("bar-secret", "mypassword")
  54. assert.NoError(t, err)
  55. // get all flags and their values, providing no filter. all of them should be returned.
  56. flagValues := GetFlagsAndValues(cmd.Flags(), "")
  57. assert.Equal(t, 2, len(flagValues))
  58. assert.Contains(t, flagValues, "--foo-data=1234")
  59. assert.Contains(t, flagValues, "--bar-secret=mypassword")
  60. // get all flags and their values, filtering any flags with "secret" in their name.
  61. // the --bar-secret flag should be redacted.
  62. flagValues = GetFlagsAndValues(cmd.Flags(), "secret")
  63. assert.Equal(t, 2, len(flagValues))
  64. assert.Contains(t, flagValues, "--foo-data=1234")
  65. assert.Contains(t, flagValues, "--bar-secret=*****")
  66. }