Golang NewController示例

说明

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

编程语言: Golang

命名空间/包名称: github.com/golang/mock/gomock

示例#1
文件: vpc_offering_test.go 项目: cloud-ca/go-cloudca

func TestListVpcOfferingReturnVpcsIfSuccess(t *testing.T) {
	//given
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	mockEntityService := services_mocks.NewMockEntityService(ctrl)

	vpcOfferingService := VpcOfferingApi{
		entityService: mockEntityService,
	}

	expectedVpcOffering1 := VpcOffering{Id: TEST_VPC_OFFERING_ID + "1",
		Name:  TEST_VPC_OFFERING_NAME + "1",
		State: TEST_VPC_OFFERING_STATE + "1",
	}

	expectedVpcOfferings := []VpcOffering{expectedVpcOffering1}

	mockEntityService.EXPECT().List(gomock.Any()).Return(buildListTestVpcOfferingJsonResponse(expectedVpcOfferings), nil)

	//when
	vpcOfferings, _ := vpcOfferingService.List()

	//then
	if assert.NotNil(t, vpcOfferings) {
		assert.Equal(t, expectedVpcOfferings, vpcOfferings)
	}
}

示例#2
文件: docker_test.go 项目: chanshunli/amazon-ecs-init

func TestStartAgentNoEnvFile(t *testing.T) {
	mockCtrl := gomock.NewController(t)
	defer mockCtrl.Finish()

	containerID := "container id"

	mockFS := NewMockfileSystem(mockCtrl)
	mockDocker := NewMockdockerclient(mockCtrl)

	mockFS.EXPECT().ReadFile(config.AgentConfigFile()).Return(nil, errors.New("test error"))
	mockDocker.EXPECT().CreateContainer(gomock.Any()).Do(func(opts godocker.CreateContainerOptions) {
		validateCommonCreateContainerOptions(opts, t)
	}).Return(&godocker.Container{
		ID: containerID,
	}, nil)
	mockDocker.EXPECT().StartContainer(containerID, nil)
	mockDocker.EXPECT().WaitContainer(containerID)

	client := &Client{
		docker: mockDocker,
		fs:     mockFS,
	}

	_, err := client.StartAgent()
	if err != nil {
		t.Error("Error should not be returned")
	}
}

示例#3
文件: docker_test.go 项目: chanshunli/amazon-ecs-init

func TestStopAgent(t *testing.T) {
	mockCtrl := gomock.NewController(t)
	defer mockCtrl.Finish()

	mockDocker := NewMockdockerclient(mockCtrl)

	mockDocker.EXPECT().ListContainers(godocker.ListContainersOptions{
		All: true,
		Filters: map[string][]string{
			"status": []string{},
		},
	}).Return([]godocker.APIContainers{
		godocker.APIContainers{
			Names: []string{"/" + config.AgentContainerName},
			ID:    "id",
		},
	}, nil)
	mockDocker.EXPECT().StopContainer("id", uint(10))

	client := &Client{
		docker: mockDocker,
	}

	err := client.StopAgent()
	if err != nil {
		t.Error("Error should not be returned")
	}
}

示例#4
文件: compute_offering_test.go 项目: cloud-ca/go-cloudca

func TestGetComputeOfferingReturnComputeOfferingIfSuccess(t *testing.T) {
	//given
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	mockEntityService := services_mocks.NewMockEntityService(ctrl)

	computeOfferingService := ComputeOfferingApi{
		entityService: mockEntityService,
	}

	expectedComputeOffering := ComputeOffering{Id: TEST_COMPUTE_OFFERING_ID,
		Name:       TEST_COMPUTE_OFFERING_NAME,
		MemoryInMB: TEST_COMPUTE_OFFERING_MEMORY,
		CpuCount:   TEST_COMPUTE_OFFERING_CPU_NUMBER,
		Custom:     TEST_COMPUTE_OFFERING_CUSTOM}

	mockEntityService.EXPECT().Get(TEST_COMPUTE_OFFERING_ID, gomock.Any()).Return(buildComputeOfferingJsonResponse(&expectedComputeOffering), nil)

	//when
	computeOffering, _ := computeOfferingService.Get(TEST_COMPUTE_OFFERING_ID)

	//then
	if assert.NotNil(t, computeOffering) {
		assert.Equal(t, expectedComputeOffering, *computeOffering)
	}
}

