Golang NewFlagSet示例

说明

golang newflagset示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: flag

示例#1
文件: main.go 项目: Shyp/lucifer

func main() {
	invalidateflags := flag.NewFlagSet("invalidate", flag.ExitOnError)
	sync := invalidateflags.Bool("sync", true, "Make request synchronously")
	verbose := invalidateflags.Bool("verbose", false, "Verbose output")
	runflags := flag.NewFlagSet("run", flag.ExitOnError)
	bail := runflags.Bool("bail", false, "Bail after a single test failure")
	runverbose := runflags.Bool("verbose", false, "Verbose response output")
	grepHelp := "Grep for the given pattern"
	grep := runflags.String("grep", "", grepHelp)
	runflags.StringVar(grep, "g", "", grepHelp+" (shorthand)")
	if len(os.Args) < 2 {
		usage()
	}
	switch os.Args[1] {
	case "invalidate":
		err := invalidateflags.Parse(os.Args[2:])
		if err != nil {
			handleError(err, true)
		}
		doInvalidate(invalidateflags, *sync, *verbose)
	case "run":
		err := runflags.Parse(os.Args[2:])
		if err != nil {
			handleError(err, true)
		}
		doRun(runflags, *bail, *runverbose, *grep)
	default:
		usage()
	}
}

示例#2
文件: cluster_app_test.go 项目: jloper3/amazon-ecs-cli

func TestCliFlagsToCfnStackParams(t *testing.T) {
	globalSet := flag.NewFlagSet("ecs-cli", 0)
	globalSet.String("region", "us-west-1", "")
	globalContext := cli.NewContext(nil, globalSet, nil)

	flagSet := flag.NewFlagSet("ecs-cli-up", 0)
	flagSet.Bool(capabilityIAMFlag, true, "")
	flagSet.String(keypairNameFlag, "default", "")

	context := cli.NewContext(nil, flagSet, globalContext)
	params := cliFlagsToCfnStackParams(context)

	_, err := params.GetParameter(cloudformation.ParameterKeyAsgMaxSize)
	if err == nil {
		t.Fatalf("Expected error for parameter '%s'", cloudformation.ParameterKeyAsgMaxSize)
	}
	if cloudformation.ParameterNotFoundError != err {
		t.Error("Enexpected error returned: ", err)
	}

	flagSet.String(asgMaxSizeFlag, "2", "")
	context = cli.NewContext(nil, flagSet, globalContext)
	params = cliFlagsToCfnStackParams(context)
	_, err = params.GetParameter(cloudformation.ParameterKeyAsgMaxSize)
	if err != nil {
		t.Error("Error getting parameter '%s'", cloudformation.ParameterKeyAsgMaxSize)
	}
}

示例#3
文件: context_test.go 项目: realestate-com-au/shush

func TestNewContext(t *testing.T) {
	set := flag.NewFlagSet("test", 0)
	set.Int("myflag", 12, "doc")
	set.Int64("myflagInt64", int64(12), "doc")
	set.Uint("myflagUint", uint(93), "doc")
	set.Uint64("myflagUint64", uint64(93), "doc")
	set.Float64("myflag64", float64(17), "doc")
	globalSet := flag.NewFlagSet("test", 0)
	globalSet.Int("myflag", 42, "doc")
	globalSet.Int64("myflagInt64", int64(42), "doc")
	globalSet.Uint("myflagUint", uint(33), "doc")
	globalSet.Uint64("myflagUint64", uint64(33), "doc")
	globalSet.Float64("myflag64", float64(47), "doc")
	globalCtx := NewContext(nil, globalSet, nil)
	command := Command{Name: "mycommand"}
	c := NewContext(nil, set, globalCtx)
	c.Command = command
	expect(t, c.Int("myflag"), 12)
	expect(t, c.Int64("myflagInt64"), int64(12))
	expect(t, c.Uint("myflagUint"), uint(93))
	expect(t, c.Uint64("myflagUint64"), uint64(93))
	expect(t, c.Float64("myflag64"), float64(17))
	expect(t, c.GlobalInt("myflag"), 42)
	expect(t, c.GlobalInt64("myflagInt64"), int64(42))
	expect(t, c.GlobalUint("myflagUint"), uint(33))
	expect(t, c.GlobalUint64("myflagUint64"), uint64(33))
	expect(t, c.GlobalFloat64("myflag64"), float64(47))
	expect(t, c.Command.Name, "mycommand")
}

示例#4
文件: command.go 项目: jmptrader/vitess

func commandWorker(wi *Instance, wr *wrangler.Wrangler, args []string, cell string, runFromCli bool) (Worker, error) {
	action := args[0]

	actionLowerCase := strings.ToLower(action)
	for _, group := range commands {
		for _, cmd := range group.Commands {
			if strings.ToLower(cmd.Name) == actionLowerCase {
				var subFlags *flag.FlagSet
				if runFromCli {
					subFlags = flag.NewFlagSet(action, flag.ExitOnError)
				} else {
					subFlags = flag.NewFlagSet(action, flag.ContinueOnError)
				}
				// The command may be run from an RPC and may not log to the console.
				// The Wrangler logger defines where the output has to go.
				subFlags.SetOutput(logutil.NewLoggerWriter(wr.Logger()))
				subFlags.Usage = func() {
					wr.Logger().Printf("Usage: %s %s %s\n\n", os.Args[0], cmd.Name, cmd.Params)
					wr.Logger().Printf("%s\n\n", cmd.Help)
					subFlags.PrintDefaults()
				}
				return cmd.Method(wi, wr, subFlags, args[1:])
			}
		}
	}
	if runFromCli {
		flag.Usage()
	} else {
		PrintAllCommands(wr.Logger())
	}
	return nil, fmt.Errorf("unknown command: %v", action)
}

示例#5
文件: cluster_app_test.go 项目: jloper3/amazon-ecs-cli

