How to use setMap method of gomock Package

Best Mock code snippet using gomock.setMap

Run Mock automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

call.go

Source: call.go Github

copy
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	"strconv"
21	"strings"
22)
23
24// Call represents an expected call to a mock.
25type Call struct {
26	t TestHelper // for triggering test failures on invalid call setup
27
28	receiver   interface{}  // the receiver of the method call
29	method     string       // the name of the method
30	methodType reflect.Type // the type of the method
31	args       []Matcher    // the args
32	origin     string       // file and line number of call setup
33
34	preReqs []*Call // prerequisite calls
35
36	// Expectations
37	minCalls, maxCalls int
38
39	numCalls int // actual number made
40
41	// actions are called when this Call is called. Each action gets the args and
42	// can set the return values by returning a non-nil slice. Actions run in the
43	// order they are created.
44	actions []func([]interface{}) []interface{}
45}
46
47// newCall creates a *Call. It requires the method type in order to support
48// unexported methods.
49func newCall(t TestHelper, receiver interface{}, method string, methodType reflect.Type, args ...interface{}) *Call {
50	t.Helper()
51
52	// TODO: check arity, types.
53	mArgs := make([]Matcher, len(args))
54	for i, arg := range args {
55		if m, ok := arg.(Matcher); ok {
56			mArgs[i] = m
57		} else if arg == nil {
58			// Handle nil specially so that passing a nil interface value
59			// will match the typed nils of concrete args.
60			mArgs[i] = Nil()
61		} else {
62			mArgs[i] = Eq(arg)
63		}
64	}
65
66	// callerInfo's skip should be updated if the number of calls between the user's test
67	// and this line changes, i.e. this code is wrapped in another anonymous function.
68	// 0 is us, 1 is RecordCallWithMethodType(), 2 is the generated recorder, and 3 is the user's test.
69	origin := callerInfo(3)
70	actions := []func([]interface{}) []interface{}{func([]interface{}) []interface{} {
71		// Synthesize the zero value for each of the return args' types.
72		rets := make([]interface{}, methodType.NumOut())
73		for i := 0; i < methodType.NumOut(); i++ {
74			rets[i] = reflect.Zero(methodType.Out(i)).Interface()
75		}
76		return rets
77	}}
78	return &Call{t: t, receiver: receiver, method: method, methodType: methodType,
79		args: mArgs, origin: origin, minCalls: 1, maxCalls: 1, actions: actions}
80}
81
82// AnyTimes allows the expectation to be called 0 or more times
83func (c *Call) AnyTimes() *Call {
84	c.minCalls, c.maxCalls = 0, 1e8 // close enough to infinity
85	return c
86}
87
88// MinTimes requires the call to occur at least n times. If AnyTimes or MaxTimes have not been called or if MaxTimes
89// was previously called with 1, MinTimes also sets the maximum number of calls to infinity.
90func (c *Call) MinTimes(n int) *Call {
91	c.minCalls = n
92	if c.maxCalls == 1 {
93		c.maxCalls = 1e8
94	}
95	return c
96}
97
98// MaxTimes limits the number of calls to n times. If AnyTimes or MinTimes have not been called or if MinTimes was
99// previously called with 1, MaxTimes also sets the minimum number of calls to 0.
100func (c *Call) MaxTimes(n int) *Call {
101	c.maxCalls = n
102	if c.minCalls == 1 {
103		c.minCalls = 0
104	}
105	return c
106}
107
108// DoAndReturn declares the action to run when the call is matched.
109// The return values from this function are returned by the mocked function.
110// It takes an interface{} argument to support n-arity functions.
111// The anonymous function must match the function signature mocked method.
112func (c *Call) DoAndReturn(f interface{}) *Call {
113	// TODO: Check arity and types here, rather than dying badly elsewhere.
114	v := reflect.ValueOf(f)
115
116	c.addAction(func(args []interface{}) []interface{} {
117		c.t.Helper()
118		ft := v.Type()
119		if c.methodType.NumIn() != ft.NumIn() {
120			if ft.IsVariadic() {
121				c.t.Fatalf("wrong number of arguments in DoAndReturn func for %T.%v The function signature must match the mocked method, a variadic function cannot be used.",
122					c.receiver, c.method)
123			} else {
124				c.t.Fatalf("wrong number of arguments in DoAndReturn func for %T.%v: got %d, want %d [%s]",
125					c.receiver, c.method, ft.NumIn(), c.methodType.NumIn(), c.origin)
126			}
127			return nil
128		}
129		vArgs := make([]reflect.Value, len(args))
130		for i := 0; i < len(args); i++ {
131			if args[i] != nil {
132				vArgs[i] = reflect.ValueOf(args[i])
133			} else {
134				// Use the zero value for the arg.
135				vArgs[i] = reflect.Zero(ft.In(i))
136			}
137		}
138		vRets := v.Call(vArgs)
139		rets := make([]interface{}, len(vRets))
140		for i, ret := range vRets {
141			rets[i] = ret.Interface()
142		}
143		return rets
144	})
145	return c
146}
147
148// Do declares the action to run when the call is matched. The function's
149// return values are ignored to retain backward compatibility. To use the
150// return values call DoAndReturn.
151// It takes an interface{} argument to support n-arity functions.
152// The anonymous function must match the function signature mocked method.
153func (c *Call) Do(f interface{}) *Call {
154	// TODO: Check arity and types here, rather than dying badly elsewhere.
155	v := reflect.ValueOf(f)
156
157	c.addAction(func(args []interface{}) []interface{} {
158		c.t.Helper()
159		ft := v.Type()
160		if c.methodType.NumIn() != ft.NumIn() {
161			if ft.IsVariadic() {
162				c.t.Fatalf("wrong number of arguments in Do func for %T.%v The function signature must match the mocked method, a variadic function cannot be used.",
163					c.receiver, c.method)
164			} else {
165				c.t.Fatalf("wrong number of arguments in Do func for %T.%v: got %d, want %d [%s]",
166					c.receiver, c.method, ft.NumIn(), c.methodType.NumIn(), c.origin)
167			}
168			return nil
169		}
170		vArgs := make([]reflect.Value, len(args))
171		for i := 0; i < len(args); i++ {
172			if args[i] != nil {
173				vArgs[i] = reflect.ValueOf(args[i])
174			} else {
175				// Use the zero value for the arg.
176				vArgs[i] = reflect.Zero(ft.In(i))
177			}
178		}
179		v.Call(vArgs)
180		return nil
181	})
182	return c
183}
184
185// Return declares the values to be returned by the mocked function call.
186func (c *Call) Return(rets ...interface{}) *Call {
187	c.t.Helper()
188
189	mt := c.methodType
190	if len(rets) != mt.NumOut() {
191		c.t.Fatalf("wrong number of arguments to Return for %T.%v: got %d, want %d [%s]",
192			c.receiver, c.method, len(rets), mt.NumOut(), c.origin)
193	}
194	for i, ret := range rets {
195		if got, want := reflect.TypeOf(ret), mt.Out(i); got == want {
196			// Identical types; nothing to do.
197		} else if got == nil {
198			// Nil needs special handling.
199			switch want.Kind() {
200			case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
201				// ok
202			default:
203				c.t.Fatalf("argument %d to Return for %T.%v is nil, but %v is not nillable [%s]",
204					i, c.receiver, c.method, want, c.origin)
205			}
206		} else if got.AssignableTo(want) {
207			// Assignable type relation. Make the assignment now so that the generated code
208			// can return the values with a type assertion.
209			v := reflect.New(want).Elem()
210			v.Set(reflect.ValueOf(ret))
211			rets[i] = v.Interface()
212		} else {
213			c.t.Fatalf("wrong type of argument %d to Return for %T.%v: %v is not assignable to %v [%s]",
214				i, c.receiver, c.method, got, want, c.origin)
215		}
216	}
217
218	c.addAction(func([]interface{}) []interface{} {
219		return rets
220	})
221
222	return c
223}
224
225// Times declares the exact number of times a function call is expected to be executed.
226func (c *Call) Times(n int) *Call {
227	c.minCalls, c.maxCalls = n, n
228	return c
229}
230
231// SetArg declares an action that will set the nth argument's value,
232// indirected through a pointer. Or, in the case of a slice and map, SetArg
233// will copy value's elements/key-value pairs into the nth argument.
234func (c *Call) SetArg(n int, value interface{}) *Call {
235	c.t.Helper()
236
237	mt := c.methodType
238	// TODO: This will break on variadic methods.
239	// We will need to check those at invocation time.
240	if n < 0 || n >= mt.NumIn() {
241		c.t.Fatalf("SetArg(%d, ...) called for a method with %d args [%s]",
242			n, mt.NumIn(), c.origin)
243	}
244	// Permit setting argument through an interface.
245	// In the interface case, we don't (nay, can't) check the type here.
246	at := mt.In(n)
247	switch at.Kind() {
248	case reflect.Ptr:
249		dt := at.Elem()
250		if vt := reflect.TypeOf(value); !vt.AssignableTo(dt) {
251			c.t.Fatalf("SetArg(%d, ...) argument is a %v, not assignable to %v [%s]",
252				n, vt, dt, c.origin)
253		}
254	case reflect.Interface:
255		// nothing to do
256	case reflect.Slice:
257		// nothing to do
258	case reflect.Map:
259		// nothing to do
260	default:
261		c.t.Fatalf("SetArg(%d, ...) referring to argument of non-pointer non-interface non-slice non-map type %v [%s]",
262			n, at, c.origin)
263	}
264
265	c.addAction(func(args []interface{}) []interface{} {
266		v := reflect.ValueOf(value)
267		switch reflect.TypeOf(args[n]).Kind() {
268		case reflect.Slice:
269			setSlice(args[n], v)
270		case reflect.Map:
271			setMap(args[n], v)
272		default:
273			reflect.ValueOf(args[n]).Elem().Set(v)
274		}
275		return nil
276	})
277	return c
278}
279
280// isPreReq returns true if other is a direct or indirect prerequisite to c.
281func (c *Call) isPreReq(other *Call) bool {
282	for _, preReq := range c.preReqs {
283		if other == preReq || preReq.isPreReq(other) {
284			return true
285		}
286	}
287	return false
288}
289
290// After declares that the call may only match after preReq has been exhausted.
291func (c *Call) After(preReq *Call) *Call {
292	c.t.Helper()
293
294	if c == preReq {
295		c.t.Fatalf("A call isn't allowed to be its own prerequisite")
296	}
297	if preReq.isPreReq(c) {
298		c.t.Fatalf("Loop in call order: %v is a prerequisite to %v (possibly indirectly).", c, preReq)
299	}
300
301	c.preReqs = append(c.preReqs, preReq)
302	return c
303}
304
305// Returns true if the minimum number of calls have been made.
306func (c *Call) satisfied() bool {
307	return c.numCalls >= c.minCalls
308}
309
310// Returns true if the maximum number of calls have been made.
311func (c *Call) exhausted() bool {
312	return c.numCalls >= c.maxCalls
313}
314
315func (c *Call) String() string {
316	args := make([]string, len(c.args))
317	for i, arg := range c.args {
318		args[i] = arg.String()
319	}
320	arguments := strings.Join(args, ", ")
321	return fmt.Sprintf("%T.%v(%s) %s", c.receiver, c.method, arguments, c.origin)
322}
323
324// Tests if the given call matches the expected call.
325// If yes, returns nil. If no, returns error with message explaining why it does not match.
326func (c *Call) matches(args []interface{}) error {
327	if !c.methodType.IsVariadic() {
328		if len(args) != len(c.args) {
329			return fmt.Errorf("expected call at %s has the wrong number of arguments. Got: %d, want: %d",
330				c.origin, len(args), len(c.args))
331		}
332
333		for i, m := range c.args {
334			if !m.Matches(args[i]) {
335				return fmt.Errorf(
336					"expected call at %s doesn't match the argument at index %d.\nGot: %v\nWant: %v",
337					c.origin, i, formatGottenArg(m, args[i]), m,
338				)
339			}
340		}
341	} else {
342		if len(c.args) < c.methodType.NumIn()-1 {
343			return fmt.Errorf("expected call at %s has the wrong number of matchers. Got: %d, want: %d",
344				c.origin, len(c.args), c.methodType.NumIn()-1)
345		}
346		if len(c.args) != c.methodType.NumIn() && len(args) != len(c.args) {
347			return fmt.Errorf("expected call at %s has the wrong number of arguments. Got: %d, want: %d",
348				c.origin, len(args), len(c.args))
349		}
350		if len(args) < len(c.args)-1 {
351			return fmt.Errorf("expected call at %s has the wrong number of arguments. Got: %d, want: greater than or equal to %d",
352				c.origin, len(args), len(c.args)-1)
353		}
354
355		for i, m := range c.args {
356			if i < c.methodType.NumIn()-1 {
357				// Non-variadic args
358				if !m.Matches(args[i]) {
359					return fmt.Errorf("expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v",
360						c.origin, strconv.Itoa(i), formatGottenArg(m, args[i]), m)
361				}
362				continue
363			}
364			// The last arg has a possibility of a variadic argument, so let it branch
365
366			// sample: Foo(a int, b int, c ...int)
367			if i < len(c.args) && i < len(args) {
368				if m.Matches(args[i]) {
369					// Got Foo(a, b, c) want Foo(matcherA, matcherB, gomock.Any())
370					// Got Foo(a, b, c) want Foo(matcherA, matcherB, someSliceMatcher)
371					// Got Foo(a, b, c) want Foo(matcherA, matcherB, matcherC)
372					// Got Foo(a, b) want Foo(matcherA, matcherB)
373					// Got Foo(a, b, c, d) want Foo(matcherA, matcherB, matcherC, matcherD)
374					continue
375				}
376			}
377
378			// The number of actual args don't match the number of matchers,
379			// or the last matcher is a slice and the last arg is not.
380			// If this function still matches it is because the last matcher
381			// matches all the remaining arguments or the lack of any.
382			// Convert the remaining arguments, if any, into a slice of the
383			// expected type.
384			vArgsType := c.methodType.In(c.methodType.NumIn() - 1)
385			vArgs := reflect.MakeSlice(vArgsType, 0, len(args)-i)
386			for _, arg := range args[i:] {
387				vArgs = reflect.Append(vArgs, reflect.ValueOf(arg))
388			}
389			if m.Matches(vArgs.Interface()) {
390				// Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, gomock.Any())
391				// Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, someSliceMatcher)
392				// Got Foo(a, b) want Foo(matcherA, matcherB, gomock.Any())
393				// Got Foo(a, b) want Foo(matcherA, matcherB, someEmptySliceMatcher)
394				break
395			}
396			// Wrong number of matchers or not match. Fail.
397			// Got Foo(a, b) want Foo(matcherA, matcherB, matcherC, matcherD)
398			// Got Foo(a, b, c) want Foo(matcherA, matcherB, matcherC, matcherD)
399			// Got Foo(a, b, c, d) want Foo(matcherA, matcherB, matcherC, matcherD, matcherE)
400			// Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, matcherC, matcherD)
401			// Got Foo(a, b, c) want Foo(matcherA, matcherB)
402
403			return fmt.Errorf("expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v",
404				c.origin, strconv.Itoa(i), formatGottenArg(m, args[i:]), c.args[i])
405		}
406	}
407
408	// Check that all prerequisite calls have been satisfied.
409	for _, preReqCall := range c.preReqs {
410		if !preReqCall.satisfied() {
411			return fmt.Errorf("expected call at %s doesn't have a prerequisite call satisfied:\n%v\nshould be called before:\n%v",
412				c.origin, preReqCall, c)
413		}
414	}
415
416	// Check that the call is not exhausted.
417	if c.exhausted() {
418		return fmt.Errorf("expected call at %s has already been called the max number of times", c.origin)
419	}
420
421	return nil
422}
423
424// dropPrereqs tells the expected Call to not re-check prerequisite calls any
425// longer, and to return its current set.
426func (c *Call) dropPrereqs() (preReqs []*Call) {
427	preReqs = c.preReqs
428	c.preReqs = nil
429	return
430}
431
432func (c *Call) call() []func([]interface{}) []interface{} {
433	c.numCalls++
434	return c.actions
435}
436
437// InOrder declares that the given calls should occur in order.
438func InOrder(calls ...*Call) {
439	for i := 1; i < len(calls); i++ {
440		calls[i].After(calls[i-1])
441	}
442}
443
444func setSlice(arg interface{}, v reflect.Value) {
445	va := reflect.ValueOf(arg)
446	for i := 0; i < v.Len(); i++ {
447		va.Index(i).Set(v.Index(i))
448	}
449}
450
451func setMap(arg interface{}, v reflect.Value) {
452	va := reflect.ValueOf(arg)
453	for _, e := range va.MapKeys() {
454		va.SetMapIndex(e, reflect.Value{})
455	}
456	for _, e := range v.MapKeys() {
457		va.SetMapIndex(e, v.MapIndex(e))
458	}
459}
460
461func (c *Call) addAction(action func([]interface{}) []interface{}) {
462	c.actions = append(c.actions, action)
463}
464
465func formatGottenArg(m Matcher, arg interface{}) string {
466	got := fmt.Sprintf("%v (%T)", arg, arg)
467	if gs, ok := m.(GotFormatter); ok {
468		got = gs.Got(arg)
469	}
470	return got
471}
472
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)