示例#5
文件: docker_container_engine_test.go 项目: bmanas/amazon-ecs-agent

func TestPullImageECRSuccess(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()
	mockDocker := mock_dockeriface.NewMockClient(ctrl)
	mockDocker.EXPECT().Ping().AnyTimes().Return(nil)
	factory := mock_dockerclient.NewMockFactory(ctrl)
	factory.EXPECT().GetDefaultClient().AnyTimes().Return(mockDocker, nil)
	client, _ := NewDockerGoClient(factory, "", config.NewSensitiveRawMessage([]byte{}), false)
	goClient, _ := client.(*dockerGoClient)
	ecrClientFactory := mock_ecr.NewMockECRFactory(ctrl)
	ecrClient := mock_ecr.NewMockECRSDK(ctrl)
	goClient.ecrClientFactory = ecrClientFactory
	testTime := ttime.NewTestTime()
	ttime.SetTime(testTime)

	registryId := "123456789012"
	region := "eu-west-1"
	endpointOverride := "my.endpoint"
	authData := &api.RegistryAuthenticationData{
		Type: "ecr",
		ECRAuthData: &api.ECRAuthData{
			RegistryId:       registryId,
			Region:           region,
			EndpointOverride: endpointOverride,
		},
	}
	imageEndpoint := "registry.endpoint"
	image := imageEndpoint + "/myimage:tag"
	username := "username"
	password := "password"
	dockerAuthConfiguration := docker.AuthConfiguration{
		Username:      username,
		Password:      password,
		ServerAddress: "https://" + imageEndpoint,
	}
	getAuthorizationTokenInput := &ecrapi.GetAuthorizationTokenInput{
		RegistryIds: []*string{aws.String(registryId)},
	}

	ecrClientFactory.EXPECT().GetClient(region, endpointOverride).Return(ecrClient)
	ecrClient.EXPECT().GetAuthorizationToken(getAuthorizationTokenInput).Return(
		&ecrapi.GetAuthorizationTokenOutput{
			AuthorizationData: []*ecrapi.AuthorizationData{
				&ecrapi.AuthorizationData{
					ProxyEndpoint:      aws.String("https://" + imageEndpoint),
					AuthorizationToken: aws.String(base64.StdEncoding.EncodeToString([]byte(username + ":" + password))),
				},
			},
		}, nil)

	mockDocker.EXPECT().PullImage(
		&pullImageOptsMatcher{image},
		dockerAuthConfiguration,
	).Return(nil)

	metadata := client.PullImage(image, authData)
	if metadata.Error != nil {
		t.Error("Expected pull to succeed")
	}
}

示例#6
文件: outbound_test.go 项目: yarpc/yarpc-go

func TestCallOnewayFailure(t *testing.T) {
	mockCtrl := gomock.NewController(t)
	defer mockCtrl.Finish()

	ctx := context.Background()

	caller := "caller"
	service := "service"
	procedure := "procedure"
	body := []byte{1, 2, 3}

	outbound := transporttest.NewMockOnewayOutbound(mockCtrl)
	client := New(channel.MultiOutbound(caller, service,
		transport.Outbounds{
			Oneway: outbound,
		}))

	outbound.EXPECT().CallOneway(gomock.Any(),
		transporttest.NewRequestMatcher(t,
			&transport.Request{
				Service:   service,
				Caller:    caller,
				Procedure: procedure,
				Encoding:  Encoding,
				Body:      bytes.NewReader(body),
			}),
	).Return(nil, errors.New("some error"))

	_, err := client.CallOneway(
		ctx,
		yarpc.NewReqMeta().Procedure(procedure),
		body)

	assert.Error(t, err)
}

