Skip to content

Commit

Permalink
Merge pull request gotestyourself#43 from dnephin/handle-unexported-p…
Browse files Browse the repository at this point in the history
…anic

Handle go-cmp panic on unexported
  • Loading branch information
Vincent Demeester committed Jan 18, 2018
2 parents 3b5a983 + cba43cc commit 3528a68
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
22 changes: 21 additions & 1 deletion assert/cmp/compare.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,32 @@ import (
//
// The comparison can be customized using comparison Options.
func Compare(x, y interface{}, opts ...cmp.Option) func() (bool, string) {
return func() (bool, string) {
return func() (success bool, msg string) {
defer func() {
if panicmsg, handled := handleCmpPanic(recover()); handled {
msg = panicmsg
}
}()
diff := cmp.Diff(x, y, opts...)
return diff == "", "\n" + diff
}
}

func handleCmpPanic(r interface{}) (string, bool) {
if r == nil {
return "", false
}
panicmsg, ok := r.(string)
if !ok {
panic(r)
}
switch {
case strings.HasPrefix(panicmsg, "cannot handle unexported field"):
return panicmsg, true
}
panic(r)
}

// Equal succeeds if x == y.
func Equal(x, y interface{}) func() (success bool, message string) {
return func() (bool, string) {
Expand Down
22 changes: 22 additions & 0 deletions assert/cmp/compare_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,28 @@ import (
"github.com/pkg/errors"
)

func TestCompare(t *testing.T) {
success, msg := Compare([]string{"a", "b"}, []string{"b", "a"})()
assertFailure(t, success, msg, `
{[]string}:
-: []string{"a", "b"}
+: []string{"b", "a"}
`)

success, msg = Compare([]string{"a"}, []string{"a"})()
assertSuccess(t, success, msg)
}

type Stub struct {
unx int
}

func TestCompareWithUnexported(t *testing.T) {
success, msg := Compare(Stub{}, Stub{unx: 1})()
assertFailure(t, success, msg, `cannot handle unexported field: {cmp.Stub}.unx
consider using AllowUnexported or cmpopts.IgnoreUnexported`)
}

func TestLen(t *testing.T) {
var testcases = []struct {
seq interface{}
Expand Down

0 comments on commit 3528a68

Please sign in to comment.