-
Notifications
You must be signed in to change notification settings - Fork 0
/
grpc_run_test.go
468 lines (371 loc) · 11.7 KB
/
grpc_run_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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
package client
import (
"context"
"errors"
"math/rand"
"os"
"testing"
"time"
"github.com/stretchr/testify/assert"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
pb "github.com/trendmicro/tm-v1-fs-golang-sdk/protos"
)
/***************************************************************************
One of the most critical functional areas for us to test with the AMaaS
client is that given a command from the server, the client will actually
carry out the task requested by the server, namely, retrieving the right
data chunk from the file when requested by the server.
***************************************************************************/
// This class will generate a temporary file with consecutive sequences of
// extended ASCII codes from 0 to 255 in ascending order, where each code
// occupies one (1) byte. For example, a file that is exactly 256 bytes long
// would be [0x00, 0x01, 0x02, ... , 0xFD, 0xFE, 0xFF] while a file that is
// exactly 512 bytes long would be [0x00, 0x01, 0x02, ... , 0xFD, 0xFE, 0xFF,
// 0x00, 0x01, 0x02, ... , 0xFD, 0xFE, 0xFF].
const (
EnvVarTestDatDir = "AMAAS_UNIT_TEST_GOLANG_DIR"
DefaultTestDatDirPath = "."
MaxFileSize = 1 << 20
MaxChunkReadSize = 1 << 12
NumReadIterations = 1 << 14
)
type TestDat struct {
filesize int
filename string
}
func createTestDat(fnameTemplate string) *TestDat {
tempDir := os.Getenv(EnvVarTestDatDir)
if tempDir == "" {
tempDir = DefaultTestDatDirPath
}
file, err := os.CreateTemp(tempDir, fnameTemplate)
if err != nil {
return nil
}
d := &TestDat{
filesize: MaxFileSize,
filename: file.Name(),
}
fd, err := os.Create(d.filename)
if err != nil {
return nil
}
defer fd.Close()
b := make([]byte, d.filesize)
for i := 0; i < d.filesize; i++ {
b[i] = byte(i % 256)
}
if n, err := fd.Write(b); err != nil || n != d.filesize {
return nil
}
return d
}
func (d *TestDat) ExpectedValueAt(pos int) byte {
return byte(pos % 256)
}
func (d *TestDat) Filename() string {
return d.filename
}
func (d *TestDat) Filesize() int {
return d.filesize
}
// Test readFileBytes() function which is critical to client retrieval
// of file content.
func TestReadFileBytes(t *testing.T) {
dat := createTestDat("test.*.dat")
defer os.Remove(dat.Filename())
fileReader, err := InitFileReader(dat.Filename())
assert.Nil(t, err)
defer fileReader.Close()
result, err := fileReader.DataSize()
assert.Nil(t, err)
fileSize := int(result)
for i := 0; i < NumReadIterations; i++ {
offset := rand.Intn(fileSize)
length := rand.Intn(MaxChunkReadSize) + 1
end := offset + length
if end > fileSize {
length -= (end - fileSize)
}
buf, err := fileReader.ReadBytes(int64(offset), int32(length))
assert.Nil(t, err)
assert.NotNil(t, len(buf) == length)
for j := 0; j < length; j++ {
expected := dat.ExpectedValueAt(offset + j)
result := buf[j]
assert.Equal(t, expected, result)
}
}
}
// Mock client stream for testing
// Essentially we're using channel here to simulate flow of commands/replies
// from the server to the client (response messages per RPC convention), and
// from client to the server (request messages per RPC convention).
//
// In the case of AMaaS client-server design, it's actually the server
// issuing commands to the client using S2C messages, and the client reading
// data chunks off the file and sending them back to the server using C2S
// messages.
type ClientStreamMock struct {
grpc.ClientStream
recvToClient chan *pb.S2C
sentFromClient chan *pb.C2S
}
func createClientStreamMock() *ClientStreamMock {
return &ClientStreamMock{
recvToClient: make(chan *pb.S2C, NumReadIterations),
sentFromClient: make(chan *pb.C2S, NumReadIterations),
}
}
func (mock *ClientStreamMock) Send(req *pb.C2S) error {
mock.sentFromClient <- req
return nil
}
func (mock *ClientStreamMock) Recv() (*pb.S2C, error) {
resp, more := <-mock.recvToClient
if !more {
return nil,
errors.New("Simulated stream is now empty of server2client responses")
}
return resp, nil
}
func (mock *ClientStreamMock) SendFromServer(resp *pb.S2C) error {
mock.recvToClient <- resp
return nil
}
func (mock *ClientStreamMock) RecvToServer() (*pb.C2S, error) {
req, more := <-mock.sentFromClient
if !more {
return nil,
errors.New("Simulated stream is now empty of client2server requests")
}
return req, nil
}
// Test gRPC client runUploadLoop() function to make sure it processes the
// RETR commands from the server correctly.
//
// Also some testing of abnormal conditions, but more unit tests will be
// added to make sure the loop handles all sorts of different abnormal
// conditions later on.
//
// Global channel for storing errors generated by runUploadLoop(). Depending
// on the testcase, this channel might be completely empty or containing
// some error.
var errChan chan error = make(chan error, NumReadIterations)
func createMockClientRun(t *testing.T, reader AmaasClientReader, bulk bool) *ClientStreamMock {
stream := createClientStreamMock()
go func() {
_, _, err := runUploadLoop(stream, reader, bulk)
if err != nil {
errChan <- err
}
close(stream.sentFromClient)
close(stream.recvToClient)
}()
return stream
}
// Test normal read conditions where client receives all valid
// S2C messages directing client to read from valid positions within
// the length of the file.
//
// This version exercises the loop using a buffer reader (as opposed to
// file reader) by reading in all the data from a test dat file into a
// byte slice, and then feeding the buffer to a buffer reader which is
// used during testing.
func TestRunUploadLoopNormalForBufferReader(t *testing.T) {
dat := createTestDat("test.*.dat")
assert.NotNil(t, dat)
defer os.Remove(dat.Filename())
// Read the content of the whole file into a byte slice.
buffer, err := os.ReadFile(dat.Filename())
assert.Nil(t, err)
// Pass the buffer to a buffer reader.
reader, err := InitBufferReader(buffer, dat.Filename())
assert.Nil(t, err)
defer reader.Close()
checkRunUploadLoop(t, dat, reader, false)
}
func TestRunUploadLoopNormalForBufferReaderBulk(t *testing.T) {
dat := createTestDat("test.*.dat")
assert.NotNil(t, dat)
defer os.Remove(dat.Filename())
// Read the content of the whole file into a byte slice.
buffer, err := os.ReadFile(dat.Filename())
assert.Nil(t, err)
// Pass the buffer to a buffer reader.
reader, err := InitBufferReader(buffer, dat.Filename())
assert.Nil(t, err)
defer reader.Close()
checkRunUploadLoop(t, dat, reader, true)
}
// Test normal read conditions where client receives all valid
// S2C messages directing client to read from valid positions within
// the length of the file.
//
// Unlike the other, earlier test, this one uses a file reader instead
// of a buffer reader. The dat filename is directly passed to the file
// reader which is used during testing.
func TestRunUploadLoopNormalForFileReader(t *testing.T) {
dat := createTestDat("test.*.dat")
assert.NotNil(t, dat)
defer os.Remove(dat.Filename())
reader, err := InitFileReader(dat.Filename())
assert.Nil(t, err)
defer reader.Close()
checkRunUploadLoop(t, dat, reader, false)
}
func TestRunUploadLoopNormalForFileReaderBulk(t *testing.T) {
dat := createTestDat("test.*.dat")
assert.NotNil(t, dat)
defer os.Remove(dat.Filename())
reader, err := InitFileReader(dat.Filename())
assert.Nil(t, err)
defer reader.Close()
checkRunUploadLoop(t, dat, reader, true)
}
func checkRunUploadLoop(t *testing.T, dat *TestDat, reader AmaasClientReader, bulk bool) {
stream := createMockClientRun(t, reader, bulk)
assert.NotNil(t, stream)
reads := make([](*pb.S2C), NumReadIterations)
for i := 0; i < NumReadIterations; i++ {
var s2c *pb.S2C
if bulk {
s2c = generateRetrS2CBulk(dat.Filesize())
assert.NotNil(t, s2c)
} else {
s2c = generateRetrS2C(dat.Filesize())
assert.NotNil(t, s2c)
}
err := stream.SendFromServer(s2c)
assert.Nil(t, err)
reads[i] = s2c
}
// No reason for runUploadLoop() to send any error into the
// error channel. Something is wrong if non-empty.
assert.Equal(t, 0, len(errChan))
for i := 0; i < NumReadIterations; i++ {
resp, err := stream.RecvToServer()
assert.Nil(t, err)
assert.NotNil(t, resp)
if bulk {
verifyC2SRespBulk(t, dat, reads[i], resp)
} else {
verifyC2SResp(t, dat, reads[i], resp)
}
}
}
func generateRetrS2C(fileSize int) *pb.S2C {
offset := rand.Intn(fileSize)
len := rand.Intn(MaxChunkReadSize) + 1
end := offset + len
if end > fileSize {
len -= (end - fileSize)
}
return &pb.S2C{
Stage: pb.Stage_STAGE_RUN,
Cmd: pb.Command_CMD_RETR,
Offset: int32(offset),
Length: int32(len),
}
}
func generateRetrS2CBulk(fileSize int) *pb.S2C {
offset := rand.Intn(fileSize)
length := rand.Intn(MaxChunkReadSize) + 1
end := offset + length
if end > fileSize {
length -= (end - fileSize)
}
bulkLength := []int32{int32(length)}
bulkOffset := []int32{int32(offset)}
return &pb.S2C{
Stage: pb.Stage_STAGE_RUN,
Cmd: pb.Command_CMD_RETR,
BulkLength: bulkLength,
BulkOffset: bulkOffset,
}
}
func verifyC2SResp(t *testing.T, dat *TestDat, req *pb.S2C, resp *pb.C2S) {
assert.Equal(t, pb.Stage_STAGE_RUN, resp.Stage)
assert.Equal(t, req.Offset, resp.Offset)
origLen := int(req.Length)
assert.Equal(t, origLen, len(resp.Chunk))
for i := 0; i < origLen; i++ {
assert.Equal(t, dat.ExpectedValueAt(int(req.Offset)+i), resp.Chunk[i])
}
}
func verifyC2SRespBulk(t *testing.T, dat *TestDat, req *pb.S2C, resp *pb.C2S) {
assert.Equal(t, pb.Stage_STAGE_RUN, resp.Stage)
assert.Equal(t, req.BulkOffset[0], resp.Offset)
origLen := int(req.BulkLength[0])
assert.Equal(t, origLen, len(resp.Chunk))
for i := 0; i < origLen; i++ {
assert.Equal(t, dat.ExpectedValueAt(int(req.BulkOffset[0])+i), resp.Chunk[i])
}
}
// Test condition where the S2C command to the client is simply
// some invalid garbage.
func TestRunUploadLoopBadS2CMsg(t *testing.T) {
reader, err := InitBufferReader(make([]byte, 10), "whatever")
assert.Nil(t, err)
stream := createMockClientRun(t, reader, false)
assert.NotNil(t, stream)
s2c := &pb.S2C{
Stage: pb.Stage(100),
Cmd: pb.Command(200),
Offset: 0,
Length: 0,
}
err = stream.SendFromServer(s2c)
assert.Nil(t, err)
// runUploadLoop() should have sent 1 error into the channel due
// to not able to interpret the received command message.
err = <-errChan
assert.NotNil(t, err)
st, _ := status.FromError(err)
assert.Equal(t, codes.Internal, st.Code())
// There should be no C2S message sent by the client into the
// simulated message channel, so trying to read from the message
// channel should result in an error.
_, err = stream.RecvToServer()
assert.NotNil(t, err)
}
func TestScanRunWithInvalidTags(t *testing.T) {
tests := []struct {
name string
tags []string
expectedErr string
}{
{
name: "Empty tags",
tags: []string{},
expectedErr: "tags cannot be empty",
},
{
name: "Too many tags",
tags: []string{"tag1", "tag2", "tag3", "tag4", "tag5", "tag6", "tag7", "tag8", "tag9"},
expectedErr: "too many tags, maximum is 8",
},
{
name: "Empty tag",
tags: []string{"", "tag1"},
expectedErr: "each tag cannot be empty",
},
{
name: "Tag length exceeds 63",
tags: []string{"1234567890123456789012345678901234567890123456789012345678901234"},
expectedErr: "tag length cannot exceed 63",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// arrange
ctx, cancel := context.WithTimeout(context.Background(), time.Second*time.Duration(180))
// act
_, err := scanRun(ctx, cancel, nil, nil, tt.tags, false, true, false, false, true)
// assert
assert.Equal(t, tt.expectedErr, err.Error())
})
}
}