• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Golang pretty.Diff函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/kr/pretty.Diff函数的典型用法代码示例。如果您正苦于以下问题:Golang Diff函数的具体用法?Golang Diff怎么用?Golang Diff使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了Diff函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: TestExecutor

func TestExecutor(t *testing.T) {
	tests := []struct {
		desc      string
		err       bool
		shouldLog bool
		log       []string
	}{
		{
			desc: "With error in state machine execution",
			err:  true,
		},
		{
			desc:      "Success",
			shouldLog: true,
			log: []string{
				"StateMachine[tester]: StateFn(Start) starting",
				"StateMachine[tester]: StateFn(Start) finished",
				"StateMachine[tester]: StateFn(Middle) starting",
				"StateMachine[tester]: StateFn(Middle) finished",
				"StateMachine[tester]: StateFn(End) starting",
				"StateMachine[tester]: StateFn(End) finished",
				"StateMachine[tester]: Execute() completed with no issues",
				"StateMachine[tester]: The following is the StateFn's called with this execution:",
				"StateMachine[tester]: \tStart",
				"StateMachine[tester]: \tMiddle",
				"StateMachine[tester]: \tEnd",
			},
		},
	}

	sm := &StateMachine{}
	for _, test := range tests {
		sm.err = test.err
		l := &logging{}
		exec := New("tester", sm.Start, Reset(sm.reset), LogFacility(l.Log))
		if test.shouldLog {
			exec.Log(true)
		} else {
			exec.Log(false)
		}

		err := exec.Execute()
		switch {
		case err == nil && test.err:
			t.Errorf("Test %q: got err == nil, want err != nil", test.desc)
			continue
		case err != nil && !test.err:
			t.Errorf("Test %q: got err != %q, want err == nil", test.desc, err)
			continue
		}

		if diff := pretty.Diff(sm.callTrace, exec.Nodes()); len(diff) != 0 {
			t.Errorf("Test %q: node trace was no accurate got/want diff:\n%s", test.desc, strings.Join(diff, "\n"))
		}

		if diff := pretty.Diff(l.msgs, test.log); len(diff) != 0 {
			t.Errorf("Test %q: log was not as expected:\n%s", test.desc, strings.Join(diff, "\n"))
		}
	}
}
开发者ID:johnsiilver,项目名称:golib,代码行数:60,代码来源:statemachine_test.go


示例2: TestHistogramPrometheus

func TestHistogramPrometheus(t *testing.T) {
	u := func(v int) *uint64 {
		n := uint64(v)
		return &n
	}

	f := func(v int) *float64 {
		n := float64(v)
		return &n
	}

	h := NewHistogram(Metadata{}, time.Hour, 10, 1)
	h.RecordValue(1)
	h.RecordValue(5)
	h.RecordValue(5)
	h.RecordValue(10)
	h.RecordValue(15000) // counts as 10
	act := *h.ToPrometheusMetric().Histogram

	expSum := float64(1*1 + 2*5 + 2*10)

	exp := prometheusgo.Histogram{
		SampleCount: u(5),
		SampleSum:   &expSum,
		Bucket: []*prometheusgo.Bucket{
			{CumulativeCount: u(1), UpperBound: f(1)},
			{CumulativeCount: u(3), UpperBound: f(5)},
			{CumulativeCount: u(5), UpperBound: f(10)},
		},
	}

	if !reflect.DeepEqual(act, exp) {
		t.Fatalf("expected differs from actual: %s", pretty.Diff(exp, act))
	}
}
开发者ID:knz,项目名称:cockroach,代码行数:35,代码来源:metric_test.go


示例3: testOne

