func Test_GetListBots(t *testing.T) {
	mb, err := newManagerBots()
	if result := assert.Nil(t, err, fmt.Sprintf("Типовая ошибка при создании нового объекта. Ошибка: %v", err)); result != true {
		require.FailNow(t, "Дальнейшее тестирование функции прервано.")
	}
	if result := assert.NotNil(t, mb, fmt.Sprint("Метод newManagerBots() не должен возвращать nil.")); result != true {
		require.FailNow(t, "Дальнейшее тестирование функции прервано.")
	}

	// подготовить данные для тестирования
	bot := &Bot{}
	bot.ID = "12345"
	bot.Name = "name bot"
	bot.Server = "server"
	bot.Login = "******"
	bot.Password = "******"
	mb.ListBot[bot.ID] = bot

	// получить данные из проверяемого метода
	result, err := mb.GetListBots()

	assert.Nil(t, err, "Метод не должен возвращать ошибку.")
	assert.Equal(t, len(result), 1, "Неверное кол-во элементов в окружении ListBot.")

	botRes := result[0]
	assert.Equal(t, botRes.ID, bot.ID, "Не совпадает ID заданного бота и проверяемого бота.")
	assert.Equal(t, botRes.Name, bot.Name, "Не совпадает Name заданного бота и проверяемого бота.")
	assert.Equal(t, botRes.Server, bot.Server, "Не совпадает Server заданного бота и проверяемого бота.")
	assert.Equal(t, botRes.Login, bot.Login, "Не совпадает Login заданного бота и проверяемого бота.")
	assert.Equal(t, botRes.Password, bot.Password, "Не совпадает Password заданного бота и проверяемого бота.")
}
Exemple #2
0
// Fuzz test for N iterations
func testTypeFuzzN(t *testing.T, base interface{}, ff interface{}, n int) {
	require.Implements(t, (*json.Marshaler)(nil), ff)
	require.Implements(t, (*json.Unmarshaler)(nil), ff)
	require.Implements(t, (*marshalerFaster)(nil), ff)
	require.Implements(t, (*unmarshalFaster)(nil), ff)

	if _, ok := base.(unmarshalFaster); ok {
		require.FailNow(t, "base should not have a UnmarshalJSONFFLexer")
	}

	if _, ok := base.(marshalerFaster); ok {
		require.FailNow(t, "base should not have a MarshalJSONBuf")
	}

	f := fuzz.New()
	f.NumElements(0, 1+n/40)
	f.NilChance(0.2)
	f.Funcs(fuzzTime, fuzzTimeSlice)
	for i := 0; i < n; i++ {
		f.RandSource(rand.New(rand.NewSource(int64(i * 5275))))
		f.Fuzz(base)
		f.RandSource(rand.New(rand.NewSource(int64(i * 5275))))
		f.Fuzz(ff)

		testSameMarshal(t, base, ff)
		testCycle(t, base, ff)
	}
}
func Test_SendActionToBot(t *testing.T) {
	// подготовка
	mb, err := newManagerBots()
	if result := assert.Nil(t, err, fmt.Sprintf("Типовая ошибка при создании нового объекта. Ошибка: %v", err)); result != true {
		require.FailNow(t, "Дальнейшее тестирование функции прервано.")
	}
	if result := assert.NotNil(t, mb, fmt.Sprint("Метод newManagerBots() не должен возвращать nil.")); result != true {
		require.FailNow(t, "Дальнейшее тестирование функции прервано.")
	}
	infbot := make(map[string]string)
	infbot["name"] = "nametest"
	infbot["server"] = "127.0.0.1:29000"
	infbot["login"] = "******"
	infbot["password"] = "******"

	uid, err := mb.AddBot(infbot)
	if result := assert.Nil(t, err, "Ошибка при создании бота."); result != true {
		require.FailNow(t, "Дальнейшее тестирование функции прервано.")
	}
	if result := assert.NotEqual(t, uid, "", "Ошибка при создании бота. Возвращенный уид не должен быть пустым."); result != true {
		require.FailNow(t, "Дальнейшее тестирование функции прервано.")
	}

	// тестирование
	result := mb.SendActionToBot("wrongid", "wrongaction", make(map[string]interface{}))
	temperr := errors.New("Не найден бот с идентификатором: wrongid")
	assert.Equal(t, result, temperr, "Метод должен вернуть ошибку.")

}
Exemple #4
0
// Perform a DNS query and assert the reply code, number or answers, etc
func assertExchange(t *testing.T, z string, ty uint16, port int, minAnswers int, maxAnswers int, expErr int) (*dns.Msg, *dns.Msg) {
	require.NotEqual(t, 0, port, "invalid DNS server port")

	c := &dns.Client{
		UDPSize: testUDPBufSize,
	}

	m := new(dns.Msg)
	m.RecursionDesired = true
	m.SetQuestion(z, ty)
	m.SetEdns0(testUDPBufSize, false) // we don't want to play with truncation here...

	lstAddr := fmt.Sprintf("127.0.0.1:%d", port)
	r, _, err := c.Exchange(m, lstAddr)
	t.Logf("Response from '%s':\n%+v\n", lstAddr, r)
	if err != nil {
		t.Errorf("Error when querying DNS server at %s: %s", lstAddr, err)
	}
	require.NoError(t, err)
	if minAnswers == 0 && maxAnswers == 0 {
		require.Equal(t, expErr, r.Rcode, "DNS response code")
	} else {
		require.Equal(t, dns.RcodeSuccess, r.Rcode, "DNS response code")
	}
	answers := len(r.Answer)
	if minAnswers >= 0 && answers < minAnswers {
		require.FailNow(t, fmt.Sprintf("Number of answers >= %d", minAnswers))
	}
	if maxAnswers >= 0 && answers > maxAnswers {
		require.FailNow(t, fmt.Sprintf("Number of answers <= %d", maxAnswers))
	}
	return m, r
}
Exemple #5
0
func TestWatch(t *testing.T) {
	server := firetest.New()
	server.Start()
	defer server.Close()

	fb := New(server.URL)

	notifications := make(chan Event)
	err := fb.Watch(notifications)
	assert.NoError(t, err)

	l := setupLargeResult()
	server.Set("/foo", l)

	select {
	case event, ok := <-notifications:
		assert.True(t, ok)
		assert.Equal(t, "put", event.Type)
		assert.Equal(t, "/", event.Path)
		assert.Nil(t, event.Data)
	case <-time.After(250 * time.Millisecond):
		require.FailNow(t, "did not receive a notification initial notification")
	}

	select {
	case event, ok := <-notifications:
		assert.True(t, ok)
		assert.Equal(t, "/foo", event.Path)
		assert.EqualValues(t, l, event.Data)
	case <-time.After(250 * time.Millisecond):
		require.FailNow(t, "did not receive a notification")
	}
}
Exemple #6
0
func TestReactsToStatusUpdateEvent(t *testing.T) {
	event := bytes.NewBufferString(`{"eventType": "status_update_event"}`)
	refresh := make(chan string, 1)

	req, err := http.NewRequest("POST", "http://localhost:9000/callback", event)
	if err != nil {
		log.Fatal(err)
	}

	w := httptest.NewRecorder()

	watcher := Watcher{
		config:         &Config{},
		httpClient:     &http.Client{},
		refreshChannel: refresh,
	}

	watcher.callbackHandler(w, req)

	require.Equal(t, 200, w.Code)
	require.Equal(t, "", w.Body.String())

	select {
	case msg := <-refresh:
		if msg != "refresh" {
			require.FailNow(t, "Expect message from refresh channel to be of value 'refresh'")
		}
	default:
		require.FailNow(t, "Expect to receive message from refresh channel")
	}
}
Exemple #7
0
func newMockServer(t *testing.T, responses MockResponseMap) *httptest.Server {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Ensure that we support the requested action.
		action := r.URL.Query().Get("api_action")
		resp, ok := responses[action]
		if !ok {
			msg := fmt.Sprintf("Unsupported mock action: %s", action)
			require.FailNow(t, msg)
		}

		// Build the response that the server will return.
		linodeResponse := LinodeResponse{
			Action: action,
			Data:   resp.Response,
			Errors: resp.Errors,
		}
		rawResponse, err := json.Marshal(linodeResponse)
		if err != nil {
			msg := fmt.Sprintf("Failed to JSON encode response: %v", err)
			require.FailNow(t, msg)
		}

		// Send the response.
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		w.Write(rawResponse)
	}))

	time.Sleep(100 * time.Millisecond)
	return srv
}
func Test_AddBot(t *testing.T) {

	mb, err := newManagerBots()
	if result := assert.Nil(t, err, fmt.Sprintf("Типовая ошибка при создании нового объекта. Ошибка: %v", err)); result != true {
		require.FailNow(t, "Дальнейшее тестирование функции прервано.")
	}
	if result := assert.NotNil(t, mb, fmt.Sprint("Метод newManagerBots() не должен возвращать nil.")); result != true {
		require.FailNow(t, "Дальнейшее тестирование функции прервано.")
	}

	infbot := make(map[string]string)
	infbot["name"] = "nametest"
	infbot["server"] = "127.0.0.1:29000"
	infbot["login"] = "******"
	infbot["password"] = "******"

	uid, err := mb.AddBot(infbot)
	assert.Nil(t, err, "Ошибка при создании бота.")
	if result := assert.NotEqual(t, uid, "", "Ошибка при создании бота. Возвращенный уид не должен быть пустым."); result != true {
		require.FailNow(t, "Дальнейшее тестирование функции прервано.")
	}

	bot := mb.ListBot[uid]
	if result := assert.NotNil(t, bot, fmt.Sprintf("Ошибка при создании бота. В окружении mb.ListBot нет бота с уид-ом %s", uid)); result != true {
		require.FailNow(t, "Дальнейшее тестирование функции прервано.")
	}

	assert.Equal(t, bot.Name, "nametest", "Имя бота не равно исходному.")
	assert.Equal(t, bot.Server, "127.0.0.1:29000", "Сервер не равен исходному.")
	assert.Equal(t, bot.Login, "logintest", "Логин не равен исходному.")
	assert.Equal(t, bot.Password, "passwordtest", "Пароль не равен исходному.")
}
Exemple #9
0
func TestCancel(t *testing.T) {
	const cidr = "10.0.4.0/26"
	router := gossip.NewTestRouter(0.0)

	alloc1, subnet := makeAllocator("01:00:00:02:00:00", cidr, 2)
	alloc1.SetInterfaces(router.Connect(alloc1.ourName, alloc1))

	alloc2, _ := makeAllocator("02:00:00:02:00:00", cidr, 2)
	alloc2.SetInterfaces(router.Connect(alloc2.ourName, alloc2))
	alloc1.claimRingForTesting(alloc1, alloc2)
	alloc2.claimRingForTesting(alloc1, alloc2)

	alloc1.Start()
	alloc2.Start()

	// tell peers about each other
	alloc1.OnGossipBroadcast(alloc2.ourName, alloc2.Encode())

	// Get some IPs, so each allocator has some space
	res1, _ := alloc1.Allocate("foo", subnet, true, returnFalse)
	common.Log.Debugf("res1 = %s", res1.String())
	res2, _ := alloc2.Allocate("bar", subnet, true, returnFalse)
	common.Log.Debugf("res2 = %s", res2.String())
	if res1 == res2 {
		require.FailNow(t, "Error: got same ips!")
	}

	// Now we're going to pause alloc2 and ask alloc1
	// for an allocation
	unpause := alloc2.pause()

	// Use up all the IPs that alloc1 owns, so the allocation after this will prompt a request to alloc2
	for i := 0; alloc1.NumFreeAddresses(subnet.HostRange()) > 0; i++ {
		alloc1.Allocate(fmt.Sprintf("tmp%d", i), subnet, true, returnFalse)
	}
	cancelChan := make(chan bool, 1)
	doneChan := make(chan bool)
	go func() {
		_, ok := alloc1.Allocate("baz", subnet, true,
			func() bool {
				select {
				case <-cancelChan:
					return true
				default:
					return false
				}
			})
		doneChan <- ok == nil
	}()

	time.Sleep(100 * time.Millisecond)
	AssertNothingSent(t, doneChan)

	cancelChan <- true
	unpause()
	if <-doneChan {
		require.FailNow(t, "Error: got result from Allocate")
	}
}
Exemple #10
0
func TestShouldTriggerRefreshWhenMasterChanges(t *testing.T) {
	refresh := make(chan string, 1)
	reqCount := 0
	wg := &sync.WaitGroup{}
	wg.Add(1)

	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Method == "GET" && r.RequestURI == "/master/state.json" {
			var s state

			if reqCount == 0 {
				s = state{Leader: "[email protected]:5050"}
			}

			if reqCount != 0 {
				s = state{Leader: "[email protected]:5050"}
			}

			reqCount = reqCount + 1

			data, err := json.Marshal(s)
			if err != nil {
				log.Fatal("Error marshalling apps")
			}

			w.Write(data)
			return
		}
	}))

	lr := &leaderRegistry{
		mutex: &sync.Mutex{},
	}

	n, _ := NewMesosNotifier(
		&Config{
			Masters:      ts.URL,
			PollInterval: 1,
		},
		lr,
	)

	go n.Start(refresh, make(chan int), wg)

	time.Sleep(3 * time.Second)

	select {
	case msg := <-refresh:
		if msg != "refresh" {
			require.FailNow(t, "Expect message from refresh channel to be of value 'refresh'")
		}
		host := lr.get()
		require.Equal(t, "10.11.10.10", host.Ip)
		require.Equal(t, 5050, host.Port)
	default:
		require.FailNow(t, "Expect to receive message from refresh channel")
	}
}
Exemple #11
0
func TestCancel(t *testing.T) {
	common.InitDefaultLogging(false)
	const (
		CIDR = "10.0.1.7/26"
	)

	router := TestGossipRouter{make(map[router.PeerName]chan gossipMessage), 0.0}

	alloc1, subnet := makeAllocator("01:00:00:02:00:00", CIDR, 2)
	alloc1.SetInterfaces(router.connect(alloc1.ourName, alloc1))

	alloc2, _ := makeAllocator("02:00:00:02:00:00", CIDR, 2)
	alloc2.SetInterfaces(router.connect(alloc2.ourName, alloc2))
	alloc1.claimRingForTesting(alloc1, alloc2)
	alloc2.claimRingForTesting(alloc1, alloc2)

	alloc1.Start()
	alloc2.Start()

	// tell peers about each other
	alloc1.OnGossipBroadcast(alloc2.Encode())

	// Get some IPs, so each allocator has some space
	res1, _ := alloc1.Allocate("foo", subnet, nil)
	common.Debug.Printf("res1 = %s", res1.String())
	res2, _ := alloc2.Allocate("bar", subnet, nil)
	common.Debug.Printf("res2 = %s", res2.String())
	if res1 == res2 {
		require.FailNow(t, "Error: got same ips!")
	}

	// Now we're going to pause alloc2 and ask alloc1
	// for an allocation
	unpause := alloc2.pause()

	// Use up all the IPs that alloc1 owns, so the allocation after this will prompt a request to alloc2
	for i := 0; alloc1.NumFreeAddresses(subnet) > 0; i++ {
		alloc1.Allocate(fmt.Sprintf("tmp%d", i), subnet, nil)
	}
	cancelChan := make(chan bool, 1)
	doneChan := make(chan bool)
	go func() {
		_, ok := alloc1.Allocate("baz", subnet, cancelChan)
		doneChan <- ok == nil
	}()

	AssertNothingSent(t, doneChan)
	time.Sleep(100 * time.Millisecond)
	AssertNothingSent(t, doneChan)

	cancelChan <- true
	unpause()
	if <-doneChan {
		require.FailNow(t, "Error: got result from Allocate")
	}
}
Exemple #12
0
// EqualSlicesWithoutOrder - regardless the order, but same items
func EqualSlicesWithoutOrder(t *testing.T, expected, actual interface{}, msgAndArgs ...interface{}) {
	castedExpected, err := builtinutil.CastInterfaceToInterfaceSlice(expected)
	if err != nil {
		require.FailNow(t, fmt.Sprintf("'expected' is not a slice: %#v", expected), msgAndArgs...)
	}

	castedActual, err := builtinutil.CastInterfaceToInterfaceSlice(actual)
	if err != nil {
		require.FailNow(t, fmt.Sprintf("'actual' is not a slice: %#v", actual), msgAndArgs...)
	}

	equalSlicesWithoutOrder(t, castedExpected, castedActual, msgAndArgs...)
}
Exemple #13
0
func (m *mockGossipComms) GossipBroadcast(update mesh.GossipData) {
	m.Lock()
	defer m.Unlock()
	buf := []byte{}
	if len(m.messages) == 0 {
		require.FailNow(m, fmt.Sprintf("%s: Gossip broadcast message unexpected: \n%x", m.name, buf))
	} else if msg := m.messages[0]; msg.dst != mesh.UnknownPeerName {
		require.FailNow(m, fmt.Sprintf("%s: Expected Gossip message to %s but got broadcast", m.name, msg.dst))
	} else if msg.buf != nil && !equalByteBuffer(msg.buf, buf) {
		require.FailNow(m, fmt.Sprintf("%s: Gossip message not sent as expected: \nwant: %x\ngot : %x", m.name, msg.buf, buf))
	} else {
		// Swallow this message
		m.messages = m.messages[1:]
	}
}
Exemple #14
0
// Subscribe with QoS 1, publish with QoS 0. So the client should receive all the
// messages as QoS 0.
func TestServiceSub1Pub0(t *testing.T) {
	runClientServerTests(t, func(svc *Client) {
		done := make(chan struct{})
		done2 := make(chan struct{})

		count := 0

		sub := newSubscribeMessage(1)
		svc.Subscribe(sub,
			func(msg, ack message.Message, err error) error {
				close(done)
				return nil
			},
			func(msg *message.PublishMessage) error {
				assertPublishMessage(t, msg, 0)

				count++

				if count == 10 {
					glog.Debugf("got 10 pub0")
					close(done2)
				}

				return nil
			})

		select {
		case <-done:
		case <-time.After(time.Millisecond * 100):
			require.FailNow(t, "Timed out waiting for subscribe response")
		}

		msg := newPublishMessage(0, 0)

		for i := uint16(0); i < 10; i++ {
			svc.Publish(msg, nil)
		}

		select {
		case <-done2:
			require.Equal(t, 10, count)

		case <-time.After(time.Millisecond * 100):
			require.FailNow(t, "Timed out waiting for publish messages")
		}

	})
}
Exemple #15
0
func TestUserPass(t *testing.T) {
	s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("X-Authorization", r.Header.Get("Authorization"))
		auth := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
		if len(auth) != 2 || auth[0] != "Basic" {
			assert.FailNow(t, "Could not find Basic authentication")
		}
		assert.True(t, len(auth[1]) > 0)
		w.WriteHeader(http.StatusNoContent)
	}))
	defer s.Close()

	hSink, err := integSink(s.URL + "?user=tester&pass=hidden")
	assert.NoError(t, err)

	// md := make([]core.MetricDescriptor, 0, 1)
	ld := core.LabelDescriptor{
		Key:         "k1",
		Description: "d1",
	}
	smd := core.MetricDescriptor{
		Name:      "test/metric/1",
		Units:     core.UnitsBytes,
		ValueType: core.ValueInt64,
		Type:      core.MetricGauge,
		Labels:    []core.LabelDescriptor{ld},
	}
	err = hSink.Register([]core.MetricDescriptor{smd})
	assert.NoError(t, err)
}
Exemple #16
0
func TestServiceGeneratorGenerate(t *testing.T) {
	configFilesPath, _ := filepath.Abs("../tests/fixtures/file")

	g := ServiceGenerator{
		c: &Config{ConfigsPath: configFilesPath},
	}

	services, err := g.Generate()
	if err != nil {
		require.FailNow(t, fmt.Sprintf("Error: %s", err))
	}

	require.IsType(t, []*types.Service{}, services)

	require.Len(t, services, 2)

	require.Equal(t, services[0].Id, "/redis")
	require.Equal(t, services[0].Domains[0], "redis.example.com")
	require.Equal(t, services[0].Port, 6379)
	require.Equal(t, services[0].TransportProtocol, "tcp")
	require.Equal(t, services[0].Source, "File")
	require.Equal(t, services[0].Hosts[0].Ip, "10.10.10.10")
	require.Equal(t, services[0].Hosts[0].Port, 31001)
	require.Equal(t, services[0].Hosts[1].Ip, "10.10.10.10")
	require.Equal(t, services[0].Hosts[1].Port, 31003)

	require.Equal(t, services[1].Id, "/registry")
	require.Equal(t, services[1].Domains[0], "registry.example.com")
	require.Equal(t, services[1].Port, 80)
	require.Equal(t, services[1].TransportProtocol, "tcp")
	require.Equal(t, services[1].Source, "File")
	require.Equal(t, services[1].Hosts[0].Ip, "10.10.10.10")
	require.Equal(t, services[1].Hosts[0].Port, 31002)
}
Exemple #17
0
func TestHTTPCancel(t *testing.T) {
	var (
		containerID = "deadbeef"
		testCIDR1   = "10.0.3.0/29"
	)

	// Say quorum=2, so the allocate won't go ahead
	alloc, _ := makeAllocatorWithMockGossip(t, "08:00:27:01:c3:9a", testCIDR1, 2)
	defer alloc.Stop()
	ExpectBroadcastMessage(alloc, nil) // trying to form consensus
	cidr, _ := address.ParseCIDR(testCIDR1)
	port := listenHTTP(alloc, cidr)

	// Ask the http server for a new address
	req, _ := http.NewRequest("POST", allocURL(port, testCIDR1, containerID), nil)
	// On another goroutine, wait for a bit then cancel the request
	go func() {
		time.Sleep(100 * time.Millisecond)
		common.Log.Debug("Cancelling allocate")
		http.DefaultTransport.(*http.Transport).CancelRequest(req)
	}()

	res, _ := http.DefaultClient.Do(req)
	if res != nil {
		body, _ := ioutil.ReadAll(res.Body)
		require.FailNow(t, "Error: Allocate returned non-nil", string(body))
	}
}
Exemple #18
0
func TestIgnoresDifferentEvent(t *testing.T) {
	event := bytes.NewBufferString(`{"eventType": "failed_health_check_event"}`)
	refresh := make(chan string, 1)

	req, err := http.NewRequest("POST", "http://localhost:9000/callback", event)
	if err != nil {
		log.Fatal(err)
	}

	w := httptest.NewRecorder()

	watcher := Watcher{
		config:         &Config{},
		httpClient:     &http.Client{},
		refreshChannel: refresh,
	}

	watcher.callbackHandler(w, req)

	require.Equal(t, 200, w.Code)
	require.Equal(t, "", w.Body.String())

	select {
	case <-refresh:
		require.FailNow(t, "Expect no message to be received from refresh channel")
	default:
	}
}
Exemple #19
0
func TestCreate(t *testing.T) {
	c, err := integrationClient()
	assert.Nil(t, err)

	id := "test.metric.create.numeric.1"
	md := MetricDefinition{Id: id, Type: Gauge}
	ok, err := c.Create(md)
	assert.Nil(t, err)
	assert.True(t, ok, "MetricDefinition should have been created")

	// Following would be nice:
	// mdd, err := c.Definitions(Filters(Type(Gauge), Id(id)))

	// mdd, err := c.Definition(Gauge, id)
	// assert.Nil(t, err)
	// assert.Equal(t, md.Id, mdd.Id)

	// Try to recreate the same..
	ok, err = c.Create(md)
	assert.False(t, ok, "Should have received false when recreating them same metric")
	assert.Nil(t, err)

	// Use tags and dataRetention
	tags := make(map[string]string)
	tags["units"] = "bytes"
	tags["env"] = "unittest"
	md_tags := MetricDefinition{Id: "test.metric.create.numeric.2", Tags: tags, Type: Gauge}

	ok, err = c.Create(md_tags)
	assert.True(t, ok, "MetricDefinition should have been created")
	assert.Nil(t, err)

	md_reten := MetricDefinition{Id: "test/metric/create/availability/1", RetentionTime: 12, Type: Availability}
	ok, err = c.Create(md_reten)
	assert.Nil(t, err)
	assert.True(t, ok, "MetricDefinition should have been created")

	// Fetch all the previously created metrics and test equalities..
	mdq, err := c.Definitions(Filters(TypeFilter(Gauge)))
	assert.Nil(t, err)
	assert.Equal(t, 2, len(mdq), "Size of the returned gauge metrics does not match 2")

	mdm := make(map[string]MetricDefinition)
	for _, v := range mdq {
		mdm[v.Id] = *v
	}

	assert.Equal(t, md.Id, mdm[id].Id)
	assert.True(t, reflect.DeepEqual(tags, mdm["test.metric.create.numeric.2"].Tags))

	mda, err := c.Definitions(Filters(TypeFilter(Availability)))
	assert.Nil(t, err)
	assert.Equal(t, 1, len(mda))
	assert.Equal(t, "test/metric/create/availability/1", mda[0].Id)
	assert.Equal(t, 12, mda[0].RetentionTime)

	if mda[0].Type != Availability {
		assert.FailNow(t, "Type did not match Availability", int(mda[0].Type))
	}
}
Exemple #20
0
func TestCancelOnDied(t *testing.T) {
	const (
		cidr       = "10.0.4.0/26"
		container1 = "abcdef"
	)

	router := gossip.NewTestRouter(0.0)
	alloc1, subnet := makeAllocator("01:00:00:02:00:00", cidr, 2)
	alloc1.SetInterfaces(router.Connect(alloc1.ourName, alloc1))
	alloc1.Start()

	doneChan := make(chan bool)
	f := func() {
		_, ok := alloc1.Allocate(container1, subnet, true, returnFalse)
		doneChan <- ok == nil
	}

	// Attempt two allocations in parallel, to check that this is handled correctly
	go f()
	go f()

	// Nothing should happen, because we declared the quorum as 2
	time.Sleep(100 * time.Millisecond)
	AssertNothingSent(t, doneChan)

	alloc1.ContainerDied(container1)

	// Check that the two allocations both exit with an error
	if <-doneChan || <-doneChan {
		require.FailNow(t, "Error: got result from Allocate")
	}
}
Exemple #21
0
func TestServiceSubUnsub(t *testing.T) {
	runClientServerTests(t, func(c *Client) {
		done := make(chan struct{})

		sub := newSubscribeMessage(1)
		c.Subscribe(sub,
			func(msg, ack message.Message, err error) error {
				unsub := newUnsubscribeMessage()
				return c.Unsubscribe(unsub, func(msg, ack message.Message, err error) error {
					close(done)
					return nil
				})

			},
			func(msg *message.PublishMessage) error {
				return nil
			})

		select {
		case <-done:
		case <-time.After(time.Millisecond * 100):
			require.FailNow(t, "Timed out waiting for subscribe response")
		}
	})
}
Exemple #22
0
func impTestHTTPCancel(t *testing.T) {
	common.InitDefaultLogging(true)
	var (
		containerID = "deadbeef"
		testCIDR1   = "10.0.3.0/29"
	)

	alloc, _ := makeAllocatorWithMockGossip(t, "08:00:27:01:c3:9a", testCIDR1, 1)
	defer alloc.Stop()
	alloc.claimRingForTesting()
	_, cidr, _ := address.ParseCIDR(testCIDR1)
	port := listenHTTP(alloc, cidr)

	// Stop the alloc so nothing actually works
	unpause := alloc.pause()

	// Ask the http server for a new address
	done := make(chan *http.Response)
	req, _ := http.NewRequest("POST", allocURL(port, testCIDR1, containerID), nil)
	go func() {
		res, _ := http.DefaultClient.Do(req)
		done <- res
	}()

	time.Sleep(100 * time.Millisecond)
	fmt.Println("Cancelling allocate")
	http.DefaultTransport.(*http.Transport).CancelRequest(req)
	unpause()
	res := <-done
	if res != nil {
		require.FailNow(t, "Error: Allocate returned non-nil")
	}
}
Exemple #23
0
func TestPingerStartMultiple(t *testing.T) {
	if skipRawSocketTests() {
		t.Skip("Test skipped due to non-root")
	}

	pinger := &Pinger{}
	pinger.AddIPs([]string{"127.0.0.1"})

	for i := 0; i < 5; i++ {
		done := make(chan struct{})
		cnt := 0

		res, err := pinger.Start()
		require.NoError(t, err)
		require.NotNil(t, res)

		go func() {
			for pr := range res {
				glog.Debugf("%v", pr)
				cnt++
			}
			close(done)
		}()

		select {
		case <-time.Tick(time.Duration(len(pinger.IPs())) * time.Second):
			require.FailNow(t, "Test timed out")

		case <-done:
			require.Equal(t, len(pinger.IPs()), cnt)
		}

		pinger.Stop()
	}
}
Exemple #24
0
// AddGetKeyCryptoServiceInterfaceBehaviorTests tests expected behavior for
// adding keys in a signed.CryptoService and other read operations on the
// crypto service after keys are present
// 1.  Adding a key succeeds
// 2.  Getting the key should return the same key, without error
// 3.  Removing the key succeeds
func AddGetKeyCryptoServiceInterfaceBehaviorTests(t *testing.T, cs signed.CryptoService, algo string) {
	expectedRolesToKeys := make(map[string]string)
	for i := 0; i < 2; i++ {
		var (
			addedPrivKey data.PrivateKey
			err          error
		)
		role := data.BaseRoles[i+1]
		switch algo {
		case data.RSAKey:
			addedPrivKey, err = trustmanager.GenerateRSAKey(rand.Reader, 2048)
		case data.ECDSAKey:
			addedPrivKey, err = trustmanager.GenerateECDSAKey(rand.Reader)
		case data.ED25519Key:
			addedPrivKey, err = trustmanager.GenerateED25519Key(rand.Reader)
		default:
			require.FailNow(t, "invalid algorithm %s", algo)
		}
		require.NoError(t, err)
		require.NotNil(t, addedPrivKey)
		require.NoError(t, cs.AddKey(role, "docker.io/notary", addedPrivKey))
		expectedRolesToKeys[role] = addedPrivKey.ID()
	}

	testGetKey(t, cs, expectedRolesToKeys, algo, true)
}
Exemple #25
0
func testType(t *testing.T, base interface{}, ff interface{}) {
	require.Implements(t, (*json.Marshaler)(nil), ff)
	require.Implements(t, (*json.Unmarshaler)(nil), ff)
	require.Implements(t, (*marshalerFaster)(nil), ff)
	require.Implements(t, (*unmarshalFaster)(nil), ff)

	if _, ok := base.(unmarshalFaster); ok {
		require.FailNow(t, "base should not have a UnmarshalJSONFFLexer")
	}

	if _, ok := base.(marshalerFaster); ok {
		require.FailNow(t, "base should not have a MarshalJSONBuf")
	}

	testSameMarshal(t, base, ff)
	testCycle(t, base, ff)
}
Exemple #26
0
func checkEqualConns(t *testing.T, ourName PeerName, got, wanted map[PeerName]Connection) {
	checkConns := make(PeerNameSet)
	for _, conn := range wanted {
		checkConns[conn.Remote().Name] = void
	}
	for _, conn := range got {
		remoteName := conn.Remote().Name
		if _, found := checkConns[remoteName]; found {
			delete(checkConns, remoteName)
		} else {
			require.FailNow(t, fmt.Sprintf("Unexpected connection from %s to %s", ourName, remoteName))
		}
	}
	if len(checkConns) > 0 {
		require.FailNow(t, fmt.Sprintf("Expected connections not found: from %s to %v", ourName, checkConns))
	}
}
Exemple #27
0
func ensureNoSubscription(t *testing.T, subscriptions <-chan *api.SubscriptionMessage) {
	select {
	case s := <-subscriptions:
		require.FailNow(t, fmt.Sprintf("unexpected subscription: %v", s))
	case <-time.After(10 * time.Millisecond):
		return
	}
}
Exemple #28
0
func AssertNothingSentErr(t *testing.T, ch <-chan error) {
	select {
	case val := <-ch:
		require.FailNow(t, fmt.Sprintf("Unexpected value on channel: %v", val))
	default:
		// no message received
	}
}
Exemple #29
0
// Check whether or not something was sent on a channel
func AssertSent(t *testing.T, ch <-chan bool) {
	timeout := time.After(10 * time.Second)
	select {
	case <-ch:
		// This case is ok
	case <-timeout:
		require.FailNow(t, "Nothing sent on channel")
	}
}
Exemple #30
0
func (g *testGossiper) checkHas(t *testing.T, vs ...byte) {
	g.RLock()
	defer g.RUnlock()
	for _, v := range vs {
		if _, found := g.state[v]; !found {
			require.FailNow(t, fmt.Sprintf("%d is missing", v))
		}
	}
}