-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathclient_test.go
289 lines (244 loc) · 8.04 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
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
package asyncsqs
import (
"math/rand"
"strconv"
"sync"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/sqs"
"github.com/aws/aws-sdk-go-v2/service/sqs/types"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
)
var letters = []rune("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
func randString(n int) string {
r := make([]rune, n)
for i := range r {
r[i] = letters[rand.Intn(len(letters))]
}
return string(r)
}
func TestNew(t *testing.T) {
assert := require.New(t)
tcs := []Config{
{},
{SQSClient: new(mockSQSClient)},
{SQSClient: new(mockSQSClient), QueueURL: "invalid URL"},
}
for _, tc := range tcs {
if _, err := NewBufferedClient(tc); err == nil {
t.Error("expected error")
}
}
c, err := NewBufferedClient(Config{
SQSClient: new(mockSQSClient),
QueueURL: "https://sqs.us-east-1.amazonaws.com/xxxxxxxxxxxx/some-queue",
})
assert.NotNil(c)
assert.Nil(err)
defer c.Stop()
// check defaults
assert.Equal(c.SendBufferSize, defaultBufferSize)
assert.Equal(c.DeleteBufferSize, defaultBufferSize)
assert.Equal(c.SendConcurrency, c.SendBufferSize/maxBatchSize)
assert.Equal(c.DeleteConcurrency, c.DeleteBufferSize/maxBatchSize)
}
func TestError(t *testing.T) {
assert := require.New(t)
c, err := NewBufferedClient(Config{
SQSClient: new(mockSQSClient),
QueueURL: "https://sqs.us-east-1.amazonaws.com/xxxxxxxxxxxx/some-queue",
})
assert.NotNil(c)
assert.Nil(err)
// Check validation of payload size
sizeExceedingLimit := (maxPayloadBytes / maxBatchSize) + 1
assert.NotNil(c.SendMessageAsync(types.SendMessageBatchRequestEntry{
Id: aws.String("some id"),
MessageBody: aws.String(randString(sizeExceedingLimit)),
}))
// Async funcs should return error after stopping
c.Stop()
assert.NotNil(c.SendMessageAsync())
assert.NotNil(c.DeleteMessageAsync())
}
func TestAsyncBatchNoWaitTime(t *testing.T) {
testNums := []int{1, 9, 10, 11, 99, 100, 101, 109}
for _, tc := range testNums {
tc := tc // capture range variable
t.Run(strconv.Itoa(tc), func(t *testing.T) {
assert := require.New(t)
numMsgs := tc
// if num of messages = 109, it should result in 11 SQS requests
// - 10 SQS requests as and when batch fills up
// - 1 more SQS request to drain remaining 9 when Stop() is called
numSqsCalls := (numMsgs / maxBatchSize)
if numMsgs%maxBatchSize != 0 {
numSqsCalls++
}
sendCbks := &sync.WaitGroup{}
sendCbks.Add(numSqsCalls)
delCbks := &sync.WaitGroup{}
delCbks.Add(numSqsCalls)
// mock SQS calls
mockSQSClient := new(mockSQSClient)
mockSQSClient.On("SendMessageBatch",
mock.AnythingOfType("todoCtx"), mock.AnythingOfType("*sqs.SendMessageBatchInput")).
Return(nil, nil).
Times(numSqsCalls)
mockSQSClient.On("DeleteMessageBatch",
mock.AnythingOfType("todoCtx"), mock.AnythingOfType("*sqs.DeleteMessageBatchInput")).
Return(nil, nil).
Times(numSqsCalls)
client, err := NewBufferedClient(Config{
SQSClient: mockSQSClient,
QueueURL: "https://sqs.us-east-1.amazonaws.com/xxxxxxxxxxxx/some-queue",
OnSendMessageBatch: func(output *sqs.SendMessageBatchOutput, err error) {
assert.Nil(output)
assert.Nil(err)
sendCbks.Done()
},
OnDeleteMessageBatch: func(output *sqs.DeleteMessageBatchOutput, err error) {
assert.Nil(output)
assert.Nil(err)
delCbks.Done()
},
})
assert.NotNil(client)
assert.Nil(err)
defer client.Stop()
wg := &sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < numMsgs; i++ {
_ = client.SendMessageAsync(types.SendMessageBatchRequestEntry{
Id: aws.String(strconv.Itoa(i)),
MessageBody: aws.String(strconv.Itoa(i)),
})
}
}()
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < numMsgs; i++ {
_ = client.DeleteMessageAsync(types.DeleteMessageBatchRequestEntry{
Id: aws.String(strconv.Itoa(i)),
})
}
}()
wg.Wait() // wait for all async calls to be accepted
client.Stop() // stop client; test that draining of remaining requests work
// wait for send callbacks to finish
sendCbks.Wait()
// wait for delete callbacks to finish
delCbks.Wait()
// assert SQS requests made
mockSQSClient.AssertExpectations(t)
// assert stats
s := client.Stats()
assert.Equal(s.MessagesSent, uint64(numMsgs))
assert.Equal(s.MessagesDeleted, uint64(numMsgs))
assert.Equal(s.SendMessageBatchCalls, uint64(numSqsCalls))
assert.Equal(s.DeleteMessageBatchCalls, uint64(numSqsCalls))
})
}
}
func TestAsyncBatchWithWaitTime(t *testing.T) {
testNums := []int{1, 9, 10, 11, 31}
for _, tc := range testNums {
tc := tc // capture range variable
t.Run(strconv.Itoa(tc), func(t *testing.T) {
assert := require.New(t)
// messages to be sent or deleted - N each
numMsgs := tc
msgs := &sync.WaitGroup{}
msgs.Add(numMsgs * 2)
// how long do we wait until we ship the batch (even if its not full)
waitTime := 250 * time.Millisecond
// delay between successive calls to SendMessageAsync or DeleteMessageAsync
// should transate to roughly 5 or less in a batch but not more
delayBetweenAsyncCalls := 50 * time.Millisecond
// setup to record every batch size during dispatch
batchSizes := make([]int, 0, numMsgs)
batchMu := &sync.RWMutex{}
recordBatchSize := func(size int) {
batchMu.Lock()
batchSizes = append(batchSizes, size)
batchMu.Unlock()
for i := 0; i < size; i++ {
msgs.Done()
}
}
// mock SQS calls
mockSQSClient := new(mockSQSClient)
mockSQSClient.On("SendMessageBatch",
mock.AnythingOfType("todoCtx"),
mock.AnythingOfType("*sqs.SendMessageBatchInput")).
Return(nil, nil).
Maybe(). // flexible no. of calls
Run(func(args mock.Arguments) { // hook to inspect and record batch size
recordBatchSize(len(args.Get(1).(*sqs.SendMessageBatchInput).Entries))
})
mockSQSClient.On("DeleteMessageBatch",
mock.AnythingOfType("todoCtx"),
mock.AnythingOfType("*sqs.DeleteMessageBatchInput")).
Return(nil, nil).
Maybe(). // flexible no. of calls
Run(func(args mock.Arguments) { // hook to inspect and record batch size
recordBatchSize(len(args.Get(1).(*sqs.DeleteMessageBatchInput).Entries))
})
client, err := NewBufferedClient(Config{
SQSClient: mockSQSClient,
QueueURL: "https://sqs.us-east-1.amazonaws.com/xxxxxxxxxxxx/some-queue",
SendWaitTime: waitTime,
DeleteWaitTime: waitTime,
})
assert.NotNil(client)
assert.Nil(err)
defer client.Stop()
wg := &sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < numMsgs; i++ {
_ = client.SendMessageAsync(types.SendMessageBatchRequestEntry{
Id: aws.String(strconv.Itoa(i)),
MessageBody: aws.String(strconv.Itoa(i)),
})
time.Sleep(delayBetweenAsyncCalls)
}
}()
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < numMsgs; i++ {
_ = client.DeleteMessageAsync(types.DeleteMessageBatchRequestEntry{
Id: aws.String(strconv.Itoa(i)),
})
time.Sleep(delayBetweenAsyncCalls)
}
}()
wg.Wait() // wait for all async calls to be accepted
client.Stop() // stop client; test that draining of remaining requests work
msgs.Wait() // wait for all batches to be dispatched
// assert SQS requests made
mockSQSClient.AssertExpectations(t)
totalDispatched := 0
for _, bs := range batchSizes {
// assert that neither empty nor full batch is ever dispatched
assert.True(bs > 0 && bs < maxBatchSize)
// keep track of total calls made for later assertion
totalDispatched += bs
}
// assert that all requests made through - numMsgs for each of sends and deletes
assert.Equal(totalDispatched, 2*numMsgs)
// assert stats
s := client.Stats()
assert.Equal(s.MessagesSent, uint64(numMsgs))
assert.Equal(s.MessagesDeleted, uint64(numMsgs))
assert.Equal(s.SendMessageBatchCalls+s.DeleteMessageBatchCalls, uint64(len(batchSizes)))
})
}
}