func setupTestProject(t *testing.T) *ecsProject {
	envLookup, err := utils.GetDefaultEnvironmentLookup()
	if err != nil {
		t.Fatal("Unexpected error in setting up a project", err)
	}
	resourceLookup, err := utils.GetDefaultResourceLookup()
	if err != nil {
		t.Fatal("Unexpected error in setting up a project", err)
	}

	composeContext := flag.NewFlagSet("ecs-cli", 0)
	composeContext.String(ProjectNameFlag, testProjectName, "")
	parentContext := cli.NewContext(nil, composeContext, nil)
	cliContext := cli.NewContext(nil, nil, parentContext)

	ecsContext := &Context{
		CLIContext: cliContext,
	}
	ecsContext.EnvironmentLookup = envLookup
	ecsContext.ResourceLookup = resourceLookup
	libcomposeProject := project.NewProject(&ecsContext.Context, nil, nil)

	return &ecsProject{
		context: ecsContext,
		Project: *libcomposeProject,
	}
}
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)
	}
}
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")
	}
}
Example #4
0
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)
}
Example #5
0
/*
 * 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)
	}
}
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")
	}
}
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)
	}
}
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)
	}
}
func TestNewCliParamsFromEnvVarsWithRegionSpecifiedAsEnvVariable(t *testing.T) {
	globalSet := flag.NewFlagSet("ecs-cli", 0)
	globalContext := cli.NewContext(nil, globalSet, nil)
	context := cli.NewContext(nil, nil, globalContext)
	rdwr := &mockReadWriter{}

	os.Setenv("AWS_REGION", "us-west-1")
	os.Setenv("AWS_ACCESS_KEY", "AKIDEXAMPLE")
	os.Setenv("AWS_SECRET_KEY", "SECRET")
	defer func() {
		os.Unsetenv("AWS_REGION")
		os.Unsetenv("AWS_ACCESS_KEY")
		os.Unsetenv("AWS_SECRET_KEY")
	}()

	params, err := NewCliParams(context, rdwr)
	if err != nil {
		t.Errorf("Unexpected error when region is specified using environment variable AWS_REGION: ", err)
	}

	paramsRegion := aws.StringValue(params.Config.Region)
	if "us-west-1" != paramsRegion {
		t.Errorf("Unexpected region set, expected: us-west-1, got: %s", paramsRegion)
	}
}
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")
	}
}
func defaultConfig() *cli.Context {
	globalSet := flag.NewFlagSet("ecs-cli", 0)
	globalContext := cli.NewContext(nil, globalSet, nil)
	globalSet.String("region", "us-east-1", "")
	globalContext = cli.NewContext(nil, globalSet, nil)
	return cli.NewContext(nil, nil, globalContext)
}
Example #12
0
/*
 * 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)
	}
}
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)
	}
}
Example #14
0
func TestPopulateContext(t *testing.T) {
	globalSet := flag.NewFlagSet("ecs-cli", 0)
	globalContext := cli.NewContext(nil, globalSet, nil)
	cliContext := cli.NewContext(nil, nil, globalContext)
	ecsContext := &ecscompose.Context{}

	// Create a temprorary directory for the dummy ecs config
	tempDirName, err := ioutil.TempDir("", "test")
	if err != nil {
		t.Fatal("Error while creating the dummy ecs config directory")
	}
	defer os.Remove(tempDirName)
	os.Setenv("HOME", tempDirName)

	os.Setenv("AWS_REGION", "us-east-1")
	os.Setenv("AWS_ACCESS_KEY", "AKIDEXAMPLE")
	os.Setenv("AWS_SECRET_KEY", "secret")
	defer func() {
		os.Unsetenv("AWS_REGION")
		os.Unsetenv("AWS_ACCESS_KEY")
		os.Unsetenv("AWS_SECRET_KEY")
		os.Unsetenv("HOME")
	}()

	projectFactory := projectFactory{}
	err = projectFactory.populateContext(ecsContext, cliContext)

	if err != nil {
		t.Fatal("Error while populating the context")
	}

	if ecsContext.ECSParams == nil {
		t.Error("ECS Params was expected to be set for ecsContext but was nil")
	}
}
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")
	}
}
Example #16
0
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())
	}
}
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())
	}
}
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)
	}
}
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")
	}
}
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)
	}
}
func TestNewCliParamsFromEnvVarsWithRegionNotSpecified(t *testing.T) {
	globalSet := flag.NewFlagSet("ecs-cli", 0)
	globalContext := cli.NewContext(nil, globalSet, nil)
	context := cli.NewContext(nil, nil, globalContext)
	rdwr := &mockReadWriter{}
	_, err := NewCliParams(context, rdwr)
	if err == nil {
		t.Errorf("Expected error when region not specified")
	}
}
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)
	}
}
Example #23
0
func TestTargetInfo(t *testing.T) {
	server := mocks.NewTestServer()
	defer server.Close()

	// We first test that with exactly one deployment, we work as expected.
	// This is the expected case in a real installation
	err := mockInfo(t, server)
	if err != nil {
		t.Error("Failed to mock info: " + err.Error())
	}
	mocks.Activate(true)

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

	globalFlags := flag.NewFlagSet("global-flags", flag.ContinueOnError)
	globalFlags.String("output", "json", "output")
	err = globalFlags.Parse([]string{"--output=json"})
	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 = showInfo(cxt, &output)
	if err != nil {
		t.Error("showInfo ailed unexpectedly: " + err.Error())
	}

	// Verify we have the fields we expect
	err = checkRegExp(`\"baseVersion\":\s*\".*\"`, output)
	if err != nil {
		t.Errorf("Show info produce a JSON field named 'baseVersion': %s", err)
	}
	err = checkRegExp(`\"fullVersion\":\s*\".*\"`, output)
	if err != nil {
		t.Errorf("Show info produce a JSON field named 'fullVersion': %s", err)
	}
	err = checkRegExp(`\"gitCommitHash\":\s*\".*\"`, output)
	if err != nil {
		t.Errorf("Show info produce a JSON field named 'gitCommitHash': %s", err)
	}
	err = checkRegExp(`\"networkType\":\s*\".*\"`, output)
	if err != nil {
		t.Errorf("Show info produce a JSON field named 'networkType': %s", err)
	}
}
Example #24
0
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")
	globalCtx := cli.NewContext(nil, globalSet, nil)
	c := cli.NewContext(nil, set, globalCtx)
	set.Parse([]string{"--myflag", "--otherflag=foo"})
	globalSet.Parse([]string{"--myflagGlobal"})
	expect(t, c.NumFlags(), 2)
}
Example #25
0
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")
	globalCtx := cli.NewContext(nil, globalSet, nil)
	command := cli.Command{Name: "mycommand"}
	c := cli.NewContext(nil, set, globalCtx)
	c.Command = command
	expect(t, c.Int("myflag"), 12)
	expect(t, c.GlobalInt("myflag"), 42)
	expect(t, c.Command.Name, "mycommand")
}
Example #26
0
func getTestClient() *seaweed.Client {
	set := flag.NewFlagSet("test", 0)

	set.Int("myflag", 12, "doc")
	set.Float64("myflag64", float64(17), "doc")
	globalSet := flag.NewFlagSet("test", 0)
	globalSet.Int("myflag", 42, "doc")
	globalSet.Float64("myflag64", float64(47), "doc")

	globalCtx := cli.NewContext(nil, globalSet, nil)
	context := cli.NewContext(nil, set, globalCtx)

	return client(context)
}
Example #27
0
func TestContext_IsSet(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")
	globalCtx := cli.NewContext(nil, globalSet, nil)
	c := cli.NewContext(nil, set, globalCtx)
	set.Parse([]string{"--myflag", "bat", "baz"})
	globalSet.Parse([]string{"--myflagGlobal", "bat", "baz"})
	expect(t, c.IsSet("myflag"), true)
	expect(t, c.IsSet("otherflag"), false)
	expect(t, c.IsSet("bogusflag"), false)
	expect(t, c.IsSet("myflagGlobal"), false)
}
Example #28
0
func (suite *CliSuite) TestSetupApp() {
	globatCtx := cli.NewContext(nil, suite.globalSet, nil)
	err := setupApplication(globatCtx, func(configFile string) (*configuration.Configuration, error) {
		config := &configuration.Configuration{
			Logging: configuration.Loggging{
				Level:     "debug",
				Output:    "console",
				Formatter: "text",
			},
			Clusters: map[string]configuration.Cluster{
				"local": {
					Disabled: true,
					Framework: configuration.Framework{
						"marathon": configuration.Parameters{
							"address": "http://localhost:8011",
						},
					},
				},
				"remote": {
					Framework: configuration.Framework{
						"marathon": configuration.Parameters{
							"address":        "http://remote:8011",
							"deploy-timeout": 30,
						},
					},
				},
			},
		}

		return config, nil
	})
	assert.Nil(suite.T(), err, "Should return nil")
}
func TestShowAvailabilityZone(t *testing.T) {
	expectedStruct := photon.AvailabilityZone{
		ID:   "availabilityzone_id",
		Name: "availabilityzone_name",
	}

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

	server := mocks.NewTestServer()
	mocks.RegisterResponder(
		"GET",
		server.URL+"/availabilityzones/"+expectedStruct.ID,
		mocks.CreateResponder(200, string(response[:])))
	defer server.Close()

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

	set := flag.NewFlagSet("test", 0)
	err = set.Parse([]string{expectedStruct.ID})
	cxt := cli.NewContext(nil, set, nil)
	err = showAvailabilityZone(cxt, os.Stdout)
	if err != nil {
		t.Error("Not expecting show availabilityzone to fail: " + err.Error())
	}
}
Example #30
0
func TestResizeHandleSingle(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.Set("id", "server1")
	c := cli.NewContext(app, flagset, nil)
	cmd := &commandResize{
		Ctx: &handler.Context{
			CLIContext:    c,
			ServiceClient: client.ServiceClient(),
		},
	}
	expected := &handler.Resource{
		Params: &paramsResize{
			serverID: "server1",
		},
	}
	actual := &handler.Resource{
		Params: &paramsResize{},
	}
	err := cmd.HandleSingle(actual)
	th.AssertNoErr(t, err)
	th.AssertEquals(t, expected.Params.(*paramsResize).serverID, actual.Params.(*paramsResize).serverID)
}