Skip to content
This repository was archived by the owner on Jun 27, 2023. It is now read-only.

Commit 4365f1b

Browse files
committed
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.
1 parent 5b45562 commit 4365f1b

File tree

2 files changed

+29
-8
lines changed

2 files changed

+29
-8
lines changed

gomock/matchers.go

+28-8
Original file line numberDiff line numberDiff line change
@@ -87,14 +87,33 @@ func GotFormatterAdapter(s GotFormatter, m Matcher) Matcher {
8787
}
8888
}
8989

90-
type anyMatcher struct{}
90+
type anyMatcher struct {
91+
matchers []Matcher
92+
}
9193

92-
func (anyMatcher) Matches(interface{}) bool {
93-
return true
94+
func (am anyMatcher) Matches(x interface{}) bool {
95+
if len(am.matchers) == 0 {
96+
return true
97+
}
98+
99+
for _, m := range am.matchers {
100+
if m.Matches(x) {
101+
return true
102+
}
103+
}
104+
return false
94105
}
95106

96-
func (anyMatcher) String() string {
97-
return "is anything"
107+
func (am anyMatcher) String() string {
108+
if len(am.matchers) == 0 {
109+
return "is anything"
110+
}
111+
112+
ss := make([]string, 0, len(am.matchers))
113+
for _, matcher := range am.matchers {
114+
ss = append(ss, matcher.String())
115+
}
116+
return strings.Join(ss, " OR ")
98117
}
99118

100119
type eqMatcher struct {
@@ -273,12 +292,13 @@ func (m inAnyOrderMatcher) String() string {
273292

274293
// Constructors
275294

276-
// All returns a composite Matcher that returns true if and only all of the
295+
// All returns a composite Matcher that returns true if and only if all of the
277296
// matchers return true.
278297
func All(ms ...Matcher) Matcher { return allMatcher{ms} }
279298

280-
// Any returns a matcher that always matches.
281-
func Any() Matcher { return anyMatcher{} }
299+
// All returns a composite Matcher that returns true if any of the
300+
// matchers return true.
301+
func Any(ms ...Matcher) Matcher { return anyMatcher{ms} }
282302

283303
// Eq returns a matcher that matches on equality.
284304
//

gomock/matchers_test.go

+1
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ func TestMatchers(t *testing.T) {
3636
yes, no []e
3737
}{
3838
{"test Any", gomock.Any(), []e{3, nil, "foo"}, nil},
39+
{"test Any", gomock.Any(gomock.Eq(3), gomock.Eq(4)), []e{3, 4}, []e{5}},
3940
{"test All", gomock.Eq(4), []e{4}, []e{3, "blah", nil, int64(4)}},
4041
{"test Nil", gomock.Nil(),
4142
[]e{nil, (error)(nil), (chan bool)(nil), (*int)(nil)},

0 commit comments

Comments
 (0)