示例#1
0
func TestDeleteRoute(t *testing.T) {
	allConnections := [][]int{
		[]int{0, 1, 0},
		[]int{1, 0, 1},
		[]int{0, 1, 0},
	}

	nodes, toClose, _ := SetupNodes((uint)(3), allConnections, t)
	defer close(toClose)
	defer func() {
		for _, node := range nodes {
			node.Close()
		}
	}()
	addedRouteID := domain.RouteID{}
	addedRouteID[0] = 55
	addedRouteID[1] = 4
	assert.Nil(t, nodes[0].AddRoute(addedRouteID, nodes[1].GetConfig().PubKey))
	assert.Nil(t, nodes[0].ExtendRoute(addedRouteID, nodes[2].GetConfig().PubKey, time.Second))
	time.Sleep(5 * time.Second)
	assert.NotZero(t, nodes[0].DebugCountRoutes())
	assert.NotZero(t, nodes[1].DebugCountRoutes())
	assert.Nil(t, nodes[0].DeleteRoute(addedRouteID))
	time.Sleep(1 * time.Second)
	assert.Zero(t, nodes[0].DebugCountRoutes())
	assert.Zero(t, nodes[1].DebugCountRoutes())
}
示例#2
0
func TestSequenceMatch(t *testing.T) {
	//abcdjibjacLMNOPjibjac1234  => abcd LMNOP 1234

	matches := sequenceMatch("abcdjibjacLMNOPjibjac1234")
	assert.Len(t, matches, 3, "Lenght should be 2")

	for _, match := range matches {
		if match.DictionaryName == "lower" {
			assert.Equal(t, 0, match.I)
			assert.Equal(t, 3, match.J)
			assert.Equal(t, "abcd", match.Token)
			assert.NotZero(t, match.Entropy, "Entropy should be set")
		} else if match.DictionaryName == "upper" {
			assert.Equal(t, 10, match.I)
			assert.Equal(t, 14, match.J)
			assert.Equal(t, "LMNOP", match.Token)
			assert.NotZero(t, match.Entropy, "Entropy should be set")
		} else if match.DictionaryName == "digits" {
			assert.Equal(t, 21, match.I)
			assert.Equal(t, 24, match.J)
			assert.Equal(t, "1234", match.Token)
			assert.NotZero(t, match.Entropy, "Entropy should be set")
		} else {
			assert.True(t, false, "Unknow dictionary")
		}
	}
}
示例#3
0
func TestAddNote(t *testing.T) {
	assert := assert.New(t)

	dbMap := initDb()
	defer dbMap.Db.Close()
	ctx := context.Background()
	ctx = context.WithValue(ctx, "db", dbMap)
	ctx = context.WithValue(ctx, "auth", &auth.AuthContext{})

	server := httptest.NewServer(http.HandlerFunc(
		func(w http.ResponseWriter, r *http.Request) {
			AddNote(ctx, w, r)
		},
	))
	defer server.Close()

	resp := request(t, server.URL, http.StatusOK, map[string]interface{}{
		"title":   "Test Title",
		"content": "lorem ipsum dolor sit amet consetetur.",
		"ownerId": 0,
	})
	assert.NotNil(resp)

	note := resp.(map[string]interface{})
	assert.Equal("Test Title", note["title"])
	assert.Equal("lorem ipsum dolor sit amet consetetur.", note["content"])
	assert.EqualValues(0, note["ownerId"])
	assert.NotZero(note["createdAt"])
	assert.NotZero(note["updatedAt"])

	count, err := dbMap.SelectInt("SELECT COUNT(id) FROM notes")
	assert.Nil(err)
	assert.EqualValues(1, count)
}
示例#4
0
func TestRouteExpiry(t *testing.T) {
	allConnections := [][]int{
		[]int{0, 1, 0},
		[]int{1, 0, 1},
		[]int{0, 1, 0},
	}

	nodes, toClose, transports := SetupNodes((uint)(3), allConnections, t)
	defer close(toClose)
	defer func() {
		for _, node := range nodes {
			node.Close()
		}
	}()

	addedRouteID := domain.RouteID{}
	addedRouteID[0] = 55
	addedRouteID[1] = 4

	assert.Nil(t, nodes[0].AddRoute(addedRouteID, nodes[1].GetConfig().PubKey))
	{
		lastConfirmed, err := nodes[0].GetRouteLastConfirmed(addedRouteID)
		assert.Nil(t, err)
		assert.Zero(t, lastConfirmed.Unix())
	}
	assert.Nil(t, nodes[0].ExtendRoute(addedRouteID, nodes[2].GetConfig().PubKey, time.Second))
	assert.NotZero(t, nodes[1].DebugCountRoutes())

	var afterExtendConfirmedTime time.Time
	{
		lastConfirmed, err := nodes[0].GetRouteLastConfirmed(addedRouteID)
		assert.Nil(t, err)
		afterExtendConfirmedTime = lastConfirmed
	}

	time.Sleep(5 * time.Second)
	assert.NotZero(t, nodes[1].DebugCountRoutes())
	var afterWaitConfirmedTime time.Time
	{
		lastConfirmed, err := nodes[0].GetRouteLastConfirmed(addedRouteID)
		assert.Nil(t, err)
		afterWaitConfirmedTime = lastConfirmed
	}

	// Don't allow refreshes to get thru
	transports[0].SetIgnoreSendStatus(true)
	time.Sleep(5 * time.Second)
	var afterIgnoreConfirmedTime time.Time
	{
		lastConfirmed, err := nodes[0].GetRouteLastConfirmed(addedRouteID)
		assert.Nil(t, err)
		afterIgnoreConfirmedTime = lastConfirmed
	}

	assert.Zero(t, nodes[1].DebugCountRoutes())
	assert.NotZero(t, afterExtendConfirmedTime)
	assert.NotZero(t, afterWaitConfirmedTime)
	assert.NotEqual(t, afterExtendConfirmedTime, afterWaitConfirmedTime)
	assert.Equal(t, afterWaitConfirmedTime, afterIgnoreConfirmedTime)
}
func TestCreatesCorrectly(t *testing.T) {
	registration := CreateNewRegistration("myevent", "mycallback")

	assert.NotZero(t, registration.Id)
	assert.NotZero(t, registration.CreationDate)
	assert.Equal(t, "myevent", registration.EventName)
	assert.Equal(t, "mycallback", registration.CallbackUrl)
}
示例#6
0
func TestSpatialMatchQwerty(t *testing.T) {
	matches := spatialMatch("qwerty")
	assert.Len(t, matches, 1, "Lenght should be 1")
	assert.NotZero(t, matches[0].Entropy, "Entropy should be set")

	matches = spatialMatch("asdf")
	assert.Len(t, matches, 1, "Lenght should be 1")
	assert.NotZero(t, matches[0].Entropy, "Entropy should be set")

}
示例#7
0
func TestFillAll(t *testing.T) {
	customName := struct {
		Name string `fako:"full_name"`
	}{}

	customU := struct {
		Username string `fako:"user_name"`
	}{}

	Fill(&customName, &customU)
	assert.NotZero(t, customName.Name)
	assert.NotZero(t, customU.Username)
}
示例#8
0
func TestTimestamps(t *testing.T) {
	var mockProposer mockProposer
	s := NewMemoryStore(&mockProposer)
	assert.NotNil(t, s)

	var (
		retrievedNode *api.Node
		updatedNode   *api.Node
	)

	// Create one node
	n := &api.Node{
		ID: "id1",
		Spec: api.NodeSpec{
			Annotations: api.Annotations{
				Name: "name1",
			},
		},
	}
	err := s.Update(func(tx Tx) error {
		assert.NoError(t, CreateNode(tx, n))
		return nil
	})
	assert.NoError(t, err)

	// Make sure our local copy got updated.
	assert.NotZero(t, n.Meta.CreatedAt)
	assert.NotZero(t, n.Meta.UpdatedAt)
	// Since this is a new node, CreatedAt should equal UpdatedAt.
	assert.Equal(t, n.Meta.CreatedAt, n.Meta.UpdatedAt)

	// Fetch the node from the store and make sure timestamps match.
	s.View(func(tx ReadTx) {
		retrievedNode = GetNode(tx, n.ID)
	})
	assert.Equal(t, retrievedNode.Meta.CreatedAt, n.Meta.CreatedAt)
	assert.Equal(t, retrievedNode.Meta.UpdatedAt, n.Meta.UpdatedAt)

	// Make an update.
	retrievedNode.Spec.Annotations.Name = "name2"
	err = s.Update(func(tx Tx) error {
		assert.NoError(t, UpdateNode(tx, retrievedNode))
		updatedNode = GetNode(tx, n.ID)
		return nil
	})
	assert.NoError(t, err)

	// Ensure `CreatedAt` is the same after the update and `UpdatedAt` got updated.
	assert.Equal(t, updatedNode.Meta.CreatedAt, n.Meta.CreatedAt)
	assert.NotEqual(t, updatedNode.Meta.CreatedAt, updatedNode.Meta.UpdatedAt)
}
示例#9
0
func TestExpiry(t *testing.T) {
	_, testKeyB, _, _,
		transportA, transportB,
		_, _ := SetupTwoPeers(t)

	testContents := []byte{4, 3, 22, 6, 88, 99}
	assert.Nil(t, transportA.SendMessage(testKeyB, testContents, nil))

	time.Sleep(time.Second)
	assert.NotZero(t, transportA.debug_countMapItems())
	assert.NotZero(t, transportB.debug_countMapItems())
	time.Sleep(7 * time.Second)
	assert.Zero(t, transportA.debug_countMapItems())
	assert.Zero(t, transportB.debug_countMapItems())
}
示例#10
0
func TestPulseEmitTheRightBeatFormat(t *testing.T) {
	done := make(chan struct{})

	NewPulse("test", newTestBackend(t,
		func(t *testing.T, beat Beat) {
			assert.Equal(t, "test", beat.Name)
			assert.Equal(t, runtime.NumGoroutine(), beat.Values["num_goroutines"])
			assert.NotZero(t, beat.Values["alloc"])
			assert.NotZero(t, beat.Values["total_alloc"])

			done <- struct{}{}
		}),
	).Tick(1 * time.Millisecond)

	<-done
}
示例#11
0
func TestNtQuerySystemProcessorPerformanceInformation(t *testing.T) {
	cpus, err := NtQuerySystemProcessorPerformanceInformation()
	if err != nil {
		t.Fatal(err)
	}

	assert.Len(t, cpus, runtime.NumCPU())

	for i, cpu := range cpus {
		assert.NotZero(t, cpu.IdleTime)
		assert.NotZero(t, cpu.KernelTime)
		assert.NotZero(t, cpu.UserTime)

		t.Logf("CPU=%v SystemProcessorPerformanceInformation=%v", i, cpu)
	}
}
示例#12
0
// TestServerTime calls the GetTime method of the messaging to test the time
func TestServerTime(t *testing.T) {
	stop, _ := NewVCRNonSubscribe("fixtures/time", []string{})
	defer stop()

	pubnubInstance := messaging.NewPubnub(PubKey, SubKey, "", "", false, "testTime")

	assert := assert.New(t)
	successChannel := make(chan []byte)
	errorChannel := make(chan []byte)

	go pubnubInstance.GetTime(successChannel, errorChannel)
	select {
	case value := <-successChannel:
		response := string(value)
		timestamp, err := strconv.Atoi(strings.Trim(response, "[]\n"))
		if err != nil {
			assert.Fail(err.Error())
		}

		assert.NotZero(timestamp)
	case err := <-errorChannel:
		assert.Fail(string(err))
	case <-timeouts(10):
		assert.Fail("Getting server timestamp timeout")
	}
}
示例#13
0
func TestSendDatagram(t *testing.T) {
	transportA, keyA, transportB, keyB := SetupAB(false, t)
	defer transportA.Close()
	defer transportB.Close()

	testKeyC := cipher.NewPubKey([]byte{3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0})
	assert.Zero(t, transportA.GetMaximumMessageSizeToPeer(keyA))
	assert.NotZero(t, transportA.GetMaximumMessageSizeToPeer(keyB))
	assert.NotZero(t, transportB.GetMaximumMessageSizeToPeer(keyA))
	assert.Zero(t, transportB.GetMaximumMessageSizeToPeer(keyB))
	assert.Zero(t, transportA.GetMaximumMessageSizeToPeer(testKeyC))
	assert.Zero(t, transportB.GetMaximumMessageSizeToPeer(testKeyC))

	sendBytesA := []byte{66, 44, 33, 2, 123, 100, 22}
	sendBytesB := []byte{23, 33, 12, 88, 43, 120}

	assert.Nil(t, transportA.SendMessage(keyB, sendBytesA, nil))
	assert.Nil(t, transportB.SendMessage(keyA, sendBytesB, nil))

	chanA := make(chan []byte, 10)
	chanB := make(chan []byte, 10)

	transportA.SetReceiveChannel(chanA)
	transportB.SetReceiveChannel(chanB)

	gotA := false
	gotB := false

	for !gotA || !gotB {
		select {
		case msg_a := <-chanA:
			{
				assert.Equal(t, sendBytesB, msg_a)
				gotA = true
				break
			}
		case msg_b := <-chanB:
			{
				assert.Equal(t, sendBytesA, msg_b)
				gotB = true
				break
			}
		case <-time.After(5 * time.Second):
			panic("Test timed out")
		}
	}
}
示例#14
0
func TestPidOf(t *testing.T) {
	if runtime.GOOS == "darwin" || runtime.GOOS == "windows" {
		t.Skipf("not supported on GOOS=%s", runtime.GOOS)
	}
	pids := PidOf(filepath.Base(os.Args[0]))
	assert.NotZero(t, pids)
	assert.Contains(t, pids, os.Getpid())
}
示例#15
0
func Test_UploadVideo(t *testing.T) {
	testFile := path.Join(testFilesDir, "cat-video.mp4")

	c := New()
	res, err := c.UploadVideo(testFile)

	assert.Nil(t, err)
	assert.NotZero(t, res)
}
示例#16
0
func TestShouldReturnFailedMethodExecutionResult(t *testing.T) {
	var called bool
	step := Step{
		Description: "Test description",
		Impl: func(args ...interface{}) {
			called = true
			var a []string
			fmt.Println(a[7])
		},
	}

	res := step.Execute("foo")

	assert.True(t, called)
	assert.True(t, res.GetFailed())
	assert.NotZero(t, res.GetExecutionTime())
	assert.Equal(t, "runtime error: index out of range", res.GetErrorMessage())
	assert.NotZero(t, res.GetStackTrace())
}
示例#17
0
func TestPutBSO(t *testing.T) {
	db, _ := getTestDB()
	assert := assert.New(t)

	cId := 1
	bId := "b0"

	// test an INSERT
	modified, err := db.PutBSO(cId, bId, String("foo"), Int(1), Int(DEFAULT_BSO_TTL))
	assert.NoError(err)
	assert.NotZero(modified)

	cModified, err := db.GetCollectionModified(cId)
	assert.NoError(err)
	assert.Equal(modified, cModified)

	bso, err := db.GetBSO(cId, bId)
	assert.NoError(err)
	assert.NotNil(bso)
	assert.Equal("foo", bso.Payload)
	assert.Equal(1, bso.SortIndex)

	// sleep a bit so we have a least a 100th of a millisecond difference
	// between the operations
	time.Sleep(19 * time.Millisecond)

	// test the UPDATE
	modified2, err := db.PutBSO(cId, bId, String("bar"), Int(2), Int(DEFAULT_BSO_TTL))
	assert.NoError(err)
	assert.NotZero(modified2)
	assert.NotEqual(modified2, modified)

	cModified, err = db.GetCollectionModified(cId)
	assert.NoError(err)
	assert.Equal(modified2, cModified)

	bso2, err := db.GetBSO(cId, bId)
	assert.NoError(err)
	assert.NotNil(bso2)
	assert.Equal("bar", bso2.Payload)
	assert.Equal(2, bso2.SortIndex)
}
示例#18
0
func TestChallengePickUsers(t *testing.T) {
	c := newChallenge()

	c.PickUsers(map[string]*User{
		"u1": {PerformanceScore: 20},
		"u2": {PerformanceScore: 40},
	})

	assert.Len(t, c.UsersShown, 2)
	assert.NotZero(t, c.RightAnswerIndex)
}
示例#19
0
文件: remote_test.go 项目: dyweb/Ayi
func TestSSHCloneRegexp(t *testing.T) {
	assert := assert.New(t)
	segments := sshCloneRegexp.FindStringSubmatch("ssh://[email protected]:3022/at15/tongqu4.git")
	assert.NotZero(segments)
	assert.Equal(5, len(segments))
	segments = sshCloneRegexp.FindStringSubmatch("[email protected]:dyweb/Ayi.git")
	assert.Equal(5, len(segments))
	// t.Log(segments)
	// port is empty
	assert.Equal("", segments[2])
}
示例#20
0
func TestRepeatMatch(t *testing.T) {
	//aaaBbBb
	matches := repeatMatch("aaabBbB")

	assert.Len(t, matches, 2, "Lenght should be 2")

	for _, match := range matches {
		if strings.ToLower(match.DictionaryName) == "b" {
			assert.Equal(t, 3, match.I)
			assert.Equal(t, 6, match.J)
			assert.Equal(t, "bBbB", match.Token)
			assert.NotZero(t, match.Entropy, "Entropy should be set")
		} else {
			assert.Equal(t, 0, match.I)
			assert.Equal(t, 2, match.J)
			assert.Equal(t, "aaa", match.Token)
			assert.NotZero(t, match.Entropy, "Entropy should be set")

		}
	}
}
示例#21
0
func TestInitializeD(t *testing.T) {
	d := InitD(100)
	for i := range d {
		for j := range d[i] {
			if i == j {
				assert.Zero(t, d[i][j], "d[%v][%v] value is %v", i, j, d[i][j])
			} else {
				assert.NotZero(t, d[i][j], "d[%v][%v] value is %v", i, j, d[i][j])
			}
		}
	}
}
示例#22
0
func (suite *LoggerTester) Test06Admin() {
	t := suite.T()
	assert := assert.New(t)

	suite.setupFixture()
	defer suite.teardownFixture()

	client := suite.client

	stats, err := client.GetStats()
	assert.NoError(err)
	assert.NotZero(stats.NumMessages)
}
示例#23
0
func assertRefDefinition(t testing.TB, defs map[string]spec.Schema, defName, refURL, goName string) {
	schema, ok := defs[defName]
	if assert.True(t, ok) {
		if assert.NotZero(t, schema.Ref) {
			url := schema.Ref.String()
			assert.Equal(t, refURL, url)
			if goName != "" {
				assert.Equal(t, goName, schema.Extensions["x-go-name"])
			} else {
				assert.Nil(t, schema.Extensions["x-go-name"])
			}
		}
	}
}
示例#24
0
func Test_UploadVideo_Authenticated_UsernamePassword(t *testing.T) {
	if os.Getenv("STREAMABLE_USERNAME") == "" || os.Getenv("STREAMABLE_PASSWORD") == "" {
		t.Skip("skipping test; $STREAMABLE_USERNAME or $STREAMABLE_PASSWORD not set")
	}

	testFile := path.Join(testFilesDir, "cat-video.mp4")

	c := New()
	c.SetCredentials(os.Getenv("STREAMABLE_USERNAME"), os.Getenv("STREAMABLE_PASSWORD"))
	res, err := c.UploadVideo(testFile)

	assert.Nil(t, err)
	assert.NotZero(t, res)
}
示例#25
0
func TestDictionaryMatch(t *testing.T) {
	var matches []match.Match
	for _, dicMatcher := range DICTIONARY_MATCHERS {
		matchesTemp := dicMatcher("first")
		matches = append(matches, matchesTemp...)
	}

	assert.Len(t, matches, 4, "Lenght should be 4")
	for _, match := range matches {
		assert.NotZero(t, match.Entropy, "Entropy should be set")

	}

}
示例#26
0
// TestChangeableComponents ensures that Components which are being referenced, are changeable
func TestChangeableComponents(t *testing.T) {
	w := &World{}

	sys1 := &MySystemOne{}
	w.AddSystem(sys1)

	e1 := MyEntity1{}
	e1.BasicEntity = NewBasic()

	sys1.Add(&e1.BasicEntity, &e1.MyComponent1)

	sys1.Update(0.125)

	assert.NotZero(t, e1.MyComponent1.A, "MySystemOne should have been able to change the value of MyComponent1.A")
}
示例#27
0
func TestHeartbeat(t *testing.T) {
	cfg := DefaultConfig()
	cfg.HeartbeatPeriod = 500 * time.Millisecond
	cfg.HeartbeatEpsilon = 0
	gd, err := startDispatcher(DefaultConfig())
	assert.NoError(t, err)
	defer gd.Close()

	var expectedSessionID string
	{
		stream, err := gd.Clients[0].Session(context.Background(), &api.SessionRequest{})
		assert.NoError(t, err)
		defer stream.CloseSend()

		resp, err := stream.Recv()
		assert.NoError(t, err)
		assert.NotEmpty(t, resp.SessionID)
		expectedSessionID = resp.SessionID
	}
	time.Sleep(250 * time.Millisecond)

	{
		// heartbeat without correct SessionID should fail
		resp, err := gd.Clients[0].Heartbeat(context.Background(), &api.HeartbeatRequest{})
		assert.Nil(t, resp)
		assert.Error(t, err)
		assert.Equal(t, grpc.Code(err), codes.InvalidArgument)
	}

	resp, err := gd.Clients[0].Heartbeat(context.Background(), &api.HeartbeatRequest{SessionID: expectedSessionID})
	assert.NoError(t, err)
	assert.NotZero(t, resp.Period)
	time.Sleep(300 * time.Millisecond)

	gd.Store.View(func(readTx store.ReadTx) {
		storeNodes, err := store.FindNodes(readTx, store.All)
		assert.NoError(t, err)
		assert.NotEmpty(t, storeNodes)
		found := false
		for _, node := range storeNodes {
			if node.ID == gd.SecurityConfigs[0].ClientTLSCreds.NodeID() {
				found = true
				assert.Equal(t, api.NodeStatus_READY, node.Status.State)
			}
		}
		assert.True(t, found)
	})
}
示例#28
0
func TestShouldReturnPassedMethodExecutionResult(t *testing.T) {
	var called bool
	step := Step{
		Description: "Test description",
		Impl: func(args ...interface{}) {
			called = true
		},
	}

	res := step.Execute("foo")

	assert.True(t, called)
	assert.False(t, res.GetFailed())
	assert.NotZero(t, res.GetExecutionTime())
	assert.Zero(t, res.GetErrorMessage())
	assert.Zero(t, res.GetStackTrace())
}
示例#29
0
func assertArrayWithRefDefinition(t testing.TB, defs map[string]spec.Schema, defName, refURL, goName string) {
	schema, ok := defs[defName]
	if assert.True(t, ok) {
		if assert.NotEmpty(t, schema.Type) {
			assert.Equal(t, "array", schema.Type[0])
			adl := schema.Items
			if assert.NotNil(t, adl) && assert.NotNil(t, adl.Schema) {
				if assert.NotZero(t, adl.Schema.Ref) {
					assert.Equal(t, refURL, adl.Schema.Ref.String())
				}
			}
			if goName != "" {
				assert.Equal(t, goName, schema.Extensions["x-go-name"])
			} else {
				assert.Nil(t, schema.Extensions["x-go-name"])
			}
		}
	}
}
示例#30
0
func TestRegisterCreateWithValidRequestCreatesValidRegistration(t *testing.T) {
	SetupRegisterTest(t)
	mockRegisterDeps.DalMock.Mock.On("GetRegistrationByEventAndCallback", "event.something", "http://some_callback_url.com").Return(nil, nil)

	var responseRecorder httptest.ResponseRecorder
	var request http.Request
	request.Body = ioutil.NopCloser(bytes.NewBufferString(`
		{
			"event_name": "event.something",
			"callback_url": "http://some_callback_url.com"
		}`))

	RegisterCreateHandler(&responseRecorder, &request)

	registration := mockRegisterDeps.DalMock.UpsertObject
	assert.NotZero(t, registration.Id)
	assert.Equal(t, "event.something", registration.EventName)
	assert.Equal(t, "http://some_callback_url.com", registration.CallbackUrl)
}