當前位置: 首頁>>代碼示例>>Golang>>正文


Golang pretty.Compare函數代碼示例

本文整理匯總了Golang中github.com/kylelemons/godebug/pretty.Compare函數的典型用法代碼示例。如果您正苦於以下問題:Golang Compare函數的具體用法?Golang Compare怎麽用?Golang Compare使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了Compare函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: TestCategories

func TestCategories(t *testing.T) {
	db := mustDB(t)
	a := &Category{Name: "a"}
	if err := db.SaveCategory(a); err != nil {
		t.Fatal(err)
	}
	b := &Category{Name: "b", ParentID: a.ID}
	if err := db.SaveCategory(b); err != nil {
		t.Fatal(err)
	}
	want := CategoryMap{a.ID: a, b.ID: b}
	if got, err := db.Categories(); err != nil {
		t.Error(err)
	} else if diff := pretty.Compare(got, want); diff != "" {
		t.Fatal(diff)
	}
	a.Name, b.Name = "c", "d"
	if err := db.SaveCategory(a); err != nil {
		t.Fatal(err)
	} else if err := db.SaveCategory(b); err != nil {
		t.Fatal(err)
	} else if got, err := db.Categories(); err != nil {
		t.Error(err)
	} else if diff := pretty.Compare(got, want); diff != "" {
		t.Fatal(diff)
	}
}
開發者ID:hiroapp,項目名稱:cli,代碼行數:27,代碼來源:db_test.go

示例2: TestInstrs

// TestInstrs tests that each instruction behaves as expected through one
// instruction cycle.
func TestInstrs(t *testing.T) {
	for _, tc := range instructions {
		var m []*metrics.Metric
		m = append(m,
			metrics.NewMetric("foo", "test", metrics.Counter),
			metrics.NewMetric("bar", "test", metrics.Counter))

		v := New(tc.name, tc.re, tc.str, m, []instr{tc.i}, true)
		v.t = new(thread)
		v.t.stack = make([]interface{}, 0)
		for _, item := range tc.reversedStack {
			v.t.Push(item)
		}
		v.t.matches = make(map[int][]string, 0)
		v.input = "aaaab"
		v.execute(v.t, tc.i)

		diff := pretty.Compare(tc.expectedStack, v.t.stack)
		if len(diff) > 0 {
			t.Errorf("%s: unexpected virtual machine stack state.\n%s", tc.name, diff)
		}
		// patch in the thread stack because otherwise the test table is huge
		tc.expectedThread.stack = tc.expectedStack

		if diff = pretty.Compare(v.t, &tc.expectedThread); len(diff) > 0 {
			t.Errorf("%s: unexpected virtual machine thread state.\n%s", tc.name, diff)
		}
	}
}
開發者ID:nulleins0130,項目名稱:mtail,代碼行數:31,代碼來源:vm_test.go

示例3: runOAuth2IdentityTests

func runOAuth2IdentityTests(t *testing.T, conn oauth2Connector, tests []oauth2IdentityTest) {
	for i, tt := range tests {
		f := func(req *http.Request) (*http.Response, error) {
			resp, ok := tt.urlResps[req.URL.String()]
			if !ok {
				return nil, fmt.Errorf("unexpected request URL: %s", req.URL.String())
			}
			return &http.Response{
				StatusCode: resp.statusCode,
				Body:       ioutil.NopCloser(strings.NewReader(resp.body)),
			}, nil
		}
		got, err := conn.Identity(fakeClient(f))
		if tt.wantErr == nil {
			if err != nil {
				t.Errorf("case %d: failed to get identity=%v", i, err)
				continue
			}
			if diff := pretty.Compare(tt.want, got); diff != "" {
				t.Errorf("case %d: Compare(want, got) = %v", i, diff)
			}
		} else {
			if err == nil {
				t.Errorf("case %d: want error=%v, got=<nil>", i, tt.wantErr)
				continue
			}
			if diff := pretty.Compare(tt.wantErr, err); diff != "" {
				t.Errorf("case %d: Compare(wantErr, gotErr) = %v", i, diff)
			}
		}
	}
}
開發者ID:GamerockSA,項目名稱:dex,代碼行數:32,代碼來源:connector_oauth2_test.go

示例4: TestMetricToGraphite

