Golang Strings示例

说明

golang strings示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: sort

示例#1
文件: purell.go 项目: rogpeppe/purell

func sortQuery(u *url.URL) {
	q := u.Query()
	if len(q) == 0 {
		return
	}
	arKeys := make([]string, len(q))
	i := 0
	for k, _ := range q {
		arKeys[i] = k
		i++
	}
	sort.Strings(arKeys)
	buf := new(bytes.Buffer)
	for _, k := range arKeys {
		sort.Strings(q[k])
		for _, v := range q[k] {
			if buf.Len() > 0 {
				buf.WriteRune('&')
			}
			buf.WriteString(fmt.Sprintf("%s=%s", k, url.QueryEscape(v)))
		}
	}

	// Rebuild the raw query string
	u.RawQuery = buf.String()
}

示例#2
文件: sort.go 项目: bcampbell/bleve

func (s *SortField) filterTermsByMode(terms []string) string {
	if len(terms) == 1 || (len(terms) > 1 && s.Mode == SortFieldDefault) {
		return terms[0]
	} else if len(terms) > 1 {
		switch s.Mode {
		case SortFieldMin:
			sort.Strings(terms)
			return terms[0]
		case SortFieldMax:
			sort.Strings(terms)
			return terms[len(terms)-1]
		}
	}

	// handle missing terms
	if s.Missing == SortFieldMissingLast {
		if s.Desc {
			return LowTerm
		}
		return HighTerm
	}
	if s.Desc {
		return HighTerm
	}
	return LowTerm
}

示例#3
文件: resource.go 项目: paultyng/terraform

// Equal checks the equality of two resource configs.
func (c *ResourceConfig) Equal(c2 *ResourceConfig) bool {
	// If either are nil, then they're only equal if they're both nil
	if c == nil || c2 == nil {
		return c == c2
	}

	// Sort the computed keys so they're deterministic
	sort.Strings(c.ComputedKeys)
	sort.Strings(c2.ComputedKeys)

	// Two resource configs if their exported properties are equal.
	// We don't compare "raw" because it is never used again after
	// initialization and for all intents and purposes they are equal
	// if the exported properties are equal.
	check := [][2]interface{}{
		{c.ComputedKeys, c2.ComputedKeys},
		{c.Raw, c2.Raw},
		{c.Config, c2.Config},
	}
	for _, pair := range check {
		if !reflect.DeepEqual(pair[0], pair[1]) {
			return false
		}
	}

	return true
}

示例#4
文件: fake.go 项目: ericcapricorn/deis

func (f *FakeRegistry) UnitStates() ([]*unit.UnitState, error) {
	f.Lock()
	defer f.Unlock()

	states := make([]*unit.UnitState, 0)

	// Sort by unit name, then by machineID
	sUnitNames := make([]string, 0)
	for name := range f.jobStates {
		sUnitNames = append(sUnitNames, name)
	}
	sort.Strings(sUnitNames)

	for _, name := range sUnitNames {
		sMIDs := make([]string, 0)
		for machineID := range f.jobStates[name] {
			sMIDs = append(sMIDs, machineID)
		}
		sort.Strings(sMIDs)
		for _, mID := range sMIDs {
			states = append(states, f.jobStates[name][mID])
		}
	}
	return states, nil
}

示例#5
文件: config_string.go 项目: RezaDKhan/terraform

func modulesStr(ms []*Module) string {
	result := ""
	order := make([]int, 0, len(ms))
	ks := make([]string, 0, len(ms))
	mapping := make(map[string]int)
	for i, m := range ms {
		k := m.Id()
		ks = append(ks, k)
		mapping[k] = i
	}
	sort.Strings(ks)
	for _, k := range ks {
		order = append(order, mapping[k])
	}

	for _, i := range order {
		m := ms[i]
		result += fmt.Sprintf("%s\n", m.Id())

		ks := make([]string, 0, len(m.RawConfig.Raw))
		for k, _ := range m.RawConfig.Raw {
			ks = append(ks, k)
		}
		sort.Strings(ks)

		result += fmt.Sprintf("  source = %s\n", m.Source)

		for _, k := range ks {
			result += fmt.Sprintf("  %s\n", k)
		}
	}

	return strings.TrimSpace(result)
}

