doushu2699 2016-03-06 13:03
浏览 274
已采纳

Cobra + Viper Golang如何测试子命令?

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.

  • 写回答

2条回答 默认 最新

  • dongxian6715 2016-03-06 14:08
    关注

    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).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • doukun5339 2019-07-23 06:34
    关注

    i have found an easy way to test commands with multiple level sub commands, it is not professional but it worked well.

    assume we have a command like this

    RootCmd = &cobra.Command{
                Use:   "cliName",
                Short: "Desc",
        }
    
    SubCmd = &cobra.Command{
                Use:   "subName",
                Short: "Desc",
        }
    
    subOfSubCmd = &cobra.Command{
                Use:   "subOfSub",
                Short: "Desc",
                Run: Exec
        }
    
    //commands relationship
    RootCmd.AddCommand(SubCmd)
    SubCmd.AddCommand(subOfSubCmd)
    

    When testing the subOfSubCmd we can do this way:

    func TestCmd(t *testing.T) {
    convey.Convey("test cmd", t, func() {
        args := []string{"subName", "subOfSub"}
        RootCmd.SetArgs(args)
        RootCmd.Execute()
        })
    }
    
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Latex算法流程图行号自定义
  • ¥15 关于#python#的问题:我在自己的电脑上运行起来总是报错,希望能给我一个详细的教程,(开发工具-github)
  • ¥40 基于51单片机实现球赛计分器功能
  • ¥15 cs2游戏画面卡住,应用程序sid与指挥者sid不匹配
  • ¥15 实验七:Pandas要有实验截图和代码
  • ¥15 TypeError: Make sure that the iterable only contains strings.
  • ¥35 电脑放图书馆,这是被黑了吗
  • ¥15 等高线中数据取消科学计数法
  • ¥15 Qt播放10路ffmpeg 视频流
  • ¥15 如何利用闲置机械硬盘变现