github.com/Finschia/finschia-sdk@v0.48.1/client/cmd_test.go (about) 1 package client_test 2 3 import ( 4 "context" 5 "fmt" 6 "testing" 7 8 "github.com/spf13/cobra" 9 "github.com/stretchr/testify/require" 10 11 "github.com/Finschia/finschia-sdk/client" 12 "github.com/Finschia/finschia-sdk/client/flags" 13 "github.com/Finschia/finschia-sdk/testutil" 14 ) 15 16 func TestValidateCmd(t *testing.T) { 17 // setup root and subcommands 18 rootCmd := &cobra.Command{ 19 Use: "root", 20 } 21 queryCmd := &cobra.Command{ 22 Use: "query", 23 } 24 rootCmd.AddCommand(queryCmd) 25 26 // command being tested 27 distCmd := &cobra.Command{ 28 Use: "distr", 29 DisableFlagParsing: true, 30 SuggestionsMinimumDistance: 2, 31 } 32 queryCmd.AddCommand(distCmd) 33 34 commissionCmd := &cobra.Command{ 35 Use: "commission", 36 } 37 distCmd.AddCommand(commissionCmd) 38 39 tests := []struct { 40 reason string 41 args []string 42 wantErr bool 43 }{ 44 {"misspelled command", []string{"COMMISSION"}, true}, 45 {"no command provided", []string{}, false}, 46 {"help flag", []string{"COMMISSION", "--help"}, false}, 47 {"shorthand help flag", []string{"COMMISSION", "-h"}, false}, 48 {"flag only, no command provided", []string{"--gas", "1000atom"}, false}, 49 {"flag and misspelled command", []string{"--gas", "1000atom", "COMMISSION"}, true}, 50 } 51 52 for _, tt := range tests { 53 err := client.ValidateCmd(distCmd, tt.args) 54 require.Equal(t, tt.wantErr, err != nil, tt.reason) 55 } 56 } 57 58 func TestSetCmdClientContextHandler(t *testing.T) { 59 initClientCtx := client.Context{}.WithHomeDir("/foo/bar").WithChainID("test-chain").WithKeyringDir("/foo/bar") 60 61 newCmd := func() *cobra.Command { 62 c := &cobra.Command{ 63 PreRunE: func(cmd *cobra.Command, args []string) error { 64 return client.SetCmdClientContextHandler(initClientCtx, cmd) 65 }, 66 RunE: func(cmd *cobra.Command, _ []string) error { 67 _, err := client.GetClientTxContext(cmd) 68 return err 69 }, 70 } 71 72 c.Flags().String(flags.FlagChainID, "", "network chain ID") 73 74 return c 75 } 76 77 testCases := []struct { 78 name string 79 expectedContext client.Context 80 args []string 81 }{ 82 { 83 "no flags set", 84 initClientCtx, 85 []string{}, 86 }, 87 { 88 "flags set", 89 initClientCtx.WithChainID("new-chain-id"), 90 []string{ 91 fmt.Sprintf("--%s=new-chain-id", flags.FlagChainID), 92 }, 93 }, 94 } 95 96 for _, tc := range testCases { 97 tc := tc 98 99 t.Run(tc.name, func(t *testing.T) { 100 ctx := context.WithValue(context.Background(), client.ClientContextKey, &client.Context{}) 101 102 cmd := newCmd() 103 _ = testutil.ApplyMockIODiscardOutErr(cmd) 104 cmd.SetArgs(tc.args) 105 106 require.NoError(t, cmd.ExecuteContext(ctx)) 107 108 clientCtx := client.GetClientContextFromCmd(cmd) 109 require.Equal(t, tc.expectedContext, clientCtx) 110 }) 111 } 112 }