示例#6
文件: handler.go 项目: waterytowers/global-hack-day-3

func (r Request) String() string {
	queryString := ""
	if len(r.QueryParams) > 0 {
		keys := make([]string, 0, len(r.QueryParams))
		queryParts := make([]string, 0, len(r.QueryParams))
		for k := range r.QueryParams {
			keys = append(keys, k)
		}
		sort.Strings(keys)
		for _, k := range keys {
			for _, val := range r.QueryParams[k] {
				queryParts = append(queryParts, fmt.Sprintf("%s=%s", k, url.QueryEscape(val)))
			}
		}
		queryString = "?" + strings.Join(queryParts, "&")
	}
	var headers []string
	if len(r.Headers) > 0 {
		var headerKeys []string
		for k := range r.Headers {
			headerKeys = append(headerKeys, k)
		}
		sort.Strings(headerKeys)

		for _, k := range headerKeys {
			for _, val := range r.Headers[k] {
				headers = append(headers, fmt.Sprintf("%s:%s", k, val))
			}
		}

	}
	return fmt.Sprintf("%s %s%s\n%s\n%s", r.Method, r.Route, queryString, headers, r.Body)
}

示例#7
文件: repo.go 项目: dholbach/snappy

func (e *BadInterfacesError) Error() string {
	inverted := make(map[string][]string)
	for name, reason := range e.issues {
		inverted[reason] = append(inverted[reason], name)
	}
	var buf bytes.Buffer
	fmt.Fprintf(&buf, "snap %q has bad plugs or slots: ", e.snap)
	reasons := make([]string, 0, len(inverted))
	for reason := range inverted {
		reasons = append(reasons, reason)
	}
	sort.Strings(reasons)
	for _, reason := range reasons {
		names := inverted[reason]
		sort.Strings(names)
		for i, name := range names {
			if i > 0 {
				buf.WriteString(", ")
			}
			buf.WriteString(name)
		}
		fmt.Fprintf(&buf, " (%s); ", reason)
	}
	return strings.TrimSuffix(buf.String(), "; ")
}

示例#8
文件: syncmap_test.go 项目: xjtdy888/syncmap

func Test_IterKeys(t *testing.T) {
	loop := 100
	expectedKeys := make([]string, loop)

	m := New()
	for i := 0; i < loop; i++ {
		key := strconv.Itoa(i)
		expectedKeys[i] = key
		m.Set(key, i)
	}

	keys := make([]string, 0)
	for key := range m.IterKeys() {
		keys = append(keys, key)
	}

	if len(keys) != len(expectedKeys) {
		t.Error("IterKeys doesn't loop the right times")
	}

	sort.Strings(keys)
	sort.Strings(expectedKeys)

	for i, v := range keys {
		if v != expectedKeys[i] {
			t.Error("IterKeys doesn't loop over the right keys")
		}
	}
}

示例#9
文件: mfs_test.go 项目: ccsblueboy/go-ipfs

func assertDirAtPath(root *Directory, pth string, children []string) error {
	fsn, err := DirLookup(root, pth)
	if err != nil {
		return err
	}

	dir, ok := fsn.(*Directory)
	if !ok {
		return fmt.Errorf("%s was not a directory", pth)
	}

	listing, err := dir.List()
	if err != nil {
		return err
	}

	var names []string
	for _, d := range listing {
		names = append(names, d.Name)
	}

	sort.Strings(children)
	sort.Strings(names)
	if !compStrArrs(children, names) {
		return errors.New("directories children did not match!")
	}

	return nil
}

示例#10
文件: scan_test.go 项目: rnoldo/meddler

func TestColumnsQuoted(t *testing.T) {
	once.Do(setup)

	p := new(Person)
	names, err := ColumnsQuoted(p, true)
	if err != nil {
		t.Errorf("Error getting ColumnsQuoted: %v", err)
	}

	lst := []string{"id", "name", "Email", "Age", "opened", "closed", "updated", "height"}
	sort.Strings(lst)
	for i, orig := range lst {
		lst[i] = Default.quoted(orig)
	}
	expected := strings.Join(lst, ",")

	if len(names) != len(expected) {
		t.Errorf("Length mismatch: expected %d, got %d", len(expected), len(names))
	}

	fields := strings.Split(names, ",")
	sort.Strings(fields)
	names = strings.Join(fields, ",")

	if expected != names {
		t.Errorf("Mismatch: expected %s, got %s", expected, names)
	}
}

示例#11
文件: rs_state.go 项目: intercom/dvara

func sameIMMembers(a *isMasterResponse, b *isMasterResponse) bool {
	if a == nil && b == nil {
		return true
	}
	if a == nil {
		a = &emptyIsMasterResponse
	}
	if b == nil {
		b = &emptyIsMasterResponse
	}
	l := len(a.Hosts)
	if l != len(b.Hosts) {
		return false
	}
	aHosts := make([]string, 0, l+1)
	bHosts := make([]string, 0, l+1)
	for i := 0; i < l; i++ {
		aHosts = append(aHosts, a.Hosts[i])
		bHosts = append(bHosts, b.Hosts[i])
	}
	sort.Strings(aHosts)
	sort.Strings(bHosts)
	aHosts = append(aHosts, a.Primary)
	bHosts = append(bHosts, b.Primary)
	for i := range aHosts {
		if aHosts[i] != bHosts[i] {
			return false
		}
	}
	return true
}

示例#12
文件: rs_state.go 项目: intercom/dvara

func sameRSMembers(a *replSetGetStatusResponse, b *replSetGetStatusResponse) bool {
	if (a == nil || len(a.Members) == 0) && (b == nil || len(b.Members) == 0) {
		return true
	}
	if a == nil || b == nil {
		return false
	}
	l := len(a.Members)
	if l != len(b.Members) {
		return false
	}
	aMembers := make([]string, 0, l)
	bMembers := make([]string, 0, l)
	for i := 0; i < l; i++ {
		aM := a.Members[i]
		aMembers = append(aMembers, fmt.Sprintf("%s:%s", aM.Name, aM.State))
		bM := b.Members[i]
		bMembers = append(bMembers, fmt.Sprintf("%s:%s", bM.Name, bM.State))
	}
	sort.Strings(aMembers)
	sort.Strings(bMembers)
	for i := 0; i < l; i++ {
		if aMembers[i] != bMembers[i] {
			return false
		}
	}
	return true
}

示例#13
文件: typeinfo.go 项目: Berkaroad/util

// 获取类型的类型信息
func GetTypeInfo(typ reflect.Type) TypeInfo {
	realType := FromPtrType(typ)
	switch realType.Kind() {
	case reflect.Struct:
		typeMemberNameList := make([]string, realType.NumField())
		typeMemberInfoList := make([]TypeMemberInfo, realType.NumField())
		for i := 0; i < len(typeMemberNameList); i++ {
			typeMemberNameList[i] = realType.Field(i).Name
		}
		sort.Strings(typeMemberNameList)
		for i, typeMemberName := range typeMemberNameList {
			typeMember, _ := realType.FieldByName(typeMemberName)
			typeMemberInfoList[i] = TypeMemberInfo{TypeMemberName: typeMember.Name, TypeMemberTypeName: typeMember.Type.String()}
		}
		return TypeInfo{TypeName: realType.Name(), TypeMemberInfos: typeMemberInfoList}
	case reflect.Interface:
		typeMemberNameList := make([]string, realType.NumMethod())
		typeMemberInfoList := make([]TypeMemberInfo, realType.NumMethod())
		for i := 0; i < len(typeMemberNameList); i++ {
			typeMemberNameList[i] = realType.Method(i).Name
		}
		sort.Strings(typeMemberNameList)
		for i, typeMemberName := range typeMemberNameList {
			typeMember, _ := realType.MethodByName(typeMemberName)
			typeMemberInfoList[i] = TypeMemberInfo{TypeMemberName: typeMember.Name, TypeMemberTypeName: typeMember.Type.String()}
		}
		return TypeInfo{TypeName: realType.Name(), TypeMemberInfos: typeMemberInfoList}
	default:
		return TypeInfo{TypeName: realType.Name()}
	}

}