func testOne(t *testing.T, input []byte) {
	templ := Template{}
	err := json.Unmarshal(input, &templ)
	if err != nil {
		t.Errorf("decode: %s", err)
		return
	}

	output, err := json.Marshal(templ)
	if err != nil {
		t.Errorf("marshal: %s", err)
		return
	}

	parsedInput := map[string]interface{}{}
	json.Unmarshal(input, &parsedInput)

	parsedOutput := map[string]interface{}{}
	json.Unmarshal(output, &parsedOutput)

	diffs := pretty.Diff(parsedInput, parsedOutput)
	for _, diff := range diffs {
		t.Errorf("%s", diff)
	}
}
开发者ID:dmreiland,项目名称:go-cloudformation,代码行数:25,代码来源:roundtrip_test.go


示例4: update_local_config_handler

func update_local_config_handler(w http.ResponseWriter, req *http.Request, strings ...string) Reply {
	conf := &config.ProxyConfig{}

	err := conf.LoadIO(req.Body)
	if err != nil {
		err = errors.NewKeyError(req.URL.String(), http.StatusBadRequest,
			fmt.Sprintf("conf: could not parse config: %q", err))
		return Reply{
			err:    err,
			status: http.StatusBadRequest,
		}
	}

	conf.Proxy.RedirectToken = proxy.bctl.Conf.Proxy.RedirectToken
	diff := pretty.Diff(proxy.bctl.Conf, conf)
	for _, d := range diff {
		log.Printf("update_local_config_handler: diff: %s\n", d)
	}

	proxy.bctl.Lock()
	proxy.bctl.Conf = conf
	proxy.bctl.DisableConfigUpdateUntil = time.Now().Add(time.Second * time.Duration(conf.Proxy.DisableConfigUpdateForSeconds))
	proxy.bctl.Unlock()

	log.Printf("update_local_config_handler: next automatic config update is only allowed in %d seconds at %s\n",
		conf.Proxy.DisableConfigUpdateForSeconds,
		proxy.bctl.DisableConfigUpdateUntil.String())

	return GoodReply()
}
开发者ID:minaevmike,项目名称:backrunner,代码行数:30,代码来源:proxy.go


示例5: TestSpec

func TestSpec(t *testing.T) {
	bs, err := ioutil.ReadFile("spec.json")
	if err != nil {
		t.Error("Unable to open the spec.")
	}
	var spec Spec
	err = json.Unmarshal(bs, &spec)
	if err != nil {
		t.Error("JSON format was wrong", err)
	}

	i := 0
	failed := 0
	for i < len(spec.Examples) {
		example := spec.Examples[i]
		renderedHTML := RenderHTML(Parse(example.Markdown))
		if renderedHTML != example.HTML {
			failed = failed + 1
			t.Error("===== " + example.Name + " failed. =====")
			t.Error("===== MARKDOWN =====")
			t.Error(strings.Replace(example.Markdown, "\t", "→", -1))
			t.Error("===== EXPECTED HTML =====")
			t.Error(example.HTML)
			t.Error("===== GOT HTML =====")
			t.Error(renderedHTML)
			t.Error(pretty.Diff(example.HTML, renderedHTML))
			t.Error("\n\n")
		}
		i = i + 1
	}
	passed := len(spec.Examples) - failed
	t.Log("Passed: ", passed, "/", len(spec.Examples))

}
开发者ID:sudhirj,项目名称:godown,代码行数:34,代码来源:spec_test.go


示例6: TestGetRateSummary

func TestGetRateSummary(t *testing.T) {
	server, zillow := testFixtures(t, rateSummaryPath, func(values url.Values) {
		assertOnlyParam(t, values, stateParam, state)
	})
	defer server.Close()

	request := RateSummaryRequest{State: state}
	result, err := zillow.GetRateSummary(request)
	if err != nil {
		t.Fatal(err)
	}
	expected := &RateSummary{
		XMLName: xml.Name{Space: "http://www.zillow.com/static/xsd/RateSummary.xsd", Local: "rateSummary"},
		Message: Message{
			Text: "Request successfully processed",
			Code: 0,
		},
		Today: []Rate{
			Rate{LoanType: "thirtyYearFixed", Count: 1252, Value: 5.91},
			Rate{LoanType: "fifteenYearFixed", Count: 839, Value: 5.68},
			Rate{LoanType: "fiveOneARM", Count: 685, Value: 5.49},
		},
		LastWeek: []Rate{
			Rate{LoanType: "thirtyYearFixed", Count: 8933, Value: 6.02},
			Rate{LoanType: "fifteenYearFixed", Count: 5801, Value: 5.94},
			Rate{LoanType: "fiveOneARM", Count: 3148, Value: 5.71},
		},
	}

	if !reflect.DeepEqual(result, expected) {
		t.Fatalf("expected:\n %#v\n\n but got:\n %#v\n\n diff:\n %s\n",
			pretty.Formatter(expected), pretty.Formatter(result), pretty.Diff(expected, result))
	}
}
开发者ID:jmank88,项目名称:zillow,代码行数:34,代码来源:zillow_test.go


