Golang StringSlice示例

说明

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

编程语言: Golang

命名空间/包名称: sort

示例#1
文件: envmap_test.go 项目: wallyqs/util

func TestEnvMap(t *testing.T) {
	tt.StartTest(t)
	defer tt.FinishTest(t)

	expected := []string{
		"START_COMMAND=XYZ",
		"TEST_CROSSREF1=cross_pkg2",
		"TEST_CROSSREF2=cross_pkg1",
		"TEST_CROSSREF_VAL1=cross_pkg1",
		"TEST_CROSSREF_VAL2=cross_pkg2",
		"TEST_ENV_VARIABLE=TEST_ENV_CONTENT",
		"TEST_MERGE_UNDEFINED=undef:",
		"TEST_MERGE_VARIABLE=pkg2:pkg1:",
		"TEST_OVERRIDE_VARIABLE=pkg2",
	}

	root := NewEnvMap()
	root.Set("TEST_ENV_VARIABLE", "TEST_ENV_CONTENT")
	root.Set("TEST_MERGE_VARIABLE", "pkg1:$TEST_MERGE_VARIABLE")
	root.Set("TEST_MERGE_UNDEFINED", "undef:$TEST_NOT_SET")
	root.Set("TEST_OVERRIDE_VARIABLE", "pkg1")
	root.Set("TEST_CROSSREF1", "$TEST_CROSSREF_VAL2")
	root.Set("TEST_CROSSREF_VAL1", "cross_pkg1")
	root.Set("START_COMMAND", "XYZ")

	c1 := root.NewChild()
	c1.Set("TEST_MERGE_VARIABLE", "pkg2:$TEST_MERGE_VARIABLE")
	c1.Set("TEST_OVERRIDE_VARIABLE", "pkg2")
	c1.Set("TEST_CROSSREF2", "$TEST_CROSSREF_VAL1")
	c1.Set("TEST_CROSSREF_VAL2", "cross_pkg2")
	c1.Set("START_COMMAND", "XYZ")

	envstrs := c1.Strings()

	// Sort the two list just in case.
	sort.Sort(sort.StringSlice(envstrs))
	sort.Sort(sort.StringSlice(expected))

	msg := make([]string, 0, len(envstrs))
	failed := false
	a := func(fmtstr string, args ...interface{}) {
		msg = append(msg, fmt.Sprintf(fmtstr, args...))
	}
	for i := 0; i < len(expected) || i < len(envstrs); i++ {
		if i >= len(expected) {
			a("\t'' > '%s'", envstrs[i])
		} else if i >= len(envstrs) {
			a("\t'%s' < ''", expected[i])
		} else if expected[i] != envstrs[i] {
			a("\t'%s' != '%s'", expected[i], envstrs[i])
		} else {
			a("\t'%s' == '%s'", expected[i], envstrs[i])
			continue
		}
		failed = true
	}
	if failed == true {
		tt.Fatalf(t, "results are not the same:\n%s", strings.Join(msg, "\n"))
	}
}

示例#2
文件: filter_test.go 项目: hfern/goseq

func TestFilter_Keys(t *testing.T) {
	valmap := map[string]interface{}{
		"string": "what what",
		"int":    3242,
		"bool":   true,
	}

	actualkeys := make([]string, len(valmap))

	for key, _ := range valmap {
		actualkeys = append(actualkeys, key)
	}

	fil, err := testFilterSuite(valmap)
	if err != nil {
		t.Log(err)
		t.FailNow()
	}

	sortedActual := sort.StringSlice(actualkeys)
	sortedActual.Sort()
	sortedReported := sort.StringSlice(fil.Keys())
	sortedReported.Sort()

	if !reflect.DeepEqual(sortedActual, sortedReported) {
		t.Log("Array keys are not the same!")
	}
}

示例#3
文件: algorithm_test.go 项目: mrekucci/epi

func testSortFn(t *testing.T, fn sortFn, fnName string) {
	for _, test := range []sort.Interface{
		sort.IntSlice([]int{660, 14, 796, 336, 223, 594, 419, 574, 372, 103, 991, 718, 436, 351, 844, 277, 668, 250, 330, 86}),
		sort.Float64Slice([]float64{213.237, 458.642, 978.311, 547.351, 57.8992, 245.518, 445.638, 251.79, 960.202, 100.069, 483.136, 407.858, 496.913, 562.943, 557.959, 219.648, 164.599, 843.304, 671.732, 222.676}),
		sort.StringSlice([]string{"assaults", "brackish", "monarchism", "ascribe", "mechanize", "andiron", "overpricing", "jading", "hauliers", "snug", "zodiac", "credit", "tremendous", "palavered", "hibiscuses", "amplest", "interrogated", "geologic", "unorthodoxy", "propagated"}),
	} {
		// Make a copy to avoid modification of the original slice.
		var data sort.Interface
		switch v := test.(type) {
		case sort.IntSlice:
			data = append(sort.IntSlice(nil), v...)
		case sort.Float64Slice:
			data = append(sort.Float64Slice(nil), v...)
		case sort.StringSlice:
			data = append(sort.StringSlice(nil), v...)
		default:
			t.Errorf("missing case: cannot copy %T", v)
			continue
		}
		fn(data)
		if !sort.IsSorted(data) {
			t.Errorf("%s(%v)", fnName, test)
			t.Errorf(" got %v", data)
			sort.Sort(data)
			t.Errorf("want %v", data)
		}
	}
}