示例#14
文件: ncrss.go 项目: serbe/ncrss

func search(w http.ResponseWriter, req *http.Request) {
	query := req.URL.Query()
	year, _ := strconv.Atoi(query.Get("year"))
	actor := query.Get("actor")
	genre := query.Get("genre")
	page, _ := strconv.Atoi(query.Get("page"))
	if page == 0 {
		page = 1
	}
	director := query.Get("director")
	movies, count, err := searchMovies(page, year, actor, genre, director)
	if err != nil {
		log.Println("searchMovies ", 1, err)
	}
	genres := []string{}
	years := []string{}
	for _, movie := range movies {
		year := strconv.Itoa(movie.Year)
		if stringInSlice(years, year) == false {
			years = append(years, year)
		}
		filmGenres := movie.Genre
		for _, genre := range filmGenres {
			if stringInSlice(genres, genre) == false {
				genres = append(genres, genre)
			}
		}
	}
	sort.Strings(genres)
	sort.Strings(years)
	cont := context{Title: "NNM-club RSS", Static: staticURL, Movies: movies, Genres: genres, Years: years, Count: count}
	render(w, cont, "index")
}

示例#15
文件: trace_test.go 项目: liugangnhm/cockroach

func TestExplainTrace(t *testing.T) {
	defer leaktest.AfterTest(t)()
	s, sqlDB, _ := setup(t)
	defer cleanup(s, sqlDB)

	if _, err := sqlDB.Exec(`CREATE DATABASE test; CREATE TABLE test.foo (id INT PRIMARY KEY)`); err != nil {
		t.Fatal(err)
	}
	rows, err := sqlDB.Query(`EXPLAIN (TRACE) INSERT INTO test.foo VALUES (1)`)
	if err != nil {
		t.Fatal(err)
	}
	expParts := []string{"coordinator", "node 1"}
	var parts []string

	pretty := rowsToStrings(rows)
	for _, row := range pretty[1:] {
		part := row[3] // Operation
		if ind := sort.SearchStrings(parts, part); ind == len(parts) || parts[ind] != part {
			parts = append(parts, part)
			sort.Strings(parts)
		}
	}
	sort.Strings(expParts)
	if err := rows.Err(); err != nil {
		t.Fatal(err)
	}
	if !reflect.DeepEqual(expParts, parts) {
		t.Fatalf("expected %v, got %v\n\nResults:\n%v", expParts, parts, prettyPrint(pretty))
	}
}

示例#16
文件: map_test.go 项目: mbref/gcc-microblaze

func TestBigItems(t *testing.T) {
	var key [256]string
	for i := 0; i < 256; i++ {
		key[i] = "foo"
	}
	m := make(map[[256]string][256]string, 4)
	for i := 0; i < 100; i++ {
		key[37] = fmt.Sprintf("string%02d", i)
		m[key] = key
	}
	var keys [100]string
	var values [100]string
	i := 0
	for k, v := range m {
		keys[i] = k[37]
		values[i] = v[37]
		i++
	}
	sort.Strings(keys[:])
	sort.Strings(values[:])
	for i := 0; i < 100; i++ {
		if keys[i] != fmt.Sprintf("string%02d", i) {
			t.Errorf("#%d: missing key: %v", i, keys[i])
		}
		if values[i] != fmt.Sprintf("string%02d", i) {
			t.Errorf("#%d: missing value: %v", i, values[i])
		}
	}
}

