Skip to content

[Bug] SetArgs doesn't reset flag value #2079

@levisyin

Description

@levisyin

See following test code. Call SetArgs won't reset flag value, Execute() also won't reset flag value too.

func TestSetArgs(t *testing.T) {
	getCMD := func() *Command {
		cmd := &Command{
			Use: "testcmd",
			RunE: func(cmd *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()

	// step 1
	cmd.SetArgs([]string{
		"--a=true",
	})
	assertNoErr(t, cmd.Execute()) // PASS

	// step 2
	cmd.SetArgs([]string{
		"--b=true",
	})
	t.Log(cmd.Flags().Changed("a")) // true
	assertNoErr(t, cmd.Execute()) // FAIL, output error msg is "a,b,c only one could be true"

	// step 3
	cmd.SetArgs([]string{
		"--c=true",
	})
	assertNoErr(t, cmd.Execute()) // FAIL, output error msg is "a,b,c only one could be true"

	// step 4
	cmd.SetArgs([]string{
		"--a=false",
		"--b=false",
		"--c=true",
	})
	assertNoErr(t, cmd.Execute()) // PASS
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions