1// Copyright 2010 Google Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package gomock
16
17import (
18	"fmt"
19	"reflect"
20	"strings"
21)
22
23// A Matcher is a representation of a class of values.
24// It is used to represent the valid or expected arguments to a mocked method.
25type Matcher interface {
26	// Matches returns whether x is a match.
27	Matches(x interface{}) bool
28
29	// String describes what the matcher matches.
30	String() string
31}
32
33// WantFormatter modifies the given Matcher's String() method to the given
34// Stringer. This allows for control on how the "Want" is formatted when
35// printing .
36func WantFormatter(s fmt.Stringer, m Matcher) Matcher {
37	type matcher interface {
38		Matches(x interface{}) bool
39	}
40
41	return struct {
42		matcher
43		fmt.Stringer
44	}{
45		matcher:  m,
46		Stringer: s,
47	}
48}
49
50// StringerFunc type is an adapter to allow the use of ordinary functions as
51// a Stringer. If f is a function with the appropriate signature,
52// StringerFunc(f) is a Stringer that calls f.
53type StringerFunc func() string
54
55// String implements fmt.Stringer.
56func (f StringerFunc) String() string {
57	return f()
58}
59
60// GotFormatter is used to better print failure messages. If a matcher
61// implements GotFormatter, it will use the result from Got when printing
62// the failure message.
63type GotFormatter interface {
64	// Got is invoked with the received value. The result is used when
65	// printing the failure message.
66	Got(got interface{}) string
67}
68
69// GotFormatterFunc type is an adapter to allow the use of ordinary
70// functions as a GotFormatter. If f is a function with the appropriate
71// signature, GotFormatterFunc(f) is a GotFormatter that calls f.
72type GotFormatterFunc func(got interface{}) string
73
74// Got implements GotFormatter.
75func (f GotFormatterFunc) Got(got interface{}) string {
76	return f(got)
77}
78
79// GotFormatterAdapter attaches a GotFormatter to a Matcher.
80func GotFormatterAdapter(s GotFormatter, m Matcher) Matcher {
81	return struct {
82		GotFormatter
83		Matcher
84	}{
85		GotFormatter: s,
86		Matcher:      m,
87	}
88}
89
90type anyMatcher struct{}
91
92func (anyMatcher) Matches(interface{}) bool {
93	return true
94}
95
96func (anyMatcher) String() string {
97	return "is anything"
98}
99
100type eqMatcher struct {
101	x interface{}
102}
103
104func (e eqMatcher) Matches(x interface{}) bool {
105	// In case, some value is nil
106	if e.x == nil || x == nil {
107		return reflect.DeepEqual(e.x, x)
108	}
109
110	// Check if types assignable and convert them to common type
111	x1Val := reflect.ValueOf(e.x)
112	x2Val := reflect.ValueOf(x)
113
114	if x1Val.Type().AssignableTo(x2Val.Type()) {
115		x1ValConverted := x1Val.Convert(x2Val.Type())
116		return reflect.DeepEqual(x1ValConverted.Interface(), x2Val.Interface())
117	}
118
119	return false
120}
121
122func (e eqMatcher) String() string {
123	return fmt.Sprintf("is equal to %v", e.x)
124}
125
126type nilMatcher struct{}
127
128func (nilMatcher) Matches(x interface{}) bool {
129	if x == nil {
130		return true
131	}
132
133	v := reflect.ValueOf(x)
134	switch v.Kind() {
135	case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map,
136		reflect.Ptr, reflect.Slice:
137		return v.IsNil()
138	}
139
140	return false
141}
142
143func (nilMatcher) String() string {
144	return "is nil"
145}
146
147type notMatcher struct {
148	m Matcher
149}
150
151func (n notMatcher) Matches(x interface{}) bool {
152	return !n.m.Matches(x)
153}
154
155func (n notMatcher) String() string {
156	// TODO: Improve this if we add a NotString method to the Matcher interface.
157	return "not(" + n.m.String() + ")"
158}
159
160type assignableToTypeOfMatcher struct {
161	targetType reflect.Type
162}
163
164func (m assignableToTypeOfMatcher) Matches(x interface{}) bool {
165	return reflect.TypeOf(x).AssignableTo(m.targetType)
166}
167
168func (m assignableToTypeOfMatcher) String() string {
169	return "is assignable to " + m.targetType.Name()
170}
171
172type allMatcher struct {
173	matchers []Matcher
174}
175
176func (am allMatcher) Matches(x interface{}) bool {
177	for _, m := range am.matchers {
178		if !m.Matches(x) {
179			return false
180		}
181	}
182	return true
183}
184
185func (am allMatcher) String() string {
186	ss := make([]string, 0, len(am.matchers))
187	for _, matcher := range am.matchers {
188		ss = append(ss, matcher.String())
189	}
190	return strings.Join(ss, "; ")
191}
192
193type lenMatcher struct {
194	i int
195}
196
197func (m lenMatcher) Matches(x interface{}) bool {
198	v := reflect.ValueOf(x)
199	switch v.Kind() {
200	case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice, reflect.String:
201		return v.Len() == m.i
202	default:
203		return false
204	}
205}
206
207func (m lenMatcher) String() string {
208	return fmt.Sprintf("has length %d", m.i)
209}
210
211// Constructors
212
213// All returns a composite Matcher that returns true if and only all of the
214// matchers return true.
215func All(ms ...Matcher) Matcher { return allMatcher{ms} }
216
217// Any returns a matcher that always matches.
218func Any() Matcher { return anyMatcher{} }
219
220// Eq returns a matcher that matches on equality.
221//
222// Example usage:
223//   Eq(5).Matches(5) // returns true
224//   Eq(5).Matches(4) // returns false
225func Eq(x interface{}) Matcher { return eqMatcher{x} }
226
227// Len returns a matcher that matches on length. This matcher returns false if
228// is compared to a type that is not an array, chan, map, slice, or string.
229func Len(i int) Matcher {
230	return lenMatcher{i}
231}
232
233// Nil returns a matcher that matches if the received value is nil.
234//
235// Example usage:
236//   var x *bytes.Buffer
237//   Nil().Matches(x) // returns true
238//   x = &bytes.Buffer{}
239//   Nil().Matches(x) // returns false
240func Nil() Matcher { return nilMatcher{} }
241
242// Not reverses the results of its given child matcher.
243//
244// Example usage:
245//   Not(Eq(5)).Matches(4) // returns true
246//   Not(Eq(5)).Matches(5) // returns false
247func Not(x interface{}) Matcher {
248	if m, ok := x.(Matcher); ok {
249		return notMatcher{m}
250	}
251	return notMatcher{Eq(x)}
252}
253
254// AssignableToTypeOf is a Matcher that matches if the parameter to the mock
255// function is assignable to the type of the parameter to this function.
256//
257// Example usage:
258//   var s fmt.Stringer = &bytes.Buffer{}
259//   AssignableToTypeOf(s).Matches(time.Second) // returns true
260//   AssignableToTypeOf(s).Matches(99) // returns false
261//
262//   var ctx = reflect.TypeOf((*context.Context)(nil)).Elem()
263//   AssignableToTypeOf(ctx).Matches(context.Background()) // returns true
264func AssignableToTypeOf(x interface{}) Matcher {
265	if xt, ok := x.(reflect.Type); ok {
266		return assignableToTypeOfMatcher{xt}
267	}
268	return assignableToTypeOfMatcher{reflect.TypeOf(x)}
269}
270