示例#17
文件: resolver_test.go 项目: pranjal5215/vitess

func TestResolverBuildEntityIds(t *testing.T) {
	shardMap := make(map[string][]interface{})
	shardMap["-20"] = []interface{}{"0", 1}
	shardMap["20-40"] = []interface{}{"2"}
	sql := "select a from table where id=:id"
	entityColName := "uid"
	bindVar := make(map[string]interface{})
	bindVar["id"] = 10
	shards, sqls, bindVars := buildEntityIds(shardMap, sql, entityColName, bindVar)
	wantShards := []string{"-20", "20-40"}
	wantSqls := map[string]string{
		"-20":   "select a from table where id=:id and uid in (:uid0, :uid1)",
		"20-40": "select a from table where id=:id and uid in (:uid0)",
	}
	wantBindVars := map[string]map[string]interface{}{
		"-20":   map[string]interface{}{"id": 10, "uid0": "0", "uid1": 1},
		"20-40": map[string]interface{}{"id": 10, "uid0": "2"},
	}
	sort.Strings(wantShards)
	sort.Strings(shards)
	if !reflect.DeepEqual(wantShards, shards) {
		t.Errorf("want %+v, got %+v", wantShards, shards)
	}
	if !reflect.DeepEqual(wantSqls, sqls) {
		t.Errorf("want %+v, got %+v", wantSqls, sqls)
	}
	if !reflect.DeepEqual(wantBindVars, bindVars) {
		t.Errorf("want %+v, got %+v", wantBindVars, bindVars)
	}
}

示例#18
文件: pubsub_test.go 项目: mafos/gopubsub

func TestListTopics(t *testing.T) {
	topicIds := []string{
		"topic1",
		"topic2",
		"topic3",
		"topic4",
		"topic5",
		"topic6",
	}

	ps := NewPubsub()
	for _, id := range topicIds {
		ps.OpenTopic(id, 0)
	}

	ps.OpenTopic("closed-topic", 0)
	ps.CloseTopic("closed-topic")

	outIds := ps.ListTopics()

	sort.Strings(outIds)
	sort.Strings(topicIds)

	if assert.Equal(t, len(topicIds), len(outIds)) {
		for i, id := range topicIds {
			assert.Equal(t, id, outIds[i])
		}
	}
}

示例#19
文件: repo.go 项目: frankkorrell/gogs

func LoadRepoConfig() {
	// Load .gitignore and license files and readme templates.
	types := []string{"gitignore", "license", "readme"}
	typeFiles := make([][]string, 3)
	for i, t := range types {
		files, err := bindata.AssetDir("conf/" + t)
		if err != nil {
			log.Fatal(4, "Fail to get %s files: %v", t, err)
		}
		customPath := path.Join(setting.CustomPath, "conf", t)
		if com.IsDir(customPath) {
			customFiles, err := com.StatDir(customPath)
			if err != nil {
				log.Fatal(4, "Fail to get custom %s files: %v", t, err)
			}

			for _, f := range customFiles {
				if !com.IsSliceContainsStr(files, f) {
					files = append(files, f)
				}
			}
		}
		typeFiles[i] = files
	}

	Gitignores = typeFiles[0]
	Licenses = typeFiles[1]
	Readmes = typeFiles[2]
	sort.Strings(Gitignores)
	sort.Strings(Licenses)
	sort.Strings(Readmes)
}

示例#20
文件: testsuites.go 项目: jhadvig/origin

