douji8017 2018-04-16 02:35
浏览 70
已采纳

眼镜蛇:如何在测试中以编程方式设置标志

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?

  • 写回答

1条回答 默认 最新

  • dppb79372 2018-06-15 18:03
    关注

    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()
    
    ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?