func TestClusterUp(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()
	mockEcs := mock_ecs.NewMockECSClient(ctrl)
	mockCloudformation := mock_cloudformation.NewMockCloudformationClient(ctrl)

	mockEcs.EXPECT().Initialize(gomock.Any())
	mockEcs.EXPECT().CreateCluster(gomock.Any()).Do(func(in interface{}) {
		if in.(string) != clusterName {
			t.Fatal("Expected to be called with " + clusterName + " not " + in.(string))
		}
	}).Return(clusterName, nil)

	mockCloudformation.EXPECT().Initialize(gomock.Any())
	mockCloudformation.EXPECT().ValidateStackExists(gomock.Any()).Return(errors.New("error"))
	mockCloudformation.EXPECT().CreateStack(gomock.Any(), gomock.Any(), gomock.Any()).Return("", nil)
	mockCloudformation.EXPECT().WaitUntilCreateComplete(gomock.Any()).Return(nil)

	globalSet := flag.NewFlagSet("ecs-cli", 0)
	globalSet.String("region", "us-west-1", "")
	globalContext := cli.NewContext(nil, globalSet, nil)

	flagSet := flag.NewFlagSet("ecs-cli-up", 0)
	flagSet.Bool(capabilityIAMFlag, true, "")
	flagSet.String(keypairNameFlag, "default", "")

	context := cli.NewContext(nil, flagSet, globalContext)
	err := createCluster(context, &mockReadWriter{}, mockEcs, mockCloudformation, ami.NewStaticAmiIds())
	if err != nil {
		t.Fatal("Error bringing up cluster: ", err)
	}
}

示例#6
文件: cluster_app_test.go 项目: yinshiua/amazon-ecs-cli

func TestClusterDown(t *testing.T) {
	newCliParams = func(context *cli.Context, rdwr config.ReadWriter) (*config.CliParams, error) {
		return &config.CliParams{
			Cluster: clusterName,
		}, nil
	}
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()
	mockECS := mock_ecs.NewMockECSClient(ctrl)
	mockCloudformation := mock_cloudformation.NewMockCloudformationClient(ctrl)

	gomock.InOrder(
		mockECS.EXPECT().Initialize(gomock.Any()),
		mockECS.EXPECT().IsActiveCluster(gomock.Any()).Return(true, nil),
		mockCloudformation.EXPECT().Initialize(gomock.Any()),
		mockCloudformation.EXPECT().ValidateStackExists(stackName).Return(nil),
		mockCloudformation.EXPECT().DeleteStack(stackName).Return(nil),
		mockCloudformation.EXPECT().WaitUntilDeleteComplete(stackName).Return(nil),
		mockECS.EXPECT().DeleteCluster(clusterName).Return(clusterName, nil),
	)
	globalSet := flag.NewFlagSet("ecs-cli", 0)
	globalSet.String("region", "us-west-1", "")
	globalContext := cli.NewContext(nil, globalSet, nil)

	flagSet := flag.NewFlagSet("ecs-cli-down", 0)
	flagSet.Bool(forceFlag, true, "")

	context := cli.NewContext(nil, flagSet, globalContext)
	err := deleteCluster(context, newMockReadWriter(), mockECS, mockCloudformation)
	if err != nil {
		t.Fatal("Error deleting cluster: ", err)
	}
}

示例#7
文件: flagset_multiple.go 项目: jmptrader/gclt_presentation

func main() {
	start := flag.NewFlagSet("start", flag.ExitOnError)
	dbIp := start.String("db_ip", "127.0.0.1", "ip address for databse host")
	startHelp := start.Bool("help", false, "show this help message")

	stop := flag.NewFlagSet("stop", flag.ExitOnError)
	flushDb := stop.Bool("flush_db", false, "flush database")

	if len(os.Args) == 1 {
		showUsage()
		return
	}

	if os.Args[1] == "start" {
		start.Parse(os.Args[2:])
		if *startHelp {
			start.PrintDefaults()
			return
		}
		fmt.Printf("Database ip address: %v\n", *dbIp)
		return
	}

	if os.Args[1] == "stop" {
		stop.Parse(os.Args[2:])
		if *flushDb {
			fmt.Println("stopping and flushing db")
			return
		}
		fmt.Println("stopping")
		return
	}
	showUsage()
}

示例#8
文件: cluster_app_test.go 项目: yinshiua/amazon-ecs-cli

func TestClusterUpWithout2AvailabilityZones(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()
	mockECS := mock_ecs.NewMockECSClient(ctrl)
	mockCloudformation := mock_cloudformation.NewMockCloudformationClient(ctrl)
	vpcAZs := "us-west-2c"

	os.Setenv("AWS_ACCESS_KEY", "AKIDEXAMPLE")
	os.Setenv("AWS_SECRET_KEY", "secret")
	defer func() {
		os.Unsetenv("AWS_ACCESS_KEY")
		os.Unsetenv("AWS_SECRET_KEY")
	}()

	gomock.InOrder(
		mockCloudformation.EXPECT().Initialize(gomock.Any()),
		mockCloudformation.EXPECT().ValidateStackExists(stackName).Return(errors.New("error")),
	)
	globalSet := flag.NewFlagSet("ecs-cli", 0)
	globalSet.String("region", "us-west-1", "")
	globalContext := cli.NewContext(nil, globalSet, nil)

	flagSet := flag.NewFlagSet("ecs-cli-up", 0)
	flagSet.Bool(capabilityIAMFlag, true, "")
	flagSet.String(keypairNameFlag, "default", "")
	flagSet.Bool(forceFlag, true, "")
	flagSet.String(vpcAzFlag, vpcAZs, "")

	context := cli.NewContext(nil, flagSet, globalContext)
	err := createCluster(context, newMockReadWriter(), mockECS, mockCloudformation, ami.NewStaticAmiIds())
	if err == nil {
		t.Fatal("Expected error for 2 AZs")
	}
}

示例#9
文件: cluster_app_test.go 项目: yinshiua/amazon-ecs-cli

