Ejemplo n.º 1
1
func TestNodeCertificateRenewalsDoNotRequireToken(t *testing.T) {
	tc := testutils.NewTestCA(t)
	defer tc.Stop()

	csr, _, err := ca.GenerateNewCSR()
	assert.NoError(t, err)

	role := api.NodeRoleManager
	issueRequest := &api.IssueNodeCertificateRequest{CSR: csr, Role: role}
	issueResponse, err := tc.NodeCAClients[2].IssueNodeCertificate(context.Background(), issueRequest)
	assert.NoError(t, err)
	assert.NotNil(t, issueResponse.NodeID)
	assert.Equal(t, api.NodeMembershipAccepted, issueResponse.NodeMembership)

	statusRequest := &api.NodeCertificateStatusRequest{NodeID: issueResponse.NodeID}
	statusResponse, err := tc.NodeCAClients[2].NodeCertificateStatus(context.Background(), statusRequest)
	assert.NoError(t, err)
	assert.Equal(t, api.IssuanceStateIssued, statusResponse.Status.State)
	assert.NotNil(t, statusResponse.Certificate.Certificate)
	assert.Equal(t, role, statusResponse.Certificate.Role)

	role = api.NodeRoleWorker
	issueRequest = &api.IssueNodeCertificateRequest{CSR: csr, Role: role}
	issueResponse, err = tc.NodeCAClients[1].IssueNodeCertificate(context.Background(), issueRequest)
	require.NoError(t, err)
	assert.NotNil(t, issueResponse.NodeID)
	assert.Equal(t, api.NodeMembershipAccepted, issueResponse.NodeMembership)

	statusRequest = &api.NodeCertificateStatusRequest{NodeID: issueResponse.NodeID}
	statusResponse, err = tc.NodeCAClients[2].NodeCertificateStatus(context.Background(), statusRequest)
	require.NoError(t, err)
	assert.Equal(t, api.IssuanceStateIssued, statusResponse.Status.State)
	assert.NotNil(t, statusResponse.Certificate.Certificate)
	assert.Equal(t, role, statusResponse.Certificate.Role)
}
Ejemplo n.º 2
0
func TestLayerUpdate(t *testing.T) {
	Open(&config.DatabaseConfig{Type: "memstore"})
	defer Close()

	l1 := &Layer{ID: "l1", OS: "os1", InstalledPackagesNodes: []string{"p1", "p2"}, RemovedPackagesNodes: []string{"p3", "p4"}, EngineVersion: 1}
	if assert.Nil(t, InsertLayer(l1)) {
		// Do not update layer content if the engine versions are equals
		l1b := &Layer{ID: "l1", OS: "os2", InstalledPackagesNodes: []string{"p1"}, RemovedPackagesNodes: []string{""}, EngineVersion: 1}
		if assert.Nil(t, InsertLayer(l1b)) {
			fl1b, err := FindOneLayerByID(l1.ID, FieldLayerAll)
			if assert.Nil(t, err) && assert.NotNil(t, fl1b) {
				assert.True(t, layerEqual(l1, fl1b), "layer contents are not equal, expected %v, have %s", l1, fl1b)
			}
		}

		// Update the layer content with new data and a higher engine version
		l1c := &Layer{ID: "l1", OS: "os2", InstalledPackagesNodes: []string{"p1", "p5"}, RemovedPackagesNodes: []string{"p6", "p7"}, EngineVersion: 2}
		if assert.Nil(t, InsertLayer(l1c)) {
			fl1c, err := FindOneLayerByID(l1c.ID, FieldLayerAll)
			if assert.Nil(t, err) && assert.NotNil(t, fl1c) {
				assert.True(t, layerEqual(l1c, fl1c), "layer contents are not equal, expected %v, have %s", l1c, fl1c)
			}
		}
	}
}
Ejemplo n.º 3
0
func testAtomicPutCreate(t *testing.T, kv store.Store) {
	// Use a key in a new directory to ensure Stores will create directories
	// that don't yet exist.
	key := "testAtomicPutCreate/create"
	value := []byte("putcreate")

	// AtomicPut the key, previous = nil indicates create.
	success, _, err := kv.AtomicPut(key, value, nil, nil)
	assert.NoError(t, err)
	assert.True(t, success)

	// Get should return the value and an incremented index
	pair, err := kv.Get(key)
	assert.NoError(t, err)
	if assert.NotNil(t, pair) {
		assert.NotNil(t, pair.Value)
	}
	assert.Equal(t, pair.Value, value)

	// Attempting to create again should fail.
	success, _, err = kv.AtomicPut(key, value, nil, nil)
	assert.Error(t, err)
	assert.False(t, success)

	// This CAS should succeed, since it has the value from Get()
	success, _, err = kv.AtomicPut(key, []byte("PUTCREATE"), pair, nil)
	assert.NoError(t, err)
	assert.True(t, success)
}
Ejemplo n.º 4
0
func (suite *IntegrationMigrateSuite) TestMigrationStateStorageAndRetrieval() {
	transform, err := NewConvert(testdata.ConvertDestination1, false, false, NewNullLogger())
	assert.Nil(suite.T(), err)

	err = transform.ConvertDirectory(testdata.ConvertSource1)
	assert.Nil(suite.T(), err)

	up := NewUp(testdata.ConvertDestination1, suite.Target)
	err = up.Migrate()
	assert.Nil(suite.T(), err)

	state, err := suite.Target.GetStatus()
	assert.Nil(suite.T(), err)
	assert.NotNil(suite.T(), state.Migrations)
	assert.Equal(suite.T(), up.Migrations.Len(), state.Migrations.Len())

	first, err := state.Migrations.First()
	assert.Nil(suite.T(), err)
	var leaf ConfigLeaf
	for _, entry := range first.Content.Entries {
		if entry.Path == "/default/alice" {
			leaf = entry
		}
	}
	assert.NotNil(suite.T(), leaf)
}
Ejemplo n.º 5
0
func TestOnDisconnect(t *testing.T) {
	gnet.EraseMessages()
	d := newDefaultDaemon()
	c := gnetConnection(addr)
	var mirror uint32 = 100

	// Not blacklistable
	reason := gnet.DisconnectWriteFailed
	setupTestOnDisconnect(d, c, mirror)
	assert.NotPanics(t, func() { d.onGnetDisconnect(c, reason) })
	// Should not be in blacklist
	assert.Equal(t, len(d.Peers.Peers.Blacklist), 0)
	// Should no longer be in OutgoingConnections
	assert.Equal(t, len(d.OutgoingConnections), 0)
	// Should no longer be in d.ExpectingIntroductions
	assert.Equal(t, len(d.ExpectingIntroductions), 0)
	// Should be removed from the mirror, and the mirror dict for this ip
	// should be removed
	assert.Equal(t, len(d.mirrorConnections), 0)
	assert.Equal(t, len(d.ConnectionMirrors), 0)

	// Blacklistable
	reason = DisconnectIntroductionTimeout
	setupTestOnDisconnect(d, c, mirror)
	assert.NotPanics(t, func() { d.onGnetDisconnect(c, reason) })
	assert.Equal(t, len(d.Peers.Peers.Blacklist), 1)
	assert.NotNil(t, d.Peers.Peers.Blacklist[addr])
	// Should be in blacklist
	assert.Equal(t, len(d.Peers.Peers.Blacklist), 1)
	assert.NotNil(t, d.Peers.Peers.Blacklist[addr])
	// Should no longer be in OutgoingConnections
	assert.Equal(t, len(d.OutgoingConnections), 0)
	// Should no longer be in d.ExpectingIntroductions
	assert.Equal(t, len(d.ExpectingIntroductions), 0)
	// Should be removed from the mirror, and the mirror dict for this ip
	// should be removed
	assert.Equal(t, len(d.mirrorConnections), 0)
	assert.Equal(t, len(d.ConnectionMirrors), 0)
	// Cleanup
	delete(d.Peers.Peers.Blacklist, addr)

	// d.mirrorConnections should retain a submap if there are other ports
	// inside
	reason = gnet.DisconnectWriteFailed
	setupTestOnDisconnect(d, c, mirror)
	d.mirrorConnections[mirror][strings.Split(addrb, ":")[0]] = addrPort
	assert.NotPanics(t, func() { d.onGnetDisconnect(c, reason) })
	// Should not be in blacklist
	assert.Equal(t, len(d.Peers.Peers.Blacklist), 0)
	// Should no longer be in OutgoingConnections
	assert.Equal(t, len(d.OutgoingConnections), 0)
	// Should no longer be in d.ExpectingIntroductions
	assert.Equal(t, len(d.ExpectingIntroductions), 0)
	// Should be removed from the mirror, and the mirror dict for this ip
	// should be removed
	assert.Equal(t, len(d.mirrorConnections), 1)
	assert.Equal(t, len(d.mirrorConnections[mirror]), 1)
	assert.Equal(t, len(d.ConnectionMirrors), 0)
	shutdown(d)
}
Ejemplo n.º 6
0
func TestIsSameFile(t *testing.T) {
	absPath, err := filepath.Abs("../tests/files/")

	assert.NotNil(t, absPath)
	assert.Nil(t, err)

	fileInfo1, err := os.Stat(absPath + "/logs/test.log")
	fileInfo2, err := os.Stat(absPath + "/logs/system.log")

	assert.Nil(t, err)
	assert.NotNil(t, fileInfo1)
	assert.NotNil(t, fileInfo2)

	file1 := &File{
		FileInfo: fileInfo1,
	}

	file2 := &File{
		FileInfo: fileInfo2,
	}

	file3 := &File{
		FileInfo: fileInfo2,
	}

	assert.False(t, file1.IsSameFile(file2))
	assert.False(t, file2.IsSameFile(file1))

	assert.True(t, file1.IsSameFile(file1))
	assert.True(t, file2.IsSameFile(file2))

	assert.True(t, file3.IsSameFile(file2))
	assert.True(t, file2.IsSameFile(file3))
}
Ejemplo n.º 7
0
func TestGetAllUdp(t *testing.T) {
	p := newProtocols()
	udp := p.GetAllUdp()
	assert.Nil(t, udp[1])
	assert.NotNil(t, udp[2])
	assert.NotNil(t, udp[3])
}
Ejemplo n.º 8
0
func TestGetAll(t *testing.T) {
	p := newProtocols()
	all := p.GetAll()
	assert.NotNil(t, all[1])
	assert.NotNil(t, all[2])
	assert.NotNil(t, all[3])
}
Ejemplo n.º 9
0
func TestRPCCreationOfDiffInstanceDiffCatalog(t *testing.T) {
	rep := createMockupReplication()
	close(rep.(*mockupReplication).syncChan) //Make sure no deadlock occur

	r := newInMemoryRegistry(nil, rep)

	catalog, err := r.GetCatalog(auth.NamespaceFrom("ns1"))
	assert.NoError(t, err)
	assert.NotNil(t, catalog)
	assert.NotEmpty(t, catalog)

	instance1 := newServiceInstance("Calc", "192.168.0.1", 9080)
	var err2 error
	instance1, err2 = catalog.Register(instance1)
	assert.NoError(t, err2)
	assert.NotNil(t, instance1)

	otherCatalog, err1 := r.GetCatalog(auth.NamespaceFrom("ns1"))
	assert.NoError(t, err1)
	assert.NotNil(t, otherCatalog)
	assert.NotEmpty(t, otherCatalog)
	assert.Equal(t, otherCatalog, catalog)

	instance2 := newServiceInstance("Calc", "192.168.0.2", 9082)
	var err3 error
	instance2, err3 = otherCatalog.Register(instance2)
	assert.NoError(t, err3)
	assert.NotNil(t, instance2)

	instances, err4 := catalog.List("Calc", protocolPredicate)
	assert.NoError(t, err4)
	assert.Len(t, instances, 2)
	assertContainsInstance(t, instances, instance1)
	assertContainsInstance(t, instances, instance2)
}
Ejemplo n.º 10
0
// Ensure that the store can delete a directory if recursive is specified.
func TestStoreDeleteDiretory(t *testing.T) {
	s := newStore()
	// create directory /foo
	s.Create("/foo", true, "", false, Permanent)
	// delete /foo with dir = true and recursive = false
	// this should succeed, since the directory is empty
	e, err := s.Delete("/foo", true, false)
	assert.Nil(t, err, "")
	assert.Equal(t, e.Action, "delete", "")
	// check pervNode
	assert.NotNil(t, e.PrevNode, "")
	assert.Equal(t, e.PrevNode.Key, "/foo", "")
	assert.Equal(t, e.PrevNode.Dir, true, "")

	// create directory /foo and directory /foo/bar
	s.Create("/foo/bar", true, "", false, Permanent)
	// delete /foo with dir = true and recursive = false
	// this should fail, since the directory is not empty
	_, err = s.Delete("/foo", true, false)
	assert.NotNil(t, err, "")

	// delete /foo with dir=false and recursive = true
	// this should succeed, since recursive implies dir=true
	// and recursively delete should be able to delete all
	// items under the given directory
	e, err = s.Delete("/foo", false, true)
	assert.Nil(t, err, "")
	assert.Equal(t, e.Action, "delete", "")

}
Ejemplo n.º 11
0
func TestGetters(t *testing.T) {
	assert.False(t, IsAuthenticatedFromContext(context.Background()))
	_, err := PoliciesFromContext(context.Background())
	assert.NotNil(t, err)
	_, err = SubjectFromContext(context.Background())
	assert.NotNil(t, err)
	_, err = TokenFromContext(context.Background())
	assert.NotNil(t, err)

	ctx := context.Background()
	claims := hjwt.ClaimsCarrier{"sub": "peter"}
	token := &jwt.Token{Valid: true}
	policies := []policy.Policy{}
	ctx = NewContextFromAuthValues(ctx, claims, token, policies)

	assert.True(t, IsAuthenticatedFromContext(ctx))
	policiesContext, err := PoliciesFromContext(ctx)
	assert.Nil(t, err)
	assert.Equal(t, policies, policiesContext)

	subjectContext, err := SubjectFromContext(ctx)
	assert.Nil(t, err)
	assert.Equal(t, claims.GetSubject(), subjectContext)

	tokenContext, err := TokenFromContext(ctx)
	assert.Nil(t, err)
	assert.Equal(t, token, tokenContext)
}
Ejemplo n.º 12
0
func TestValidate(t *testing.T) {
	f := FeatureFlag{
		Key:        "foo",
		Enabled:    false,
		Users:      []uint32{},
		Groups:     []string{},
		Percentage: 101,
	}

	err := f.Validate()
	assert.NotNil(t, err)
	assert.Equal(t, "Percentage must be between 0 and 100", err.Error())

	f.Percentage = 50
	f.Key = "ab"
	err = f.Validate()
	assert.NotNil(t, err)
	assert.Equal(t, "Feature key must be between 3 and 50 characters", err.Error())

	f.Key = "a&6"
	err = f.Validate()
	assert.NotNil(t, err)
	assert.Equal(t, "Feature key must only contain digits, lowercase letters and underscores", err.Error())

	f.Key = "foo"
	assert.Nil(t, f.Validate())
}
Ejemplo n.º 13
0
func TestIssueNodeCertificateBrokenCA(t *testing.T) {
	if !testutils.External {
		t.Skip("test only applicable for external CA configuration")
	}

	tc := testutils.NewTestCA(t)
	defer tc.Stop()

	csr, _, err := ca.GenerateNewCSR()
	assert.NoError(t, err)

	tc.ExternalSigningServer.Flake()

	go func() {
		time.Sleep(250 * time.Millisecond)
		tc.ExternalSigningServer.Deflake()
	}()
	issueRequest := &api.IssueNodeCertificateRequest{CSR: csr, Token: tc.WorkerToken}
	issueResponse, err := tc.NodeCAClients[0].IssueNodeCertificate(context.Background(), issueRequest)
	assert.NoError(t, err)
	assert.NotNil(t, issueResponse.NodeID)
	assert.Equal(t, api.NodeMembershipAccepted, issueResponse.NodeMembership)

	statusRequest := &api.NodeCertificateStatusRequest{NodeID: issueResponse.NodeID}
	statusResponse, err := tc.NodeCAClients[0].NodeCertificateStatus(context.Background(), statusRequest)
	require.NoError(t, err)
	assert.Equal(t, api.IssuanceStateIssued, statusResponse.Status.State)
	assert.NotNil(t, statusResponse.Certificate.Certificate)
	assert.Equal(t, api.NodeRoleWorker, statusResponse.Certificate.Role)

}
Ejemplo n.º 14
0
func assertOperation(t *testing.T, op *spec.Operation, id, summary, description string, tags []string) {
	assert.NotNil(t, op)
	assert.Equal(t, summary, op.Summary)
	assert.Equal(t, description, op.Description)
	assert.Equal(t, id, op.ID)
	assert.EqualValues(t, tags, op.Tags)
	assert.EqualValues(t, []string{"application/json", "application/x-protobuf"}, op.Consumes)
	assert.EqualValues(t, []string{"application/json", "application/x-protobuf"}, op.Produces)
	assert.EqualValues(t, []string{"http", "https", "ws", "wss"}, op.Schemes)
	assert.Len(t, op.Security, 2)
	_, ok := op.Security[0]["api_key"]
	assert.True(t, ok)

	vv, ok := op.Security[1]["oauth"]
	assert.True(t, ok)
	assert.EqualValues(t, []string{"read", "write"}, vv)

	assert.NotNil(t, op.Responses.Default)
	assert.Equal(t, "#/responses/genericError", op.Responses.Default.Ref.String())

	rsp, ok := op.Responses.StatusCodeResponses[200]
	assert.True(t, ok)
	assert.Equal(t, "#/responses/someResponse", rsp.Ref.String())
	rsp, ok = op.Responses.StatusCodeResponses[422]
	assert.True(t, ok)
	assert.Equal(t, "#/responses/validationError", rsp.Ref.String())
}
Ejemplo n.º 15
0
func TestMetadataCreateAllDropAllError(t *testing.T) {
	accounts := Table(
		"account",
		Column("id", Type("UUID")),
		PrimaryKey("id"),
	)
	engine, err := New("postgres", postgresDsn)
	metadata := MetaData()

	engine.Dialect().SetEscaping(true)
	assert.Nil(t, err)
	metadata.AddTable(accounts)
	err = metadata.CreateAll(engine)
	assert.Nil(t, err)

	engineNew, err := New("postgres", postgresDsn)
	engineNew.Dialect().SetEscaping(true)
	metadataNew := MetaData()
	assert.Nil(t, err)
	metadataNew.AddTable(accounts)
	err = metadataNew.CreateAll(engineNew)
	assert.NotNil(t, err)

	err = metadataNew.DropAll(engine)
	assert.Nil(t, err)

	err = metadataNew.DropAll(engineNew)
	assert.NotNil(t, err)
}
Ejemplo n.º 16
0
func TestMergeFlagValueNewList(t *testing.T) {
	config, _ := ucfg.NewFrom(map[string]interface{}{
		"c.0.b":  true,
		"c.0.b2": true,
		"c.0.i":  42,
		"c.0.c":  3.14,
		"c.0.s":  "wrong",
	}, ucfg.PathSep("."))

	cliConfig, err := parseTestFlags("-D c.0.s=string -D c.0.f=3.14 -D c.1.b=true")
	assert.NoError(t, err)

	err = config.Merge(cliConfig, ucfg.PathSep("."))
	assert.NoError(t, err)

	// validate
	sub, err := config.Child("c", 0)
	assert.NoError(t, err)
	assert.NotNil(t, sub)
	if sub != nil {
		checkFields(t, sub)
	}

	sub, err = config.Child("c", 1)
	assert.NoError(t, err)
	assert.NotNil(t, sub)
	if sub == nil {
		return
	}

	b, err := sub.Bool("b", -1)
	assert.NoError(t, err)
	assert.True(t, b)
}
Ejemplo n.º 17
0
func TestWrite(t *testing.T) {
	const s string = "All work and no play makes Jack a dull boy"
	dir, err := ioutil.TempDir("", "testrotlog")
	if err != nil {
		fmt.Println("Failed to create test dir in TestIfFileExists, skipping...")
		return
	}
	r, err := InitRotlog(dir+"/test", 43, 3)
	assert.Nil(t, err)
	assert.NotNil(t, r)
	assert.Equal(t, dir+"/test", r.filename)
	assert.Equal(t, true, r.fileNumberExists(0))
	assert.NotNil(t, r.current)

	for i := 0; i < 10; i++ {
		n, err := r.Write([]byte(s))
		if err != nil {
			t.Errorf(err.Error())
		}
		assert.Equal(t, len(s)+1, n)
		//on lit le fichier, pour voir
		content, err := ioutil.ReadFile(r.filename)
		if err != nil {
			t.Errorf(err.Error())
		}
		assert.Equal(t, s+"\n", string(content))
		if i < 3 {
			assert.Equal(t, true, r.fileNumberExists(i))
		} else {
			assert.Equal(t, false, r.fileNumberExists(i))
		}
	}
	os.RemoveAll(dir)
}
Ejemplo n.º 18
0
func TestNewHydre(t *testing.T) {
	h, err := NewHydre("test/good-conf.yml")
	assert.Nil(t, err)
	assert.Equal(t, 10, h.Timeout)
	assert.Len(t, h.Daemons, 2)
	assert.Contains(t, h.Daemons, &Daemon{
		Name:        "daemon1",
		Command:     []string{"start", "daemon1"},
		StopCommand: []string{"stop", "daemon1"},
		PidFile:     "path/to/pidfile",
		LogFiles:    []string{"1.log", "2.log"},
	})
	assert.Contains(t, h.Daemons, &Daemon{
		Name:    "daemon2",
		Command: []string{"start", "daemon2"},
	})

	h, err = NewHydre("test/bad-conf.yml")
	assert.NotNil(t, err)
	assert.Nil(t, h)

	h, err = NewHydre("does-not-exist.yml")
	assert.NotNil(t, err)
	assert.Nil(t, h)
}
Ejemplo n.º 19
0
func TestGetAllTcp(t *testing.T) {
	p := newProtocols()
	tcp := p.GetAllTcp()
	assert.NotNil(t, tcp[1])
	assert.Nil(t, tcp[2])
	assert.NotNil(t, tcp[3])
}
Ejemplo n.º 20
0
func (suite *OauthTestSuite) TestFindClientByClientID() {
	var (
		client *Client
		err    error
	)

	// When we try to find a client with a bogus client ID
	client, err = suite.service.FindClientByClientID("bogus")

	// Client object should be nil
	assert.Nil(suite.T(), client)

	// Correct error should be returned
	if assert.NotNil(suite.T(), err) {
		assert.Equal(suite.T(), ErrClientNotFound, err)
	}

	// When we try to find a client with a valid cliend ID
	client, err = suite.service.FindClientByClientID("test_client_1")

	// Error should be nil
	assert.Nil(suite.T(), err)

	// Correct client object should be returned
	if assert.NotNil(suite.T(), client) {
		assert.Equal(suite.T(), "test_client_1", client.Key)
	}
}
Ejemplo n.º 21
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)
}
Ejemplo n.º 22
0
func TestDecodeHex(t *testing.T) {
	hexData := []byte("0123456789abcdef")
	targetBytes := make([]byte, 8)
	err := DecodeHex(targetBytes, hexData)
	require.Nil(t, err)
	assert.Equal(t, []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}, targetBytes)

	hexData = []byte("0123 4567\t89Ab\ncDef")
	targetBytes = make([]byte, 8)
	err = DecodeHex(targetBytes, hexData)
	require.Nil(t, err)
	assert.Equal(t, []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}, targetBytes)

	// Destination too long
	hexData = []byte("0123 4567\t89ab\ncdef")
	targetBytes = make([]byte, 10)
	err = DecodeHex(targetBytes, hexData)
	assert.NotNil(t, err)
	assert.Equal(t, make([]byte, 10), targetBytes)

	// Destination too short
	hexData = []byte("0123 4567\t89ab\ncdef")
	targetBytes = make([]byte, 7)
	err = DecodeHex(targetBytes, hexData)
	assert.NotNil(t, err)
	assert.Equal(t, make([]byte, 7), targetBytes)
}
Ejemplo n.º 23
0
func TestSimpleEvent(t *testing.T) {
	transp := newMockTransport()
	client := newClientTestDriver(newLumberjackClient(transp, 5*time.Second))

	event := common.MapStr{"name": "me", "line": 10}
	client.Publish([]common.MapStr{event})

	// receive window message
	buf := streambuf.New(nil)
	win, err := recvMessage(buf, transp)
	assert.Nil(t, err)

	// receive data message
	msg, err := recvMessage(buf, transp)
	assert.Nil(t, err)

	// send ack
	sendAck(transp, 1)

	// stop test driver
	transp.Close()
	client.Stop()

	// validate
	assert.NotNil(t, win)
	assert.NotNil(t, msg)
	assert.Equal(t, 1, len(msg.events))
	msg = msg.events[0]
	assert.Equal(t, "me", msg.doc["name"])
	assert.Equal(t, 10.0, msg.doc["line"])
}
Ejemplo n.º 24
0
func init() {
	Describe("Testing with Ginkgo", func() {
		It("lookup host with a valid host", func() {
			res := createResolver()
			ip, err := res.LookupHost([]string{"8.8.8.8"}, "google.com.")

			assert.NoError(GinkgoT(), err)
			assert.NotNil(GinkgoT(), net.ParseIP(ip))
		})
		It("lookup host with an i p", func() {

			res := createResolver()
			ip, err := res.LookupHost([]string{"8.8.8.8"}, "74.125.239.101")

			assert.NoError(GinkgoT(), err)
			assert.Equal(GinkgoT(), ip, "74.125.239.101")
		})
		It("lookup host with multiple dns servers", func() {

			res := createResolver()
			ip, err := res.LookupHost([]string{"127.0.0.127", "8.8.8.8"}, "google.com.")

			assert.NoError(GinkgoT(), err)
			assert.NotNil(GinkgoT(), net.ParseIP(ip))
		})
		It("lookup host an unknown host", func() {

			res := createResolver()
			_, err := res.LookupHost([]string{"8.8.8.8"}, "google.com.local.")

			assert.Error(GinkgoT(), err)
		})
	})
}
Ejemplo n.º 25
0
func TestMakePrivateConnections(t *testing.T) {
	d := newDefaultDaemon()
	defer shutdown(d)
	d.Pool.Config.DialTimeout = time.Hour
	addr := "192.168.1.198:43071"
	addrb := "192.168.1.197:43072"
	// Two privates
	p, err := d.Peers.Peers.AddPeer(addr)
	assert.Nil(t, err)
	p.Private = true
	p, err = d.Peers.Peers.AddPeer(addrb)
	assert.Nil(t, err)
	p.Private = true
	// Not private
	p, err = d.Peers.Peers.AddPeer(addrc)
	assert.Nil(t, err)
	p.Private = false

	// Disabled
	d.Config.DisableOutgoingConnections = true
	d.makePrivateConnections()
	assert.Equal(t, len(d.pendingConnections), 0)

	// Enabled
	d.Config.DisableOutgoingConnections = false
	d.makePrivateConnections()
	assert.Equal(t, len(d.pendingConnections), 2)
	assert.NotNil(t, d.pendingConnections[addr])
	assert.NotNil(t, d.pendingConnections[addrb])
	assert.Nil(t, d.pendingConnections[addrc])
}
Ejemplo n.º 26
0
func TestValidClaimsContext(t *testing.T) {
	userClaims := ClaimsContext{"user-id": "123456", "custom-time": 1453066866, "custom-time-f": 1631.083, "custom-date": time.Date(2016, time.January, 17, 19, 00, 00, 00, &time.Location{})}
	ctx, err := NewClaimsContext("fosite/auth", "Peter", "*****@*****.**", "", time.Now().Add(time.Hour), time.Now(), time.Now(), userClaims)
	assert.Nil(t, err)

	assert.Equal(t, "fosite/auth", ctx.GetIssuer())
	assert.NotEqual(t, "fosite/token", ctx.GetIssuer())
	assert.Equal(t, "Peter", ctx.GetSubject())
	assert.NotEqual(t, "Alex", ctx.GetSubject())
	assert.Equal(t, "*****@*****.**", ctx.GetAudience())
	assert.NotEqual(t, "*****@*****.**", ctx.GetAudience())

	assert.Equal(t, time.Now().Day(), ctx.GetNotBefore().Day())
	assert.Equal(t, time.Now().Day(), ctx.GetIssuedAt().Day())
	assert.Equal(t, time.Now().Add(time.Hour).Day(), ctx.GetExpiresAt().Day())

	assert.Equal(t, time.Now().Add(time.Hour).Day(), ctx.GetAsTime("exp").Day())
	assert.Equal(t, time.Date(2016, time.January, 17, 19, 00, 00, 00, &time.Location{}), ctx.GetAsTime("custom-date"))
	assert.NotNil(t, ctx.GetAsTime("custom-time"))
	assert.NotNil(t, ctx.GetAsTime("custom-time-f"))

	str, err := ctx.String()
	assert.NotNil(t, str)
	assert.Nil(t, err)

	assert.Empty(t, ctx.GetAsString("doesnotexist"))
	assert.Equal(t, time.Time{}, ctx.GetAsTime("doesnotexist"))
	stringRep, err := ctx.String()
	assert.Nil(t, err)
	assert.NotEmpty(t, stringRep)
}
Ejemplo n.º 27
0
func testAtomicPut(t *testing.T, kv store.Store) {
	key := "testAtomicPut"
	value := []byte("world")

	// Put the key
	err := kv.Put(key, value, nil)
	assert.NoError(t, err)

	// Get should return the value and an incremented index
	pair, err := kv.Get(key)
	assert.NoError(t, err)
	if assert.NotNil(t, pair) {
		assert.NotNil(t, pair.Value)
	}
	assert.Equal(t, pair.Value, value)
	assert.NotEqual(t, pair.LastIndex, 0)

	// This CAS should fail: previous exists.
	success, _, err := kv.AtomicPut(key, []byte("WORLD"), nil, nil)
	assert.Error(t, err)
	assert.False(t, success)

	// This CAS should succeed
	success, _, err = kv.AtomicPut(key, []byte("WORLD"), pair, nil)
	assert.NoError(t, err)
	assert.True(t, success)

	// This CAS should fail, key exists.
	pair.LastIndex = 6744
	success, _, err = kv.AtomicPut(key, []byte("WORLDWORLD"), pair, nil)
	assert.Error(t, err)
	assert.False(t, success)
}
Ejemplo n.º 28
0
func (exec *testExecutor) Registered(driver ExecutorDriver, execinfo *mesos.ExecutorInfo, fwinfo *mesos.FrameworkInfo, slaveinfo *mesos.SlaveInfo) {
	log.Infoln("Exec.Registered() called.")
	assert.NotNil(exec.t, execinfo)
	assert.NotNil(exec.t, fwinfo)
	assert.NotNil(exec.t, slaveinfo)
	exec.ch <- true
}
func TestParseFederationReplicaSetReference(t *testing.T) {
	successPrefs := []string{
		`{"rebalance": true,
		  "clusters": {
		    "k8s-1": {"minReplicas": 10, "maxReplicas": 20, "weight": 2},
		    "*": {"weight": 1}
		}}`,
	}
	failedPrefes := []string{
		`{`, // bad json
	}

	rs := newReplicaSetWithReplicas("rs-1", 100)
	accessor, _ := meta.Accessor(rs)
	anno := accessor.GetAnnotations()
	if anno == nil {
		anno = make(map[string]string)
		accessor.SetAnnotations(anno)
	}
	for _, prefString := range successPrefs {
		anno[FedReplicaSetPreferencesAnnotation] = prefString
		pref, err := parseFederationReplicaSetReference(rs)
		assert.NotNil(t, pref)
		assert.Nil(t, err)
	}
	for _, prefString := range failedPrefes {
		anno[FedReplicaSetPreferencesAnnotation] = prefString
		pref, err := parseFederationReplicaSetReference(rs)
		assert.Nil(t, pref)
		assert.NotNil(t, err)
	}
}
Ejemplo n.º 30
0
func TestCustomTransferBothConfig(t *testing.T) {
	path := "/path/to/binary"
	args := "-c 1 --whatever --yeah"
	cfg := config.NewFrom(config.Values{
		Git: map[string]string{
			"lfs.customtransfer.testboth.path":       path,
			"lfs.customtransfer.testboth.args":       args,
			"lfs.customtransfer.testboth.concurrent": "yes",
			"lfs.customtransfer.testboth.direction":  "both",
		},
	})

	m := ConfigureManifest(NewManifest(), cfg)

	d := m.NewDownloadAdapter("testboth")
	assert.NotNil(t, d, "Download adapter should be present")
	cd, _ := d.(*customAdapter)
	assert.NotNil(t, cd, "Download adapter should be customAdapter")
	assert.Equal(t, cd.path, path, "Path should be correct")
	assert.Equal(t, cd.args, args, "args should be correct")
	assert.Equal(t, cd.concurrent, true, "concurrent should be set")

	u := m.NewUploadAdapter("testboth")
	assert.NotNil(t, u, "Upload adapter should be present")
	cu, _ := u.(*customAdapter)
	assert.NotNil(t, cu, "Upload adapter should be customAdapter")
	assert.Equal(t, cu.path, path, "Path should be correct")
	assert.Equal(t, cu.args, args, "args should be correct")
	assert.Equal(t, cu.concurrent, true, "concurrent should be set")
}