Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Example code and documentation on how to mock gRPC services #1021

Merged
merged 9 commits into from
Feb 14, 2017
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,6 @@ before_install:
script:
- '! gofmt -s -d -l . 2>&1 | read'
- '! goimports -l . | read'
- 'if [[ $TRAVIS_GO_VERSION != 1.5* ]]; then ! golint ./... | grep -vE "(_string|\.pb)\.go:"; fi'
- 'if [[ $TRAVIS_GO_VERSION != 1.5* ]]; then ! golint ./... | grep -vE "(_mock|_string|\.pb)\.go:"; fi'
- '! go tool vet -all . 2>&1 | grep -vE "constant [0-9]+ not a string in call to Errorf" | grep -vF .pb.go:' # https://github.com/golang/protobuf/issues/214
- make test testrace
121 changes: 121 additions & 0 deletions Documentation/gomock-example.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
# Mocking Service for gRPC

Example code: examples/helloworld/mock
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add a link here to the folder.
And a one line file summary?


## Why?

To test client-side logic without the overhead of connecting to a real server. Mocking enables users to write light-weight unit tests to check functionalities on client-side without invoking RPC calls to a server.

## Idea: Mock the client stub that connects to the server.

We use Gomock to mock the client interface (in the generated code) and programmatically set its methods to expect and return pre-determined values. This enables users to write tests around the client logic and use this mocked stub while making RPC calls.

## How to use Gomock?