func TestMetricToGraphite(t *testing.T) {
	ts, terr := time.Parse("2006/01/02 15:04:05", "2012/07/24 10:14:00")
	if terr != nil {
		t.Errorf("time parse error: %s", terr)
	}

	scalarMetric := metrics.NewMetric("foo", "prog", metrics.Counter)
	d, _ := scalarMetric.GetDatum()
	d.Set(37, ts)
	r := FakeSocketWrite(metricToGraphite, scalarMetric)
	expected := []string{"prog.foo 37 1343124840\n"}
	diff := pretty.Compare(r, expected)
	if len(diff) > 0 {
		t.Errorf("String didn't match:\n%s", diff)
	}

	dimensionedMetric := metrics.NewMetric("bar", "prog", metrics.Gauge, "l")
	d, _ = dimensionedMetric.GetDatum("quux")
	d.Set(37, ts)
	d, _ = dimensionedMetric.GetDatum("snuh")
	d.Set(37, ts)
	r = FakeSocketWrite(metricToGraphite, dimensionedMetric)
	expected = []string{
		"prog.bar.l.quux 37 1343124840\n",
		"prog.bar.l.snuh 37 1343124840\n"}
	diff = pretty.Compare(r, expected)
	if len(diff) > 0 {
		t.Errorf("String didn't match:\n%s", diff)
	}
}
開發者ID:hanscj1,項目名稱:mtail,代碼行數:30,代碼來源:export_test.go

示例5: TestNewPasswordReset

func TestNewPasswordReset(t *testing.T) {
	clock = clockwork.NewFakeClock()
	defer func() {
		clock = clockwork.NewRealClock()
	}()

	now := clock.Now()

	issuer, _ := url.Parse("http://example.com")
	clientID := "myclient"
	usr := User{ID: "123456", Email: "[email protected]"}
	callback := "http://client.example.com/callback"
	expires := time.Hour * 3
	password := Password("passy")

	tests := []struct {
		user     User
		password Password
		issuer   url.URL
		clientID string
		callback string
		expires  time.Duration
		want     jose.Claims
	}{
		{
			issuer:   *issuer,
			clientID: clientID,
			user:     usr,
			callback: callback,
			expires:  expires,
			password: password,
			want: map[string]interface{}{
				"iss": issuer.String(),
				"aud": clientID,
				ClaimPasswordResetCallback: callback,
				ClaimPasswordResetPassword: string(password),
				"exp": float64(now.Add(expires).Unix()),
				"sub": usr.ID,
				"iat": float64(now.Unix()),
			},
		},
	}

	for i, tt := range tests {
		cbURL, err := url.Parse(tt.callback)
		if err != nil {
			t.Fatalf("case %d: non-nil err: %q", i, err)
		}
		ev := NewPasswordReset(tt.user, tt.password, tt.issuer, tt.clientID, *cbURL, tt.expires)

		if diff := pretty.Compare(tt.want, ev.claims); diff != "" {
			t.Errorf("case %d: Compare(want, got): %v", i, diff)
		}

		if diff := pretty.Compare(ev.Password(), password); diff != "" {
			t.Errorf("case %d: Compare(want, got): %v", i, diff)
		}
	}
}
開發者ID:no2key,項目名稱:dex,代碼行數:59,代碼來源:password_test.go

示例6: TestRouteLookup

func TestRouteLookup(t *testing.T) {
	if diff := pretty.Compare(testRoutes["test1"], testRoutes.Lookup(net.IP{10, 1, 0, 1})); diff != "" {
		t.Errorf("routes.Lookup 10.1.0.1:\n%s", diff)
	}
	if diff := pretty.Compare(testRoutes["internal"], testRoutes.Lookup(net.IP{10, 99, 0, 1})); diff != "" {
		t.Errorf("routes.Lookup 10.99.0.1:\n%s", diff)
	}
	if diff := pretty.Compare(nil, testRoutes.Lookup(net.IP{192, 0, 2, 1})); diff != "" {
		t.Errorf("routes.Lookup 192.0.2.1:\n%s", diff)
	}
}
開發者ID:qmsk,項目名稱:clusterf,代碼行數:11,代碼來源:route_test.go

示例7: TestRevokeRefreshToken

