当前位置: 首页>>代码示例>>Golang>>正文


Golang gomock.NewController函数代码示例

本文整理汇总了Golang中code/google/com/p/gomock/gomock.NewController函数的典型用法代码示例。如果您正苦于以下问题:Golang NewController函数的具体用法?Golang NewController怎么用?Golang NewController使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了NewController函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: TestCallbackError

/*-------------------------------------------------------------------------------*/
func TestCallbackError(t *testing.T) {
	port := 8202

	//create controller for all mocks
	ctrl := gomock.NewController(t)
	//check mocks at end
	defer ctrl.Finish()

	//key values
	loser := "you are a loser"
	state := "jabba da hut/:)" //make sure we are decoding correctly by adding strange chars

	pageMapper := NewSimplePageMapper(three, "notused", "notused")
	cookieMapper := NewMockCookieMapper(ctrl)
	serveMux, authConn := createDispatcherWithMocks(ctrl, pageMapper, cookieMapper, nil)
	go func() {
		http.ListenAndServe(fmt.Sprintf(":%d", port), serveMux)
	}()

	//don't care about the cookie name
	cookieMapper.EXPECT().CookieName().Return("my_chef").AnyTimes()

	//just to get the constants
	authConn.EXPECT().ErrorValueName().Return("error")
	authConn.EXPECT().CodeValueName().Return("code")
	authConn.EXPECT().ClientTokenValueName().Return("dontbotherimnotgoingtousethisanyway")

	// this is what happens when google refuses
	v := url.Values{
		//no code!
		"state": []string{state},
		"error": []string{loser},
	}

	returnURLHost := fmt.Sprintf("localhost:%d", port)
	returnURL, err := url.Parse(fmt.Sprintf("http://%s%s?%s", returnURLHost, returl, v.Encode()))
	if err != nil {
		t.Fatalf("Can't understand url: %s", err)
	}

	client := new(http.Client)
	client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
		checkRedirValues(t, "error from goog", via, map[string][]string{
			"path":       []string{req.URL.Path, three},
			"host":       []string{req.URL.Host, returnURLHost},
			"state":      []string{req.URL.Query().Get("state"), ""},
			"error":      []string{req.URL.Query().Get("error"), loser},
			"service":    []string{req.URL.Query().Get("service"), "google"},
			"via url[0]": []string{via[0].URL.String(), returnURL.String()},
		})
		return stopProcessing
	}
	resp := createReqAndDo(t, client, returnURL.String(), nil)
	for k, v := range resp.Header {
		if k == "Set-Cookie" {
			t.Errorf("Should not have set cookie on error: %s\n", v[0])
		}
	}

}
开发者ID:jmcvetta,项目名称:seven5,代码行数:61,代码来源:auth_test.go

示例2: TestClientReportTTransportErrors

func TestClientReportTTransportErrors(t *testing.T) {
	mockCtrl := gomock.NewController(t)
	transport := thrift.NewTMemoryBuffer()

	thing := errortest.NewTestStruct()
	thing.M = make(map[string]string)
	thing.L = make([]string, 0)
	thing.S = make(map[string]bool)
	thing.I = 3

	err := thrift.NewTTransportException(thrift.TIMED_OUT, "test")
	for i := 0; ; i++ {
		protocol := NewMockTProtocol(mockCtrl)
		if !prepareClientProtocolFailure(protocol, i, err) {
			return
		}
		client := errortest.NewErrorTestClientProtocol(transport, protocol, protocol)
		_, retErr := client.TestStruct(thing)
		err2, ok := retErr.(thrift.TTransportException)
		if !ok {
			t.Fatal("Expected a TTrasportException")
		}

		if err2.TypeId() != err.TypeId() {
			t.Fatal("Expected a same error type id")
		}

		mockCtrl.Finish()
	}
}
开发者ID:simplifi,项目名称:thrift,代码行数:30,代码来源:client_error_test.go

示例3: TestWriterInsert

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{
		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)
	}
}
开发者ID:maraino,项目名称:gossie,代码行数:26,代码来源:writer_test.go

示例4: TestReadProcessSchedStat