示例7: TestGetChart

func TestGetChart(t *testing.T) {
	server, zillow := testFixtures(t, chartPath, func(values url.Values) {
		assertOnlyParam(t, values, zpidParam, zpid)
		assertOnlyParam(t, values, unitTypeParam, unitType)
		assertOnlyParam(t, values, widthParam, strconv.Itoa(width))
		assertOnlyParam(t, values, heightParam, strconv.Itoa(height))
	})
	defer server.Close()

	request := ChartRequest{Zpid: zpid, UnitType: unitType, Width: width, Height: height}
	result, err := zillow.GetChart(request)
	if err != nil {
		t.Fatal(err)
	}
	expected := &ChartResult{
		XMLName: xml.Name{Space: "http://www.zillowstatic.com/vstatic/8d9b5f1/static/xsd/Chart.xsd", Local: "chart"},
		Request: request,
		Message: Message{
			Text: "Request successfully processed",
			Code: 0,
		},
		Url: "http://www.zillow.com/app?chartDuration=1year&chartType=partner&height=150&page=webservice%2FGetChart&service=chart&showPercent=true&width=300&zpid=48749425",
	}

	if !reflect.DeepEqual(result, expected) {
		t.Fatalf("expected:\n %#v\n\n but got:\n %#v\n\n diff:\n %s\n",
			pretty.Formatter(expected), pretty.Formatter(result), pretty.Diff(expected, result))
	}
}
开发者ID:jmank88,项目名称:zillow,代码行数:29,代码来源:zillow_test.go


示例8: TestUnmarshalJSON

func TestUnmarshalJSON(t *testing.T) {
	type unmarshalJSONTest struct {
		dir string
	}
	tests := []unmarshalJSONTest{
		{"testdata"},
	}
	for _, test := range tests {
		units, err := Default.Scan(test.dir)
		if err != nil {
			t.Errorf("scan error: %s", err)
			continue
		}
		for _, unit := range units {
			data, err := json.Marshal(unit)
			if err != nil {
				t.Errorf("marshal error: %s", err)
				continue
			}
			unit2, err := UnmarshalJSON(data, UnitType(unit))
			if err != nil {
				t.Errorf("UnmarshalJSON error: %s", err)
				continue
			}
			if !reflect.DeepEqual(unit, unit2) {
				t.Errorf("unit != unit2:\n%+v\n%+v\n%v", unit, unit2, strings.Join(pretty.Diff(unit, unit2), "\n"))
			}
		}
	}
}
开发者ID:pombredanne,项目名称:srcscan,代码行数:30,代码来源:unit_test.go


示例9: TestMarshalableUnit

func TestMarshalableUnit(t *testing.T) {
	type unmarshalJSONTest struct {
		dir string
	}
	tests := []unmarshalJSONTest{
		{"testdata"},
	}
	for _, test := range tests {
		units, err := Default.Scan(test.dir)
		if err != nil {
			t.Errorf("scan error: %s", err)
			continue
		}
		for _, unit := range units {
			mu := &MarshalableUnit{unit}
			data, err := json.Marshal(mu)
			if err != nil {
				t.Errorf("marshal error: %s", err)
				continue
			}
			var mu2 *MarshalableUnit
			err = json.Unmarshal(data, &mu2)
			if err != nil {
				t.Errorf("Unmarshal error: %s", err)
				continue
			}
			if !reflect.DeepEqual(mu, mu2) {
				t.Errorf("mu != mu2:\n%+v\n%+v\n%v", mu, mu2, strings.Join(pretty.Diff(mu, mu2), "\n"))
			}
		}
	}
}
开发者ID:pombredanne,项目名称:srcscan,代码行数:32,代码来源:unit_test.go