示例#7
文件: publisher_test.go 项目: jfrazelle/boulder

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)
}

示例#8
文件: docker_task_engine_test.go 项目: appuri/amazon-ecs-agent

func mocks(t *testing.T, cfg *config.Config) (*gomock.Controller, *MockDockerClient, TaskEngine) {
	ctrl := gomock.NewController(t)
	client := NewMockDockerClient(ctrl)
	taskEngine := NewTaskEngine(cfg, false)
	taskEngine.(*DockerTaskEngine).SetDockerClient(client)
	return ctrl, client, taskEngine
}

示例#9
文件: cmd_help_test.go 项目: cadrian/gate

func TestHelpRun2(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	cmd := NewMockCommander(ctrl)
	rem := remote.NewMockRemoter(ctrl)
	srv := server.NewMockServer(ctrl)
	cfg := core.NewMockConfig(ctrl)
	mmi := ui.NewMockUserInteraction(ctrl)
	help := &cmd_help{cmd, rem, srv, cfg, mmi}

	cmd_foo := NewMockCommand(ctrl)

	cmd.EXPECT().Command("foo").Return(cmd_foo)

	cmd_foo.EXPECT().Help([]string{"help", "foo"}).Return("\nhelp for foo\n", nil)

	mmi.EXPECT().Pager(`
[1;32mHelp for command foo[0m

help for foo

[1m--------[0m
[32mGate Copyright (C) 2012-2015 Cyril Adrian <[email protected]>[0m
[32mThis program comes with ABSOLUTELY NO WARRANTY; for details type [33mshow w[32m.[0m
[32mThis is free software, and you are welcome to redistribute it[0m
[32munder certain conditions; type [33mshow c[32m for details.[0m
`)

	err := help.Run([]string{"help", "foo"})
	if err != nil {
		t.Error(err)
	}
}

示例#10
文件: acs_handler_test.go 项目: bmanas/amazon-ecs-agent

func TestAcsWsUrl(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()
	taskEngine := engine.NewMockTaskEngine(ctrl)

	taskEngine.EXPECT().Version().Return("Docker version result", nil)

	wsurl := handler.AcsWsUrl("http://endpoint.tld", "myCluster", "myContainerInstance", taskEngine)

	parsed, err := url.Parse(wsurl)
	if err != nil {
		t.Fatal("Should be able to parse url")
	}

	if parsed.Path != "/ws" {
		t.Fatal("Wrong path")
	}

	if parsed.Query().Get("clusterArn") != "myCluster" {
		t.Fatal("Wrong cluster")
	}
	if parsed.Query().Get("containerInstanceArn") != "myContainerInstance" {
		t.Fatal("Wrong cluster")
	}
	if parsed.Query().Get("agentVersion") != version.Version {
		t.Fatal("Wrong cluster")
	}
	if parsed.Query().Get("agentHash") != version.GitHashString() {
		t.Fatal("Wrong cluster")
	}

	if parsed.Query().Get("dockerVersion") != "Docker version result" {
		t.Fatal("Wrong docker version")
	}
}

示例#11
文件: FaultTolerantHdfsReader_test.go 项目: Microsoft/hdfs-mount

// 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)
}

示例#12
文件: writer_test.go 项目: apesternikov/gossie

func TestWriterInsert(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()
	cli := mock_cassandra.NewMockCassandra(ctrl)
	//expectingBatch := thrift.NewTMap(k, v, s)
	cli.EXPECT().BatchMutate(gomock.Any(), ConsistencyLevel_ONE)
	conn := &connection{
		socket:    nil,
		transport: nil,
		client:    cli,
		node:      &node{node: "node"},
	}
	cp := &stubTransactionRunner{conn: conn}
	w := newWriter(cp, CONSISTENCY_ONE)
	row := &Row{
		Key: []byte("rowkey"),
		Columns: []*Column{
			&Column{Name: []byte("name1"), Value: []byte("value1")},
			&Column{Name: []byte("name2"), Value: []byte("value2")},
		},
	}
	w.Insert("cf", row)
	e := w.Run()
	if e != nil {
		t.Error("Error", e)
	}
}

