繁体   English   中英

如何在 Cobra 的子命令上调用 SetOut()?

[英]How to call SetOut() on subcommands in Cobra?

我正在尝试测试用 Cobra 编写的 CLI 应用程序,特别是测试子命令是否正确写入 STDOUT。 为此,我尝试将 output 从 STDOUT 重定向到我的缓冲区。 不幸的是,无论出于何种原因,SetOut() function 在通过调用 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))
    }
}

这是测试 output:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM