-
Notifications
You must be signed in to change notification settings - Fork 1
/
serialclient_test.go
361 lines (280 loc) · 9.44 KB
/
serialclient_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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
package modbus
import (
"context"
"errors"
"github.com/aldas/go-modbus-client/packet"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"io"
"testing"
"time"
)
type serialMock struct {
mock.Mock
}
func (m *serialMock) Read(b []byte) (n int, err error) {
args := m.Called(b)
return args.Int(0), args.Error(1)
}
func (m *serialMock) Write(b []byte) (n int, err error) {
args := m.Called(b)
return args.Int(0), args.Error(1)
}
func (m *serialMock) Close() error {
args := m.Called()
return args.Error(0)
}
func (m *serialMock) Flush() error {
args := m.Called()
return args.Error(0)
}
func exampleFC1RTURequest() packet.Request {
return &packet.ReadCoilsRequestRTU{
ReadCoilsRequest: packet.ReadCoilsRequest{
UnitID: 16,
StartAddress: 200,
Quantity: 9,
},
}
}
func exampleFC1RTUResponse() packet.Response {
return &packet.ReadCoilsResponseRTU{
ReadCoilsResponse: packet.ReadCoilsResponse{
UnitID: 16,
// +1 function code
CoilsByteLength: 2,
Data: []byte{0x1, 0x2},
},
}
}
type mockSerialLogger struct {
mock.Mock
}
func (l *mockSerialLogger) BeforeWrite(toWrite []byte) {
l.Called(toWrite)
}
func (l *mockSerialLogger) AfterEachRead(received []byte, n int, err error) {
l.Called(received, n, err)
}
func (l *mockSerialLogger) BeforeParse(received []byte) {
l.Called(received)
}
func TestSerialClient_WithOptions(t *testing.T) {
serialMock := new(serialMock)
client := NewSerialClient(
serialMock,
WithSerialReadTimeout(4*time.Second),
WithSerialHooks(new(mockSerialLogger)),
)
assert.Equal(t, 4*time.Second, client.readTimeout)
assert.NotNil(t, client.asProtocolErrorFunc)
assert.NotNil(t, client.parseResponseFunc)
assert.Equal(t, new(mockSerialLogger), client.hooks)
}
func TestSerialClient_Do_receivePacketWith1Read(t *testing.T) {
serialPort := new(serialMock)
serialPort.On("Write", []byte{0x10, 0x1, 0x0, 0xc8, 0x0, 0x9, 0x7e, 0xb3}).Once().Return(0, nil)
serialPort.On("Flush").Once().Return(nil)
// full packet []byte{0x10, 0x1, 0x2, 0x1, 0x2, 0xc5, 0xae}
serialPort.On("Read", mock.Anything).
Return(7, nil).
Run(func(args mock.Arguments) {
b := args.Get(0).([]byte)
copy(b, []byte{0x10, 0x1, 0x2, 0x1, 0x2, 0xc5, 0xae})
}).Once()
logger := new(mockLogger)
logger.On("BeforeWrite", []byte{0x10, 0x1, 0x0, 0xc8, 0x0, 0x9, 0x7e, 0xb3}).Once()
logger.On("AfterEachRead", []byte{0x10, 0x1, 0x2, 0x1, 0x2, 0xc5, 0xae}, 7, nil).Once()
logger.On("BeforeParse", []byte{0x10, 0x1, 0x2, 0x1, 0x2, 0xc5, 0xae}).Once()
client := NewSerialClient(serialPort, WithSerialHooks(logger))
response, err := client.Do(context.Background(), exampleFC1RTURequest())
assert.Equal(t, exampleFC1RTUResponse(), response)
assert.NoError(t, err)
serialPort.AssertExpectations(t)
logger.AssertExpectations(t)
}
func TestSerialClient_Do_receivePacketWith2Reads(t *testing.T) {
serialPort := new(serialMock)
serialPort.On("Write", []byte{0x10, 0x1, 0x0, 0xc8, 0x0, 0x9, 0x7e, 0xb3}).Once().Return(0, nil)
serialPort.On("Flush").Once().Return(nil)
// full packet []byte{0x10, 0x1, 0x2, 0x1, 0x2, 0xc5, 0xae}
serialPort.On("Read", mock.Anything).
Return(5, nil).
Run(func(args mock.Arguments) {
b := args.Get(0).([]byte)
copy(b, []byte{0x10, 0x1, 0x2, 0x1, 0x2}) // first 5 bytes
}).Once()
serialPort.On("Read", mock.Anything).
Return(2, nil).
Run(func(args mock.Arguments) {
b := args.Get(0).([]byte)
copy(b, []byte{0xc5, 0xae}) // last 2 bytes
}).Once()
client := NewSerialClient(serialPort)
response, err := client.Do(context.Background(), exampleFC1RTURequest())
assert.Equal(t, exampleFC1RTUResponse(), response)
assert.NoError(t, err)
serialPort.AssertExpectations(t)
}
func TestSerialClient_Do_receiveErrorPacket(t *testing.T) {
serialPort := new(serialMock)
serialPort.On("Write", []byte{0x10, 0x1, 0x0, 0xc8, 0x0, 0x9, 0x7e, 0xb3}).Once().Return(0, nil)
serialPort.On("Flush").Once().Return(nil)
serialPort.On("Read", mock.Anything).
Return(5, nil).
Run(func(args mock.Arguments) {
b := args.Get(0).([]byte)
copy(b, []byte{0x01, 0x81, 0x01, 0x81, 0x90})
}).Once()
client := NewSerialClient(serialPort)
response, err := client.Do(context.Background(), exampleFC1RTURequest())
assert.Nil(t, response)
expectedErr := &packet.ErrorResponseRTU{UnitID: 1, Function: 1, Code: 1}
assert.EqualError(t, err, expectedErr.Error())
var target *ClientError
assert.True(t, errors.As(err, &target))
serialPort.AssertExpectations(t)
}
func TestSerialClient_Do_ReadSomeBytesWithEOF(t *testing.T) {
// when `github.com/tarm/serial` serialport is created as nonblocking. `Read` can return
// 0 bytes return EOF error on Linux / POSIX on read deadline timeout.
serialPort := new(serialMock)
serialPort.On("Write", []byte{0x10, 0x1, 0x0, 0xc8, 0x0, 0x9, 0x7e, 0xb3}).Once().Return(0, nil)
serialPort.On("Flush").Once().Return(nil)
// full packet []byte{0x10, 0x1, 0x2, 0x1, 0x2, 0xc5, 0xae}
serialPort.On("Read", mock.Anything).
Return(5, nil).
Run(func(args mock.Arguments) {
b := args.Get(0).([]byte)
copy(b, []byte{0x10, 0x1, 0x2, 0x1, 0x2}) // first 5 bytes
}).Once()
serialPort.On("Read", mock.Anything).
Return(0, io.EOF).
Once() // second read should return 2 bytes but returns 1 with io.EOF
serialPort.On("Read", mock.Anything).
Return(2, nil).
Run(func(args mock.Arguments) {
b := args.Get(0).([]byte)
copy(b, []byte{0xc5, 0xae}) // last 2 bytes
}).Once()
client := NewSerialClient(serialPort)
response, err := client.Do(context.Background(), exampleFC1RTURequest())
assert.Equal(t, exampleFC1RTUResponse(), response)
assert.NoError(t, err)
serialPort.AssertExpectations(t)
}
func TestSerialClient_Do_contextCancelAfterFirstRead(t *testing.T) {
serialPort := new(serialMock)
ctx, cancel := context.WithCancel(context.Background())
serialPort.On("Write", []byte{0x10, 0x1, 0x0, 0xc8, 0x0, 0x9, 0x7e, 0xb3}).Once().Return(0, nil)
serialPort.On("Read", mock.Anything).
Return(5, nil).
Run(func(args mock.Arguments) {
b := args.Get(0).([]byte)
copy(b, []byte{0x10, 0x1, 0x2, 0x1, 0x2})
cancel()
})
client := NewSerialClient(serialPort)
response, err := client.Do(ctx, exampleFC1RTURequest())
assert.Nil(t, response)
assert.EqualError(t, err, context.Canceled.Error())
serialPort.AssertExpectations(t)
}
func TestSerialClient_Do_RequestShouldBeSet(t *testing.T) {
serialPort := new(serialMock)
client := NewSerialClient(serialPort)
response, err := client.Do(context.Background(), nil)
assert.Nil(t, response)
assert.EqualError(t, err, "request can not be nil")
serialPort.AssertExpectations(t)
}
func TestSerialClient_Do_SerialPortShouldBeSet(t *testing.T) {
client := NewSerialClient(nil)
response, err := client.Do(context.Background(), exampleFC1RTURequest())
assert.Nil(t, response)
assert.EqualError(t, err, "serial port is not set")
}
func TestSerialClient_Do_writeError(t *testing.T) {
serialPort := new(serialMock)
serialPort.On("Write", []byte{0x10, 0x1, 0x0, 0xc8, 0x0, 0x9, 0x7e, 0xb3}).
Once().
Return(0, errors.New("write error"))
serialPort.On("Flush").Once().Return(nil)
client := NewSerialClient(serialPort)
response, err := client.Do(context.Background(), exampleFC1RTURequest())
assert.Nil(t, response)
assert.EqualError(t, err, "write error")
var target *ClientError
assert.True(t, errors.As(err, &target))
serialPort.AssertExpectations(t)
}
func TestSerialClient_Do_unknownReadError(t *testing.T) {
serialPort := new(serialMock)
serialPort.On("Write", []byte{0x10, 0x1, 0x0, 0xc8, 0x0, 0x9, 0x7e, 0xb3}).Once().Return(0, nil)
serialPort.On("Flush").Once().Return(nil)
serialPort.On("Read", mock.Anything).
Return(0, io.ErrUnexpectedEOF)
client := NewSerialClient(serialPort)
response, err := client.Do(context.Background(), exampleFC1RTURequest())
assert.Nil(t, response)
assert.EqualError(t, err, io.ErrUnexpectedEOF.Error())
serialPort.AssertExpectations(t)
}
func TestSerialClient_Do_ReadMoreBytesThanPacketCanBe(t *testing.T) {
serialPort := new(serialMock)
serialPort.On("Write", []byte{0x10, 0x1, 0x0, 0xc8, 0x0, 0x9, 0x7e, 0xb3}).Once().Return(0, nil)
serialPort.On("Flush").Once().Return(nil)
serialPort.On("Read", mock.Anything).
Return(tcpPacketMaxLen+1, nil)
client := NewSerialClient(serialPort)
response, err := client.Do(context.Background(), exampleFC1RTURequest())
assert.Nil(t, response)
assert.EqualError(t, err, "received more bytes than valid Modbus packet size can be")
var target *ClientError
assert.True(t, errors.As(err, &target))
serialPort.AssertExpectations(t)
}
func TestSerialClient_Close(t *testing.T) {
var testCases = []struct {
name string
givenNotConnected bool
whenError error
expectClose bool
expectError string
}{
{
name: "ok",
expectClose: true,
},
{
name: "ok, no connection is no-op",
givenNotConnected: true,
expectClose: false,
},
{
name: "nok, error on close",
expectClose: true,
whenError: errors.New("close error"),
expectError: "close error",
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
serialPort := new(serialMock)
if tc.expectClose {
serialPort.On("Close").Once().Return(tc.whenError)
}
client := NewSerialClient(nil)
if !tc.givenNotConnected {
client.serialPort = serialPort
}
err := client.Close()
if tc.expectError != "" {
assert.EqualError(t, err, tc.expectError)
} else {
assert.NoError(t, err)
}
serialPort.AssertExpectations(t)
})
}
}