// TestList checks the returned list of keys after populating a directory tree.
func (suite *DriverSuite) TestList(c *check.C) {
	rootDirectory := "/" + randomFilename(int64(8+rand.Intn(8)))
	defer suite.StorageDriver.Delete(rootDirectory)

	parentDirectory := rootDirectory + "/" + randomFilename(int64(8+rand.Intn(8)))
	childFiles := make([]string, 50)
	for i := 0; i < len(childFiles); i++ {
		childFile := parentDirectory + "/" + randomFilename(int64(8+rand.Intn(8)))
		childFiles[i] = childFile
		err := suite.StorageDriver.PutContent(childFile, randomContents(32))
		c.Assert(err, check.IsNil)
	}
	sort.Strings(childFiles)

	keys, err := suite.StorageDriver.List("/")
	c.Assert(err, check.IsNil)
	c.Assert(keys, check.DeepEquals, []string{rootDirectory})

	keys, err = suite.StorageDriver.List(rootDirectory)
	c.Assert(err, check.IsNil)
	c.Assert(keys, check.DeepEquals, []string{parentDirectory})

	keys, err = suite.StorageDriver.List(parentDirectory)
	c.Assert(err, check.IsNil)

	sort.Strings(keys)
	c.Assert(keys, check.DeepEquals, childFiles)

	// A few checks to add here (check out #819 for more discussion on this):
	// 1. Ensure that all paths are absolute.
	// 2. Ensure that listings only include direct children.
	// 3. Ensure that we only respond to directory listings that end with a slash (maybe?).
}

示例#21
文件: watcher.go 项目: zhouqt/juju

// assertChange asserts the given list of changes was reported by
// the watcher, but does not assume there are no following changes.
func (c StringsWatcherC) assertChange(single bool, expect ...string) {
	c.State.StartSync()
	timeout := time.After(testing.LongWait)
	var actual []string
loop:
	for {
		select {
		case changes, ok := <-c.Watcher.Changes():
			c.Assert(ok, jc.IsTrue)
			actual = append(actual, changes...)
			if single || len(actual) >= len(expect) {
				break loop
			}
		case <-timeout:
			c.Fatalf("watcher did not send change")
		}
	}
	if len(expect) == 0 {
		c.Assert(actual, gc.HasLen, 0)
	} else {
		sort.Strings(expect)
		sort.Strings(actual)
		c.Assert(actual, gc.DeepEquals, expect)
	}
}

示例#22
文件: example_test.go 项目: dionb/tools

func printProgram(prog *loader.Program) {
	// Created packages are the initial packages specified by a call
	// to CreateFromFilenames or CreateFromFiles.
	var names []string
	for _, info := range prog.Created {
		names = append(names, info.Pkg.Path())
	}
	fmt.Printf("created: %s\n", names)

	// Imported packages are the initial packages specified by a
	// call to Import or ImportWithTests.
	names = nil
	for _, info := range prog.Imported {
		names = append(names, info.Pkg.Path())
	}
	sort.Strings(names)
	fmt.Printf("imported: %s\n", names)

	// InitialPackages contains the union of created and imported.
	names = nil
	for _, info := range prog.InitialPackages() {
		names = append(names, info.Pkg.Path())
	}
	sort.Strings(names)
	fmt.Printf("initial: %s\n", names)

	// AllPackages contains all initial packages and their dependencies.
	names = nil
	for pkg := range prog.AllPackages {
		names = append(names, pkg.Path())
	}
	sort.Strings(names)
	fmt.Printf("all: %s\n", names)
}

示例#23
文件: lifecycle.go 项目: pritten/evergreen

