This repository was archived by the owner on Aug 17, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 182
Expand file tree
/
Copy pathlambda_test.go
More file actions
570 lines (523 loc) · 14.9 KB
/
Copy pathlambda_test.go
File metadata and controls
570 lines (523 loc) · 14.9 KB
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
package main
import (
"context"
"encoding/json"
"fmt"
"html"
"math"
"net"
"net/http"
"os"
"strconv"
"sync"
"testing"
"time"
"github.com/aws/aws-sdk-go/service/lambda"
"github.com/aws/aws-sdk-go/service/lambda/lambdaiface"
"github.com/goadapp/goad/api"
)
var port int
var urlStr string
var portStr string
func TestMain(m *testing.M) {
port = 8080
urlStr = fmt.Sprintf("http://localhost:%d/", port)
portStr = fmt.Sprintf(":%d", port)
code := m.Run()
os.Exit(code)
}
func TestRequestMetric(t *testing.T) {
metric := NewRequestMetric("us-east-1", 0)
agg := metric.aggregatedResults
if agg.RequestCount != 0 {
t.Error("totalRequestsFinished should be initialized with 0")
}
if metric.requestCountSinceLastSend != 0 {
t.Error("totalRequestsFinished should be initialized with 0")
}
if agg.Fastest != math.MaxInt64 {
t.Error("Fastest should be initialized with a big value")
}
if agg.Slowest != 0 {
t.Error("Slowest should be initialized with a big value")
}
if metric.firstRequestTime != 0 {
t.Error("without requests this field should be 0")
}
if metric.lastRequestTime != 0 {
t.Error("without requests this field should be 0")
}
if metric.timeToFirstTotal != 0 {
t.Error("without requests this field should be 0")
}
if metric.requestTimeTotal != 0 {
t.Error("without requests this field should be 0")
}
if agg.BytesRead != 0 {
t.Error("without requests this field should be 0")
}
}
func TestAddRequestStatus(t *testing.T) {
success := 200
successStr := strconv.Itoa(success)
metric := NewRequestMetric("us-east-1", 0)
result := &requestResult{
Status: success,
}
metric.addRequest(result)
if metric.aggregatedResults.Statuses[successStr] != 1 {
t.Error("metric should update cound of statuses map")
}
metric.addRequest(result)
if metric.aggregatedResults.Statuses[successStr] != 2 {
t.Error("metric should update cound of statuses map")
}
}
func TestAddRequest(t *testing.T) {
bytes := 1000
elapsedFirst := int64(100)
elapsedLast := int64(300)
metric := NewRequestMetric("us-east-1", 0)
result := &requestResult{
Time: 400,
ElapsedFirstByte: elapsedFirst,
ElapsedLastByte: elapsedLast,
Bytes: bytes,
Timeout: false,
ConnectionError: false,
Elapsed: 100,
}
metric.addRequest(result)
if metric.lastRequestTime != result.Time+100 {
t.Error("metrics should update lastRequestTime")
}
if metric.aggregatedResults.RequestCount != 1 {
t.Error("metrics should update totalRequestsFinished")
}
if metric.requestCountSinceLastSend != 1 {
t.Error("metrics should upate totalRequestsFinished")
}
result.ElapsedLastByte = 400
result.Time = 800
metric.addRequest(result)
agg := metric.aggregatedResults
if agg.RequestCount != 2 {
t.Error("metrics should update totalRequestsFinished")
}
if metric.requestCountSinceLastSend != 2 {
t.Error("metrics should upate totalRequestsFinished")
}
if agg.BytesRead != 2*bytes {
t.Error("metrics should add successful requests Bytes to totalBytesRead")
}
if metric.requestTimeTotal != 700 {
t.Error("metrics should add successful requests elapsedLast to requestTimeTotal")
}
if metric.timeToFirstTotal != 2*elapsedFirst {
t.Error("metrics should add successful requests elapsedFirst to timeToFirstTotal")
}
if metric.firstRequestTime != 400 {
t.Error("metrics should keep first requests time")
}
if metric.lastRequestTime != 800+100 {
t.Error("metrics should update lastRequestsTime")
}
if agg.Fastest != 300 {
t.Errorf("Expected fastes requests to have taken 300, was: %d", agg.Fastest)
}
if agg.Slowest != 400 {
t.Errorf("Expected fastes requests to have taken 300, was: %d", agg.Fastest)
}
result.Timeout = true
metric.addRequest(result)
if agg.RequestCount != 3 {
t.Error("metrics should update totalRequestsFinished")
}
if metric.requestCountSinceLastSend != 3 {
t.Error("metrics should upate totalRequestsFinished")
}
if agg.BytesRead != 2*bytes {
t.Error("metrics should not add timedout requests Bytes to totalBytesRead")
}
if metric.requestTimeTotal != 700 {
t.Error("metrics should not add timedout requests elapsedLast to requestTimeTotal")
}
if metric.timeToFirstTotal != 2*elapsedFirst {
t.Error("metrics should not add timedout requests elapsedFirst to timeToFirstTotal")
}
if metric.firstRequestTime != 400 {
t.Error("metrics should keep first requests time")
}
if metric.lastRequestTime != 800+100 {
t.Error("metrics should update lastRequestsTime")
}
if agg.TimedOut != 1 {
t.Error("metrics should update TotalTimeOut")
}
result.ConnectionError = true
result.Timeout = false
metric.addRequest(result)
if agg.RequestCount != 4 {
t.Error("metrics should update totalRequestsFinished")
}
if metric.requestCountSinceLastSend != 4 {
t.Error("metrics should upate totalRequestsFinished")
}
if agg.BytesRead != 2*bytes {
t.Error("metrics should not add timedout requests Bytes to totalBytesRead")
}
if metric.requestTimeTotal != 700 {
t.Error("metrics should not add timedout requests elapsedLast to requestTimeTotal")
}
if metric.timeToFirstTotal != 2*elapsedFirst {
t.Error("metrics should not add timedout requests elapsedFirst to timeToFirstTotal")
}
if metric.firstRequestTime != 400 {
t.Error("metrics should keep first requests time")
}
if metric.lastRequestTime != 800+100 {
t.Error("metrics should update lastRequestsTime")
}
if agg.ConnectionErrors != 1 {
t.Error("metrics should update TotalConnectionError")
}
}
func TestResetAndKeepTotalReqs(t *testing.T) {
metric := NewRequestMetric("us-east-1", 0)
agg := metric.aggregatedResults
agg.RequestCount = 7
metric.firstRequestTime = 123
metric.lastRequestTime = 123
metric.requestCountSinceLastSend = 123
metric.requestTimeTotal = 123
metric.timeToFirstTotal = 123
agg.BytesRead = 123
metric.resetAndKeepTotalReqs()
agg = metric.aggregatedResults
if agg.RequestCount != 0 {
t.Error("TotalReqs should be reset to 0")
}
if metric.requestCountSinceLastSend != 0 {
t.Error("totalRequestsFinished should be reset to 0")
}
if agg.Fastest != math.MaxInt64 {
t.Error("Fastest should be re-initialized with a big value")
}
if agg.Slowest != 0 {
t.Error("Slowest should be re-initialized with a big value")
}
if metric.firstRequestTime != 0 {
t.Error("firstRequestTime should be reset")
}
if metric.lastRequestTime != 0 {
t.Error("lastRequestTime should be reset")
}
if metric.requestCountSinceLastSend != 0 {
t.Error("requestCuntSinceLastSend should be reset")
}
if metric.requestTimeTotal != 0 {
t.Error("requestTimeTotal should be reset")
}
if metric.timeToFirstTotal != 0 {
t.Error("timeToFirstTotal should be reset")
}
if agg.BytesRead != 0 {
t.Error("totalBytesRead should be reset")
}
}
func TestMetricsAggregate(t *testing.T) {
bytes := 1000
elapsedFirst := int64(100)
elapsedLast := int64(300)
metric := NewRequestMetric("us-east-1", 0)
result := &requestResult{
Time: 10000000,
Elapsed: 10000000,
ElapsedFirstByte: elapsedFirst,
ElapsedLastByte: elapsedLast,
Bytes: bytes,
Timeout: false,
ConnectionError: false,
}
metric.aggregate()
agg := metric.aggregatedResults
if agg.AveTimeToFirst != 0 {
t.Errorf("should result in 0, but was: %d", agg.AveTimeToFirst)
}
if agg.AveTimeForReq != 0 {
t.Errorf("should result in 0, but was: %d", agg.AveTimeForReq)
}
for i := 0; i < 10; i++ {
result.Time += 10000000
metric.addRequest(result)
}
metric.aggregate()
if agg.AveTimeToFirst != 100 {
t.Errorf("should result in 100 but was %d", agg.AveTimeToFirst)
}
if agg.AveTimeForReq != 300 {
t.Errorf("should result in 30 but was %d", agg.AveTimeForReq)
}
if agg.FatalError != "" {
t.Errorf("there should be no fatal error but received: %s", agg.FatalError)
}
result.Timeout = true
for i := 0; i < 10; i++ {
result.Time += 10000000
metric.addRequest(result)
}
if agg.FatalError != "" {
t.Errorf("there should be no fatal error but received: %s", agg.FatalError)
}
metric.addRequest(result)
if agg.FatalError != "Over 50% of requests failed, aborting" {
t.Errorf("there should be a fatal error for failed requests but received: %s", agg.FatalError)
}
}
type TestResultSender struct {
sentResults []api.RunnerResult
}
func (s *TestResultSender) SendResult(data api.RunnerResult) error {
s.sentResults = append(s.sentResults, data)
return nil
}
type mockLambdaClient struct {
lambdaiface.LambdaAPI
input *invokeArgs
}
func (m *mockLambdaClient) Invoke(in *lambda.InvokeInput) (*lambda.InvokeOutput, error) {
args := &invokeArgs{}
json.Unmarshal(in.Payload, args)
m.input = args
return &lambda.InvokeOutput{}, nil
}
func TestQuitOnLambdaTimeout(t *testing.T) {
if testing.Short() {
t.Skip("skipping test in short mode.")
}
handler := &delayRequstHandler{
DelayMilliseconds: 400,
}
server := &testServer{
Handler: handler,
}
server.Start()
defer server.Stop()
reportingFrequency := time.Duration(5) * time.Second
settings := LambdaSettings{
MaxRequestCount: 3,
ConcurrencyCount: 1,
ReportingFrequency: reportingFrequency,
StresstestTimeout: 10,
LambdaRegion: "us-east-1",
}
settings.RequestParameters.URL = urlStr
sender := &TestResultSender{}
lambda := newLambda(settings)
lambda.resultSender = sender
mockClient := &mockLambdaClient{}
lambda.lambdaService = mockClient
function := &lambdaTestFunction{
lambda: lambda,
}
lambda.Settings.LambdaExecTimeoutSeconds = 1
RunOrFailAfterTimout(t, function, 1400)
resLength := len(sender.sentResults)
timeoutRemaining := lambda.Settings.StresstestTimeout
if timeoutRemaining != 9 {
t.Errorf("we shoud have 9 seconds of stresstest left, actual: %d", timeoutRemaining)
}
requestCount := lambda.Settings.MaxRequestCount
if requestCount != 3 {
t.Errorf("the request count of 3 should not have changed, actual: %d", requestCount)
}
if resLength != 1 {
t.Errorf("We should have received exactly 1 result but got %d instead.", resLength)
t.FailNow()
}
if sender.sentResults[0].Finished == true {
t.Error("lambda should not have finished all it's requests")
}
reqs := sender.sentResults[0].RequestCount
if reqs != 2 {
t.Errorf("should have completed 2 requests yet but registered %d.", reqs)
}
}
func TestMetricSendResults(t *testing.T) {
bytes := 1024
elapsedFirst := int64(100)
elapsedLast := int64(300)
result := &requestResult{
Time: 400,
ElapsedFirstByte: elapsedFirst,
ElapsedLastByte: elapsedLast,
Bytes: bytes,
Timeout: false,
ConnectionError: false,
}
metric := NewRequestMetric("us-east-1", 0)
sender := &TestResultSender{}
metric.addRequest(result)
metric.sendAggregatedResults(sender)
if len(sender.sentResults) != 1 {
t.Error("sender should have received one item")
t.FailNow()
}
}
func TestRunLoadTestWithHighConcurrency(t *testing.T) {
server := createAndStartTestServer()
defer server.Stop()
runLoadTestWithDefaultExecTimeout(t, 500, 100, 500)
}
func TestRunLoadTestWithOneRequest(t *testing.T) {
server := createAndStartTestServer()
defer server.Stop()
runLoadTestWithDefaultExecTimeout(t, 1, -1, 50)
}
func TestRunLoadTestWithZeroRequests(t *testing.T) {
server := createAndStartTestServer()
defer server.Stop()
runLoadTestWithDefaultExecTimeout(t, 1, 1, 120)
}
func TestRunWithExecTimeout(t *testing.T) {
server := createAndStartTestServer()
defer server.Stop()
runLoadTestWith(t, 0, 1, 1, 1050)
}
func runLoadTestWithDefaultExecTimeout(t *testing.T, requestCount int, concurrency int, milliseconds int) {
runLoadTestWith(t, requestCount, 0, concurrency, milliseconds)
}
func runLoadTestWith(t *testing.T, requestCount int, stresstestTimeout int, concurrency int, milliseconds int) {
if testing.Short() {
t.Skip("skipping test in short mode.")
}
reportingFrequency := time.Duration(5) * time.Second
settings := LambdaSettings{
MaxRequestCount: requestCount,
ConcurrencyCount: concurrency,
ReportingFrequency: reportingFrequency,
StresstestTimeout: stresstestTimeout,
}
settings.RequestParameters.URL = urlStr
sender := &TestResultSender{}
lambda := newLambda(settings)
lambda.resultSender = sender
function := &lambdaTestFunction{
lambda: lambda,
}
RunOrFailAfterTimout(t, function, milliseconds)
if len(sender.sentResults) != 1 {
t.Error("sender should have received one item")
t.FailNow()
}
results := sender.sentResults[0]
if results.Finished != true {
t.Error("the lambda should have finished it's results")
}
if results.RequestCount != requestCount && requestCount > 0 {
t.Errorf("the lambda generated results for %d request, expected %d", results.RequestCount, requestCount)
}
}
func RunOrFailAfterTimout(t *testing.T, f TestFunction, milliseconds int) {
timeout := time.Duration(milliseconds) * time.Millisecond
select {
case <-time.After(timeout):
t.Error("Test is stuck")
t.FailNow()
case <-func() chan bool {
quit := make(chan bool)
go func() {
f.Run()
quit <- true
}()
return quit
}():
}
}
type lambdaTestFunction struct {
lambda *goadLambda
}
type TestFunction interface {
Run()
}
func (a *lambdaTestFunction) Run() {
a.lambda.runLoadTest()
}
func TestFetchSuccess(t *testing.T) {
handler := &requestCountHandler{}
server := createAndStartTestServerWithHandler(handler)
defer server.Stop()
// setup for the fetch function
expectedRequestCount := 1
client := &http.Client{}
r := requestParameters{
URL: urlStr,
}
result := requestResult{}
for result.State != "Success" {
result = fetch(client, r, time.Now())
}
if handler.RequestCount != expectedRequestCount {
t.Error("Did not receive exactly one request, received: ", handler.RequestCount)
}
}
func createAndStartTestServer() *testServer {
handler := &requestCountHandler{}
server := createAndStartTestServerWithHandler(handler)
return server
}
func createAndStartTestServerWithHandler(handler http.Handler) *testServer {
server := &testServer{
Handler: handler,
}
server.Start()
return server
}
type testServer struct {
Handler http.Handler
Listener net.Listener
HTTPServer http.Server
wg sync.WaitGroup
}
type requestCountHandler struct {
RequestCount int
}
func (h *requestCountHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h.RequestCount++
fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
}
type delayRequstHandler struct {
DelayMilliseconds int
}
func (h *delayRequstHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
time.Sleep(time.Duration(h.DelayMilliseconds) * time.Millisecond)
fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
}
func (s *testServer) Start() {
listener, err := net.Listen("tcp", portStr)
if err != nil {
panic(err)
}
s.Listener = listener
s.HTTPServer = http.Server{
Addr: portStr,
Handler: s.Handler,
}
s.wg.Add(1)
go func() {
s.HTTPServer.Serve(listener)
s.wg.Done()
}()
}
func (s *testServer) Stop() {
s.Listener.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
s.HTTPServer.Shutdown(ctx)
s.wg.Wait()
}
func _TestMultipleFetch(t *testing.T) {
for i := 0; i < 1000; i++ {
TestFetchSuccess(t)
}
}