xref: /aosp_15_r20/external/go-cmp/cmp/example_reporter_test.go (revision 88d15eac089d7f20c739ff1001d56b91872b21a1)
1// Copyright 2019, The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package cmp_test
6
7import (
8	"fmt"
9	"strings"
10
11	"github.com/google/go-cmp/cmp"
12)
13
14// DiffReporter is a simple custom reporter that only records differences
15// detected during comparison.
16type DiffReporter struct {
17	path  cmp.Path
18	diffs []string
19}
20
21func (r *DiffReporter) PushStep(ps cmp.PathStep) {
22	r.path = append(r.path, ps)
23}
24
25func (r *DiffReporter) Report(rs cmp.Result) {
26	if !rs.Equal() {
27		vx, vy := r.path.Last().Values()
28		r.diffs = append(r.diffs, fmt.Sprintf("%#v:\n\t-: %+v\n\t+: %+v\n", r.path, vx, vy))
29	}
30}
31
32func (r *DiffReporter) PopStep() {
33	r.path = r.path[:len(r.path)-1]
34}
35
36func (r *DiffReporter) String() string {
37	return strings.Join(r.diffs, "\n")
38}
39
40func ExampleReporter() {
41	x, y := MakeGatewayInfo()
42
43	var r DiffReporter
44	cmp.Equal(x, y, cmp.Reporter(&r))
45	fmt.Print(r.String())
46
47	// Output:
48	// {cmp_test.Gateway}.IPAddress:
49	// 	-: 192.168.0.1
50	// 	+: 192.168.0.2
51	//
52	// {cmp_test.Gateway}.Clients[4].IPAddress:
53	// 	-: 192.168.0.219
54	// 	+: 192.168.0.221
55	//
56	// {cmp_test.Gateway}.Clients[5->?]:
57	// 	-: {Hostname:americano IPAddress:192.168.0.188 LastSeen:2009-11-10 23:03:05 +0000 UTC}
58	// 	+: <invalid reflect.Value>
59}
60