// sortLayer groups tasks by common dependencies, sorting alphabetically within each group
func sortLayer(layer []Task, idToDisplayName map[string]string) []Task {
	sortKeys := make([]string, 0, len(layer))
	sortKeyToTask := make(map[string]Task)
	for _, task := range layer {
		// Construct a key to sort by, consisting of all dependency names, sorted alphabetically,
		// followed by the task name
		sortKeyWords := make([]string, 0, len(task.DependsOn)+1)
		for _, dep := range task.DependsOn {
			depName, ok := idToDisplayName[dep.TaskId]
			// Cross-variant dependencies will not be included in idToDisplayName
			if !ok {
				depName = dep.TaskId
			}
			sortKeyWords = append(sortKeyWords, depName)
		}
		sort.Strings(sortKeyWords)
		sortKeyWords = append(sortKeyWords, task.DisplayName)
		sortKey := strings.Join(sortKeyWords, " ")
		sortKeys = append(sortKeys, sortKey)
		sortKeyToTask[sortKey] = task
	}
	sort.Strings(sortKeys)
	sortedLayer := make([]Task, 0, len(layer))
	for _, sortKey := range sortKeys {
		sortedLayer = append(sortedLayer, sortKeyToTask[sortKey])
	}
	return sortedLayer
}

示例#24
文件: cbt.go 项目: Celluliodio/flannel

func doLS(ctx context.Context, args ...string) {
	switch len(args) {
	default:
		log.Fatalf("Can't do `cbt ls %s`", args)
	case 0:
		tables, err := getAdminClient().Tables(ctx)
		if err != nil {
			log.Fatalf("Getting list of tables: %v", err)
		}
		sort.Strings(tables)
		for _, table := range tables {
			fmt.Println(table)
		}
	case 1:
		table := args[0]
		ti, err := getAdminClient().TableInfo(ctx, table)
		if err != nil {
			log.Fatalf("Getting table info: %v", err)
		}
		sort.Strings(ti.Families)
		for _, fam := range ti.Families {
			fmt.Println(fam)
		}
	}
}

示例#25
文件: db_test.go 项目: eswdd/bosun

// mustContainKeys checks that a bucket contains a given set of keys.
func mustContainKeys(b *bolt.Bucket, m map[string]string) {
	found := make(map[string]string)
	b.ForEach(func(k, _ []byte) error {
		found[string(k)] = ""
		return nil
	})

	// Check for keys found in bucket that shouldn't be there.
	var keys []string
	for k, _ := range found {
		if _, ok := m[string(k)]; !ok {
			keys = append(keys, k)
		}
	}
	if len(keys) > 0 {
		sort.Strings(keys)
		panic(fmt.Sprintf("keys found(%d): %s", len(keys), strings.Join(keys, ",")))
	}

	// Check for keys not found in bucket that should be there.
	for k, _ := range m {
		if _, ok := found[string(k)]; !ok {
			keys = append(keys, k)
		}
	}
	if len(keys) > 0 {
		sort.Strings(keys)
		panic(fmt.Sprintf("keys not found(%d): %s", len(keys), strings.Join(keys, ",")))
	}
}

示例#26
文件: ingester_test.go 项目: Tiger66639/skia-buildbot

func TestGetGSResultFileLocations(t *testing.T) {
	testutils.SkipIfShort(t)
	storage, err := storage.New(http.DefaultClient)
	assert.Nil(t, err)

	startTS := time.Date(2014, time.December, 10, 0, 0, 0, 0, time.UTC).Unix()
	endTS := time.Date(2014, time.December, 10, 23, 59, 59, 0, time.UTC).Unix()

	// TODO(stephana): Switch this to a dedicated test bucket, so we are not
	// in danger of removing it.
	resultFiles, err := getGSResultsFileLocations(startTS, endTS, storage, "chromium-skia-gm", "dm-json-v1")
	assert.Nil(t, err)

	// Read the expected list of files and compare them.
	content, err := ioutil.ReadFile("./testdata/filelist_dec_10.txt")
	assert.Nil(t, err)
	lines := strings.Split(strings.TrimSpace(string(content)), "\n")
	sort.Strings(lines)

	resultNames := make([]string, len(resultFiles))
	for idx, rf := range resultFiles {
		resultNames[idx] = rf.Name
	}
	sort.Strings(resultNames)
	assert.Equal(t, len(lines), len(resultNames))
	assert.Equal(t, lines, resultNames)
}

