-
Notifications
You must be signed in to change notification settings - Fork 23
/
main.go
executable file
·362 lines (306 loc) · 9.3 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
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
package main
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"strconv"
"text/tabwriter"
"time"
"github.com/bitrise-io/go-steputils/stepconf"
"github.com/bitrise-io/go-steputils/tools"
"github.com/bitrise-io/go-utils/colorstring"
"github.com/bitrise-io/go-utils/log"
"github.com/bitrise-io/go-utils/pathutil"
"github.com/bitrise-io/go-utils/sliceutil"
"github.com/bitrise-steplib/steps-virtual-device-testing-for-android/resultprocessing"
toolresults "google.golang.org/api/toolresults/v1beta3"
)
const (
testTypeInstrumentation = "instrumentation"
testTypeRobo = "robo"
)
func failf(f string, v ...interface{}) {
log.Errorf(f, v...)
os.Exit(1)
}
func main() {
var configs ConfigsModel
if err := stepconf.Parse(&configs); err != nil {
failf("Invalid input: %s", err)
}
if err := configs.validate(); err != nil {
log.Errorf("Failed to parse config:")
failf("%s", err)
}
fmt.Println()
configs.print()
log.SetEnableDebugLog(configs.VerboseLog)
fmt.Println()
successful := true
log.Infof("Uploading app and test files")
testAssets, err := uploadTestAssets(configs)
if err != nil {
failf("Failed to upload test assets, error: %s", err)
}
log.Donef("=> Files uploaded")
fmt.Println()
log.Infof("Starting test")
if err = startTestRun(configs, testAssets); err != nil {
failf("Starting test run failed, error: %s", err)
}
log.Donef("=> Test started")
fmt.Println()
log.Infof("Waiting for test results")
{
finished := false
printedLogs := []string{}
for !finished {
url := configs.APIBaseURL + "/" + configs.AppSlug + "/" + configs.BuildSlug + "/" + configs.APIToken
req, err := http.NewRequest("GET", url, nil)
if err != nil {
failf("Failed to create http request, error: %s", err)
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil || resp.StatusCode != http.StatusOK {
resp, err = client.Do(req)
if err != nil {
failf("Failed to get http response, error: %s", err)
}
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
failf("Failed to read response body, error: %s", err)
}
if resp.StatusCode != http.StatusOK {
failf("Failed to get test status, error: %s", string(body))
}
responseModel := &toolresults.ListStepsResponse{}
err = json.Unmarshal(body, responseModel)
if err != nil {
failf("Failed to unmarshal response body, error: %s, body: %s", err, string(body))
}
finished = true
testsRunning := 0
for _, step := range responseModel.Steps {
if step.State != "complete" {
finished = false
testsRunning++
}
}
msg := ""
if len(responseModel.Steps) == 0 {
finished = false
msg = fmt.Sprintf("- Validating")
} else {
msg = fmt.Sprintf("- (%d/%d) running", testsRunning, len(responseModel.Steps))
}
if !sliceutil.IsStringInSlice(msg, printedLogs) {
log.Printf(msg)
printedLogs = append(printedLogs, msg)
}
if finished {
log.Donef("=> Test finished")
fmt.Println()
log.Infof("Test results:")
w := tabwriter.NewWriter(os.Stdout, 0, 0, 3, ' ', 0)
if _, err := fmt.Fprintln(w, "Model\tAPI Level\tLocale\tOrientation\tOutcome\t"); err != nil {
failf("Failed to write in tabwriter, error: %s", err)
}
successful, err = resultprocessing.GetSuccessOfExecution(responseModel.Steps)
if err != nil {
failf("Failed to process results, error: %s", err)
}
for _, step := range responseModel.Steps {
dimensions := map[string]string{}
for _, dimension := range step.DimensionValue {
dimensions[dimension.Key] = dimension.Value
}
outcome := processStepResult(step)
if _, err := fmt.Fprintln(w, fmt.Sprintf("%s\t%s\t%s\t%s\t%s\t", dimensions["Model"], dimensions["Version"], dimensions["Locale"], dimensions["Orientation"], outcome)); err != nil {
failf("Failed to write in tabwriter, error: %s", err)
}
}
if err := w.Flush(); err != nil {
log.Errorf("Failed to flush writer, error: %s", err)
}
}
if !finished {
time.Sleep(10 * time.Second)
}
}
}
if configs.DownloadTestResults {
fmt.Println()
log.Infof("Downloading test assets")
{
url := configs.APIBaseURL + "/assets/" + configs.AppSlug + "/" + configs.BuildSlug + "/" + configs.APIToken
req, err := http.NewRequest("GET", url, nil)
if err != nil {
failf("Failed to create http request, error: %s", err)
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
failf("Failed to get http response, error: %s", err)
}
if resp.StatusCode != http.StatusOK {
failf("Failed to get http response, status code: %d", resp.StatusCode)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
failf("Failed to read response body, error: %s", err)
}
responseModel := map[string]string{}
err = json.Unmarshal(body, &responseModel)
if err != nil {
failf("Failed to unmarshal response body, error: %s", err)
}
tempDir, err := pathutil.NormalizedOSTempDirPath("vdtesting_test_assets")
if err != nil {
failf("Failed to create temp dir, error: %s", err)
}
for fileName, fileURL := range responseModel {
err := downloadFile(fileURL, filepath.Join(tempDir, fileName))
if err != nil {
failf("Failed to download file, error: %s", err)
}
}
log.Donef("=> Assets downloaded")
if err := tools.ExportEnvironmentWithEnvman("VDTESTING_DOWNLOADED_FILES_DIR", tempDir); err != nil {
log.Warnf("Failed to export environment (VDTESTING_DOWNLOADED_FILES_DIR), error: %s", err)
} else {
log.Printf("The downloaded test assets path (%s) is exported to the VDTESTING_DOWNLOADED_FILES_DIR environment variable.", tempDir)
}
}
}
if !successful {
os.Exit(1)
}
}
func downloadFile(url string, localPath string) error {
out, err := os.Create(localPath)
if err != nil {
return fmt.Errorf("Failed to open the local cache file for write: %s", err)
}
defer func() {
if err := out.Close(); err != nil {
log.Printf("Failed to close Archive download file (%s): %s", localPath, err)
}
}()
resp, err := http.Get(url)
if err != nil {
return fmt.Errorf("Failed to create cache download request: %s", err)
}
defer func() {
if err := resp.Body.Close(); err != nil {
log.Printf("Failed to close Archive download response body: %s", err)
}
}()
if resp.StatusCode != 200 {
return fmt.Errorf("Failed to download archive - non success response code: %d", resp.StatusCode)
}
_, err = io.Copy(out, resp.Body)
if err != nil {
return fmt.Errorf("Failed to save cache content into file: %s", err)
}
return nil
}
func uploadFile(uploadURL string, archiveFilePath string) error {
archFile, err := os.Open(archiveFilePath)
if err != nil {
return fmt.Errorf("Failed to open archive file for upload (%s): %s", archiveFilePath, err)
}
isFileCloseRequired := true
defer func() {
if !isFileCloseRequired {
return
}
if err := archFile.Close(); err != nil {
log.Printf(" (!) Failed to close archive file (%s): %s", archiveFilePath, err)
}
}()
fileInfo, err := archFile.Stat()
if err != nil {
return fmt.Errorf("Failed to get File Stats of the Archive file (%s): %s", archiveFilePath, err)
}
fileSize := fileInfo.Size()
req, err := http.NewRequest("PUT", uploadURL, archFile)
if err != nil {
return fmt.Errorf("Failed to create upload request: %s", err)
}
req.Header.Add("Content-Length", strconv.FormatInt(fileSize, 10))
req.ContentLength = fileSize
resp, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("Failed to upload: %s", err)
}
isFileCloseRequired = false
defer func() {
if err := resp.Body.Close(); err != nil {
log.Printf(" [!] Failed to close response body: %s", err)
}
}()
_, err = ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("Failed to read response: %s", err)
}
if resp.StatusCode != 200 {
return fmt.Errorf("Failed to upload file, response code was: %d", resp.StatusCode)
}
return nil
}
func processStepResult(step *toolresults.Step) string {
outcome := step.Outcome.Summary
switch outcome {
case "success":
outcome = colorstring.Green(outcome)
case "failure":
if step.Outcome.FailureDetail != nil {
if step.Outcome.FailureDetail.Crashed {
outcome += "(Crashed)"
}
if step.Outcome.FailureDetail.NotInstalled {
outcome += "(NotInstalled)"
}
if step.Outcome.FailureDetail.OtherNativeCrash {
outcome += "(OtherNativeCrash)"
}
if step.Outcome.FailureDetail.TimedOut {
outcome += "(TimedOut)"
}
if step.Outcome.FailureDetail.UnableToCrawl {
outcome += "(UnableToCrawl)"
}
}
outcome = colorstring.Red(outcome)
case "inconclusive":
if step.Outcome.InconclusiveDetail != nil {
if step.Outcome.InconclusiveDetail.AbortedByUser {
outcome += "(AbortedByUser)"
}
if step.Outcome.InconclusiveDetail.InfrastructureFailure {
outcome += "(InfrastructureFailure)"
}
}
outcome = colorstring.Yellow(outcome)
case "skipped":
if step.Outcome.SkippedDetail != nil {
if step.Outcome.SkippedDetail.IncompatibleAppVersion {
outcome += "(IncompatibleAppVersion)"
}
if step.Outcome.SkippedDetail.IncompatibleArchitecture {
outcome += "(IncompatibleArchitecture)"
}
if step.Outcome.SkippedDetail.IncompatibleDevice {
outcome += "(IncompatibleDevice)"
}
}
outcome = colorstring.Blue(outcome)
}
return outcome
}