/*-------------------------------------------------------------------------------*/ 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]) } } }
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() } }
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) } }
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) } }
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") } }
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 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)) }) }) }
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} }
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) }
func TestShow2(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() json.MOCK().SetController(ctrl) base64.MOCK().SetController(ctrl) }
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") } }
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 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() }
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") } }
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) }
// TestCase: Comprehensive call and reply workflow in the client. // Expecting TTProtocolErrors on fail. func TestClientReportTProtocolErrors(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.NewTProtocolExceptionWithType(thrift.INVALID_DATA, errors.New("test")) for i := 0; ; i++ { protocol := NewMockTProtocol(mockCtrl) if !prepareClientCallReply(protocol, i, err) { return } client := errortest.NewErrorTestClientProtocol(transport, protocol, protocol) _, retErr := client.TestStruct(thing) mockCtrl.Finish() err2, ok := retErr.(thrift.TProtocolException) if !ok { t.Fatal("Expected a TProtocolException") } if err2.TypeId() != thrift.INVALID_DATA { t.Fatal("Expected INVALID_DATA error") } } }
func (s *RequestSuite) TestPublishParse(c *C) { ctrl := gomock.NewController(c) defer ctrl.Finish() config := &Config{} config.Limits.Payload = 100 options := &ConnOptions{} server := NewMockServer(ctrl) server.EXPECT().Config().Return(config).AnyTimes() conn := NewMockConn(ctrl) conn.EXPECT().Options().Return(options).AnyTimes() conn.EXPECT().Server().Return(server).AnyTimes() conn.EXPECT().Read(gomock.Any()).Return(100, nil).Do(func(buf []byte) { copy(buf, []byte("TEST")) }).Times(2) conn.EXPECT().ReadControlLine().Times(2) req, err := ParsePublishRequest(conn, "FOO 4") c.Check(err, IsNil) c.Check(req, DeepEquals, &PublishRequest{ &Message{Subject: "FOO", Content: []byte("TEST")}}) req, err = ParsePublishRequest(conn, "FOO inbox 4") c.Check(err, IsNil) c.Check(req, DeepEquals, &PublishRequest{ &Message{Subject: "FOO", ReplyTo: "inbox", Content: []byte("TEST")}}) }
func (t *EngineTest) TestSetsUrlFetcher(c *C) { m := gomock.NewController(c) defer m.Finish() u := NewMockUrlFetcher(m) r1 := NewMockUrlFetchingRule(m) r1.EXPECT().Name().Return("Non-pollable 1").AnyTimes() r1.EXPECT().SetUrlFetcher(u).Times(1) r2 := NewMockUrlFetchingRule(m) r2.EXPECT().Name().Return("Non-pollable 2").AnyTimes() r2.EXPECT().SetUrlFetcher(u).Times(1) rules := []Rule{r1, r2} n := NewMockNotifier(m) n.EXPECT().Notify(gomock.Any(), gomock.Any(), gomock.Any()).Times(0) conf := NewMockConfig(m) conf.EXPECT().DefaultNotifier().Return(n, nil).AnyTimes() conf.EXPECT().DefaultNotificationRecipient().Return("").AnyTimes() conf.EXPECT().LogLevel().Return("DEBUG").AnyTimes() conf.EXPECT().Rules().Return(rules).AnyTimes() e := NewEngine(conf) e.SetUrlFetcher(u) }
func StatsdInputSpec(c gs.Context) { t := &pipeline_ts.SimpleT{} ctrl := gomock.NewController(t) defer ctrl.Finish() pConfig := NewPipelineConfig(nil) ith := new(plugins_ts.InputTestHelper) ith.Msg = pipeline_ts.GetTestMessage() ith.Pack = NewPipelinePack(pConfig.InputRecycleChan()) ith.PackSupply = make(chan *PipelinePack, 1) // Specify localhost, but we're not really going to use the network ith.AddrStr = "localhost:55565" ith.ResolvedAddrStr = "127.0.0.1:55565" // set up mock helper, input runner, and stat accumulator ith.MockHelper = NewMockPluginHelper(ctrl) ith.MockInputRunner = NewMockInputRunner(ctrl) mockStatAccum := NewMockStatAccumulator(ctrl) c.Specify("A StatsdInput", func() { statsdInput := StatsdInput{} config := statsdInput.ConfigStruct().(*StatsdInputConfig) config.Address = ith.AddrStr err := statsdInput.Init(config) c.Assume(err, gs.IsNil) realListener := statsdInput.listener c.Expect(realListener.LocalAddr().String(), gs.Equals, ith.ResolvedAddrStr) realListener.Close() mockListener := pipeline_ts.NewMockConn(ctrl) statsdInput.listener = mockListener ith.MockHelper.EXPECT().StatAccumulator("StatAccumInput").Return(mockStatAccum, nil) mockListener.EXPECT().Close() mockListener.EXPECT().SetReadDeadline(gomock.Any()) c.Specify("sends a Stat to the StatAccumulator", func() { statName := "sample.count" statVal := 303 msg := fmt.Sprintf("%s:%d|c\n", statName, statVal) expected := Stat{statName, strconv.Itoa(statVal), "c", float32(1)} mockStatAccum.EXPECT().DropStat(expected).Return(true) readCall := mockListener.EXPECT().Read(make([]byte, 512)) readCall.Return(len(msg), nil) readCall.Do(func(msgBytes []byte) { copy(msgBytes, []byte(msg)) statsdInput.Stop() }) var wg sync.WaitGroup wg.Add(1) go func() { err = statsdInput.Run(ith.MockInputRunner, ith.MockHelper) c.Expect(err, gs.IsNil) wg.Done() }() wg.Wait() }) }) }
func (s *GaudiTestSuite) TestExtendsShouldThrowAnErrorWhenTheElementDoesNotExists(c *C) { os.RemoveAll("/var/tmp/gaudi/") // Create a gomock controller, and arrange for it's finish to be called ctrl := gomock.NewController(c) defer ctrl.Finish() docker.MOCK().SetController(ctrl) util.MOCK().DisableMock("IsDir") util.MOCK().DisableMock("IsFile") util.MOCK().DisableMock("LogError") disableLog() g := gaudi.Gaudi{} c.Assert(func() { g.Init(` applications: a: type: apache b: extends: c `) }, PanicMatches, "b extends a non existing application : c") enableLog() }
func (s *GaudiTestSuite) TestEnterContainerShouldUseNsEnter(c *C) { os.RemoveAll("/var/tmp/gaudi/") // 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) // Setup the util mock package util.MOCK().SetController(ctrl) // Disable the util package mock util.MOCK().DisableMock("IsDir") util.MOCK().DisableMock("IsFile") util.EXPECT().PrintGreen("Retrieving templates ...") images := make(map[string]string) images["jpetazzo/nsenter"] = "123" docker.EXPECT().ImageExists(gomock.Any()).Return(true).Times(1) docker.EXPECT().HasDocker().Return(true).Times(1) docker.EXPECT().GetImages().Return(images, nil).Times(1) docker.EXPECT().Enter(gomock.Any()).Times(1) g := gaudi.Gaudi{} g.Init(` applications: app: type: apache `) g.Enter("app") }
func (s *ConnSuite) SetUpTest(c *C) { s.delegate = &TestReporterDelegate{} s.ctrl = gomock.NewController(s.delegate) s.pingTicker = make(chan time.Time, 1) s.tcpConn = NewDummyTCPConn() s.serverCmds = make(chan ServerCmd, 1) s.heartbeatHelper = NewMockHeartbeatHelper(s.ctrl) s.heartbeatHelper.EXPECT().Ticker().Return(s.pingTicker).AnyTimes() s.heartbeatHelper.EXPECT().Stop().AnyTimes() NewHeartbeatHelper = func(Conn, time.Duration, int) HeartbeatHelper { return s.heartbeatHelper } config := &Config{} config.Limits.ControlLine = 20 config.Limits.Pending = 1024 s.server = NewMockServer(s.ctrl) s.server.EXPECT().Config().Return(config).AnyTimes() s.server.EXPECT().Info().Return(&dummyInfo).AnyTimes() s.server.EXPECT().Commands().Return(s.serverCmds).AnyTimes() s.server.EXPECT().Stats().Return(NewStats()).AnyTimes() }
// 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") } }
// 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") } }
// TestCase: call and reply with exception workflow in the client. func TestClientCallException(t *testing.T) { mockCtrl := gomock.NewController(t) transport := thrift.NewTMemoryBuffer() err := thrift.NewTTransportException(thrift.TIMED_OUT, "test") for i := 0; ; i++ { protocol := NewMockTProtocol(mockCtrl) willComplete := !prepareClientCallException(protocol, i, err) client := errortest.NewErrorTestClientProtocol(transport, protocol, protocol) _, retErr := client.TestString("test") mockCtrl.Finish() if !willComplete { err2, ok := retErr.(thrift.TTransportException) if !ok { t.Fatal("Expected a TTransportException") } if err2.TypeId() != thrift.TIMED_OUT { t.Fatal("Expected TIMED_OUT error") } } else { err2, ok := retErr.(thrift.TApplicationException) if !ok { t.Fatal("Expected a TApplicationException") } if err2.TypeId() != thrift.PROTOCOL_ERROR { t.Fatal("Expected PROTOCOL_ERROR error") } break } } }
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") } }
func setUp(t *testing.T, start ...bool) (*Conn, *testState) { ctrl := gomock.NewController(t) st := state.NewMockStateTracker(ctrl) r := event.NewRegistry() ed := event.NewMockEventDispatcher(ctrl) l := logging.NewMockLogger(ctrl) nc := MockNetConn(t) c := Client("test", "test", "Testing IRC", r, l) // We don't want to have to specify s.log.EXPECT().Debug() for all the // random crap that gets logged. This mocks it all out nicely. ctrl.RecordCall(l, "Debug", gomock.Any(), gomock.Any()).AnyTimes() 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, l, st, ed, nc, c} }
func TestClientAndStateTracking(t *testing.T) { ctrl := gomock.NewController(t) st := state.NewMockTracker(ctrl) c := SimpleClient("test", "test", "Testing IRC") // Assert some basic things about the initial state of the Conn struct if me := c.cfg.Me; me.Nick != "test" || me.Ident != "test" || me.Name != "Testing IRC" || me.Host != "" { t.Errorf("Conn.cfg.Me not correctly initialised.") } // Check that the internal handlers are correctly set up for k, _ := range intHandlers { if _, ok := c.handlers.set[strings.ToLower(k)]; !ok { t.Errorf("Missing internal handler for '%s'.", k) } } // Now enable the state tracking code and check its handlers c.EnableStateTracking() for k, _ := range stHandlers { if _, ok := c.handlers.set[strings.ToLower(k)]; !ok { t.Errorf("Missing state handler for '%s'.", k) } } if len(c.stRemovers) != len(stHandlers) { t.Errorf("Incorrect number of Removers (%d != %d) when adding state handlers.", len(c.stRemovers), len(stHandlers)) } // We're expecting the untracked me to be replaced by a tracked one if me := c.cfg.Me; me.Nick != "test" || me.Ident != "test" || me.Name != "Testing IRC" || me.Host != "" { t.Errorf("Enabling state tracking did not replace Me correctly.") } if c.st == nil || c.cfg.Me != c.st.Me() { t.Errorf("State tracker not enabled correctly.") } // Now, shim in the mock state tracker and test disabling state tracking me := c.cfg.Me c.st = st st.EXPECT().Wipe() c.DisableStateTracking() if c.st != nil || c.cfg.Me != me { t.Errorf("State tracker not disabled correctly.") } // Finally, check state tracking handlers were all removed correctly for k, _ := range stHandlers { if _, ok := c.handlers.set[strings.ToLower(k)]; ok && k != "NICK" { // A bit leaky, because intHandlers adds a NICK handler. t.Errorf("State handler for '%s' not removed correctly.", k) } } if len(c.stRemovers) != 0 { t.Errorf("stRemovers not zeroed correctly when removing state handlers.") } ctrl.Finish() }
func (s *ClientCmdSuite) TestCloseCmd(c *C) { ctrl := gomock.NewController(c) defer ctrl.Finish() conn := NewMockConn(ctrl) conn.EXPECT().Close() CLOSE_CMD.Process(conn) }
func createFixtures(t *testing.T) (reporter *ErrorReporter, ctrl *gomock.Controller) { // reporter acts as a testing.T-like object that we pass to the // Controller. We use it to test that the mock considered tests // successful or failed. reporter = NewErrorReporter(t) ctrl = gomock.NewController(reporter) return }