Skip to content

Commit

Permalink
feat: add AnyOf that matches values that satisfy at least one matcher (
Browse files Browse the repository at this point in the history
…#63)

Closes #58.
  • Loading branch information
favonia committed Sep 19, 2023
1 parent 3377b02 commit fcaca4a
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
43 changes: 43 additions & 0 deletions gomock/matchers.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,27 @@ func (m assignableToTypeOfMatcher) String() string {
return "is assignable to " + m.targetType.Name()
}

type anyOfMatcher struct {
matchers []Matcher
}

func (am anyOfMatcher) Matches(x any) bool {
for _, m := range am.matchers {
if m.Matches(x) {
return true
}
}
return false
}

func (am anyOfMatcher) String() string {
ss := make([]string, 0, len(am.matchers))
for _, matcher := range am.matchers {
ss = append(ss, matcher.String())
}
return strings.Join(ss, " | ")
}

type allMatcher struct {
matchers []Matcher
}
Expand Down Expand Up @@ -302,6 +323,28 @@ func Any() Matcher { return anyMatcher{} }
// Cond(func(x any){return x.(int) == 2}).Matches(1) // returns false
func Cond(fn func(x any) bool) Matcher { return condMatcher{fn} }

// AnyOf returns a composite Matcher that returns true if at least one of the
// matchers returns true.
//
// Example usage:
//
// AnyOf(1, 2, 3).Matches(2) // returns true
// AnyOf(1, 2, 3).Matches(10) // returns false
// AnyOf(Nil(), Len(2)).Matches(nil) // returns true
// AnyOf(Nil(), Len(2)).Matches("hi") // returns true
// AnyOf(Nil(), Len(2)).Matches("hello") // returns false
func AnyOf(xs ...any) Matcher {
ms := make([]Matcher, 0, len(xs))
for _, x := range xs {
if m, ok := x.(Matcher); ok {
ms = append(ms, m)
} else {
ms = append(ms, Eq(x))
}
}
return anyOfMatcher{ms}
}

// Eq returns a matcher that matches on equality.
//
// Example usage:
Expand Down
3 changes: 3 additions & 0 deletions gomock/matchers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ func TestMatchers(t *testing.T) {
yes, no []e
}{
{"test Any", gomock.Any(), []e{3, nil, "foo"}, nil},
{"test AnyOf", gomock.AnyOf(gomock.Nil(), gomock.Len(2), 1, 2, 3),
[]e{nil, "hi", "to", 1, 2, 3},
[]e{"s", "", 0, 4, 10}},
{"test All", gomock.Eq(4), []e{4}, []e{3, "blah", nil, int64(4)}},
{"test Nil", gomock.Nil(),
[]e{nil, (error)(nil), (chan bool)(nil), (*int)(nil)},
Expand Down

0 comments on commit fcaca4a

Please sign in to comment.