func TestReadProcessSchedStat(t *testing.T) {

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

	mfs := mockfs.NewMockFileSystem(mockCtrl)

	pid := 10

	stat := &ProcessSchedStat{
		NumProcesses:  1,
		Running:       100,
		RunWait:       120,
		NumTimeSlices: 130,
	}

	path := fmt.Sprintf("/proc/%v/schedstat", pid)
	content := fmt.Sprintf("%v %v %v\n", stat.Running, stat.RunWait, stat.NumTimeSlices)
	mockfs.AddTextFile(mfs, path, content)
	fs.ChangeFileSystem(mfs)

	receivedStat := &ProcessSchedStat{}
	err := receivedStat.Add(pid)
	if err != nil {
		t.Fatal(err)
	}
	if !reflect.DeepEqual(receivedStat, stat) {
		t.Errorf("Received wrong schedstat: %+v", receivedStat)
	}
}
开发者ID:Barba-studio,项目名称:kubernetes,代码行数:30,代码来源:schedstats_test.go

示例5: TestStartSupervisedUpgrade

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")
	}
}
开发者ID:tomwilkie,项目名称:amazon-ecs-init,代码行数:26,代码来源:engine_test.go

示例6: TestStartSupervisedExitsWhenTerminalSuccess

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")
	}
}
开发者ID:tomwilkie,项目名称:amazon-ecs-init,代码行数:25,代码来源:engine_test.go

示例7: ProtobufDecoderSpec

func ProtobufDecoderSpec(c gospec.Context) {
	t := &ts.SimpleT{}
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	msg := ts.GetTestMessage()
	config := NewPipelineConfig(nil) // Initializes globals.

	c.Specify("A ProtobufDecoder", func() {
		encoded, err := proto.Marshal(msg)
		c.Assume(err, gs.IsNil)
		pack := NewPipelinePack(config.inputRecycleChan)
		decoder := new(ProtobufDecoder)
		decoder.sampleDenominator = 1000 // Since we don't call decoder.Init().

		c.Specify("decodes a protobuf message", func() {
			pack.MsgBytes = encoded
			_, err := decoder.Decode(pack)
			c.Expect(err, gs.IsNil)
			c.Expect(pack.Message, gs.Equals, msg)
			v, ok := pack.Message.GetFieldValue("foo")
			c.Expect(ok, gs.IsTrue)
			c.Expect(v, gs.Equals, "bar")
		})

		c.Specify("returns an error for bunk encoding", func() {
			bunk := append([]byte{0, 0, 0}, encoded...)
			pack.MsgBytes = bunk
			_, err := decoder.Decode(pack)
			c.Expect(err, gs.Not(gs.IsNil))
		})
	})
}
开发者ID:RogerBai,项目名称:heka,代码行数:33,代码来源:protobuf_test.go

示例8: setUp

func setUp(t *testing.T, start ...bool) (*Conn, *testState) {
	ctrl := gomock.NewController(t)
	st := state.NewMockStateTracker(ctrl)
	r := event.NewRegistry()
	ed := event.NewMockEventDispatcher(ctrl)
	nc := MockNetConn(t)
	c := Client("test", "test", "Testing IRC", r)
	logging.SetLogLevel(logging.LogFatal)

	c.ED = ed
	c.ST = st
	c.st = true
	c.sock = nc
	c.Flood = true // Tests can take a while otherwise
	c.Connected = true
	if len(start) == 0 {
		// Hack to allow tests of send, recv, write etc.
		// NOTE: the value of the boolean doesn't matter.
		c.postConnect()
		// Sleep 1ms to allow background routines to start.
		<-time.After(1e6)
	}

	return c, &testState{ctrl, st, ed, nc, c}
}
开发者ID:Jyggafey,项目名称:drone,代码行数:25,代码来源:connection_test.go

示例9: TestInitFromStringShouldCreateAMaestro

func (s *MaestroTestSuite) TestInitFromStringShouldCreateAMaestro(c *C) {
	m := maestro.Maestro{}
	m.InitFromString(`
applications:
    app:
        type: php-fpm
        links: [db]
    db:
        type: mysql
        ports:
            3306: 9000
`, "")

	// Create a gomock controller, and arrange for it's finish to be called
	ctrl := gomock.NewController(c)
	defer ctrl.Finish()
	docker.MOCK().SetController(ctrl)
	docker.EXPECT().Inspect(gomock.Any()).Return([]byte("[{\"ID\": \"123\", \"State\":{\"Running\": false}, \"NetworkSettings\": {\"IPAddress\": \"\"}}]"), nil)

	c.Assert(len(m.Applications), Equals, 2)
	c.Assert(m.GetContainer("app").Name, Equals, "app")
	c.Assert(m.GetContainer("app").Type, Equals, "php-fpm")
	c.Assert(m.GetContainer("app").Dependencies[0].Name, Equals, "db")
	c.Assert(m.GetContainer("db").GetFirstPort(), Equals, "3306")
	c.Assert(m.GetContainer("db").IsRunning(), Equals, false)
}
开发者ID:pborreli,项目名称:gaudi,代码行数:26,代码来源:maestro_unit_test.go

