当前位置: 首页>>代码示例>>Golang>>正文


Golang pretty.Diff函数代码示例

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


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


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