示例#27
文件: repo.go 项目: pmatulis/juju

func (s *RepoSuite) AssertUnitMachines(c *gc.C, units []*state.Unit) {
	tags := make([]names.UnitTag, len(units))
	expectUnitNames := make([]string, len(units))
	for i, u := range units {
		expectUnitNames[i] = u.Name()
		tags[i] = u.UnitTag()
	}

	// manually assign all units to machines.  This replaces work normally done
	// by the unitassigner code.
	errs, err := s.APIState.UnitAssigner().AssignUnits(tags)
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(errs, gc.DeepEquals, make([]error, len(units)))

	sort.Strings(expectUnitNames)

	machines, err := s.State.AllMachines()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(machines, gc.HasLen, len(units))

	unitNames := []string{}
	for _, m := range machines {
		mUnits, err := m.Units()
		c.Assert(err, jc.ErrorIsNil)
		c.Assert(mUnits, gc.HasLen, 1)
		unitNames = append(unitNames, mUnits[0].Name())
	}
	sort.Strings(unitNames)
	c.Assert(unitNames, gc.DeepEquals, expectUnitNames)
}

示例#28
文件: ingester_test.go 项目: Tiger66639/skia-buildbot

func TestGetLocalResultFileLocations(t *testing.T) {
	testutils.SkipIfShort(t)

	err := testutils.DownloadTestDataArchive(t, TEST_DATA_STORAGE_PATH, TEST_DATA_DIR)
	assert.Nil(t, err)

	startTS := time.Date(2015, time.May, 5, 0, 0, 0, 0, time.UTC).Unix()
	endTS := time.Date(2015, time.May, 17, 23, 59, 59, 0, time.UTC).Unix()

	resultFiles, err := getLocalResultsFileLocations(startTS, endTS, filepath.Join(TEST_DATA_DIR, "nano-json-v1"))
	assert.Nil(t, err)

	// Read the expected list of files and compare them.
	content, err := ioutil.ReadFile("./testdata/local_ingest_files.txt")
	assert.Nil(t, err)
	lines := strings.Split(strings.TrimSpace(string(content)), "\n")
	sort.Strings(lines)

	resultNames := make([]string, len(resultFiles))
	for idx, rf := range resultFiles {
		resultNames[idx] = rf.Name
	}
	sort.Strings(resultNames)
	assert.Equal(t, len(lines), len(resultNames))
	assert.Equal(t, lines, resultNames)
}

示例#29
文件: virtual_schema.go 项目: BramGruneir/cockroach

func (vs *virtualSchemaHolder) init(p *planner) error {
	*vs = virtualSchemaHolder{
		entries:      make(map[string]virtualSchemaEntry, len(virtualSchemas)),
		orderedNames: make([]string, len(virtualSchemas)),
	}
	for i, schema := range virtualSchemas {
		dbName := schema.name
		dbDesc := initVirtualDatabaseDesc(dbName)
		tables := make(map[string]virtualTableEntry, len(schema.tables))
		orderedTableNames := make([]string, 0, len(schema.tables))
		for _, table := range schema.tables {
			tableDesc, err := initVirtualTableDesc(p, table)
			if err != nil {
				return err
			}
			tables[tableDesc.Name] = virtualTableEntry{
				tableDef: table,
				desc:     &tableDesc,
			}
			orderedTableNames = append(orderedTableNames, tableDesc.Name)
		}
		sort.Strings(orderedTableNames)
		vs.entries[dbName] = virtualSchemaEntry{
			desc:              dbDesc,
			tables:            tables,
			orderedTableNames: orderedTableNames,
		}
		vs.orderedNames[i] = dbName
	}
	sort.Strings(vs.orderedNames)
	return nil
}

示例#30
文件: telegraf_test.go 项目: amonapp/amonagent

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")

	}

}

展开阅读全文