// Test that KBPKI forces a cache flush one time if it can't find a // given verifying key. func TestKBPKIClientHasVerifyingKeyStaleCache(t *testing.T) { ctr := NewSafeTestReporter(t) mockCtrl := gomock.NewController(ctr) config := NewConfigMock(mockCtrl, ctr) c := NewKBPKIClient(config) config.SetKBPKI(c) defer func() { config.ctr.CheckForFailures() mockCtrl.Finish() }() u := keybase1.MakeTestUID(1) key1 := MakeLocalUserVerifyingKeyOrBust("u_1") key2 := MakeLocalUserVerifyingKeyOrBust("u_2") info1 := UserInfo{ VerifyingKeys: []VerifyingKey{key1}, } config.mockKbd.EXPECT().LoadUserPlusKeys(gomock.Any(), u). Return(info1, nil) config.mockKbd.EXPECT().FlushUserFromLocalCache(gomock.Any(), u) info2 := UserInfo{ VerifyingKeys: []VerifyingKey{key1, key2}, } config.mockKbd.EXPECT().LoadUserPlusKeys(gomock.Any(), u). Return(info2, nil) err := c.HasVerifyingKey(context.Background(), u, key2, time.Now()) if err != nil { t.Error(err) } }
func TestCreateContainerMergesLabels(t *testing.T) { ctrl, client, _, taskEngine, _ := mocks(t, &defaultConfig) defer ctrl.Finish() testTask := &api.Task{ Arn: "arn:aws:ecs:us-east-1:012345678910:task/c09f0188-7f87-4b0f-bfc3-16296622b6fe", Family: "myFamily", Version: "1", Containers: []*api.Container{ &api.Container{ Name: "c1", DockerConfig: api.DockerConfig{ Config: aws.String(`{"Labels":{"key":"value"}}`), }, }, }, } expectedConfig, err := testTask.DockerConfig(testTask.Containers[0]) if err != nil { t.Fatal(err) } expectedConfig.Labels = map[string]string{ "com.amazonaws.ecs.task-arn": "arn:aws:ecs:us-east-1:012345678910:task/c09f0188-7f87-4b0f-bfc3-16296622b6fe", "com.amazonaws.ecs.container-name": "c1", "com.amazonaws.ecs.task-definition-family": "myFamily", "com.amazonaws.ecs.task-definition-version": "1", "com.amazonaws.ecs.cluster": "", "key": "value", } client.EXPECT().CreateContainer(expectedConfig, gomock.Any(), gomock.Any()) taskEngine.(*DockerTaskEngine).createContainer(testTask, testTask.Containers[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") } }
func TestFunction_Rollback_latestVersion(t *testing.T) { mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() serviceMock := mock_lambdaiface.NewMockLambdaAPI(mockCtrl) deployedVersions := []*lambda.FunctionConfiguration{ &lambda.FunctionConfiguration{Version: aws.String("$LATEST")}, &lambda.FunctionConfiguration{Version: aws.String("1")}, &lambda.FunctionConfiguration{Version: aws.String("2")}, } currentVersion := aws.String("1") afterRollbackVersion := aws.String("2") serviceMock.EXPECT().GetAlias(gomock.Any()).Return(&lambda.AliasConfiguration{FunctionVersion: currentVersion}, nil) serviceMock.EXPECT().ListVersionsByFunction(gomock.Any()).Return(&lambda.ListVersionsByFunctionOutput{Versions: deployedVersions}, nil) serviceMock.EXPECT().UpdateAlias(&lambda.UpdateAliasInput{ FunctionName: aws.String("testfn"), Name: aws.String("current"), FunctionVersion: afterRollbackVersion, }) fn := &function.Function{ FunctionName: "testfn", Service: serviceMock, Log: log.Log, } err := fn.Rollback() assert.Nil(t, err) }
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) }
func TestCreateVpcReturnCreatedInstanceIfSuccess(t *testing.T) { //given ctrl := gomock.NewController(t) defer ctrl.Finish() mockEntityService := services_mocks.NewMockEntityService(ctrl) vpcService := VpcApi{ entityService: mockEntityService, } vpcToCreate := Vpc{Name: "new_name", Description: "new_description", VpcOfferingId: "vpc_offering_id", } mockEntityService.EXPECT().Create(gomock.Any(), gomock.Any()).Return([]byte(`{"id":"new_id"}`), nil) //when createdVpc, _ := vpcService.Create(vpcToCreate) //then if assert.NotNil(t, createdVpc) { assert.Equal(t, "new_id", createdVpc.Id) } }
func TestGCMConnector_GetErrorMessageFromGcm(t *testing.T) { ctrl, finish := testutil.NewMockCtrl(t) defer finish() // defer testutil.EnableDebugForMethod()() a := assert.New(t) routerMock := NewMockRouter(ctrl) routerMock.EXPECT().Subscribe(gomock.Any()).Do(func(route *server.Route) { a.Equal("/gcm/broadcast", string(route.Path)) a.Equal("gcm_connector", route.UserID) a.Equal("gcm_connector", route.ApplicationID) }) // expect the route unsubscribed from removeSubscription routerMock.EXPECT().Unsubscribe(gomock.Any()).Do(func(route *server.Route) { a.Equal("/path", string(route.Path)) a.Equal("id", route.ApplicationID) }) // expect the route subscribe with the new canonicalId from replaceSubscriptionWithCanonicalID routerMock.EXPECT().Subscribe(gomock.Any()).Do(func(route *server.Route) { a.Equal("/path", string(route.Path)) a.Equal("marvin", route.UserID) a.Equal("gcmCanonicalID", route.ApplicationID) }) kvStore := store.NewMemoryKVStore() routerMock.EXPECT().KVStore().Return(kvStore, nil) gcm, err := NewGCMConnector(routerMock, "/gcm/", "testApi", 1) a.Nil(err) err = gcm.Start() a.Nil(err) done := make(chan bool, 1) mockSender := testutil.CreateGcmSender( testutil.CreateRoundTripperWithJsonResponse(http.StatusOK, testutil.ErrorResponseMessageJSON, done)) gcm.Sender = mockSender // put a dummy gcm message with minimum information msg := &server.MessageForRoute{ Message: &protocol.Message{ ID: uint64(4), Body: []byte("{id:id}"), Time: 1405544146, Path: "/gcm/marvin/gcm124/subscribe/stuff"}, Route: &server.Route{ ApplicationID: "id", Path: "/path", UserID: "marvin"}} gcm.routerC <- msg // expect that the Http Server gives us a malformed message <-done //wait before closing the gcm connector time.Sleep(50 * time.Millisecond) err = gcm.Stop() a.NoError(err) }
func TestDownloadAgentMD5Mismatch(t *testing.T) { mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() md5response := &http.Response{} md5sum := "md5sum" tarballResponse := &http.Response{ StatusCode: 200, Body: ioutil.NopCloser(&bytes.Buffer{}), } mockFS := NewMockfileSystem(mockCtrl) mockFS.EXPECT().MkdirAll(config.CacheDirectory(), os.ModeDir|0700) mockGetter := NewMockhttpGetter(mockCtrl) mockGetter.EXPECT().Get(config.AgentRemoteTarballMD5()).Return(md5response, nil) mockFS.EXPECT().ReadAll(md5response.Body).Return([]byte(md5sum), nil) mockGetter.EXPECT().Get(config.AgentRemoteTarball()).Return(tarballResponse, nil) tempfile, err := ioutil.TempFile("", "test") if err != nil { t.Fail() } defer tempfile.Close() mockFS.EXPECT().TempFile("", "ecs-agent.tar").Return(tempfile, nil) mockFS.EXPECT().TeeReader(tarballResponse.Body, gomock.Any()) mockFS.EXPECT().Copy(tempfile, gomock.Any()).Return(int64(0), nil) mockFS.EXPECT().Remove(tempfile.Name()) d := &Downloader{ getter: mockGetter, fs: mockFS, } d.DownloadAgent() }
func TestCreateInstanceReturnCreatedInstanceIfSuccess(t *testing.T) { //given ctrl := gomock.NewController(t) defer ctrl.Finish() mockEntityService := services_mocks.NewMockEntityService(ctrl) instanceService := InstanceApi{ entityService: mockEntityService, } instanceToCreate := Instance{Id: "new_id", Name: "new_name", TemplateId: "templateId", ComputeOfferingId: "computeOfferingId", NetworkId: "networkId"} mockEntityService.EXPECT().Create(gomock.Any(), gomock.Any()).Return([]byte(`{"id":"new_id", "password": "******"}`), nil) //when createdInstance, _ := instanceService.Create(instanceToCreate) //then if assert.NotNil(t, createdInstance) { assert.Equal(t, "new_password", createdInstance.Password) } }
func TestWaitExhaustRetries(t *testing.T) { ctrl := gomock.NewController(t) mockCfn := mock_cloudformationiface.NewMockCloudFormationAPI(ctrl) cfnClient := NewCloudformationClient() cfnClient.(*cloudformationClient).client = mockCfn cfnClient.(*cloudformationClient).sleeper = &noopsleeper{} defer ctrl.Finish() eventCreateInProgress := createStackEvent(cloudformation.ResourceStatusCreateInProgress) mockCfn.EXPECT().DescribeStackEvents(gomock.Any()).AnyTimes().Return(eventCreateInProgress, nil) mockCfn.EXPECT().DescribeStacks(gomock.Any()).AnyTimes().Return(createDescribeStacksOutput(cloudformation.StackStatusCreateInProgress), nil) err := cfnClient.(*cloudformationClient).waitUntilComplete("", failureInCreateEvent, "", createStackFailures, 10) if err == nil { t.Error("Expected error waiting for create completion") } err = cfnClient.(*cloudformationClient).waitUntilComplete("", failureInDeleteEvent, "", deleteStackFailures, 10) if err == nil { t.Error("Expected error waiting for delete completion") } err = cfnClient.(*cloudformationClient).waitUntilComplete("", failureInUpdateEvent, "", updateStackFailures, 10) if err == nil { t.Error("Expected error waiting for update completion") } }
func TestWaitDescribeStackFailure(t *testing.T) { ctrl := gomock.NewController(t) mockCfn := mock_cloudformationiface.NewMockCloudFormationAPI(ctrl) cfnClient := NewCloudformationClient() cfnClient.(*cloudformationClient).client = mockCfn cfnClient.(*cloudformationClient).sleeper = &noopsleeper{} defer ctrl.Finish() // Create some stack events for firstStackEventWithFailure() to process. // latest event, no error. eventsWithFailure := createStackEvent(cloudformation.ResourceStatusCreateInProgress) eventsWithFailure.StackEvents = append(eventsWithFailure.StackEvents, &cloudformation.StackEvent{ ResourceStatus: aws.String(cloudformation.ResourceStatusCreateInProgress), }) // second event. failure. eventsWithFailure.StackEvents = append(eventsWithFailure.StackEvents, &cloudformation.StackEvent{ ResourceStatus: aws.String(cloudformation.ResourceStatusCreateFailed), ResourceStatusReason: aws.String("do you really wanna know?"), }) // oldest event, no error. eventsWithFailure.StackEvents = append(eventsWithFailure.StackEvents, &cloudformation.StackEvent{ ResourceStatus: aws.String(cloudformation.ResourceStatusCreateInProgress), }) mockCfn.EXPECT().DescribeStackEvents(gomock.Any()).AnyTimes().Return(eventsWithFailure, nil) mockCfn.EXPECT().DescribeStacks(gomock.Any()).Return(createDescribeStacksOutput(cloudformation.StackStatusCreateFailed), nil) err := cfnClient.(*cloudformationClient).waitUntilComplete("", failureInCreateEvent, "", createStackFailures, 10) if err == nil { t.Error("Expected error waiting for create completion") } }
func TestCreateUser(t *testing.T) { testKey := []byte(`MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4f5wg5l2hKsTeNemV41`) authenForTest := NewAuthenticator(testKey) //-- params userid := "salmon" username := "******" password := "******" cred, _ := NewUserIDPassword(userid, []byte(password)) clientId := "ios" otherFields := make(map[UserFieldName]interface{}) otherFields[UserField_Language] = "en" ctrl := gomock.NewController(t) defer ctrl.Finish() mockUserDb := NewMockUserDb_I(ctrl) mockUserDb.EXPECT().CreateUser(cred.UserId(), username, gomock.Any(), RegularUser, otherFields) mockUserDb.EXPECT().SetRefreshToken(cred.UserId(), clientId, gomock.Any()) _, _, err := authenForTest.CreateUser( userid, username, []byte(password), clientId, otherFields, mockUserDb) if err != nil { t.Error("create user failed:%v", err) } }
func TestQueueConsumerRunStopsGracefullyWhenCancelled(t *testing.T) { // log to /dev/null because the deleter is chatty log.SetOutput(ioutil.Discard) defer func() { log.SetOutput(os.Stderr) }() ctl := gomock.NewController(t) defer ctl.Finish() // delay so that the cancel occurs mid-receive delay := func(x interface{}) { time.Sleep(10 * time.Millisecond) } m := mock.NewMockSQSAPI(ctl) m.EXPECT().ReceiveMessage(gomock.Any()).Do(delay).Return(&sqs.ReceiveMessageOutput{}, nil).AnyTimes() m.EXPECT().DeleteMessageBatch(gomock.Any()).AnyTimes().Return(&sqs.DeleteMessageBatchOutput{}, nil) m.EXPECT().ChangeMessageVisibilityBatch(gomock.Any()).AnyTimes() s := &SQSService{Svc: m} q := NewConsumer(s, noop) q.delayAfterReceiveError = time.Millisecond ngo := runtime.NumGoroutine() // wait long enough to ensure ReceiveMessage is running ctx, _ := context.WithTimeout(context.Background(), 5*time.Millisecond) err := q.Run(ctx) assert.Error(t, err) time.Sleep(time.Millisecond) // time for goroutines to end assert.InDelta(t, ngo, runtime.NumGoroutine(), 2, "Should not leak goroutines") }
func TestHandleActivation(t *testing.T) { a := New(t) gtwID := "eui-0102030405060708" devEUI := types.DevEUI([8]byte{0, 1, 2, 3, 4, 5, 6, 7}) appEUI := types.AppEUI([8]byte{0, 1, 2, 3, 4, 5, 6, 7}) b := getTestBroker(t) b.ns.EXPECT().PrepareActivation(gomock.Any(), gomock.Any()).Return(&pb_broker.DeduplicatedDeviceActivationRequest{ Payload: []byte{}, DevEui: &devEUI, AppEui: &appEUI, AppId: "appid", DevId: "devid", GatewayMetadata: []*gateway.RxMetadata{ &gateway.RxMetadata{Snr: 1.2, GatewayId: gtwID}, }, ProtocolMetadata: &protocol.RxMetadata{}, }, nil) b.discovery.EXPECT().GetAllHandlersForAppID("appid").Return([]*pb_discovery.Announcement{}, nil) res, err := b.HandleActivation(&pb_broker.DeviceActivationRequest{ Payload: []byte{}, DevEui: &devEUI, AppEui: &appEUI, GatewayMetadata: &gateway.RxMetadata{Snr: 1.2, GatewayId: gtwID}, ProtocolMetadata: &protocol.RxMetadata{}, }) a.So(err, ShouldNotBeNil) a.So(res, ShouldBeNil) b.ctrl.Finish() // TODO: Integration test with Handler }
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") } }
func TestCreateInstanceReturnNilWithErrorIfError(t *testing.T) { //given ctrl := gomock.NewController(t) defer ctrl.Finish() mockEntityService := services_mocks.NewMockEntityService(ctrl) instanceService := InstanceApi{ entityService: mockEntityService, } mockError := mocks.MockError{"some_create_instance_error"} mockEntityService.EXPECT().Create(gomock.Any(), gomock.Any()).Return(nil, mockError) instanceToCreate := Instance{Name: "new_name", TemplateId: "templateId", ComputeOfferingId: "computeOfferingId", NetworkId: "networkId"} //when createdInstance, err := instanceService.Create(instanceToCreate) //then assert.Nil(t, createdInstance) assert.Equal(t, mockError, err) }
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)) }
func TestDescribeInstancesErrorCases(t *testing.T) { ctrl := gomock.NewController(t) mockEC2 := mock_ec2iface.NewMockEC2API(ctrl) client := NewEC2Client(&config.CliParams{}) client.(*ec2Client).client = mockEC2 defer ctrl.Finish() expectedIds := []*string{aws.String("id1"), aws.String("id2")} // Describe returned error mockEC2.EXPECT().DescribeInstances(gomock.Any()).Return(nil, errors.New("something failed")) _, err := client.DescribeInstances(expectedIds) if err == nil { t.Error("Expected error while Describing EC2 Instances, but got none") } // Describe returned nil reservations in the response mockEC2.EXPECT().DescribeInstances(gomock.Any()).Return(&ec2.DescribeInstancesOutput{}, nil) _, err = client.DescribeInstances(expectedIds) if err == nil { t.Error("Expected error for nil reservations, but got none") } // Describe returned empty reservations in the response mockEC2.EXPECT().DescribeInstances(gomock.Any()).Return( &ec2.DescribeInstancesOutput{Reservations: []*ec2.Reservation{}}, nil) _, err = client.DescribeInstances(expectedIds) if err == nil { t.Error("Expected error for empty reservations, but got none") } }
func TestCreateVpcReturnNilWithErrorIfError(t *testing.T) { //given ctrl := gomock.NewController(t) defer ctrl.Finish() mockEntityService := services_mocks.NewMockEntityService(ctrl) vpcService := VpcApi{ entityService: mockEntityService, } mockError := mocks.MockError{"some_create_vpc_error"} mockEntityService.EXPECT().Create(gomock.Any(), gomock.Any()).Return(nil, mockError) vpcToCreate := Vpc{Name: "new_name", Description: "new_description", VpcOfferingId: "vpcOfferingId"} //when createdVpc, err := vpcService.Create(vpcToCreate) //then assert.Nil(t, createdVpc) assert.Equal(t, mockError, err) }
func TestCreateNetworkAclReturnCreatedNetworkAclIfSuccess(t *testing.T) { //given ctrl := gomock.NewController(t) defer ctrl.Finish() mockEntityService := services_mocks.NewMockEntityService(ctrl) networkAclService := NetworkAclApi{ entityService: mockEntityService, } networkAclToCreate := NetworkAcl{Name: "new_name", Description: "new_description", VpcId: "new_vpc", } mockEntityService.EXPECT().Create(gomock.Any(), gomock.Any()).Return([]byte(`{"id":"new_id"}`), nil) //when createdNetworkAcl, _ := networkAclService.Create(networkAclToCreate) //then if assert.NotNil(t, createdNetworkAcl) { assert.Equal(t, "new_id", createdNetworkAcl.Id) } }
func TestRouter_SimpleMessageSending(t *testing.T) { ctrl, finish := testutil.NewMockCtrl(t) defer finish() a := assert.New(t) // Given a Router with route router, r := aRouterRoute(chanSize) msMock := NewMockMessageStore(ctrl) router.messageStore = msMock id, ts := uint64(2), time.Now().Unix() msMock.EXPECT(). StoreMessage(gomock.Any(), gomock.Any()). Do(func(m *protocol.Message, nodeID uint8) (int, error) { m.ID = id m.Time = ts m.NodeID = nodeID return len(m.Bytes()), nil }) // when i send a message to the route router.HandleMessage(&protocol.Message{Path: r.Path, Body: aTestByteMessage}) // then I can receive it a short time later assertChannelContainsMessage(a, r.MessagesChannel(), aTestByteMessage) }
func TestCreateNetworkAclReturnNilWithErrorIfError(t *testing.T) { //given ctrl := gomock.NewController(t) defer ctrl.Finish() mockEntityService := services_mocks.NewMockEntityService(ctrl) networkAclService := NetworkAclApi{ entityService: mockEntityService, } mockError := mocks.MockError{"some_create_vpc_error"} mockEntityService.EXPECT().Create(gomock.Any(), gomock.Any()).Return(nil, mockError) networkAclToCreate := NetworkAcl{Name: "new_name", Description: "new_description", VpcId: "vpcId"} //when createdNetworkAcl, err := networkAclService.Create(networkAclToCreate) //then assert.Nil(t, createdNetworkAcl) assert.Equal(t, mockError, err) }
func TestBasicSuccessful(t *testing.T) { pub, leaf, k := setup(t) ctrl := gomock.NewController(t) defer ctrl.Finish() scope := mock_metrics.NewMockScope(ctrl) pub.stats = scope server := logSrv(leaf.Raw, k) defer server.Close() port, err := getPort(server) test.AssertNotError(t, err, "Failed to get test server port") addLog(t, pub, port, &k.PublicKey) statName := pub.ctLogs[0].statName log.Clear() scope.EXPECT().NewScope(statName).Return(scope) scope.EXPECT().Inc("Submits", int64(1)).Return(nil) scope.EXPECT().TimingDuration("SubmitLatency", gomock.Any()).Return(nil) err = pub.SubmitToCT(ctx, leaf.Raw) test.AssertNotError(t, err, "Certificate submission failed") test.AssertEquals(t, len(log.GetAllMatching("Failed to.*")), 0) // No Intermediate pub.issuerBundle = []ct.ASN1Cert{} log.Clear() scope.EXPECT().NewScope(statName).Return(scope) scope.EXPECT().Inc("Submits", int64(1)).Return(nil) scope.EXPECT().TimingDuration("SubmitLatency", gomock.Any()).Return(nil) err = pub.SubmitToCT(ctx, leaf.Raw) test.AssertNotError(t, err, "Certificate submission failed") test.AssertEquals(t, len(log.GetAllMatching("Failed to.*")), 0) }
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(stackName).Return(nil) mockCloudformation.EXPECT().UpdateStack(stackName, gomock.Any()).Return("", nil) mockCloudformation.EXPECT().WaitUntilUpdateComplete(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-down", 0) flagSet.Bool(capabilityIAMFlag, true, "") flagSet.String(asgMaxSizeFlag, "1", "") context := cli.NewContext(nil, flagSet, globalContext) err := scaleCluster(context, newMockReadWriter(), mockECS, mockCloudformation) if err != nil { t.Fatal("Error scaling cluster: ", err) } }
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) } }
func TestFunction_Rollback_UpdateAlias_failed(t *testing.T) { mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() serviceMock := mock_lambdaiface.NewMockLambdaAPI(mockCtrl) serviceMock.EXPECT().GetAlias(gomock.Any()).Return(&lambda.AliasConfiguration{FunctionVersion: aws.String("1")}, nil) serviceMock.EXPECT().ListVersionsByFunction(gomock.Any()).Return(&lambda.ListVersionsByFunctionOutput{ Versions: []*lambda.FunctionConfiguration{ &lambda.FunctionConfiguration{Version: aws.String("$LATEST")}, &lambda.FunctionConfiguration{Version: aws.String("1")}, &lambda.FunctionConfiguration{Version: aws.String("2")}, }, }, nil) serviceMock.EXPECT().UpdateAlias(gomock.Any()).Return(nil, errors.New("API err")) fn := &function.Function{ FunctionName: "testfn", Alias: "current", Service: serviceMock, Log: log.Log, } err := fn.Rollback() assert.EqualError(t, err, "API err") }
func TestGetTaskByArn(t *testing.T) { // Need a mock client as AddTask not only adds a task to the engine, but // also causes the engine to progress the task. ctrl, client, _, taskEngine, _ := mocks(t, &defaultConfig) defer ctrl.Finish() eventStream := make(chan DockerContainerChangeEvent) client.EXPECT().ContainerEvents(gomock.Any()).Return(eventStream, nil) client.EXPECT().PullImage(gomock.Any(), gomock.Any()).AnyTimes() // TODO change to MaxTimes(1) err := taskEngine.Init() if err != nil { t.Fatal(err) } defer taskEngine.Disable() sleepTask := testdata.LoadTask("sleep5") sleepTaskArn := sleepTask.Arn taskEngine.AddTask(sleepTask) _, found := taskEngine.GetTaskByArn(sleepTaskArn) if !found { t.Fatalf("Task %s not found", sleepTaskArn) } _, found = taskEngine.GetTaskByArn(sleepTaskArn + "arn") if found { t.Fatal("Task with invalid arn found in the task engine") } }
// Testing retry logic for Read() func TestSeekAndReadWithRetries(t *testing.T) { mockCtrl := gomock.NewController(t) hdfsReader := NewMockReadSeekCloser(mockCtrl) hdfsAccessor := NewMockHdfsAccessor(mockCtrl) ftHdfsReader := NewFaultTolerantHdfsReader("/path/to/file", hdfsReader, hdfsAccessor, atMost2Attempts()) var err error var nr int // Performing succesfull read of 60 bytes of requested 100 at offset 1000 hdfsReader.EXPECT().Seek(int64(1000)).Return(nil) err = ftHdfsReader.Seek(1000) assert.Nil(t, err) hdfsReader.EXPECT().Read(gomock.Any()).Return(60, nil) nr, err = ftHdfsReader.Read(make([]byte, 100)) assert.Nil(t, err) assert.Equal(t, 60, nr) // Now the stream should be at position 160 // Requesting one more read of 200 bytes, but this time it will fail hdfsReader.EXPECT().Read(gomock.Any()).Return(0, errors.New("Injected failure")) // As a result, ftHdfsReader should close the stream... hdfsReader.EXPECT().Close().Return(nil) // ...and invoke an OpenRead() to get new HdfsReader newHdfsReader := NewMockReadSeekCloser(mockCtrl) hdfsAccessor.EXPECT().OpenRead("/path/to/file").Return(newHdfsReader, nil) // It should seek at corret position (1060), and repeat the read newHdfsReader.EXPECT().Seek(int64(1060)).Return(nil) newHdfsReader.EXPECT().Read(gomock.Any()).Return(150, nil) nr, err = ftHdfsReader.Read(make([]byte, 200)) assert.Nil(t, err) assert.Equal(t, 150, nr) }
func TestPullImageGlobalTimeout(t *testing.T) { mockDocker, client, testTime, done := dockerclientSetup(t) defer done() wait := sync.WaitGroup{} wait.Add(1) mockDocker.EXPECT().PullImage(&pullImageOptsMatcher{"image:latest"}, gomock.Any()).Do(func(x, y interface{}) { opts, ok := x.(docker.PullImageOptions) if !ok { t.Error("Cannot cast argument to PullImageOptions") } io.WriteString(opts.OutputStream, "string\n") testTime.Warp(3 * time.Hour) wait.Wait() // Don't return, verify timeout happens }) metadata := client.PullImage("image", nil) if metadata.Error == nil { t.Error("Expected error for pull timeout") } if metadata.Error.(api.NamedError).ErrorName() != "DockerTimeoutError" { t.Error("Wrong error type") } mockDocker.EXPECT().PullImage(&pullImageOptsMatcher{"image2:latest"}, gomock.Any()) _ = client.PullImage("image2", nil) // cleanup wait.Done() }
// getResponseForCredentialsRequestWithParameters queries credentials for the // given id. The getCredentials function is used to simulate getting the // credentials object from the CredentialsManager func getResponseForCredentialsRequestWithParameters(t *testing.T, expectedStatus int, expectedErrorMessage *errorMessage, id string, getCredentials func() (*credentials.TaskIAMRoleCredentials, bool)) (*bytes.Buffer, error) { ctrl := gomock.NewController(t) defer ctrl.Finish() credentialsManager := mock_credentials.NewMockManager(ctrl) auditLog := mock_audit.NewMockAuditLogger(ctrl) server := setupServer(credentialsManager, auditLog) recorder := httptest.NewRecorder() creds, ok := getCredentials() credentialsManager.EXPECT().GetTaskCredentials(gomock.Any()).Return(creds, ok) auditLog.EXPECT().Log(gomock.Any(), gomock.Any(), gomock.Any()) params := make(url.Values) params[credentials.CredentialsIdQueryParameterName] = []string{credentialsId} req, _ := http.NewRequest("GET", credentials.CredentialsPath+"?"+params.Encode(), nil) server.Handler.ServeHTTP(recorder, req) if recorder.Code != expectedStatus { return nil, fmt.Errorf("Expected return code: %d. Got: %d", expectedStatus, recorder.Code) } if recorder.Code != http.StatusOK { errorMessage := &errorMessage{} json.Unmarshal(recorder.Body.Bytes(), errorMessage) if errorMessage.Code != expectedErrorMessage.Code || errorMessage.Message != expectedErrorMessage.Message { return nil, fmt.Errorf("Unexpected values. Actual: %v| Expected: %v", errorMessage, expectedErrorMessage) } } return recorder.Body, nil }