Path: blob/main/vendor/github.com/golang/mock/gomock/matchers.go
2880 views
// Copyright 2010 Google Inc.1//2// Licensed under the Apache License, Version 2.0 (the "License");3// you may not use this file except in compliance with the License.4// You may obtain a copy of the License at5//6// http://www.apache.org/licenses/LICENSE-2.07//8// Unless required by applicable law or agreed to in writing, software9// distributed under the License is distributed on an "AS IS" BASIS,10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11// See the License for the specific language governing permissions and12// limitations under the License.1314package gomock1516import (17"fmt"18"reflect"19"strings"20)2122// A Matcher is a representation of a class of values.23// It is used to represent the valid or expected arguments to a mocked method.24type Matcher interface {25// Matches returns whether x is a match.26Matches(x interface{}) bool2728// String describes what the matcher matches.29String() string30}3132// WantFormatter modifies the given Matcher's String() method to the given33// Stringer. This allows for control on how the "Want" is formatted when34// printing .35func WantFormatter(s fmt.Stringer, m Matcher) Matcher {36type matcher interface {37Matches(x interface{}) bool38}3940return struct {41matcher42fmt.Stringer43}{44matcher: m,45Stringer: s,46}47}4849// StringerFunc type is an adapter to allow the use of ordinary functions as50// a Stringer. If f is a function with the appropriate signature,51// StringerFunc(f) is a Stringer that calls f.52type StringerFunc func() string5354// String implements fmt.Stringer.55func (f StringerFunc) String() string {56return f()57}5859// GotFormatter is used to better print failure messages. If a matcher60// implements GotFormatter, it will use the result from Got when printing61// the failure message.62type GotFormatter interface {63// Got is invoked with the received value. The result is used when64// printing the failure message.65Got(got interface{}) string66}6768// GotFormatterFunc type is an adapter to allow the use of ordinary69// functions as a GotFormatter. If f is a function with the appropriate70// signature, GotFormatterFunc(f) is a GotFormatter that calls f.71type GotFormatterFunc func(got interface{}) string7273// Got implements GotFormatter.74func (f GotFormatterFunc) Got(got interface{}) string {75return f(got)76}7778// GotFormatterAdapter attaches a GotFormatter to a Matcher.79func GotFormatterAdapter(s GotFormatter, m Matcher) Matcher {80return struct {81GotFormatter82Matcher83}{84GotFormatter: s,85Matcher: m,86}87}8889type anyMatcher struct{}9091func (anyMatcher) Matches(interface{}) bool {92return true93}9495func (anyMatcher) String() string {96return "is anything"97}9899type eqMatcher struct {100x interface{}101}102103func (e eqMatcher) Matches(x interface{}) bool {104// In case, some value is nil105if e.x == nil || x == nil {106return reflect.DeepEqual(e.x, x)107}108109// Check if types assignable and convert them to common type110x1Val := reflect.ValueOf(e.x)111x2Val := reflect.ValueOf(x)112113if x1Val.Type().AssignableTo(x2Val.Type()) {114x1ValConverted := x1Val.Convert(x2Val.Type())115return reflect.DeepEqual(x1ValConverted.Interface(), x2Val.Interface())116}117118return false119}120121func (e eqMatcher) String() string {122return fmt.Sprintf("is equal to %v (%T)", e.x, e.x)123}124125type nilMatcher struct{}126127func (nilMatcher) Matches(x interface{}) bool {128if x == nil {129return true130}131132v := reflect.ValueOf(x)133switch v.Kind() {134case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map,135reflect.Ptr, reflect.Slice:136return v.IsNil()137}138139return false140}141142func (nilMatcher) String() string {143return "is nil"144}145146type notMatcher struct {147m Matcher148}149150func (n notMatcher) Matches(x interface{}) bool {151return !n.m.Matches(x)152}153154func (n notMatcher) String() string {155return "not(" + n.m.String() + ")"156}157158type assignableToTypeOfMatcher struct {159targetType reflect.Type160}161162func (m assignableToTypeOfMatcher) Matches(x interface{}) bool {163return reflect.TypeOf(x).AssignableTo(m.targetType)164}165166func (m assignableToTypeOfMatcher) String() string {167return "is assignable to " + m.targetType.Name()168}169170type allMatcher struct {171matchers []Matcher172}173174func (am allMatcher) Matches(x interface{}) bool {175for _, m := range am.matchers {176if !m.Matches(x) {177return false178}179}180return true181}182183func (am allMatcher) String() string {184ss := make([]string, 0, len(am.matchers))185for _, matcher := range am.matchers {186ss = append(ss, matcher.String())187}188return strings.Join(ss, "; ")189}190191type lenMatcher struct {192i int193}194195func (m lenMatcher) Matches(x interface{}) bool {196v := reflect.ValueOf(x)197switch v.Kind() {198case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice, reflect.String:199return v.Len() == m.i200default:201return false202}203}204205func (m lenMatcher) String() string {206return fmt.Sprintf("has length %d", m.i)207}208209type inAnyOrderMatcher struct {210x interface{}211}212213func (m inAnyOrderMatcher) Matches(x interface{}) bool {214given, ok := m.prepareValue(x)215if !ok {216return false217}218wanted, ok := m.prepareValue(m.x)219if !ok {220return false221}222223if given.Len() != wanted.Len() {224return false225}226227usedFromGiven := make([]bool, given.Len())228foundFromWanted := make([]bool, wanted.Len())229for i := 0; i < wanted.Len(); i++ {230wantedMatcher := Eq(wanted.Index(i).Interface())231for j := 0; j < given.Len(); j++ {232if usedFromGiven[j] {233continue234}235if wantedMatcher.Matches(given.Index(j).Interface()) {236foundFromWanted[i] = true237usedFromGiven[j] = true238break239}240}241}242243missingFromWanted := 0244for _, found := range foundFromWanted {245if !found {246missingFromWanted++247}248}249extraInGiven := 0250for _, used := range usedFromGiven {251if !used {252extraInGiven++253}254}255256return extraInGiven == 0 && missingFromWanted == 0257}258259func (m inAnyOrderMatcher) prepareValue(x interface{}) (reflect.Value, bool) {260xValue := reflect.ValueOf(x)261switch xValue.Kind() {262case reflect.Slice, reflect.Array:263return xValue, true264default:265return reflect.Value{}, false266}267}268269func (m inAnyOrderMatcher) String() string {270return fmt.Sprintf("has the same elements as %v", m.x)271}272273// Constructors274275// All returns a composite Matcher that returns true if and only all of the276// matchers return true.277func All(ms ...Matcher) Matcher { return allMatcher{ms} }278279// Any returns a matcher that always matches.280func Any() Matcher { return anyMatcher{} }281282// Eq returns a matcher that matches on equality.283//284// Example usage:285// Eq(5).Matches(5) // returns true286// Eq(5).Matches(4) // returns false287func Eq(x interface{}) Matcher { return eqMatcher{x} }288289// Len returns a matcher that matches on length. This matcher returns false if290// is compared to a type that is not an array, chan, map, slice, or string.291func Len(i int) Matcher {292return lenMatcher{i}293}294295// Nil returns a matcher that matches if the received value is nil.296//297// Example usage:298// var x *bytes.Buffer299// Nil().Matches(x) // returns true300// x = &bytes.Buffer{}301// Nil().Matches(x) // returns false302func Nil() Matcher { return nilMatcher{} }303304// Not reverses the results of its given child matcher.305//306// Example usage:307// Not(Eq(5)).Matches(4) // returns true308// Not(Eq(5)).Matches(5) // returns false309func Not(x interface{}) Matcher {310if m, ok := x.(Matcher); ok {311return notMatcher{m}312}313return notMatcher{Eq(x)}314}315316// AssignableToTypeOf is a Matcher that matches if the parameter to the mock317// function is assignable to the type of the parameter to this function.318//319// Example usage:320// var s fmt.Stringer = &bytes.Buffer{}321// AssignableToTypeOf(s).Matches(time.Second) // returns true322// AssignableToTypeOf(s).Matches(99) // returns false323//324// var ctx = reflect.TypeOf((*context.Context)(nil)).Elem()325// AssignableToTypeOf(ctx).Matches(context.Background()) // returns true326func AssignableToTypeOf(x interface{}) Matcher {327if xt, ok := x.(reflect.Type); ok {328return assignableToTypeOfMatcher{xt}329}330return assignableToTypeOfMatcher{reflect.TypeOf(x)}331}332333// InAnyOrder is a Matcher that returns true for collections of the same elements ignoring the order.334//335// Example usage:336// InAnyOrder([]int{1, 2, 3}).Matches([]int{1, 3, 2}) // returns true337// InAnyOrder([]int{1, 2, 3}).Matches([]int{1, 2}) // returns false338func InAnyOrder(x interface{}) Matcher {339return inAnyOrderMatcher{x}340}341342343