-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLoadSun.go
236 lines (193 loc) · 6.01 KB
/
LoadSun.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
package main
import (
"bytes"
crypto_rand "crypto/rand"
"encoding/binary"
"encoding/csv"
"encoding/json"
"fmt"
"io"
"log"
math_rand "math/rand"
"net"
"net/http"
"os"
"strings"
"sync"
"time"
)
type Configuration struct {
VUsersAmount int
TotalTestTime int
TimeOut int
RampUpInterval int
VUserRampUpAmount int
Requests []Request
}
type Request struct {
TYPE string
URL string
BODY map[string]string
ThinkTime int
}
func init() {
var b [8]byte
_, err := crypto_rand.Read(b[:])
if err != nil {
panic("cannot seed math/rand package with cryptographically secure random number generator")
}
math_rand.Seed(int64(binary.LittleEndian.Uint64(b[:])))
}
var timeoutCount = 0
func main() {
config := getConfig()
vUsersAmount := config.VUsersAmount
totalTestTime := time.Duration(config.TotalTestTime) * time.Second
timeout := time.Duration(config.TimeOut) * time.Second
requests := config.Requests
//rampUpInterval := time.Duration(config.RampUpInterval) * time.Second
//vUserRampUpAmount := config.VUserRampUpAmount
var waitGroup sync.WaitGroup
waitGroup.Add(vUsersAmount)
// counts the total of requests made
requestCount := 0
// Saves initial timestamp to determine total testing time
StartTime := time.Now()
for i := 0; i < vUsersAmount; i++ {
go func(vUserId int) {
// counter to manage which REQUEST is being made
requestStep := 0
var netTransport = &http.Transport{
TLSHandshakeTimeout: 5 * time.Second,
}
var client = &http.Client{
Timeout: timeout,
Transport: netTransport,
}
for totalTestTime >= time.Since(StartTime) {
// selectedLines saves the selected line number of the column
selectedLines := make(map[string]int)
if len(requests) <= requestStep {
requestStep = 0
// resets the list of selected line numbers here
for k := range selectedLines {
delete(selectedLines, k)
}
}
request := requests[requestStep]
for key, value := range request.BODY {
// check if the parameter is surrounded in curly brackets {}
if strings.HasPrefix(value, "{") && strings.HasSuffix(value, "}") {
// delete the curly brackets
value = strings.Replace(value, "{", "", -1)
value = strings.Replace(value, "}", "", -1)
// split the parameter by dots "."
parametersConfig := strings.Split(value, ".")
fileName := parametersConfig[0] + ".csv"
column := parametersConfig[1]
method := parametersConfig[2]
fmt.Println(fileName, column, method)
// open the file
csvfile, err := os.Open(fileName)
checkError("Error opening .csv file!", err)
parameters := CSVToMap(csvfile)
var line int
switch method {
case "random":
randomInt := math_rand.Intn(len(parameters))
line = randomInt
selectedLines[column] = line
fmt.Printf("random selected line for %s = %v \n parameter size %v \n", column, line, len(parameters))
case "sameastype":
sameascolumnName := parametersConfig[3]
line = selectedLines[sameascolumnName]
fmt.Printf("selected line for %s = %v \n", column, line)
case "sequencial":
}
request.BODY[key] = parameters[line][column]
}
}
requestBody, err := json.Marshal(request.BODY)
checkError("Error marshaling json!", err)
httpRequest, err := http.NewRequest(request.TYPE, request.URL, bytes.NewBuffer(requestBody))
httpRequest.Header.Set("Content-type", "application/json")
userAgent := fmt.Sprintf("[LoadSun's VUser ID - %v]", vUserId)
httpRequest.Header.Set("User-Agent", userAgent)
// Logs the error
checkError("Error setting http request with parameters!", err)
// The client does the request.
resp, err := client.Do(httpRequest)
// Logs the error
checkError("Error doing http request!", err)
requestCount++
if err == nil {
// The body of the response should be closed when it is no longer used.
defer resp.Body.Close()
//body, err := ioutil.ReadAll(resp.Body)
//checkError("Error reading http response body!", err)
log.Printf(" HTTP Response Status: %-3v %-3s %-3v %-5v Request step: %-4v \n", resp.StatusCode, http.StatusText(resp.StatusCode), "VUser id:", vUserId, requestStep)
}
requestStep++
thinkTime := time.Duration(request.ThinkTime) * time.Second
time.Sleep(thinkTime)
}
defer waitGroup.Done()
}(i)
//if vUserRampUpAmount == i {
// fmt.Printf("\n\n ADDED %v VUsers at %v \n\n", vUserRampUpAmount, time.Now())
// time.Sleep(rampUpInterval)
//}
}
// Wait for all goroutines to finish running and sync.
waitGroup.Wait()
// defer function that is executed at the end of the main function informing the total number of tests and the total test time.
defer func() {
fmt.Printf("All tests finished in %s.\n", time.Since(StartTime))
fmt.Printf("%-6v total requests.\n", requestCount)
fmt.Printf("%-6v timeouts.\n", timeoutCount)
fmt.Printf("%-6v requests excluding timeouts.\n", requestCount-timeoutCount)
}()
}
// getConfig reads the config.json file and returns a Configuration instance.
func getConfig() Configuration {
file, _ := os.Open("config.json")
defer file.Close()
config := Configuration{}
err := json.NewDecoder(file).Decode(&config)
if err != nil {
fmt.Println("error:", err)
}
return config
}
// checkError does error handling.
func checkError(msg string, err error) {
if err != nil {
log.Print(err)
}
if err, ok := err.(net.Error); ok && err.Timeout() {
timeoutCount++
}
}
// CSVToMap takes a reader and returns an array of dictionaries, using the header row as the keys
func CSVToMap(reader io.Reader) []map[string]string {
r := csv.NewReader(reader)
rows := []map[string]string{}
var header []string
for {
record, err := r.Read()
if err == io.EOF {
break
}
checkError("error reading file", err)
if header == nil {
header = record
} else {
dict := map[string]string{}
for i := range header {
dict[header[i]] = record[i]
}
rows = append(rows, dict)
}
}
return rows
}