我正在尝试测试用 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
显然,SetOut() 无法更改直接发送到 os.Stdout 的输出,而是必须使用 cmd.Println(),然后一切都会按预期进行。