func TestRevokeRefreshToken(t *testing.T) {
	tests := []struct {
		userID   string
		toRevoke string
		before   []string // clientIDs expected before the change.
		after    []string // clientIDs expected after the change.
	}{
		{"ID-1", goodClientID, []string{goodClientID}, []string{}},
		{"ID-2", goodClientID, []string{goodClientID}, []string{}},
	}

	api, _ := makeTestFixtures(false)

	listClientsWithRefreshTokens := func(creds Creds, userID string) ([]string, error) {
		clients, err := api.ListClientsWithRefreshTokens(creds, userID)
		if err != nil {
			return nil, err
		}
		clientIDs := make([]string, len(clients))
		for i, client := range clients {
			clientIDs[i] = client.ClientID
		}
		sort.Strings(clientIDs)
		return clientIDs, nil
	}

	for i, tt := range tests {
		creds := Creds{User: user.User{ID: tt.userID}}

		gotBefore, err := listClientsWithRefreshTokens(creds, tt.userID)
		if err != nil {
			t.Errorf("case %d: list clients failed: %v", i, err)
		} else {
			if diff := pretty.Compare(tt.before, gotBefore); diff != "" {
				t.Errorf("case %d: before exp!=got: %s", i, diff)
			}
		}

		if err := api.RevokeRefreshTokensForClient(creds, tt.userID, tt.toRevoke); err != nil {
			t.Errorf("case %d: failed to revoke client: %v", i, err)
			continue
		}

		gotAfter, err := listClientsWithRefreshTokens(creds, tt.userID)
		if err != nil {
			t.Errorf("case %d: list clients failed: %v", i, err)
		} else {
			if diff := pretty.Compare(tt.after, gotAfter); diff != "" {
				t.Errorf("case %d: after exp!=got: %s", i, diff)
			}
		}
	}
}
開發者ID:Tecsisa,項目名稱:dex,代碼行數:53,代碼來源:api_test.go

示例8: TestMetricToCollectd

func TestMetricToCollectd(t *testing.T) {
	ts, terr := time.Parse("2006/01/02 15:04:05", "2012/07/24 10:14:00")
	if terr != nil {
		t.Errorf("time parse error: %s", terr)
	}
	ms := metrics.NewStore()

	scalarMetric := metrics.NewMetric("foo", "prog", metrics.Counter)
	d, _ := scalarMetric.GetDatum()
	d.Set(37, ts)
	ms.Add(scalarMetric)

	r := FakeSocketWrite(metricToCollectd, scalarMetric)
	expected := []string{"PUTVAL \"gunstar/mtail-prog/counter-foo\" interval=60 1343124840:37\n"}
	diff := pretty.Compare(r, expected)
	if len(diff) > 0 {
		t.Errorf("String didn't match:\n%s", diff)
	}

	dimensionedMetric := metrics.NewMetric("bar", "prog", metrics.Gauge, "label")
	d, _ = dimensionedMetric.GetDatum("quux")
	d.Set(37, ts)
	d, _ = dimensionedMetric.GetDatum("snuh")
	d.Set(37, ts)
	ms.ClearMetrics()
	ms.Add(dimensionedMetric)

	r = FakeSocketWrite(metricToCollectd, dimensionedMetric)
	expected = []string{
		"PUTVAL \"gunstar/mtail-prog/gauge-bar-label-quux\" interval=60 1343124840:37\n",
		"PUTVAL \"gunstar/mtail-prog/gauge-bar-label-snuh\" interval=60 1343124840:37\n"}
	diff = pretty.Compare(r, expected)
	if len(diff) > 0 {
		t.Errorf("String didn't match:\n%s", diff)
	}

	timingMetric := metrics.NewMetric("foo", "prog", metrics.Timer)
	d, _ = timingMetric.GetDatum()
	d.Set(123, ts)
	ms.Add(timingMetric)

	r = FakeSocketWrite(metricToCollectd, timingMetric)
	expected = []string{"PUTVAL \"gunstar/mtail-prog/gauge-foo\" interval=60 1343124840:123\n"}
	diff = pretty.Compare(r, expected)
	if len(diff) > 0 {
		t.Errorf("String didn't match:\n%s", diff)
	}
}
開發者ID:yanghongkjxy,項目名稱:mtail,代碼行數:48,代碼來源:export_test.go

示例9: TestClientMetadataMarshalRoundTrip

