Esempio n. 1
0
func TestLinesWithSimilarAngle(t *testing.T) {
	examples := []struct {
		angle   float64
		lines   []polarLine
		similar []polarLine
		other   []polarLine
	}{
		{
			angle:   0,
			lines:   []polarLine{polarLine{Theta: 0, Distance: 1}, polarLine{Theta: 0, Distance: 1000}, polarLine{Theta: 0.49}, polarLine{Theta: 0.5}, polarLine{Theta: -0.49}, polarLine{Theta: -0.5}},
			similar: []polarLine{polarLine{Theta: 0, Distance: 1}, polarLine{Theta: 0, Distance: 1000}, polarLine{Theta: 0.49}, polarLine{Theta: -0.49}},
			other:   []polarLine{polarLine{Theta: 0.5}, polarLine{Theta: -0.5}},
		},
		{
			angle:   2 * math.Pi,
			lines:   []polarLine{polarLine{Theta: 0, Distance: 1}, polarLine{Theta: 0, Distance: 1000}, polarLine{Theta: 0.49}, polarLine{Theta: 0.5}, polarLine{Theta: -0.49}, polarLine{Theta: -0.5}},
			similar: []polarLine{polarLine{Theta: 0, Distance: 1}, polarLine{Theta: 0, Distance: 1000}, polarLine{Theta: 0.49}, polarLine{Theta: -0.49}},
			other:   []polarLine{polarLine{Theta: 0.5}, polarLine{Theta: -0.5}},
		},
		{
			angle:   math.Pi,
			lines:   []polarLine{polarLine{Theta: math.Pi + 0, Distance: 1}, polarLine{Theta: math.Pi + 0, Distance: 1000}, polarLine{Theta: math.Pi + 0.49}, polarLine{Theta: math.Pi + 0.5}, polarLine{Theta: math.Pi - 0.49}, polarLine{Theta: math.Pi - 0.5}},
			similar: []polarLine{polarLine{Theta: math.Pi + 0, Distance: 1}, polarLine{Theta: math.Pi + 0, Distance: 1000}, polarLine{Theta: math.Pi + 0.49}, polarLine{Theta: math.Pi - 0.49}},
			other:   []polarLine{polarLine{Theta: math.Pi + 0.5}, polarLine{Theta: math.Pi - 0.5}},
		},
		{
			angle:   math.Pi,
			lines:   []polarLine{polarLine{Theta: 0, Distance: 1}, polarLine{Theta: 0, Distance: 1000}, polarLine{Theta: 0.49}, polarLine{Theta: 0.5}, polarLine{Theta: -0.49}, polarLine{Theta: -0.5}},
			similar: []polarLine{},
			other:   []polarLine{polarLine{Theta: 0, Distance: 1}, polarLine{Theta: 0, Distance: 1000}, polarLine{Theta: 0.49}, polarLine{Theta: 0.5}, polarLine{Theta: -0.49}, polarLine{Theta: -0.5}},
		},
		{
			angle:   0,
			lines:   []polarLine{polarLine{Theta: 0, Distance: 1}, polarLine{Theta: 0, Distance: 1000}, polarLine{Theta: 0.49}, polarLine{Theta: -0.49}},
			similar: []polarLine{polarLine{Theta: 0, Distance: 1}, polarLine{Theta: 0, Distance: 1000}, polarLine{Theta: 0.49}, polarLine{Theta: -0.49}},
			other:   []polarLine{},
		},
	}

	for _, tt := range examples {
		similar, other := linesWithSimilarAngle(tt.lines, tt.angle)
		if !assert.Len(t, similar, len(tt.similar)) {
			t.Logf("Got:\n%v\nexpecting:\n%v", similar, tt.similar)
			t.FailNow()
		}
		for i, line := range similar {
			assert.InDelta(t, tt.similar[i].Theta, line.Theta, thetaDelta)
			assert.Equal(t, tt.similar[i].Distance, line.Distance)
		}

		if !assert.Len(t, other, len(tt.other)) {
			t.Logf("Got:\n%v\nexpecting:\n%v", similar, tt.similar)
			t.FailNow()
		}
		for i, line := range other {
			assert.InDelta(t, tt.other[i].Theta, line.Theta, thetaDelta)
			assert.Equal(t, tt.other[i].Distance, line.Distance)
		}
	}
}
Esempio n. 2
0
func TestMultipleGetEmpty(t *testing.T) {
	q := New(10)
	var wg sync.WaitGroup
	wg.Add(2)
	results := make([][]interface{}, 2)

	go func() {
		wg.Done()
		local, err := q.Get(1)
		assert.Nil(t, err)
		results[0] = local
		wg.Done()
	}()

	go func() {
		wg.Done()
		local, err := q.Get(1)
		assert.Nil(t, err)
		results[1] = local
		wg.Done()
	}()

	wg.Wait()
	wg.Add(2)

	q.Put(`a`, `b`, `c`)
	wg.Wait()

	if assert.Len(t, results[0], 1) && assert.Len(t, results[1], 1) {
		assert.True(t, (results[0][0] == `a` && results[1][0] == `b`) ||
			(results[0][0] == `b` && results[1][0] == `a`),
			`The array should be a, b or b, a`)
	}
}
Esempio n. 3
0
func TestCreateControlChannel(t *testing.T) {
	node := NewNode()
	assert.Len(t, node.controlChannels, 0, "Should be 0 control channels")
	node.AddControlChannel()
	assert.Len(t, node.controlChannels, 1, "Should be 1 control channels")
	fmt.Println("--------------------\n")
}
Esempio n. 4
0
func TestContextError(t *testing.T) {
	c, _, _ := CreateTestContext()
	assert.Empty(t, c.Errors)

	c.Error(errors.New("first error"))
	assert.Len(t, c.Errors, 1)
	assert.Equal(t, c.Errors.String(), "Error #01: first error\n")

	c.Error(&Error{
		Err:  errors.New("second error"),
		Meta: "some data 2",
		Type: ErrorTypePublic,
	})
	assert.Len(t, c.Errors, 2)

	assert.Equal(t, c.Errors[0].Err, errors.New("first error"))
	assert.Nil(t, c.Errors[0].Meta)
	assert.Equal(t, c.Errors[0].Type, ErrorTypePrivate)

	assert.Equal(t, c.Errors[1].Err, errors.New("second error"))
	assert.Equal(t, c.Errors[1].Meta, "some data 2")
	assert.Equal(t, c.Errors[1].Type, ErrorTypePublic)

	assert.Equal(t, c.Errors.Last(), c.Errors[1])
}
Esempio n. 5
0
func TestGetRemoteSignedCertificate(t *testing.T) {
	tc := testutils.NewTestCA(t)
	defer tc.Stop()

	// Create a new CSR to be signed
	csr, _, err := ca.GenerateAndWriteNewKey(tc.Paths.Node)
	assert.NoError(t, err)

	certs, err := ca.GetRemoteSignedCertificate(context.Background(), csr, tc.ManagerToken, tc.RootCA.Pool, tc.Remotes, nil, nil)
	assert.NoError(t, err)
	assert.NotNil(t, certs)

	// Test the expiration for a manager certificate
	parsedCerts, err := helpers.ParseCertificatesPEM(certs)
	assert.NoError(t, err)
	assert.Len(t, parsedCerts, 2)
	assert.True(t, time.Now().Add(ca.DefaultNodeCertExpiration).AddDate(0, 0, -1).Before(parsedCerts[0].NotAfter))
	assert.True(t, time.Now().Add(ca.DefaultNodeCertExpiration).AddDate(0, 0, 1).After(parsedCerts[0].NotAfter))
	assert.Equal(t, parsedCerts[0].Subject.OrganizationalUnit[0], ca.ManagerRole)

	// Test the expiration for an agent certificate
	certs, err = ca.GetRemoteSignedCertificate(tc.Context, csr, tc.WorkerToken, tc.RootCA.Pool, tc.Remotes, nil, nil)
	assert.NoError(t, err)
	assert.NotNil(t, certs)
	parsedCerts, err = helpers.ParseCertificatesPEM(certs)
	assert.NoError(t, err)
	assert.Len(t, parsedCerts, 2)
	assert.True(t, time.Now().Add(ca.DefaultNodeCertExpiration).AddDate(0, 0, -1).Before(parsedCerts[0].NotAfter))
	assert.True(t, time.Now().Add(ca.DefaultNodeCertExpiration).AddDate(0, 0, 1).After(parsedCerts[0].NotAfter))
	assert.Equal(t, parsedCerts[0].Subject.OrganizationalUnit[0], ca.AgentRole)
}
Esempio n. 6
0
//TestGetPodContainers tests the flow of GetPodContainers.
func TestGetPodContainers(t *testing.T) {
	var (
		cluster      = newRealCluster(newTimeStore, time.Minute)
		source_cache = cacheFactory()
		assert       = assert.New(t)
	)
	// Invocation with empty cluster
	res := cluster.GetPodContainers("test", "pod1")
	assert.Len(res, 0)

	// Populate cluster
	assert.NoError(cluster.Update(source_cache))

	// Normal Invocation
	res = cluster.GetPodContainers("test", "pod1")
	assert.Len(res, 2)

	// Invocation with non-existant namespace
	res = cluster.GetPodContainers("fail", "pod1")
	assert.Len(res, 0)

	// Invocation with non-existant pod
	res = cluster.GetPodContainers("test", "pod5")
	assert.Len(res, 0)
}
Esempio n. 7
0
func TestEmailsService_All(t *testing.T) {
	setup()
	defer tearDown()

	link := fmt.Sprintf(`<%s>; rel="next", <%s>; rel="last"`, testURLOf("/user/emails?page=2"), testURLOf("/user/emails?page=3"))
	respHeaderParams := map[string]string{"Link": link}
	stubGet(t, "/user/emails", "emails", respHeaderParams)

	url, _ := EmailUrl.Expand(nil)
	allEmails, result := client.Emails(url).All()

	assert.False(t, result.HasError())
	assert.Len(t, allEmails, 1)

	email := allEmails[0]
	assert.Equal(t, "*****@*****.**", email.Email)
	assert.Equal(t, true, email.Verified)
	assert.Equal(t, true, email.Primary)

	assert.Equal(t, testURLStringOf("/user/emails?page=2"), string(*result.NextPage))
	assert.Equal(t, testURLStringOf("/user/emails?page=3"), string(*result.LastPage))

	nextPageURL, err := result.NextPage.Expand(nil)
	assert.NoError(t, err)

	allEmails, result = client.Emails(nextPageURL).All()
	assert.False(t, result.HasError())
	assert.Len(t, allEmails, 1)
}
Esempio n. 8
0
// adding a key to a role marks root as dirty as well as the role
func TestAddBaseKeysToRoot(t *testing.T) {
	for _, role := range data.BaseRoles {
		ed25519 := signed.NewEd25519()
		keyDB := keys.NewDB()
		repo := initRepo(t, ed25519, keyDB)

		key, err := ed25519.Create(role, data.ED25519Key)
		assert.NoError(t, err)

		assert.Len(t, repo.Root.Signed.Roles[role].KeyIDs, 1)

		assert.NoError(t, repo.AddBaseKeys(role, key))

		_, ok := repo.Root.Signed.Keys[key.ID()]
		assert.True(t, ok)
		assert.Len(t, repo.Root.Signed.Roles[role].KeyIDs, 2)
		assert.True(t, repo.Root.Dirty)

		switch role {
		case data.CanonicalSnapshotRole:
			assert.True(t, repo.Snapshot.Dirty)
		case data.CanonicalTargetsRole:
			assert.True(t, repo.Targets[data.CanonicalTargetsRole].Dirty)
		case data.CanonicalTimestampRole:
			assert.True(t, repo.Timestamp.Dirty)
		}
	}
}
Esempio n. 9
0
// Test that running output doesn't flush until it's full when
// FlushBufferWhenFull is set.
func TestRunningOutputFlushWhenFull(t *testing.T) {
	conf := &OutputConfig{
		Filter: Filter{
			IsActive: false,
		},
	}

	m := &mockOutput{}
	ro := NewRunningOutput("test", m, conf, 6, 10)

	// Fill buffer to 1 under limit
	for _, metric := range first5 {
		ro.AddMetric(metric)
	}
	// no flush yet
	assert.Len(t, m.Metrics(), 0)

	// add one more metric
	ro.AddMetric(next5[0])
	// now it flushed
	assert.Len(t, m.Metrics(), 6)

	// add one more metric and write it manually
	ro.AddMetric(next5[1])
	err := ro.Write()
	assert.NoError(t, err)
	assert.Len(t, m.Metrics(), 7)
}
Esempio n. 10
0
// A delegation can be created with a role that is missing a signing key, so
// long as UpdateDelegations is called with the key
func TestUpdateDelegationsRoleThatIsMissingDelegationKey(t *testing.T) {
	ed25519 := signed.NewEd25519()
	keyDB := keys.NewDB()
	repo := initRepo(t, ed25519, keyDB)

	roleKey, err := ed25519.Create("Invalid Role", data.ED25519Key)
	assert.NoError(t, err)

	role, err := data.NewRole("targets/role", 1, []string{}, []string{""}, []string{})
	assert.NoError(t, err)

	// key should get added to role as part of updating the delegation
	err = repo.UpdateDelegations(role, data.KeyList{roleKey})
	assert.NoError(t, err)

	r, ok := repo.Targets[data.CanonicalTargetsRole]
	assert.True(t, ok)
	assert.Len(t, r.Signed.Delegations.Roles, 1)
	assert.Len(t, r.Signed.Delegations.Keys, 1)
	keyIDs := r.Signed.Delegations.Roles[0].KeyIDs
	assert.Len(t, keyIDs, 1)
	assert.Equal(t, roleKey.ID(), keyIDs[0])
	assert.True(t, r.Dirty)

	// no empty delegation metadata created for new delegation
	_, ok = repo.Targets["targets/role"]
	assert.False(t, ok, "no targets file should be created for empty delegation")
}
Esempio n. 11
0
func TestDeleteDelegationsMidSliceRole(t *testing.T) {
	ed25519 := signed.NewEd25519()
	keyDB := keys.NewDB()
	repo := initRepo(t, ed25519, keyDB)

	testKey, err := ed25519.Create("targets/test", data.ED25519Key)
	assert.NoError(t, err)
	role, err := data.NewRole("targets/test", 1, []string{}, []string{""}, []string{})
	assert.NoError(t, err)

	err = repo.UpdateDelegations(role, data.KeyList{testKey})
	assert.NoError(t, err)

	role2, err := data.NewRole("targets/test2", 1, []string{}, []string{""}, []string{})
	assert.NoError(t, err)

	err = repo.UpdateDelegations(role2, data.KeyList{testKey})
	assert.NoError(t, err)

	role3, err := data.NewRole("targets/test3", 1, []string{}, []string{""}, []string{})
	assert.NoError(t, err)

	err = repo.UpdateDelegations(role3, data.KeyList{testKey})
	assert.NoError(t, err)

	err = repo.DeleteDelegation(*role2)
	assert.NoError(t, err)

	r, ok := repo.Targets[data.CanonicalTargetsRole]
	assert.True(t, ok)
	assert.Len(t, r.Signed.Delegations.Roles, 2)
	assert.Len(t, r.Signed.Delegations.Keys, 1)
	assert.True(t, r.Dirty)
}
func TestSplitService(t *testing.T) {
	e := executor{}

	tests := []struct {
		description string
		service     string
		version     string
		alias       string
		alternative string
	}{
		{"service", "service", "latest", "service", ""},
		{"service:version", "service", "version", "service", ""},
		{"namespace/service", "namespace/service", "latest", "namespace__service", "namespace-service"},
		{"namespace/service:version", "namespace/service", "version", "namespace__service", "namespace-service"},
	}

	for _, test := range tests {
		service, version, linkNames := e.splitServiceAndVersion(test.description)

		assert.Equal(t, test.service, service, "for", test.description)
		assert.Equal(t, test.version, version, "for", test.description)
		assert.Equal(t, test.alias, linkNames[0], "for", test.description)
		if test.alternative != "" {
			assert.Len(t, linkNames, 2, "for", test.description)
			assert.Equal(t, test.alternative, linkNames[1], "for", test.description)
		} else {
			assert.Len(t, linkNames, 1, "for", test.description)
		}
	}
}
Esempio n. 13
0
func TestPutLinesIntoBucketsReuseLineIfBucketsHaveSlightlyDifferent(t *testing.T) {
	buckets := map[float64][]angleBucket{
		1.0: {angleBucket{0, 2}},
		2.0: {angleBucket{1, 3}},
	}

	lines := []polarLine{
		polarLine{Theta: 1},
		polarLine{Theta: 1.1},
		polarLine{Theta: 2.1},
	}

	expected := map[float64][]polarLine{
		1.0: {polarLine{Theta: 1}, polarLine{Theta: 1.1}},
		2.0: {polarLine{Theta: 1}, polarLine{Theta: 1.1}, polarLine{Theta: 2.1}},
	}

	bucketed := putLinesIntoBuckets(buckets, lines)
	assert.Len(t, bucketed, len(expected))
	for angle, expected_lines := range expected {
		if !assert.Len(t, bucketed[angle], len(expected_lines)) {
			t.FailNow()
		}

		for i, line := range bucketed[angle] {
			assert.EqualValues(t, expected_lines[i], line)
		}
	}
}
Esempio n. 14
0
func TestPutLinesIntoBuckets(t *testing.T) {
	buckets := map[float64][]angleBucket{
		0.0: {angleBucket{-0.1, 0.1}, angleBucket{math.Pi - 0.1, math.Pi + 0.1}},
		1.0: {angleBucket{0.9, 1.1}},
	}

	lines := []polarLine{
		polarLine{Theta: 0},
		polarLine{Theta: -0.1},
		polarLine{Theta: 0.1},
		polarLine{Theta: math.Pi},
		polarLine{Theta: 1.1},
		polarLine{Theta: 100},
		polarLine{Theta: -0.11},
		polarLine{Theta: 0.11},
	}

	expected := map[float64][]polarLine{
		0.0: {polarLine{Theta: 0}, polarLine{Theta: -0.1}, polarLine{Theta: 0.1}, polarLine{Theta: math.Pi}},
		1.0: {polarLine{Theta: 1.1}},
	}

	bucketed := putLinesIntoBuckets(buckets, lines)
	assert.Len(t, bucketed, len(expected))
	for angle, expected_lines := range expected {
		if !assert.Len(t, bucketed[angle], len(expected_lines)) {
			t.FailNow()
		}

		for i, line := range bucketed[angle] {
			assert.EqualValues(t, expected_lines[i], line)
		}
	}
}
Esempio n. 15
0
func TestTelegrafParseLine(t *testing.T) {

	s := Telegraf{}
	r, err := s.ParseLine("> mem,host=ubuntu available_percent=78.43483331332489,buffered=199602176i,used=1802661888i,used_percent=21.56516668667511 1469886743")
	require.NoError(t, err)

	assert.Len(t, r.Elements, 4)
	for _, line := range r.Elements {
		assert.Equal(t, line.Plugin, "telegraf.mem")

		validGauges := []string{"mem_available.percent", "mem_buffered", "mem_used", "mem_used.percent"}
		sort.Strings(validGauges)
		i := sort.SearchStrings(validGauges, line.Gauge)
		var gaugeFound = i < len(validGauges) && validGauges[i] == line.Gauge
		assert.True(t, gaugeFound, "Valid Gauge Name")

	}

	r, err = s.ParseLine("> system,host=ubuntu load1=0.11,load15=0.06,load5=0.05,n_cpus=4i,n_users=2i,uptime=7252i 1469891972000000000")
	require.NoError(t, err)
	assert.Len(t, r.Elements, 6)

	for _, line := range r.Elements {
		assert.Equal(t, line.Plugin, "telegraf.system")

		validGauges := []string{"system_load1", "system_load15", "system_load5", "system_n.cpus", "system_n.users", "system_uptime"}
		sort.Strings(validGauges)
		i := sort.SearchStrings(validGauges, line.Gauge)
		var gaugeFound = i < len(validGauges) && validGauges[i] == line.Gauge
		assert.True(t, gaugeFound, "Valid Gauge Name")

	}

}
Esempio n. 16
0
func TestRunningOutputWriteFail(t *testing.T) {
	conf := &OutputConfig{
		Filter: Filter{
			IsActive: false,
		},
	}

	m := &mockOutput{}
	m.failWrite = true
	ro := NewRunningOutput("test", m, conf, 4, 12)

	// Fill buffer to limit twice
	for _, metric := range first5 {
		ro.AddMetric(metric)
	}
	for _, metric := range next5 {
		ro.AddMetric(metric)
	}
	// no successful flush yet
	assert.Len(t, m.Metrics(), 0)

	// manual write fails
	err := ro.Write()
	require.Error(t, err)
	// no successful flush yet
	assert.Len(t, m.Metrics(), 0)

	m.failWrite = false
	err = ro.Write()
	require.NoError(t, err)

	assert.Len(t, m.Metrics(), 10)
}
Esempio n. 17
0
// verifyCacheFactoryCluster performs assertions over a ClusterInfo structure,
// based on the values and structure generated by cacheFactory.
func verifyCacheFactoryCluster(clinfo *ClusterInfo, t *testing.T) {
	assert := assert.New(t)
	assert.NotNil(clinfo.Nodes["hostname2"])
	node2 := clinfo.Nodes["hostname2"]
	assert.NotEmpty(node2.Metrics)
	assert.Len(node2.FreeContainers, 1)
	assert.NotNil(node2.FreeContainers["free_container1"])

	assert.NotNil(clinfo.Nodes["hostname3"])
	node3 := clinfo.Nodes["hostname3"]
	assert.NotEmpty(node3.Metrics)

	assert.NotNil(clinfo.Namespaces["test"])
	namespace := clinfo.Namespaces["test"]

	assert.NotNil(namespace.Pods)
	pod1_ptr := namespace.Pods["pod1"]
	require.NotNil(t, pod1_ptr)
	assert.Equal(pod1_ptr, node2.Pods["pod1"])
	assert.Len(pod1_ptr.Containers, 2)
	pod2_ptr := namespace.Pods["pod2"]
	require.NotNil(t, pod2_ptr)
	assert.Equal(pod2_ptr, node3.Pods["pod2"])
	assert.Len(pod2_ptr.Containers, 2)
}
Esempio n. 18
0
func TestReadModifiedRefs(t *testing.T) {
	client := new(ApiClient)
	client.Init()

	project := new(types.Project)
	project.SetFQName("domain", []string{"default-domain", "p1"})
	assert.NoError(t, client.Create(project))

	net := new(types.VirtualNetwork)
	net.SetFQName("project", []string{"default-domain", "p1", "n1"})
	assert.NoError(t, client.Create(net))

	vmi1 := new(types.VirtualMachineInterface)
	vmi1.SetFQName("project", []string{"default-domain", "p1", "port1"})
	vmi1.AddVirtualNetwork(net)
	assert.NoError(t, client.Create(vmi1))

	vmi2 := new(types.VirtualMachineInterface)
	vmi2.SetFQName("project", []string{"default-domain", "p1", "port2"})
	vmi2.AddVirtualNetwork(net)
	assert.NoError(t, client.Create(vmi2))

	refs, err := net.GetVirtualMachineInterfaceBackRefs()
	assert.NoError(t, err)
	assert.Len(t, refs, 2)

	assert.NoError(t, client.Delete(vmi1))
	refs, err = net.GetVirtualMachineInterfaceBackRefs()
	assert.NoError(t, err)
	assert.Len(t, refs, 1)
}
Esempio n. 19
0
func TestAppendix_B(t *testing.T) {
	var jwksrc = []byte(`{"keys":
       [
        {"kty":"RSA",
         "use":"sig",
         "kid":"1b94c",
         "n":"vrjOfz9Ccdgx5nQudyhdoR17V-IubWMeOZCwX_jj0hgAsz2J_pqYW08PLbK_PdiVGKPrqzmDIsLI7sA25VEnHU1uCLNwBuUiCO11_-7dYbsr4iJmG0Qu2j8DsVyT1azpJC_NG84Ty5KKthuCaPod7iI7w0LK9orSMhBEwwZDCxTWq4aYWAchc8t-emd9qOvWtVMDC2BXksRngh6X5bUYLy6AyHKvj-nUy1wgzjYQDwHMTplCoLtU-o-8SNnZ1tmRoGE9uJkBLdh5gFENabWnU5m1ZqZPdwS-qo-meMvVfJb6jJVWRpl2SUtCnYG2C32qvbWbjZ_jBPD5eunqsIo1vQ",
         "e":"AQAB",
         "x5c": ["MIIDQjCCAiqgAwIBAgIGATz/FuLiMA0GCSqGSIb3DQEBBQUAMGIxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDTzEPMA0GA1UEBxMGRGVudmVyMRwwGgYDVQQKExNQaW5nIElkZW50aXR5IENvcnAuMRcwFQYDVQQDEw5CcmlhbiBDYW1wYmVsbDAeFw0xMzAyMjEyMzI5MTVaFw0xODA4MTQyMjI5MTVaMGIxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDTzEPMA0GA1UEBxMGRGVudmVyMRwwGgYDVQQKExNQaW5nIElkZW50aXR5IENvcnAuMRcwFQYDVQQDEw5CcmlhbiBDYW1wYmVsbDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL64zn8/QnHYMeZ0LncoXaEde1fiLm1jHjmQsF/449IYALM9if6amFtPDy2yvz3YlRij66s5gyLCyO7ANuVRJx1NbgizcAblIgjtdf/u3WG7K+IiZhtELto/A7Fck9Ws6SQvzRvOE8uSirYbgmj6He4iO8NCyvaK0jIQRMMGQwsU1quGmFgHIXPLfnpnfajr1rVTAwtgV5LEZ4Iel+W1GC8ugMhyr4/p1MtcIM42EA8BzE6ZQqC7VPqPvEjZ2dbZkaBhPbiZAS3YeYBRDWm1p1OZtWamT3cEvqqPpnjL1XyW+oyVVkaZdklLQp2Btgt9qr21m42f4wTw+Xrp6rCKNb0CAwEAATANBgkqhkiG9w0BAQUFAAOCAQEAh8zGlfSlcI0o3rYDPBB07aXNswb4ECNIKG0CETTUxmXl9KUL+9gGlqCz5iWLOgWsnrcKcY0vXPG9J1r9AqBNTqNgHq2G03X09266X5CpOe1zFo+Owb1zxtp3PehFdfQJ610CDLEaS9V9Rqp17hCyybEpOGVwe8fnk+fbEL2Bo3UPGrpsHzUoaGpDftmWssZkhpBJKVMJyf/RuP2SmmaIzmnw9JiSlYhzo4tpzd5rFXhjRbg4zW9C+2qok+2+qDM1iJ684gPHMIY8aLWrdgQTxkumGmTqgawR+N5MDtdPTEQ0XfIBc2cJEUyMTY5MPvACWpkA6SdS4xSvdXK3IVfOWA=="]}
       ]
     }`)

	set, err := Parse(jwksrc)
	if !assert.NoError(t, err, "Parse should succeed") {
		return
	}
	if !assert.Len(t, set.Keys, 1, "There should be 1 key") {
		return
	}

	{
		key, ok := set.Keys[0].(*RsaPublicKey)
		if !assert.True(t, ok, "set.Keys[0] should be a RsaPublicKey") {
			return
		}
		if !assert.Len(t, key.X509CertChain, 1, "key.X509CertChain should be 1 cert") {
			return
		}
	}
}
Esempio n. 20
0
// The Public network subnet configuration may change.
func TestPublicNetworkSubnetChange(t *testing.T) {
	client := new(contrail_mocks.ApiClient)
	client.Init()

	config := new(Config)
	config.PublicNetwork = "default-domain:default-project:Public"
	config.PublicSubnet = "192.0.2.0/24"
	netman := NewNetworkManager(client, config)

	// No public IP addresses are assigned: expect the public network to
	// have a single subnet.
	config.PublicSubnet = "198.51.100.0/24"
	netman = NewNetworkManager(client, config)

	network := netman.GetPublicNetwork()
	refs, err := network.GetNetworkIpamRefs()
	require.NoError(t, err)
	assert.Len(t, refs, 1)
	if len(refs) > 0 {
		attr := refs[0].Attr.(types.VnSubnetsType)
		assert.Len(t, attr.IpamSubnets, 1)
		if len(attr.IpamSubnets) > 0 {
			prefix := fmt.Sprintf("%s/%d",
				attr.IpamSubnets[0].Subnet.IpPrefix,
				attr.IpamSubnets[0].Subnet.IpPrefixLen)
			assert.Equal(t, config.PublicSubnet, prefix)
		}
	}
}
Esempio n. 21
0
// If there is more than one key, removeKeyInteractively will ask which key to
// delete.  Then it will confirm whether they want to delete, and the user can
// abort at that confirmation.
func TestRemoveMultikeysAbortChoice(t *testing.T) {
	in := bytes.NewBuffer([]byte("1\nn\n"))

	key, err := trustmanager.GenerateED25519Key(rand.Reader)
	assert.NoError(t, err)

	stores := []trustmanager.KeyStore{
		trustmanager.NewKeyMemoryStore(ret),
		trustmanager.NewKeyMemoryStore(ret),
	}

	err = stores[0].AddKey(key.ID(), "root", key)
	assert.NoError(t, err)

	err = stores[1].AddKey("gun/"+key.ID(), "target", key)
	assert.NoError(t, err)

	var out bytes.Buffer

	err = removeKeyInteractively(stores, key.ID(), in, &out)
	assert.NoError(t, err) // no error to abort deleting
	text, err := ioutil.ReadAll(&out)
	assert.NoError(t, err)

	assert.Len(t, stores[0].ListKeys(), 1)
	assert.Len(t, stores[1].ListKeys(), 1)

	// It should have listed the keys, asked whether the user really wanted to
	// delete, and then aborted.
	output := string(text)
	assert.Contains(t, output, "Found the following matching keys")
	assert.Contains(t, output, "Are you sure")
	assert.Contains(t, output, "Aborting action")
}
Esempio n. 22
0
func (suite *OperationSuite) TestParseResponseComment() {
	op := parser.NewOperation(suite.parser, "test")
	err := op.ParseResponseComment("200 {simple} string")
	assert.Nil(suite.T(), err, "Can not parse response comment")
	assert.Len(suite.T(), op.ResponseMessages, 1, "Can not parse response comment")

	assert.Equal(suite.T(), op.ResponseMessages[0].Code, 200, "Can not parse response comment")
	assert.Equal(suite.T(), op.ResponseMessages[0].Message, "", "Can not parse response comment")
	assert.Equal(suite.T(), op.Type, "string", "Can not parse response comment")

	op2 := parser.NewOperation(suite.parser, "test")
	err2 := op2.ParseResponseComment("400 {simple} string     \"Order ID must be specified\"")
	assert.Nil(suite.T(), err2, "Can not parse response comment")
	assert.Len(suite.T(), op2.ResponseMessages, 1, "Can not parse response comment")

	assert.Equal(suite.T(), op2.ResponseMessages[0].Code, 400, "Can not parse response comment")
	assert.Equal(suite.T(), op2.ResponseMessages[0].Message, "Order ID must be specified", "Can not parse response comment")
	assert.Equal(suite.T(), op2.Type, "", "Can not parse response comment")

	op3 := parser.NewOperation(suite.parser, "test")
	err3 := op3.ParseResponseComment("200 {array} string ")
	assert.Nil(suite.T(), err3, "Can not parse response comment")
	assert.Len(suite.T(), op3.ResponseMessages, 1, "Can not parse response comment")

	assert.Equal(suite.T(), op3.ResponseMessages[0].Code, 200, "Can not parse response comment")
	assert.Equal(suite.T(), op3.ResponseMessages[0].Message, "", "Can not parse response comment")
	assert.Equal(suite.T(), op3.Type, "array", "Can not parse response comment")
	assert.Equal(suite.T(), op3.Items.Type, "string", "Can not parse response comment")
}
Esempio n. 23
0
func TestOTMultipleAddMultipleDimensions(t *testing.T) {
	tree, entries := constructMultiDimensionalOrderedTree(4)

	assert.Equal(t, uint64(4), tree.Len())

	result := tree.Query(constructMockInterval(dimension{0, 1}, dimension{0, 1}))
	assert.Equal(t, Entries{entries[0]}, result)

	result = tree.Query(constructMockInterval(dimension{3, 4}, dimension{3, 4}))
	assert.Equal(t, Entries{entries[3]}, result)

	result = tree.Query(constructMockInterval(dimension{0, 4}, dimension{0, 4}))
	assert.Equal(t, entries, result)

	result = tree.Query(constructMockInterval(dimension{1, 3}, dimension{1, 3}))
	assert.Equal(t, Entries{entries[1], entries[2]}, result)

	result = tree.Query(constructMockInterval(dimension{0, 2}, dimension{10, 20}))
	assert.Len(t, result, 0)

	result = tree.Query(constructMockInterval(dimension{10, 20}, dimension{0, 2}))
	assert.Len(t, result, 0)

	result = tree.Query(constructMockInterval(dimension{0, 2}, dimension{0, 1}))
	assert.Equal(t, Entries{entries[0]}, result)

	result = tree.Query(constructMockInterval(dimension{0, 1}, dimension{0, 2}))
	assert.Equal(t, Entries{entries[0]}, result)
}
func TestMultiplePriorityGetEmpty(t *testing.T) {
	q := NewPriorityQueue(1, false)
	var wg sync.WaitGroup
	wg.Add(2)
	results := make([][]Item, 2)

	go func() {
		wg.Done()
		local, _ := q.Get(1)
		results[0] = local
		wg.Done()
	}()

	go func() {
		wg.Done()
		local, _ := q.Get(1)
		results[1] = local
		wg.Done()
	}()

	wg.Wait()
	wg.Add(2)

	q.Put(mockItem(1), mockItem(3), mockItem(2))
	wg.Wait()

	if !assert.Len(t, results[0], 1) || !assert.Len(t, results[1], 1) {
		return
	}

	assert.True(
		t, (results[0][0] == mockItem(1) && results[1][0] == mockItem(2)) ||
			results[0][0] == mockItem(2) && results[1][0] == mockItem(1),
	)
}
Esempio n. 25
0
func doTestPrefixScan(t *testing.T, node Node) {
	for i := 1; i < 3; i++ {
		n := node.From(fmt.Sprintf("%d%02d", 2015, i))
		err := n.Save(&SimpleUser{ID: i, Name: "John"})
		assert.NoError(t, err)
	}

	for i := 1; i < 4; i++ {
		n := node.From(fmt.Sprintf("%d%02d", 2016, i))
		err := n.Save(&SimpleUser{ID: i, Name: "John"})
		assert.NoError(t, err)
	}

	assert.Len(t, node.PrefixScan("2015"), 2)
	assert.Len(t, node.PrefixScan("20"), 5)

	buckets2016 := node.PrefixScan("2016")
	assert.Len(t, buckets2016, 3)
	count, err := buckets2016[1].Count(&SimpleUser{})

	assert.NoError(t, err)
	assert.Equal(t, 1, count)

	assert.NoError(t, buckets2016[1].One("ID", 2, &SimpleUser{}))
}
Esempio n. 26
0
func TestTimeValueSlice(t *testing.T) {
	for idx, in := range testCasesTimeValueSlice {
		if in == nil {
			continue
		}
		out := aws.TimeValueSlice(in)
		assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
		for i := range out {
			if in[i] == nil {
				assert.Empty(t, out[i], "Unexpected value at idx %d", idx)
			} else {
				assert.Equal(t, *(in[i]), out[i], "Unexpected value at idx %d", idx)
			}
		}

		out2 := aws.TimeSlice(out)
		assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
		for i := range out2 {
			if in[i] == nil {
				assert.Empty(t, *(out2[i]), "Unexpected value at idx %d", idx)
			} else {
				assert.Equal(t, in[i], out2[i], "Unexpected value at idx %d", idx)
			}
		}
	}
}
Esempio n. 27
0
func TestGet(t *testing.T) {
	q := New(10)

	q.Put(`test`)
	result, err := q.Get(2)
	if !assert.Nil(t, err) {
		return
	}

	assert.Len(t, result, 1)
	assert.Equal(t, `test`, result[0])
	assert.Equal(t, int64(0), q.Len())

	q.Put(`1`)
	q.Put(`2`)

	result, err = q.Get(1)
	if !assert.Nil(t, err) {
		return
	}

	assert.Len(t, result, 1)
	assert.Equal(t, `1`, result[0])
	assert.Equal(t, int64(1), q.Len())

	result, err = q.Get(2)
	if !assert.Nil(t, err) {
		return
	}

	assert.Equal(t, `2`, result[0])
}
Esempio n. 28
0
func TestConversion(t *testing.T) {
	buf := make([]byte, 8)
	message.Uint64ToByteArray(buf, testId)
	id := message.ByteArrayToUint64(buf)
	assert.Equal(t, testId, id, "uint64 conversion is wrong!")

	buf = make([]byte, 4)
	message.Uint32ToByteArray(buf, testNum)
	n := message.ByteArrayToUint32(buf)
	assert.Equal(t, testNum, n, "uint32 conversion is wrong!")

	a1 := message.Uint64ArrayToByteArray(nil)
	a2 := message.Uint64ArrayToByteArray(make([]uint64, 0))
	a3 := message.Uint64ArrayToByteArray(testList)

	assert.Nil(t, a1, "Should return nil with nil as input")
	assert.Len(t, a2, 0, "Should give empty byte list")
	assert.Len(t, a3, len(testList)*8, "One element takes 8 bytes of space")

	l1 := message.ByteArrayToUint64Array(nil)
	l2 := message.ByteArrayToUint64Array(make([]byte, 7))
	l3 := message.ByteArrayToUint64Array(make([]byte, 0))
	l4 := message.ByteArrayToUint64Array(a3)

	assert.Nil(t, l1, "Should return nil with nil as input")
	assert.Nil(t, l2, "Should return nil with incorrect length")
	assert.Len(t, l3, 0, "Should give empty byte list")
	assert.Nil(t, testutils.CompareList(l4, testList), "Lists should be the same")
}
Esempio n. 29
0
func TestAddRoute(t *testing.T) {
	node1, node2 := NewNode(), NewNode()
	assert.Len(t, node1.RouteForwardingRules, 0, "Should be 0 routes")

	ccid := node1.AddControlChannel()
	node1.Tick() // run channels consuming

	tf := transport.NewTransportFactory()
	tf.ConnectNodeToNode(node1, node2)
	tr1, _ := tf.GetTransports()
	tid1 := tr1.Id

	incomingRouteId := messages.RandRouteId()
	outgoingRouteId := messages.RandRouteId()

	msg := messages.AddRouteControlMessage{
		(messages.TransportId)(0),
		tr1.Id,
		incomingRouteId,
		outgoingRouteId,
	}
	msgS := messages.Serialize(messages.MsgAddRouteControlMessage, msg)

	controlMessage := messages.InControlMessage{ccid, msgS}

	node1.InjectControlMessage(controlMessage)
	time.Sleep(1 * time.Millisecond)

	assert.Len(t, node1.RouteForwardingRules, 1, "Should be 1 routes")
	assert.Equal(t, node1.RouteForwardingRules[incomingRouteId].IncomingRoute, incomingRouteId)
	assert.Equal(t, node1.RouteForwardingRules[incomingRouteId].OutgoingRoute, outgoingRouteId)
	assert.Equal(t, node1.RouteForwardingRules[incomingRouteId].OutgoingTransport, tid1)

	fmt.Println("--------------------\n")
}
Esempio n. 30
0
func TestServiceWithNamePort(t *testing.T) {
	const (
		testService   = "testservice"
		testNamespace = "default"
	)
	ec := &fakeEtcdClient{make(map[string]string)}
	k2s := newKube2Sky(ec)

	// create service
	service := newService(testNamespace, testService, "1.2.3.4", "http1", 80)
	k2s.newService(&service)
	expectedValue := getHostPort(&service)
	assertDnsServiceEntryInEtcd(t, ec, testService, testNamespace, expectedValue)
	assertSRVEntryInEtcd(t, ec, "http1", "tcp", testService, testNamespace, 80, 1)
	assert.Len(t, ec.writes, 2)

	// update service
	newService := service
	newService.Spec.Ports[0].Name = "http2"
	k2s.updateService(&service, &newService)
	expectedValue = getHostPort(&newService)
	assertDnsServiceEntryInEtcd(t, ec, testService, testNamespace, expectedValue)
	assertSRVEntryInEtcd(t, ec, "http2", "tcp", testService, testNamespace, 80, 1)
	assert.Len(t, ec.writes, 2)

	// Delete the service
	k2s.removeService(&service)
	assert.Empty(t, ec.writes)
}