-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebTester.go
239 lines (187 loc) · 6.44 KB
/
webTester.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
package webtester
import (
"encoding/json"
"errors"
"io/ioutil"
"math"
"math/rand"
"net/http"
"sort"
"time"
"github.com/juju/loggo"
)
var log = loggo.GetLogger("webtester")
func init() {
log.SetLogLevel(loggo.INFO)
}
// CreateDataSample - Function type, which creates a new input data sample,
// which is passed on to the CreateNewRequest function to
// create a new request to the server using the created data
// sample as payload
type CreateDataSample func() interface{}
// CreateNewRequest - Function type that creates a new http request using
// the provided payload
type CreateNewRequest func(payload interface{}) (*http.Request, error)
// HandleResponse - Function type that handles the returned http response
type HandleResponse func(resp *http.Response) error
// ScenarioSamples - A struct type that servers as the basis for scenario definition.
// Each test scenario is composed of a sequence of samples, which define http requests
// fired of at certain points in time using predefined payloads
type ScenarioSample struct {
Time time.Duration `json:"time"`
Payload interface{} `json:"payload"`
}
type ScenarioExecutor struct {
}
type statusResponse struct {
status int
err error
duration time.Duration
}
func init() {
rand.Seed(time.Now().UnixNano())
}
func randomDuration(max int) int {
return rand.Intn(max)
}
func sortedRandomSamples(len int, max int) []int {
samples := make([]int, len)
// create an array of random integers
for i := 0; i < len; i++ {
samples[i] = randomDuration(max)
}
sort.Ints(samples)
return samples
}
func randomMoments(duration time.Duration, requestsPerSecond int) []time.Duration {
var moments []time.Duration
// first we create samples for a defined number of seconds (<duration)
var t0 time.Duration
for {
t1 := t0 + time.Second
if t1 > duration {
break
}
ts := sortedRandomSamples(requestsPerSecond, 1000000000)
mts := make([]time.Duration, requestsPerSecond)
for i := 0; i < requestsPerSecond; i++ {
mts[i] = t0 + time.Duration(ts[i])*time.Nanosecond
}
moments = append(moments, mts...)
t0 = t1
}
// for the leftover fraction of a second we must add additional samples
if t0 < duration {
additionalSamples := int(math.Floor(float64(requestsPerSecond) * float64((duration - t0)) / float64(time.Second)))
ts := sortedRandomSamples(additionalSamples, int(math.Floor(float64(1000000000*(duration-t0))/float64(time.Second))))
mts := make([]time.Duration, additionalSamples)
for i := 0; i < additionalSamples; i++ {
mts[i] = t0 +
time.Duration(ts[i])*time.Nanosecond
}
moments = append(moments, mts...)
}
return moments
}
//To create a new test scenario the CreateNewTestScenario should be used. This creates a test scenario of
//length specified by the "duration" parameter. During the test the average load of the server is specified by the number
//of requests that are to be fired each second (specified by the "requestsPerSecond" parameter).
//For each request the input data is created by using the provided CreateDataSample function and the resulting
//scenario is written to the file specified by the "scenarioFile" parameter.
func CreateNewTestScenario(duration time.Duration, requestsPerSecond int, ids CreateDataSample, scenarioFile string) {
moments := randomMoments(duration, requestsPerSecond)
samples := make([]ScenarioSample, len(moments))
for i, t0 := range moments {
s := ScenarioSample{t0, nil}
if ids != nil {
s.Payload = ids()
}
samples[i] = s
}
data, err := json.Marshal(samples)
if err != nil {
log.Errorf("Error marshalling input data to json :: %v", err)
}
err = ioutil.WriteFile(scenarioFile, data, 0644)
if err != nil {
log.Errorf("Error writing scenario to the target file :: %v", err)
}
}
func executeRequest(resultChanel chan statusResponse, t0 time.Duration, client *http.Client, request *http.Request, hr HandleResponse) {
if client == nil {
log.Criticalf("Nil client.")
return
}
if request == nil {
log.Criticalf("Nil request.")
return
}
timer := time.NewTimer(t0)
<-timer.C
var err error
tStart := time.Now()
response, err := client.Do(request)
if err != nil {
log.Errorf("Error sending a request via the specified client :: %v", err)
resultChanel <- statusResponse{response.StatusCode, err, time.Since(tStart)}
return
}
if hr != nil {
err = hr(response)
if err != nil {
log.Errorf("Error handling the received response :: %v", response)
resultChanel <- statusResponse{response.StatusCode, err, time.Since(tStart)}
return
}
}
resultChanel <- statusResponse{response.StatusCode, nil, time.Since(tStart)}
}
// ExecuteTestScenario function executes a test scenario description stored in the "scenarioFile". Http client
// must be provided, which is reused for all connections. In addition one must provide two fucntions: 1) CreateNewRequest
// function which takes interface{} as input and produces a new http Request to the desired server. Input is read from
// scenario definition file (json - only exported fields are available). 2) The HandleResponse function which is given
// http Response and returns an error - in this function one may do erro handling, additional logging, etc.
func ExecuteTestScenario(scenarioFile string, client *http.Client, cnr CreateNewRequest, hr HandleResponse) error {
if client == nil {
log.Criticalf("Nil client.")
return errors.New("Nil client")
}
data, err := ioutil.ReadFile(scenarioFile)
if err != nil {
log.Errorf("Error reading scenario file :: %v", err)
return err
}
var samples []ScenarioSample
err = json.Unmarshal(data, &samples)
if err != nil {
log.Errorf("Error converting contents of scenario file to scenario samples :: %v", err)
return err
}
resultChanel := make(chan statusResponse)
for _, sample := range samples {
request, err := cnr(sample.Payload)
if err != nil {
log.Errorf("Error creating a new http request from payload :: %v |-> %v", sample.Payload, err)
return err
}
go executeRequest(resultChanel, sample.Time, client, request, hr)
}
var noSamples = len(samples)
var totalDuration time.Duration
for {
s := <-resultChanel
if s.err != nil {
log.Warningf("Received error :: %v", err)
}
if s.status != 200 {
log.Warningf("Received status code :: %v", s.status)
}
totalDuration = totalDuration + s.duration
noSamples = noSamples - 1
if noSamples <= 0 {
break
}
}
log.Infof("Average response time :: %v", time.Duration(math.Floor(float64(totalDuration)/float64(len(samples)))))
return nil
}