Esempio n. 1
0
func TestReadDirTrailingSlash(t *testing.T) {
	client := getClient(t)

	mkdirp(t, "/_test/fulldir2")
	mkdirp(t, "/_test/fulldir2/dir")
	touch(t, "/_test/fulldir2/1")
	touch(t, "/_test/fulldir2/2")
	touch(t, "/_test/fulldir2/3")

	res, err := client.ReadDir("/_test/fulldir2/")
	require.NoError(t, err)
	require.Equal(t, len(res), 4)

	assert.EqualValues(t, "1", res[0].Name())
	assert.False(t, res[0].IsDir())

	assert.EqualValues(t, "2", res[1].Name())
	assert.False(t, res[1].IsDir())

	assert.EqualValues(t, "3", res[2].Name())
	assert.False(t, res[2].IsDir())

	assert.EqualValues(t, "dir", res[3].Name())
	assert.True(t, res[3].IsDir())
}
Esempio n. 2
0
func TestGenerateAndSignNewTLSCert(t *testing.T) {
	tempBaseDir, err := ioutil.TempDir("", "swarm-ca-test-")
	assert.NoError(t, err)
	defer os.RemoveAll(tempBaseDir)

	paths := ca.NewConfigPaths(tempBaseDir)

	rootCA, err := ca.CreateAndWriteRootCA("rootCN", paths.RootCA)
	assert.NoError(t, err)

	_, err = ca.GenerateAndSignNewTLSCert(rootCA, "CN", "OU", "ORG", paths.Node)
	assert.NoError(t, err)

	perms, err := permbits.Stat(paths.Node.Cert)
	assert.NoError(t, err)
	assert.False(t, perms.GroupWrite())
	assert.False(t, perms.OtherWrite())
	perms, err = permbits.Stat(paths.Node.Key)
	assert.NoError(t, err)
	assert.False(t, perms.GroupRead())
	assert.False(t, perms.OtherRead())

	certBytes, err := ioutil.ReadFile(paths.Node.Cert)
	assert.NoError(t, err)
	certs, err := helpers.ParseCertificatesPEM(certBytes)
	assert.NoError(t, err)
	assert.Len(t, certs, 2)
	assert.Equal(t, "CN", certs[0].Subject.CommonName)
	assert.Equal(t, "OU", certs[0].Subject.OrganizationalUnit[0])
	assert.Equal(t, "ORG", certs[0].Subject.Organization[0])
	assert.Equal(t, "rootCN", certs[1].Subject.CommonName)
}
Esempio n. 3
0
func TestSearchService_Code(t *testing.T) {
	setup()
	defer tearDown()

	stubGet(t, "/search/code", "code_search", nil)

	searchResults, result := client.Search().Code(nil, M{
		"query": "addClass in:file language:js repo:jquery/jquery"})

	assert.False(t, result.HasError())
	assert.False(t, searchResults.IncompleteResults)
	assert.Equal(t, 7, searchResults.TotalCount)
	assert.Equal(t, 7, len(searchResults.Items))
	assert.EqualValues(t, "classes.js", searchResults.Items[0].Name)
	assert.EqualValues(t, "src/attributes/classes.js", searchResults.Items[0].Path)
	assert.EqualValues(t,
		"f9dba94f7de43d6b6b7256e05e0d17c4741a4cde", searchResults.Items[0].SHA)
	assert.EqualValues(t,
		"https://api.github.com/repositories/167174/contents/src/attributes/classes.js?ref=53aa87f3bf4284763405f3eb8affff296e55ba4f", string(searchResults.Items[0].URL))
	assert.EqualValues(t,
		"https://api.github.com/repositories/167174/git/blobs/f9dba94f7de43d6b6b7256e05e0d17c4741a4cde", searchResults.Items[0].GitURL)
	assert.EqualValues(t,
		"https://github.com/jquery/jquery/blob/53aa87f3bf4284763405f3eb8affff296e55ba4f/src/attributes/classes.js", searchResults.Items[0].HTMLURL)
	assert.Equal(t, 167174, searchResults.Items[0].Repository.ID)
	assert.EqualValues(t,
		"jquery/jquery", searchResults.Items[0].Repository.FullName)
}
Esempio n. 4
0
func TestRunAndStopGracefully(t *testing.T) {
	d1 := &mockDaemon{}
	d2 := &mockDaemon{}

	h := &Hydre{
		Timeout: 1,
		Daemons: []Service{d1, d2},
	}

	go h.Run()

	time.Sleep(100 * time.Millisecond)

	assert.True(t, d1.IsStarted())
	assert.False(t, d1.IsStopped())
	assert.False(t, d1.IsKilled())
	assert.True(t, d2.IsStarted())
	assert.False(t, d2.IsStopped())
	assert.False(t, d2.IsKilled())

	require.NotNil(t, d1.StopNotifier)
	d1.StopNotifier <- "stop daemon 1"

	time.Sleep(700 * time.Millisecond)

	assert.True(t, d1.IsStarted())
	assert.True(t, d1.IsStopped())
	assert.True(t, d1.IsKilled())
	assert.True(t, d2.IsStarted())
	assert.True(t, d2.IsStopped())
	assert.True(t, d2.IsKilled())
}
Esempio n. 5
0
func TestDefaultConfig(t *testing.T) {
	assert := assert.New(t)

	config := DefaultConfig()
	assert.False(config.SSL.Enabled)
	assert.False(config.Ldap.Enabled)
}
Esempio n. 6
0
// Ensure that the store can create a new key if it doesn't already exist.
func TestStoreCreateValue(t *testing.T) {
	s := newStore()
	// Create /foo=bar
	e, err := s.Create("/foo", false, "bar", false, Permanent)
	assert.Nil(t, err, "")
	assert.Equal(t, e.Action, "create", "")
	assert.Equal(t, e.Node.Key, "/foo", "")
	assert.False(t, e.Node.Dir, "")
	assert.Equal(t, e.Node.Value, "bar", "")
	assert.Nil(t, e.Node.Nodes, "")
	assert.Nil(t, e.Node.Expiration, "")
	assert.Equal(t, e.Node.TTL, 0, "")
	assert.Equal(t, e.Node.ModifiedIndex, uint64(1), "")

	// Create /empty=""
	e, err = s.Create("/empty", false, "", false, Permanent)
	assert.Nil(t, err, "")
	assert.Equal(t, e.Action, "create", "")
	assert.Equal(t, e.Node.Key, "/empty", "")
	assert.False(t, e.Node.Dir, "")
	assert.Equal(t, e.Node.Value, "", "")
	assert.Nil(t, e.Node.Nodes, "")
	assert.Nil(t, e.Node.Expiration, "")
	assert.Equal(t, e.Node.TTL, 0, "")
	assert.Equal(t, e.Node.ModifiedIndex, uint64(2), "")

}
Esempio n. 7
0
func TestHttpParser_splitResponse_midHeaderName(t *testing.T) {
	http := httpModForTests()
	http.parserConfig.sendHeaders = true
	http.parserConfig.sendAllHeaders = true

	data1 := "HTTP/1.1 200 OK\r\n" +
		"Date: Tue, 14 Aug 2012 22:31:45 GMT\r\n" +
		"Expires: -1\r\n" +
		"Cache-Control: private, max-age=0\r\n" +
		"Content-Type: text/html; charset=UTF-8\r\n" +
		"Content-En"
	data2 := "coding: gzip\r\n" +
		"Server: gws\r\n" +
		"Content-Length: 0\r\n" +
		"X-XSS-Protection: 1; mode=block\r\n" +
		"X-Frame-Options: SAMEORIGIN\r\n" +
		"\r\n"
	tp := newTestParser(http, data1, data2)

	_, ok, complete := tp.parse()
	assert.True(t, ok)
	assert.False(t, complete)

	message, ok, complete := tp.parse()
	assert.True(t, ok)
	assert.True(t, complete)
	assert.False(t, message.isRequest)
	assert.Equal(t, 200, int(message.statusCode))
	assert.Equal(t, "OK", string(message.statusPhrase))
	assert.True(t, isVersion(message.version, 1, 1))
	assert.Equal(t, 262, int(message.size))
	assert.Equal(t, 0, message.contentLength)
}
Esempio n. 8
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. 9
0
func TestAfterRetryRefreshCreds(t *testing.T) {
	os.Clearenv()
	credProvider := &mockCredsProvider{}

	svc := awstesting.NewClient(&aws.Config{
		Credentials: credentials.NewCredentials(credProvider),
		MaxRetries:  aws.Int(1),
	})

	svc.Handlers.Clear()
	svc.Handlers.ValidateResponse.PushBack(func(r *request.Request) {
		r.Error = awserr.New("UnknownError", "", nil)
		r.HTTPResponse = &http.Response{StatusCode: 400}
	})
	svc.Handlers.UnmarshalError.PushBack(func(r *request.Request) {
		r.Error = awserr.New("ExpiredTokenException", "", nil)
	})
	svc.Handlers.AfterRetry.PushBackNamed(corehandlers.AfterRetryHandler)

	assert.True(t, svc.Config.Credentials.IsExpired(), "Expect to start out expired")
	assert.False(t, credProvider.retrieveCalled)

	req := svc.NewRequest(&request.Operation{Name: "Operation"}, nil, nil)
	req.Send()

	assert.True(t, svc.Config.Credentials.IsExpired())
	assert.False(t, credProvider.retrieveCalled)

	_, err := svc.Config.Credentials.Get()
	assert.NoError(t, err)
	assert.True(t, credProvider.retrieveCalled)
}
Esempio n. 10
0
func TestFilter(t *testing.T) {
	assert := assert.New(t)

	str := "This is a topic string"

	filters0 := []Filter{}
	assert.True(filteredAny(str, filters0))

	filters1 := []Filter{""}
	assert.True(filteredAny(str, filters1))

	filters2 := []Filter{"This"}
	assert.True(filteredAny(str, filters2))

	filters3 := []Filter{"this is"}
	assert.True(filteredAny(str, filters3))

	filters4 := []Filter{"this is", "topic"}
	assert.True(filteredAny(str, filters4))

	filters5 := []Filter{"this is", "other string"}
	assert.True(filteredAny(str, filters5))

	filters6 := []Filter{"not"}
	assert.False(filteredAny(str, filters6))

	filters7 := []Filter{"not", "appear"}
	assert.False(filteredAny(str, filters7))
}
Esempio n. 11
0
func TestCheckLevel(t *testing.T) {

	logger := DefaultLogger()

	SetDefaultLogLevel(ERROR)
	assert.True(t, logger.CheckLevel(ERROR, nil), "Error should be valid when level set to Error")
	assert.False(t, logger.CheckLevel(WARN, nil), "Warning should not be valid when level set to Error")
	assert.False(t, logger.CheckLevel(INFO, nil), "Info should not be valid when level set to Error")
	assert.False(t, logger.CheckLevel(DEBUG, nil), "Debug should not be valid when level set to Error")
	assert.False(t, logger.CheckLevel(VERBOSE, nil), "Verbose should not be valid when level set to Error")

	SetDefaultLogLevel(WARN)
	assert.True(t, logger.CheckLevel(ERROR, nil), "Error should be valid when level set to Warn")
	assert.True(t, logger.CheckLevel(WARN, nil), "Warning should be valid when level set to Warn")
	assert.False(t, logger.CheckLevel(INFO, nil), "Info should not be valid when level set to Warn")
	assert.False(t, logger.CheckLevel(DEBUG, nil), "Debug should not be valid when level set to Warn")
	assert.False(t, logger.CheckLevel(VERBOSE, nil), "Verbose should not be valid when level set to Warn")

	SetDefaultLogLevel(INFO)
	assert.True(t, logger.CheckLevel(ERROR, nil), "Error should be valid when level set to Info")
	assert.True(t, logger.CheckLevel(WARN, nil), "Warning should be valid when level set to Info")
	assert.True(t, logger.CheckLevel(INFO, nil), "Info should be valid when level set to Info")
	assert.False(t, logger.CheckLevel(DEBUG, nil), "Debug should not be valid when level set to Info")
	assert.False(t, logger.CheckLevel(VERBOSE, nil), "Verbose should not be valid when level set to Info")

	SetDefaultLogLevel(DEBUG)
	assert.True(t, logger.CheckLevel(ERROR, nil), "Error should be valid when level set to Debug")
	assert.True(t, logger.CheckLevel(WARN, nil), "Warning should be valid when level set to Debug")
	assert.True(t, logger.CheckLevel(INFO, nil), "Info should be valid when level set to Debug")
	assert.True(t, logger.CheckLevel(DEBUG, nil), "Debug should be valid when level set to Debug")
	assert.False(t, logger.CheckLevel(VERBOSE, nil), "Verbose should not be valid when level set to Debug")

	SetDefaultLogLevel(VERBOSE)
	assert.True(t, logger.CheckLevel(VERBOSE, nil), "Verbose should be valid when level set to Verbose")
}
func TestClearHighestLowest(t *testing.T) {
	ba := newBitArray(10)

	ba.SetBit(5)
	ba.ClearBit(5)

	assert.False(t, ba.anyset)
	assert.Equal(t, uint64(0), ba.lowest)
	assert.Equal(t, uint64(0), ba.highest)

	ba.SetBit(3)
	ba.SetBit(5)
	ba.SetBit(7)

	ba.ClearBit(7)
	assert.True(t, ba.anyset)
	assert.Equal(t, uint64(5), ba.highest)
	assert.Equal(t, uint64(3), ba.lowest)

	ba.SetBit(7)
	ba.ClearBit(3)
	assert.True(t, ba.anyset)
	assert.Equal(t, uint64(5), ba.lowest)
	assert.Equal(t, uint64(7), ba.highest)

	ba.ClearBit(7)
	assert.True(t, ba.anyset)
	assert.Equal(t, uint64(5), ba.lowest)
	assert.Equal(t, uint64(5), ba.highest)

	ba.ClearBit(5)
	assert.False(t, ba.anyset)
	assert.Equal(t, uint64(0), ba.lowest)
	assert.Equal(t, uint64(0), ba.highest)
}
Esempio n. 13
0
func TestContextInvalidResponseFormat(t *testing.T) {
	ct := "application/x-yaml"
	other := "application/sgml"
	spec, api := petstore.NewAPI(t)
	ctx := NewContext(spec, api, nil)
	ctx.router = DefaultRouter(spec, ctx.api)

	request, _ := http.NewRequest("GET", "http://localhost:8080", nil)
	request.Header.Set(httpkit.HeaderAccept, ct)

	// check there's nothing there
	cached, ok := context.GetOk(request, ctxResponseFormat)
	assert.False(t, ok)
	assert.Empty(t, cached)

	// trigger the parse
	mt := ctx.ResponseFormat(request, []string{other})
	assert.Empty(t, mt)

	// check it was cached
	cached, ok = context.GetOk(request, ctxResponseFormat)
	assert.False(t, ok)
	assert.Empty(t, cached)

	// check if the cast works and fetch from cache too
	mt = ctx.ResponseFormat(request, []string{other})
	assert.Empty(t, mt)
}
Esempio n. 14
0
func TestIsHijacked(t *testing.T) {
	//t.SkipNow()
	assert.False(t, IsHijacked(nil))
	assert.False(t, IsHijacked(errors.New("Foo")))
	assert.True(t, IsHijacked(newErrorCode(ErrHijacked, "hijacked")))
	assert.True(t, IsHijacked(Hijacked))
}
Esempio n. 15
0
func TestUserHasAccess(t *testing.T) {
	f := FeatureFlag{
		Key:        "foo",
		Enabled:    false,
		Users:      []uint32{42},
		Groups:     []string{},
		Percentage: 20,
	}
	// Make sure the feature is not enabled
	assert.False(t, f.IsEnabled())

	assert.True(t, f.UserHasAccess(42))
	assert.False(t, f.UserHasAccess(1337))

	f.Users = []uint32{42, 1337}
	assert.True(t, f.UserHasAccess(1337))

	f.Enabled = true
	assert.True(t, f.UserHasAccess(222))

	f.Users = []uint32{}
	f.Percentage = 100
	f.Enabled = false
	assert.True(t, f.UserHasAccess(222))
}
Esempio n. 16
0
func TestValidateDomain(t *testing.T) {
	assert.False(t, ValidateDomainPart(strings.Repeat("a", 256)),
		"Max domain length is 255")
	assert.False(t, ValidateDomainPart(strings.Repeat("a", 64)+".com"),
		"Max label length is 63")
	assert.True(t, ValidateDomainPart(strings.Repeat("a", 63)+".com"),
		"Should allow 63 char label")

	var testTable = []struct {
		input  string
		expect bool
		msg    string
	}{
		{"", false, "Empty domain is not valid"},
		{"hostname", true, "Just a hostname is valid"},
		{"github.com", true, "Two labels should be just fine"},
		{"my-domain.com", true, "Hyphen is allowed mid-label"},
		{"_domainkey.foo.com", true, "Underscores are allowed"},
		{"bar.com.", true, "Must be able to end with a dot"},
		{"ABC.6DBS.com", true, "Mixed case is OK"},
		{"mail.123.com", true, "Number only label valid"},
		{"123.com", true, "Number only label valid"},
		{"google..com", false, "Double dot not valid"},
		{".foo.com", false, "Cannot start with a dot"},
		{"google\r.com", false, "Special chars not allowed"},
		{"foo.-bar.com", false, "Label cannot start with hyphen"},
		{"foo-.bar.com", false, "Label cannot end with hyphen"},
	}

	for _, tt := range testTable {
		if ValidateDomainPart(tt.input) != tt.expect {
			t.Errorf("Expected %v for %q: %s", tt.expect, tt.input, tt.msg)
		}
	}
}
Esempio n. 17
0
func TestGroupHasAccess(t *testing.T) {
	f := FeatureFlag{
		Key:        "foo",
		Enabled:    false,
		Users:      []uint32{42},
		Groups:     []string{"bar"},
		Percentage: 20,
	}
	// Make sure the feature is not enabled
	assert.False(t, f.IsEnabled())

	assert.True(t, f.GroupHasAccess("bar"))
	assert.False(t, f.GroupHasAccess("baz"))

	f.Groups = []string{"bar", "baz"}
	assert.True(t, f.GroupHasAccess("baz"))

	f.Enabled = true
	assert.True(t, f.GroupHasAccess("klm"))

	f.Groups = []string{}
	f.Percentage = 100
	f.Enabled = false
	assert.True(t, f.GroupHasAccess("test"))
}
Esempio n. 18
0
func doTestSectionPagesMenu(canonifyUrls bool, t *testing.T) {
	viper.Set("CanonifyURLs", canonifyUrls)
	s := setupMenuTests(t, MENU_PAGE_SECTIONS_SOURCES)

	assert.Equal(t, 2, len(s.Sections))

	firstSectionPages := s.Sections["first"]
	assert.Equal(t, 2, len(firstSectionPages))
	secondSectionPages := s.Sections["second-section"]
	assert.Equal(t, 1, len(secondSectionPages))

	nodeFirst := s.newSectionListNode("first", firstSectionPages)
	nodeSecond := s.newSectionListNode("second-section", secondSectionPages)

	firstSectionMenuEntry := findTestMenuEntryByID(s, "spm", "first")
	secondSectionMenuEntry := findTestMenuEntryByID(s, "spm", "second-section")

	assert.NotNil(t, firstSectionMenuEntry)
	assert.NotNil(t, secondSectionMenuEntry)
	assert.NotNil(t, nodeFirst)
	assert.NotNil(t, nodeSecond)

	for _, p := range firstSectionPages {
		assert.True(t, p.Page.HasMenuCurrent("spm", firstSectionMenuEntry))
		assert.False(t, p.Page.HasMenuCurrent("spm", secondSectionMenuEntry))
		assert.True(t, nodeFirst.IsMenuCurrent("spm", firstSectionMenuEntry))
		assert.False(t, nodeFirst.IsMenuCurrent("spm", secondSectionMenuEntry))
	}

	for _, p := range secondSectionPages {
		assert.False(t, p.Page.HasMenuCurrent("spm", firstSectionMenuEntry))
		assert.True(t, p.Page.HasMenuCurrent("spm", secondSectionMenuEntry))
	}
}
Esempio n. 19
0
func TestHttpParser_eatBody_connclose(t *testing.T) {
	if testing.Verbose() {
		logp.LogInit(logp.LOG_DEBUG, "", false, true, []string{"http", "httpdetailed"})
	}

	http := httpModForTests()
	http.parserConfig.sendHeaders = true
	http.parserConfig.sendAllHeaders = true

	data := []byte("HTTP/1.1 200 ok\r\n" +
		"user-agent: curl/7.35.0\r\n" +
		"host: localhost:9000\r\n" +
		"accept: */*\r\n" +
		"authorization: Company 1\r\n" +
		"connection: close\r\n" +
		"\r\n" +
		"0123456789")

	st := &stream{data: data, message: new(message)}
	ok, complete := testParseStream(http, st, 0)
	assert.True(t, ok)
	assert.False(t, complete)
	assert.Equal(t, st.bodyReceived, 10)

	ok, complete = testParseStream(http, st, 5)
	assert.True(t, ok)
	assert.False(t, complete)
	assert.Equal(t, st.bodyReceived, 15)

	ok, complete = testParseStream(http, st, 5)
	assert.True(t, ok)
	assert.False(t, complete)
	assert.Equal(t, st.bodyReceived, 20)
}
Esempio n. 20
0
func TestPagerNoPages(t *testing.T) {
	pages := createTestPages(0)
	urlFactory := func(page int) string {
		return fmt.Sprintf("page/%d/", page)
	}

	paginator, _ := newPaginator(pages, 5, urlFactory)
	paginatorPages := paginator.Pagers()

	assert.Equal(t, 1, len(paginatorPages))
	assert.Equal(t, 0, paginator.TotalNumberOfElements())
	assert.Equal(t, 5, paginator.PageSize())
	assert.Equal(t, 0, paginator.TotalPages())

	// pageOne should be nothing but the first
	pageOne := paginatorPages[0]
	assert.NotNil(t, pageOne.First())
	assert.False(t, pageOne.HasNext())
	assert.False(t, pageOne.HasPrev())
	assert.Nil(t, pageOne.Next())
	assert.Equal(t, 1, len(pageOne.Pagers()))
	assert.Equal(t, 0, len(pageOne.Pages()))
	assert.Equal(t, 0, pageOne.NumberOfElements())
	assert.Equal(t, 0, pageOne.TotalNumberOfElements())
	assert.Equal(t, 0, pageOne.TotalPages())
	assert.Equal(t, 1, pageOne.PageNumber())
	assert.Equal(t, 5, pageOne.PageSize())

}
Esempio n. 21
0
func TestHttpParser_splitResponse_midBody(t *testing.T) {
	data1 := "HTTP/1.1 200 OK\r\n" +
		"Date: Tue, 14 Aug 2012 22:31:45 GMT\r\n" +
		"Expires: -1\r\n" +
		"Cache-Control: private, max-age=0\r\n" +
		"Content-Type: text/html; charset=UTF-8\r\n" +
		"Content-Encoding: gzip\r\n" +
		"Server: gws\r\n" +
		"Content-Length: 3"
	data2 := "0\r\n" +
		"X-XSS-Protection: 1; mode=block\r\n" +
		"X-Frame-Options: SAMEORIGIN\r\n" +
		"\r\n" +
		"xxxxxxxxxx"
	data3 := "xxxxxxxxxxxxxxxxxxxx"
	tp := newTestParser(nil, data1, data2, data3)

	_, ok, complete := tp.parse()
	assert.True(t, ok)
	assert.False(t, complete)

	_, ok, complete = tp.parse()
	assert.True(t, ok)
	assert.False(t, complete)

	message, ok, complete := tp.parse()
	assert.True(t, ok)
	assert.True(t, complete)
	assert.Equal(t, 30, message.contentLength)
	assert.Equal(t, []byte(""), tp.stream.data[tp.stream.parseOffset:])
}
Esempio n. 22
0
// Ensure that the store can create a new key if it doesn't already exist.
func TestStoreCreateValue(t *testing.T) {
	s := newStore()
	// Create /foo=bar
	var eidx uint64 = 1
	e, err := s.Create("/foo", false, "bar", false, TTLOptionSet{ExpireTime: Permanent})
	assert.Nil(t, err, "")
	assert.Equal(t, e.EtcdIndex, eidx, "")
	assert.Equal(t, e.Action, "create", "")
	assert.Equal(t, e.Node.Key, "/foo", "")
	assert.False(t, e.Node.Dir, "")
	assert.Equal(t, *e.Node.Value, "bar", "")
	assert.Nil(t, e.Node.Nodes, "")
	assert.Nil(t, e.Node.Expiration, "")
	assert.Equal(t, e.Node.TTL, 0, "")
	assert.Equal(t, e.Node.ModifiedIndex, uint64(1), "")

	// Create /empty=""
	eidx = 2
	e, err = s.Create("/empty", false, "", false, TTLOptionSet{ExpireTime: Permanent})
	assert.Nil(t, err, "")
	assert.Equal(t, e.EtcdIndex, eidx, "")
	assert.Equal(t, e.Action, "create", "")
	assert.Equal(t, e.Node.Key, "/empty", "")
	assert.False(t, e.Node.Dir, "")
	assert.Equal(t, *e.Node.Value, "", "")
	assert.Nil(t, e.Node.Nodes, "")
	assert.Nil(t, e.Node.Expiration, "")
	assert.Equal(t, e.Node.TTL, 0, "")
	assert.Equal(t, e.Node.ModifiedIndex, uint64(2), "")

}
Esempio n. 23
0
func TestIndexRecordEncodeDecode(t *testing.T) {
	now := time.Now()

	unix := now.UnixNano()
	index, offset := uint64(0), int64(24)
	ir := BasicIndexRecord{unix, index, offset, 0}

	encoder := NewIndexRecordEncoder()
	decoder := NewIndexRecordDecoder()
	buffer := encoder.Encode(ir)

	record, err := decoder.Decode(buffer)
	assert.Nil(t, err)

	// time
	assert.Equal(t, ir.Time(), record.Time())

	// index
	assert.Equal(t, ir.Index(), record.Index())

	// offset
	assert.Equal(t, ir.Offset(), record.Offset())

	// ttl
	assert.Equal(t, ir.TimeToLive(), record.TimeToLive())
	assert.False(t, ir.IsExpired())
	assert.False(t, record.IsExpired())
}
Esempio n. 24
0
func TestOverwrite(t *testing.T) {
	fillDB(t)
	oldCat := testData["cat4"]

	newCat := ShortenObject{
		Slug:    oldCat.Slug,
		Owner:   "yodie",
		LongURL: "http://imgur.com/t/dogs/8IrIs", // todo find actua dog :-P
	}
	// this currently should overwrite the existing slug
	err := datastore.ShortenURL(newCat.Slug, newCat.LongURL, newCat.Owner, time.Now())
	assert.Nil(t, err, "Shorten to overwrite failed for slug:long '%s':%s, datastore type: %s, err: %s",
		newCat.Slug, newCat.LongURL, datastoreType, err)

	// ensure the old one is gone, new one exists
	l, err := datastore.GetList()
	assert.Nil(t, err, "getlist should not err out: %s", err)
	for _, u := range l {
		if u.Slug == newCat.Slug {
			assert.Equal(t, newCat.LongURL, u.LongURL)
			assert.False(t, newCat.LongURL == oldCat.LongURL, fmt.Sprintf("Old longURL persists for slug: %s", newCat.Slug))
			assert.False(t, newCat.Owner == oldCat.Owner, fmt.Sprintf("Old Owner persists for slug: %s", newCat.Slug))
		}
	}

	// Attempt to get long as well. Somewhat uneccessary, but a precaution against caching, etc
	long, err := datastore.GetLongURL(newCat.Slug)
	assert.Nil(t, err, "Failed to get record '%s' with '%s': %s", newCat.Slug, datastoreType, err)
	assert.Equal(t, newCat.LongURL, long, "Record %s on %s", long, datastoreType)
}
Esempio n. 25
0
func TestRotationNewSigMissing(t *testing.T) {
	logrus.SetLevel(logrus.DebugLevel)
	kdb := keys.NewDB()
	signer := signed.NewEd25519()
	repo := tuf.NewRepo(kdb, signer)
	remote := store.NewMemoryStore(nil, nil)
	cache := store.NewMemoryStore(nil, nil)

	// Generate initial root key and role and add to key DB
	rootKey, err := signer.Create("root", data.ED25519Key)
	assert.NoError(t, err, "Error creating root key")
	rootRole, err := data.NewRole("root", 1, []string{rootKey.ID()}, nil, nil)
	assert.NoError(t, err, "Error creating root role")

	kdb.AddKey(rootKey)
	err = kdb.AddRole(rootRole)
	assert.NoError(t, err, "Error adding root role to db")

	// Generate new key and role. These will appear in the root.json
	// but will not be added to the keyDB.
	replacementKey, err := signer.Create("root", data.ED25519Key)
	assert.NoError(t, err, "Error creating replacement root key")
	replacementRole, err := data.NewRole("root", 1, []string{replacementKey.ID()}, nil, nil)
	assert.NoError(t, err, "Error creating replacement root role")

	assert.NotEqual(t, rootKey.ID(), replacementKey.ID(), "Key IDs are the same")

	// Generate a new root with the replacement key and role
	testRoot, err := data.NewRoot(
		map[string]data.PublicKey{replacementKey.ID(): replacementKey},
		map[string]*data.RootRole{"root": &replacementRole.RootRole},
		false,
	)
	assert.NoError(t, err, "Failed to create new root")

	_, ok := testRoot.Signed.Keys[rootKey.ID()]
	assert.False(t, ok, "Old root key appeared in test root")

	// Sign testRoot with both old and new keys
	signedRoot, err := testRoot.ToSigned()
	err = signed.Sign(signer, signedRoot, rootKey)
	assert.NoError(t, err, "Failed to sign root")
	var origKeySig bool
	var replKeySig bool
	for _, sig := range signedRoot.Signatures {
		if sig.KeyID == rootKey.ID() {
			origKeySig = true
		} else if sig.KeyID == replacementKey.ID() {
			replKeySig = true
		}
	}
	assert.True(t, origKeySig, "Original root key signature not present")
	assert.False(t, replKeySig, "Replacement root key signature was present and shouldn't be")

	client := NewClient(repo, remote, kdb, cache)

	err = client.verifyRoot("root", signedRoot, 0)
	assert.Error(t, err, "Should have errored on verify as replacement signature was missing.")

}
Esempio n. 26
0
func TestRedisReadFromClosed(t *testing.T) {
	r, w := newReaderWriter()
	p := make([]byte, 10)

	r.Read(p)
	w.Write([]byte("hello"))
	w.Close()

	// this read should short circuit with EOF
	_, err := r.Read(p)
	assert.Equal(t, err, io.EOF)

	// We'll get true here because r.closed is already set
	assert.True(t, readerDone(r))

	// We should still get true here because doneID is set
	r, _ = NewReader(string(r.(*reader).channel))
	assert.True(t, readerDone(r))

	// Reader done on a regular io.Reader should return false
	// and not panic
	assert.False(t, readerDone(strings.NewReader("hello")))

	// NoContent should respond accordingly based on offset
	assert.False(t, NoContent(r, 0))
	assert.True(t, NoContent(r, 5))
}
Esempio n. 27
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))
}
Esempio n. 28
0
func TestApplicationAllTaskRunning(t *testing.T) {
	app := NewDockerApplication()

	app.Instances = nil
	app.Tasks = nil

	assert.True(t, app.AllTaskRunning())

	var cnt int
	app.Instances = &cnt

	cnt = 0
	assert.True(t, app.AllTaskRunning())

	cnt = 1
	assert.False(t, app.AllTaskRunning())

	app.Tasks = []*Task{}
	app.TasksRunning = 1
	assert.True(t, app.AllTaskRunning())

	cnt = 2
	app.TasksRunning = 1
	assert.False(t, app.AllTaskRunning())
}
Esempio n. 29
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)
}
Esempio n. 30
0
func TestCreateGenesisBlock(t *testing.T) {
	defer cleanupVisor()
	// Test as master, successful
	vc := newMasterVisorConfig(t)
	v := NewMinimalVisor(vc)
	assert.True(t, v.Config.IsMaster)
	assert.Equal(t, len(v.blockchain.Blocks), 0)
	assert.Equal(t, len(v.blockSigs.Sigs), 0)
	sb := v.CreateGenesisBlock()
	assert.NotEqual(t, sb.Block, coin.Block{})
	assert.NotEqual(t, sb.Sig, cipher.Sig{})
	assert.Equal(t, len(v.blockchain.Blocks), 1)
	assert.Equal(t, len(v.blockSigs.Sigs), 1)
	assert.Nil(t, v.blockSigs.Verify(vc.MasterKeys.Public, v.blockchain))

	// Test as not master, successful
	vc = newGenesisConfig(t)
	v = NewMinimalVisor(vc)
	assert.False(t, v.Config.IsMaster)
	assert.Equal(t, len(v.blockchain.Blocks), 0)
	assert.Equal(t, len(v.blockSigs.Sigs), 0)
	sb = v.CreateGenesisBlock()
	assert.NotEqual(t, sb.Block, coin.Block{})
	assert.NotEqual(t, sb.Sig, cipher.Sig{})
	assert.Equal(t, len(v.blockchain.Blocks), 1)
	assert.Equal(t, len(v.blockSigs.Sigs), 1)
	assert.Nil(t, v.blockSigs.Verify(vc.MasterKeys.Public, v.blockchain))
	assert.Equal(t, v.Config.GenesisSignature, sb.Sig)
	assert.Equal(t, v.blockchain.Blocks[0].Header.Time, v.Config.GenesisTimestamp)

	// Test as master, blockSigs invalid for pubkey
	vc = newMasterVisorConfig(t)
	vc.MasterKeys.Public = cipher.PubKey{}
	v = NewMinimalVisor(vc)
	assert.True(t, v.Config.IsMaster)
	assert.Equal(t, len(v.blockchain.Blocks), 0)
	assert.Equal(t, len(v.blockSigs.Sigs), 0)
	assert.Panics(t, func() { v.CreateGenesisBlock() })

	// Test as not master, blockSigs invalid for pubkey
	vc = newGenesisConfig(t)
	vc.MasterKeys.Public = cipher.PubKey{}
	v = NewMinimalVisor(vc)
	assert.False(t, v.Config.IsMaster)
	assert.Equal(t, len(v.blockchain.Blocks), 0)
	assert.Equal(t, len(v.blockSigs.Sigs), 0)
	assert.Panics(t, func() { v.CreateGenesisBlock() })

	// Test as master, signing failed
	vc = newMasterVisorConfig(t)
	vc.MasterKeys.Secret = cipher.SecKey{}
	assert.Equal(t, vc.MasterKeys.Secret, cipher.SecKey{})
	v = NewMinimalVisor(vc)
	assert.True(t, v.Config.IsMaster)
	assert.Equal(t, v.Config, vc)
	assert.Equal(t, v.Config.MasterKeys.Secret, cipher.SecKey{})
	assert.Equal(t, len(v.blockchain.Blocks), 0)
	assert.Equal(t, len(v.blockSigs.Sigs), 0)
	assert.Panics(t, func() { v.CreateGenesisBlock() })
}