Skip to content

Commit

Permalink
check: Print diff for anything that doesn't print nicely
Browse files Browse the repository at this point in the history
For a *int, printing only the addresses when they're different is
useless. Now, anything that's non-printable will show a proper diff.
  • Loading branch information
thatguystone committed Aug 14, 2023
1 parent 15c9633 commit 0e6dc3f
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 20 deletions.
48 changes: 29 additions & 19 deletions check/assert_fmt.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,30 +21,40 @@ func fmtVals(g, e any) (string, string) {
return gs, es
}

func typeAndKind(v any) (reflect.Type, reflect.Kind) {
t := reflect.TypeOf(v)
k := t.Kind()
if k == reflect.Ptr {
t = t.Elem()
k = t.Kind()
// If fmt.Sprintf("%+v") generally produces a reasonable value
func isFormattable(v any) bool {
rt := reflect.TypeOf(v)
if rt == nil {
return true
}

return t, k
}

func diff(g, e any) string {
if g == nil || e == nil {
return ""
switch rt.Kind() {
case reflect.Bool:
case reflect.Int:
case reflect.Int8:
case reflect.Int16:
case reflect.Int32:
case reflect.Int64:
case reflect.Uint:
case reflect.Uint8:
case reflect.Uint16:
case reflect.Uint32:
case reflect.Uint64:
case reflect.Uintptr:
case reflect.Float32:
case reflect.Float64:
case reflect.Complex64:
case reflect.Complex128:
case reflect.String:
default:
return false
}

gt, _ := typeAndKind(g)
et, ek := typeAndKind(e)

if gt != et {
return ""
}
return true
}

if ek != reflect.Struct && ek != reflect.Map && ek != reflect.Slice && ek != reflect.Array {
func diff(g, e any) string {
if isFormattable(g) && isFormattable(e) {
return ""
}

Expand Down
2 changes: 1 addition & 1 deletion check/assert_fmt_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ func TestAssertFmtDiffCoverage(t *testing.T) {
c.Equal(diff(1, 1), "")

v := new(int)
c.Equal(diff(1, v), "")
c.NotEqual(diff(1, v), "")

c.NotEqual(diff([]string{"test"}, []string{"nope"}), "")
}

0 comments on commit 0e6dc3f

Please sign in to comment.