Skip to content

Commit fcaca4a

Browse files
authored
feat: add AnyOf that matches values that satisfy at least one matcher (#63)
Closes #58.
1 parent 3377b02 commit fcaca4a

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

gomock/matchers.go

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,27 @@ func (m assignableToTypeOfMatcher) String() string {
180180
return "is assignable to " + m.targetType.Name()
181181
}
182182

183+
type anyOfMatcher struct {
184+
matchers []Matcher
185+
}
186+
187+
func (am anyOfMatcher) Matches(x any) bool {
188+
for _, m := range am.matchers {
189+
if m.Matches(x) {
190+
return true
191+
}
192+
}
193+
return false
194+
}
195+
196+
func (am anyOfMatcher) String() string {
197+
ss := make([]string, 0, len(am.matchers))
198+
for _, matcher := range am.matchers {
199+
ss = append(ss, matcher.String())
200+
}
201+
return strings.Join(ss, " | ")
202+
}
203+
183204
type allMatcher struct {
184205
matchers []Matcher
185206
}
@@ -302,6 +323,28 @@ func Any() Matcher { return anyMatcher{} }
302323
// Cond(func(x any){return x.(int) == 2}).Matches(1) // returns false
303324
func Cond(fn func(x any) bool) Matcher { return condMatcher{fn} }
304325

326+
// AnyOf returns a composite Matcher that returns true if at least one of the
327+
// matchers returns true.
328+
//
329+
// Example usage:
330+
//
331+
// AnyOf(1, 2, 3).Matches(2) // returns true
332+
// AnyOf(1, 2, 3).Matches(10) // returns false
333+
// AnyOf(Nil(), Len(2)).Matches(nil) // returns true
334+
// AnyOf(Nil(), Len(2)).Matches("hi") // returns true
335+
// AnyOf(Nil(), Len(2)).Matches("hello") // returns false
336+
func AnyOf(xs ...any) Matcher {
337+
ms := make([]Matcher, 0, len(xs))
338+
for _, x := range xs {
339+
if m, ok := x.(Matcher); ok {
340+
ms = append(ms, m)
341+
} else {
342+
ms = append(ms, Eq(x))
343+
}
344+
}
345+
return anyOfMatcher{ms}
346+
}
347+
305348
// Eq returns a matcher that matches on equality.
306349
//
307350
// Example usage:

gomock/matchers_test.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,9 @@ func TestMatchers(t *testing.T) {
3939
yes, no []e
4040
}{
4141
{"test Any", gomock.Any(), []e{3, nil, "foo"}, nil},
42+
{"test AnyOf", gomock.AnyOf(gomock.Nil(), gomock.Len(2), 1, 2, 3),
43+
[]e{nil, "hi", "to", 1, 2, 3},
44+
[]e{"s", "", 0, 4, 10}},
4245
{"test All", gomock.Eq(4), []e{4}, []e{3, "blah", nil, int64(4)}},
4346
{"test Nil", gomock.Nil(),
4447
[]e{nil, (error)(nil), (chan bool)(nil), (*int)(nil)},

0 commit comments

Comments
 (0)