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


Golang require.FailNow函数代码示例

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


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

示例1: Test_GetListBots

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 = "login"
	bot.Password = "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 заданного бота и проверяемого бота.")
}
开发者ID:Dremalka,项目名称:SkynetPW_old,代码行数:31,代码来源:managerbots_test.go

示例2: testTypeFuzzN

// 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)
	}
}
开发者ID:gooops,项目名称:ffjson,代码行数:29,代码来源:fuzz_test.go

示例3: Test_SendActionToBot

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"] = "logintest"
	infbot["password"] = "passwordtest"

	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, "Метод должен вернуть ошибку.")

}
开发者ID:Dremalka,项目名称:SkynetPW_old,代码行数:29,代码来源:managerbots_test.go

示例4: assertExchange

// 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
}
开发者ID:rahulxkrishna,项目名称:weave,代码行数:34,代码来源:mocks_test.go

示例5: TestWatch

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")
	}
}
开发者ID:alungboy,项目名称:firego,代码行数:33,代码来源:watch_test.go

示例6: TestReactsToStatusUpdateEvent

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")
	}
}
开发者ID:nickwales,项目名称:proxym,代码行数:31,代码来源:watcher_test.go

示例7: newMockServer

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
}
开发者ID:Rudloff,项目名称:platform,代码行数:31,代码来源:linode_test.go

示例8: Test_AddBot

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"] = "logintest"
	infbot["password"] = "passwordtest"

	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", "Пароль не равен исходному.")
}
开发者ID:Dremalka,项目名称:SkynetPW_old,代码行数:32,代码来源:managerbots_test.go

示例9: TestCancel

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")
	}
}
开发者ID:n054,项目名称:weave,代码行数:59,代码来源:allocator_test.go

示例10: TestShouldTriggerRefreshWhenMasterChanges

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")
	}
}
开发者ID:nickwales,项目名称:proxym,代码行数:58,代码来源:notifier_test.go

示例11: TestCancel

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")
	}
}
开发者ID:rahulxkrishna,项目名称:weave,代码行数:56,代码来源:allocator_test.go

示例12: EqualSlicesWithoutOrder

// 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...)
}
开发者ID:bitrise-tools,项目名称:codesigndoc,代码行数:14,代码来源:testutil.go

示例13: GossipBroadcast

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:]
	}
}
开发者ID:mandubian,项目名称:weave,代码行数:15,代码来源:testutils_test.go

示例14: TestServiceSub1Pub0

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

	})
}
开发者ID:XcoderAlex,项目名称:surgemq,代码行数:50,代码来源:service_test.go

示例15: TestUserPass

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)
}
开发者ID:titilambert,项目名称:heapster,代码行数:30,代码来源:driver_test.go


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