示例10: assertEqual

func assertEqual(t *testing.T, expected, actual interface{}, message string) {
	if expected != actual {
		t.Error(message)
		for _, desc := range pretty.Diff(expected, actual) {
			t.Error(desc)
		}
	}
}
开发者ID:mark-adams,项目名称:cap-go,代码行数:8,代码来源:utils_test.go


示例11: TestDeltas

func TestDeltas(t *testing.T) {
	tests := []struct {
		spec          DeltaSpec
		wantRouteVars map[string]string
	}{
		{
			spec: DeltaSpec{
				Base: RepoRevSpec{RepoSpec: RepoSpec{URI: "samerepo"}, Rev: "baserev", CommitID: baseCommit},
				Head: RepoRevSpec{RepoSpec: RepoSpec{URI: "samerepo"}, Rev: "headrev", CommitID: headCommit},
			},
			wantRouteVars: map[string]string{
				"Repo":                 "samerepo",
				"Rev":                  baseRev.Rev,
				"CommitID":             baseCommit,
				"DeltaHeadResolvedRev": "headrev===" + headCommit,
			},
		},
		{
			spec: DeltaSpec{
				Base: baseRev,
				Head: headRev,
			},
			wantRouteVars: map[string]string{
				"Repo":                 "base.com/repo",
				"Rev":                  baseRev.Rev,
				"CommitID":             baseCommit,
				"DeltaHeadResolvedRev": encodeCrossRepoRevSpecForDeltaHeadResolvedRev(headRev),
			},
		},
	}
	for _, test := range tests {
		vars := test.spec.RouteVars()
		if !reflect.DeepEqual(vars, test.wantRouteVars) {
			t.Errorf("got route vars != want\n\n%s", strings.Join(pretty.Diff(vars, test.wantRouteVars), "\n"))
		}

		spec, err := UnmarshalDeltaSpec(vars)
		if err != nil {
			t.Errorf("UnmarshalDeltaSpec(%+v): %s", vars, err)
			continue
		}
		if !reflect.DeepEqual(spec, test.spec) {
			t.Errorf("got spec != original spec\n\n%s", strings.Join(pretty.Diff(spec, test.spec), "\n"))
		}
	}
}
开发者ID:alexsaveliev,项目名称:go-sourcegraph,代码行数:46,代码来源:deltas_test.go


示例12: assertStartsWith

func assertStartsWith(t *testing.T, strVal, prefix string, message string) {

	if strings.Index(strVal, prefix) == -1 {
		t.Error(message)
		for _, desc := range pretty.Diff(prefix, strVal[:len(prefix)]) {
			t.Error(desc)
		}
	}
}
开发者ID:mark-adams,项目名称:cap-go,代码行数:9,代码来源:utils_test.go


示例13: assertEq

func assertEq(a assertable, expected, got interface{}, args ...interface{}) {
	if !reflect.DeepEqual(expected, got) {
		fatal(a,
			args,
			"\tEXPECTED: %v\n\tGOT:      %v\n\tDIFF:     %v",
			expected,
			got,
			fmt.Diff(expected, got))
	}
}
开发者ID:ftrvxmtrx,项目名称:testingo,代码行数:10,代码来源:testingo.go


示例14: equal

func equal(t *testing.T, expected, got interface{}, callDepth int, messages ...interface{}) {
	fn := func() {
		for _, desc := range pretty.Diff(expected, got) {
			t.Error(errorPrefix, desc)
		}
		if len(messages) > 0 {
			t.Error(errorPrefix, "-", fmt.Sprint(messages...))
		}
	}
	assert(t, isEqual(expected, got), fn, callDepth+1)
}
开发者ID:unrolled,项目名称:assert,代码行数:11,代码来源:assert.go


