Exemplo n.º 1
0
// Test the handler for MODE messages
func TestMODE(t *testing.T) {
	c, s := setUp(t)
	defer s.tearDown()

	// Channel modes
	gomock.InOrder(
		s.st.EXPECT().GetChannel("#test1").Return(&state.Channel{Name: "#test1"}),
		s.st.EXPECT().ChannelModes("#test1", "+sk", "somekey"),
	)
	c.h_MODE(ParseLine(":[email protected] MODE #test1 +sk somekey"))

	// Nick modes for Me.
	gomock.InOrder(
		s.st.EXPECT().GetChannel("test").Return(nil),
		s.st.EXPECT().GetNick("test").Return(c.cfg.Me),
		s.st.EXPECT().Me().Return(c.cfg.Me),
		s.st.EXPECT().NickModes("test", "+i"),
	)
	c.h_MODE(ParseLine(":[email protected] MODE test +i"))

	// Check error paths
	gomock.InOrder(
		// send a valid user mode that's not us
		s.st.EXPECT().GetChannel("user1").Return(nil),
		s.st.EXPECT().GetNick("user1").Return(&state.Nick{Nick: "user1"}),
		s.st.EXPECT().Me().Return(c.cfg.Me),
		// Send a random mode for an unknown channel
		s.st.EXPECT().GetChannel("#test2").Return(nil),
		s.st.EXPECT().GetNick("#test2").Return(nil),
	)
	c.h_MODE(ParseLine(":[email protected] MODE user1 +w"))
	c.h_MODE(ParseLine(":[email protected] MODE #test2 +is"))
}
Exemplo n.º 2
0
// Test the handler for 352 / RPL_WHOREPLY
func Test352(t *testing.T) {
	c, s := setUp(t)
	defer s.tearDown()

	// Ensure 352 reply calls NickInfo and NickModes
	gomock.InOrder(
		s.st.EXPECT().GetNick("user1").Return(&state.Nick{Nick: "user1"}),
		s.st.EXPECT().Me().Return(c.cfg.Me),
		s.st.EXPECT().NickInfo("user1", "ident1", "host1.com", "name"),
	)
	c.h_352(ParseLine(":irc.server.org 352 test #test1 ident1 host1.com irc.server.org user1 G :0 name"))

	// Check that modes are set correctly from WHOREPLY
	gomock.InOrder(
		s.st.EXPECT().GetNick("user1").Return(&state.Nick{Nick: "user1"}),
		s.st.EXPECT().Me().Return(c.cfg.Me),
		s.st.EXPECT().NickInfo("user1", "ident1", "host1.com", "name"),
		s.st.EXPECT().NickModes("user1", "+o"),
		s.st.EXPECT().NickModes("user1", "+i"),
	)
	c.h_352(ParseLine(":irc.server.org 352 test #test1 ident1 host1.com irc.server.org user1 H* :0 name"))

	// Check error paths -- send a 352 for an unknown nick
	s.st.EXPECT().GetNick("user2").Return(nil)
	c.h_352(ParseLine(":irc.server.org 352 test #test2 ident2 host2.com irc.server.org user2 G :0 fooo"))
}
Exemplo n.º 3
0
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)
	}
}
Exemplo n.º 4
0
func TestContainerStatsCollectionReconnection(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()
	mockDockerClient := ecsengine.NewMockDockerClient(ctrl)

	dockerID := "container1"
	ctx, cancel := context.WithCancel(context.TODO())

	statChan := make(chan *docker.Stats)
	statErr := fmt.Errorf("test error")
	closedChan := make(chan *docker.Stats)
	close(closedChan)
	gomock.InOrder(
		mockDockerClient.EXPECT().Stats(dockerID, ctx).Return(nil, statErr),
		mockDockerClient.EXPECT().Stats(dockerID, ctx).Return(closedChan, nil),
		mockDockerClient.EXPECT().Stats(dockerID, ctx).Return(statChan, nil),
	)

	container := &StatsContainer{
		containerMetadata: &ContainerMetadata{
			DockerID: dockerID,
		},
		ctx:    ctx,
		cancel: cancel,
		client: mockDockerClient,
	}
	container.StartStatsCollection()
	time.Sleep(checkPointSleep)
	container.StopStatsCollection()
}
Exemplo n.º 5
0
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)
	}
}
Exemplo n.º 6
0
func TestValidationError(t *testing.T) {
	u, ctrl, _, mockfs, mockacs, mockhttp := mocks(t, nil)
	defer ctrl.Finish()

	var writtenFile bytes.Buffer
	gomock.InOrder(
		mockhttp.EXPECT().RoundTrip(mock_http.NewHTTPSimpleMatcher("GET", "https://s3.amazonaws.com/amazon-ecs-agent/update.tar")).Return(mock_http.SuccessResponse("update-tar-data"), nil),
		mockfs.EXPECT().Create(gomock.Any()).Return(mock_os.NopReadWriteCloser(&writtenFile), nil),
		mockfs.EXPECT().Remove(gomock.Any()),
		mockacs.EXPECT().MakeRequest(&nackRequestMatcher{&ecsacs.NackRequest{
			Cluster:           ptr("cluster").(*string),
			ContainerInstance: ptr("containerInstance").(*string),
			MessageId:         ptr("StageMID").(*string),
		}}),
	)

	u.stageUpdateHandler()(&ecsacs.StageUpdateMessage{
		ClusterArn:           ptr("cluster").(*string),
		ContainerInstanceArn: ptr("containerInstance").(*string),
		MessageId:            ptr("StageMID").(*string),
		UpdateInfo: &ecsacs.UpdateInfo{
			Location:  ptr("https://s3.amazonaws.com/amazon-ecs-agent/update.tar").(*string),
			Signature: ptr("Invalid signature").(*string),
		},
	})

	if writtenFile.String() != "update-tar-data" {
		t.Error("Incorrect data written")
	}
}
Exemplo n.º 7
0
// Test the handler for 001 / RPL_WELCOME
func Test001(t *testing.T) {
	c, s := setUp(t)
	defer s.tearDown()

	l := ParseLine(":irc.server.org 001 test :Welcome to IRC [email protected]")
	// Set up a handler to detect whether connected handler is called from 001
	hcon := false
	c.HandleFunc("connected", func(conn *Conn, line *Line) {
		hcon = true
	})

	// Test state tracking first.
	gomock.InOrder(
		s.st.EXPECT().Me().Return(c.cfg.Me),
		s.st.EXPECT().NickInfo("test", "test", "somehost.com", "Testing IRC"),
	)
	// Call handler with a valid 001 line
	c.h_001(l)
	<-time.After(time.Millisecond)
	if !hcon {
		t.Errorf("001 handler did not dispatch connected event.")
	}

	// Now without state tracking.
	c.st = nil
	c.h_001(l)
	// Check host parsed correctly
	if c.cfg.Me.Host != "somehost.com" {
		t.Errorf("Host parsing failed, host is '%s'.", c.cfg.Me.Host)
	}
	c.st = s.st
}
Exemplo n.º 8
0
func TestControllerWaitExitError(t *testing.T) {
	task := genTask(t)
	ctx, client, ctlr, config, finish := genTestControllerEnv(t, task)
	defer finish(t)

	gomock.InOrder(
		client.EXPECT().ContainerInspect(gomock.Any(), config.name()).
			Return(types.ContainerJSON{
				ContainerJSONBase: &types.ContainerJSONBase{
					State: &types.ContainerState{
						Status: "running",
					},
				},
			}, nil),
		client.EXPECT().Events(gomock.Any(), types.EventsOptions{
			Since:   "0",
			Filters: config.eventFilter(),
		}).Return(makeEvents(t, config, "create", "die"), nil),
		client.EXPECT().ContainerInspect(gomock.Any(), config.name()).
			Return(types.ContainerJSON{
				ContainerJSONBase: &types.ContainerJSONBase{
					ID: "cid",
					State: &types.ContainerState{
						Status:   "exited", // can be anything but created
						ExitCode: 1,
						Pid:      1,
					},
				},
			}, nil),
	)

	err := ctlr.Wait(ctx)
	checkExitError(t, 1, err)
}
Exemplo n.º 9
0
func TestStartSupervisedExitsWhenTerminalSuccess(t *testing.T) {
	mockCtrl := gomock.NewController(t)
	defer mockCtrl.Finish()

	mockDocker := NewMockdockerClient(mockCtrl)

	gomock.InOrder(
		mockDocker.EXPECT().RemoveExistingAgentContainer(),
		mockDocker.EXPECT().StartAgent().Return(1, nil),
		mockDocker.EXPECT().RemoveExistingAgentContainer(),
		mockDocker.EXPECT().StartAgent().Return(1, nil),
		mockDocker.EXPECT().RemoveExistingAgentContainer(),
		mockDocker.EXPECT().StartAgent().Return(1, nil),
		mockDocker.EXPECT().RemoveExistingAgentContainer(),
		mockDocker.EXPECT().StartAgent().Return(terminalSuccessAgentExitCode, nil),
	)

	engine := &Engine{
		docker: mockDocker,
	}
	err := engine.StartSupervised()
	if err != nil {
		t.Error("Expected error to be nil but was returned")
	}
}
func TestCreateContainerForceSave(t *testing.T) {
	ctrl, client, _, privateTaskEngine, _ := mocks(t, &config.Config{})
	saver := mock_statemanager.NewMockStateManager(ctrl)
	defer ctrl.Finish()
	taskEngine, _ := privateTaskEngine.(*DockerTaskEngine)
	taskEngine.SetSaver(saver)

	sleepTask := testdata.LoadTask("sleep5")
	sleepContainer, _ := sleepTask.ContainerByName("sleep5")

	gomock.InOrder(
		saver.EXPECT().ForceSave().Do(func() interface{} {
			task, ok := taskEngine.state.TaskByArn(sleepTask.Arn)
			if task == nil || !ok {
				t.Fatalf("Expected task with arn %s", sleepTask.Arn)
			}
			_, ok = task.ContainerByName("sleep5")
			if !ok {
				t.Error("Expected container sleep5")
			}
			return nil
		}),
		client.EXPECT().CreateContainer(gomock.Any(), gomock.Any(), gomock.Any()),
	)

	metadata := taskEngine.createContainer(sleepTask, sleepContainer)
	if metadata.Error != nil {
		t.Error("Unexpected error", metadata.Error)
	}
}
Exemplo n.º 11
0
func TestControllerWait(t *testing.T) {
	task := genTask(t)
	ctx, client, ctlr, config, finish := genTestControllerEnv(t, task)
	defer finish(t)

	evs, errs := makeEvents(t, config, "create", "die")
	gomock.InOrder(
		client.EXPECT().ContainerInspect(gomock.Any(), config.name()).
			Return(types.ContainerJSON{
				ContainerJSONBase: &types.ContainerJSONBase{
					State: &types.ContainerState{
						Status: "running",
					},
				},
			}, nil),
		client.EXPECT().Events(gomock.Any(), types.EventsOptions{
			Since:   "0",
			Filters: config.eventFilter(),
		}).Return(evs, errs),
		client.EXPECT().ContainerInspect(gomock.Any(), config.name()).
			Return(types.ContainerJSON{
				ContainerJSONBase: &types.ContainerJSONBase{
					State: &types.ContainerState{
						Status: "stopped", // can be anything but created
					},
				},
			}, nil),
	)

	assert.NoError(t, ctlr.Wait(ctx))
}
Exemplo n.º 12
0
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")
	}
}
Exemplo n.º 13
0
// TestCase: Wrong message type has been received in the client.
func TestClientWrongMessageType(t *testing.T) {
	mockCtrl := gomock.NewController(t)
	transport := thrift.NewTMemoryBuffer()
	protocol := NewMockTProtocol(mockCtrl)
	gomock.InOrder(
		protocol.EXPECT().WriteMessageBegin("testString", thrift.CALL, int32(1)),
		protocol.EXPECT().WriteStructBegin("testString_args"),
		protocol.EXPECT().WriteFieldBegin("s", thrift.TType(thrift.STRING), int16(1)),
		protocol.EXPECT().WriteString("test"),
		protocol.EXPECT().WriteFieldEnd(),
		protocol.EXPECT().WriteFieldStop(),
		protocol.EXPECT().WriteStructEnd(),
		protocol.EXPECT().WriteMessageEnd(),
		protocol.EXPECT().Flush(),
		protocol.EXPECT().ReadMessageBegin().Return("testString", thrift.INVALID_TMESSAGE_TYPE, int32(1), nil),
	)

	client := errortest.NewErrorTestClientProtocol(transport, protocol, protocol)
	_, err := client.TestString("test")
	mockCtrl.Finish()
	appErr, ok := err.(thrift.TApplicationException)
	if !ok {
		t.Fatal("Expected TApplicationException")
	}
	if appErr.TypeId() != thrift.INVALID_MESSAGE_TYPE_EXCEPTION {
		t.Fatal("Expected INVALID_MESSAGE_TYPE_EXCEPTION error")
	}
}
Exemplo n.º 14
0
// TestCase: Mismatching sequence id has been received in the client.
func TestClientSeqIdMismatch(t *testing.T) {
	mockCtrl := gomock.NewController(t)
	transport := thrift.NewTMemoryBuffer()
	protocol := NewMockTProtocol(mockCtrl)
	gomock.InOrder(
		protocol.EXPECT().WriteMessageBegin("testString", thrift.CALL, int32(1)),
		protocol.EXPECT().WriteStructBegin("testString_args"),
		protocol.EXPECT().WriteFieldBegin("s", thrift.TType(thrift.STRING), int16(1)),
		protocol.EXPECT().WriteString("test"),
		protocol.EXPECT().WriteFieldEnd(),
		protocol.EXPECT().WriteFieldStop(),
		protocol.EXPECT().WriteStructEnd(),
		protocol.EXPECT().WriteMessageEnd(),
		protocol.EXPECT().Flush(),
		protocol.EXPECT().ReadMessageBegin().Return("testString", thrift.REPLY, int32(2), nil),
	)

	client := errortest.NewErrorTestClientProtocol(transport, protocol, protocol)
	_, err := client.TestString("test")
	mockCtrl.Finish()
	appErr, ok := err.(thrift.TApplicationException)
	if !ok {
		t.Fatal("Expected TApplicationException")
	}
	if appErr.TypeId() != thrift.BAD_SEQUENCE_ID {
		t.Fatal("Expected BAD_SEQUENCE_ID error")
	}
}
func TestCreateContainerInspectTimeout(t *testing.T) {
	mockDocker, client, testTime, done := dockerclientSetup(t)
	defer done()

	warp := make(chan time.Time)
	testTime.EXPECT().After(inspectContainerTimeout).Return(warp)
	testTime.EXPECT().After(gomock.Any()).AnyTimes()
	wait := &sync.WaitGroup{}
	wait.Add(1)
	config := docker.CreateContainerOptions{Config: &docker.Config{Memory: 100}, Name: "containerName"}
	gomock.InOrder(
		mockDocker.EXPECT().CreateContainer(config).Return(&docker.Container{ID: "id"}, nil),
		mockDocker.EXPECT().InspectContainer("id").Do(func(x interface{}) {
			warp <- time.Now()
			wait.Wait()
		}),
	)
	metadata := client.CreateContainer(config.Config, nil, config.Name)
	if metadata.DockerId != "id" {
		t.Error("Expected ID to be set even if inspect failed; was " + metadata.DockerId)
	}
	if metadata.Error == nil {
		t.Error("Expected error for inspect timeout")
	}
	wait.Done()
}
Exemplo n.º 16
0
func TestStartSupervisedUpgrade(t *testing.T) {
	mockCtrl := gomock.NewController(t)
	defer mockCtrl.Finish()

	mockDocker := NewMockdockerClient(mockCtrl)
	mockDownloader := NewMockdownloader(mockCtrl)

	gomock.InOrder(
		mockDocker.EXPECT().RemoveExistingAgentContainer(),
		mockDocker.EXPECT().StartAgent().Return(upgradeAgentExitCode, nil),
		mockDownloader.EXPECT().LoadDesiredAgent().Return(&os.File{}, nil),
		mockDocker.EXPECT().LoadImage(gomock.Any()),
		mockDownloader.EXPECT().RecordCachedAgent(),
		mockDocker.EXPECT().RemoveExistingAgentContainer(),
		mockDocker.EXPECT().StartAgent().Return(terminalSuccessAgentExitCode, nil),
	)

	engine := &Engine{
		downloader: mockDownloader,
		docker:     mockDocker,
	}
	err := engine.StartSupervised()
	if err != nil {
		t.Error("Expected error to be nil but was returned")
	}
}
Exemplo n.º 17
0
// Test the handler for 433 / ERR_NICKNAMEINUSE
func Test433(t *testing.T) {
	c, s := setUp(t)
	defer s.tearDown()

	// Call handler with a 433 line, not triggering c.cfg.Me.Renick()
	s.st.EXPECT().Me().Return(c.cfg.Me)
	c.h_433(ParseLine(":irc.server.org 433 test new :Nickname is already in use."))
	s.nc.Expect("NICK new_")

	// Send a line that will trigger a renick. This happens when our wanted
	// nick is unavailable during initial negotiation, so we must choose a
	// different one before the connection can proceed. No NICK line will be
	// sent by the server to confirm nick change in this case.
	gomock.InOrder(
		s.st.EXPECT().Me().Return(c.cfg.Me),
		s.st.EXPECT().ReNick("test", "test_").Return(c.cfg.Me),
	)
	c.h_433(ParseLine(":irc.server.org 433 test test :Nickname is already in use."))
	s.nc.Expect("NICK test_")

	// Test the code path that *doesn't* involve state tracking.
	c.st = nil
	c.h_433(ParseLine(":irc.server.org 433 test test :Nickname is already in use."))
	s.nc.Expect("NICK test_")

	if c.cfg.Me.Nick != "test_" {
		t.Errorf("My nick not updated from '%s'.", c.cfg.Me.Nick)
	}
	c.st = s.st
}
Exemplo n.º 18
0
func TestPrepareAlready(t *testing.T) {
	var (
		task              = newTestTask(t, api.TaskStateAssigned, api.TaskStateRunning)
		ctx, ctlr, finish = buildTestEnv(t, task)
	)
	defer finish()
	gomock.InOrder(
		ctlr.EXPECT().Prepare(gomock.Any()).Return(ErrTaskPrepared),
	)

	// Report acceptance.
	status := checkDo(t, ctx, task, ctlr, &api.TaskStatus{
		State:   api.TaskStateAccepted,
		Message: "accepted",
	})

	// Actually prepare the task.
	task.Status = *status

	status = checkDo(t, ctx, task, ctlr, &api.TaskStatus{
		State:   api.TaskStatePreparing,
		Message: "preparing",
	})

	task.Status = *status

	checkDo(t, ctx, task, ctlr, &api.TaskStatus{
		State:   api.TaskStateReady,
		Message: "prepared",
	})
}
Exemplo n.º 19
0
func TestRegisterTaskDefinitionIfNeededCachedTDIsInactive(t *testing.T) {
	mockEcs, mockCache, client, ctrl := setupTestController(t, &defaultCliConfigParams)
	defer ctrl.Finish()

	registerTaskDefinitionInput1 := ecs.RegisterTaskDefinitionInput{
		Family: aws.String("family1"),
		ContainerDefinitions: []*ecs.ContainerDefinition{
			{
				Name: aws.String("foo"),
			},
		},
	}
	taskDefinition2 := ecs.TaskDefinition{
		Family:            registerTaskDefinitionInput1.Family,
		Revision:          aws.Int64(2),
		Status:            aws.String(ecs.TaskDefinitionStatusActive),
		TaskDefinitionArn: aws.String("arn:aws:ecs:region1:123456:task-definition/family1:2"),
	}
	taskDefinition1CachedInactive := ecs.TaskDefinition{
		Family:            registerTaskDefinitionInput1.Family,
		Revision:          aws.Int64(1),
		Status:            aws.String(ecs.TaskDefinitionStatusInactive),
		TaskDefinitionArn: aws.String("arn:aws:ecs:region1:123456:task-definition/family1:1"),
	}
	describeTaskDefinitionInput2 := ecs.DescribeTaskDefinitionInput{
		TaskDefinition: registerTaskDefinitionInput1.Family,
	}
	describeTaskDefinitionInput1Inactive := ecs.DescribeTaskDefinitionInput{
		TaskDefinition: taskDefinition1CachedInactive.TaskDefinitionArn,
	}

	gomock.InOrder(
		mockEcs.EXPECT().DescribeTaskDefinition(&describeTaskDefinitionInput2).
			Return(&ecs.DescribeTaskDefinitionOutput{TaskDefinition: &taskDefinition2}, nil),

		mockCache.EXPECT().Get(gomock.Any(), gomock.Any()).Do(func(x, y interface{}) {
			*y.(*ecs.TaskDefinition) = taskDefinition1CachedInactive
		}).Return(nil),

		mockEcs.EXPECT().DescribeTaskDefinition(&describeTaskDefinitionInput1Inactive).
			Return(&ecs.DescribeTaskDefinitionOutput{TaskDefinition: &taskDefinition1CachedInactive}, nil),

		mockEcs.EXPECT().RegisterTaskDefinition(&registerTaskDefinitionInput1).
			Return(&ecs.RegisterTaskDefinitionOutput{TaskDefinition: &taskDefinition2}, nil),

		mockCache.EXPECT().Put(gomock.Any(), gomock.Any()).Return(nil),
	)

	resp1, err := client.RegisterTaskDefinitionIfNeeded(&registerTaskDefinitionInput1, mockCache)
	if err != nil {
		t.Fatal(err)
	}

	if *resp1.Revision <= *taskDefinition1CachedInactive.Revision {
		t.Errorf("Expected revison of response to be incremented because the cached task definition is INACTIVE: %v:%v",
			*taskDefinition1CachedInactive.Revision, *resp1.Revision)
	}

}
Exemplo n.º 20
0
func TestClusterUp(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")
	}()

	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()).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(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)
	}
}
Exemplo n.º 21
0
// Test the handler for 353 / RPL_NAMREPLY
func Test353(t *testing.T) {
	c, s := setUp(t)
	defer s.tearDown()

	// 353 handler is called twice, so GetChannel will be called twice
	s.st.EXPECT().GetChannel("#test1").Return(&state.Channel{Name: "#test1"}).Times(2)
	gomock.InOrder(
		// "test" is Me, i am known, and already on the channel
		s.st.EXPECT().GetNick("test").Return(c.cfg.Me),
		s.st.EXPECT().IsOn("#test1", "test").Return(&state.ChanPrivs{}, true),
		// user1 is known, but not on the channel, so should be associated
		s.st.EXPECT().GetNick("user1").Return(&state.Nick{Nick: "user1"}),
		s.st.EXPECT().IsOn("#test1", "user1").Return(nil, false),
		s.st.EXPECT().Associate("#test1", "user1").Return(&state.ChanPrivs{}),
		s.st.EXPECT().ChannelModes("#test1", "+o", "user1"),
	)
	for n, m := range map[string]string{
		"user2":  "",
		"voice":  "+v",
		"halfop": "+h",
		"op":     "+o",
		"admin":  "+a",
		"owner":  "+q",
	} {
		calls := []*gomock.Call{
			s.st.EXPECT().GetNick(n).Return(nil),
			s.st.EXPECT().NewNick(n).Return(&state.Nick{Nick: n}),
			s.st.EXPECT().IsOn("#test1", n).Return(nil, false),
			s.st.EXPECT().Associate("#test1", n).Return(&state.ChanPrivs{}),
		}
		if m != "" {
			calls = append(calls, s.st.EXPECT().ChannelModes("#test1", m, n))
		}
		gomock.InOrder(calls...)
	}

	// Send a couple of names replies (complete with trailing space)
	c.h_353(ParseLine(":irc.server.org 353 test = #test1 :test @user1 user2 +voice "))
	c.h_353(ParseLine(":irc.server.org 353 test = #test1 :%halfop @op &admin ~owner "))

	// Check error paths -- send 353 for an unknown channel
	s.st.EXPECT().GetChannel("#test2").Return(nil)
	c.h_353(ParseLine(":irc.server.org 353 test = #test2 :test ~user3"))
}
Exemplo n.º 22
0
func createServiceTest(t *testing.T, cliContext *cli.Context, validateDeploymentConfig validateDeploymentConfiguration) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	taskDefId := "taskDefinitionId"
	taskDefArn := "arn/" + taskDefId

	taskDefinition := ecs.TaskDefinition{
		Family:               aws.String("family"),
		ContainerDefinitions: []*ecs.ContainerDefinition{},
		Volumes:              []*ecs.Volume{},
	}
	respTaskDef := taskDefinition
	respTaskDef.TaskDefinitionArn = aws.String(taskDefArn)

	mockEcs := mock_ecs.NewMockECSClient(ctrl)
	gomock.InOrder(
		mockEcs.EXPECT().RegisterTaskDefinitionIfNeeded(gomock.Any(), gomock.Any()).Do(func(x, y interface{}) {
			// verify input fields
			req := x.(*ecs.RegisterTaskDefinitionInput)
			if aws.StringValue(taskDefinition.Family) != aws.StringValue(req.Family) {
				t.Errorf("Expected taskDefintion family to be [%s] but got [%s]",
					aws.StringValue(taskDefinition.Family), aws.StringValue(req.Family))
			}
		}).Return(&respTaskDef, nil),
		mockEcs.EXPECT().CreateService(gomock.Any(), gomock.Any(), gomock.Any()).Do(func(x, y, z interface{}) {
			observedTaskDefId := y.(string)
			if taskDefId != observedTaskDefId {
				t.Errorf("Expected task definition name to be [%s] but got [%s]", taskDefId, observedTaskDefId)
			}
			observedDeploymentConfig := z.(*ecs.DeploymentConfiguration)
			validateDeploymentConfig(observedDeploymentConfig)
		}).Return(nil),
	)

	context := &Context{
		ECSClient:  mockEcs,
		ECSParams:  &config.CliParams{},
		CLIContext: cliContext,
	}

	service := NewService(context)
	if err := service.LoadContext(); err != nil {
		t.Fatal("Unexpected error while loading context in create service test")
	}
	service.SetTaskDefinition(&taskDefinition)
	if err := service.Create(); err != nil {
		t.Fatal("Unexpected error while create")
	}

	// task definition should be set
	if taskDefArn != aws.StringValue(service.TaskDefinition().TaskDefinitionArn) {
		t.Errorf("Expected service TaskDefArn to be [%s] but got [%s]",
			taskDefArn, aws.StringValue(service.TaskDefinition().TaskDefinitionArn))
	}
}
Exemplo n.º 23
0
func TestAlreadyStarted(t *testing.T) {
	var (
		task              = newTestTask(t, api.TaskStateReady, api.TaskStateRunning)
		ctx, ctlr, finish = buildTestEnv(t, task)
	)
	defer finish()

	dctlr := &decorateController{
		MockController: ctlr,
		cstatus: &api.ContainerStatus{
			ExitCode: 1,
		},
	}

	gomock.InOrder(
		ctlr.EXPECT().Start(gomock.Any()).Return(ErrTaskStarted),
		ctlr.EXPECT().Wait(gomock.Any()).Return(context.Canceled),
		ctlr.EXPECT().Wait(gomock.Any()).Return(newExitError(1)),
	)

	// Before we can move to running, we have to move to startin.
	status := checkDo(t, ctx, task, ctlr, &api.TaskStatus{
		State:   api.TaskStateStarting,
		Message: "starting",
	})

	task.Status = *status

	// start the container
	status = checkDo(t, ctx, task, ctlr, &api.TaskStatus{
		State:   api.TaskStateRunning,
		Message: "started",
	})

	task.Status = *status

	status = checkDo(t, ctx, task, ctlr, &api.TaskStatus{
		State:   api.TaskStateRunning,
		Message: "started",
	}, ErrTaskRetry)

	task.Status = *status

	// now take the real exit to test wait cancelling.
	checkDo(t, ctx, task, dctlr, &api.TaskStatus{
		State: api.TaskStateFailed,
		RuntimeStatus: &api.TaskStatus_Container{
			Container: &api.ContainerStatus{
				ExitCode: 1,
			},
		},
		Message: "started",
		Err:     "test error, exit code=1",
	})

}
Exemplo n.º 24
0
Arquivo: ctests.go Projeto: kego/ke
func (cb *ClientContextBuilder) ExpectNotified(object interface{}, notif flux.Notif, data interface{}) *ClientContextBuilder {
	closedChannel := func() chan struct{} {
		c := make(chan struct{}, 1)
		close(c)
		return c
	}
	call := cb.GetNotifier().EXPECT().NotifyWithData(object, notif, data).Return(closedChannel())
	gomock.InOrder(call)
	return cb
}
Exemplo n.º 25
0
func TestClusterUpWithVPC(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()
	mockECS := mock_ecs.NewMockECSClient(ctrl)
	mockCloudformation := mock_cloudformation.NewMockCloudformationClient(ctrl)
	vpcId := "vpc-02dd3038"
	subnetIds := "subnet-04726b21,subnet-04346b21"

	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(clusterName).Return(clusterName, nil),
	)

	gomock.InOrder(
		mockCloudformation.EXPECT().Initialize(gomock.Any()),
		mockCloudformation.EXPECT().ValidateStackExists(stackName).Return(errors.New("error")),
		mockCloudformation.EXPECT().CreateStack(gomock.Any(), stackName, gomock.Any()).Return("", nil),
		mockCloudformation.EXPECT().WaitUntilCreateComplete(stackName).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(vpcIdFlag, vpcId, "")
	flagSet.String(subnetIdsFlag, subnetIds, "")

	context := cli.NewContext(nil, flagSet, globalContext)
	err := createCluster(context, newMockReadWriter(), mockECS, mockCloudformation, ami.NewStaticAmiIds())
	if err != nil {
		t.Fatal("Error bringing up cluster: ", err)
	}
}
Exemplo n.º 26
0
func TestDispatcher_Notify(t *testing.T) {
	m := gomock.NewController(t)
	defer m.Finish()
	not := mock_flux.NewMockNotifierInterface(m)
	a := &st1{}
	gomock.InOrder(not.EXPECT().NotifyWithData("a", notif1{}, nil).Return(closedChannel()))
	d := flux.NewDispatcher(not, a)
	done := d.Dispatch(false)
	<-done
}
Exemplo n.º 27
0
// TestHandlerReconnectsCorrectlySetsSendCredentialsURLParameter tests if
// the 'sendCredentials' URL parameter is set correctly for successive
// invocations of startACSSession
func TestHandlerReconnectsCorrectlySetsSendCredentialsURLParameter(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()
	taskEngine := engine.NewMockTaskEngine(ctrl)
	ecsClient := mock_api.NewMockECSClient(ctrl)
	statemanager := statemanager.NewNoopStateManager()

	ctx, cancel := context.WithCancel(context.Background())
	mockWsClient := mock_wsclient.NewMockClientServer(ctrl)

	args := StartSessionArguments{
		ContainerInstanceArn: "myArn",
		CredentialProvider:   credentials.AnonymousCredentials,
		Config:               &config.Config{Cluster: "someCluster"},
		TaskEngine:           taskEngine,
		ECSClient:            ecsClient,
		StateManager:         statemanager,
		AcceptInvalidCert:    true,
		_heartbeatTimeout:    20 * time.Millisecond,
		_heartbeatJitter:     10 * time.Millisecond,
	}
	session := newSessionResources(args)

	mockWsClient.EXPECT().SetAnyRequestHandler(gomock.Any()).AnyTimes()
	mockWsClient.EXPECT().AddRequestHandler(gomock.Any()).AnyTimes()
	mockWsClient.EXPECT().Close().Return(nil).AnyTimes()
	mockWsClient.EXPECT().Serve().Return(io.EOF).AnyTimes()
	gomock.InOrder(
		// When the websocket client connects to ACS for the first
		// time, 'sendCredentials' should be set to true
		mockWsClient.EXPECT().Connect().Do(func() {
			validateSendCredentialsInSession(t, session, "true")
		}).Return(nil),
		// For all subsequent connections to ACS, 'sendCredentials'
		// should be set to false
		mockWsClient.EXPECT().Connect().Do(func() {
			validateSendCredentialsInSession(t, session, "false")
		}).Return(nil).AnyTimes(),
	)

	backoff := utils.NewSimpleBackoff(connectionBackoffMin, connectionBackoffMax, connectionBackoffJitter, connectionBackoffMultiplier)
	timer := newDisconnectionTimer(mockWsClient, args.time(), args.heartbeatTimeout(), args.heartbeatJitter())
	defer timer.Stop()
	go func() {
		for i := 0; i < 10; i++ {
			startACSSession(ctx, mockWsClient, timer, args, backoff, session)
		}
		cancel()
	}()

	// Wait for context to be cancelled
	select {
	case <-ctx.Done():
	}
}
Exemplo n.º 28
0
func TestReadyRunning(t *testing.T) {
	var (
		task              = newTestTask(t, api.TaskStateReady, api.TaskStateRunning)
		ctx, ctlr, finish = buildTestEnv(t, task)
	)
	defer finish()

	gomock.InOrder(
		ctlr.EXPECT().Start(gomock.Any()),
		ctlr.EXPECT().Wait(gomock.Any()).Return(context.Canceled),
		ctlr.EXPECT().Wait(gomock.Any()),
	)

	dctlr := &decorateController{
		MockController: ctlr,
		cstatus: &api.ContainerStatus{
			ExitCode: 0,
		},
	}

	// Report starting
	status := checkDo(t, ctx, task, ctlr, &api.TaskStatus{
		State:   api.TaskStateStarting,
		Message: "starting",
	})

	task.Status = *status

	// start the container
	status = checkDo(t, ctx, task, ctlr, &api.TaskStatus{
		State:   api.TaskStateRunning,
		Message: "started",
	})

	task.Status = *status

	// resume waiting
	status = checkDo(t, ctx, task, ctlr, &api.TaskStatus{
		State:   api.TaskStateRunning,
		Message: "started",
	}, ErrTaskRetry)

	task.Status = *status
	// wait and cancel
	checkDo(t, ctx, task, dctlr, &api.TaskStatus{
		State:   api.TaskStateCompleted,
		Message: "finished",
		RuntimeStatus: &api.TaskStatus_Container{
			Container: &api.ContainerStatus{
				ExitCode: 0,
			},
		},
	})
}
Exemplo n.º 29
0
func TestControllerShutdown(t *testing.T) {
	task := genTask(t)
	ctx, client, ctlr, config, finish := genTestControllerEnv(t, task)
	defer finish(t)

	gomock.InOrder(
		client.EXPECT().ContainerStop(gomock.Any(), config.name(), 10*time.Second),
	)

	assert.NoError(t, ctlr.Shutdown(ctx))
}
//Make sure that optional fields are not being serialized
func TestNoOptionalUnsetFieldsOnWire(t *testing.T) {
	mockCtrl := gomock.NewController(t)
	defer mockCtrl.Finish()
	proto := NewMockTProtocol(mockCtrl)
	gomock.InOrder(
		proto.EXPECT().WriteStructBegin("all_optional").Return(nil),
		proto.EXPECT().WriteFieldStop().Return(nil),
		proto.EXPECT().WriteStructEnd().Return(nil),
	)
	ao := optionalfieldstest.NewAllOptional()
	ao.Write(proto)
}