示例#4
文件: loadbalancers.go 项目: murdinc/awsm

// Marshal parses the response from the aws sdk into an awsm LoadBalancer
func (l *LoadBalancer) Marshal(balancer *elb.LoadBalancerDescription, region string, secGrpList *SecurityGroups, vpcList *Vpcs, subList *Subnets) {

	// security groups
	secGroupNames := secGrpList.GetSecurityGroupNames(aws.StringValueSlice(balancer.SecurityGroups))
	secGroupNamesSorted := sort.StringSlice(secGroupNames[0:])
	secGroupNamesSorted.Sort()

	// subnets
	subnetNames := subList.GetSubnetNames(aws.StringValueSlice(balancer.Subnets))
	subnetNamesSorted := sort.StringSlice(subnetNames[0:])
	subnetNamesSorted.Sort()

	l.Name = aws.StringValue(balancer.LoadBalancerName)
	l.DNSName = aws.StringValue(balancer.DNSName)
	l.CreatedTime = aws.TimeValue(balancer.CreatedTime) // robots
	l.CreatedHuman = humanize.Time(l.CreatedTime)       // humans
	l.VpcID = aws.StringValue(balancer.VPCId)
	l.Vpc = vpcList.GetVpcName(l.VpcID)
	l.SubnetIDs = aws.StringValueSlice(balancer.Subnets)
	l.Subnets = strings.Join(subnetNamesSorted, ", ")
	l.HealthCheckTarget = aws.StringValue(balancer.HealthCheck.Target)
	l.HealthCheckInterval = fmt.Sprintf("%d seconds", *balancer.HealthCheck.Interval)
	l.Scheme = aws.StringValue(balancer.Scheme)
	l.SecurityGroups = strings.Join(secGroupNamesSorted, ", ")
	l.AvailabilityZones = strings.Join(aws.StringValueSlice(balancer.AvailabilityZones), ", ") // TODO
	l.Region = region
}

示例#5
文件: sort.go 项目: rkoesters/goblin

func Sort(buf []string) {
	if *reverse {
		sort.Sort(sort.Reverse(sort.StringSlice(buf)))
	} else {
		sort.Sort(sort.StringSlice(buf))
	}
}

示例#6
文件: main.go 项目: plod/goLearning

func main() {
	// sort people as type
	studyGroup := people{"Zeno", "John", "Al", "Jenny"}

	fmt.Println(studyGroup)
	sort.Sort(studyGroup)
	fmt.Println(studyGroup)
	sort.Sort(sort.Reverse(studyGroup))
	fmt.Println(studyGroup)

	// sort s as string slice
	s := []string{"Zeno", "John", "Al", "Jenny"}
	fmt.Println(s)
	sort.StringSlice(s).Sort()
	fmt.Println(s)
	sort.Sort(sort.Reverse(sort.StringSlice(s)))
	fmt.Println(s)

	// sort n as int slice
	n := []int{7, 4, 8, 2, 9, 19, 12, 32, 3}
	fmt.Println(n)
	sort.IntSlice(n).Sort()
	fmt.Println(n)
	sort.Sort(sort.Reverse(sort.IntSlice(n)))
	fmt.Println(n)
}

示例#7
文件: wiki_test.go 项目: dankennedy/gocql

func TestWikiTypicalCRUD(t *testing.T) {
	session := createSession(t)
	defer session.Close()

	w := WikiTest{session, t}
	w.CreateSchema()
	for _, page := range wikiTestData {
		if err := w.InsertPage(page); err != nil {
			t.Error("InsertPage:", err)
		}
	}
	if count := w.GetPageCount(); count != len(wikiTestData) {
		t.Errorf("count: expected %d, got %d\n", len(wikiTestData), count)
	}
	for _, original := range wikiTestData {
		page := new(WikiPage)
		if err := w.SelectPage(page, original.Title, original.RevId); err != nil {
			t.Error("SelectPage:", err)
			continue
		}
		sort.Sort(sort.StringSlice(page.Tags))
		sort.Sort(sort.StringSlice(original.Tags))
		if !reflect.DeepEqual(page, original) {
			t.Errorf("page: expected %#v, got %#v\n", original, page)
		}
	}
}

示例#8
文件: set.go 项目: jonboulle/fleet

// Equals returns whether the contents of two sets are identical
func (us *unsafeSet) Equals(other Set) bool {
	v1 := sort.StringSlice(us.Values())
	v2 := sort.StringSlice(other.Values())
	v1.Sort()
	v2.Sort()
	return reflect.DeepEqual(v1, v2)
}

示例#9
文件: set_test.go 项目: Blystad/deis

// Check that two slices contents are equal; order is irrelevant
func equal(a, b []string) bool {
	as := sort.StringSlice(a)
	bs := sort.StringSlice(b)
	as.Sort()
	bs.Sort()
	return reflect.DeepEqual(as, bs)
}

示例#10
文件: client.go 项目: jak-atx/vic

func (c *httpClusterClient) Sync(ctx context.Context) error {
	mAPI := NewMembersAPI(c)
	ms, err := mAPI.List(ctx)
	if err != nil {
		return err
	}

	c.Lock()
	defer c.Unlock()

	eps := make([]string, 0)
	for _, m := range ms {
		eps = append(eps, m.ClientURLs...)
	}
	sort.Sort(sort.StringSlice(eps))

	ceps := make([]string, len(c.endpoints))
	for i, cep := range c.endpoints {
		ceps[i] = cep.String()
	}
	sort.Sort(sort.StringSlice(ceps))
	// fast path if no change happens
	// this helps client to pin the endpoint when no cluster change
	if reflect.DeepEqual(eps, ceps) {
		return nil
	}

	return c.SetEndpoints(eps)
}

示例#11
文件: validator_test.go 项目: ifraixedes/go-hmac-validator

func TestMapToSlice(t *testing.T) {
	type expect struct {
		keysToExclude []string
		payload       map[string]string
		result        []string
	}

	expectations := []expect{
		expect{[]string{"key2", "key3"}, map[string]string{"key1": "value1", "key2": "value2", "key3": "value3"}, []string{"key1", "value1"}},
		expect{[]string{"key1"}, map[string]string{"key1": "value1", "key2": "value2", "key3": "value3"}, []string{"key2", "value2", "key3", "value3"}},
		expect{[]string{"key2", "not-exist"}, map[string]string{"key1": "value1", "key2": "value2", "key3": "value3"}, []string{"key1", "value1", "key3", "value3"}},
		expect{[]string{"key1", "key2", "key3"}, map[string]string{"key1": "value1", "key2": "value2", "key3": "value3"}, []string{}},
		expect{[]string{}, map[string]string{"key1": "value1", "key2": "value2", "key3": "value3"}, []string{"key1", "value1", "key2", "value2", "key3", "value3"}},
		expect{nil, map[string]string{"key1": "value1", "key2": "value2", "key3": "value3"}, []string{"key1", "value1", "key2", "value2", "key3", "value3"}},
	}

	for _, e := range expectations {
		result := mapToSlice(e.keysToExclude, e.payload)
		eres := sort.StringSlice(e.result)
		res := sort.StringSlice(result)

		eres.Sort()
		res.Sort()
		assert.EqualValues(t, eres, res, "Result doesn't match the expectation")
	}
}

示例#12
文件: reconcile_sccs.go 项目: johnmccawley/origin

// computeUpdatedSCC determines if the expected SCC looks like the actual SCC
// it does this by making the expected SCC mirror the actual SCC for items that
// we are not reconciling and performing a diff (ignoring changes to metadata).
// If a diff is produced then the expected SCC is submitted as needing an update.
func (o *ReconcileSCCOptions) computeUpdatedSCC(expected kapi.SecurityContextConstraints, actual kapi.SecurityContextConstraints) (*kapi.SecurityContextConstraints, bool) {
	needsUpdate := false

	// if unioning old and new groups/users then make the expected contain all
	// also preserve and set priorities
	if o.Union {
		groupSet := sets.NewString(actual.Groups...)
		groupSet.Insert(expected.Groups...)
		expected.Groups = groupSet.List()

		userSet := sets.NewString(actual.Users...)
		userSet.Insert(expected.Users...)
		expected.Users = userSet.List()

		if actual.Priority != nil {
			expected.Priority = actual.Priority
		}
	}

	// sort users and groups to remove any variants in order when diffing
	sort.StringSlice(actual.Groups).Sort()
	sort.StringSlice(actual.Users).Sort()
	sort.StringSlice(expected.Groups).Sort()
	sort.StringSlice(expected.Users).Sort()

	// make a copy of the expected scc here so we can ignore metadata diffs.
	updated := expected
	expected.ObjectMeta = actual.ObjectMeta

	if !kapi.Semantic.DeepEqual(expected, actual) {
		needsUpdate = true
	}

	return &updated, needsUpdate
}

示例#13
文件: emit_messages_matcher.go 项目: emc-xchallenge/route-emitter

func (m *messagesToEmitMatcher) matchArrs(actual, expected []routing_table.RegistryMessage) bool {
	if len(actual) != len(expected) {
		return false
	}

	fixedActual := []routing_table.RegistryMessage{}
	fixedExpected := []routing_table.RegistryMessage{}

	for _, message := range actual {
		sort.Sort(sort.StringSlice(message.URIs))
		fixedActual = append(fixedActual, message)
	}

	for _, message := range expected {
		sort.Sort(sort.StringSlice(message.URIs))
		fixedExpected = append(fixedExpected, message)
	}

	sort.Sort(ByMessage(fixedActual))
	sort.Sort(ByMessage(fixedExpected))

	for i := 0; i < len(fixedActual); i++ {
		if !reflect.DeepEqual(fixedActual[i], fixedExpected[i]) {
			return false
		}
	}

	return true
}

示例#14
文件: main.go 项目: imcmurray/UdemyTraining