示例#13
文件: function_test.go 项目: Robh081956/apex

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")
}

示例#14
文件: docker_task_engine_test.go 项目: nickschuch/amazon-ecs-agent

func mocks(t *testing.T, cfg *config.Config) (*gomock.Controller, *mock_engine.MockDockerClient, engine.TaskEngine) {
	ctrl := gomock.NewController(t)
	client := mock_engine.NewMockDockerClient(ctrl)
	taskEngine := engine.NewTaskEngine(cfg)
	taskEngine.(*engine.DockerTaskEngine).SetDockerClient(client)
	return ctrl, client, taskEngine
}

示例#15
文件: api_client_test.go 项目: rafkhan/amazon-ecs-agent

func TestSubmitContainerStateChangeLongReason(t *testing.T) {
	mockCtrl := gomock.NewController(t)
	defer mockCtrl.Finish()
	client, _, mockSubmitStateClient := NewMockClient(mockCtrl)
	exitCode := 20
	trimmedReason := strings.Repeat("a", api.EcsMaxReasonLength)
	reason := strings.Repeat("a", api.EcsMaxReasonLength+1)

	mockSubmitStateClient.EXPECT().SubmitContainerStateChange(&containerSubmitInputMatcher{
		ecs.SubmitContainerStateChangeInput{
			Cluster:         strptr(configuredCluster),
			Task:            strptr("arn"),
			ContainerName:   strptr("cont"),
			Status:          strptr("STOPPED"),
			ExitCode:        int64ptr(&exitCode),
			Reason:          strptr(trimmedReason),
			NetworkBindings: []*ecs.NetworkBinding{},
		},
	})
	err := client.SubmitContainerStateChange(api.ContainerStateChange{
		TaskArn:       "arn",
		ContainerName: "cont",
		Status:        api.ContainerStopped,
		ExitCode:      &exitCode,
		Reason:        reason,
	})
	if err != nil {
		t.Errorf("Unable to submit container state change: %v", err)
	}
}

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

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

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

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

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

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

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

示例#17
文件: ibm_test.go 项目: hack4impact/transcribe4all

func TestTranscribeWithIBM(t *testing.T) {
	assert := assert.New(t)
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	// Setup the mock package
	websocket.MOCK().SetController(ctrl)
	mockos.MOCK().SetController(ctrl)
	bufio.MOCK().SetController(ctrl)

	mockWS := new(websocket.Conn)
	mockFile := new(mockos.File)
	mockReader := new(bufio.Reader)

	websocket.DefaultDialer.EXPECT().Dial(gomock.Any(), gomock.Any()).Return(mockWS, nil, nil).Times(1)
	mockWS.EXPECT().WriteJSON(gomock.Any()).MinTimes(1)
	mockos.EXPECT().Open("file.flac").Times(1).Return(mockFile, nil).Times(1)
	bufio.EXPECT().NewReader(mockFile).Return(mockReader).Times(1)
	mockReader.EXPECT().Read(gomock.Any()).Return(0, nil).Times(1)
	mockWS.EXPECT().WriteMessage(websocket.BinaryMessage, gomock.Any()).MinTimes(1)
	mockWS.EXPECT().ReadJSON(gomock.Any()).Do(func(res **IBMResult) {
		(*res).Results = []ibmResultField{
			ibmResultField{},
			ibmResultField{},
		}
	}).Times(1)
	mockWS.EXPECT().Close().Times(1) // could run many times

	_, err := TranscribeWithIBM("file.flac", "", "")
	assert.NoError(err)
}

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

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

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

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

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

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

示例#19
文件: function_test.go 项目: kujohn/apex

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)
}

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

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

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

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

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

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

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

示例#21

