Ejemplo n.º 1
0
func TestNewDispatch(t *testing.T) {
	bot := getMockBot()
	assert.Empty(t, bot.dispatch.commands, "A new bot should have no commands.")
	assert.Nil(t, bot.dispatch.defaultHandler, "Default handler should be nil.")
	assert.Empty(t, bot.commandNames, "No command names should be stored on creation.")
	assert.Empty(t, bot.patterns, "Patterns array should be empty on creation.")
}
Ejemplo n.º 2
0
func TestPager(t *testing.T) {
	pages := createTestPages(21)
	groups, _ := pages.GroupBy("Weight", "desc")

	urlFactory := func(page int) string {
		return fmt.Sprintf("page/%d/", page)
	}

	_, err := newPaginatorFromPages(pages, -1, urlFactory)
	assert.NotNil(t, err)

	_, err = newPaginatorFromPageGroups(groups, -1, urlFactory)
	assert.NotNil(t, err)

	pag, err := newPaginatorFromPages(pages, 5, urlFactory)
	assert.Nil(t, err)
	doTestPages(t, pag)
	first := pag.Pagers()[0].First()
	assert.NotEmpty(t, first.Pages())
	assert.Empty(t, first.PageGroups())

	pag, err = newPaginatorFromPageGroups(groups, 5, urlFactory)
	assert.Nil(t, err)
	doTestPages(t, pag)
	first = pag.Pagers()[0].First()
	assert.NotEmpty(t, first.PageGroups())
	assert.Empty(t, first.Pages())

}
Ejemplo n.º 3
0
// If applying a change fails due to a prefix error, it does not fall back
// on the parent.
func TestChangeTargetMetaDoesntFallbackIfPrefixError(t *testing.T) {
	repo, cs, err := testutils.EmptyRepo("docker.com/notary")
	assert.NoError(t, err)

	newKey, err := cs.Create("targets/level1", data.ED25519Key)
	assert.NoError(t, err)

	r, err := data.NewRole("targets/level1", 1, []string{newKey.ID()},
		[]string{"pathprefix"})
	assert.NoError(t, err)
	repo.UpdateDelegations(r, []data.PublicKey{newKey})

	hash := sha256.Sum256([]byte{})
	f := &data.FileMeta{
		Length: 1,
		Hashes: map[string][]byte{
			"sha256": hash[:],
		},
	}
	fjson, err := json.Marshal(f)
	assert.NoError(t, err)

	err = changeTargetMeta(repo, &changelist.TufChange{
		Actn:       changelist.ActionCreate,
		Role:       "targets/level1",
		ChangeType: "target",
		ChangePath: "notPathPrefix",
		Data:       fjson,
	})
	assert.Error(t, err)

	// no target in targets or targets/latest
	assert.Empty(t, repo.Targets[data.CanonicalTargetsRole].Signed.Targets)
	assert.Empty(t, repo.Targets["targets/level1"].Signed.Targets)
}
Ejemplo n.º 4
0
func TestGC(t *testing.T) {
	var podEvictedCount int
	var containerEvictedCount int

	cache := NewCache(time.Millisecond, time.Second)
	cache.AddCacheListener(CacheListener{
		PodEvicted: func(namespace string, name string) {
			podEvictedCount += 1
		},
		FreeContainerEvicted: func(hostname string, name string) {
			containerEvictedCount += 1
		},
	})

	var (
		pods       []source_api.Pod
		containers []source_api.Container
	)
	f := fuzz.New().NumElements(2, 10).NilChance(0)
	f.Fuzz(&pods)
	f.Fuzz(&containers)
	assert := assert.New(t)
	assert.NoError(cache.StorePods(pods))
	assert.NoError(cache.StoreContainers(containers))
	zeroTime := time.Time{}
	assert.NotEmpty(cache.GetFreeContainers(zeroTime, zeroTime))
	assert.NotEmpty(cache.GetPods(zeroTime, zeroTime))
	// Expect all data to be deleted after 2 seconds.
	time.Sleep(10 * time.Second)
	assert.Empty(cache.GetFreeContainers(zeroTime, zeroTime))
	assert.Empty(cache.GetPods(zeroTime, zeroTime))

	assert.Equal(len(pods), podEvictedCount)
	assert.Equal(len(containers), containerEvictedCount)
}
Ejemplo n.º 5
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)
			}
		}
	}
}
Ejemplo n.º 6
0
func TestNewConfigWithKeys(t *testing.T) {
	assert := assert.New(t)

	var conf Config

	conf = NewConfigWithKeys(Keys{
		AccessKey: "access",
		SecretKey: "secret",
	})
	assert.NotNil(conf.Config)
	assert.NotNil(conf.Config.Credentials)
	assert.Empty(conf.Config.Region)
	assert.Empty(conf.Config.Endpoint)

	conf = NewConfigWithKeys(Keys{
		AccessKey: "access",
		SecretKey: "secret",
		Region:    "region",
		Endpoint:  "endpoint",
	})
	assert.NotNil(conf.Config)
	assert.NotNil(conf.Config.Credentials)
	assert.Equal("region", conf.Config.Region)
	assert.Equal("endpoint", conf.Config.Endpoint)
}
Ejemplo n.º 7
0
func TestRouterBuilder(t *testing.T) {
	spec, api := petstore.NewAPI(t)

	assert.Len(t, spec.RequiredConsumes(), 3)
	assert.Len(t, spec.RequiredProduces(), 5)
	assert.Len(t, spec.OperationIDs(), 4)

	// context := NewContext(spec, api)
	builder := petAPIRouterBuilder(spec, api)
	getRecords := builder.records["GET"]
	postRecords := builder.records["POST"]
	deleteRecords := builder.records["DELETE"]

	assert.Len(t, getRecords, 2)
	assert.Len(t, postRecords, 1)
	assert.Len(t, deleteRecords, 1)

	assert.Empty(t, builder.records["PATCH"])
	assert.Empty(t, builder.records["OPTIONS"])
	assert.Empty(t, builder.records["HEAD"])
	assert.Empty(t, builder.records["PUT"])

	rec := postRecords[0]
	assert.Equal(t, rec.Key, "/pets")
	val := rec.Value.(*routeEntry)
	assert.Len(t, val.Consumers, 3)
	assert.Len(t, val.Producers, 5)
	assert.Len(t, val.Consumes, 3)
	assert.Len(t, val.Produces, 5)

	assert.Len(t, val.Parameters, 1)
}
Ejemplo n.º 8
0
func TestCommand(t *testing.T) {

	t.Parallel()

	assert := assert.New(t)

	c := Command(good1)
	res, err := c.Value()

	assert.Equal("values_test.go", res)
	assert.NoError(err)

	c = Command(bad)
	res, err = c.Value()

	assert.Empty(res)
	assert.Equal(`failed to execute "false": "" (exit status 1)`, err.Error())

	c = Command(missing)
	res, err = c.Value()

	assert.Empty(res)
	assert.Equal(`failed to execute "no_such_binary_exists": /bin/bash: no_such_binary_exists: command not found (exit status 127)`, err.Error())

}
func TestFailedRetrieveCredentials(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(400)
		encoder := json.NewEncoder(w)
		err := encoder.Encode(map[string]interface{}{
			"Code":    "Error",
			"Message": "Message",
		})

		if err != nil {
			fmt.Println("failed to write error", err)
		}
	}))

	client := endpointcreds.NewProviderClient(*unit.Session.Config, unit.Session.Handlers, server.URL)
	creds, err := client.Retrieve()

	assert.Error(t, err)
	aerr := err.(awserr.Error)

	assert.Equal(t, "CredentialsEndpointError", aerr.Code())
	assert.Equal(t, "failed to load credentials", aerr.Message())

	aerr = aerr.OrigErr().(awserr.Error)
	assert.Equal(t, "Error", aerr.Code())
	assert.Equal(t, "Message", aerr.Message())

	assert.Empty(t, creds.AccessKeyID)
	assert.Empty(t, creds.SecretAccessKey)
	assert.Empty(t, creds.SessionToken)
	assert.True(t, client.IsExpired())
}
Ejemplo n.º 10
0
func TestLocksome(t *testing.T) {
	j := setUpTest(t, "TestLocksome")
	defer tearDownTest(t, j)

	ok, msg, err := j.Lock("id", 0,
		[]interface{}{[]interface{}{"foo"}})
	if assert.NoError(t, err) {
		assert.True(t, ok)
		assert.Empty(t, msg)
	}

	locked, msg, err := j.Locksome("id", 0, []interface{}{
		[]interface{}{"foo"},
		[]interface{}{"bar"},
		[]interface{}{"baz"},
	})
	if assert.NoError(t, err) {
		assert.Empty(t, msg)
		assert.Equal(t, [][]interface{}{
			nil,
			[]interface{}{"bar"},
			[]interface{}{"baz"},
		}, locked)
	}
}
Ejemplo n.º 11
0
func TestClearSession(t *testing.T) {
	withFakeHome(t, func() {
		repo := NewConfigurationDiskRepository()
		config, err := repo.Get()
		assert.NoError(t, err)

		config.Target = "http://api.example.com"
		config.RefreshToken = "some old refresh token"
		config.AccessToken = "some old access token"
		org := cf.OrganizationFields{}
		org.Name = "my-org"
		space := cf.SpaceFields{}
		space.Name = "my-space"
		repo.Save()

		err = repo.ClearSession()
		assert.NoError(t, err)

		repo.Save()

		savedConfig, err := repo.Get()
		assert.NoError(t, err)
		assert.Equal(t, savedConfig.Target, "http://api.example.com")
		assert.Empty(t, savedConfig.AccessToken)
		assert.Empty(t, savedConfig.RefreshToken)
		assert.Equal(t, savedConfig.OrganizationFields, cf.OrganizationFields{})
		assert.Equal(t, savedConfig.SpaceFields, cf.SpaceFields{})
	})
}
Ejemplo n.º 12
0
func TestUnlockSanity(t *testing.T) {
	j := setUpTest(t, "TestUnlockSanity")
	defer tearDownTest(t, j)

	keys := []interface{}{[]interface{}{"foo"}, []interface{}{"bar"}}

	ok, msg, err := j.Lock("id", 0, keys)
	if assert.NoError(t, err) {
		assert.True(t, ok)
		assert.Empty(t, msg)
	}

	// Should not be able to unlock something a different locker locked
	ok, msg, err = j.Unlock("id2", keys)
	if assert.NoError(t, err) {
		assert.False(t, ok)
		assert.NotEmpty(t, msg)
	}

	// Should be able to read original lock
	lockid, err := j.Readlock(keys)
	if assert.NoError(t, err) {
		assert.Equal(t, []interface{}{"id", "id"}, lockid)
	}

	ok, msg, err = j.Unlock("id", keys)
	if assert.NoError(t, err) {
		assert.True(t, ok)
		assert.Empty(t, msg)
	}
}
Ejemplo n.º 13
0
func TestPushingAppWhenItDoesNotExistButRouteExists(t *testing.T) {
	domains := []cf.Domain{
		cf.Domain{Name: "foo.cf-app.com", Guid: "foo-domain-guid"},
	}
	route := cf.Route{Host: "my-new-app"}
	domainRepo := &testhelpers.FakeDomainRepository{FindByNameDomain: domains[0]}
	routeRepo := &testhelpers.FakeRouteRepository{FindByHostRoute: route}
	appRepo := &testhelpers.FakeApplicationRepository{AppByNameErr: true}
	stackRepo := &testhelpers.FakeStackRepository{}
	fakeStarter := &testhelpers.FakeAppStarter{}
	fakeStopper := &testhelpers.FakeAppStopper{}
	zipper := &testhelpers.FakeZipper{}

	fakeUI := callPush([]string{"--name", "my-new-app"}, fakeStarter, fakeStopper, zipper, appRepo, domainRepo, routeRepo, stackRepo)

	assert.Empty(t, routeRepo.CreatedRoute.Host)
	assert.Empty(t, routeRepo.CreatedRouteDomain.Guid)
	assert.Contains(t, fakeUI.Outputs[2], "my-new-app.foo.cf-app.com")
	assert.Equal(t, routeRepo.FindByHostHost, "my-new-app")

	assert.Contains(t, fakeUI.Outputs[3], "my-new-app.foo.cf-app.com")
	assert.Equal(t, routeRepo.BoundApp.Name, "my-new-app")
	assert.Equal(t, routeRepo.BoundRoute.Host, "my-new-app")
	assert.Contains(t, fakeUI.Outputs[4], "OK")
}
Ejemplo n.º 14
0
func TestCleanupEvents(t *testing.T) {
	_, server := initServer()
	notice := buildSlack(server.URL, map[string]string{"delay_in_sec": "0"})
	assert.True(t, notice.debounce)
	testEvents := []notices.Event{
		notices.Event{
			ServiceName: "testService",
			Status:      storages.DownStatus,
			Occurred:    time.Now(),
		},
		notices.Event{
			ServiceName: "testService",
			Status:      storages.UpStatus,
			Occurred:    time.Now(),
		},
	}
	assert.Empty(t, notice.cleanupEvents(testEvents))
	testEvents[0].Status = storages.UpStatus
	testEvents[1].Status = storages.DownStatus
	assert.Empty(t, notice.cleanupEvents(testEvents))
	testEvents[0].Status = storages.DownStatus
	testEvents[1].Status = storages.DownStatus
	assert.NotEmpty(t, notice.cleanupEvents(testEvents))
	testEvents[0].Status = storages.UpStatus
	testEvents[1].Status = storages.UpStatus
	assert.NotEmpty(t, notice.cleanupEvents(testEvents))
}
Ejemplo n.º 15
0
func TestSetupSettingsClearDb(t *testing.T) {
	clearDb()
	defer clearDb()
	var err error
	db, err = OpenDatabase(testDbPath)
	assert.Nil(t, err)
	defer db.Close()
	eventSettings, _ = db.GetEventSettings()

	db.CreateTeam(new(Team))
	db.CreateMatch(&Match{Type: "qualification"})
	db.CreateMatchResult(new(MatchResult))
	db.CreateRanking(new(Ranking))
	db.CreateAllianceTeam(new(AllianceTeam))
	recorder := postHttpResponse("/setup/db/clear", "")
	assert.Equal(t, 302, recorder.Code)

	teams, _ := db.GetAllTeams()
	assert.NotEmpty(t, teams)
	matches, _ := db.GetMatchesByType("qualification")
	assert.Empty(t, matches)
	rankings, _ := db.GetAllRankings()
	assert.Empty(t, rankings)
	db.CalculateRankings()
	assert.Empty(t, rankings)
	alliances, _ := db.GetAllAlliances()
	assert.Empty(t, alliances)
}
Ejemplo n.º 16
0
func TestPushingAppWhenItDoesNotExistButRouteExists(t *testing.T) {
	deps := getPushDependencies()

	domain := cf.Domain{}
	domain.Name = "foo.cf-app.com"
	domain.Guid = "foo-domain-guid"
	domain.Shared = true

	route := cf.Route{}
	route.Guid = "my-route-guid"
	route.Host = "my-new-app"
	route.Domain = domain.DomainFields

	deps.domainRepo.ListSharedDomainsDomains = []cf.Domain{domain}

	deps.routeRepo.FindByHostAndDomainRoute = route
	deps.appRepo.ReadNotFound = true

	ui := callPush(t, []string{"my-new-app"}, deps)

	assert.Empty(t, deps.routeRepo.CreatedHost)
	assert.Empty(t, deps.routeRepo.CreatedDomainGuid)
	assert.Equal(t, deps.routeRepo.FindByHostAndDomainHost, "my-new-app")
	assert.Equal(t, deps.routeRepo.BoundAppGuid, "my-new-app-guid")
	assert.Equal(t, deps.routeRepo.BoundRouteGuid, "my-route-guid")

	testassert.SliceContains(t, ui.Outputs, testassert.Lines{
		{"Using", "my-new-app.foo.cf-app.com"},
		{"Binding", "my-new-app.foo.cf-app.com"},
		{"OK"},
	})
}
Ejemplo n.º 17
0
func TestUpdateAgent(t *testing.T) {
	pluginInput := createStubPluginInput()
	pluginInput.TargetVersion = ""
	context := createStubInstanceContext()
	manifest := createStubManifest(pluginInput, context, true, true)
	config := contracts.Configuration{}
	plugin := &Plugin{}

	testCases := []fakeUpdateManager{
		{
			generateUpdateCmdResult: "-updater -message id value",
			generateUpdateCmdError:  nil,
			downloadManifestResult:  manifest,
			downloadManifestError:   nil,
			downloadUpdaterResult:   "updater",
			downloadUpdaterError:    nil,
			validateUpdateResult:    false,
			validateUpdateError:     nil,
		},
	}

	pluginInput.TargetVersion = ""
	mockCancelFlag := new(task.MockCancelFlag)
	util := fakeUtility{}

	for _, manager := range testCases {
		out := updateAgent(plugin, config, logger, &manager, &util, pluginInput, mockCancelFlag, "", "", time.Now())
		assert.Empty(t, out.Stderr)
		assert.Empty(t, out.Errors)
	}
}
Ejemplo n.º 18
0
func TestPassesAllowedAllOrigins(t *testing.T) {
	router := newTestRouter(Config{
		AllowAllOrigins:  true,
		AllowMethods:     []string{" Patch ", "get", "post", "POST"},
		AllowHeaders:     []string{"Content-type", "  testheader "},
		ExposeHeaders:    []string{"Data2", "x-User2"},
		AllowCredentials: false,
		MaxAge:           10 * time.Hour,
	})

	// no CORS request, origin == ""
	w := performRequest(router, "GET", "")
	assert.Equal(t, w.Body.String(), "get")
	assert.Empty(t, w.Header().Get("Access-Control-Allow-Origin"))
	assert.Empty(t, w.Header().Get("Access-Control-Allow-Credentials"))
	assert.Empty(t, w.Header().Get("Access-Control-Expose-Headers"))

	// allowed CORS request
	w = performRequest(router, "POST", "example.com")
	assert.Equal(t, w.Body.String(), "post")
	assert.Equal(t, w.Header().Get("Access-Control-Allow-Origin"), "*")
	assert.Equal(t, w.Header().Get("Access-Control-Expose-Headers"), "Data2,X-User2")
	assert.Empty(t, w.Header().Get("Access-Control-Allow-Credentials"))

	// allowed CORS prefligh request
	w = performRequest(router, "OPTIONS", "https://facebook.com")
	assert.Equal(t, w.Code, 200)
	assert.Equal(t, w.Header().Get("Access-Control-Allow-Origin"), "*")
	assert.Equal(t, w.Header().Get("Access-Control-Allow-Methods"), "PATCH,GET,POST")
	assert.Equal(t, w.Header().Get("Access-Control-Allow-Headers"), "Content-Type,Testheader")
	assert.Equal(t, w.Header().Get("Access-Control-Max-Age"), "36000")
	assert.Empty(t, w.Header().Get("Access-Control-Allow-Credentials"))
}
Ejemplo n.º 19
0
func TestBitFlush(t *testing.T) {
	var err error
	buf := new(bytes.Buffer)
	w := newBitWriter(buf)

	// Empty flush
	err = w.Flush()
	assert.Nil(t, err)
	assert.Empty(t, buf.Bytes())

	// Flush with one 0 bit
	buf.Reset()
	w.WriteBitString("0")
	assert.Empty(t, buf.Bytes())
	err = w.Flush()
	assert.Nil(t, err)
	assert.Equal(t, []byte{0x00}, buf.Bytes())

	// Flush with 2 bytes
	buf.Reset()
	w.WriteBitString("01100101010")
	assert.Equal(t, []byte{0x65}, buf.Bytes())
	err = w.Flush()
	assert.Nil(t, err)
	assert.Equal(t, []byte{0x65, 0x40}, buf.Bytes())
	// Test double flush
	err = w.Flush()
	assert.Nil(t, err)
	assert.Equal(t, []byte{0x65, 0x40}, buf.Bytes())
}
Ejemplo n.º 20
0
func TestBoltDatabase_FindNames(t *testing.T) {
	db := NewBoltDatabase("test9.db")
	defer db.Release()
	defer os.Remove("test9.db")

	config := BasketConfig{Capacity: 5}
	for i := 0; i < 35; i++ {
		db.Create(fmt.Sprintf("test%v", i), config)
	}

	res1 := db.FindNames("test2", 20, 0)
	assert.False(t, res1.HasMore, "no more names are expected")
	assert.Len(t, res1.Names, 11, "wrong number of found names")
	for _, name := range res1.Names {
		assert.Contains(t, name, "test2", "invalid name among search results")
	}

	res2 := db.FindNames("test1", 5, 0)
	assert.True(t, res2.HasMore, "more names are expected")
	assert.Len(t, res2.Names, 5, "wrong number of found names")

	// Corner cases
	assert.Len(t, db.FindNames("test1", 5, 10).Names, 1, "wrong number of returned names")
	assert.Empty(t, db.FindNames("test2", 5, 20).Names, "names in this page are not expected")
	assert.False(t, db.FindNames("test3", 5, 6).HasMore, "no more names are expected")
	assert.False(t, db.FindNames("abc", 5, 0).HasMore, "no more names are expected")
	assert.Empty(t, db.FindNames("xyz", 5, 0).Names, "names are not expected")
}
Ejemplo n.º 21
0
func TestExtraEurekacheSetExpire(t *testing.T) {
	assert := assert.New(t)
	val := "value"

	e := New()
	m := memorycache.NewCacheTTL(1)
	e.SetCacheSources([]Cache{m})
	e.SetExpire("key", val, 100)

	var result string
	var ok bool

	ok = m.Get("nokey", &result)
	assert.False(ok)
	assert.Empty(result)

	result = ""
	ok = e.Get("key", &result)
	assert.True(ok)
	assert.Equal(val, result)

	result = ""
	time.Sleep(100 * time.Millisecond)
	ok = e.Get("key", &result)
	assert.False(ok)
	assert.Empty(result)
}
Ejemplo n.º 22
0
func TestFetchWithoutChecksums(t *testing.T) {
	if !canTestS3() {
		return
	}
	download := getS3DownloadObject(t)
	if download == nil {
		return
	}
	download.CalculateMd5 = false
	download.CalculateSha256 = false
	download.Fetch()
	defer os.Remove(download.LocalPath)

	assert.Empty(t, download.ErrorMessage)
	if download.Response == nil {
		assert.FailNow(t, "Response object is nil")
	}

	assert.Equal(t, testFileETag, *download.Response.ETag)
	assert.Equal(t, int64(testFileSize), *download.Response.ContentLength)
	assert.Equal(t, int64(testFileSize), download.BytesCopied)

	fileStat, err := os.Stat(download.LocalPath)
	if err != nil {
		assert.FailNow(t, "Download file '%s' does not exist", download.LocalPath)
	}
	assert.Equal(t, int64(testFileSize), fileStat.Size())

	assert.Empty(t, download.Md5Digest)
	assert.Empty(t, download.Sha256Digest)
}
Ejemplo n.º 23
0
func TestGetIPErrors(t *testing.T) {
	var tests = []struct {
		stdOut   string
		err      error
		finalErr error
	}{
		{`VMState="poweroff"`, nil, errors.New("Host is not running")},
		{"", errors.New("Unable to get state"), errors.New("Unable to get state")},
	}

	for _, expected := range tests {
		driver := newTestDriver("default")
		driver.VBoxManager = &VBoxManagerMock{
			args:   "showvminfo default --machinereadable",
			stdOut: expected.stdOut,
			err:    expected.err,
		}

		ip, err := driver.GetIP()

		assert.Empty(t, ip)
		assert.Equal(t, err, expected.finalErr)

		url, err := driver.GetURL()

		assert.Empty(t, url)
		assert.Equal(t, err, expected.finalErr)
	}
}
Ejemplo n.º 24
0
func TestFask(t *testing.T) {
	question := "question"
	expectedQuestion := "question: "

	answer := "answer\n"
	expectedAnswer := "answer"

	w := new(bytes.Buffer)
	r := bytes.NewBufferString(answer)

	a, err := Fask(question, w, r)
	assert.Nil(t, err)
	assert.Equal(t, expectedQuestion, w.String())
	assert.Equal(t, expectedAnswer, a)

	// Error while reading answer
	a, err = Fask(question, ioutil.Discard, new(bytes.Buffer))
	assert.Empty(t, a)
	assert.Error(t, err)

	// Error while writing question
	brokenWriter := new(WriterMock)
	brokenWriter.On("Write", []byte(expectedQuestion)).Return(0, io.EOF)
	a, err = Fask(question, brokenWriter, r)
	assert.Empty(t, a)
	assert.Error(t, err)
}
Ejemplo n.º 25
0
func TestClearTokens(t *testing.T) {
	org := cf.OrganizationFields{}
	org.Name = "my-org"
	space := cf.SpaceFields{}
	space.Name = "my-space"

	repo := NewConfigurationDiskRepository()
	config := repo.loadDefaultConfig(t)
	defer repo.restoreConfig(t)

	config.Target = "http://api.example.com"
	config.RefreshToken = "some old refresh token"
	config.AccessToken = "some old access token"
	config.OrganizationFields = org
	config.SpaceFields = space
	repo.Save()

	err := repo.ClearTokens()
	assert.NoError(t, err)

	repo.Save()

	savedConfig, err := repo.Get()
	assert.NoError(t, err)
	assert.Equal(t, savedConfig.Target, "http://api.example.com")
	assert.Empty(t, savedConfig.AccessToken)
	assert.Empty(t, savedConfig.RefreshToken)
	assert.Equal(t, savedConfig.OrganizationFields, org)
	assert.Equal(t, savedConfig.SpaceFields, space)
}
Ejemplo n.º 26
0
func TestVirtualBagRead_ChecksumOptions(t *testing.T) {
	tempDir, bagPath, err := testhelper.UntarTestBag("example.edu.tagsample_good.tar")
	if err != nil {
		assert.Fail(t, err.Error())
	}
	if tempDir != "" {
		defer os.RemoveAll(tempDir)
	}
	files := []string{"bagit.txt", "bag-info.txt", "aptrust-info.txt"}
	vbag := models.NewVirtualBag(bagPath, files, true, false)
	assert.NotNil(t, vbag)
	obj, _ := vbag.Read()

	// Should calculate md5 only
	for _, gf := range obj.GenericFiles {
		assert.NotEmpty(t, gf.IngestMd5)
		assert.Empty(t, gf.IngestSha256)
	}

	vbag = models.NewVirtualBag(bagPath, files, false, true)
	assert.NotNil(t, vbag)
	obj, _ = vbag.Read()

	// Should calculate sha256 only
	for _, gf := range obj.GenericFiles {
		assert.Empty(t, gf.IngestMd5)
		assert.NotEmpty(t, gf.IngestSha256)
	}

}
Ejemplo n.º 27
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)
}
Ejemplo n.º 28
0
func TestEntriesDiff(t *testing.T) {
	entry1 := &Entry{Host: "1.1.1.1", Port: "1111"}
	entry2 := &Entry{Host: "2.2.2.2", Port: "2222"}
	entry3 := &Entry{Host: "3.3.3.3", Port: "3333"}
	entries := Entries{entry1, entry2}

	// No diff
	added, removed := entries.Diff(Entries{entry2, entry1})
	assert.Empty(t, added)
	assert.Empty(t, removed)

	// Add
	added, removed = entries.Diff(Entries{entry2, entry3, entry1})
	assert.Len(t, added, 1)
	assert.True(t, added.Contains(entry3))
	assert.Empty(t, removed)

	// Remove
	added, removed = entries.Diff(Entries{entry2})
	assert.Empty(t, added)
	assert.Len(t, removed, 1)
	assert.True(t, removed.Contains(entry1))

	// Add and remove
	added, removed = entries.Diff(Entries{entry1, entry3})
	assert.Len(t, added, 1)
	assert.True(t, added.Contains(entry3))
	assert.Len(t, removed, 1)
	assert.True(t, removed.Contains(entry2))
}
Ejemplo n.º 29
0
// TestContextParamsGet tests that a parameter can be parsed from the URL.
func TestRouteParamsByName(t *testing.T) {
	name := ""
	lastName := ""
	wild := ""
	router := New()
	router.GET("/test/:name/:last_name/*wild", func(c *Context) {
		name = c.Params.ByName("name")
		lastName = c.Params.ByName("last_name")
		var ok bool
		wild, ok = c.Params.Get("wild")

		assert.True(t, ok)
		assert.Equal(t, name, c.Param("name"))
		assert.Equal(t, name, c.Param("name"))
		assert.Equal(t, lastName, c.Param("last_name"))

		assert.Empty(t, c.Param("wtf"))
		assert.Empty(t, c.Params.ByName("wtf"))

		wtf, ok := c.Params.Get("wtf")
		assert.Empty(t, wtf)
		assert.False(t, ok)
	})

	w := performRequest(router, "GET", "/test/john/smith/is/super/great")

	assert.Equal(t, w.Code, 200)
	assert.Equal(t, name, "john")
	assert.Equal(t, lastName, "smith")
	assert.Equal(t, wild, "/is/super/great")
}
Ejemplo n.º 30
0
func TestConsumerDelay(t *testing.T) {
	assert := assert.New(t)
	FlushQueue()
	// Instantiation
	consumer, err := Consumer(dqConfig, rConfig)
	assert.Empty(err)
	assert.NotEmpty(consumer)
	defer consumer.Close()
	queue := "jobq" + RandomKey()
	// Add delay job
	eta := time.Now().Add(5 * time.Second)
	body := RandomKey()
	job, err := consumer.AddJob(queue, body, eta, nil)
	assert.Empty(err)
	assert.NotEmpty(job)
	assert.NotEmpty(job.ID)
	assert.Equal(job.Body, body)
	// Setup the processor
	p := &DummyProcessor{
		Bodies: make([]string, 0, 1),
	}
	consumer.Register(queue, p)
	// Kick off processing
	go consumer.Process(queue)
	time.Sleep(2 * time.Second)
	assert.True(consumer.IsProcessing())
	// Check delay behavior
	time.Sleep(time.Second)
	assert.Equal(len(p.Bodies), 0)
	time.Sleep(2 * time.Second)
	assert.Equal(len(p.Bodies), 1)
	assert.Equal(p.Bodies[0], body+"dummy")
}