Documentation on Gomock can be found [here](https://github.com/golang/mock).
A quick reading of the documentation should enable users to follow the code below.

Consider a gRPC service based on following proto file:

```proto
//helloworld.proto

package helloworld;

message HelloRequest {
string name = 1;
}

message HelloReply {
string name = 1;
}

service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
```

The generated file helloworld.pb.go will have a client interface for each service defined in the proto file. This interface will have methods corresponding to each rpc inside that service.

```Go
type GreeterClient interface {
SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error)
}
```

The generated code also contains a struct that implements this interface.

```Go
type greeterClient struct {
cc *grpc.ClientConn
}
func (c *greeterClient) SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error){
// ...
// gRPC specific code here
// ...
}
```

Along with this the generated code has a method to create an instance of this struct.
```Go
func NewGreeterClient(cc *grpc.ClientConn) GreeterClient
```

The user code uses this function to create an instance of the struct greeterClient which then can be used to make rpc calls to the server.
We will mock this interface GreeterClient and use an instance of that mock to make rpc calls. These calls instead of going to server will return pre-determined values.

To create a mock we’ll use [mockgen](https://github.com/golang/mock#running-mockgen).
From the directory ``` examples/helloworld/mock/ ``` run ``` mockgen google.golang.org/grpc/examples/helloworld/helloworld GreeterClient > mock_helloworld/hw_mock.go ```

Notice that in the above command we specify GreeterClient as the interface to be mocked.

The user test code can import the package generated by mockgen along with library package gomock to write unit tests around client-side logic.
```Go
import "github.com/golang/mock/gomock"
import hwmock "google.golang.org/grpc/examples/helloworld/mock/mock_helloworld"
```

An instance of the mocked interface can be created as:
```Go
mockGreeterClient := hwmock.NewMockGreeterClient(ctrl)
```
This mocked object can be programmed to expect calls to its methods and return pre-determined values. For instance, we can program mockGreeterClient to expect a call to its method SayHello and return a HelloReply with message “Mocked RPC”.

```Go
mockGreeterClient.EXPECT().SayHello(
gomock.Any(), // expect any value for first parameter
gomock.Any(), // expect any value for second parameter
).Return(&helloworld.HelloReply{Message: “Mocked RPC”},nil)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add a space before nil

```

gomock.Any() indicates that the parameter can have any value or type. We can indicate specific values for built-in types with gomock.Eq().
However, if the test code needs to specify the parameter to have a proto message type, we can replace gomock.Any() with an instance of a struct that implements gomock.Matcher interface.

```Go
type rpcMsg struct {
msg proto.Message
}

func (r *rpcMsg) Matches(msg interface{}) bool {
m, ok := msg.(proto.Message)
if !ok {
return false
}
return proto.Equal(m, r.msg)
}

func (r *rpcMsg) String() string {
return fmt.Sprintf("is %s", r.msg)
}

...

req := &helloworld.HelloRequest{Name: "unit_test"}
mockGreeterClient.EXPECT().SayHello(
gomock.Any(),
&rpcMsg{msg: req},
).Return(&helloworld.HelloReply{Message: "Mocked Interface"}, nil)
```



2 changes: 2 additions & 0 deletions examples/helloworld/mock/generate_mock.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
mockgen google.golang.org/grpc/examples/helloworld/helloworld GreeterClient > mock_helloworld/hw_mock.go
gofmt -w mock_helloworld/hw_mock.go
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this file necessary? We already have the commands in the md file.
(And why do we need the gofmt here?

49 changes: 49 additions & 0 deletions examples/helloworld/mock/hw_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package mock

import (
"fmt"
"testing"

"github.com/golang/mock/gomock"
proto "github.com/golang/protobuf/proto"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The renaming is unnecessary.

"golang.org/x/net/context"
"google.golang.org/grpc/examples/helloworld/helloworld"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add alias for this import because it is a proto.

hwmock "google.golang.org/grpc/examples/helloworld/mock/mock_helloworld"
)

// rpcMsg implements the gomock.Matcher interface
type rpcMsg struct {
msg proto.Message
}

func (r *rpcMsg) Matches(msg interface{}) bool {
m, ok := msg.(proto.Message)
if !ok {
return false
}
return proto.Equal(m, r.msg)
}

func (r *rpcMsg) String() string {
return fmt.Sprintf("is %s", r.msg)
}

func TestSayHello(t *testing.T) {
ctrl := gomock.NewController(t)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wrap this in a function createMock returning a mocking client?

defer ctrl.Finish()
mockGreeterClient := hwmock.NewMockGreeterClient(ctrl)
req := &helloworld.HelloRequest{Name: "unit_test"}
mockGreeterClient.EXPECT().SayHello(
gomock.Any(),
&rpcMsg{msg: req},
).Return(&helloworld.HelloReply{Message: "Mocked Interface"}, nil)
testSayHello(t, mockGreeterClient)
}

func testSayHello(t *testing.T, client helloworld.GreeterClient) {
r, err := client.SayHello(context.Background(), &helloworld.HelloRequest{Name: "unit_test"})
if err != nil || r.Message != "Mocked Interface" {
t.Errorf("mocking failed")
}
t.Log("Reply : ", r.Message)
}
48 changes: 48 additions & 0 deletions examples/helloworld/mock/mock_helloworld/hw_mock.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// Automatically generated by MockGen. DO NOT EDIT!
// Source: google.golang.org/grpc/examples/helloworld/helloworld (interfaces: GreeterClient)

package mock_helloworld

import (
gomock "github.com/golang/mock/gomock"
context "golang.org/x/net/context"
grpc "google.golang.org/grpc"
helloworld "google.golang.org/grpc/examples/helloworld/helloworld"
)

// Mock of GreeterClient interface
type MockGreeterClient struct {
ctrl *gomock.Controller
recorder *_MockGreeterClientRecorder
}

// Recorder for MockGreeterClient (not exported)
type _MockGreeterClientRecorder struct {
mock *MockGreeterClient
}

func NewMockGreeterClient(ctrl *gomock.Controller) *MockGreeterClient {
mock := &MockGreeterClient{ctrl: ctrl}
mock.recorder = &_MockGreeterClientRecorder{mock}
return mock
}

func (_m *MockGreeterClient) EXPECT() *_MockGreeterClientRecorder {
return _m.recorder
}

func (_m *MockGreeterClient) SayHello(_param0 context.Context, _param1 *helloworld.HelloRequest, _param2 ...grpc.CallOption) (*helloworld.HelloReply, error) {
_s := []interface{}{_param0, _param1}
for _, _x := range _param2 {
_s = append(_s, _x)
}
ret := _m.ctrl.Call(_m, "SayHello", _s...)
ret0, _ := ret[0].(*helloworld.HelloReply)
ret1, _ := ret[1].(error)
return ret0, ret1
}

func (_mr *_MockGreeterClientRecorder) SayHello(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {
_s := append([]interface{}{arg0, arg1}, arg2...)
return _mr.mock.ctrl.RecordCall(_mr.mock, "SayHello", _s...)
}