Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test(client): wrap cmd.SetArgs to fix bugs for cmd.SetArgs #18876

Merged
merged 5 commits into from
Dec 26, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 14 additions & 17 deletions client/keys/show_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
"github.com/cosmos/cosmos-sdk/crypto/keys/multisig"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
internaltestutil "github.com/cosmos/cosmos-sdk/internal/testutil"
"github.com/cosmos/cosmos-sdk/testutil"
"github.com/cosmos/cosmos-sdk/testutil/testdata"
sdk "github.com/cosmos/cosmos-sdk/types"
Expand Down Expand Up @@ -69,10 +70,10 @@ func Test_runShowCmd(t *testing.T) {

ctx := context.WithValue(context.Background(), client.ClientContextKey, &clientCtx)

cmd.SetArgs([]string{"invalid"})
internaltestutil.SetArgs(cmd, []string{"invalid"})
require.EqualError(t, cmd.ExecuteContext(ctx), "invalid is not a valid name or address: decoding bech32 failed: invalid bech32 string length 7")

cmd.SetArgs([]string{"invalid1", "invalid2"})
internaltestutil.SetArgs(cmd, []string{"invalid1", "invalid2"})
require.EqualError(t, cmd.ExecuteContext(ctx), "invalid1 is not a valid name or address: decoding bech32 failed: invalid separator index 7")

fakeKeyName1 := "runShowCmd_Key1"
Expand All @@ -92,15 +93,15 @@ func Test_runShowCmd(t *testing.T) {
require.NoError(t, err)

// Now try single key
cmd.SetArgs([]string{
internaltestutil.SetArgs(cmd, []string{
fakeKeyName1,
fmt.Sprintf("--%s=%s", flags.FlagKeyringDir, kbHome),
fmt.Sprintf("--%s=", FlagBechPrefix),
fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest),
})
require.EqualError(t, cmd.ExecuteContext(ctx), "invalid Bech32 prefix encoding provided: ")

cmd.SetArgs([]string{
internaltestutil.SetArgs(cmd, []string{
fakeKeyName1,
fmt.Sprintf("--%s=%s", flags.FlagKeyringDir, kbHome),
fmt.Sprintf("--%s=%s", FlagBechPrefix, sdk.PrefixAccount),
Expand All @@ -115,7 +116,7 @@ func Test_runShowCmd(t *testing.T) {
require.NoError(t, err)
addr, err := k.GetAddress()
require.NoError(t, err)
cmd.SetArgs([]string{
internaltestutil.SetArgs(cmd, []string{
addr.String(),
fmt.Sprintf("--%s=%s", flags.FlagKeyringDir, kbHome),
fmt.Sprintf("--%s=%s", FlagBechPrefix, sdk.PrefixAccount),
Expand All @@ -125,7 +126,7 @@ func Test_runShowCmd(t *testing.T) {
require.NoError(t, cmd.ExecuteContext(ctx))

// Now try multisig key - set bech to acc
cmd.SetArgs([]string{
internaltestutil.SetArgs(cmd, []string{
fakeKeyName1, fakeKeyName2,
fmt.Sprintf("--%s=%s", flags.FlagKeyringDir, kbHome),
fmt.Sprintf("--%s=%s", FlagBechPrefix, sdk.PrefixAccount),
Expand All @@ -136,7 +137,7 @@ func Test_runShowCmd(t *testing.T) {

// Now try multisig key duplicate
_, mockOut := testutil.ApplyMockIO(cmd)
cmd.SetArgs([]string{
internaltestutil.SetArgs(cmd, []string{
fakeKeyName1, fakeKeyName1,
fmt.Sprintf("--%s=%s", flags.FlagKeyringDir, kbHome),
fmt.Sprintf("--%s=%s", FlagBechPrefix, sdk.PrefixAccount),
Expand All @@ -146,7 +147,7 @@ func Test_runShowCmd(t *testing.T) {
require.NoError(t, cmd.ExecuteContext(ctx))
require.Contains(t, mockOut.String(), fmt.Sprintf("WARNING: duplicate keys found: %s", fakeKeyName1))

cmd.SetArgs([]string{
internaltestutil.SetArgs(cmd, []string{
fakeKeyName1, fakeKeyName2,
fmt.Sprintf("--%s=%s", flags.FlagKeyringDir, kbHome),
fmt.Sprintf("--%s=%s", FlagBechPrefix, sdk.PrefixAccount),
Expand All @@ -156,7 +157,7 @@ func Test_runShowCmd(t *testing.T) {
require.NoError(t, cmd.ExecuteContext(ctx))

// Now try multisig key - set bech to acc + threshold=2
cmd.SetArgs([]string{
internaltestutil.SetArgs(cmd, []string{
fakeKeyName1, fakeKeyName2,
fmt.Sprintf("--%s=%s", flags.FlagKeyringDir, kbHome),
fmt.Sprintf("--%s=acc", FlagBechPrefix),
Expand All @@ -166,7 +167,7 @@ func Test_runShowCmd(t *testing.T) {
})
require.EqualError(t, cmd.ExecuteContext(ctx), "the device flag (-d) can only be used for accounts stored in devices")

cmd.SetArgs([]string{
internaltestutil.SetArgs(cmd, []string{
fakeKeyName1, fakeKeyName2,
fmt.Sprintf("--%s=%s", flags.FlagKeyringDir, kbHome),
fmt.Sprintf("--%s=val", FlagBechPrefix),
Expand All @@ -176,7 +177,7 @@ func Test_runShowCmd(t *testing.T) {
})
require.EqualError(t, cmd.ExecuteContext(ctx), "the device flag (-d) can only be used for accounts")

cmd.SetArgs([]string{
internaltestutil.SetArgs(cmd, []string{
fakeKeyName1, fakeKeyName2,
fmt.Sprintf("--%s=%s", flags.FlagKeyringDir, kbHome),
fmt.Sprintf("--%s=val", FlagBechPrefix),
Expand All @@ -187,22 +188,18 @@ func Test_runShowCmd(t *testing.T) {
})
require.EqualError(t, cmd.ExecuteContext(ctx), "the device flag (-d) can only be used for addresses not pubkeys")

cmd.SetArgs([]string{
internaltestutil.SetArgs(cmd, []string{
fakeKeyName1,
fmt.Sprintf("--%s=%s", flags.FlagKeyringDir, kbHome),
fmt.Sprintf("--%s=true", FlagAddress),
fmt.Sprintf("--%s=true", flagQRCode),
// we have to reset following flags as they were set to true above, and won't be auto reset to false if we skip to specify these flags.
// Note: this maybe a bug about spf13/cobra as cmd.flags's value won't be reset by changing cmd.args with cmd.SetArgs.
fmt.Sprintf("--%s=false", FlagDevice),
fmt.Sprintf("--%s=false", FlagPublicKey),
fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest),
})

// try fetch by name
require.NoError(t, cmd.ExecuteContext(ctx))

cmd.SetArgs([]string{
internaltestutil.SetArgs(cmd, []string{
fakeKeyName1, fakeKeyName2,
fmt.Sprintf("--%s=%s", flags.FlagKeyringDir, kbHome),
fmt.Sprintf("--%s=true", FlagAddress),
Expand Down
22 changes: 22 additions & 0 deletions internal/testutil/cmd.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package testutil

import (
"fmt"

"github.com/spf13/cobra"
"github.com/spf13/pflag"
)

// SetArgs sets arguments for the command. It is desired to replace the cmd.SetArgs in all test case, as cmd.SetArgs doesn't reset flag value as expected.
//
// see https://github.com/spf13/cobra/issues/2079#issuecomment-1867991505 for more detail info
func SetArgs(cmd *cobra.Command, args []string) {
if cmd.Flags().Parsed() {
cmd.Flags().Visit(func(pf *pflag.Flag) {
if err := pf.Value.Set(pf.DefValue); err != nil {
panic(fmt.Errorf("reset argument[%s] value error %v", pf.Name, err))
}
})
}
cmd.SetArgs(args)
}
levisyin marked this conversation as resolved.
Show resolved Hide resolved
119 changes: 119 additions & 0 deletions internal/testutil/cmd_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
package testutil_test

import (
"fmt"
"testing"

"github.com/spf13/cobra"
"github.com/stretchr/testify/require"

"github.com/cosmos/cosmos-sdk/internal/testutil"
)

// TestSetArgsWithOriginalMethod is used to illustrate cobra.Command.SetArgs won't reset args as expected
func TestSetArgsWithOriginalMethod(t *testing.T) {
getCMD := func() *cobra.Command {
cmd := &cobra.Command{
Use: "testcmd",
RunE: func(cmd *cobra.Command, args []string) error {
a, _ := cmd.Flags().GetBool("a")
b, _ := cmd.Flags().GetBool("b")
c, _ := cmd.Flags().GetBool("c")
switch {
case a && b, a && c, b && c:
return fmt.Errorf("a,b,c only one could be true")
}
return nil
},
}
f := cmd.Flags()
f.BoolP("a", "a", false, "a,b,c only one could be true")
f.BoolP("b", "b", false, "a,b,c only one could be true")
f.Bool("c", false, "a,b,c only one could be true")
return cmd
}

cmd := getCMD()

cmd.SetArgs([]string{
"testcmd",
"--a=true",
})
require.NoError(t, cmd.Execute())

// This call to cmd.SetArgs is expected to set only the 'b' flag. However, due to the bug, the 'a' flag remains set from the previous call to cmd.SetArgs, leading to an error.
cmd.SetArgs([]string{
"testcmd",
"--b=true",
})
require.True(t, cmd.Flags().Changed("a"))
levisyin marked this conversation as resolved.
Show resolved Hide resolved
require.Error(t, cmd.Execute())

// This call to cmd.SetArgs is expected to set only the 'c' flag. However, the 'a' and 'b' flags remain set from the previous calls, causing an unexpected error.
cmd.SetArgs([]string{
"testcmd",
"--c=true",
})
require.Error(t, cmd.Execute())

// To work around the bug, we must explicitly reset the 'a' and 'b' flags to false, even though we only want to set the 'c' flag to true.
cmd.SetArgs([]string{
"testcmd",
"--a=false",
"--b=false",
"--c=true",
})
require.NoError(t, cmd.Execute())
}

func TestSetArgsWithWrappedMethod(t *testing.T) {
getCMD := func() *cobra.Command {
cmd := &cobra.Command{
Use: "testcmd",
RunE: func(cmd *cobra.Command, args []string) error {
a, _ := cmd.Flags().GetBool("a")
b, _ := cmd.Flags().GetBool("b")
c, _ := cmd.Flags().GetBool("c")
switch {
case a && b, a && c, b && c:
return fmt.Errorf("a,b,c only one could be true")
}
return nil
},
}
f := cmd.Flags()
f.BoolP("a", "a", false, "a,b,c only one could be true")
f.BoolP("b", "b", false, "a,b,c only one could be true")
f.Bool("c", false, "a,b,c only one could be true")
return cmd
}

cmd := getCMD()

testutil.SetArgs(cmd, []string{
"testcmd",
"--a=true",
})
require.NoError(t, cmd.Execute())

testutil.SetArgs(cmd, []string{
"testcmd",
"--b=true",
})
require.True(t, cmd.Flags().Changed("a"))
require.NoError(t, cmd.Execute())

testutil.SetArgs(cmd, []string{
"testcmd",
"--c=true",
})
require.NoError(t, cmd.Execute())

testutil.SetArgs(cmd, []string{
"testcmd",
"--a=false",
"--b=false",
"--c=true",
})
require.NoError(t, cmd.Execute())
levisyin marked this conversation as resolved.
Show resolved Hide resolved
}
Loading