-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathtesting.go
440 lines (345 loc) · 9.81 KB
/
testing.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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
package vertex
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"path"
"runtime"
"sync"
"text/tabwriter"
"time"
"github.com/dvirsky/go-pylog/logging"
)
// Tester represents a testcase the API runs for a certain API.
//
// Each API contains a list of integration tests that can be run to monitor it. Each test can have a category
// associated with it, and we can run tests by a specific category only.
//
// A test should fail or succeed, and can optionally write error output
type Tester interface {
Test(*TestContext)
Category() string
}
// test categories
const (
CriticalTests = "critical"
WarningTests = "warning"
AllTests = "all"
)
type testFunc struct {
f func(*TestContext)
category string
}
func (f testFunc) Test(ctx *TestContext) {
f.f(ctx)
}
func (f testFunc) Category() string {
return f.category
}
// CrititcalTest wraps testers to signify that the tester is considered critical
func CriticalTest(f func(ctx *TestContext)) Tester {
return testFunc{f, CriticalTests}
}
// WarningTest wraps testers to signify that the tester is a warning test
func WarningTest(f func(ctx *TestContext)) Tester {
return testFunc{f, WarningTests}
}
// TestContext is a utility available for all testing functions, allowing them to easily test the current route.
// It is inspired by Go's testing framework.
//
// In general, a tester needs to call t.Fail(), t.Fatal() or t.Skip() to stop the execution of the test.
// A test that doesn't call either of them is considered passing
type TestContext struct {
api *API
serverURl string
routePath string
category string
messages []string
startTime time.Time
}
// Log writes a message to be displayed alongside the test result ONLY if the test failed
func (t *TestContext) Log(format string, params ...interface{}) {
msg := fmt.Sprintf("%v> %s", time.Now().Format("15:04:05.000"), fmt.Sprintf(format, params...))
logging.Info(msg)
t.messages = append(t.messages, msg)
}
// Fatal aborts the test with a FATAL status
func (t *TestContext) Fatal(format string, params ...interface{}) {
res := newTestResult(resultFatal, fmt.Sprintf(format, params...), 2, t)
panic(res)
}
// Skip aborts the test with a SKIP status, that is considered passing
func (t *TestContext) Skip() {
panic(newTestResult(resultSkipped, "", 2, t))
}
// Fail aborts the test with a FAIL status, that is the normal case for failing tests
func (t *TestContext) Fail(format string, params ...interface{}) {
panic(newTestResult(resultFailed, fmt.Sprintf(format, params...), 2, t))
}
// ServerUrl returns the URL of the vertex server we are testing
func (t *TestContext) ServerUrl() string {
return t.serverURl
}
// FormatUrl returns a fully formatted URL for the context's route, with all path params replaced by
// their respective values in the pathParams map
func (t *TestContext) FormatUrl(pathParams Params) string {
u := fmt.Sprintf("%s%s", t.serverURl, t.api.FullPath(FormatPath(t.routePath, pathParams)))
logging.Debug("Formatted url: %s", u)
return u
}
// NewRequest creates a new http request to the route we are testing now, with optional values for post/get, and optional path params
func (t *TestContext) NewRequest(method string, values url.Values, pathParams Params) (*http.Request, error) {
var body io.Reader
u := t.FormatUrl(pathParams)
if values != nil && len(values) > 0 {
if method == "POST" {
body = bytes.NewReader([]byte(values.Encode()))
} else {
u += "?" + values.Encode()
}
}
req, err := http.NewRequest(method, u, body)
// for POST requests we need to correctly set the content type
if err == nil && body != nil {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
return req, err
}
// GetJSON performs the given request, and tries to deserialize the response object to v.
// If we received an error or decoding is impossible, we return an error.
// The raw http response is also returned for inspection
func (t *TestContext) GetJSON(r *http.Request, v interface{}) (*http.Response, error) {
resp, err := http.DefaultClient.Do(r)
if err != nil {
return resp, err
}
b, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
// We replace the request's body with a fake one if the caller wants to peek inside
resp.Body = ioutil.NopCloser(bytes.NewReader(b))
err = json.Unmarshal(b, v)
if err == nil && resp.StatusCode >= 400 {
err = fmt.Errorf("Bad HTTP response code: %s", resp.Status)
}
return resp, err
}
type testRunner struct {
category string
serverURL string
api *API
output io.Writer
formatter resultFormatter
}
type resultFormatter interface {
format(testResult) error
}
const (
TestFormatText = "text"
TestFormatJson = "json"
)
type jsonResultFormatter struct {
encoder *json.Encoder
w io.Writer
}
func newJsonResultFormatter(out io.Writer) *jsonResultFormatter {
return &jsonResultFormatter{
encoder: json.NewEncoder(out),
w: out,
}
}
func (f jsonResultFormatter) format(r testResult) error {
if err := f.encoder.Encode(r); err != nil {
return err
}
return nil
}
type textResultFormatter struct {
w *tabwriter.Writer
}
func newTextResultFormatter(w io.Writer) *textResultFormatter {
return &textResultFormatter{
w: tabwriter.NewWriter(w, 40, 8, 0, '\t', tabwriter.DiscardEmptyColumns),
}
}
func (f textResultFormatter) format(result testResult) error {
if _, err := fmt.Fprintf(f.w, "- %s\t(category: %s)\t[%s]\t(%v)\n", result.Path, result.Category, result.Result, result.Duration); err != nil {
return err
}
// Output log messages if we failed
if result.isFailure() {
if result.Message != "" {
if _, err := fmt.Fprintf(f.w, " ERROR in %s: %s\n", result.FailPoint, result.Message); err != nil {
return err
}
}
if result.Log != nil && len(result.Log) > 0 {
fmt.Fprintln(f.w, " Messages:")
for _, msg := range result.Log {
if _, err := fmt.Fprintln(f.w, " ", msg); err != nil {
return err
}
}
}
fmt.Fprintln(f.w, "")
}
return f.w.Flush()
}
func newTestRunner(output io.Writer, a *API, serverURL string, category string, format string) *testRunner {
var formatter resultFormatter
switch format {
case TestFormatJson:
formatter = newJsonResultFormatter(output)
case TestFormatText:
fallthrough
default:
formatter = newTextResultFormatter(output)
}
return &testRunner{
serverURL: serverURL,
category: category,
api: a,
output: output,
formatter: formatter,
}
}
// test status codes
const (
resultFatal = "FATAL"
resultSkipped = "SKIP"
resultMissing = "MISSING"
resultFailed = "FAIL"
resultPass = "PASS"
)
type testResult struct {
Result string `json:"result"`
Path string `json:"path,omitempty"`
Category string `json:"category,omitempty"`
Log []string `json:"log,omitempty"`
Message string `json:"message,omitempty"`
FailPoint string `json:"failpoint,omitempty"`
Duration time.Duration `json:"duration,omitempty"`
}
func (r testResult) isFailure() bool {
return !(r.Result == resultPass || r.Result == resultSkipped)
}
func newTestResult(result, message string, depth int, ctx *TestContext) testResult {
ret := testResult{
Path: ctx.routePath,
Category: ctx.category,
Result: result,
Message: message,
Duration: time.Since(ctx.startTime),
}
if ret.isFailure() {
if pc, _, line, ok := runtime.Caller(depth); ok {
f := runtime.FuncForPC(pc)
if f != nil {
ret.FailPoint = fmt.Sprintf("%s:%d", path.Base(f.Name()), line)
}
}
}
return ret
}
// runTest safely runs a test and catches its output and panics
func (t *testRunner) runTest(tc Tester, path string) (res testResult) {
// missing testers fail as missing
if tc == nil {
res = newTestResult(resultMissing, "", 1, &TestContext{routePath: path, category: WarningTests, startTime: time.Now()})
return
}
ctx := &TestContext{
api: t.api,
serverURl: t.serverURL,
routePath: path,
messages: make([]string, 0),
category: tc.Category(),
startTime: time.Now(),
}
// recover from panics and analyze the input
defer func() {
e := recover()
if e != nil {
switch x := e.(type) {
case testResult:
res = x
default:
res = newTestResult(resultFatal, fmt.Sprintf("Panic handling test: %v", x), 6, ctx)
}
}
return
}()
tc.Test(ctx)
res = newTestResult(resultPass, "", 1, ctx)
return
}
// Determine whether a test shuold run based on the context
func (t *testRunner) shouldRun(tc Tester) bool {
if t.category == "" || t.category == AllTests {
return true
}
if tc == nil {
return false
}
return getTestCategory(tc) == t.category
}
func getTestCategory(tc Tester) string {
if tc != nil {
return tc.Category()
}
return AllTests
}
// invokeTest runs a tester and prints the output
func (t *testRunner) invokeTest(path string, tc Tester) *testResult {
if t.shouldRun(tc) {
var result testResult
if tc == nil || t.shouldRun(tc) {
result = t.runTest(tc, path)
logging.Info("Test result for %s: %#v", path, result)
if err := t.formatter.format(result); err != nil {
logging.Error("Error running formatter: %s", err)
}
return &result
}
}
return nil
}
func (t *testRunner) Run() bool {
reschan := make(chan *testResult)
wg := sync.WaitGroup{}
for _, route := range t.api.Routes {
wg.Add(1)
go func(route Route) {
reschan <- t.invokeTest(route.Path, route.Test)
wg.Done()
}(route)
}
go func() {
wg.Wait()
close(reschan)
}()
success := true
for res := range reschan {
if res == nil {
continue
}
if res.isFailure() {
success = false
}
}
return success
}
func RunCLITest(apiName, serverAddr, category, format string, out io.Writer) bool {
builder, ok := apiBuilders[apiName]
if !ok {
fmt.Fprintf(os.Stderr, "Error: API %s not found\n", apiName)
return false
}
a := builder()
tr := newTestRunner(out, a, serverAddr, category, format)
return tr.Run()
}