func TestClusterUpWithClusterNameEmpty(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()
	mockECS := mock_ecs.NewMockECSClient(ctrl)
	mockCloudformation := mock_cloudformation.NewMockCloudformationClient(ctrl)

	os.Setenv("AWS_ACCESS_KEY", "AKIDEXAMPLE")
	os.Setenv("AWS_SECRET_KEY", "secret")
	defer func() {
		os.Unsetenv("AWS_ACCESS_KEY")
		os.Unsetenv("AWS_SECRET_KEY")
	}()

	globalSet := flag.NewFlagSet("ecs-cli", 0)
	globalSet.String("region", "us-west-1", "")
	globalContext := cli.NewContext(nil, globalSet, nil)

	flagSet := flag.NewFlagSet("ecs-cli-up", 0)
	flagSet.Bool(capabilityIAMFlag, true, "")
	flagSet.String(keypairNameFlag, "default", "")

	context := cli.NewContext(nil, flagSet, globalContext)
	err := createCluster(context, &mockReadWriter{clusterName: ""}, mockECS, mockCloudformation, ami.NewStaticAmiIds())
	if err == nil {
		t.Fatal("Expected error bringing up cluster")
	}
}

示例#10
文件: auth_test.go 项目: toliaqat/photon-controller

/*
 * This does spot checking (not 100% thorough, since the format will change)
 * on the output of "show-login-token"
 */
func TestShowLoginToken(t *testing.T) {
	config := configuration.Configuration{
		Token: accessToken,
	}

	globalFlags := flag.NewFlagSet("global-flags", flag.ContinueOnError)
	err := globalFlags.Parse([]string{})
	if err != nil {
		t.Error(err)
	}
	globalCtx := cli.NewContext(nil, globalFlags, nil)
	commandFlags := flag.NewFlagSet("command-flags", flag.ContinueOnError)
	err = commandFlags.Parse([]string{})
	if err != nil {
		t.Error(err)
	}
	cxt := cli.NewContext(nil, commandFlags, globalCtx)

	var output bytes.Buffer
	err = showLoginTokenWriter(cxt, &output, &config)

	// Verify it didn't fail
	if err != nil {
		t.Error(err)
	}

	// Verify we printed the subject
	err = checkRegExp(`Subject:\s+`+expectedSubject, output)
	if err != nil {
		t.Error(err)
	}

	// Verify we printed the admin group
	err = checkRegExp(`Groups:.*`+expectedAdminGroup, output)
	if err != nil {
		t.Error(err)
	}

	// Verify we printed the everyone group
	err = checkRegExp(`Groups:.*`+expectedEveryoneGroup, output)
	if err != nil {
		t.Error(err)
	}

	// Verify we printed the date for Issued and Expires
	err = checkRegExp(`Issued:.*`+expectedDate, output)
	if err != nil {
		t.Error(err)
	}
	err = checkRegExp(`Expires:.*`+expectedDate, output)
	if err != nil {
		t.Error(err)
	}

	// Verify we printed the token itself
	err = checkRegExp(`Token:\s+`+accessToken, output)
	if err != nil {
		t.Error(err)
	}
}

示例#11
文件: auth_test.go 项目: toliaqat/photon-controller

/*
 * This validates the output of "show-login-token --non-interactive"
 */
func TestShowLoginTokenNonInteractive(t *testing.T) {
	config := configuration.Configuration{
		Token: accessToken,
	}

	globalFlags := flag.NewFlagSet("global-flags", flag.ContinueOnError)
	globalFlags.Bool("non-interactive", true, "non-interactive")
	err := globalFlags.Parse([]string{"--non-interactive"})
	if err != nil {
		t.Error(err)
	}
	globalCtx := cli.NewContext(nil, globalFlags, nil)
	commandFlags := flag.NewFlagSet("command-flags", flag.ContinueOnError)
	err = commandFlags.Parse([]string{})
	if err != nil {
		t.Error(err)
	}
	cxt := cli.NewContext(nil, commandFlags, globalCtx)

	var output bytes.Buffer
	err = showLoginTokenWriter(cxt, &output, &config)

	// Verify it didn't fail
	if err != nil {
		t.Error(err)
	}

	// Verify we printed the token and only the token (well, with a newline)
	outputString := output.String()
	if outputString != accessToken+"\n" {
		t.Errorf("Expected just access token, found '%s'", outputString)
	}
}

示例#12
文件: util.go 项目: mattkanwisher/doit

func withinTest(cs Config, fs *flag.FlagSet, fn func(*cli.Context)) {
	ogSource := DefaultConfig
	DefaultConfig = cs

	defer func() {
		DefaultConfig = ogSource
	}()

	var b bytes.Buffer
	app := cli.NewApp()
	app.Writer = bufio.NewWriter(&b)

	globalSet := flag.NewFlagSet("global test", 0)
	globalSet.String("token", "token", "token")

	globalCtx := cli.NewContext(app, globalSet, nil)

	if fs == nil {
		fs = flag.NewFlagSet("local test", 0)
	}

	c := cli.NewContext(app, fs, globalCtx)

	fn(c)
}

示例#13
文件: network.go 项目: hkumarmk/contrail-go-api

func init() {
	listFlags := flag.NewFlagSet("network-list", flag.ExitOnError)
	initCommonFlags(listFlags)
	listFlags.BoolVar(&networkListOpts.allTenants, "all-tenants", false,
		"Display networks for all tenants")
	listFlags.BoolVar(&networkListOpts.brief, "brief", false,
		"Multiline format")
	listFlags.BoolVar(&networkListOpts.detail, "detail", false,
		"Multiline format (detailed information)")
	RegisterCliCommand("network-list", listFlags, networkList)

	createFlags := flag.NewFlagSet("network-create", flag.ExitOnError)
	initCommonFlags(createFlags)
	createFlags.StringVar(&networkCreateOpts.subnet, "subnet", "",
		"Subnet prefix for network")
	createFlags.Usage = networkCreateUsage(createFlags)
	RegisterCliCommand("network-create", createFlags, networkCreate)

	deleteFlags := flag.NewFlagSet("network-delete", flag.ExitOnError)
	initCommonFlags(deleteFlags)
	deleteFlags.BoolVar(&networkDeleteOpts.purge, "purge", false,
		"Delete all dependent objects")
	deleteFlags.Usage = networkNameOrIdUsage(deleteFlags)
	RegisterCliCommand("network-delete", deleteFlags, networkDelete)

	showFlags := flag.NewFlagSet("network-show", flag.ExitOnError)
	initCommonFlags(showFlags)
	showFlags.BoolVar(&networkShowOpts.detail, "detail", false,
		"Detail output")
	showFlags.Usage = networkNameOrIdUsage(showFlags)
	RegisterCliCommand("network-show", showFlags, networkShow)
}

