Example #1
0
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
}
Example #2
0
func TestApp_DefaultStdout(t *testing.T) {
	app := cli.NewApp()

	if app.Writer != os.Stdout {
		t.Error("Default output writer not set.")
	}
}
Example #3
0
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: &paramsUpload{
			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)
}
Example #4
0
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
}
Example #5
0
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: &paramsCreate{
			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)
}
Example #6
0
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)
}
Example #7
0
func TestGenerateHandleSingle(t *testing.T) {
	app := cli.NewApp()
	flagset := flag.NewFlagSet("flags", 1)
	flagset.String("name", "", "")
	flagset.Set("name", "keypair1Name")
	c := cli.NewContext(app, flagset, nil)
	cmd := &commandGenerate{
		Ctx: &handler.Context{
			CLIContext: c,
		},
	}
	expected := &handler.Resource{
		Params: &paramsGenerate{
			opts: &osKeypairs.CreateOpts{
				Name: "keypair1Name",
			},
		},
	}
	actual := &handler.Resource{
		Params: &paramsGenerate{
			opts: &osKeypairs.CreateOpts{},
		},
	}
	err := cmd.HandleSingle(actual)
	th.AssertNoErr(t, err)
	th.AssertEquals(t, *expected.Params.(*paramsGenerate).opts, *actual.Params.(*paramsGenerate).opts)
}
Example #8
0
func TestGetHandleSingle(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 := &commandGet{
		Ctx: &handler.Context{
			CLIContext:    c,
			ServiceClient: client.ServiceClient(),
		},
	}
	expected := &handler.Resource{
		Params: &paramsGet{
			server: "server1",
		},
	}
	actual := &handler.Resource{
		Params: &paramsGet{},
	}
	err := cmd.HandleSingle(actual)
	th.AssertNoErr(t, err)
	th.AssertEquals(t, expected.Params.(*paramsGet).server, actual.Params.(*paramsGet).server)
}
Example #9
0
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: &paramsList{
			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)
}
Example #10
0
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.Bool("json", false, "")
	c := cli.NewContext(app, flagset, nil)
	cmd := &commandGenerate{
		Ctx: &handler.Context{
			CLIContext:    c,
			ServiceClient: client.ServiceClient(),
		},
	}
	actual := &handler.Resource{
		Params: &paramsGenerate{
			opts: &osKeypairs.CreateOpts{
				Name: "keypair1Name",
			},
		},
	}
	cmd.Execute(actual)
	th.AssertNoErr(t, actual.Err)
}
Example #11
0
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)
		}
	}
}
Example #12
0
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: &paramsDelete{
			container: "container1",
		},
	}
	cmd.Execute(actual)
	th.AssertNoErr(t, actual.Err)
}
Example #13
0
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])
	}
}
Example #14
0
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")
}
Example #15
0
File: main.go Project: hdansou/rack
func main() {
	cli.HelpPrinter = printHelp
	cli.CommandHelpTemplate = `NAME: {{.Name}} - {{.Usage}}{{if .Description}}

DESCRIPTION: {{.Description}}{{end}}{{if .Flags}}

OPTIONS:
{{range .Flags}}{{flag .}}
{{end}}{{ end }}
`
	app := cli.NewApp()
	app.Name = "rack"
	app.Usage = "An opinionated CLI for the Rackspace cloud"
	app.EnableBashCompletion = true
	app.Commands = []cli.Command{
		{
			Name:   "init",
			Usage:  "[Linux/OS X only] Setup environment with command completion for the Bash shell.",
			Action: setup.Init,
		},
		{
			Name:   "configure",
			Usage:  "Interactively create a config file for Rackspace authentication.",
			Action: configure,
		},
		{
			Name:        "servers",
			Usage:       "Operations on cloud servers, both virtual and bare metal.",
			Subcommands: serverscommands.Get(),
		},
		{
			Name:        "files",
			Usage:       "Object storage for files and media.",
			Subcommands: filescommands.Get(),
		},
		{
			Name:        "networks",
			Usage:       "Software-defined networking.",
			Subcommands: networkscommands.Get(),
		},
		{
			Name:        "block-storage",
			Usage:       "Block-level storage, exposed as volumes to mount to host servers. Work with volumes and their associated snapshots.",
			Subcommands: blockstoragecommands.Get(),
		},
	}
	app.Flags = util.GlobalFlags()
	app.BashComplete = func(c *cli.Context) {
		completeGlobals(globalOptions(app))
	}
	app.Before = func(c *cli.Context) error {
		//fmt.Printf("c.Args: %+v\n", c.Args())
		return nil
	}
	app.CommandNotFound = commandNotFound
	app.Run(os.Args)
}
Example #16
0
func main() {
	cli.HelpPrinter = printHelp
	cli.CommandHelpTemplate = `NAME: {{.Name}} - {{.Usage}}{{if .Description}}

DESCRIPTION: {{.Description}}{{end}}{{if .Flags}}

OPTIONS:
{{range .Flags}}{{flag .}}
{{end}}{{ end }}
`
	app := cli.NewApp()
	app.Name = "rack"
	app.Usage = "An opinionated CLI for the Rackspace cloud"
	app.EnableBashCompletion = true
	app.Commands = []cli.Command{
		{
			Name:   "init",
			Usage:  "Used to setup a user's environment with amenities like command completion for the Bash shell.",
			Action: setup.Init,
		},
		{
			Name:   "configure",
			Usage:  "Used to interactively create a config file for Rackspace authentication.",
			Action: configure,
		},
		{
			Name:        "servers",
			Usage:       "Used for the Servers service",
			Subcommands: serverscommands.Get(),
		},
		{
			Name:        "files",
			Usage:       "Used for the Files service",
			Subcommands: filescommands.Get(),
		},
		{
			Name:        "networks",
			Usage:       "Used for the Networks service",
			Subcommands: networkscommands.Get(),
		},
		{
			Name:        "block-storage",
			Usage:       "Used for the Block Storage service",
			Subcommands: blockstoragecommands.Get(),
		},
	}
	app.Flags = util.GlobalFlags()
	app.BashComplete = func(c *cli.Context) {
		completeGlobals(globalOptions(app))
	}
	app.Before = func(c *cli.Context) error {
		//fmt.Printf("c.Args: %+v\n", c.Args())
		return nil
	}
	app.CommandNotFound = commandNotFound
	app.Run(os.Args)
}
Example #17
0
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)
	}
}
Example #18
0
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)
			}
		}
	}
}
Example #19
0
func TestDeleteContext(t *testing.T) {
	app := cli.NewApp()
	flagset := flag.NewFlagSet("flags", 1)
	c := cli.NewContext(app, flagset, nil)
	cmd := &commandDelete{
		Ctx: &handler.Context{
			CLIContext: c,
		},
	}
	expected := cmd.Ctx
	actual := cmd.Context()
	th.AssertDeepEquals(t, expected, actual)
}
Example #20
0
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):")
	}
}
Example #21
0
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)
	}
}
Example #22
0
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: &paramsCreate{
			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)
}
Example #23
0
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")
}
Example #24
0
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)
}
Example #25
0
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: &paramsRebuild{
			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)
}
Example #26
0
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)
	}
}
Example #27
0
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)

}
Example #28
0
func TestDeleteHandleFlags(t *testing.T) {
	app := cli.NewApp()
	flagset := flag.NewFlagSet("flags", 1)
	c := cli.NewContext(app, flagset, nil)
	cmd := &commandDelete{
		Ctx: &handler.Context{
			CLIContext: c,
		},
	}
	expected := &handler.Resource{
		Params: &paramsDelete{},
	}
	actual := &handler.Resource{}
	err := cmd.HandleFlags(actual)
	th.AssertNoErr(t, err)
	th.AssertDeepEquals(t, expected.Params.(*paramsDelete), actual.Params.(*paramsDelete))
}
Example #29
0
func TestApp_SetStdout(t *testing.T) {
	w := &mockWriter{}

	app := cli.NewApp()
	app.Name = "test"
	app.Writer = w

	err := app.Run([]string{"help"})

	if err != nil {
		t.Fatalf("Run error: %s", err)
	}

	if len(w.written) == 0 {
		t.Error("App did not write output to desired writer.")
	}
}
Example #30
0
func TestApp_Run_DoesNotOverwriteErrorFromBefore(t *testing.T) {
	app := cli.NewApp()
	app.Action = func(c *cli.Context) {}
	app.Before = func(c *cli.Context) error { return fmt.Errorf("before error") }
	app.After = func(c *cli.Context) error { return fmt.Errorf("after error") }

	err := app.Run([]string{"foo"})
	if err == nil {
		t.Fatalf("expected to recieve error from Run, got none")
	}

	if !strings.Contains(err.Error(), "before error") {
		t.Errorf("expected text of error from Before method, but got none in \"%v\"", err)
	}
	if !strings.Contains(err.Error(), "after error") {
		t.Errorf("expected text of error from After method, but got none in \"%v\"", err)
	}
}