Commit 509abe0b authored by Robin Martinjak's avatar Robin Martinjak

Add pretty.CompareWithoutZeroFields

CompareWithoutZeroFields returns a diff like Compare but omits
struct fields that have a zero value.
parent 808ac284
......@@ -35,6 +35,7 @@ type Config struct {
// Field and value options
IncludeUnexported bool // Include unexported fields in output
PrintStringers bool // Call String on a fmt.Stringer
SkipZeroFields bool // Skip struct fields that have a zero value.
// Output transforms
ShortList int // Maximum character length for short lists if nonzero.
......@@ -96,6 +97,16 @@ func Compare(got, want interface{}) string {
Diffable: true,
IncludeUnexported: true,
}
return diff.Diff(diffOpt.Sprint(got), diffOpt.Sprint(want))
}
// CompareWithoutZeroFields returns a diff like Compare but omits struct fields
// that have a zero value.
func CompareWithoutZeroFields(got, want interface{}) string {
diffOpt := &Config{
Diffable: true,
IncludeUnexported: true,
SkipZeroFields: true,
}
return diff.Diff(diffOpt.Sprint(got), diffOpt.Sprint(want))
}
......@@ -70,3 +70,56 @@ func TestDiff(t *testing.T) {
}
}
}
func TestDiffWithoutZeroes(t *testing.T) {
type example struct {
Name string
Species string
Age int
Friends []string
}
tests := []struct {
desc string
got, want interface{}
diff string
}{
{
desc: "basic struct",
got: example{
Name: "Zaphd",
Species: "Betelgeusian",
Age: 42,
},
want: example{
Name: "Zaphod",
Species: "Betelgeusian",
Age: 42,
Friends: []string{
"Ford Prefect",
"Trillian",
"",
},
},
diff: ` {
- Name: "Zaphd",
+ Name: "Zaphod",
Species: "Betelgeusian",
Age: 42,
+ Friends: [
+ "Ford Prefect",
+ "Trillian",
+ "",
+ ],
}`,
},
}
for _, test := range tests {
if got, want := CompareWithoutZeroFields(test.got, test.want), test.diff; got != want {
t.Errorf("%s:", test.desc)
t.Errorf(" got: %q", got)
t.Errorf(" want: %q", want)
}
}
}
......@@ -20,6 +20,14 @@ import (
"sort"
)
func isZeroVal(val reflect.Value) bool {
if !val.CanInterface() {
return false
}
z := reflect.Zero(val.Type()).Interface()
return reflect.DeepEqual(val.Interface(), z)
}
func (c *Config) val2node(val reflect.Value) node {
// TODO(kevlar): pointer tracking?
......@@ -63,7 +71,11 @@ func (c *Config) val2node(val reflect.Value) node {
if !c.IncludeUnexported && sf.PkgPath != "" {
continue
}
n = append(n, keyval{sf.Name, c.val2node(val.Field(i))})
field := val.Field(i)
if c.SkipZeroFields && isZeroVal(field) {
continue
}
n = append(n, keyval{sf.Name, c.val2node(field)})
}
return n
case reflect.Bool:
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment