【问题标题】:How to call SetOut() on subcommands in Cobra?如何在 Cobra 的子命令上调用 SetOut()?
【发布时间】:2021-03-26 00:48:42
【问题描述】:

我正在尝试测试用 Cobra 编写的 CLI 应用程序,特别是测试子命令是否正确写入 STDOUT。为此,我尝试将输出从 STDOUT 重定向到我的缓冲区。不幸的是,无论出于何种原因,SetOut() 函数在通过调用 Commands() 获得的子命令上的行为均不符合预期。

如何在 Cobra 的子命令中正确调用 SetOut()?

这是我的代码:

package cmd

import (
    "os"
    "testing"
    "bytes"
    "io/ioutil"
    "github.com/spf13/cobra"
)

func NewCmd() *cobra.Command {
    cmd := &cobra.Command{}
    cmd.AddCommand(NewChildCmd())
    return cmd
}

func NewChildCmd() *cobra.Command {
    cmd := &cobra.Command{
        Use:   "child",
        Run: func(cmd *cobra.Command, args []string) {
                os.Stdout.WriteString("TEST\n")
        },
    }
    return cmd
}

func TestChild(t *testing.T) {
    cmd := NewCmd()
    buffer := new(bytes.Buffer)

    subCommands := cmd.Commands()
    for i := range subCommands {
        subCommands[i].SetOut(buffer)
    }

    cmd.SetOut(buffer)
    cmd.SetArgs([]string{"child"})
    cmd.Execute()
    out, err := ioutil.ReadAll(buffer)
    if err != nil {
        t.Fatal(err)
    }
    if string(out) != "child" {
        t.Fatalf("Expected \"TEST\", got \"%s\"", string(out))
    }
}

这是测试输出:

TEST
--- FAIL: TestChild (0.00s)
    cmd/my_test.go:44: Expected "TEST", got ""
FAIL
FAIL    cmd 0.004s
FAIL

【问题讨论】:

    标签: go go-cobra cobra


    【解决方案1】:

    显然,SetOut() 无法更改直接发送到 os.Stdout 的输出,而是必须使用 cmd.Println(),然后一切正常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-15
      • 1970-01-01
      • 1970-01-01
      • 2018-04-18
      • 1970-01-01
      • 1970-01-01
      • 2021-12-01
      • 1970-01-01
      相关资源
      最近更新 更多