示例15: TestGolangBackend

func TestGolangBackend(t *testing.T) {
	dir, err := ioutil.TempDir("", "gencode")
	if err != nil {
		t.Fatalf("Failed to create temp dir: %v", err)
	}
	defer os.RemoveAll(dir)

	for _, tc := range []string{
		"array.schema",
		"int.schema",
	} {
		inputF := filepath.Join("./testdata", tc)
		outputF := filepath.Join(dir, tc+".go")
		goldenF := inputF + ".golden.go"

		in, err := ioutil.ReadFile(inputF)
		if err != nil {
			t.Fatalf("%v: Failed to read: %v", tc, err)
		}
		s, err := schema.ParseSchema(bytes.NewReader(in))
		if err != nil {
			t.Fatalf("%v: Failed schema.ParseSchema: %v", tc, err)
		}

		b := GolangBackend{Package: "testdata"}
		g, err := b.Generate(s)
		if err != nil {
			t.Fatalf("%v: Failed Generate: %v", tc, err)
		}
		out := []byte(g)
		if err = ioutil.WriteFile(outputF, out, 0777); err != nil {
			t.Fatalf("%v: Failed to write generated file: %v", tc, err)
		}
		if out, err := exec.Command("go", "build", outputF).CombinedOutput(); err != nil {
			t.Fatalf("%v: Failed to compile generated code (error: %v):\n%s", tc, err, out)
		}

		want, err := ioutil.ReadFile(goldenF)
		needUpdate := true
		if err != nil {
			t.Errorf("%v: Failed to read golden file: %v", tc, err)
		} else if diff := pretty.Diff(want, out); len(diff) != 0 {
			t.Errorf("%v: Diff(want, got) = %v", tc, strings.Join(diff, "\n"))
		} else {
			needUpdate = false
		}

		if needUpdate && *update {
			if err := ioutil.WriteFile(goldenF, out, 0777); err != nil {
				t.Errorf("%v: Failed to update golden file: %v", tc, err)
			}
		}
	}
}
开发者ID:andyleap,项目名称:gencode,代码行数:54,代码来源:golang_test.go


示例16: equal

func equal(t *testing.T, exp, got interface{}, cd int, args ...interface{}) {
	fn := func() {
		for _, desc := range pretty.Diff(exp, got) {
			t.Error("!", desc)
		}
		if len(args) > 0 {
			t.Error("!", " -", fmt.Sprint(args...))
		}
	}
	result := reflect.DeepEqual(exp, got)
	assert(t, result, fn, cd+1)
}
开发者ID:tietang,项目名称:assert,代码行数:12,代码来源:assert.go


示例17: TestAExpr

func TestAExpr(t *testing.T) {
	for _, test := range aExprTests {
		var actualTree nodes.A_Expr
		err := json.Unmarshal([]byte(test.jsonText), &actualTree)

		if err != nil {
			t.Errorf("Unmarshal(%s)\nerror %s\n\n", test.jsonText, err)
		} else if !reflect.DeepEqual(actualTree, test.expectedNode) {
			t.Errorf("Unmarshal(%s)\ndiff %s\n\n", test.jsonText, pretty.Diff(test.expectedNode, actualTree))
		}
	}
}
开发者ID:lfittl,项目名称:pg_query_go,代码行数:12,代码来源:a_expr_test.go


示例18: compareJson

func compareJson(a, b []byte) ([]string, error) {
	oa := make(map[string]interface{})
	if err := json.Unmarshal(a, &oa); err != nil {
		return nil, maskAny(err)
	}

	ob := make(map[string]interface{})
	if err := json.Unmarshal(b, &ob); err != nil {
		return nil, maskAny(err)
	}

	diffs := pretty.Diff(oa, ob)
	return diffs, nil
}
开发者ID:pulcy,项目名称:j2,代码行数:14,代码来源:jobs_test.go


