Skip to content

Instantly share code, notes, and snippets.

@micheam
Last active October 17, 2022 16:30
Show Gist options
  • Save micheam/507a792297381e99e5200c95156ddd8f to your computer and use it in GitHub Desktop.
Save micheam/507a792297381e99e5200c95156ddd8f to your computer and use it in GitHub Desktop.
[Go] How to test urfave/cli command
module how/to/test/urfave/cli/command
go 1.19
require github.com/urfave/cli/v2 v2.20.2
require (
github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 // indirect
)
package main
import (
"fmt"
"os"
"github.com/urfave/cli/v2"
)
func main() {
err := NewApp().Run(os.Args)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func NewApp() *cli.App {
app := cli.NewApp()
app.Name = "hello-world"
app.Action = func(c *cli.Context) error {
fmt.Fprintf(c.App.Writer, "Hello, World!")
return nil
}
app.Commands = []*cli.Command{
Greeting,
}
return app
}
var Greeting *cli.Command = &cli.Command{
Name: "greet",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "name",
Aliases: []string{"n"},
Value: "nameless",
},
},
Action: func(c *cli.Context) error {
fmt.Fprintf(c.App.Writer, "Hello, %s!!", c.String("name"))
return nil
},
}
package main
import (
"bytes"
"flag"
"testing"
"github.com/urfave/cli/v2"
)
func TestNewApp(t *testing.T) {
var output bytes.Buffer // capture output
app := NewApp()
app.Writer = &output
set := flag.NewFlagSet("test", 0)
_ = set.Parse([]string{"foo", "bar"})
// Exercise
err := app.Run([]string{"-foo"})
// Verify
if err != nil {
t.Error(err)
t.FailNow()
}
expected := "Hello, World!"
if output.String() != expected {
t.Errorf("expected '%s' but got '%s'", expected, output.String())
}
}
func TestApp_Greeting(t *testing.T) {
t.Run("with name", func(t *testing.T) {
var output bytes.Buffer // capture output
app := NewApp()
app.Writer = &output
cCtx := cli.NewContext(app, nil, nil)
args := []string{"greet", "--name", "foo"}
// Exercise
err := app.Command("greet").Run(cCtx, args...)
// Verify
if err != nil {
t.Error(err)
t.FailNow()
}
expected := "Hello, foo!!"
if output.String() != expected {
t.Errorf("expected '%s' but got '%s'", expected, output.String())
}
})
t.Run("nameless", func(t *testing.T) {
var output bytes.Buffer // capture output
app := NewApp()
app.Writer = &output
cCtx := cli.NewContext(app, nil, nil)
args := []string{"greet"}
// Exercise
err := app.Command("greet").Run(cCtx, args...)
// Verify
if err != nil {
t.Error(err)
t.FailNow()
}
expected := "Hello, nameless!!"
if output.String() != expected {
t.Errorf("expected '%s' but got '%s'", expected, output.String())
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment