reporter.go 1.4 KB

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