【问题标题】:Writing tests for cli input为 cli 输入编写测试
【发布时间】:2018-07-04 19:51:50
【问题描述】:

我有一个带有使用标志的 cli 的小型 Go 应用程序,我被要求让它更可测试。

我的应用程序在命令行上被调用,例如 deploy.exe <task> <command> -tenant tenant_name -validate -package "c:\some dir\\"

基于 taskcommand 调用不同的执行路径,最终调用驻留在另一个包中的函数,如下所示:

if command == "db" {
     dbhelper.RunDBCmds(*tenant, *validate, *package)
}

我需要为标志解析编写单元测试,而不是在最后调用实际函数。

我对 Go 还很陌生,我正在努力弄清楚如何实现这一点。我考虑过将我的 Os.Args() 和 Flag 解析添加到一个函数中,该函数接受输入并输出一个指向 RunDBCmds(*tenant, ...) 函数的指针。但是,我只是不确定我能否完成返回指向函数的指针。

如果我能在不实际调用函数的情况下使我的代码更具可测试性,我将不胜感激。

【问题讨论】:

标签: unit-testing go


【解决方案1】:

如果你所有的任务/命令都有不同的标志集,我最终会引入某种命令抽象。最好的例子可以在 Go 源代码中找到:

base.Commands = []*base.Command{
        work.CmdBuild,
        clean.CmdClean,
        doc.CmdDoc,
        envcmd.CmdEnv,
        bug.CmdBug,
        fix.CmdFix,
        //...
}

每个命令都可以有自己的标志。FlagSet 来解析特定命令的标志:

// A Command is an implementation of a go command
// like go build or go fix.
type Command struct {
    // Run runs the command.
    // The args are the arguments after the command name.
    Run func(cmd *Command, args []string)

    // UsageLine is the one-line usage message.
    // The first word in the line is taken to be the command name.
    UsageLine string

    // Short is the short description shown in the 'go help' output.
    Short string

    // Long is the long message shown in the 'go help <this-command>' output.
    Long string

    // Flag is a set of flags specific to this command.
    Flag flag.FlagSet

    // CustomFlags indicates that the command will do its own
    // flag parsing.
    CustomFlags bool
}

使用这种方法,您可以将命令的标志解析与执行分开。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-06
    • 1970-01-01
    • 1970-01-01
    • 2012-09-10
    • 2017-11-22
    • 2017-07-24
    • 2011-02-23
    • 1970-01-01
    相关资源
    最近更新 更多