func main() {

	studyGroup := people{"Zeno", "Ian", "John", "Al", "Jenny"}

	fmt.Println("1: = sorting slice of strings of type people by name:")
	fmt.Println("\to:", studyGroup)
	sort.Strings(studyGroup)
	fmt.Println("\t\t [Strings method]:", studyGroup)
	sort.Sort(sort.StringSlice(studyGroup))
	fmt.Println("\t\t [StringSlice interface conversion]", studyGroup)
	sort.Sort(sort.Reverse(sort.StringSlice(studyGroup)))
	fmt.Println("\t\t [Reverse]", studyGroup)

	fmt.Println("2: = by literal slice of strings")
	s := []string{"Zeno", "John", "Al", "Jenny", "Ben"}
	fmt.Println("\to:", s)
	sort.Strings(s)
	fmt.Println("\t\t [Strings method]:", s)
	sort.Sort(sort.StringSlice(s))
	fmt.Println("\t\t [StringSlice interface conversion]", s)
	sort.Sort(sort.Reverse(sort.StringSlice(s)))
	fmt.Println("\t\t [Reverse]", s)

	fmt.Println("3: = slice of ints")
	n := []int{7, 4, 8, 2, 9, 19, 12, 32, 3}
	fmt.Println("\to:", n)
	sort.Ints(n)
	fmt.Println("\t\t [Ints method]", n)
	sort.Sort(sort.IntSlice(n))
	fmt.Println("\t\t [IntSlice interface conversion]", n)
	sort.Sort(sort.Reverse(sort.IntSlice(n)))
	fmt.Println("\t\t [Reverse]", n)

}

示例#15
文件: dht_test.go 项目: djbarber/ipfs-hack

func testPeerListsMatch(t *testing.T, p1, p2 []peer.ID) {

	if len(p1) != len(p2) {
		t.Fatal("did not find as many peers as should have", p1, p2)
	}

	ids1 := make([]string, len(p1))
	ids2 := make([]string, len(p2))

	for i, p := range p1 {
		ids1[i] = string(p)
	}

	for i, p := range p2 {
		ids2[i] = string(p)
	}

	sort.Sort(sort.StringSlice(ids1))
	sort.Sort(sort.StringSlice(ids2))

	for i := range ids1 {
		if ids1[i] != ids2[i] {
			t.Fatal("Didnt find expected peer", ids1[i], ids2)
		}
	}
}

示例#16
文件: common_test.go 项目: DirtyHairy/csync

func checkDirectoryContents(directory storage.Directory, expectedContents []string) (entries map[string]storage.Entry, e error) {
	entries = make(map[string]storage.Entry)
	e = nil

	contents := make([]string, 0, 10)

	for entry, err := directory.NextEntry(); entry != nil; entry, err = directory.NextEntry() {
		if err != nil {
			e = errors.New(fmt.Sprintf("error while iterating over directory entries: %v", err))
			return
		}

		contents = append(contents, entry.Name())
		entries[entry.Name()] = entry
	}

	if len(contents) != len(expectedContents) {
		e = errors.New(fmt.Sprintf("expected %d dir entries, got %d instead", len(expectedContents), len(contents)))
		return
	}

	sort.Sort(sort.StringSlice(contents))
	sort.Sort(sort.StringSlice(expectedContents))

	for idx, filename := range contents {
		if filename != expectedContents[idx] {
			e = errors.New(fmt.Sprintf("directory listing differs at %d: expected %s, got %s", idx, expectedContents[idx], filename))
			return
		}
	}

	return
}

示例#17
文件: main.go 项目: ScottShao/crawlDoubanGroup

func renderHtml(topicList map[string]*Topic) string {
	topic_keys := make([]string, 0)
	for key, _ := range topicList {
		topic_keys = append(topic_keys, key)
	}

	sort.StringSlice(topic_keys).Sort()

	htmlHead := `<!DOCTYPE html>
		<html>
			<head>
			<title>topic and reply</title>
			</head>
		`
	htmlList := ""
	for _, key := range topic_keys {
		v, _ := topicList[key]
		listHead := fmt.Sprintf(
			`<li>
				<a href=%s style='text-decoration: none;' target=\"blank\">%s -- %s</a>
				</br>
				<ul>`,
			v.Url, v.Title, v.User)
		listBody := ""

		reply_keys := make([]string, 0)
		for key, _ := range v.Replys {
			reply_keys = append(reply_keys, key)
		}

		sort.StringSlice(reply_keys).Sort()

		for _, key := range reply_keys {
			reply, _ := v.Replys[key]
			listBody += fmt.Sprintf(
				`<li>
					<quote>
						%s
					</quote>
					<h3>
						%s
					</h3>
					<h5>
						%s
					</h5>
				</li>`, reply.Quote, reply.Content, reply.Time)
		}
		listFooter := `
			</ul>
			</li>`

		htmlList += listHead + listBody + listFooter
	}
	htmlBody := "<body><ol>" + htmlList + "</ol></body>"
	htmlFooter := `
		</html>
		`
	return htmlHead + htmlBody + htmlFooter
}

示例#18
文件: cassandra_db_test.go 项目: deveshmittal/metrics

