-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
run.go
310 lines (266 loc) · 6.95 KB
/
run.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
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
package testr
import (
"context"
"fmt"
"github.com/tomwright/api-testr/testr/check"
"io/ioutil"
"log"
"net/http"
"sync"
)
const (
DefaultMaxConcurrentTests = 5
)
// Run executes a single test
func Run(ctx context.Context, t *Test, httpClient *http.Client, logger *log.Logger) error {
testData := check.DataFromContext(ctx)
if testData == nil {
testData = make(map[string]interface{})
ctx = check.ContextWithData(ctx, testData)
}
if httpClient == nil {
httpClient = http.DefaultClient
}
if logger != nil {
logger.Printf("running test: %s\n", t.Name)
}
var err error
for i, initFunc := range t.RequestInitFuncs {
initFuncData := t.RequestInitFuncsData[i]
t.Request, err = initFunc(ctx, t.Request, initFuncData)
if err != nil {
return fmt.Errorf("request init func failed: %s", err)
}
}
t.Response, err = httpClient.Do(t.Request)
if err != nil {
return fmt.Errorf("could not execute request: %s", err)
}
for _, c := range t.Checks {
err := c.Check(ctx, t.Response)
if err != nil {
return fmt.Errorf("failed `%T` check: %s", c, err)
}
}
return nil
}
// RunAllArgs defines which arguments are available to give to RunAll
type RunAllArgs struct {
HTTPClient *http.Client
MaxConcurrentTests int
Logger *log.Logger
// If Groups is not nil, only tests belonging to one of these groups will be executed
Groups []string
// If IgnoreGroups is not nil, any tests belonging to one of these groups will not be executed
IgnoreGroups []string
// IgnoreAllOnFailure should be true if when a test fails you want no more tests to be executed
IgnoreAllOnFailure bool
// IgnoreGroupOnFailure should be true if when a test fails you want no more tests in the failed group to be executed
IgnoreGroupOnFailure bool
}
// RunAllResult is the response given from RunAll
type RunAllResult struct {
Executed int
Passed int
Failed int
Skipped int
}
// RunAll runs the set of given tests
func RunAll(ctx context.Context, args RunAllArgs, tests ...*Test) RunAllResult {
if args.HTTPClient == nil {
args.HTTPClient = http.DefaultClient
}
if args.MaxConcurrentTests == 0 {
args.MaxConcurrentTests = DefaultMaxConcurrentTests
}
testData := check.DataFromContext(ctx)
if testData == nil {
testData = make(map[string]interface{})
ctx = check.ContextWithData(ctx, testData)
}
sem := make(chan struct{}, args.MaxConcurrentTests)
groupedTests := groupTests(tests...)
if args.Groups != nil {
for groupName := range groupedTests {
found := false
foundLoop:
for _, g := range args.Groups {
if groupName == g {
found = true
break foundLoop
}
}
if !found {
delete(groupedTests, groupName)
}
}
}
if args.IgnoreGroups != nil {
for _, g := range args.IgnoreGroups {
delete(groupedTests, g)
}
}
overallResMu := sync.Mutex{}
overallRes := &RunAllResult{}
groupLoop:
for groupName, groupTests := range groupedTests {
if args.Logger != nil {
args.Logger.Printf("running group %s\n", groupName)
}
if len(groupTests.tests) == 0 {
if args.Logger != nil {
args.Logger.Println("no tests")
}
continue groupLoop
}
groupResMu := sync.Mutex{}
groupRes := &RunAllResult{}
groupOrderLoop:
for i := groupTests.minOrder; i <= groupTests.maxOrder; i++ {
if args.Logger != nil {
args.Logger.Printf("running order %d\n", i)
}
groupOrderTests, ok := groupTests.tests[i]
if !ok {
continue groupOrderLoop
}
wg := &sync.WaitGroup{}
wg.Add(len(groupOrderTests))
for _, t := range groupOrderTests {
go func(t *Test) {
defer func() {
<-sem
wg.Done()
}()
sem <- struct{}{}
skip := false
if args.IgnoreGroupOnFailure {
groupResMu.Lock()
if groupRes.Failed > 0 {
skip = true
}
groupResMu.Unlock()
}
if !skip && args.IgnoreAllOnFailure {
overallResMu.Lock()
groupResMu.Lock()
if overallRes.Failed > 0 || groupRes.Failed > 0 {
skip = true
}
overallResMu.Unlock()
groupResMu.Unlock()
}
if skip {
groupResMu.Lock()
groupRes.Skipped++
if args.Logger != nil {
args.Logger.Printf("test `%s` skipped", t.Name)
}
groupResMu.Unlock()
return
}
err := Run(ctx, t, args.HTTPClient, args.Logger)
groupResMu.Lock()
defer groupResMu.Unlock()
groupRes.Executed++
if err != nil {
groupRes.Failed++
if args.Logger != nil {
args.Logger.Printf("test `%s` failed: %s\nRequest:\n%s\nResponse:\n%s\n", t.Name, err, fmtRequest(t.Request), fmtResponse(t.Response))
}
} else {
groupRes.Passed++
}
}(t)
}
wg.Wait()
}
overallResMu.Lock()
groupResMu.Lock()
overallRes.Executed += groupRes.Executed
overallRes.Passed += groupRes.Passed
overallRes.Failed += groupRes.Failed
overallRes.Skipped += groupRes.Skipped
overallResMu.Unlock()
groupResMu.Unlock()
}
overallResMu.Lock()
defer overallResMu.Unlock()
return *overallRes
}
func fmtRequest(r *http.Request) string {
if r == nil {
return ""
}
reqBodyStr, _ := ioutil.ReadAll(r.Body)
requestInfo := fmt.Sprintf("%s %s", r.Method, r.URL.String())
if reqBodyStr != nil && len(reqBodyStr) > 0 {
requestInfo = fmt.Sprintf("%s\nBody:", requestInfo)
requestInfo = fmt.Sprintf("%s\n%s", requestInfo, string(reqBodyStr))
}
if r.Header != nil && len(r.Header) > 0 {
requestInfo = fmt.Sprintf("%s%s", requestInfo, fmtHeader(r.Header))
}
return requestInfo
}
func fmtResponse(r *http.Response) string {
if r == nil {
return ""
}
respBodyStr, _ := ioutil.ReadAll(r.Body)
responseInfo := fmt.Sprintf("%s", r.Status)
if respBodyStr != nil && len(respBodyStr) > 0 {
responseInfo = fmt.Sprintf("%s\nBody:", responseInfo)
responseInfo = fmt.Sprintf("%s\n%s", responseInfo, string(respBodyStr))
}
if r.Header != nil && len(r.Header) > 0 {
responseInfo = fmt.Sprintf("%s%s", responseInfo, fmtHeader(r.Header))
}
return responseInfo
}
func fmtHeader(header http.Header) string {
resp := ""
if header != nil && len(header) > 0 {
resp = fmt.Sprintf("%s\nHeaders:", resp)
for headerName, headers := range header {
for _, headerVal := range headers {
resp = fmt.Sprintf("%s\n\t%s: %s", resp, headerName, headerVal)
}
}
}
return resp
}
func newTestsGroup() *testsGroup {
return &testsGroup{
minOrder: -1,
maxOrder: -1,
tests: make(map[int][]*Test, 0),
}
}
type testsGroup struct {
minOrder int
maxOrder int
tests map[int][]*Test
}
func (g *testsGroup) add(t *Test) {
if t.Order < g.minOrder || g.minOrder == -1 {
g.minOrder = t.Order
}
if t.Order > g.maxOrder || g.maxOrder == -1 {
g.maxOrder = t.Order
}
if _, ok := g.tests[t.Order]; !ok {
g.tests[t.Order] = make([]*Test, 0)
}
g.tests[t.Order] = append(g.tests[t.Order], t)
}
func groupTests(tests ...*Test) map[string]*testsGroup {
res := make(map[string]*testsGroup)
for _, t := range tests {
if _, ok := res[t.Group]; !ok {
res[t.Group] = newTestsGroup()
}
res[t.Group].add(t)
}
return res
}