示例#14
文件: cluster_app_test.go 项目: jloper3/amazon-ecs-cli

func TestClusterPSTaskGetInfoFail(t *testing.T) {
	newCliParams = func(context *cli.Context, rdwr config.ReadWriter) (*config.CliParams, error) {
		return &config.CliParams{
			Cluster: clusterName,
		}, nil
	}
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()
	mockEcs := mock_ecs.NewMockECSClient(ctrl)

	mockEcs.EXPECT().Initialize(gomock.Any())
	mockEcs.EXPECT().IsActiveCluster(gomock.Any()).Return(true, nil)
	mockEcs.EXPECT().GetTasksPages(gomock.Any(), gomock.Any()).Do(func(x, y interface{}) {
	}).Return(errors.New("error"))

	globalSet := flag.NewFlagSet("ecs-cli", 0)
	globalSet.String("region", "us-west-1", "")
	globalContext := cli.NewContext(nil, globalSet, nil)

	flagSet := flag.NewFlagSet("ecs-cli-down", 0)

	context := cli.NewContext(nil, flagSet, globalContext)
	_, err := clusterPS(context, &mockReadWriter{}, mockEcs)
	if err == nil {
		t.Fatal("Expected error in cluster ps")
	}
}

示例#15
文件: cluster_app_test.go 项目: jloper3/amazon-ecs-cli

func TestClusterScale(t *testing.T) {
	newCliParams = func(context *cli.Context, rdwr config.ReadWriter) (*config.CliParams, error) {
		return &config.CliParams{
			Cluster: clusterName,
		}, nil
	}
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()
	mockEcs := mock_ecs.NewMockECSClient(ctrl)
	mockCloudformation := mock_cloudformation.NewMockCloudformationClient(ctrl)

	mockEcs.EXPECT().Initialize(gomock.Any())
	mockEcs.EXPECT().IsActiveCluster(gomock.Any()).Return(true, nil)

	mockCloudformation.EXPECT().Initialize(gomock.Any())
	mockCloudformation.EXPECT().ValidateStackExists(gomock.Any()).Return(nil)
	mockCloudformation.EXPECT().UpdateStack(gomock.Any(), gomock.Any()).Return("", nil)
	mockCloudformation.EXPECT().WaitUntilUpdateComplete(gomock.Any()).Return(nil)

	globalSet := flag.NewFlagSet("ecs-cli", 0)
	globalSet.String("region", "us-west-1", "")
	globalContext := cli.NewContext(nil, globalSet, nil)

	flagSet := flag.NewFlagSet("ecs-cli-down", 0)
	flagSet.Bool(capabilityIAMFlag, true, "")
	flagSet.String(asgMaxSizeFlag, "1", "")

	context := cli.NewContext(nil, flagSet, globalContext)
	err := scaleCluster(context, &mockReadWriter{}, mockEcs, mockCloudformation)
	if err != nil {
		t.Fatal("Error scaling cluster: ", err)
	}
}

示例#16
文件: vms_test.go 项目: vmware/photon-controller-cli

func TestReleaseFloatingIp(t *testing.T) {
	queuedTask := &photon.Task{
		Operation: "RELEASE_FLOATING_IP",
		State:     "QUEUED",
		ID:        "fake-vm-task-ID",
		Entity:    photon.Entity{ID: "fake_vm_ID"},
	}
	completedTask := &photon.Task{
		Operation: "RELEASE_FLOATING_IP",
		State:     "COMPLETED",
		ID:        "fake-vm-task-ID",
		Entity:    photon.Entity{ID: "fake_vm_ID"},
	}

	response, err := json.Marshal(queuedTask)
	if err != nil {
		t.Error("Not expecting error serializaing expected queuedTask")
	}
	taskResponse, err := json.Marshal(completedTask)
	if err != nil {
		t.Error("Not expecting error serializaing expected completedTask")
	}

	server := mocks.NewTestServer()
	mocks.RegisterResponder(
		"POST",
		server.URL+"/vms/"+"fake_vm_ID"+"/release_floating_ip",
		mocks.CreateResponder(200, string(response[:])))
	mocks.RegisterResponder(
		"GET",
		server.URL+"/tasks/"+queuedTask.ID,
		mocks.CreateResponder(200, string(taskResponse[:])))
	defer server.Close()

	mocks.Activate(true)
	httpClient := &http.Client{Transport: mocks.DefaultMockTransport}
	client.Esxclient = photon.NewTestClient(server.URL, nil, httpClient)

	globalSet := flag.NewFlagSet("test", 0)
	globalSet.Bool("non-interactive", true, "doc")
	globalCtx := cli.NewContext(nil, globalSet, nil)
	err = globalSet.Parse([]string{"--non-interactive"})
	if err != nil {
		t.Error("Not expecting arguments parsing to fail")
	}

	set := flag.NewFlagSet("test", 0)
	err = set.Parse([]string{"fake_vm_ID"})
	if err != nil {
		t.Error("Not expecting arguments parsing to fail")
	}
	set.String("network_id", "fake_network_id", "network id")
	cxt := cli.NewContext(nil, set, globalCtx)

	err = releaseFloatingIp(cxt)
	if err != nil {
		t.Error("Not expecting error creating VM image: " + err.Error())
	}
}

示例#17
文件: clusters_test.go 项目: toliaqat/photon-controller

