This repository has been archived by the owner on Jul 27, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
executable file
·560 lines (474 loc) · 15.5 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
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
package main
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"text/tabwriter"
"time"
"github.com/bitrise-io/go-steputils/input"
"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"
testing "google.golang.org/api/testing/v1"
toolresults "google.golang.org/api/toolresults/v1beta3"
)
const (
maxTimeoutSeconds = 1800
)
// ConfigsModel ...
type ConfigsModel struct {
// api
APIBaseURL string
BuildSlug string
AppSlug string
APIToken string
// shared
ZipPath string
TestDevices string
TestTimeout string
DownloadTestResults string
}
// UploadURLRequest ...
type UploadURLRequest struct {
AppURL string `json:"appUrl"`
TestAppURL string `json:"testAppUrl"`
}
func createConfigsModelFromEnvs() ConfigsModel {
return ConfigsModel{
// api
APIBaseURL: os.Getenv("api_base_url"),
BuildSlug: os.Getenv("BITRISE_BUILD_SLUG"),
AppSlug: os.Getenv("BITRISE_APP_SLUG"),
APIToken: os.Getenv("api_token"),
// shared
ZipPath: os.Getenv("zip_path"),
TestDevices: os.Getenv("test_devices"),
TestTimeout: os.Getenv("test_timeout"),
DownloadTestResults: os.Getenv("download_test_results"),
}
}
func (configs ConfigsModel) print() {
log.Infof("Configs:")
log.Printf("- ZipPath: %s", configs.ZipPath)
log.Printf("- TestTimeout: %s", configs.TestTimeout)
log.Printf("- TestDevices:\n---")
w := tabwriter.NewWriter(os.Stdout, 0, 0, 3, ' ', 0)
if _, err := fmt.Fprintln(w, "Model\tOS version\tOrientation\tLocale\t"); err != nil {
failf("Failed to write in writer")
}
scanner := bufio.NewScanner(strings.NewReader(configs.TestDevices))
for scanner.Scan() {
device := scanner.Text()
device = strings.TrimSpace(device)
if device == "" {
continue
}
deviceParams := strings.Split(device, ",")
if len(deviceParams) != 4 {
continue
}
if _, err := fmt.Fprintln(w, fmt.Sprintf("%s\t%s\t%s\t%s\t", deviceParams[0], deviceParams[1], deviceParams[3], deviceParams[2])); err != nil {
failf("Failed to write in writer")
}
}
if err := w.Flush(); err != nil {
log.Errorf("Failed to flush writer, error: %s", err)
}
log.Printf("---")
}
func (configs ConfigsModel) validate() error {
if err := input.ValidateIfNotEmpty(configs.APIBaseURL); err != nil {
if _, set := os.LookupEnv("BITRISE_IO"); !set {
log.Warnf("Warning: please make sure that Virtual Device Testing add-on is turned on under your app's settings tab.")
}
return fmt.Errorf("Issue with APIBaseURL: %s", err)
}
if err := input.ValidateIfNotEmpty(configs.APIToken); err != nil {
return fmt.Errorf("Issue with APIToken: %s", err)
}
if err := input.ValidateIfNotEmpty(configs.BuildSlug); err != nil {
return fmt.Errorf("Issue with BuildSlug: %s", err)
}
if err := input.ValidateIfNotEmpty(configs.AppSlug); err != nil {
return fmt.Errorf("Issue with AppSlug: %s", err)
}
if err := input.ValidateIfNotEmpty(configs.ZipPath); err != nil {
return fmt.Errorf("Issue with ZipPath: %s", err)
}
if err := input.ValidateIfPathExists(configs.ZipPath); err != nil {
return fmt.Errorf("Issue with ZipPath: %s", err)
}
return nil
}
func failf(f string, v ...interface{}) {
log.Errorf(f, v...)
os.Exit(1)
}
func main() {
configs := createConfigsModelFromEnvs()
fmt.Println()
configs.print()
if err := configs.validate(); err != nil {
failf("%s", err)
}
fmt.Println()
successful := true
log.Infof("Upload IPAs")
{
url := configs.APIBaseURL + "/assets/" + configs.AppSlug + "/" + configs.BuildSlug + "/" + configs.APIToken
req, err := http.NewRequest("POST", 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 {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
failf("Failed to read response body, error: %s", err)
}
failf("Failed to start test: %d, error: %s", resp.StatusCode, string(body))
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
failf("Failed to read response body, error: %s", err)
}
responseModel := &UploadURLRequest{}
if err := json.Unmarshal(body, responseModel); err != nil {
failf("Failed to unmarshal response body, error: %s", err)
}
if err := uploadFile(responseModel.AppURL, configs.ZipPath); err != nil {
failf("Failed to upload file(%s) to (%s), error: %s", configs.ZipPath, responseModel.AppURL, err)
}
log.Donef("=> .xctestrun uploaded")
}
fmt.Println()
log.Infof("Start test")
{
url := configs.APIBaseURL + "/" + configs.AppSlug + "/" + configs.BuildSlug + "/" + configs.APIToken
testModel := &testing.TestMatrix{}
testModel.EnvironmentMatrix = &testing.EnvironmentMatrix{IosDeviceList: &testing.IosDeviceList{}}
testModel.EnvironmentMatrix.IosDeviceList.IosDevices = []*testing.IosDevice{}
scanner := bufio.NewScanner(strings.NewReader(configs.TestDevices))
for scanner.Scan() {
device := scanner.Text()
device = strings.TrimSpace(device)
if device == "" {
continue
}
deviceParams := strings.Split(device, ",")
if len(deviceParams) != 4 {
failf("Invalid test device configuration: %s", device)
}
newDevice := testing.IosDevice{
IosModelId: deviceParams[0],
IosVersionId: deviceParams[1],
Locale: deviceParams[2],
Orientation: deviceParams[3],
}
testModel.EnvironmentMatrix.IosDeviceList.IosDevices = append(testModel.EnvironmentMatrix.IosDeviceList.IosDevices, &newDevice)
}
timeout := configs.TestTimeout
if val, err := strconv.ParseFloat(timeout, 64); err != nil {
failf("could not parse float from timeout value (%s): %s", timeout, err)
} else if val > float64(maxTimeoutSeconds) {
log.Warnf("timeout value (%f) is greater than available maximum (%f). Maximum will be used instead.", val, maxTimeoutSeconds)
timeout = strconv.Itoa(maxTimeoutSeconds)
}
testModel.TestSpecification = &testing.TestSpecification{
TestTimeout: fmt.Sprintf("%ss", timeout),
}
testModel.TestSpecification.IosXcTest = &testing.IosXcTest{}
jsonByte, err := json.Marshal(testModel)
if err != nil {
failf("Failed to marshal test model, error: %s", err)
}
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonByte))
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 {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
failf("Failed to read response body, error: %s", err)
}
failf("Failed to start test: %d, error: %s", resp.StatusCode, string(body))
}
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 resp.StatusCode != http.StatusOK || err != nil {
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{}
if err := json.Unmarshal(body, responseModel); 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\tOS version\tOrientation\tLocale\tOutcome\t"); err != nil {
failf("Failed to write in writer")
}
for _, step := range responseModel.Steps {
dimensions := map[string]string{}
for _, dimension := range step.DimensionValue {
dimensions[dimension.Key] = dimension.Value
}
outcome := step.Outcome.Summary
switch outcome {
case "success":
outcome = colorstring.Green(outcome)
case "failure":
successful = false
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":
successful = false
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":
successful = false
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)
}
if _, err := fmt.Fprintln(w, fmt.Sprintf("%s\t%s\t%s\t%s\t%s\t", dimensions["Model"], dimensions["Version"], dimensions["Orientation"], dimensions["Locale"], outcome)); err != nil {
failf("Failed to write in writer")
}
}
if err := w.Flush(); err != nil {
log.Errorf("Failed to flush writer, error: %s", err)
}
}
if !finished {
time.Sleep(5 * time.Second)
}
}
}
if configs.DownloadTestResults == "true" {
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{}
if err := json.Unmarshal(body, &responseModel); 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 {
if err := downloadFile(fileURL, filepath.Join(tempDir, fileName)); 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)
}
}
}
fmt.Println()
log.Infof("Exporting test run result")
if err := tools.ExportEnvironmentWithEnvman("VDTESTING_IS_TEST_RUN_SUCCESSFUL", strconv.FormatBool(successful)); err != nil {
log.Warnf("Failed to export environment (VDTESTING_IS_TEST_RUN_SUCCESSFUL), error: %s", err)
} else {
log.Printf("The test run result is exported to the VDTESTING_IS_TEST_RUN_SUCCESSFUL environment variable.")
}
log.Donef("=> Test run result exported")
if !successful {
os.Exit(1)
}
}
func downloadFile(url string, localPath string) error {
// on HFS file system the max file name length: 255 UTF-16 encoding units
base := filepath.Base(localPath)
if len(base) > 255 {
log.Warnf("too long filename: %s", base)
base = base[len(base)-255:]
log.Warnf("trimming to: %s", base)
localPath = filepath.Join(filepath.Dir(localPath), base)
}
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)
}
if _, err := io.Copy(out, resp.Body); 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
}