Skip to content

Commit

Permalink
fix: use recover to let it as usual error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
xiantank committed Apr 23, 2022
1 parent 220c595 commit 8824ca4
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 14 deletions.
13 changes: 12 additions & 1 deletion matchers/compare_matcher.go
Expand Up @@ -12,7 +12,7 @@ type CompareMatcher struct {
Options cmp.Options
}

func (matcher *CompareMatcher) Match(actual interface{}) (success bool, err error) {
func (matcher *CompareMatcher) Match(actual interface{}) (success bool, matchErr error) {
if actual == nil && matcher.Expected == nil {
return false, fmt.Errorf("Refusing to compare <nil> to <nil>.\nBe explicit and use BeNil() instead. This is to avoid mistakes where both sides of an assertion are erroneously uninitialized.")
}
Expand All @@ -25,6 +25,17 @@ func (matcher *CompareMatcher) Match(actual interface{}) (success bool, err erro
}
}

defer func() {
if r := recover(); r != nil {
success = false
if err, ok := r.(error); ok {
matchErr = err
} else if errMsg, ok := r.(string); ok {
matchErr = fmt.Errorf(errMsg)
}
}
}()

return cmp.Equal(actual, matcher.Expected, matcher.Options...), nil
}

Expand Down
20 changes: 7 additions & 13 deletions matchers/compare_matcher_test.go
Expand Up @@ -43,16 +43,17 @@ var _ = Describe("Compare", func() {
})

Context("When asserting time with different location ", func() {
var t1, t2 time.Time
var t1, t2, t3 time.Time

BeforeEach(func() {
t1 = time.Time{}
t2 = time.Time{}.Local()
t3 = t1.Add(time.Second)
})

It("should do the right thing", func() {
Expect(t1).ShouldNot(Equal(t2))
Expect(t1).Should(Compare(t2))
Expect(t1).ShouldNot(Compare(t3))
})
})

Expand All @@ -69,17 +70,10 @@ var _ = Describe("Compare", func() {
s2 = structWithUnexportedFields{unexported: "unexported", Exported: "Exported"}
})

It("should panic with unexported field", func() {
defer func() {
if e := recover(); e != nil {
Expect(e).Should(HavePrefix("cannot handle unexported field at"))
}
}()

matcher := &CompareMatcher{
Expected: s1,
}
_, _ = matcher.Match(s2)
It("should get match err", func() {
success, err := (&CompareMatcher{Expected: s1}).Match(s2)
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
})

It("should do the right thing", func() {
Expand Down

0 comments on commit 8824ca4

Please sign in to comment.