Exemplo n.º 1
0
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)
}
Exemplo n.º 2
0
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)
}
Exemplo n.º 3
0
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")
}
Exemplo n.º 4
0
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()
}
Exemplo n.º 5
0
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}
}
Exemplo n.º 6
0
func TestClientAndStateTracking(t *testing.T) {
	// This doesn't use setUp() as we want to pass in a mock EventRegistry.
	ctrl := gomock.NewController(t)
	r := event.NewMockEventRegistry(ctrl)
	l := logging.NewMockLogger(ctrl)
	st := state.NewMockStateTracker(ctrl)

	for n, _ := range intHandlers {
		// We can't use EXPECT() here as comparisons of functions are
		// no longer valid in Go, which causes reflect.DeepEqual to bail.
		// Instead, ignore the function arg and just ensure that all the
		// handler names are correctly passed to AddHandler.
		ctrl.RecordCall(r, "AddHandler", gomock.Any(), n)
	}
	c := Client("test", "test", "Testing IRC", r, l)

	// Assert some basic things about the initial state of the Conn struct
	if c.ER != r || c.ED != r || c.l != l || c.st != false || c.ST != nil {
		t.Errorf("Conn not correctly initialised with external deps.")
	}
	if c.in == nil || c.out == nil || c.cSend == nil || c.cLoop == nil {
		t.Errorf("Conn control channels not correctly initialised.")
	}
	if c.Me.Nick != "test" || c.Me.Ident != "test" ||
		c.Me.Name != "Testing IRC" || c.Me.Host != "" {
		t.Errorf("Conn.Me not correctly initialised.")
	}

	// OK, while we're here with a mock event registry...
	for n, _ := range stHandlers {
		// See above.
		ctrl.RecordCall(r, "AddHandler", gomock.Any(), n)
	}
	c.EnableStateTracking()

	// We're expecting the untracked me to be replaced by a tracked one.
	if c.Me.Nick != "test" || c.Me.Ident != "test" ||
		c.Me.Name != "Testing IRC" || c.Me.Host != "" {
		t.Errorf("Enabling state tracking did not replace Me correctly.")
	}
	if !c.st || c.ST == nil || c.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.Me
	c.ST = st
	st.EXPECT().Wipe()
	for n, _ := range stHandlers {
		// See above.
		ctrl.RecordCall(r, "DelHandler", gomock.Any(), n)
	}
	c.DisableStateTracking()
	if c.st || c.ST != nil || c.Me != me {
		t.Errorf("State tracker not disabled correctly.")
	}
	ctrl.Finish()
}
Exemplo n.º 7
0
func TestRemember(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	mockIndex := mock_user.NewMockIndex(ctrl)
	mockIndex.EXPECT().Put("a", 1)            // literals work
	mockIndex.EXPECT().Put("b", gomock.Eq(2)) // matchers work too

	// NillableRet returns error. Not declaring it should result in a nil return.
	mockIndex.EXPECT().NillableRet()
	// Calls that returns something assignable to the return type.
	boolc := make(chan bool)
	// In this case, "chan bool" is assignable to "chan<- bool".
	mockIndex.EXPECT().ConcreteRet().Return(boolc)
	// In this case, nil is assignable to "chan<- bool".
	mockIndex.EXPECT().ConcreteRet().Return(nil)

	// Should be able to place expectations on variadic methods.
	mockIndex.EXPECT().Ellip("%d", 0, 1, 1, 2, 3) // direct args
	tri := []interface{}{1, 3, 6, 10, 15}
	mockIndex.EXPECT().Ellip("%d", tri...) // args from slice
	mockIndex.EXPECT().EllipOnly(gomock.Eq("arg"))

	user.Remember(mockIndex, []string{"a", "b"}, []interface{}{1, 2})
	// Check the ConcreteRet calls.
	if c := mockIndex.ConcreteRet(); c != boolc {
		t.Errorf("ConcreteRet: got %v, want %v", c, boolc)
	}
	if c := mockIndex.ConcreteRet(); c != nil {
		t.Errorf("ConcreteRet: got %v, want nil", c)
	}

	// Try one with an action.
	calledString := ""
	mockIndex.EXPECT().Put(gomock.Any(), gomock.Any()).Do(func(key string, _ interface{}) {
		calledString = key
	})
	mockIndex.EXPECT().NillableRet()
	user.Remember(mockIndex, []string{"blah"}, []interface{}{7})
	if calledString != "blah" {
		t.Fatalf(`Uh oh. %q != "blah"`, calledString)
	}

	// Use Do with a nil arg.
	mockIndex.EXPECT().Put("nil-key", gomock.Any()).Do(func(key string, value interface{}) {
		if value != nil {
			t.Errorf("Put did not pass through nil; got %v", value)
		}
	})
	mockIndex.EXPECT().NillableRet()
	user.Remember(mockIndex, []string{"nil-key"}, []interface{}{nil})
}
Exemplo n.º 8
0
func TestMatchers(t *testing.T) {
	type e interface{}
	type testCase struct {
		matcher gomock.Matcher
		yes, no []e
	}
	tests := []testCase{
		testCase{gomock.Any(), []e{3, nil, "foo"}, nil},
		testCase{gomock.Eq(4), []e{4}, []e{3, "blah", nil, int64(4)}},
		testCase{gomock.Nil(),
			[]e{nil, (error)(nil), (chan bool)(nil), (*int)(nil)},
			[]e{"", 0, make(chan bool), errors.New("err"), new(int)}},
		testCase{gomock.Not(gomock.Eq(4)), []e{3, "blah", nil, int64(4)}, []e{4}},
	}
	for i, test := range tests {
		for _, x := range test.yes {
			if !test.matcher.Matches(x) {
				t.Errorf(`test %d: "%v %s" should be true.`, i, x, test.matcher)
			}
		}
		for _, x := range test.no {
			if test.matcher.Matches(x) {
				t.Errorf(`test %d: "%v %s" should be false.`, i, x, test.matcher)
			}
		}
	}
}
Exemplo n.º 9
0
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)
}
Exemplo n.º 10
0
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")
	}
}
Exemplo n.º 11
0
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)
	}
}
Exemplo n.º 12
0
func TestStartSupervisedUpgrade(t *testing.T) {
	mockCtrl := gomock.NewController(t)
	defer mockCtrl.Finish()

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

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

	engine := &Engine{
		downloader: mockDownloader,
		docker:     mockDocker,
	}
	err := engine.StartSupervised()
	if err != nil {
		t.Error("Expected error to be nil but was returned")
	}
}
Exemplo n.º 13
0
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")}})
}
Exemplo n.º 14
0
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()
		})
	})
}
Exemplo n.º 15
0
/*-------------------------------------------------------------------------------*/
func TestLogout(t *testing.T) {
	port := 8203

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

	pageMapper := NewSimplePageMapper("notused", "notused", two)
	sm := NewMockSessionManager(ctrl)
	cookieMapper := NewSimpleCookieMapper(appName)
	serveMux, _ := createDispatcherWithMocks(ctrl, pageMapper, cookieMapper, sm)

	sm.EXPECT().Destroy(gomock.Any()).Return(nil)

	go func() {
		http.ListenAndServe(fmt.Sprintf(":%d", port), serveMux)
	}()

	logoutURLHost := fmt.Sprintf("localhost:%d", port)
	logoutURL, err := url.Parse(fmt.Sprintf("http://%s%s", logoutURLHost, "/fart/google/logout"))
	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, two},
			"host":       []string{req.URL.Host, logoutURLHost},
			"via url[0]": []string{via[0].URL.String(), logoutURL.String()},
		})
		return stopProcessing
	}
	resp := createReqAndDo(t, client, logoutURL.String(),
		&http.Cookie{
			Name:  cookieMapper.CookieName(),
			Value: "forty-series-tires",
		})
	for k, v := range resp.Header {
		if k == "Set-Cookie" {
			p := strings.Split(v[0], ";")
			for _, piece := range p {
				if strings.Index(piece, cookieMapper.CookieName()) != -1 {
					if strings.TrimSpace(piece) != cookieMapper.CookieName()+"=" {
						t.Errorf("Cookie not destroyed properly! '%s'", piece)
					}
				}
				if strings.Index(piece, "Max-Age") != -1 {
					if strings.TrimSpace(piece) != "Max-Age=0" {
						t.Errorf("Cookie not destroyed properly! '%s'", piece)
					}
				}
			}
		}
	}

}
Exemplo n.º 16
0
func (s *ContainerTestSuite) TestCallCleanShouldStopTheContainer(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().Inspect(gomock.Any()).Return([]byte("[{\"ID\": \"123\", \"State\":{\"Running\": false}, \"NetworkSettings\": {\"IPAddress\": \"172.17.0.10\"}}]"), nil)
	docker.EXPECT().Kill(gomock.Any()).Return()
	docker.EXPECT().Remove(gomock.Any()).Return()

	done := make(chan bool, 1)
	container := container.Container{Name: "Test"}
	container.Clean(done)
	<-done

	c.Check(container.IsRunning(), Equals, false)
}
Exemplo n.º 17
0
func HttpListenInputSpec(c gs.Context) {
	t := &pipeline_ts.SimpleT{}
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()
	pConfig := NewPipelineConfig(nil)

	httpListenInput := HttpListenInput{}
	ith := new(plugins_ts.InputTestHelper)
	ith.MockHelper = pipelinemock.NewMockPluginHelper(ctrl)
	ith.MockInputRunner = pipelinemock.NewMockInputRunner(ctrl)

	startInput := func() {
		go func() {
			httpListenInput.Run(ith.MockInputRunner, ith.MockHelper)
		}()
	}

	ith.Pack = NewPipelinePack(pConfig.InputRecycleChan())
	ith.PackSupply = make(chan *PipelinePack, 1)

	config := httpListenInput.ConfigStruct().(*HttpListenInputConfig)
	config.Address = "127.0.0.1:8325"
	config.Decoder = "PayloadJsonDecoder"

	ith.MockHelper.EXPECT().PipelineConfig().Return(pConfig)

	mockDecoderRunner := pipelinemock.NewMockDecoderRunner(ctrl)

	dRunnerInChan := make(chan *PipelinePack, 1)
	mockDecoderRunner.EXPECT().InChan().Return(dRunnerInChan).AnyTimes()

	ith.MockInputRunner.EXPECT().InChan().Return(ith.PackSupply).AnyTimes()
	ith.MockInputRunner.EXPECT().Name().Return("HttpListenInput").AnyTimes()
	ith.MockHelper.EXPECT().DecoderRunner("PayloadJsonDecoder", "HttpListenInput-PayloadJsonDecoder").Return(mockDecoderRunner, true)

	err := httpListenInput.Init(config)
	c.Assume(err, gs.IsNil)
	ith.MockInputRunner.EXPECT().LogMessage(gomock.Any())
	startInput()

	c.Specify("A HttpListenInput", func() {
		c.Specify("Adds query parameters to the message pack as fields", func() {
			ith.PackSupply <- ith.Pack
			resp, err := http.Get("http://127.0.0.1:8325/?test=Hello%20World")
			c.Assume(err, gs.IsNil)
			resp.Body.Close()
			c.Assume(resp.StatusCode, gs.Equals, 200)

			pack := <-dRunnerInChan
			fieldValue, ok := pack.Message.GetFieldValue("test")
			c.Assume(ok, gs.IsTrue)
			c.Expect(fieldValue, gs.Equals, "Hello World")
		})
		httpListenInput.Stop()
	})
}
Exemplo n.º 18
0
func (s *GaudiTestSuite) TestCheckRunningContainerShouldUseDockerPs(c *C) {
	os.RemoveAll("/var/tmp/gaudi/templates/")

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

	psResult := make(map[string]string)
	psResult["gaudi/lb"] = "123"
	psResult["gaudi/front1"] = "124"
	psResult["gaudi/db"] = "125"

	util.EXPECT().PrintGreen("Retrieving templates ...").Times(1)

	docker.EXPECT().ImageExists(gomock.Any()).Return(true).Times(1)
	docker.EXPECT().HasDocker().Return(true).Times(1)
	docker.EXPECT().SnapshotProcesses().Return(psResult, nil)

	docker.EXPECT().Inspect("123").Return([]byte("[{\"ID\": \"123\", \"State\":{\"Running\": true}, \"NetworkSettings\": {\"IPAddress\": \"123.124.125.126\"}}]"), nil)
	docker.EXPECT().Inspect("124").Return([]byte("[{\"ID\": \"123\", \"State\":{\"Running\": true}, \"NetworkSettings\": {\"IPAddress\": \"123.124.125.127\"}}]"), nil)
	docker.EXPECT().Inspect("125").Return([]byte("[{\"ID\": \"123\", \"State\":{\"Running\": true}, \"NetworkSettings\": {\"IPAddress\": \"123.124.125.128\"}}]"), nil)

	util.EXPECT().PrintOrange("Application", "lb", "is running", "(123.124.125.126:)")
	util.EXPECT().PrintOrange("Application", "front1", "is running", "(123.124.125.127:)")
	util.EXPECT().PrintOrange("Application", "db", "is running", "(123.124.125.128:3306)")

	g := gaudi.Gaudi{}
	g.Init(`
applications:
    lb:
        links: [front1]
        type: varnish

    front1:
        type: apache

    db:
        type: mysql
        ports:
            3306: 9000
`)

	g.Check()
}
Exemplo n.º 19
0
func (t *EngineTest) TestNotifiesOnInsane(c *C) {
	m := gomock.NewController(c)
	defer m.Finish()

	r := NewMockRule(m)
	r.EXPECT().TestTriggered().Return(false, false).Times(1)
	r.EXPECT().Name().Return("Test Rule").AnyTimes()

	n := NewMockNotifier(m)
	n.EXPECT().Notify(gomock.Any(), gomock.Any(), gomock.Any()).Times(1)

	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([]Rule{r}).AnyTimes()

	e := NewEngine(conf)
	e.Run(r)
}
Exemplo n.º 20
0
func TestGrabPointer(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	mockIndex := mock_user.NewMockIndex(ctrl)
	mockIndex.EXPECT().Ptr(gomock.Any()).SetArg(0, 7) // set first argument to 7

	i := user.GrabPointer(mockIndex)
	if i != 7 {
		t.Errorf("Expected 7, got %d", i)
	}
}
Exemplo n.º 21
0
func TestDownloadAgentSuccess(t *testing.T) {
	mockCtrl := gomock.NewController(t)
	defer mockCtrl.Finish()

	tarballContents := "tarball contents"
	tarballResponse := &http.Response{
		StatusCode: 200,
		Body:       ioutil.NopCloser(bytes.NewBufferString(tarballContents)),
	}
	expectedMd5Sum := fmt.Sprintf("%x\n", md5.Sum([]byte(tarballContents)))
	md5response := &http.Response{}

	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(expectedMd5Sum), 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()).Do(func(reader io.Reader, writer io.Writer) {
		_, err = io.Copy(writer, reader)
		if err != nil {
			t.Fail()
		}
	})
	mockFS.EXPECT().Copy(tempfile, gomock.Any()).Return(int64(0), nil)
	mockFS.EXPECT().Rename(tempfile.Name(), config.AgentTarball())

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

	d.DownloadAgent()
}
Exemplo n.º 22
0
func (s *GaudiTestSuite) TestInitShouldCreateApplications(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)

	// 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 ...")

	docker.EXPECT().ImageExists(gomock.Any()).Return(true).Times(1)
	docker.EXPECT().HasDocker().Return(true).Times(1)
	docker.EXPECT().Inspect(gomock.Any()).Return([]byte("[{\"ID\": \"123\", \"State\":{\"Running\": false}, \"NetworkSettings\": {\"IPAddress\": \"\"}}]"), nil)

	g := gaudi.Gaudi{}
	g.Init(`
applications:
    app:
        type: php-fpm
        links: [db]
    db:
        type: mysql
        ports:
            3306: 9000
`)

	c.Assert(len(g.Applications), Equals, 2)
	c.Assert(g.GetApplication("app").Name, Equals, "app")
	c.Assert(g.GetApplication("app").Type, Equals, "php-fpm")
	c.Assert(g.GetApplication("app").Dependencies[0].Name, Equals, "db")
	c.Assert(g.GetApplication("db").GetFirstPort(), Equals, "3306")
	c.Assert(g.GetApplication("db").IsRunning(), Equals, false)
}
Exemplo n.º 23
0
func (s *GaudiTestSuite) TestStartBinariesShouldCleanAndBuildThem(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 ...")

	docker.EXPECT().ImageExists(gomock.Any()).Return(true).Times(1)
	docker.EXPECT().HasDocker().Return(true).Times(1)
	docker.EXPECT().ShouldRebuild(gomock.Any()).Return(true).Times(1)

	util.EXPECT().PrintGreen("Building", "gaudi/npm", "...")
	docker.EXPECT().Build(gomock.Any(), gomock.Any()).Times(1)

	util.EXPECT().PrintGreen("Running", "npm", "update", "...")
	docker.EXPECT().Run(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return().Times(1)

	g := gaudi.Gaudi{}
	g.Init(`
binaries:
    npm:
        type: npm
`)

	c.Assert(len(g.Applications), Equals, 0)
	c.Assert(len(g.Binaries), Equals, 1)

	g.Run("npm", []string{"update"})
}
Exemplo n.º 24
0
func TestMe(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	notify := func(ch chan<- os.Signal, signal os.Signal) {
		ch <- os.Kill
	}

	signal.MOCK().SetController(ctrl)
	signal.EXPECT().Notify(gomock.Any(), os.Interrupt).Do(notify)

	if RunMe() != os.Kill {
		t.Errorf("expected mock signal")
	}
}
Exemplo n.º 25
0
func (s *RequestSuite) TestPublishParseBadRead(c *C) {
	ctrl := gomock.NewController(c)
	defer ctrl.Finish()

	config := &Config{}
	config.Limits.Payload = 100
	server := NewMockServer(ctrl)
	server.EXPECT().Config().Return(config).AnyTimes()
	conn := NewMockConn(ctrl)
	conn.EXPECT().Server().Return(server).AnyTimes()
	conn.EXPECT().Read(gomock.Any()).Return(0, io.EOF)

	req, err := ParsePublishRequest(conn, "FOO 20")
	c.Check(err, Equals, io.EOF)
	c.Check(req, IsNil)
}
Exemplo n.º 26
0
func TestTryMe(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	gcfg.MOCK().SetController(ctrl)

	data := "This is some data to decode"
	gcfg.EXPECT().ReadStringInto(gomock.Any(), data).Return(nil)

	// Run the function we want to test
	err := TryMe(data)

	if err != nil {
		t.Errorf("Unexpected error return: %s", err)
	}
}
Exemplo n.º 27
0
func (s *GaudiTestSuite) TestExtendsShouldCopyElements(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")

	disableLog()

	docker.EXPECT().ImageExists(gomock.Any()).Return(true).Times(1)
	docker.EXPECT().HasDocker().Return(true).Times(1)

	g := gaudi.Gaudi{}

	g.Init(`
applications:
    a:
        type: apache
        before_script: echo hello
    b:
        extends: a
    c:
        extends: a
        before_script: echo ok
    d:
        extends: c
        type: mysql
`)

	c.Check(g.Applications["a"].Type, Equals, "apache")
	c.Check(g.Applications["b"].BeforeScript, Equals, "echo hello")

	c.Check(g.Applications["b"].Type, Equals, "apache")
	c.Check(g.Applications["b"].BeforeScript, Equals, "echo hello")

	c.Check(g.Applications["c"].Type, Equals, "apache")
	c.Check(g.Applications["c"].BeforeScript, Equals, "echo ok")

	c.Check(g.Applications["d"].Type, Equals, "mysql")
	c.Check(g.Applications["d"].BeforeScript, Equals, "echo ok")

	enableLog()
}
Exemplo n.º 28
0
func TestLoadDesiredAgent(t *testing.T) {
	mockCtrl := gomock.NewController(t)
	defer mockCtrl.Finish()

	desiredImage := "my-new-agent-image"

	mockFS := NewMockfileSystem(mockCtrl)

	mockFS.EXPECT().Open(config.DesiredImageLocatorFile()).Return(ioutil.NopCloser(bytes.NewBufferString(desiredImage+"\n")), nil)
	mockFS.EXPECT().Base(gomock.Any()).Return(desiredImage + "\n")
	mockFS.EXPECT().Open(config.CacheDirectory() + "/" + desiredImage)

	d := &Downloader{
		fs: mockFS,
	}

	d.LoadDesiredAgent()
}
Exemplo n.º 29
0
func (s *GaudiTestSuite) TestUseCustomTemplateShouldUseIt(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)

	// Setup the util mock package
	util.MOCK().SetController(ctrl)

	util.MOCK().EnableMock("IsDir")
	util.MOCK().EnableMock("IsFile")
	util.MOCK().EnableMock("LogError")

	g := gaudi.Gaudi{}
	g.ApplicationDir = "/vagrant"

	docker.EXPECT().HasDocker().Return(true).Times(1)
	docker.EXPECT().ImageExists(gomock.Any()).Return(true).Times(1)

	util.EXPECT().IsDir("/var/tmp/gaudi/templates/").Return(false)
	util.EXPECT().IsFile("/vagrant/.gaudi/version.txt").Return(false)
	util.EXPECT().PrintGreen("Retrieving templates ...")

	util.EXPECT().IsFile("/vagrant/front/Dockerfile").Return(true).Times(3)
	util.EXPECT().LogError("Application 'custom' is not supported. Check http://gaudi.io/components.html for a list of supported applications.").Times(3)

	g.Init(`
applications:
    app:
        type: custom
        template: ./front/Dockerfile

    app2:
        type: custom
        template: front/Dockerfile

    app3:
        type: custom
        template: /vagrant/front/Dockerfile
`)
}
Exemplo n.º 30
0
func (s *ContainerTestSuite) TestStartedApplicationShouldRetrieveItsIp(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().Start(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return("123")
	docker.EXPECT().Inspect(gomock.Any()).Return([]byte("[{\"ID\": \"123\", \"State\":{\"Running\": false}, \"NetworkSettings\": {\"IPAddress\": \"\"}}]"), nil)
	docker.EXPECT().Inspect(gomock.Any()).Return([]byte("[{\"ID\": \"123\", \"State\":{\"Running\": true}, \"NetworkSettings\": {\"IPAddress\": \"172.17.0.10\"}}]"), nil)

	// @TODO : find a way to mock time.Sleep
	container := container.Container{Name: "Test"}
	container.Start()

	c.Check(container.IsRunning(), Equals, true)
	c.Check(container.Ip, Equals, "172.17.0.10")
}