From c45008e63fa1b8db7823c8d535b544964f8f3245 Mon Sep 17 00:00:00 2001 From: Robert Bittle <guywithnose@gmail.com> Date: Fri, 12 Aug 2022 18:03:55 -0400 Subject: [PATCH] Allow Any to take a list of matchers This works like an OR the same way that All works like an AND. If you pass 0 parameters it works the same way it always has. --- gomock/matchers.go | 36 ++++++++++++++++++++++++++++-------- gomock/matchers_test.go | 1 + 2 files changed, 29 insertions(+), 8 deletions(-) diff --git a/gomock/matchers.go b/gomock/matchers.go index 2822fb2c..239e2a0d 100644 --- a/gomock/matchers.go +++ b/gomock/matchers.go @@ -87,14 +87,33 @@ func GotFormatterAdapter(s GotFormatter, m Matcher) Matcher { } } -type anyMatcher struct{} +type anyMatcher struct { + matchers []Matcher +} -func (anyMatcher) Matches(interface{}) bool { - return true +func (am anyMatcher) Matches(x interface{}) bool { + if len(am.matchers) == 0 { + return true + } + + for _, m := range am.matchers { + if m.Matches(x) { + return true + } + } + return false } -func (anyMatcher) String() string { - return "is anything" +func (am anyMatcher) String() string { + if len(am.matchers) == 0 { + return "is anything" + } + + ss := make([]string, 0, len(am.matchers)) + for _, matcher := range am.matchers { + ss = append(ss, matcher.String()) + } + return strings.Join(ss, " OR ") } type eqMatcher struct { @@ -273,12 +292,13 @@ func (m inAnyOrderMatcher) String() string { // Constructors -// All returns a composite Matcher that returns true if and only all of the +// All returns a composite Matcher that returns true if and only if all of the // matchers return true. func All(ms ...Matcher) Matcher { return allMatcher{ms} } -// Any returns a matcher that always matches. -func Any() Matcher { return anyMatcher{} } +// All returns a composite Matcher that returns true if any of the +// matchers return true. +func Any(ms ...Matcher) Matcher { return anyMatcher{ms} } // Eq returns a matcher that matches on equality. // diff --git a/gomock/matchers_test.go b/gomock/matchers_test.go index 61bc1993..ec9e815e 100644 --- a/gomock/matchers_test.go +++ b/gomock/matchers_test.go @@ -36,6 +36,7 @@ func TestMatchers(t *testing.T) { yes, no []e }{ {"test Any", gomock.Any(), []e{3, nil, "foo"}, nil}, + {"test Any", gomock.Any(gomock.Eq(3), gomock.Eq(4)), []e{3, 4}, []e{5}}, {"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)},