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

Commit

Permalink
gomock/controller: use skip additional frame (#443)
Browse files Browse the repository at this point in the history
In 8321731, the callerInfo call
gets nested within an additional function call, but the frame skip
isn't updated. When used with mockgen, this causes the location frame
to unhelpfully point to the generated mock instead of the callsite in
the user's test.

Add an explanation for future readers, explaining callerInfo and when it
should be updated.
  • Loading branch information
stephen committed Jun 12, 2020
1 parent b76a85f commit d9ac678
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
3 changes: 3 additions & 0 deletions gomock/call.go
Expand Up @@ -63,6 +63,9 @@ func newCall(t TestHelper, receiver interface{}, method string, methodType refle
}
}

// callerInfo's skip should be updated if the number of calls between the user's test
// and this line changes, i.e. this code is wrapped in another anonymous function.
// 0 is us, 1 is RecordCallWithMethodType(), 2 is the generated recorder, and 3 is the user's test.
origin := callerInfo(3)
actions := []func([]interface{}) []interface{}{func([]interface{}) []interface{} {
// Synthesize the zero value for each of the return args' types.
Expand Down
7 changes: 6 additions & 1 deletion gomock/controller.go
Expand Up @@ -224,7 +224,10 @@ func (ctrl *Controller) Call(receiver interface{}, method string, args ...interf

expected, err := ctrl.expectedCalls.FindMatch(receiver, method, args)
if err != nil {
origin := callerInfo(2)
// callerInfo's skip should be updated if the number of calls between the user's test
// and this line changes, i.e. this code is wrapped in another anonymous function.
// 0 is us, 1 is controller.Call(), 2 is the generated mock, and 3 is the user's test.
origin := callerInfo(3)
ctrl.T.Fatalf("Unexpected call to %T.%v(%v) at %s because: %s", receiver, method, args, origin, err)
}

Expand Down Expand Up @@ -291,6 +294,8 @@ func (ctrl *Controller) Finish() {
}
}

// callerInfo returns the file:line of the call site. skip is the number
// of stack frames to skip when reporting. 0 is callerInfo's call site.
func callerInfo(skip int) string {
if _, file, line, ok := runtime.Caller(skip + 1); ok {
return fmt.Sprintf("%s:%d", file, line)
Expand Down

0 comments on commit d9ac678

Please sign in to comment.