/
utils.go
446 lines (369 loc) · 10.7 KB
/
utils.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
441
442
443
444
445
446
package cmd
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"os"
"path/filepath"
"strings"
"time"
humanize "github.com/dustin/go-humanize"
"github.com/fatih/color"
"github.com/stormforger/cli/api"
"github.com/stormforger/cli/api/filefixture"
"github.com/stormforger/cli/api/organisation"
"github.com/stormforger/cli/api/testcase"
"github.com/stormforger/cli/api/testrun"
"github.com/stormforger/cli/internal/esbundle"
)
// FindFixtureByName fetches a FileFixture from a given Organisation.
func findFixtureByName(client api.Client, orga string, name string) *filefixture.FileFixture {
success, result, err := client.ListFileFixture(orga)
if err != nil {
log.Fatalf("ListFileFixtures failed: %v", err)
}
if !success {
fmt.Fprintln(os.Stderr, "Could not lookup data source!")
fmt.Fprintln(os.Stderr, string(result))
os.Exit(1)
}
fileFixtures, err := filefixture.Unmarshal(bytes.NewReader(result))
if err != nil {
log.Fatalf("Unmarshal failed: %v", err)
}
fileFixture := fileFixtures.FindByName(name)
if fileFixture.ID == "" {
log.Fatalf("Data source %s not found in organisation %s!", name, orga)
}
return &fileFixture
}
// findOrganisationByName fetches a FileFixture from a given Organisation.
func findOrganisationByName(client *api.Client, name string) *organisation.Organisation {
status, response, err := client.ListOrganisations()
if err != nil {
log.Fatal(err)
}
if !status {
log.Fatal(string(response))
}
organisations, err := organisation.Unmarshal(bytes.NewReader(response))
if err != nil {
log.Fatal(err)
}
organisation := organisations.FindByNameOrUID(name)
if organisation.ID == "" {
log.Fatalf("Organisation %s not found!", name)
}
return &organisation
}
// readFromStdinOrReadFromArgument returns the filename and a filereader for fileArg.
// If fileArg matches "-", the defaultFileName and stdin is returned
func readFromStdinOrReadFromArgument(fileArg, defaultFileName string) (fileName string, reader io.Reader, err error) {
if fileArg == "-" {
fileName = defaultFileName
reader = os.Stdin
} else {
fileName = filepath.Base(fileArg)
reader, err = os.OpenFile(fileArg, os.O_RDONLY, 0755)
if err != nil {
return fileName, nil, err
}
}
return fileName, reader, err
}
type testCaseFileBundle struct {
Name string
Content io.Reader
Mapper esbundle.SourceMapper
}
type testCaseFileBundler struct {
Defines map[string]string
}
func (bundler testCaseFileBundler) Bundle(arg, defaultFileName string) (testCaseFileBundle, error) {
fileName, testCaseFile, err := readFromStdinOrReadFromArgument(arg, defaultFileName)
if err != nil {
return testCaseFileBundle{}, err
}
if arg != "-" && filepath.Ext(arg) == ".mjs" {
result, err := esbundle.Bundle(arg, bundler.Defines)
if err != nil {
return testCaseFileBundle{}, err
}
return testCaseFileBundle{Name: fileName, Content: strings.NewReader(result.CompiledContent), Mapper: result.SourceMapper}, nil
}
if len(bundler.Defines) > 0 {
log.Println("WARN: --define used with non-module testcase file - missing .mjs file extension")
}
return testCaseFileBundle{Name: fileName, Content: testCaseFile}, err
}
func watchTestRun(testRunUID string, maxWatchTime float64, outputFormat string) {
client := NewClient()
started := time.Now()
first := true
testStarted := false
testEnded := false
for true {
runningSince := time.Since(started).Seconds()
testRun, response, err := client.TestRunWatch(testRunUID)
if err != nil {
log.Fatal(err)
}
if first {
first = false
if testRunSuccess(&testRun) {
if outputFormat != "json" {
fmt.Printf("Test Run %s is finished.\n", testRun.ID)
}
return
}
if outputFormat == "json" {
fmt.Println(response)
} else {
formattedStartedAt := "not yet"
formattedEstimatedEnd := "n/a"
if testRun.StartedAt != "" {
formattedStartedAt = humanize.Time(parseTime(testRun.StartedAt))
testStarted = true
}
if testRun.EstimatedEnd != "" {
formattedEstimatedEnd = humanize.Time(parseTime(testRun.EstimatedEnd))
}
fmt.Printf("[status] Test Run: %s started %s (est. end %s)\n", testRun.ID, formattedStartedAt, formattedEstimatedEnd)
}
}
if outputFormat == "json" {
fmt.Println(response)
} else {
switch testRun.State {
case "running":
if !testStarted {
formattedStartedAt := "not yet"
formattedEstimatedEnd := "n/a"
if testRun.StartedAt != "" {
formattedStartedAt = humanize.Time(parseTime(testRun.StartedAt))
}
if testRun.EstimatedEnd != "" {
formattedEstimatedEnd = humanize.Time(parseTime(testRun.EstimatedEnd))
}
fmt.Printf("[status] Test Run: %s started %s (est. end %s)\n", testRun.ID, formattedStartedAt, formattedEstimatedEnd)
testStarted = true
}
fmt.Printf("[%s] Progress: %d%%\n", testRun.State, testRun.Progress)
default:
if testStarted && !testEnded {
fmt.Printf("[status] Test run ended...\n")
testEnded = true
}
fmt.Printf("[%s]\n", testRun.State)
}
}
if !testRunOkay(&testRun) {
os.Exit(1)
}
if testRunSuccess(&testRun) {
return
}
if int(maxWatchTime) > 0 && int(runningSince) > int(maxWatchTime) {
os.Exit(2)
}
time.Sleep(5 * time.Second)
}
}
func lookupOrganisationUID(client *api.Client, input string) string {
organisation := findOrganisationByName(client, input)
if organisation.ID == "" {
log.Fatalf("Organisation %s not found", input)
}
return organisation.ID
}
// mustLookupTestCase returns the ID of the test-case for the given input or calls log.Fatal().
func mustLookupTestCase(client *api.Client, input string) string {
s := lookupTestCase(client, input)
if s == "" {
log.Fatalf("Test case for query '%s' not found", input)
}
return s
}
func lookupTestCase(client *api.Client, input string) string {
segments := strings.Split(input, "/")
nameOrUID := input
if len(segments) == 2 {
organisationNameOrUID := segments[0]
nameOrUID = segments[1]
organisationUID := lookupOrganisationUID(client, organisationNameOrUID)
_, result, err := client.ListTestCases(organisationUID, "all")
if err != nil {
log.Fatal(err)
}
testCases, err := testcase.Unmarshal(bytes.NewReader(result))
if err != nil {
log.Fatal(err)
}
testCase := testCases.FindByNameOrUID(nameOrUID)
return testCase.ID
}
return nameOrUID
}
func getTestRunUID(client api.Client, input string) string {
testRunParts := api.ExtractTestRunResources(input)
if testRunParts.UID != "" {
return testRunParts.UID
} else if testRunParts.Organisation == "" || testRunParts.TestCase == "" {
log.Fatal("Invalid test run reference provided! Consult with --help to learn more.")
}
result := fetchTestRun(client, input)
testRun, err := testrun.UnmarshalSingle(bytes.NewReader(result))
if err != nil {
log.Fatal(err)
}
return testRun.ID
}
func fetchTestRun(client api.Client, input string) []byte {
testRunParts := api.ExtractTestRunResources(input)
if testRunParts.UID != "" {
status, response, err := client.FetchTestRun(testRunParts.UID)
if err != nil {
log.Fatal(err)
}
if !status {
log.Fatalf("Could not load test run %s", testRunParts.UID)
}
return response
} else if testRunParts.Organisation == "" || testRunParts.TestCase == "" {
log.Fatal("Invalid test run reference provided! Consult with --help to learn more.")
}
status, response, err := client.LookupAndFetchResource("test_run", input)
if err != nil {
log.Fatal(err)
}
if !status {
log.Fatalf("Test Run %s not found", input)
}
return response
}
func parseTime(subject string) time.Time {
parsedTime, err := time.Parse(time.RFC3339Nano, subject)
if err != nil {
log.Fatal(err)
}
return parsedTime
}
func convertToLocalTZ(timeToConvert time.Time) time.Time {
loc, err := time.LoadLocation("Local")
if err != nil {
log.Fatal(err)
}
return timeToConvert.In(loc)
}
type NfrChecker struct {
Client *api.Client
TestRunUID string
ResultFilter func(items testrun.NfrResultList) testrun.NfrResultList
}
func (checker *NfrChecker) runNfrCheck(fileName string, nfrData io.Reader) {
status, result, err := checker.Client.TestRunNfrCheck(checker.TestRunUID, fileName, nfrData)
if err != nil {
log.Fatal(err)
}
checker.handleNfrResponseData(status, result)
}
func (checker *NfrChecker) handleNfrResponseData(status bool, result []byte) {
if rootOpts.OutputFormat == "json" {
fmt.Println(string(result))
return
}
if !status {
var response struct {
Status string
Message string
Error string
}
log.Println("Could not perform test-run NFR checks...")
if err := json.Unmarshal(result, &response); err != nil {
log.Println(string(result))
} else {
if response.Status != "" {
log.Printf(" Status:\t%s\n", response.Status)
}
if response.Message != "" {
log.Printf(" Message:\t%s\n", response.Message)
}
if response.Error != "" {
log.Printf(" Error:\t%s\n", response.Error)
}
}
os.Exit(1)
}
items, err := testrun.UnmarshalNfrResults(bytes.NewReader(result))
if err != nil {
log.Fatal(err)
}
if checker.ResultFilter != nil {
items = checker.ResultFilter(items)
}
anyFails := checker.displayNfrResult(items)
if anyFails {
os.Exit(1)
}
}
func (checker *NfrChecker) displayNfrResult(items testrun.NfrResultList) bool {
green := color.New(color.FgGreen).SprintFunc()
red := color.New(color.FgRed).SprintFunc()
redBg := color.New(color.BgRed).Add(color.FgWhite).SprintFunc()
white := color.New(color.FgWhite).SprintFunc()
whiteBold := color.New(color.FgWhite, color.Bold).SprintFunc()
checkStatus := ""
anyFails := false
var success, total int
for _, item := range items.NfrResults {
total++ // we count everything, including disable and unavailable here.
if !item.Disabled {
actualSubject := ""
if item.SubjectAvailable {
if item.Success {
success++
checkStatus = green("\u2713")
actualSubject = fmt.Sprintf("was %s", item.SubjectWithUnit())
} else {
anyFails = true
checkStatus = red("\u2717")
actualSubject = fmt.Sprintf("but actually was %s", item.SubjectWithUnit())
}
} else {
checkStatus = whiteBold("?")
actualSubject = fmt.Sprintf("was %s", whiteBold("not available"))
}
filter := ""
if item.Filter != "null" && item.Filter != "" {
filter = " (where: " + item.Filter + ")"
}
fmt.Printf(
"%s %s expected to be %s; %s (%s)%s\n",
checkStatus,
item.Metric,
item.ExpectationWithUnit(),
actualSubject,
item.Type,
filter,
)
} else {
fmt.Printf(
"%s %s %s expected to be %s (%s)\n",
white("?"),
redBg("DISABLED"),
item.Metric,
item.ExpectationWithUnit(),
item.Type,
)
}
}
fmt.Printf("%d/%d checks passed\n", success, total)
if !anyFails {
fmt.Println(green("\nAll checks passed!"))
} else {
fmt.Println(red("\nYou have failing checks!"))
}
return anyFails
}