func genTestControllerEnv(t *testing.T, task *api.Task) (context.Context, *MockAPIClient, exec.Controller, *containerConfig, func(t *testing.T)) {
	mocks := gomock.NewController(t)
	client := NewMockAPIClient(mocks)
	ctlr, err := newController(client, task)
	assert.NoError(t, err)

	config, err := newContainerConfig(task)
	assert.NoError(t, err)
	assert.NotNil(t, config)

	ctx := context.Background()

	// Put test name into log messages. Awesome!
	pc, _, _, ok := runtime.Caller(1)
	if ok {
		fn := runtime.FuncForPC(pc)
		ctx = log.WithLogger(ctx, log.L.WithField("test", fn.Name()))
	}

	ctx, cancel := context.WithCancel(ctx)
	return ctx, client, ctlr, config, func(t *testing.T) {
		cancel()
		mocks.Finish()
	}
}

示例#22
文件: metrics_test.go 项目: kujohn/apex

func TestGetStatistics(t *testing.T) {
	mockCtrl := gomock.NewController(t)
	defer mockCtrl.Finish()
	serviceMock := mock_cloudwatchiface.NewMockCloudWatchAPI(mockCtrl)

	metrics := [][]string{
		[]string{"Invocations", "Count"},
		[]string{"Errors", "Count"},
		[]string{"Duration", "Milliseconds"},
		[]string{"Throttles", "Count"},
	}

	startTime := time.Date(2016, time.January, 17, 10, 0, 0, 0, time.UTC)
	endTime := time.Date(2016, time.January, 18, 18, 0, 0, 0, time.UTC)

	for _, metric := range metrics {
		rand.Seed(time.Now().UTC().UnixNano())
		serviceMock.EXPECT().GetMetricStatistics(&cloudwatch.GetMetricStatisticsInput{
			MetricName: aws.String(metric[0]),
			Namespace:  aws.String("AWS/Lambda"),
			StartTime:  aws.Time(startTime),
			EndTime:    aws.Time(endTime),
			Period:     aws.Int64(int64((time.Duration(24) * time.Hour).Seconds())),
			Statistics: []*string{
				aws.String("Sum"),
			},
			Dimensions: []*cloudwatch.Dimension{
				{
					Name:  aws.String("FunctionName"),
					Value: aws.String("go_testf"),
				},
			},
			Unit: aws.String(metric[1]),
		}).Return(&cloudwatch.GetMetricStatisticsOutput{
			Datapoints: []*cloudwatch.Datapoint{
				&cloudwatch.Datapoint{Sum: aws.Float64(float64(rand.Intn(9999)))},
			},
			Label: aws.String("label"),
		}, nil)
	}

	name := "go_testf"

	mc := &MetricCollector{
		Metrics:      []string{"Invocations", "Errors", "Duration", "Throttles"},
		Collected:    0,
		FunctionName: name,
		Service:      serviceMock,
		StartDate:    startTime,
		EndDate:      endTime,
	}

	count := 0
	for _ = range mc.Collect() {
		count++
	}
	if count != 4 {
		t.Errorf("Wrong metrics count")
	}
}

示例#23
文件: match_test.go 项目: nsaje/dagger