func TestClientMetadataMarshalRoundTrip(t *testing.T) {
	tests := []ClientMetadata{
		{
			RedirectURIs: []url.URL{
				{Scheme: "https", Host: "example.com", Path: "/callback"},
			},
			LogoURI: &url.URL{Scheme: "https", Host: "example.com", Path: "/logo"},
			RequestObjectOptions: JWAOptions{
				EncryptionAlg: "RSA1_5",
				EncryptionEnc: "A128CBC-HS256",
			},
			ApplicationType:         "native",
			TokenEndpointAuthMethod: "client_secret_basic",
		},
	}

	for i, want := range tests {
		data, err := json.Marshal(&want)
		if err != nil {
			t.Errorf("case %d: failed to marshal metadata: %v", i, err)
			continue
		}
		var got ClientMetadata
		if err := json.Unmarshal(data, &got); err != nil {
			t.Errorf("case %d: failed to unmarshal metadata: %v", i, err)
			continue
		}
		if diff := pretty.Compare(want, got); diff != "" {
			t.Errorf("case %d: struct did not survive a marshaling round trip: %s", i, diff)
		}
	}
}
開發者ID:RomainVabre,項目名稱:origin,代碼行數:32,代碼來源:client_test.go

示例10: TestTagMapping

func TestTagMapping(t *testing.T) {
	mapper := NewTagMapper("db", "json")
	data := TestMappingStruct{}
	val := reflect.ValueOf(data)
	expected := map[string][]int{
		"NoTag":                        {0},
		"json_tag":                     {1},
		"db_tag":                       {2},
		"both_tag_db":                  {3},
		"String":                       {4},
		"StringPtr":                    {5},
		"Time":                         {6},
		"TimePtr":                      {7},
		"Int":                          {8},
		"IntPtr":                       {9},
		"Float":                        {10},
		"FloatPtr":                     {11},
		"Bool":                         {12},
		"BoolPtr":                      {13},
		"IncludedStruct.IncludedField": {15, 0},
		"IncludedStruct.NoTag":         {15, 1},
		"IncludedStructSingleField":    {16, 0},
	}
	result, err := mapper.KeyIndexes(val)
	if err != nil {
		t.Errorf("Unexpected error: %s", err)
	}
	if !reflect.DeepEqual(result.Indexes, expected) {
		t.Errorf("Unexpected Results\n%s", pretty.Compare(result, expected))

	}
}
開發者ID:snikch,項目名稱:api,代碼行數:32,代碼來源:mapper_test.go

示例11: TestInhibitRuleGC

func TestInhibitRuleGC(t *testing.T) {
	// TODO(fabxc): add now() injection function to Resolved() to remove
	// dependency on machine time in this test.
	now := time.Now()
	newAlert := func(start, end time.Duration) *types.Alert {
		return &types.Alert{
			Alert: model.Alert{
				Labels:   model.LabelSet{"a": "b"},
				StartsAt: now.Add(start * time.Minute),
				EndsAt:   now.Add(end * time.Minute),
			},
		}
	}

	before := map[model.Fingerprint]*types.Alert{
		0: newAlert(-10, -5),
		1: newAlert(10, 20),
		2: newAlert(-10, 10),
		3: newAlert(-10, -1),
	}
	after := map[model.Fingerprint]*types.Alert{
		1: newAlert(10, 20),
		2: newAlert(-10, 10),
	}

	r := &InhibitRule{scache: before}
	r.gc()

	if !reflect.DeepEqual(r.scache, after) {
		t.Errorf("Unexpected cache state after GC")
		t.Errorf(pretty.Compare(r.scache, after))
	}
}
開發者ID:farcaller,項目名稱:alertmanager,代碼行數:33,代碼來源:inhibit_test.go

示例12: TestEmitLabelSet

func TestEmitLabelSet(t *testing.T) {
	m := NewMetric("test", "prog", Gauge, "foo", "bar", "quux")
	c := make(chan *LabelSet)

	ts := time.Now().UTC()

	var expectedLabels []map[string]string
	for _, tc := range labelSetTests {
		d, _ := m.GetDatum(tc.values...)
		d.Set(37, ts)
		expectedLabels = append(expectedLabels, tc.expectedLabels)
	}

	go m.EmitLabelSets(c)

	var labels []map[string]string
	for ls := range c {
		labels = append(labels, ls.Labels)
	}

	diff := pretty.Compare(labels, expectedLabels)
	if len(diff) > 0 {
		t.Errorf("Labels don't match:\n%s", diff)
	}
}
開發者ID:yanghongkjxy,項目名稱:mtail,代碼行數:25,代碼來源:metric_test.go