示例19: TestGetMonthlyPayments

func TestGetMonthlyPayments(t *testing.T) {
	server, zillow := testFixtures(t, monthlyPaymentsPath, func(values url.Values) {
		assertOnlyParam(t, values, priceParam, strconv.Itoa(price))
		assertOnlyParam(t, values, downParam, strconv.Itoa(down))
		assertOnlyParam(t, values, zipParam, zip)
	})
	defer server.Close()

	request := MonthlyPaymentsRequest{Price: price, Down: down, Zip: zip}
	result, err := zillow.GetMonthlyPayments(request)
	if err != nil {
		t.Fatal(err)
	}
	expected := &MonthlyPayments{
		XMLName: xml.Name{Space: "http://www.zillow.com/static/xsd/MonthlyPayments.xsd", Local: "paymentsSummary"},
		Request: request,
		Message: Message{
			Text: "Request successfully processed",
			Code: 0,
		},
		Payments: []Payment{
			{
				LoanType: "thirtyYearFixed",
				Rate:     5.9,
				MonthlyPrincipalAndInterest: 1512,
				MonthlyMortgageInsurance:    68,
			},
			{
				LoanType: "fifteenYearFixed",
				Rate:     5.68,
				MonthlyPrincipalAndInterest: 1477,
				MonthlyMortgageInsurance:    68,
			},
			{
				LoanType: "fiveOneARM",
				Rate:     5.71,
				MonthlyPrincipalAndInterest: 1482,
				MonthlyMortgageInsurance:    74,
			},
		},
		DownPayment:            45000,
		MonthlyPropertyTaxes:   193,
		MonthlyHazardInsurance: 49,
	}

	if !reflect.DeepEqual(result, expected) {
		t.Fatalf("expected:\n %#v\n\n but got:\n %#v\n\n diff:\n %s\n",
			pretty.Formatter(expected), pretty.Formatter(result), pretty.Diff(expected, result))
	}
}
开发者ID:jmank88,项目名称:zillow,代码行数:50,代码来源:zillow_test.go


示例20: TestProducer

func TestProducer(t *testing.T) {
	stack := new(mango.Stack)
	handler := stack.HandlerFunc(pact.Producer)

	testflight.WithServer(handler, func(r *testflight.Requester) {

		pact_str, err := ioutil.ReadFile("../pacts/my_consumer-my_producer.json")
		if err != nil {
			t.Error(err)
		}

		pacts := make(map[string]interface{})
		err = json.Unmarshal(pact_str, &pacts)
		if err != nil {
			t.Error(err)
		}

		for _, i := range pacts["interactions"].([]interface{}) {
			interaction := i.(map[string]interface{})
			t.Logf("Given %s", interaction["producer_state"])
			t.Logf("  %s", interaction["description"])

			request := interaction["request"].(map[string]interface{})
			var actualResponse *testflight.Response
			switch request["method"] {
			case "get":
				actualResponse = r.Get(request["path"].(string) + "?" + request["query"].(string))
			}

			expectedResponse := interaction["response"].(map[string]interface{})

			assert.Equal(t, int(expectedResponse["status"].(float64)), actualResponse.StatusCode)

			for k, v := range expectedResponse["headers"].(map[string]interface{}) {
				assert.Equal(t, v, actualResponse.RawResponse.Header[k][0])
			}

			responseBody := make(map[string]interface{})
			err = json.Unmarshal([]byte(actualResponse.Body), &responseBody)
			if err != nil {
				t.Error(err)
			}
			for _, diff := range pretty.Diff(expectedResponse["body"], responseBody) {
				t.Log(diff)
			}
			assert.Equal(t, expectedResponse["body"], responseBody)
		}
	})
}
开发者ID:uglyog,项目名称:example_pact_with_go,代码行数:49,代码来源:producer_test.go



注:本文中的github.com/kr/pretty.Diff函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang pretty.Formatter函数代码示例发布时间:2022-05-23
下一篇:
Golang fs.Walker类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap