Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add AnyOf that matches values that satisfy at least one matcher #63

Merged
merged 1 commit into from Sep 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
43 changes: 43 additions & 0 deletions gomock/matchers.go
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
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