-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathmock_test.go
75 lines (61 loc) · 1.88 KB
/
mock_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package main
import (
"context"
"fmt"
"testing"
"time"
"github.com/golang/mock/gomock"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/ptypes/empty"
pubsub_mock "github.com/vardius/pubsub/v2/mock_proto"
pubsub_proto "github.com/vardius/pubsub/v2/proto"
)
var topic = "my-topic"
var msg = []byte("Hello you!")
var emptyResponse *empty.Empty
var subscribeResponse = &pubsub_proto.SubscribeResponse{Payload: msg}
var publishRequest = &pubsub_proto.PublishRequest{Topic: topic, Payload: msg}
var subscribeRequest = &pubsub_proto.SubscribeRequest{Topic: topic}
func TestServer(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
// Create mock for the stream returned by Subscribe
stream := pubsub_mock.NewMockPubSub_SubscribeClient(ctrl)
// Set expectation on receiving.
stream.EXPECT().Recv().Return(subscribeResponse, nil)
stream.EXPECT().CloseSend().Return(nil)
// Create mock for the client interface.
client := pubsub_mock.NewMockPubSubClient(ctrl)
// Set expectation on Publish
client.EXPECT().Publish(gomock.Any(), publishRequest).Return(emptyResponse, nil)
// Set expectation on Subscribe
client.EXPECT().Subscribe(gomock.Any(), subscribeRequest).Return(stream, nil)
if err := testPubSub(client); err != nil {
t.Fatalf("Test failed: %v", err)
}
}
func testPubSub(client pubsub_proto.PubSubClient) error {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// test Subscribe
stream, err := client.Subscribe(ctx, subscribeRequest)
if err != nil {
return err
}
if err := stream.CloseSend(); err != nil {
return err
}
got, err := stream.Recv()
if err != nil {
return err
}
if !proto.Equal(got, subscribeResponse) {
return fmt.Errorf("stream.Recv() = %v, want %v", got, subscribeResponse)
}
// test Publish
_, err = client.Publish(ctx, publishRequest)
if err != nil {
return err
}
return nil
}