reporter.go

 1// Copyright 2017, 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.md file.
 4
 5package cmp
 6
 7import (
 8	"fmt"
 9	"reflect"
10	"strings"
11
12	"github.com/google/go-cmp/cmp/internal/value"
13)
14
15type defaultReporter struct {
16	Option
17	diffs  []string // List of differences, possibly truncated
18	ndiffs int      // Total number of differences
19	nbytes int      // Number of bytes in diffs
20	nlines int      // Number of lines in diffs
21}
22
23var _ reporter = (*defaultReporter)(nil)
24
25func (r *defaultReporter) Report(x, y reflect.Value, eq bool, p Path) {
26	if eq {
27		return // Ignore equal results
28	}
29	const maxBytes = 4096
30	const maxLines = 256
31	r.ndiffs++
32	if r.nbytes < maxBytes && r.nlines < maxLines {
33		sx := value.Format(x, value.FormatConfig{UseStringer: true})
34		sy := value.Format(y, value.FormatConfig{UseStringer: true})
35		if sx == sy {
36			// Unhelpful output, so use more exact formatting.
37			sx = value.Format(x, value.FormatConfig{PrintPrimitiveType: true})
38			sy = value.Format(y, value.FormatConfig{PrintPrimitiveType: true})
39		}
40		s := fmt.Sprintf("%#v:\n\t-: %s\n\t+: %s\n", p, sx, sy)
41		r.diffs = append(r.diffs, s)
42		r.nbytes += len(s)
43		r.nlines += strings.Count(s, "\n")
44	}
45}
46
47func (r *defaultReporter) String() string {
48	s := strings.Join(r.diffs, "")
49	if r.ndiffs == len(r.diffs) {
50		return s
51	}
52	return fmt.Sprintf("%s... %d more differences ...", s, r.ndiffs-len(r.diffs))
53}