func TestResizeCluster(t *testing.T) {
	queuedTask := &photon.Task{
		Operation: "RESIZE_CLUSTER",
		State:     "QUEUED",
		ID:        "fake_resize_cluster_task_id",
		Entity:    photon.Entity{ID: "fake_cluster_id"},
	}
	queuedTaskResponse, err := json.Marshal(queuedTask)
	if err != nil {
		t.Error("Not expecting error serializing expected queued task")
	}

	completedTask := &photon.Task{
		Operation: "RESIZE_CLUSTER",
		State:     "COMPLETED",
		ID:        "fake_resize_cluster_task_id",
		Entity:    photon.Entity{ID: "fake_cluster_id"},
	}
	completedTaskResponse, err := json.Marshal(completedTask)
	if err != nil {
		t.Error("Not expecting error serializing expected completed task")
	}

	server := mocks.NewTestServer()
	defer server.Close()

	mocks.RegisterResponder(
		"POST",
		server.URL+"/clusters/fake_cluster_id/resize",
		mocks.CreateResponder(200, string(queuedTaskResponse[:])))
	mocks.RegisterResponder(
		"GET",
		server.URL+"/tasks/fake_resize_cluster_task_id",
		mocks.CreateResponder(200, string(completedTaskResponse[:])))
	mocks.Activate(true)

	httpClient := &http.Client{Transport: mocks.DefaultMockTransport}
	client.Esxclient = photon.NewTestClient(server.URL, nil, httpClient)

	globalSet := flag.NewFlagSet("test", 0)
	globalSet.Bool("non-interactive", true, "doc")
	globalCtx := cli.NewContext(nil, globalSet, nil)
	err = globalSet.Parse([]string{"--non-interactive"})
	if err != nil {
		t.Error("Not expecting argument parsing to fail")
	}

	set := flag.NewFlagSet("test", 0)
	err = set.Parse([]string{"fake_cluster_id", "50"})
	if err != nil {
		t.Error("Not expecting argument parsing to fail")
	}
	ctx := cli.NewContext(nil, set, globalCtx)

	err = resizeCluster(ctx, os.Stdout)
	if err != nil {
		t.Error("Not expecting error resizing cluster: " + err.Error())
	}
}

示例#18
文件: deployments_test.go 项目: vmware/photon-controller-cli

func TestEnableClusterType(t *testing.T) {
	deploymentId := "deployment1"
	queuedTask := &photon.Task{
		Operation: "CONFIGURE_CLUSTER",
		State:     "QUEUED",
		Entity:    photon.Entity{ID: deploymentId},
	}
	completedTask := &photon.Task{
		Operation: "CONFIGURE_CLUSTER",
		State:     "COMPLETED",
		Entity:    photon.Entity{ID: deploymentId},
	}
	response, err := json.Marshal(queuedTask)
	if err != nil {
		t.Error("Not expecting error during serializing expected queuedTask")
	}
	taskResponse, err := json.Marshal(completedTask)
	if err != nil {
		t.Error("Not expecting error during serializing expected completedTask")
	}

	server := mocks.NewTestServer()
	mocks.RegisterResponder(
		"POST",
		server.URL+"/deployments/"+deploymentId+"/enable_cluster_type",
		mocks.CreateResponder(200, string(response[:])))
	mocks.RegisterResponder(
		"GET",
		server.URL+"/tasks/"+queuedTask.ID,
		mocks.CreateResponder(200, string(taskResponse[:])))

	defer server.Close()

	mocks.Activate(true)
	httpClient := &http.Client{Transport: mocks.DefaultMockTransport}
	client.Esxclient = photon.NewTestClient(server.URL, nil, httpClient)

	globalSet := flag.NewFlagSet("test", 0)
	globalSet.Bool("non-interactive", true, "doc")
	globalCtx := cli.NewContext(nil, globalSet, nil)
	err = globalSet.Parse([]string{"--non-interactive"})
	if err != nil {
		t.Error("Not expecting arguments parsing to fail")
	}
	set := flag.NewFlagSet("test", 0)
	err = set.Parse([]string{deploymentId})
	if err != nil {
		t.Error("Not expecting arguments parsing to fail")
	}
	set.String("type", "SWARM", "Cluster type")
	set.String("image-id", "abcd", "image id")

	cxt := cli.NewContext(nil, set, globalCtx)
	err = enableClusterType(cxt)
	if err != nil {
		t.Error(err)
		t.Error("Not expecting deployment list hosts to fail")
	}
}

示例#19
文件: basic_test.go 项目: sirnewton01/gojazz

func TestSwitchStreams(t *testing.T) {
	sandbox1, err := ioutil.TempDir(os.TempDir(), "gojazz-test")
	if err != nil {
		panic(err)
	}

	defer os.RemoveAll(sandbox1)

	t.Logf("Loading test project into %v\n", sandbox1)
	os.Args = []string{"load", "sirnewton | gojazz-test", "-sandbox=" + sandbox1}
	flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
	loadOp()

	t.Logf("Loading test project into %v\n", sandbox1)
	os.Args = []string{"load", "sirnewton | gojazz-test", "-stream=Alternate Stream", "-sandbox=" + sandbox1}
	flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
	loadOp()

	// Verify that specific files show up
	filesToCheck := []string{
		"project.json", "bigFile.txt", ".jazzignore",
		".cfignore", "folder", "filename(with)[chars$]^that.must-be-escaped", "bin",
		"bin/mybinary.so", "filename(with)[chars$]^that.must-be-escaped/test.java",
		"folder/file.exe", "folder/file2.jsp", "folder/file3.jar",
		"folder/filename(with)[chars$]^that.must-be-escaped",
		"alternateFile.txt", "alternateFolder", "alternateFolder/anotherAlternateFolder",
		"alternateFolder/anotherAlternateFile.txt",
	}
	for _, file := range filesToCheck {
		file = filepath.FromSlash(file)

		p := filepath.Join(sandbox1, file)
		s, _ := os.Stat(p)
		if s == nil {
			t.Error("File not found in sandbox: %v", p)
		}
	}

	// Verify that the file from the other stream no longer exists
	filesToCheck = []string{
		"folder/file1.txt", "README.md",
	}
	for _, file := range filesToCheck {
		file = filepath.FromSlash(file)

		p := filepath.Join(sandbox1, file)
		s, _ := os.Stat(p)
		if s != nil {
			t.Error("File from the wrong stream found in sandbox: %v", p)
		}
	}

	// Verify that there are no backups since nothing was modified
	s, _ := os.Stat(filepath.Join(sandbox1, backupFolder))
	if s != nil {
		t.Fatalf("Found a backup folder even though no changes were made.")
	}
}

示例#20
文件: wildcard_plugin.go 项目: lemaral/Wildcard_Plugin

func (cmd *Wildcard) Run(cliConnection plugin.CliConnection, args []string) {
	if len(args) < 2 {
		usage(args)
		return
	}
	command := args[0]
	args = append(args[:0], args[1:]...)

	switch command {
	case "wildcard-apps":
		if len(args) == 1 {
			cmd.WildcardCommandApps(cliConnection, args[0])
		}
	case "wildcard-delete":
		if len(args) <= 3 {
			pattern := args[0]
			fmt.Println(pattern)
			var _force bool = false
			var _routes = false
			var force *bool = &_force
			var routes *bool = &_routes
			if len(args) > 1 {
				wildcardFlagSet := flag.NewFlagSet("echo", flag.ExitOnError)
				force := wildcardFlagSet.Bool("f", false, "forces deletion of all apps matching APP_NAME_WITH_WILDCARD")
				routes := wildcardFlagSet.Bool("r", false, "delete associated routes")
				err := wildcardFlagSet.Parse(args[0:])
				fmt.Println(args)
				fmt.Println(wildcardFlagSet)

				reversedArgs := reverseOrder(args)

				fmt.Println(reversedArgs)

				wildcardFlagSet2 := flag.NewFlagSet("echo", flag.ExitOnError)
				force2 := wildcardFlagSet2.Bool("f", false, "forces deletion of all apps matching APP_NAME_WITH_WILDCARD")
				routes2 := wildcardFlagSet2.Bool("r", false, "delete associated routes")
				err2 := wildcardFlagSet2.Parse(reversedArgs)
				fmt.Println(reversedArgs)
				fmt.Println(wildcardFlagSet2)

				pattern = wildcardFlagSet.Arg(0)
				*force = *force || *force2
				*routes = *routes || *routes2

				//wildcardFlagSet's parsing begins with 0 (*name -f -r) and args left with unchanged
				//and wildcardFlagSet.Args() returns (*name)
				checkError(err)
				checkError(err2)
			}
			cmd.WildcardCommandDelete(cliConnection, pattern, force, routes)
		}
	case "wildcard-command":
		cmd.WildcardCommand(cliConnection, args)
	default:
		usage(args)
	}
}

示例#21
文件: deployments_test.go 项目: vmware/photon-controller-cli

func TestSetDeploymentSecurityGroups(t *testing.T) {
	deploymentId := "deployment1"
	queuedTask := &photon.Task{
		Operation: "UPDATE_DEPLOYMENT_SECURITY_GROUPS",
		State:     "QUEUED",
		Entity:    photon.Entity{ID: deploymentId},
	}
	completedTask := &photon.Task{
		Operation: "UPDATE_DEPLOYMENT_SECURITY_GROUPS",
		State:     "COMPLETED",
		Entity:    photon.Entity{ID: deploymentId},
	}

	response, err := json.Marshal(queuedTask)
	if err != nil {
		t.Error("Not expecting error during serializing expected queuedTask")
	}
	taskResponse, err := json.Marshal(completedTask)
	if err != nil {
		t.Error("Not expecting error during serializing expected completedTask")
	}

	server := mocks.NewTestServer()
	mocks.RegisterResponder(
		"POST",
		server.URL+"/deployments/"+deploymentId+"/set_security_groups",
		mocks.CreateResponder(200, string(response[:])))
	mocks.RegisterResponder(
		"GET",
		server.URL+"/tasks/"+queuedTask.ID,
		mocks.CreateResponder(200, string(taskResponse[:])))
	defer server.Close()

	mocks.Activate(true)
	httpClient := &http.Client{Transport: mocks.DefaultMockTransport}
	client.Esxclient = photon.NewTestClient(server.URL, nil, httpClient)

	globalSet := flag.NewFlagSet("test", 0)
	globalSet.Bool("non-interactive", true, "doc")
	globalCtx := cli.NewContext(nil, globalSet, nil)
	err = globalSet.Parse([]string{"--non-interactive"})
	if err != nil {
		t.Error("Not expecting arguments parsing to fail")
	}
	set := flag.NewFlagSet("test", 0)
	err = set.Parse([]string{deploymentId, "tenant\admingroup"})
	if err != nil {
		t.Error("Not expecting arguments parsing to fail")
	}
	cxt := cli.NewContext(nil, set, globalCtx)

	err = setDeploymentSecurityGroups(cxt)
	if err != nil {
		t.Error(err)
		t.Error("Not expecting setDeploymentSecurityGroups to fail")
	}
}

示例#22
文件: context_test.go 项目: ryansb/cli

func TestNewContext(t *testing.T) {
	set := flag.NewFlagSet("test", 0)
	set.Int("myflag", 12, "doc")
	globalSet := flag.NewFlagSet("test", 0)
	globalSet.Int("myflag", 42, "doc")
	c := cli.NewContext(nil, set, globalSet)
	expect(t, c.Int("myflag"), 12)
	expect(t, c.GlobalInt("myflag"), 42)
}

示例#23
文件: virtual-networks_test.go 项目: toliaqat/photon-controller

func TestSetDefaultVirtualNetwork(t *testing.T) {
	completedTask := &photon.Task{
		Operation: "SET_DEFAULT_NETWORK",
		State:     "COMPLETED",
		Entity:    photon.Entity{ID: "id"},
	}

	taskresponse, err := json.Marshal(completedTask)
	if err != nil {
		t.Error("Not expecting error serializing expected completedTask")
	}

	info := &photon.Info{
		NetworkType: SOFTWARE_DEFINED,
	}

	infoString, err := json.Marshal(info)
	if err != nil {
		t.Error("Not expecting error when serializing expected info")
	}

	server := mocks.NewTestServer()
	mocks.RegisterResponder(
		"POST",
		server.URL+"/subnets/"+completedTask.Entity.ID+"/set_default",
		mocks.CreateResponder(200, string(taskresponse[:])))
	mocks.RegisterResponder(
		"GET",
		server.URL+"/tasks/"+completedTask.ID,
		mocks.CreateResponder(200, string(taskresponse[:])))
	mocks.RegisterResponder(
		"GET",
		server.URL+"/info",
		mocks.CreateResponder(200, string(infoString[:])))
	defer server.Close()

	mocks.Activate(true)
	httpClient := &http.Client{Transport: mocks.DefaultMockTransport}
	client.Esxclient = photon.NewTestClient(server.URL, nil, httpClient)

	globalSet := flag.NewFlagSet("test", 0)
	globalSet.Bool("non-interactive", true, "doc")
	globalCtx := cli.NewContext(nil, globalSet, nil)
	err = globalSet.Parse([]string{"--non-interactive"})
	if err != nil {
		t.Error("Not expecting arguments parsing to fail")
	}

	set := flag.NewFlagSet("test", 0)
	err = set.Parse([]string{completedTask.Entity.ID})
	cxt := cli.NewContext(nil, set, globalCtx)

	err = setDefaultNetwork(cxt, os.Stdout)
	if err != nil {
		t.Error("Not expecting set default network to fail", err)
	}
}

示例#24
文件: main.go 项目: dnascimento/symbios

// Client Commands
func clientCmd() {
	// new-user
	var newUserCmd = flag.NewFlagSet("new-user", flag.ExitOnError)
	var keyLength = newUserCmd.Int("size", 4096, "User key size")
	var username = newUserCmd.String("username", "user", "Username")
	var out = newUserCmd.String("out", "id_rsa", "Key output file")
	var expiresDays = newUserCmd.Int("days", daysInTenYears, "User key expires after (days)")
	var expires = time.Now().AddDate(0, 0, *expiresDays).UTC()

	// new-token
	var newTokenCmd = flag.NewFlagSet("new-token", flag.ExitOnError)
	var newTokenHostname = newTokenCmd.String("hostname", "", "Username")
	var privateKeyPath = newTokenCmd.String("key", "id_rsa", "Private key file")

	// ca-hash
	var caHashCmd = flag.NewFlagSet("ca-hash", flag.ExitOnError)
	var caHost = caHashCmd.String("host", "localhost", "Certificate Authority hostname")
	var caPort = caHashCmd.String("port", "33004", "Certificate Authority port")

	// select subcommand
	//switch os.Args[2] {
	switch os.Args[1] {
	case "new-user":
		newUserCmd.Parse(os.Args[2:])
		encodedCert, _, _, err := client.NewUserKey(username, *keyLength, &expires, out)
		if err != nil {
			logger.Error.Printf("Failed to create new user key: %s", err)
			os.Exit(2)
		}
		fmt.Println(*encodedCert)

	case "new-token":
		newTokenCmd.Parse(os.Args[2:])
		token, err := client.NewTokenUsingPrivateKeyFile(*privateKeyPath, *newTokenHostname, defaultTokenDuration)
		if err != nil {
			logger.Error.Printf("Failed to create token: %s", err)
			os.Exit(2)
		}
		fmt.Println(*token)

	case "ca-hash":
		caHashCmd.Parse(os.Args[2:])
		endpoint := "https://" + (*caHost) + ":" + (*caPort)
		hash, err := client.GetCACertHashEncoded(&endpoint)
		if err != nil {
			logger.Error.Printf("Failed to get CA Hash: %s", err)
			os.Exit(2)
		}
		fmt.Println(*hash)

	default:
		error := fmt.Sprintf("%q is not valid command.\n", os.Args[1])
		argError(error)
		os.Exit(2)
	}
}

示例#25
文件: virtual-networks_test.go 项目: toliaqat/photon-controller

func TestCreateVirtualSubnet(t *testing.T) {
	queuedTask := &photon.Task{
		Operation: "CREATE_NETWORK",
		State:     "QUEUED",
		Entity:    photon.Entity{ID: "network-ID"},
	}
	completedTask := &photon.Task{
		Operation: "CREATE_NETWORK",
		State:     "COMPLETED",
		Entity:    photon.Entity{ID: "network-ID"},
	}
	response, err := json.Marshal(queuedTask)
	if err != nil {
		t.Error("Not expecting error serializing expected queuedTask")
	}
	taskresponse, err := json.Marshal(completedTask)
	if err != nil {
		t.Error("Not expecting error serializing expected completedTask")
	}

	server := mocks.NewTestServer()
	mocks.RegisterResponder(
		"POST",
		server.URL+"/projects/project_id/subnets",
		mocks.CreateResponder(200, string(response[:])))
	mocks.RegisterResponder(
		"GET",
		server.URL+"/tasks/"+queuedTask.ID,
		mocks.CreateResponder(200, string(taskresponse[:])))
	defer server.Close()

	mocks.Activate(true)
	httpClient := &http.Client{Transport: mocks.DefaultMockTransport}
	client.Esxclient = photon.NewTestClient(server.URL, nil, httpClient)

	globalSet := flag.NewFlagSet("test", 0)
	globalSet.Bool("non-interactive", true, "doc")
	globalCtx := cli.NewContext(nil, globalSet, nil)
	err = globalSet.Parse([]string{"--non-interactive"})
	if err != nil {
		t.Error("Not expecting arguments parsing to fail")
	}
	set := flag.NewFlagSet("test", 0)
	set.String("name", "network_name", "network name")
	set.String("routingType", "ROUTED", "routing type")
	set.Int("size", 256, "network size")
	set.Int("staticIpSize", 0, "reserved static ip size")
	set.String("projectId", "project_id", "project ID")

	cxt := cli.NewContext(nil, set, globalCtx)

	err = createVirtualNetwork(cxt, os.Stdout)
	if err != nil {
		t.Error("Not expecting create network to fail", err)
	}
}

示例#26
文件: cluster_app_test.go 项目: abdollar/amazon-ecs-cli

