Cobra + Viper Golang如何测试子命令? [英] Cobra + Viper Golang How to test subcommands?

查看:506
本文介绍了Cobra + Viper Golang如何测试子命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个Go应用程序。目前为止这么好,但现在我正在将Wercker作为CI工具并开始关注测试。但是我的应用很大程度上依赖于Cobra / Viper配置/ flags / environment_variables方案,并且我不知道如何在运行测试套件之前正确初始化Viper值。任何帮助将非常感激。

解决方案

当我使用Cobra / Viper或任何其他CLI帮助组合时,我的做法是使用CLI工具运行一个函数,其唯一目的是获取参数并将其传递给另一个将执行实际工作的方法。



这是一个使用眼镜蛇的简短(愚蠢的)例子:

 包主要

导入(
fmt
os

github.com/spf13/cobra


func main(){
var Cmd =& cobra.Command {
使用:boom,
Short:爆炸所有东西!,
运行:Boom,
}

if err:= Cmd.Execute(); err!= nil {
fmt.Println(err)
os.Exit(-1)
}
}

func Boom(cmd * cobra .command,args [] string){
boom(args ...)
}

func boom(args ... string){
for _, arg:= range args {
println(boom+ arg)
}
}

这里, Boom 函数很难测试,但是 boom 很容易。

你可以看到这个这里(和相应的测试此处)。


I am developing an web app with Go. So far so good, but now I am integrating Wercker as a CI tool and started caring about testing. But my app relies heavily on Cobra/Viper configuration/flags/environment_variables scheme, and I do not know how to properly init Viper values before running my test suite. Any help would be much appreciated.

解决方案

When I use Cobra/Viper or any other combination of CLI helpers, my way of doing this is to have the CLI tool run a function whose sole purpose will be to get arguments and pass them to another method who will do the actual work.

Here is a short (and dumb) example using Cobra :

package main

import (
        "fmt"
        "os"

        "github.com/spf13/cobra"
)

func main() {
        var Cmd = &cobra.Command{
                Use:   "boom",
                Short: "Explode all the things!",
                Run:   Boom,
        }

        if err := Cmd.Execute(); err != nil {
                fmt.Println(err)
                os.Exit(-1)
        }
}

func Boom(cmd *cobra.Command, args []string) {
        boom(args...)
}

func boom(args ...string) {
        for _, arg := range args {
                println("boom " + arg)
        }
}

Here, the Boom function is hard to test, but the boom one is easy.

You can see another (non-dumb) example of this here (and the correspond test here).

这篇关于Cobra + Viper Golang如何测试子命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