func TestMatchTaskRun(t *testing.T) {
	t.Log("here we are")
	mockCtrl := gomock.NewController(t)
	defer mockCtrl.Finish()
	srv := NewTestServer(t)
	defer srv.Stop()
	conf := api.DefaultConfig()
	conf.Address = srv.HTTPAddr
	coord := NewConsulCoordinator(func(conf *ConsulConfig) {
		conf.Address = srv.HTTPAddr
	}).(*consulCoordinator)
	coord.Start(&net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 0}, make(chan error))
	receiver := NewMockInputManager(mockCtrl)

	// NewMatchTask(coord, receiver, StreamID("match(cpu_util{service=monitoring}, user_perc{service=monitoring} by hostname, device in alarm(avg($1, 5min) )")
	sid := StreamID("match(s1{t1=v1}, s2{t1=v1} by t2, t3 in alarm(avg(%s)<2 and avg(%s)>3))")
	_, definition, err := ParseComputationID(sid)
	assert.Nil(t, err)
	taskInfo, _ := NewMatchTask(coord, receiver, sid, definition)

	receiver.EXPECT().SubscribeTo(StreamID("alarm(avg(s1{t1=v1,t2=a,t3=1})<2 and avg(s2{t1=v1,t2=a,t3=1})>3)"), Timestamp(0), gomock.Any())
	receiver.EXPECT().SubscribeTo(StreamID("alarm(avg(s1{t1=v1,t2=b,t3=1})<2 and avg(s2{t1=v1,t2=b,t3=1})>3)"), Timestamp(0), gomock.Any())
	receiver.EXPECT().SubscribeTo(StreamID("alarm(avg(s1{t1=v1,t2=a,t3=2})<2 and avg(s2{t1=v1,t2=a,t3=2})>3)"), Timestamp(0), gomock.Any())

	go taskInfo.Task.Run(make(chan error))

	coord.RegisterAsPublisher(StreamID("s1{t1=v1,t2=a,t3=1,t4=x}"))
	coord.RegisterAsPublisher(StreamID("s2{t1=v1,t2=a,t3=1,t4=x}"))
	coord.RegisterAsPublisher(StreamID("s1{t1=v1,t2=b,t3=1,t4=y}"))
	coord.RegisterAsPublisher(StreamID("s2{t1=v1,t2=a,t3=2,t4=x}"))
	time.Sleep(2 * time.Second)
}

示例#24
文件: vpc_test.go 项目: cloud-ca/go-cloudca

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)
	}
}

示例#25
文件: docker_container_engine_test.go 项目: bmanas/amazon-ecs-agent

func TestUnavailableVersionError(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()
	mockDocker := mock_dockeriface.NewMockClient(ctrl)
	mockDocker.EXPECT().Ping().Return(nil)
	factory := mock_dockerclient.NewMockFactory(ctrl)
	factory.EXPECT().GetDefaultClient().Return(mockDocker, nil)
	client, err := NewDockerGoClient(factory, "", config.NewSensitiveRawMessage([]byte{}), false)
	if err != nil {
		t.Fatal(err)
	}

	vclient := client.WithVersion(dockerclient.DockerVersion("1.21"))

	factory.EXPECT().GetClient(dockerclient.DockerVersion("1.21")).Times(1).Return(nil, errors.New("Cannot get client"))

	metadata := vclient.StartContainer("foo")

	if metadata.Error == nil {
		t.Fatal("Expected error, didn't get one")
	}
	if namederr, ok := metadata.Error.(api.NamedError); ok {
		if namederr.ErrorName() != "CannotGetDockerclientError" {
			t.Fatal("Wrong error name, expected CannotGetDockerclientError but got " + namederr.ErrorName())
		}
	} else {
		t.Fatal("Error was not a named error")
	}
}

示例#26
文件: vpc_test.go 项目: cloud-ca/go-cloudca

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)

}

示例#27
文件: docker_test.go 项目: chanshunli/amazon-ecs-init

func TestGetContainerConfigWithFileOverrides(t *testing.T) {
	mockCtrl := gomock.NewController(t)
	defer mockCtrl.Finish()

	envFile := "\nECS_UPDATES_ENABLED=false\nAGENT_TEST_VAR2=\"val2\"=val2\n"

	mockFS := NewMockfileSystem(mockCtrl)

	mockFS.EXPECT().ReadFile(config.AgentConfigFile()).Return([]byte(envFile), nil)

	client := &Client{
		fs: mockFS,
	}
	cfg := client.getContainerConfig()

	envVariables := make(map[string]struct{})
	for _, envVar := range cfg.Env {
		envVariables[envVar] = struct{}{}
	}
	expectKey("ECS_UPDATES_ENABLED=false", envVariables, t)
	expectKey("AGENT_TEST_VAR2=\"val2\"=val2", envVariables, t)
	if _, ok := envVariables["ECS_UPDATES_ENABLED=true"]; ok {
		t.Errorf("Did not expect ECS_UPDATES_ENABLED=true to be defined")
	}

}