func TestClusterUpForImageIdInput(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()
	mockEcs := mock_ecs.NewMockECSClient(ctrl)
	mockCloudformation := mock_cloudformation.NewMockCloudformationClient(ctrl)
	imageId := "ami-12345"

	os.Setenv("AWS_ACCESS_KEY", "AKIDEXAMPLE")
	os.Setenv("AWS_SECRET_KEY", "secret")
	defer func() {
		os.Unsetenv("AWS_ACCESS_KEY")
		os.Unsetenv("AWS_SECRET_KEY")
	}()

	gomock.InOrder(
		mockEcs.EXPECT().Initialize(gomock.Any()),
		mockEcs.EXPECT().CreateCluster(gomock.Any()).Do(func(in interface{}) {
			if in.(string) != clusterName {
				t.Fatal("Expected to be called with " + clusterName + " not " + in.(string))
			}
		}).Return(clusterName, nil),
	)

	gomock.InOrder(
		mockCloudformation.EXPECT().Initialize(gomock.Any()),
		mockCloudformation.EXPECT().ValidateStackExists(gomock.Any()).Return(errors.New("error")),
		mockCloudformation.EXPECT().CreateStack(gomock.Any(), gomock.Any(), gomock.Any()).Do(func(x, y, z interface{}) {
			cfnStackParams := z.(*cloudformation.CfnStackParams)
			param, err := cfnStackParams.GetParameter(cloudformation.ParameterKeyAmiId)
			if err != nil {
				t.Fatal("Expected image id params to be present")
			}
			if imageId != aws.StringValue(param.ParameterValue) {
				t.Fatalf("Expected image id to equal %s but got %s", imageId, aws.StringValue(param.ParameterValue))
			}
		}).Return("", nil),
		mockCloudformation.EXPECT().WaitUntilCreateComplete(gomock.Any()).Return(nil),
	)

	globalSet := flag.NewFlagSet("ecs-cli", 0)
	globalSet.String("region", "us-west-1", "")
	globalContext := cli.NewContext(nil, globalSet, nil)

	flagSet := flag.NewFlagSet("ecs-cli-up", 0)
	flagSet.Bool(capabilityIAMFlag, true, "")
	flagSet.String(keypairNameFlag, "default", "")
	flagSet.String(imageIdFlag, imageId, "")
	flagSet.String(certificateFlag, "default", "")

	context := cli.NewContext(nil, flagSet, globalContext)
	err := createCluster(context, &mockReadWriter{}, mockEcs, mockCloudformation, ami.NewStaticAmiIds())
	if err != nil {
		t.Fatal("Error bringing up cluster: ", err)
	}
}

示例#27
文件: main.go 项目: gtfierro/askgiles

func main() {
	var (
		query string

		host       string
		formatTime bool
		timeFormat string

		where       string
		beginYear   int
		endYear     int
		dataLimit   int
		destination string
		timeunit    string
	)

	queryCommand := flag.NewFlagSet("query", flag.ExitOnError)
	queryCommand.StringVar(&host, "h", "http://0.0.0.0:8079/api/query", "Host to direct queries to")
	queryCommand.BoolVar(&formatTime, "t", true, "If true, formats time according to RFC3339. Can specify ANSIC, RFC822, RFC1123, RFC3339 using the -f flag. If false, displays the unix-style timestamp.")
	queryCommand.StringVar(&timeFormat, "f", "RFC3339", "Time format. Can specify ANSIC, RFC822, RFC1123, RFC3339.")

	vizCommand := flag.NewFlagSet("viz", flag.ExitOnError)
	vizCommand.StringVar(&host, "h", "http://0.0.0.0:8079/api/query", "Host to direct queries to")

	downloadCommand := flag.NewFlagSet("download", flag.ExitOnError)
	downloadCommand.StringVar(&host, "h", "http://0.0.0.0:8079/api/query", "Host to direct queries to")
	downloadCommand.IntVar(&beginYear, "b", 2000, "Start year for download (low)")
	downloadCommand.IntVar(&endYear, "e", 2020, "End year for download (high)")
	downloadCommand.IntVar(&dataLimit, "l", 10000000, "Maximum number of points to download per stream")
	downloadCommand.StringVar(&destination, "d", "./data/", "Path to folder to save data")
	downloadCommand.StringVar(&timeunit, "t", "_", "Unit of time to download data as: s, ms, us, ns")

	if len(os.Args) == 1 {
		flag.Usage()
		os.Exit(1)
	}

	switch os.Args[1] {
	case "query":
		queryCommand.Parse(os.Args[2:])
		query = os.Args[len(os.Args)-1]
		handleQuery(host, query)
	case "viz":
		query = os.Args[len(os.Args)-1]
		vizCommand.Parse(os.Args[3:])
		handleVis(host, query, os.Args[2])
	case "dl", "download":
		where = os.Args[len(os.Args)-1]
		downloadCommand.Parse(os.Args[2:])
		doDownload(host, where, destination, timeunit, beginYear, endYear, dataLimit)
	}

	if queryCommand.Parsed() {
	}
}

示例#28
文件: context_test.go 项目: realestate-com-au/shush

func TestContext_GlobalBoolT(t *testing.T) {
	set := flag.NewFlagSet("test", 0)

	globalSet := flag.NewFlagSet("test-global", 0)
	globalSet.Bool("myflag", true, "doc")
	globalCtx := NewContext(nil, globalSet, nil)

	c := NewContext(nil, set, globalCtx)
	expect(t, c.GlobalBoolT("myflag"), true)
	expect(t, c.GlobalBoolT("nope"), false)
}

示例#29
文件: arguments_test.go 项目: iverberk/opsgenie-heartbeat

func createCliAll(apiKey string, name string, intervalUnit string, description string, interval int, delete bool) *cli.Context {
	globalSet := flag.NewFlagSet("testGlobal", 0)
	globalSet.String("apiKey", apiKey, "")
	globalSet.String("name", name, "")
	set := flag.NewFlagSet("test", 0)
	set.String("description", description, "")
	set.Int("interval", interval, "")
	set.String("intervalUnit", intervalUnit, "")
	set.Bool("delete", delete, "")
	return cli.NewContext(nil, set, globalSet)
}

示例#30
文件: context_test.go 项目: devick/flynn

func TestContext_NumFlags(t *testing.T) {
	set := flag.NewFlagSet("test", 0)
	set.Bool("myflag", false, "doc")
	set.String("otherflag", "hello world", "doc")
	globalSet := flag.NewFlagSet("test", 0)
	globalSet.Bool("myflagGlobal", true, "doc")
	c := cli.NewContext(nil, set, globalSet)
	set.Parse([]string{"--myflag", "--otherflag=foo"})
	globalSet.Parse([]string{"--myflagGlobal"})
	expect(t, c.NumFlags(), 2)
}

展开阅读全文