-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient_test.go
250 lines (213 loc) · 7.71 KB
/
client_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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
package lugo4go
import (
"context"
"errors"
"fmt"
"io"
"log"
"net"
"testing"
"time"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert"
"google.golang.org/grpc"
"github.com/lugobots/lugo4go/v3/proto"
)
const testServerPort = 2222
func NewMockServer(ctx context.Context, ctr *gomock.Controller, port int16) (*MockGameServer, error) {
mock := NewMockGameServer(ctr)
gRPCServer := grpc.NewServer()
proto.RegisterGameServer(gRPCServer, mock)
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
if err != nil {
return nil, err
}
go func() {
<-ctx.Done()
gRPCServer.Stop()
}()
go func() {
if err := gRPCServer.Serve(lis); err != nil {
log.Fatalf("test server has stopped: %s", err)
}
}()
return mock, nil
}
func TestNewRawClient(t *testing.T) {
// initiates Mock controller
ctrl := gomock.NewController(t)
defer ctrl.Finish() // checks all expected things for mocks
ctx, stop := context.WithCancel(context.Background())
defer stop()
// creates a fake server to test our Client
srv, err := NewMockServer(ctx, ctrl, testServerPort)
if err != nil {
t.Fatalf("did not start mock server: %s", err)
}
config := Config{
GRPCAddress: fmt.Sprintf(":%d", testServerPort),
Insecure: true,
TeamSide: proto.Team_HOME,
Number: 3,
InitialPosition: &proto.Point{X: 4000, Y: 4000},
}
// it is an async test, we have to wait some stuff be done before finishing the game, but we do not want to freeze
waiting, done := context.WithTimeout(context.Background(), 500*time.Millisecond)
// the Client will try to join to a team, so our server need to expect it happens
srv.EXPECT().JoinATeam(NewMatcher(func(arg interface{}) bool {
expectedRequest := &proto.JoinRequest{
Number: uint32(config.Number),
InitPosition: config.InitialPosition,
TeamSide: config.TeamSide,
ProtocolVersion: ProtocolVersion,
}
defer done()
return fmt.Sprintf("%s", arg) == fmt.Sprintf("%s", expectedRequest)
}), gomock.Any()).Return(nil)
// Now we may create the Client to connect to our fake server
playerClient, err := NewClient(config, DefaultLogger(config))
// This last lines may run really quickly, and the server may not have ran the expected methods yet
// Let's give some time to the server run it before finish the test function
<-waiting.Done()
if err != nil {
t.Fatalf("did not connect to the server: %s", err)
}
if err := playerClient.Stop(); err != nil {
t.Fatalf("did not connect to the server: %s", err)
}
}
func TestClient_PlayEndsTheConnectionCorrectly(t *testing.T) {
// initiates Mock controller
ctrl := gomock.NewController(t)
defer ctrl.Finish() // checks all expected things for mocks
// defining mocks and expected method calls
mockStream := NewMockGame_JoinATeamClient(ctrl)
mockGRPCClient := NewMockGameClient(ctrl)
mockHandler := NewMockRawBot(ctrl)
mockSender := NewMockOrderSender(ctrl)
c := &Client{
Stream: mockStream,
GRPCClient: mockGRPCClient,
config: Config{
TeamSide: proto.Team_AWAY,
Number: 5,
},
Logger: DefaultLogger(Config{}),
Sender: mockSender,
}
// it is an async test, we have to wait some stuff be done before finishing the game, but we do not want to freeze
waiting, done := context.WithTimeout(context.Background(), 500*time.Millisecond)
// defining expectations
expectedSnapshot := &proto.GameSnapshot{
State: proto.GameSnapshot_LISTENING,
Turn: 200,
AwayTeam: &proto.Team{
Players: []*proto.Player{
{Number: 5},
},
},
}
mockStream.EXPECT().Recv().Return(expectedSnapshot, nil)
mockStream.EXPECT().Recv().DoAndReturn(func() {
//let's pretend some interval between messages
time.Sleep(50 * time.Millisecond)
}).Return(nil, io.EOF)
mockHandler.EXPECT().TurnHandler(gomock.Any(), gomock.Any())
mockSender.EXPECT().Send(gomock.Any(), gomock.Any(), nil, "").Return(&proto.OrderResponse{Code: proto.OrderResponse_SUCCESS}, nil)
err := c.Play(mockHandler)
done()
assert.Equal(t, ErrGRPCConnectionClosed, err)
if waiting.Err() != context.Canceled {
t.Errorf("Unexpected waiting - Expected %v, Got %v", context.Canceled, waiting.Err())
}
}
func TestClient_PlayReturnsTheRightError(t *testing.T) {
// initiates Mock controller
ctrl := gomock.NewController(t)
defer ctrl.Finish() // checks all expected things for mocks
// defining mocks and expected method calls
mockStream := NewMockGame_JoinATeamClient(ctrl)
mockGRPCClient := NewMockGameClient(ctrl)
mockHandler := NewMockRawBot(ctrl)
c := &Client{
Stream: mockStream,
GRPCClient: mockGRPCClient,
Logger: DefaultLogger(Config{}),
}
// it is an async test, we have to wait some stuff be done before finishing the game, but we do not want to freeze
waiting, done := context.WithTimeout(context.Background(), 500*time.Millisecond)
// defining expectations
expectedError := errors.New("some-error")
mockStream.EXPECT().Recv().DoAndReturn(func() {
//let's pretend some interval between messages
time.Sleep(50 * time.Millisecond)
}).Return(nil, expectedError)
err := c.Play(mockHandler)
done()
assert.True(t, errors.Is(err, ErrGRPCConnectionLost))
if waiting.Err() != context.Canceled {
t.Errorf("Unexpected waiting - Expected %v, Got %v", context.Canceled, waiting.Err())
}
}
func TestClient_PlayShouldStopContextWhenANewTurnStarts(t *testing.T) {
// initiates Mock controller
ctrl := gomock.NewController(t)
defer ctrl.Finish() // checks all expected things for mocks
// defining mocks and expected method calls
mockStream := NewMockGame_JoinATeamClient(ctrl)
mockGRPCClient := NewMockGameClient(ctrl)
mockHandler := NewMockRawBot(ctrl)
mockSender := NewMockOrderSender(ctrl)
c := &Client{
Stream: mockStream,
GRPCClient: mockGRPCClient,
config: Config{
TeamSide: proto.Team_AWAY,
Number: 5,
},
Sender: mockSender,
Logger: DefaultLogger(Config{}),
}
// it is an async test, we have to wait some stuff be done before finishing the game, but we do not want to freeze
waiting, done := context.WithTimeout(context.Background(), 500*time.Millisecond)
awayTeam := &proto.Team{
Players: []*proto.Player{
{Number: 5},
},
}
// defining expectations
expectedSnapshotA := &proto.GameSnapshot{State: proto.GameSnapshot_LISTENING, Turn: 200, AwayTeam: awayTeam}
expectedSnapshotB := &proto.GameSnapshot{State: proto.GameSnapshot_LISTENING, Turn: 201, AwayTeam: awayTeam}
mockStream.EXPECT().Recv().Return(expectedSnapshotA, nil)
mockStream.EXPECT().Recv().Return(expectedSnapshotB, nil)
mockStream.EXPECT().Recv().Return(nil, io.EOF)
firstHandlerIsExpired := false
holder := make(chan bool, 1)
// this is the first time the rawBotWrapper will be called
// we expect that it finishes immediately after the stream gets a new turn msg
// if it does not, the next rawBotWrapper will unblock it, but it will be considered an error
mockHandler.EXPECT().
TurnHandler(gomock.Any(), gomock.Any()).
DoAndReturn(func(ctx context.Context, inspector SnapshotInspector) {
select {
case <-ctx.Done():
firstHandlerIsExpired = true
case <-holder:
firstHandlerIsExpired = false
}
}).Return(nil, "", nil)
// the second call to rawBotWrapper will close our channel just to ensure anything will be left behind in your test
mockHandler.EXPECT().
TurnHandler(gomock.Any(), gomock.Any()).
DoAndReturn(func(ctx context.Context, inspector SnapshotInspector) {
close(holder)
}).Return(nil, "", nil)
mockSender.EXPECT().Send(gomock.Any(), gomock.Any(), nil, "").Return(&proto.OrderResponse{Code: proto.OrderResponse_SUCCESS}, nil).AnyTimes()
err := c.Play(mockHandler)
done()
assert.Equal(t, ErrGRPCConnectionClosed, err)
assert.True(t, firstHandlerIsExpired)
if waiting.Err() != context.Canceled {
t.Errorf("Unexpected waiting - Expected %v, Got %v", context.Canceled, waiting.Err())
}
}