func TestApp_ParseSliceFlagsWithMissingValue(t *testing.T) { var parsedIntSlice []int var parsedStringSlice []string app := cli.NewApp() command := cli.Command{ Name: "cmd", Flags: []cli.Flag{ cli.IntSliceFlag{Name: "a", Usage: "set numbers"}, cli.StringSliceFlag{Name: "str", Usage: "set strings"}, }, Action: func(c *cli.Context) { parsedIntSlice = c.IntSlice("a") parsedStringSlice = c.StringSlice("str") }, } app.Commands = []cli.Command{command} app.Run([]string{"", "cmd", "my-arg", "-a", "2", "-str", "A"}) var expectedIntSlice = []int{2} var expectedStringSlice = []string{"A"} if parsedIntSlice[0] != expectedIntSlice[0] { t.Errorf("%v does not match %v", parsedIntSlice[0], expectedIntSlice[0]) } if parsedStringSlice[0] != expectedStringSlice[0] { t.Errorf("%v does not match %v", parsedIntSlice[0], expectedIntSlice[0]) } }
func TestListHandleSingle(t *testing.T) { app := cli.NewApp() flagset := flag.NewFlagSet("flags", 1) flagset.String("stack-name", "", "") flagset.String("stack-id", "", "") flagset.Set("stack-name", "stack1") flagset.Set("stack-id", "id1") c := cli.NewContext(app, flagset, nil) cmd := &commandList{ Ctx: &handler.Context{ CLIContext: c, }, } expected := &handler.Resource{ Params: ¶msList{ stackName: "stack1", stackID: "id1", }, } actual := &handler.Resource{ Params: ¶msList{}, } err := cmd.HandleSingle(actual) th.AssertNoErr(t, err) th.AssertEquals(t, expected.Params.(*paramsList).stackName, actual.Params.(*paramsList).stackName) th.AssertEquals(t, expected.Params.(*paramsList).stackID, actual.Params.(*paramsList).stackID) }
func TestGenerateExecute(t *testing.T) { th.SetupHTTP() defer th.TeardownHTTP() th.Mux.HandleFunc("/os-keypairs", func(w http.ResponseWriter, r *http.Request) { w.Header().Add("Content-Type", "application/json") fmt.Fprintf(w, `{"keypair":{}}`) }) app := cli.NewApp() flagset := flag.NewFlagSet("flags", 1) flagset.String("output", "json", "") c := cli.NewContext(app, flagset, nil) cmd := &commandGenerate{ Ctx: &handler.Context{ CLIContext: c, ServiceClient: client.ServiceClient(), }, } actual := &handler.Resource{ Params: ¶msGenerate{ opts: &osKeypairs.CreateOpts{ Name: "keypair1Name", }, }, } cmd.Execute(actual) th.AssertNoErr(t, actual.Err) }
func TestCreateHandleFlags(t *testing.T) { app := cli.NewApp() flagset := flag.NewFlagSet("flags", 1) flagset.String("metadata", "", "") flagset.String("container-read", "", "") flagset.String("container-write", "", "") flagset.Set("metadata", "key=val,foo=bar") c := cli.NewContext(app, flagset, nil) cmd := &commandCreate{ Ctx: &handler.Context{ CLIContext: c, }, } expected := &handler.Resource{ Params: ¶msCreate{ opts: containers.CreateOpts{ Metadata: map[string]string{ "key": "val", "foo": "bar", }, }, }, } actual := &handler.Resource{} err := cmd.HandleFlags(actual) th.AssertNoErr(t, err) th.AssertDeepEquals(t, expected.Params.(*paramsCreate).opts, actual.Params.(*paramsCreate).opts) }
func TestApp_DefaultStdout(t *testing.T) { app := cli.NewApp() if app.Writer != os.Stdout { t.Error("Default output writer not set.") } }
func Example() { app := cli.NewApp() app.Name = "todo" app.Usage = "task list on the command line" app.Commands = []cli.Command{ { Name: "add", Aliases: []string{"a"}, Usage: "add a task to the list", Action: func(c *cli.Context) { println("added task: ", c.Args().First()) }, }, { Name: "complete", Aliases: []string{"c"}, Usage: "complete a task on the list", Action: func(c *cli.Context) { println("completed task: ", c.Args().First()) }, }, } app.Run(os.Args) }
func ExampleAppBashComplete() { // set args for examples sake os.Args = []string{"greet", "--generate-bash-completion"} app := cli.NewApp() app.Name = "greet" app.EnableBashCompletion = true app.Commands = []cli.Command{ { Name: "describeit", Aliases: []string{"d"}, Usage: "use it to see a description", Description: "This is how we describe describeit the function", Action: func(c *cli.Context) { fmt.Printf("i like to describe things") }, }, { Name: "next", Usage: "next example", Description: "more stuff to see when generating bash completion", Action: func(c *cli.Context) { fmt.Printf("the next example") }, }, } app.Run(os.Args) // Output: // describeit // d // next // help // h }
func TestListHandleFlags(t *testing.T) { app := cli.NewApp() flagset := flag.NewFlagSet("flags", 1) flagset.String("image", "", "") flagset.String("flavor", "", "") flagset.String("name", "", "") flagset.String("status", "", "") flagset.String("marker", "", "") flagset.Set("image", "13ba-75c0-4483-acf9") flagset.Set("flavor", "1234-b95f-ac5b-cd23") flagset.Set("name", "server*") flagset.Set("status", "AVAILABLE") flagset.Set("marker", "1fd3-4f9f-44df-1b5c") c := cli.NewContext(app, flagset, nil) cmd := &commandList{ Ctx: &handler.Context{ CLIContext: c, }, } expected := &handler.Resource{ Params: ¶msList{ opts: &osServers.ListOpts{ Image: "13ba-75c0-4483-acf9", Flavor: "1234-b95f-ac5b-cd23", Name: "server*", Status: "AVAILABLE", Marker: "1fd3-4f9f-44df-1b5c", }, }, } actual := &handler.Resource{} err := cmd.HandleFlags(actual) th.AssertNoErr(t, err) th.AssertDeepEquals(t, *expected.Params.(*paramsList).opts, *actual.Params.(*paramsList).opts) }
func TestUploadHandleFlags(t *testing.T) { app := cli.NewApp() flagset := flag.NewFlagSet("flags", 1) flagset.String("name", "", "") flagset.String("file", "", "") flagset.String("public-key", "", "") flagset.Set("name", "keypair1Name") flagset.Set("public-key", "ssh public key data here") c := cli.NewContext(app, flagset, nil) cmd := &commandUpload{ Ctx: &handler.Context{ CLIContext: c, }, } expected := &handler.Resource{ Params: ¶msUpload{ opts: &osKeypairs.CreateOpts{ Name: "keypair1Name", PublicKey: "ssh public key data here", }, }, } actual := &handler.Resource{} err := cmd.HandleFlags(actual) th.AssertNoErr(t, err) th.AssertDeepEquals(t, *expected.Params.(*paramsUpload).opts, *actual.Params.(*paramsUpload).opts) }
func TestCreateHandleSingle(t *testing.T) { app := cli.NewApp() flagset := flag.NewFlagSet("flags", 1) flagset.String("name", "", "") flagset.Set("name", "server1") c := cli.NewContext(app, flagset, nil) cmd := &commandCreate{ Ctx: &handler.Context{ CLIContext: c, }, } expected := &handler.Resource{ Params: ¶msCreate{ opts: &servers.CreateOpts{ Name: "server1", }, }, } actual := &handler.Resource{ Params: ¶msCreate{ opts: &servers.CreateOpts{}, }, } err := cmd.HandleSingle(actual) th.AssertNoErr(t, err) th.AssertEquals(t, expected.Params.(*paramsCreate).opts.Name, actual.Params.(*paramsCreate).opts.Name) }
func TestListHandleFlags(t *testing.T) { app := cli.NewApp() flagset := flag.NewFlagSet("flags", 1) flagset.String("sort-dir", "", "") flagset.String("sort-key", "", "") flagset.String("name", "", "") flagset.String("status", "", "") flagset.String("marker", "", "") flagset.Set("sort-dir", "asc") flagset.Set("sort-key", "name") flagset.Set("name", "stacks*") flagset.Set("status", "CREATE_COMPLETE") flagset.Set("marker", "1fd3-4f9f-44df-1b5c") c := cli.NewContext(app, flagset, nil) cmd := &commandList{ Ctx: &handler.Context{ CLIContext: c, }, } expected := &handler.Resource{ Params: ¶msList{ opts: &osStacks.ListOpts{ SortKey: "name", SortDir: "asc", Name: "stacks*", Status: "CREATE_COMPLETE", Marker: "1fd3-4f9f-44df-1b5c", }, }, } actual := &handler.Resource{} err := cmd.HandleFlags(actual) th.AssertNoErr(t, err) th.AssertDeepEquals(t, *expected.Params.(*paramsList).opts, *actual.Params.(*paramsList).opts) }
func TestApp_Run_Version(t *testing.T) { var versionArguments = [][]string{{"boom", "--version"}, {"boom", "-v"}} for _, args := range versionArguments { buf := new(bytes.Buffer) t.Logf("==> checking with arguments %v", args) app := cli.NewApp() app.Name = "boom" app.Usage = "make an explosive entrance" app.Version = "0.1.0" app.Writer = buf app.Action = func(c *cli.Context) { buf.WriteString("boom I say!") } err := app.Run(args) if err != nil { t.Error(err) } output := buf.String() t.Logf("output: %q\n", buf.Bytes()) if !strings.Contains(output, "0.1.0") { t.Errorf("want version to contain %q, did not: \n%q", "0.1.0", output) } } }
func TestRebootHandleSingle(t *testing.T) { th.SetupHTTP() defer th.TeardownHTTP() th.Mux.HandleFunc("/servers/detail", func(w http.ResponseWriter, r *http.Request) { w.Header().Add("Content-Type", "application/json") fmt.Fprintf(w, `{"servers":[{"ID":"server1","Name":"server1Name"}]}`) }) app := cli.NewApp() flagset := flag.NewFlagSet("flags", 1) flagset.String("name", "", "") flagset.Set("name", "server1Name") c := cli.NewContext(app, flagset, nil) cmd := &commandReboot{ Ctx: &handler.Context{ CLIContext: c, ServiceClient: client.ServiceClient(), }, } expected := &handler.Resource{ Params: ¶msReboot{ serverID: "server1", }, } actual := &handler.Resource{ Params: ¶msReboot{}, } err := cmd.HandleSingle(actual) th.AssertNoErr(t, err) th.AssertEquals(t, expected.Params.(*paramsReboot).serverID, actual.Params.(*paramsReboot).serverID) }
func TestDeleteExecute(t *testing.T) { th.SetupHTTP() defer th.TeardownHTTP() th.Mux.HandleFunc("/container1", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNoContent) }) app := cli.NewApp() flagset := flag.NewFlagSet("flags", 1) flagset.String("name", "", "") flagset.Set("name", "container1") c := cli.NewContext(app, flagset, nil) cmd := &commandDelete{ Ctx: &handler.Context{ ServiceClient: client.ServiceClient(), CLIContext: c, }, } actual := &handler.Resource{ Params: ¶msDelete{ container: "container1", }, } cmd.Execute(actual) th.AssertNoErr(t, actual.Err) }
func TestApp_RunAsSubcommandParseFlags(t *testing.T) { var context *cli.Context a := cli.NewApp() a.Commands = []cli.Command{ { Name: "foo", Action: func(c *cli.Context) { context = c }, Flags: []cli.Flag{ cli.StringFlag{ Name: "lang", Value: "english", Usage: "language for the greeting", }, }, Before: func(_ *cli.Context) error { return nil }, }, } a.Run([]string{"", "foo", "--lang", "spanish", "abcd"}) expect(t, context.Args().Get(0), "abcd") expect(t, context.String("lang"), "spanish") }
func ExampleAppHelp() { // set args for examples sake os.Args = []string{"greet", "h", "describeit"} app := cli.NewApp() app.Name = "greet" app.Flags = []cli.Flag{ cli.StringFlag{Name: "name", Value: "bob", Usage: "a name to say"}, } app.Commands = []cli.Command{ { Name: "describeit", Aliases: []string{"d"}, Usage: "use it to see a description", Description: "This is how we describe describeit the function", Action: func(c *cli.Context) { fmt.Printf("i like to describe things") }, }, } app.Run(os.Args) // Output: // NAME: // describeit - use it to see a description // // USAGE: // command describeit [arguments...] // // DESCRIPTION: // This is how we describe describeit the function }
func TestPreviewHandleSingle(t *testing.T) { app := cli.NewApp() flagset := flag.NewFlagSet("flags", 1) flagset.String("name", "", "") flagset.Set("name", "stack1") c := cli.NewContext(app, flagset, nil) cmd := &commandPreview{ Ctx: &handler.Context{ CLIContext: c, }, } expected := &handler.Resource{ Params: ¶msPreview{ opts: &osStacks.PreviewOpts{Name: "stack1"}, }, } actual := &handler.Resource{ Params: ¶msPreview{ opts: &osStacks.PreviewOpts{}, }, } err := cmd.HandleSingle(actual) th.AssertNoErr(t, err) th.AssertEquals(t, expected.Params.(*paramsPreview).opts.Name, actual.Params.(*paramsPreview).opts.Name) }
func TestApp_ParseSliceFlags(t *testing.T) { var parsedOption, firstArg string var parsedIntSlice []int var parsedStringSlice []string app := cli.NewApp() command := cli.Command{ Name: "cmd", Flags: []cli.Flag{ cli.IntSliceFlag{Name: "p", Value: &cli.IntSlice{}, Usage: "set one or more ip addr"}, cli.StringSliceFlag{Name: "ip", Value: &cli.StringSlice{}, Usage: "set one or more ports to open"}, }, Action: func(c *cli.Context) { parsedIntSlice = c.IntSlice("p") parsedStringSlice = c.StringSlice("ip") parsedOption = c.String("option") firstArg = c.Args().First() }, } app.Commands = []cli.Command{command} app.Run([]string{"", "cmd", "my-arg", "-p", "22", "-p", "80", "-ip", "8.8.8.8", "-ip", "8.8.4.4"}) IntsEquals := func(a, b []int) bool { if len(a) != len(b) { return false } for i, v := range a { if v != b[i] { return false } } return true } StrsEquals := func(a, b []string) bool { if len(a) != len(b) { return false } for i, v := range a { if v != b[i] { return false } } return true } var expectedIntSlice = []int{22, 80} var expectedStringSlice = []string{"8.8.8.8", "8.8.4.4"} if !IntsEquals(parsedIntSlice, expectedIntSlice) { t.Errorf("%v does not match %v", parsedIntSlice, expectedIntSlice) } if !StrsEquals(parsedStringSlice, expectedStringSlice) { t.Errorf("%v does not match %v", parsedStringSlice, expectedStringSlice) } }
func newCreateApp(flags map[string]string) *cli.Context { app := cli.NewApp() flagset := flag.NewFlagSet("flags", 1) flagset.String("volume-id", "", "") flagset.String("name", "", "") flagset.String("description", "", "") for k, v := range flags { flagset.Set(k, v) } return cli.NewContext(app, flagset, nil) }
func newGetApp(flags map[string]string) *cli.Context { app := cli.NewApp() flagset := flag.NewFlagSet("flags", 1) flagset.String("id", "", "") flagset.String("name", "", "") flagset.String("stdin", "", "") for k, v := range flags { flagset.Set(k, v) } return cli.NewContext(app, flagset, nil) }
func TestApp_Run_CommandWithSubcommandHasHelpTopic(t *testing.T) { var subcommandHelpTopics = [][]string{ {"command", "foo", "--help"}, {"command", "foo", "-h"}, {"command", "foo", "help"}, } for _, flagSet := range subcommandHelpTopics { t.Logf("==> checking with flags %v", flagSet) app := cli.NewApp() buf := new(bytes.Buffer) app.Writer = buf subCmdBar := cli.Command{ Name: "bar", Usage: "does bar things", } subCmdBaz := cli.Command{ Name: "baz", Usage: "does baz things", } cmd := cli.Command{ Name: "foo", Description: "descriptive wall of text about how it does foo things", Subcommands: []cli.Command{subCmdBar, subCmdBaz}, } app.Commands = []cli.Command{cmd} err := app.Run(flagSet) if err != nil { t.Error(err) } output := buf.String() t.Logf("output: %q\n", buf.Bytes()) if strings.Contains(output, "No help topic for") { t.Errorf("expect a help topic, got none: \n%q", output) } for _, shouldContain := range []string{ cmd.Name, cmd.Description, subCmdBar.Name, subCmdBar.Usage, subCmdBaz.Name, subCmdBaz.Usage, } { if !strings.Contains(output, shouldContain) { t.Errorf("want help to contain %q, did not: \n%q", shouldContain, output) } } } }
func Test_ShowAppHelp_NoAuthor(t *testing.T) { output := new(bytes.Buffer) app := cli.NewApp() app.Writer = output c := cli.NewContext(app, nil, nil) cli.ShowAppHelp(c) if bytes.Index(output.Bytes(), []byte("AUTHOR(S):")) != -1 { t.Errorf("expected\n%snot to include %s", output.String(), "AUTHOR(S):") } }
func TestListContext(t *testing.T) { app := cli.NewApp() flagset := flag.NewFlagSet("flags", 1) c := cli.NewContext(app, flagset, nil) cmd := &commandList{ Ctx: &handler.Context{ CLIContext: c, }, } expected := cmd.Ctx actual := cmd.Context() th.AssertDeepEquals(t, expected, actual) }
func TestApp_Command(t *testing.T) { app := cli.NewApp() fooCommand := cli.Command{Name: "foobar", Aliases: []string{"f"}} batCommand := cli.Command{Name: "batbaz", Aliases: []string{"b"}} app.Commands = []cli.Command{ fooCommand, batCommand, } for _, test := range commandAppTests { expect(t, app.Command(test.name) != nil, test.expected) } }
func TestCreateHandleFlags(t *testing.T) { app := cli.NewApp() flagset := flag.NewFlagSet("flags", 1) flagset.String("image-id", "", "") flagset.String("flavor-id", "", "") flagset.String("security-groups", "", "") flagset.String("networks", "", "") flagset.String("metadata", "", "") flagset.String("admin-pass", "", "") flagset.String("keypair", "", "") flagset.Set("image-id", "13ba-75c0-4483-acf9") flagset.Set("flavor-id", "1234-b95f-ac5b-cd23") flagset.Set("security-groups", "sg1,sg2,sg3") flagset.Set("networks", "1111-2222-3333-4444,5555-7777-8888-9999") flagset.Set("metadata", "img=foo,flavor=bar") flagset.Set("admin-pass", "secret") flagset.Set("keypair", "kp1") c := cli.NewContext(app, flagset, nil) cmd := &commandCreate{ Ctx: &handler.Context{ CLIContext: c, }, } expected := &handler.Resource{ Params: ¶msCreate{ opts: &servers.CreateOpts{ ImageRef: "13ba-75c0-4483-acf9", FlavorRef: "1234-b95f-ac5b-cd23", SecurityGroups: []string{"sg1", "sg2", "sg3"}, Networks: []osServers.Network{ { UUID: "1111-2222-3333-4444", }, { UUID: "5555-7777-8888-9999", }, }, Metadata: map[string]string{ "img": "foo", "flavor": "bar", }, AdminPass: "******", KeyPair: "kp1", }, }, } actual := &handler.Resource{} err := cmd.HandleFlags(actual) th.AssertNoErr(t, err) th.AssertDeepEquals(t, *expected.Params.(*paramsCreate).opts, *actual.Params.(*paramsCreate).opts) }
func TestApp_Run(t *testing.T) { s := "" app := cli.NewApp() app.Action = func(c *cli.Context) { s = s + c.Args().First() } err := app.Run([]string{"command", "foo"}) expect(t, err, nil) err = app.Run([]string{"command", "bar"}) expect(t, err, nil) expect(t, s, "foobar") }
func TestApp_Float64Flag(t *testing.T) { var meters float64 app := cli.NewApp() app.Flags = []cli.Flag{ cli.Float64Flag{Name: "height", Value: 1.5, Usage: "Set the height, in meters"}, } app.Action = func(c *cli.Context) { meters = c.Float64("height") } app.Run([]string{"", "--height", "1.93"}) expect(t, meters, 1.93) }
func TestRebuildHandleFlags(t *testing.T) { th.SetupHTTP() defer th.TeardownHTTP() th.Mux.HandleFunc("/servers/detail", func(w http.ResponseWriter, r *http.Request) { w.Header().Add("Content-Type", "application/json") fmt.Fprintf(w, `{"servers":[{"ID":"server1","Name":"server1Name"}]}`) }) app := cli.NewApp() flagset := flag.NewFlagSet("flags", 1) flagset.String("id", "", "") flagset.String("image-id", "", "") flagset.String("admin-pass", "", "") flagset.String("ipv4", "", "") flagset.String("ipv6", "", "") flagset.String("metadata", "", "") flagset.String("rename", "", "") flagset.Set("id", "server1") flagset.Set("image-id", "123456789") flagset.Set("admin-pass", "secret") flagset.Set("ipv4", "123.45.67.89") flagset.Set("metadata", "img=bar,flavor=foo") flagset.Set("rename", "server1Rename") c := cli.NewContext(app, flagset, nil) cmd := &commandRebuild{ Ctx: &handler.Context{ CLIContext: c, }, } expected := &handler.Resource{ Params: ¶msRebuild{ opts: &servers.RebuildOpts{ ImageID: "123456789", AdminPass: "******", AccessIPv4: "123.45.67.89", Metadata: map[string]string{ "img": "bar", "flavor": "foo", }, Name: "server1Rename", }, serverID: "server1", }, } actual := &handler.Resource{} err := cmd.HandleFlags(actual) th.AssertNoErr(t, err) th.AssertDeepEquals(t, *expected.Params.(*paramsRebuild).opts, *actual.Params.(*paramsRebuild).opts) }
func TestAppNoHelpFlag(t *testing.T) { oldFlag := cli.HelpFlag defer func() { cli.HelpFlag = oldFlag }() cli.HelpFlag = cli.BoolFlag{} app := cli.NewApp() err := app.Run([]string{"test", "-h"}) if err != flag.ErrHelp { t.Errorf("expected error about missing help flag, but got: %s (%T)", err, err) } }
func TestGlobalFlag(t *testing.T) { var globalFlag string var globalFlagSet bool app := cli.NewApp() app.Flags = []cli.Flag{ cli.StringFlag{Name: "global, g", Usage: "global"}, } app.Action = func(c *cli.Context) { globalFlag = c.GlobalString("global") globalFlagSet = c.GlobalIsSet("global") } app.Run([]string{"command", "-g", "foo"}) expect(t, globalFlag, "foo") expect(t, globalFlagSet, true) }