go - 如何在 Cobra 的子命令上调用 SetOut()?
问题描述
我正在尝试测试用 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(),然后一切都按预期工作。
推荐阅读
- go - 无法处理在 Windows (ImageSearch.dll) 上返回 char* 的自定义 dll
- laravel - Laravel Auth 使用自定义消息重置密码
- react-native - 如何在 android 的窗口管理器视图上启动 react-native
- javascript - 第一次失败后开玩笑停止测试套件
- delphi - Delphi 发送 HTTP GET 请求而不等待服务器响应
- postgresql - Pl/Pgsql,将数组参数传递给 INSERT
- netsuite - Netsuite 记录器字符串太长,无法显示在详细信息字段中
- rest - HTTP GET 请求的有效负载正文
- eclipse - 添加按钮以在 Eclipse 中注释掉代码
- android - Arraylist :使用未经检查或不安全的操作