gotestingcommand-line-interfacego-cobra

How to set flags programmatically in tests with Cobra?


I'm using cobra to build a CLI and want to simulate a command being run with different sets of options/flags. I've been trying to figure out how I can use the cobra APIs to set flags within my test but haven't really gotten it yet.

I have this:

// NewFooCmd returns a cobra.Command fitted to print output to the buffer for easier testing.
buf := &bytes.Buffer{}
cmd := package.NewFooCmd(buf)

cmd.Execute()

// some validations on the content of buf

So far the closest thing I've found is:

cmd.Flags().Set(name string, value string)

...but this doesn't seem right because while the names of flags are all strings, they don't all take strings as values. Also it just doesn't seem to work even if I have an int flag and pass string(1).

Is there something simple I'm missing here?


Solution

  • You can use the (c *Command) SetArgs(a []string) function for this. The fact that some of your arguments are integers or booleans doesn't matter here - after all, that's what a user will be entering on the command line!

    The (c *Command) DebugFlags() function can be used when you're developing the test to ensure that the flags you're passing are being interperted properly, too.

    My integration tests with Cobra tend to end up looking like this:

    ...
    
    cmd := cli.RootCmd()
    buf := new(bytes.Buffer)
    cmd.SetOutput(buf)
    cmd.SetArgs([]string{
        "--some-flag",
        fmt.Sprintf("--some-string=%s", value),
        fmt.Sprintf("--some-integer=%d", integer),
    })
    err := cmd.Execute()
    
    ...