示例#28
文件: vpc_test.go 项目: cloud-ca/go-cloudca

func TestGetVpcReturnVpcIfSuccess(t *testing.T) {
	//given
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	mockEntityService := services_mocks.NewMockEntityService(ctrl)

	vpcService := VpcApi{
		entityService: mockEntityService,
	}

	expectedVpc := Vpc{Id: TEST_VPC_ID,
		Name:          TEST_VPC_NAME,
		Description:   TEST_VPC_DESCRIPTION,
		State:         TEST_VPC_STATE,
		Cidr:          TEST_VPC_CIDR,
		ZoneId:        TEST_VPC_ZONE_ID,
		ZoneName:      TEST_VPC_ZONE_NAME,
		NetworkDomain: TEST_VPC_NETWORK_DOMAIN,
		SourceNatIp:   TEST_VPC_SOURCE_NAT_IP,
		VpnStatus:     TEST_VPC_VPN_STATUS,
		Type:          TEST_VPC_TYPE,
		VpcOfferingId: TEST_VPC_VPC_OFFERING_ID,
	}

	mockEntityService.EXPECT().Get(TEST_VPC_ID, gomock.Any()).Return(buildTestVpcJsonResponse(&expectedVpc), nil)

	//when
	vpc, _ := vpcService.Get(TEST_VPC_ID)

	//then
	if assert.NotNil(t, vpc) {
		assert.Equal(t, expectedVpc, *vpc)
	}
}

示例#29
文件: adapter_test.go 项目: ghilbut/ygg.go

func Test_OneToOneAdapter_close_adapter(t *testing.T) {
	log.Println("######## [Test_OneToOneAdapter_close_adapter] ########")

	var ctrl Connection = NewLocalConnection()
	var target Connection = NewLocalConnection()

	cdesc, _ := NewCtrlDesc(kCtrlJson)
	cproxy := NewCtrlProxy(ctrl.(*LocalConnection).Other(), cdesc)

	tdesc, _ := NewTargetDesc(kTargetJson)
	tproxy := NewTargetProxy(target.(*LocalConnection).Other(), tdesc)

	adapter := NewOneToOneAdapter(tproxy)
	adapter.SetCtrlProxy(cproxy)

	mockCtrl := gomock.NewController(t)
	defer mockCtrl.Finish()

	mockConnDelegate := NewMockConnectionDelegate(mockCtrl)
	mockConnDelegate.EXPECT().OnClosed(ctrl)
	mockConnDelegate.EXPECT().OnClosed(target)
	ctrl.BindDelegate(mockConnDelegate)
	target.BindDelegate(mockConnDelegate)

	mockAdapterDelegate := NewMockAdapterDelegate(mockCtrl)
	mockAdapterDelegate.EXPECT().OnAdapterClosed(adapter)
	adapter.BindDelegate(mockAdapterDelegate)

	adapter.Close()
}

示例#30
文件: vpc_offering_test.go 项目: cloud-ca/go-cloudca

func TestGetVpcOfferingReturnVpcOfferingIfSuccess(t *testing.T) {
	//given
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	mockEntityService := services_mocks.NewMockEntityService(ctrl)

	vpcOfferingService := VpcOfferingApi{
		entityService: mockEntityService,
	}

	expectedVpcOffering := VpcOffering{Id: TEST_VPC_OFFERING_ID,
		Name:  TEST_VPC_OFFERING_NAME,
		State: TEST_VPC_OFFERING_STATE,
	}

	mockEntityService.EXPECT().Get(TEST_VPC_OFFERING_ID, gomock.Any()).Return(buildTestVpcOfferingJsonResponse(&expectedVpcOffering), nil)

	//when
	vpcOffering, _ := vpcOfferingService.Get(TEST_VPC_OFFERING_ID)

	//then
	if assert.NotNil(t, vpcOffering) {
		assert.Equal(t, expectedVpcOffering, *vpcOffering)
	}
}

展开阅读全文