github.com/nats-io/nsc@v0.0.0-20221206222106-35db9400b257/cmd/listeditor_test.go (about) 1 /* 2 * Copyright 2018-2019 The NATS 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 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 package cmd 17 18 import ( 19 "testing" 20 21 "github.com/spf13/cobra" 22 "github.com/stretchr/testify/require" 23 ) 24 25 func listEditorCmd(params *ListEditorParam) *cobra.Command { 26 cmd := &cobra.Command{ 27 Use: "test", 28 RunE: func(cmd *cobra.Command, args []string) error { 29 if InteractiveFlag { 30 return params.Edit() 31 } 32 return params.Valid() 33 }, 34 } 35 cmd.Flags().StringSliceVarP(¶ms.Values, params.FlagName, "", nil, "") 36 return cmd 37 } 38 39 func TestListEditorParams(t *testing.T) { 40 var p ListEditorParam 41 p.FlagName = "test" 42 validatorCalled := false 43 p.ValidatorFn = func(string) error { 44 validatorCalled = true 45 return nil 46 } 47 cmd := listEditorCmd(&p) 48 _, _, err := ExecuteCmd(cmd, "--test", "a", "--test", "b") 49 require.NoError(t, err) 50 require.True(t, validatorCalled) 51 require.Len(t, p.Values, 2) 52 require.EqualValues(t, p.Values, []string{"a", "b"}) 53 } 54 55 func TestListEditorParams_Interactive(t *testing.T) { 56 var p ListEditorParam 57 p.FlagName = "test" 58 validatorCalled := false 59 p.ValidatorFn = func(string) error { 60 validatorCalled = true 61 return nil 62 } 63 cmd := listEditorCmd(&p) 64 _, _, err := ExecuteInteractiveCmd(cmd, []interface{}{true, "x", true, "y", false}) 65 require.NoError(t, err) 66 require.True(t, validatorCalled) 67 require.Len(t, p.Values, 2) 68 require.EqualValues(t, p.Values, []string{"x", "y"}) 69 } 70 71 func TestListEditorParams_InteractiveEdit(t *testing.T) { 72 p := &ListEditorParam{} 73 p.FlagName = "test" 74 validatorCalled := false 75 p.ValidatorFn = func(string) error { 76 validatorCalled = true 77 return nil 78 } 79 cmd := listEditorCmd(p) 80 _, _, err := ExecuteInteractiveCmd(cmd, []interface{}{"aa", "bb", true, "x", true, "y", false}, "--test", "a", "--test", "b") 81 require.NoError(t, err) 82 require.True(t, validatorCalled) 83 require.Len(t, p.Values, 4) 84 require.EqualValues(t, p.Values, []string{"aa", "bb", "x", "y"}) 85 require.EqualValues(t, p.GetValues(), []string{"aa", "bb", "x", "y"}) 86 87 t.Log() 88 }