示例10: TestShow2

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

	json.MOCK().SetController(ctrl)
	base64.MOCK().SetController(ctrl)
}
开发者ID:Grigs-b,项目名称:withmock,代码行数:7,代码来源:code_test.go

示例11: TestPublishDispatchVerbose

func (s *RequestSuite) TestPublishDispatchVerbose(c *C) {
	ctrl := gomock.NewController(c)
	defer ctrl.Finish()

	serverCmds := make(chan ServerCmd, 1)
	server := NewMockServer(ctrl)
	server.EXPECT().Commands().Return(serverCmds).AnyTimes()

	options := &ConnOptions{Verbose: true}
	conn := NewMockConn(ctrl)
	conn.EXPECT().Options().Return(options).AnyTimes()
	conn.EXPECT().Server().Return(server).AnyTimes()

	msg := &Message{Subject: "Foo"}
	req := &PublishRequest{msg}
	conn.EXPECT().ServeRequest(req)
	req.Dispatch(conn)

	select {
	case cmd := <-serverCmds:
		c.Check(cmd, DeepEquals, &PublishCmd{msg})
	case <-time.After(time.Second):
		c.Errorf("Did not dispatch server command")
	}
}
开发者ID:cloudfoundry-attic,项目名称:gonatsd,代码行数:25,代码来源:request_test.go

示例12: TestDownloadAgentMD5Mismatch

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()
}
开发者ID:tomwilkie,项目名称:amazon-ecs-init,代码行数:34,代码来源:cache_test.go

示例13: TestDownloadAgentTempFile

func TestDownloadAgentTempFile(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)
	mockFS.EXPECT().TempFile("", "ecs-agent.tar").Return(nil, errors.New("test error"))

	d := &Downloader{
		getter: mockGetter,
		fs:     mockFS,
	}

	d.DownloadAgent()
}
开发者ID:tomwilkie,项目名称:amazon-ecs-init,代码行数:26,代码来源:cache_test.go

示例14: TestStopAgent

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")
	}
}
开发者ID:2opremio,项目名称:amazon-ecs-init,代码行数:28,代码来源:docker_test.go

示例15: TestStartApplicationShouldCleanAndBuildThem

func (s *MaestroTestSuite) TestStartApplicationShouldCleanAndBuildThem(c *C) {
	// Create a gomock controller, and arrange for it's finish to be called
	ctrl := gomock.NewController(c)
	defer ctrl.Finish()

	// Setup the docker mock package
	docker.MOCK().SetController(ctrl)
	docker.EXPECT().Kill(gomock.Any()).Return().Times(2)
	docker.EXPECT().Remove(gomock.Any()).Return().Times(2)
	docker.EXPECT().Build(gomock.Any(), gomock.Any()).Return().Times(2)
	docker.EXPECT().Start(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return("123").Times(2)
	docker.EXPECT().Inspect(gomock.Any()).Return([]byte("[{\"ID\": \"123\", \"State\":{\"Running\": false}, \"NetworkSettings\": {\"IPAddress\": \"172.17.0.10\"}}]"), nil).Times(4)

	m := maestro.Maestro{}
	m.InitFromString(`
applications:
    app:
        type: php-fpm
        links: [db]
    db:
        type: mysql
        ports:
            3306: 9000
`, "")

	c.Assert(len(m.Applications), Equals, 2)

	m.Start()
	c.Assert(m.GetContainer("db").IsRunning(), Equals, true)
	c.Assert(m.GetContainer("app").IsRunning(), Equals, true)
}
开发者ID:pborreli,项目名称:gaudi,代码行数:31,代码来源:maestro_unit_test.go


注:本文中的code/google/com/p/gomock/gomock.NewController函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。