/
main.go
233 lines (192 loc) · 5.34 KB
/
main.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
package main
import (
"flag"
"os"
"fmt"
"io/ioutil"
"log"
"os/exec"
"strings"
"encoding/csv"
"gopkg.in/yaml.v2"
)
var (
conf Config
cfgFlag = flag.String("config", "config.yaml", "path of the config file")
outputFlag = flag.String("output", "", "csv file to export, non if left blank")
resultParams = [][]string {
{"title"},
{"time_taken", "Time taken for tests:"},
{"completed", "Complete requests:"},
{"failed", "Failed requests:"},
{"requests_per_second", "Requests per second:"},
}
)
// Config contains the settings of the ST server getting testes and all the tests
type Config struct {
Host string `yaml:"host"`
Version string `yaml:"version"`
Requests int64 `yaml:"requests"`
Concurrency int64 `yaml:"concurrency"`
APIEndpoint string
Tests []Test `yaml:"tests"`
}
// Test is a test loaded from config/yaml and getting executed by AB
type Test struct {
Name string `yaml:"name"`
Requests int64 `yaml:"requests"`
Concurrency int64 `yaml:"concurrency"`
Endpoint string `yaml:"endpoint"`
RequestType string `yaml:"type"`
File string `yaml:"file"`
}
func main() {
log.Print("Starting AB tests")
flag.Parse()
cfg := *cfgFlag
output := *outputFlag
var err error
conf, err = getConfig(cfg)
if err != nil {
log.Fatal("config read error: ", err)
return
}
results := runABTest()
if len(output) > 0 {
writeCSV(output, results)
}
log.Print("Done!")
}
func runABTest() [][]string {
results := [][]string{}
for i := 0; i < len(conf.Tests); i++ {
//log.Print("Starting test " + conf.Tests[i].Name)
testCommand := testToAb(conf.APIEndpoint, conf.Tests[i]);
cmd := exec.Command("ab", testCommand...)
stdout, err := cmd.Output()
if err != nil {
println(err.Error())
return nil
}
result := getResultFromOutput(stdout)
result = append([]string{conf.Tests[i].Name}, result...)
results = append(results, result)
printResults(conf.Tests[i].Name, result)
}
return results
}
func testToAb(apiEndpoint string, test Test) []string {
params := []string{
"-n", fmt.Sprintf("%v", test.Requests),
"-k",
"-c", fmt.Sprintf("%v", test.Concurrency),
}
if test.RequestType == "POST" || test.RequestType == "PUT" {
method := ""
if test.RequestType == "POST"{
method = "-p"
} else if test.RequestType == "PUT"{
method = "-u"
}
params = append(params, method)
params = append(params, test.File)
params = append(params, "-T")
params = append(params, "content-type-:application/json")
}
endpoint := strings.Join([]string{apiEndpoint, strings.TrimPrefix(test.Endpoint, "/")}, "/")
params = append(params, endpoint)
return params
}
func getResultFromOutput(output []byte) []string {
split := strings.Split(string(output), "\n")
results := []string{}
for i := 0; i < len(split); i++ {
for j := 1; j < len(resultParams); j++ {
if strings.Contains(split[i], resultParams[j][1]) {
sub := strings.Trim(split[i], resultParams[j][1])
results = append(results, strings.Split(sub, " ")[0])
}
}
}
return results
}
func printResults(test string, results []string){
log.Printf("----------------------------------\n")
indent := 25
for i := 0; i < len(results); i++ {
log.Printf("%s%s%s", resultParams[i][0], createIndent(indent - len(resultParams[i][0])), results[i])
}
}
func createIndent(length int) string {
indent := ""
for i := 0; i < length; i++ {
indent = fmt.Sprintf("%s ", indent)
}
return indent
}
func writeCSV(path string, results [][]string){
file, err := os.Create(path)
if err != nil {
log.Fatal("Cannot create file", err)
}
defer file.Close()
writer := csv.NewWriter(file)
defer writer.Flush()
//add header to results
header := []string{}
for i := 0; i < len(resultParams); i++{
header = append(header, resultParams[i][0])
}
results = append([][]string {header}, results...)
// write
for _, value := range results {
err := writer.Write(value)
if err != nil {
log.Fatal("Cannot write to file", err)
}
}
log.Printf("CSV output written to %s", path)
}
func getConfig(cfgFile string) (Config, error) {
config := Config{}
content, err := ioutil.ReadFile(cfgFile)
if err != nil {
return config, err
}
err = yaml.Unmarshal(content, &config)
if err != nil {
return config, err
}
config.Host = strings.TrimSuffix(config.Host, "/")
config.APIEndpoint = strings.Join([]string{config.Host, config.Version}, "/")
checkConfig(config)
return config, nil
}
func checkConfig(config Config) {
for i := 0; i < len(config.Tests); i++ {
test := &config.Tests[i]
// fatal on error
if(test.Name == ""){
log.Fatalf("test at index %v missing name", i);
}
if(test.RequestType != "GET" && test.RequestType != "POST" && test.RequestType != "PUT"){
log.Fatalf("%s test type '%s' is not support, supported types are GET, POST or PUT", test.Name, test.RequestType);
}
if((test.RequestType == "POST" || test.RequestType == "PUT") && len(test.File) == 0){
log.Fatalf("%s test type is '%s' but no file given", test.Name, test.RequestType);
}
if(test.File != ""){
_, err := ioutil.ReadFile(test.File)
if err != nil {
log.Fatalf("%s unable to read or find file '%s'", test.Name, test.File);
}
}
// set default params
if(test.Requests == 0){
test.Requests = config.Requests
}
if(test.Concurrency == 0){
test.Concurrency = config.Concurrency
}
}
}