Cli: How to test the CLI app properly/easily?

Created on 30 Mar 2018  路  2Comments  路  Source: urfave/cli

Hi,

I have unit tests for all functionality including different behaviour flags (settable via cli), so I thought, I could easily use my "Example"-based tests to get the "should-be" output and the output of the compiled cli-based binary and somehow only write the run command in the comment above the "Example"-test source code, parse it and run the binary test file and compare the output.

With this idea in mind, is something like this this possible? I most certainly do not want to repeat myself.

Most helpful comment

You can set the flags like this:

args := os.Args[0:1]
args = append(args, "-flag=whatever")
err = app.Run(args)

Structure your code like this:

func run(args []string) {
    app := cli.NewApp()
    cli.Uint64Flag{
        Name:  "foo",
        Usage: "flag",
    },
    // Configure stuff
    err = app.Run(args)
    if err != nil {
         os.Exit(1)
    }
}

func main() {
    run(os.Args)
}

func Test(t *testing.T){
   args := os.Args[0:1] // Name of the program.
   args = append(args, "-foo=100") // Append a flag
   run(args)
}

All 2 comments

You can set the flags like this:

args := os.Args[0:1]
args = append(args, "-flag=whatever")
err = app.Run(args)

Structure your code like this:

func run(args []string) {
    app := cli.NewApp()
    cli.Uint64Flag{
        Name:  "foo",
        Usage: "flag",
    },
    // Configure stuff
    err = app.Run(args)
    if err != nil {
         os.Exit(1)
    }
}

func main() {
    run(os.Args)
}

func Test(t *testing.T){
   args := os.Args[0:1] // Name of the program.
   args = append(args, "-foo=100") // Append a flag
   run(args)
}

It sounds like we could use a wiki page on testing 馃 but since there's a good answer here, I think I'll close this

Was this page helpful?
0 / 5 - 0 ratings

Related issues

lvbin2012 picture lvbin2012  路  20Comments

cab picture cab  路  18Comments

odiferousmint picture odiferousmint  路  14Comments

lynncyrin picture lynncyrin  路  22Comments

johnwyles picture johnwyles  路  17Comments