func Test_MetricName_GetTagSet_DB(t *testing.T) {
	a := assert.New(t)
	db := newDatabase(t)
	if db == nil {
		return
	}
	defer cleanDatabase(t, db)
	if _, err := db.GetTagSet("sample"); err == nil {
		t.Errorf("Cassandra should error on fetching nonexistent metric")
	}

	metricNamesTests := []struct {
		addTest      bool
		metricName   string
		tagString    string
		expectedTags map[string][]string // { metricName: [ tags ] }
	}{
		{true, "sample", "foo=bar1", map[string][]string{
			"sample": []string{"foo=bar1"},
		}},
		{true, "sample", "foo=bar2", map[string][]string{
			"sample": []string{"foo=bar1", "foo=bar2"},
		}},
		{true, "sample2", "foo=bar2", map[string][]string{
			"sample":  []string{"foo=bar1", "foo=bar2"},
			"sample2": []string{"foo=bar2"},
		}},
		{false, "sample2", "foo=bar2", map[string][]string{
			"sample": []string{"foo=bar1", "foo=bar2"},
		}},
		{false, "sample", "foo=bar1", map[string][]string{
			"sample": []string{"foo=bar2"},
		}},
	}

	for _, c := range metricNamesTests {
		if c.addTest {
			a.CheckError(db.AddMetricName(api.MetricKey(c.metricName), api.ParseTagSet(c.tagString)))
		} else {
			a.CheckError(db.RemoveMetricName(api.MetricKey(c.metricName), api.ParseTagSet(c.tagString)))
		}

		for k, v := range c.expectedTags {
			if tags, err := db.GetTagSet(api.MetricKey(k)); err != nil {
				t.Errorf("Error fetching tags")
			} else {
				stringTags := make([]string, len(tags))
				for i, tag := range tags {
					stringTags[i] = tag.Serialize()
				}

				a.EqInt(len(stringTags), len(v))
				sort.Sort(sort.StringSlice(stringTags))
				sort.Sort(sort.StringSlice(v))
				a.Eq(stringTags, v)
			}
		}
	}
}

示例#19
文件: cassandra_test.go 项目: Gibheer/gocql

func TestCRUD(t *testing.T) {
	session := createSession(t)
	defer session.Close()

	if err := session.Query(`CREATE TABLE page (
			title       varchar,
			revid       timeuuid,
			body        varchar,
			views       bigint,
			protected   boolean,
			modified    timestamp,
			rating      decimal,
			tags        set<varchar>,
			attachments map<varchar, text>,
			PRIMARY KEY (title, revid)
		)`).Exec(); err != nil {
		t.Fatal("create table:", err)
	}

	for _, page := range pageTestData {
		if err := session.Query(`INSERT INTO page
			(title, revid, body, views, protected, modified, rating, tags, attachments)
			VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
			page.Title, page.RevId, page.Body, page.Views, page.Protected,
			page.Modified, page.Rating, page.Tags, page.Attachments).Exec(); err != nil {
			t.Fatal("insert:", err)
		}
	}

	var count int
	if err := session.Query("SELECT COUNT(*) FROM page").Scan(&count); err != nil {
		t.Error("select count:", err)
	}
	if count != len(pageTestData) {
		t.Errorf("count: expected %d, got %d\n", len(pageTestData), count)
	}

	for _, original := range pageTestData {
		page := new(Page)
		err := session.Query(`SELECT title, revid, body, views, protected, modified,
			tags, attachments, rating
			FROM page WHERE title = ? AND revid = ? LIMIT 1`,
			original.Title, original.RevId).Scan(&page.Title, &page.RevId,
			&page.Body, &page.Views, &page.Protected, &page.Modified, &page.Tags,
			&page.Attachments, &page.Rating)
		if err != nil {
			t.Error("select page:", err)
			continue
		}
		sort.Sort(sort.StringSlice(page.Tags))
		sort.Sort(sort.StringSlice(original.Tags))
		if !reflect.DeepEqual(page, original) {
			t.Errorf("page: expected %#v, got %#v\n", original, page)
		}
	}
}

示例#20
文件: docker_cli_exec_test.go 项目: jbbarth/docker

func TestExecCgroup(t *testing.T) {
	defer deleteAllContainers()
	var cmd *exec.Cmd

	cmd = exec.Command(dockerBinary, "run", "-d", "--name", "testing", "busybox", "top")
	_, err := runCommand(cmd)
	if err != nil {
		t.Fatal(err)
	}

	cmd = exec.Command(dockerBinary, "exec", "testing", "cat", "/proc/1/cgroup")
	out, _, err := runCommandWithOutput(cmd)
	if err != nil {
		t.Fatal(out, err)
	}
	containerCgroups := sort.StringSlice(strings.Split(string(out), "\n"))

	var wg sync.WaitGroup
	var s sync.Mutex
	execCgroups := []sort.StringSlice{}
	// exec a few times concurrently to get consistent failure
	for i := 0; i < 5; i++ {
		wg.Add(1)
		go func() {
			cmd := exec.Command(dockerBinary, "exec", "testing", "cat", "/proc/self/cgroup")
			out, _, err := runCommandWithOutput(cmd)
			if err != nil {
				t.Fatal(out, err)
			}
			cg := sort.StringSlice(strings.Split(string(out), "\n"))

			s.Lock()
			execCgroups = append(execCgroups, cg)
			s.Unlock()
			wg.Done()
		}()
	}
	wg.Wait()

	for _, cg := range execCgroups {
		if !reflect.DeepEqual(cg, containerCgroups) {
			fmt.Println("exec cgroups:")
			for _, name := range cg {
				fmt.Printf(" %s\n", name)
			}

			fmt.Println("container cgroups:")
			for _, name := range containerCgroups {
				fmt.Printf(" %s\n", name)
			}
			t.Fatal("cgroups mismatched")
		}
	}

	logDone("exec - exec has the container cgroups")
}

示例#21
文件: resource_aws_s3_bucket_notification_test.go 项目: Originate/terraform

func testAccCheckAWSS3BucketLambdaFunctionConfiguration(n, i, t string, events []string, filters *s3.KeyFilter) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		rs, _ := s.RootModule().Resources[n]
		funcArn := s.RootModule().Resources[t].Primary.Attributes["arn"]
		conn := testAccProvider.Meta().(*AWSClient).s3conn

		err := resource.Retry(1*time.Minute, func() *resource.RetryError {
			out, err := conn.GetBucketNotificationConfiguration(&s3.GetBucketNotificationConfigurationRequest{
				Bucket: aws.String(rs.Primary.ID),
			})

			if err != nil {
				return resource.NonRetryableError(fmt.Errorf("GetBucketNotification error: %v", err))
			}

			eventSlice := sort.StringSlice(events)
			eventSlice.Sort()

			outputFunctions := out.LambdaFunctionConfigurations
			matched := false
			for _, outputFunc := range outputFunctions {
				if *outputFunc.Id == i {
					matched = true

					if *outputFunc.LambdaFunctionArn != funcArn {
						return resource.RetryableError(fmt.Errorf("bad lambda function arn, expected: %s, got %#v", funcArn, *outputFunc.LambdaFunctionArn))
					}

					if filters != nil {
						if !reflect.DeepEqual(filters, outputFunc.Filter.Key) {
							return resource.RetryableError(fmt.Errorf("bad notification filters, expected: %#v, got %#v", filters, outputFunc.Filter.Key))
						}
					} else {
						if outputFunc.Filter != nil {
							return resource.RetryableError(fmt.Errorf("bad notification filters, expected: nil, got %#v", outputFunc.Filter))
						}
					}

					outputEventSlice := sort.StringSlice(aws.StringValueSlice(outputFunc.Events))
					outputEventSlice.Sort()
					if !reflect.DeepEqual(eventSlice, outputEventSlice) {
						return resource.RetryableError(fmt.Errorf("bad notification events, expected: %#v, got %#v", events, outputEventSlice))
					}
				}
			}

			if !matched {
				return resource.RetryableError(fmt.Errorf("No match lambda function configurations: %#v", out))
			}

			return nil
		})

		return err
	}
}

示例#22
文件: kuberuntime_manager_test.go 项目: ncdc/kubernetes

func verifyFakeContainerList(fakeRuntime *apitest.FakeRuntimeService, expected []string) ([]string, bool) {
	actual := []string{}
	for _, c := range fakeRuntime.Containers {
		actual = append(actual, c.GetId())
	}
	sort.Sort(sort.StringSlice(actual))
	sort.Sort(sort.StringSlice(expected))

	return actual, reflect.DeepEqual(expected, actual)
}

示例#23
文件: registry_message_matcher.go 项目: emc-xchallenge/route-emitter

func (m *registryMessageMatcher) Match(a interface{}) (success bool, err error) {
	actual, ok := a.(routing_table.RegistryMessage)
	if !ok {
		return false, fmt.Errorf("%s is not a routing_table.RegistryMessage", format.Object(actual, 1))
	}

	sort.Sort(sort.StringSlice(m.expected.URIs))
	sort.Sort(sort.StringSlice(actual.URIs))
	return reflect.DeepEqual(actual, m.expected), nil
}

示例#24
文件: fake_docker_client.go 项目: Clarifai/kubernetes

func (f *FakeDockerClient) AssertStopped(stopped []string) error {
	f.Lock()
	defer f.Unlock()
	sort.StringSlice(stopped).Sort()
	sort.StringSlice(f.Stopped).Sort()
	if !reflect.DeepEqual(stopped, f.Stopped) {
		return fmt.Errorf("expected %#v, got %#v", stopped, f.Stopped)
	}
	return nil
}

示例#25
文件: router_test.go 项目: hartsock/go-swagger

func TestRouterMiddleware(t *testing.T) {
	spec, api := petstore.NewAPI(t)
	context := NewContext(spec, api, nil)
	mw := newRouter(context, http.HandlerFunc(terminator))

	recorder := httptest.NewRecorder()
	request, _ := http.NewRequest("GET", "/api/pets", nil)

	mw.ServeHTTP(recorder, request)
	assert.Equal(t, 200, recorder.Code)

	recorder = httptest.NewRecorder()
	request, _ = http.NewRequest("DELETE", "/api/pets", nil)

	mw.ServeHTTP(recorder, request)
	assert.Equal(t, http.StatusMethodNotAllowed, recorder.Code)

	methods := strings.Split(recorder.Header().Get("Allow"), ",")
	sort.Sort(sort.StringSlice(methods))
	assert.Equal(t, "GET,POST", strings.Join(methods, ","))

	recorder = httptest.NewRecorder()
	request, _ = http.NewRequest("GET", "/nopets", nil)

	mw.ServeHTTP(recorder, request)
	assert.Equal(t, http.StatusNotFound, recorder.Code)

	spec, api = petstore.NewRootAPI(t)
	context = NewContext(spec, api, nil)
	mw = newRouter(context, http.HandlerFunc(terminator))

	recorder = httptest.NewRecorder()
	request, _ = http.NewRequest("GET", "/pets", nil)

	mw.ServeHTTP(recorder, request)
	assert.Equal(t, 200, recorder.Code)

	recorder = httptest.NewRecorder()
	request, _ = http.NewRequest("DELETE", "/pets", nil)

	mw.ServeHTTP(recorder, request)
	assert.Equal(t, http.StatusMethodNotAllowed, recorder.Code)

	methods = strings.Split(recorder.Header().Get("Allow"), ",")
	sort.Sort(sort.StringSlice(methods))
	assert.Equal(t, "GET,POST", strings.Join(methods, ","))

	recorder = httptest.NewRecorder()
	request, _ = http.NewRequest("GET", "/nopets", nil)

	mw.ServeHTTP(recorder, request)
	assert.Equal(t, http.StatusNotFound, recorder.Code)

}

示例#26

func Test_MultiNodeJoinRemove(t *testing.T) {
	s0 := mustNewStore(true)
	defer os.RemoveAll(s0.Path())
	if err := s0.Open(true); err != nil {
		t.Fatalf("failed to open node for multi-node test: %s", err.Error())
	}
	defer s0.Close(true)
	s0.WaitForLeader(10 * time.Second)

	s1 := mustNewStore(true)
	defer os.RemoveAll(s1.Path())
	if err := s1.Open(false); err != nil {
		t.Fatalf("failed to open node for multi-node test: %s", err.Error())
	}
	defer s1.Close(true)

	// Get sorted list of cluster nodes.
	storeNodes := []string{s0.Addr().String(), s1.Addr().String()}
	sort.StringSlice(storeNodes).Sort()

	// Join the second node to the first.
	if err := s0.Join(s1.Addr().String()); err != nil {
		t.Fatalf("failed to join to node at %s: %s", s0.Addr().String(), err.Error())
	}

	nodes, err := s0.Nodes()
	if err != nil {
		t.Fatalf("failed to get nodes: %s", err.Error())
	}
	sort.StringSlice(nodes).Sort()

	if len(nodes) != len(storeNodes) {
		t.Fatalf("size of cluster is not correct")
	}
	if storeNodes[0] != nodes[0] && storeNodes[1] != nodes[1] {
		t.Fatalf("cluster does not have correct nodes")
	}

	// Remove a node.
	if err := s0.Remove(s1.Addr().String()); err != nil {
		t.Fatalf("failed to remove %s from cluster: %s", s1.Addr().String(), err.Error())
	}

	nodes, err = s0.Nodes()
	if err != nil {
		t.Fatalf("failed to get nodes post remove: %s", err.Error())
	}
	if len(nodes) != 1 {
		t.Fatalf("size of cluster is not correct post remove")
	}
	if s0.Addr().String() != nodes[0] {
		t.Fatalf("cluster does not have correct nodes post remove")
	}
}

示例#27
文件: request.go 项目: gotajuly/aliyun-oss-golang-sdk-linthub

// Signature calculate Signature
func (req *Request) Signature() (sig string, err error) {
	sigStr := req.Method + "\n"
	var cntMd5 string
	if req.Body != nil {
		cntMd5, err = Base64AndMd5(req.Body)
		if err != nil {
			Logger.Error(err.Error())
			return
		}
	}
	sigStr += cntMd5 + "\n"
	sigStr += req.CntType + "\n"
	sigStr += req.Date + "\n"
	var ossHeaders []string
	var ossHeadersStr string
	if req.XOSSes != nil {
		var ossHeaderKeys []string
		//fmt.Println("req.XOSSes : ", req.XOSSes)
		for k := range req.XOSSes {
			ossHeaderKeys = append(ossHeaderKeys, strings.ToLower(k))
		}
		sort.Sort(sort.StringSlice(ossHeaderKeys))
		//fmt.Println("ossheaderKeys:", ossHeaderKeys)
		for i := 0; i < len(ossHeaderKeys); i++ {
			//fmt.Println("ossHeaderKeys[i]:", i, ": ", ossHeaderKeys[i])
			ossHeaders = append(ossHeaders, ossHeaderKeys[i]+":"+req.XOSSes[ossHeaderKeys[i]])
		}
		ossHeadersStr = strings.Join(ossHeaders, "\n")
		ossHeadersStr += "\n"
	}
	var overrideStrs []string
	if req.Override != nil {
		for k, v := range req.Override {
			overrideStrs = append(overrideStrs, k+"="+v)
		}
	}
	var subResStr string
	var resourcesStr string
	if req.SubRes != nil {
		subRes := append(req.SubRes, overrideStrs...)
		sort.Sort(sort.StringSlice(subRes))
		subResStr = strings.Join(subRes, "&")
		subResStr = "?" + subResStr
	}
	resourcesStr = req.Resource + subResStr
	sigStr += ossHeadersStr + resourcesStr
	//fmt.Println("sigStr:", sigStr)
	sig, err = Base64AndHmacSha1([]byte(accessKeySecret), []byte(sigStr))
	if err != nil {
		Logger.Error(err.Error())
		return
	}
	return
}

示例#28
文件: docker_cli_exec_test.go 项目: shakamunyi/docker

func (s *DockerSuite) TestExecCgroup(c *check.C) {
	// Not applicable on Windows - using Linux specific functionality
	testRequires(c, NotUserNamespace)
	testRequires(c, DaemonIsLinux)
	dockerCmd(c, "run", "-d", "--name", "testing", "busybox", "top")

	out, _ := dockerCmd(c, "exec", "testing", "cat", "/proc/1/cgroup")
	containerCgroups := sort.StringSlice(strings.Split(out, "\n"))

	var wg sync.WaitGroup
	var mu sync.Mutex
	execCgroups := []sort.StringSlice{}
	errChan := make(chan error)
	// exec a few times concurrently to get consistent failure
	for i := 0; i < 5; i++ {
		wg.Add(1)
		go func() {
			out, _, err := dockerCmdWithError("exec", "testing", "cat", "/proc/self/cgroup")
			if err != nil {
				errChan <- err
				return
			}
			cg := sort.StringSlice(strings.Split(out, "\n"))

			mu.Lock()
			execCgroups = append(execCgroups, cg)
			mu.Unlock()
			wg.Done()
		}()
	}
	wg.Wait()
	close(errChan)

	for err := range errChan {
		c.Assert(err, checker.IsNil)
	}

	for _, cg := range execCgroups {
		if !reflect.DeepEqual(cg, containerCgroups) {
			fmt.Println("exec cgroups:")
			for _, name := range cg {
				fmt.Printf(" %s\n", name)
			}

			fmt.Println("container cgroups:")
			for _, name := range containerCgroups {
				fmt.Printf(" %s\n", name)
			}
			c.Fatal("cgroups mismatched")
		}
	}
}

示例#29
文件: function.go 项目: wolfeidau/apex

// configChanged checks if function configuration differs from configuration stored in AWS Lambda
func (f *Function) configChanged(config *lambda.GetFunctionOutput) bool {
	type diffConfig struct {
		Description string
		Memory      int64
		Timeout     int64
		Role        string
		Runtime     string
		Handler     string
		VPC         vpc.VPC
	}

	localConfig := &diffConfig{
		Description: f.Description,
		Memory:      f.Memory,
		Timeout:     f.Timeout,
		Role:        f.Role,
		Runtime:     f.Runtime,
		Handler:     f.Handler,
		VPC: vpc.VPC{
			Subnets:        f.VPC.Subnets,
			SecurityGroups: f.VPC.SecurityGroups,
		},
	}

	remoteConfig := &diffConfig{
		Description: *config.Configuration.Description,
		Memory:      *config.Configuration.MemorySize,
		Timeout:     *config.Configuration.Timeout,
		Role:        *config.Configuration.Role,
		Runtime:     *config.Configuration.Runtime,
		Handler:     *config.Configuration.Handler,
	}

	// SDK is inconsistent here. VpcConfig can be nil or empty struct.
	remoteConfig.VPC = vpc.VPC{Subnets: []string{}, SecurityGroups: []string{}}
	if config.Configuration.VpcConfig != nil {
		remoteConfig.VPC = vpc.VPC{
			Subnets:        aws.StringValueSlice(config.Configuration.VpcConfig.SubnetIds),
			SecurityGroups: aws.StringValueSlice(config.Configuration.VpcConfig.SecurityGroupIds),
		}
	}

	// don't make any assumptions about the order AWS stores the subnets or security groups
	sort.StringSlice(remoteConfig.VPC.Subnets).Sort()
	sort.StringSlice(localConfig.VPC.Subnets).Sort()
	sort.StringSlice(remoteConfig.VPC.SecurityGroups).Sort()
	sort.StringSlice(localConfig.VPC.SecurityGroups).Sort()

	localConfigJSON, _ := json.Marshal(localConfig)
	remoteConfigJSON, _ := json.Marshal(remoteConfig)
	return string(localConfigJSON) != string(remoteConfigJSON)
}

示例#30
文件: helpers.go 项目: maxwhale/docker-gogs-centos

func sliceEq(left, right []string) bool {
	if len(left) != len(right) {
		return false
	}
	sort.Sort(sort.StringSlice(left))
	sort.Sort(sort.StringSlice(right))
	for i := 0; i < len(left); i++ {
		if left[i] != right[i] {
			return false
		}
	}
	return true
}

展开阅读全文