forked from americanexpress/baton
-
Notifications
You must be signed in to change notification settings - Fork 0
/
baton_test.go
271 lines (228 loc) · 7.81 KB
/
baton_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
/*
* Copyright 2018 American Express
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package main
import (
"encoding/hex"
"fmt"
"github.com/valyala/fasthttp"
"io/ioutil"
"os"
"sync/atomic"
"testing"
"time"
)
type HTTPTestHandler struct {
noRequestsReceived uint32
lastBodyReceived string
lastMethodReceived string
lastURIReceived string
lastHeadersReceived *fasthttp.RequestHeader
lastTimestamp int64
}
func (h *HTTPTestHandler) HandleRequest(ctx *fasthttp.RequestCtx) {
atomic.AddUint32(&h.noRequestsReceived, 1)
atomic.StoreInt64(&h.lastTimestamp, time.Now().Unix())
h.lastBodyReceived = hex.EncodeToString(ctx.Request.Body())
h.lastMethodReceived = string(ctx.Request.Header.Method())
h.lastURIReceived = ctx.Request.URI().String()
newHeader := fasthttp.RequestHeader{}
ctx.Request.Header.CopyTo(&newHeader)
h.lastHeadersReceived = &newHeader
}
func (h *HTTPTestHandler) reset() {
h.noRequestsReceived = 0
h.lastBodyReceived = ""
h.lastMethodReceived = ""
h.lastURIReceived = ""
h.lastTimestamp = 0
}
var serverRunning = false
var internalHandlerRef *HTTPTestHandler
var port = "8888"
func startServer() *HTTPTestHandler {
if !serverRunning {
internalHandlerRef = &HTTPTestHandler{0, "", "", "", &fasthttp.RequestHeader{}, 0}
serverRunning = true
go func() {
err := fasthttp.ListenAndServe(":"+port, internalHandlerRef.HandleRequest)
if err != nil {
fmt.Printf("Failed to bind on port %s. Make sure no other service is running on that port and restart the test\n", port)
os.Exit(1)
}
}()
return internalHandlerRef
}
internalHandlerRef.reset()
return internalHandlerRef
}
func defaultConfig() Configuration {
return Configuration{
"",
1,
"",
0,
false,
"GET",
1,
"",
true,
"http://localhost:" + port,
0,
}
}
func setupAndListen(config Configuration) *HTTPTestHandler {
testHandler := startServer()
// Give server enough time to spin
time.Sleep(time.Duration(500) * time.Millisecond)
// Create a baton instance with given config
baton := &Baton{configuration: config, result: Result{}}
baton.run()
// Give server enough time to receive requests
time.Sleep(time.Duration(500) * time.Millisecond)
// Collect results from handler
return testHandler
}
func TestRequestCount(t *testing.T) {
noRequestsToSend := 10000
config := defaultConfig()
config.numberOfRequests = noRequestsToSend
testHandler := setupAndListen(config)
reqsReceived := int(testHandler.noRequestsReceived)
if reqsReceived != noRequestsToSend {
t.Errorf("Wrong number of requests sent. Expected %d, got %d", noRequestsToSend, reqsReceived)
}
}
func TestRequestCountWithMoreWorkers(t *testing.T) {
noRequestsToSend := 100000
config := defaultConfig()
config.concurrency = 10
config.numberOfRequests = noRequestsToSend
testHandler := setupAndListen(config)
reqsReceived := int(testHandler.noRequestsReceived)
if reqsReceived != noRequestsToSend {
t.Errorf("Wrong number of requests sent. Expected %d, got %d", noRequestsToSend, reqsReceived)
}
}
func TestThatBodyHasCorrectValue(t *testing.T) {
body := "Hello World"
bodyBytes := hex.EncodeToString([]byte(body))
config := defaultConfig()
config.body = body
config.method = "POST"
testHandler := setupAndListen(config)
bytesReceived := testHandler.lastBodyReceived
if bytesReceived != bodyBytes {
t.Errorf("The body received by the server didn't match. Expected %s, got %s", bodyBytes, bytesReceived)
}
}
func TestThatTheCorrectHTTPMethodIsUsed(t *testing.T) {
method := "DELETE"
config := defaultConfig()
config.method = method
testHandler := setupAndListen(config)
methodReceived := testHandler.lastMethodReceived
if methodReceived != method {
t.Errorf("The HTTP method received by the server didn't match. Expected %s, got %s", method, methodReceived)
}
}
func TestThatServerReceivesCorrectURI(t *testing.T) {
uri := "http://localhost:" + port + "/path/to/complex?uri&with=html&entities=&#ef"
config := defaultConfig()
config.url = uri
testHandler := setupAndListen(config)
uriReceived := testHandler.lastURIReceived
if uriReceived != uri {
t.Errorf("The URI received by the server does not match. Expected %s, got %s.", uri, uriReceived)
}
}
func TestLoadPostFromTextFile(t *testing.T) {
body := "Hello World"
bodyBytes := hex.EncodeToString([]byte(body))
config := defaultConfig()
config.dataFilePath = "test-resources/post-body.txt"
config.method = "POST"
testHandler := setupAndListen(config)
bytesReceived := testHandler.lastBodyReceived
if bytesReceived != bodyBytes {
t.Errorf("The body received by the server didn't match. Expected %s, got %s", bodyBytes, bytesReceived)
}
}
func TestPostRequestLoadedFromFile(t *testing.T) {
uri := "http://localhost:" + port
method := "POST"
fileContents := method + "," + uri + "," + "Data"
fileInBytes := []byte(fileContents)
fileDir := "test-resources/requests-from-file.txt"
if ioutil.WriteFile(fileDir, fileInBytes, 0644) != nil {
t.Errorf("Failed to write a required test case file. Check the directory permissions.")
}
defer os.Remove(fileDir)
config := defaultConfig()
config.requestsFromFile = fileDir
config.numberOfRequests = 2
testHandler := setupAndListen(config)
postBodyInBytes := hex.EncodeToString([]byte("Data"))
methodReceived := testHandler.lastMethodReceived
bodyReceived := testHandler.lastBodyReceived
if methodReceived != method {
t.Errorf("The HTTP method received by the server didn't match. Expected %s, got %s", method, methodReceived)
}
if bodyReceived != postBodyInBytes {
t.Errorf("The body received by the server didn't match. Expected %s, got %s", postBodyInBytes, bodyReceived)
}
}
func TestThatHeadersAreSetWhenSendingFromFile(t *testing.T) {
uri := "http://localhost:" + port
method := "GET"
fileContents := method + "," + uri + "," + "" + "," + "Content-Type: Hello, Secret: World"
fileInBytes := []byte(fileContents)
fileDir := "test-resources/requests-from-file.txt"
if ioutil.WriteFile(fileDir, fileInBytes, 0644) != nil {
t.Errorf("Failed to write a required test case file. Check the directory permissions.")
}
defer os.Remove(fileDir)
config := defaultConfig()
config.requestsFromFile = fileDir
config.numberOfRequests = 1
testHandler := setupAndListen(config)
headerActual := hex.EncodeToString(testHandler.lastHeadersReceived.Peek("Content-Type"))
headerExpected := hex.EncodeToString([]byte("Hello"))
if headerExpected != headerActual {
t.Errorf("Header not found or improperly set, Expected %s, got %s", headerExpected, headerActual)
}
headerActual2 := hex.EncodeToString(testHandler.lastHeadersReceived.Peek("Secret"))
headerExpected2 := hex.EncodeToString([]byte("World"))
if headerExpected != headerActual {
t.Errorf("Header not found or improperly set, Expected %s, got %s", headerExpected2, headerActual2)
}
}
func TestThatTimeOptionRunsForCorrectAmountOfTime(t *testing.T) {
duration := 10
testHandler := startServer()
timeNow := time.Now().Unix()
config := defaultConfig()
config.duration = duration
baton := &Baton{configuration: config, result: Result{}}
baton.run()
time.Sleep(time.Duration(15) * time.Second)
lastTimeStamp := testHandler.lastTimestamp
epsilonLow := int64(duration - 1)
epsilonHigh := int64(duration + 1)
diff := lastTimeStamp - timeNow
if diff < epsilonLow || diff > epsilonHigh {
t.Errorf("Requests sent for longer/shorter than expected. Expected %d, got %d)", duration, diff)
}
}