示例13: TestPage

func TestPage(t *testing.T) {
	p := &Page{
		URL:          "https://www.example.com",
		HTML:         testPage,
		MetaReader:   &MetaReader{},
		SchemaReader: &SchemaReader{},
	}
	p.PageReader = &PageReader{page: p}
	mockbytes := []byte(testPage)
	p.Read(mockbytes)
	if p.Title != "TestPage" {
		t.Errorf("Expected page title %s", p.Title)
	}
	if p.Text != "Blend-O-Matic $19.95 Based on 25 user ratings Spinal Tap One of the loudest bands ever reunites for an unforgettable two-day show. Event date: May 8, 7:30pm Alice Jones Bob Smith" {
		t.Errorf("unexpected page text %s", p.Text)
	}
	for i, m := range p.MetaData() {
		if !reflect.DeepEqual(m, meta[i]) {
			t.Errorf(`Meta result item %d differs:
                expected %+v
                got %+v`, i, meta[i], m)
		}
	}
	for i, s := range p.SchemaData() {
		if !reflect.DeepEqual(s, schema[i]) {
			t.Error(pretty.Compare(s, schema[i]))
		}
	}
}
開發者ID:tborg,項目名稱:metascraper,代碼行數:29,代碼來源:page_test.go

示例14: TestParserRoundTrip

func TestParserRoundTrip(t *testing.T) {
	for _, tc := range mtailPrograms {
		p := newParser(tc.name, strings.NewReader(tc.program), &metrics.Store{})
		r := mtailParse(p)

		if r != 0 || p.root == nil || len(p.errors) > 0 {
			t.Errorf("1st pass parse errors:\n")
			for _, e := range p.errors {
				t.Errorf("\t%s\n", e)
			}
			continue
		}

		u := Unparser{}
		output := u.Unparse(p.root)

		p2 := newParser(tc.name+" 2", strings.NewReader(output), &metrics.Store{})
		r = mtailParse(p2)
		if r != 0 || p2.root == nil || len(p2.errors) > 0 {
			t.Errorf("2nd pass parse errors:\n")
			for _, e := range p2.errors {
				t.Errorf("\t%s\n", e)
			}
			continue
		}

		u = Unparser{}
		output2 := u.Unparse(p2.root)

		diff := pretty.Compare(output2, output)
		if len(diff) > 0 {
			t.Errorf("Round trip failed to generate same output.\n%s", diff)
		}
	}
}
開發者ID:4honor,項目名稱:mtail,代碼行數:35,代碼來源:parser_test.go

示例15: TestRefreshTokenRepoClientsWithRefreshTokens

func TestRefreshTokenRepoClientsWithRefreshTokens(t *testing.T) {
	tests := []struct {
		clientIDs []string
	}{
		{clientIDs: []string{"client1", "client2"}},
		{clientIDs: []string{"client1"}},
		{clientIDs: []string{}},
	}

	for i, tt := range tests {
		repo := newRefreshRepo(t, testRefreshUsers, testRefreshClients)

		for _, clientID := range tt.clientIDs {
			_, err := repo.Create(testRefreshUserID, clientID, testRefreshConnectorID, []string{"openid"})
			if err != nil {
				t.Fatalf("case %d: client_id: %s couldn't create refresh token: %v", i, clientID, err)
			}
		}

		clients, err := repo.ClientsWithRefreshTokens(testRefreshUserID)
		if err != nil {
			t.Fatalf("case %d: unexpected error fetching clients %q", i, err)
		}
		var clientIDs []string
		for _, client := range clients {
			clientIDs = append(clientIDs, client.Credentials.ID)
		}
		sort.Strings(clientIDs)

		if diff := pretty.Compare(clientIDs, tt.clientIDs); diff != "" {
			t.Errorf("case %d: Compare(want, got): %v", i, diff)
		}
	}
}
開發者ID:Tecsisa,項目名稱:dex,代碼行數:34,代碼來源:refresh_repo_test.go


注:本文中的github.com/kylelemons/godebug/pretty.Compare函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。