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

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog