-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbrowserstack_maestro
More file actions
executable file
·234 lines (202 loc) · 7.68 KB
/
Copy pathbrowserstack_maestro
File metadata and controls
executable file
·234 lines (202 loc) · 7.68 KB
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
#!/usr/bin/env ruby
# frozen_string_literal: true
require "base64"
require "fileutils"
require "json"
require "net/http"
require "optparse"
require "securerandom"
require "uri"
require_relative "../lib/browserstack_device_resolver"
require_relative "../lib/e2e_matrix"
class BrowserStackMaestro
API_HOST = "api-cloud.browserstack.com"
TERMINAL_STATUSES = %w[passed failed error timedout stopped done].freeze
def initialize(options)
@options = options
@username = ENV.fetch("BROWSERSTACK_USERNAME")
@access_key = ENV.fetch("BROWSERSTACK_ACCESS_KEY")
end
def run
FileUtils.mkdir_p(output_dir)
run = E2EMatrix.load(matrix_path).run_at(run_index)
app_path = ENV.fetch(run.fetch("artifact_env"))
device = resolve_device(run)
app = upload_file("/app-automate/maestro/v2/app", app_path, custom_id(run, "app"))
suite = upload_file("/app-automate/maestro/v2/test-suite", suite_zip, custom_id(run, "suite"))
build = start_build(run, app.fetch("app_url"), suite.fetch("test_suite_url"), device.fetch("browserstack_device"))
build_status = poll_build(build.fetch("build_id"))
sessions = fetch_sessions(build_status)
result = normalize_result(run, device, app, suite, build, build_status, sessions)
write_json("result.json", result)
exit(result.fetch("passed") || !strict? ? 0 : 1)
end
private
def strict?
ENV.fetch("E2E_STRICT", "false") == "true"
end
def resolve_device(run)
override = ENV["E2E_DEVICE_OVERRIDE"] || ENV["E2E_#{run.fetch("platform").upcase}_DEVICE_OVERRIDE"]
if override && !override.empty?
return {
"device_selector" => run.fetch("device_selector"),
"browserstack_device" => override,
"resolved_device" => override.split("-").first,
"resolved_os_version" => override.split("-").last
}
end
devices = get_json("/app-automate/devices.json")
limits = get_json("/app-automate/device_tier_limits.json")
BrowserStackDeviceResolver.new(devices, limits).resolve(run.fetch("device_selector"))
end
def upload_file(path, file_path, custom_id)
response = multipart_post(path, file_path, custom_id)
write_json("#{custom_id}.json", response)
response
end
def start_build(run, app_url, test_suite_url, device)
body = {
app: app_url,
testSuite: test_suite_url,
project: ENV.fetch("E2E_BROWSERSTACK_PROJECT", "checkout-kit-e2e"),
buildTag: ENV.fetch("BITRISE_GIT_COMMIT", "local"),
customBuildName: run.fetch("id"),
devices: [device],
execute: [run.fetch("execute")],
setEnvVariables: {
E2E_APP_ID: run.fetch("app_id"),
E2E_READY_MARKER: run.fetch("ready_marker")
}
}
response = post_json("/app-automate/maestro/v2/#{run.fetch("platform")}/build", body)
write_json("build-start.json", response)
response
end
def poll_build(build_id)
deadline = Time.now + ENV.fetch("E2E_BROWSERSTACK_TIMEOUT_SECONDS", "1800").to_i
loop do
response = get_json("/app-automate/maestro/v2/builds/#{build_id}")
write_json("build-status.json", response)
return response if TERMINAL_STATUSES.include?(response.fetch("status").to_s.downcase)
if Time.now >= deadline
stop_build(build_id)
raise "BrowserStack build timed out: #{build_id}"
end
sleep ENV.fetch("E2E_BROWSERSTACK_POLL_SECONDS", "30").to_i
end
end
def stop_build(build_id)
post_json("/app-automate/maestro/builds/#{build_id}/stop", {})
rescue StandardError => error
warn "Unable to stop BrowserStack build #{build_id}: #{error.message}"
end
def fetch_sessions(build_status)
build_id = build_status.fetch("id")
build_status.fetch("devices", []).flat_map do |device|
device.fetch("sessions", []).map do |session|
get_json("/app-automate/maestro/v2/builds/#{build_id}/sessions/#{session.fetch("id")}")
end
end
end
def normalize_result(run, device, app, suite, build, build_status, sessions)
status = build_status.fetch("status").to_s.downcase
failed_tests = sessions.flat_map do |session|
session.dig("testcases", "data").to_a.flat_map do |group|
group.fetch("testcases", []).select { |testcase| testcase.fetch("status", "") != "passed" }
end
end
{
"id" => run.fetch("id"),
"status_context" => run.fetch("status_context"),
"platform" => run.fetch("platform"),
"target" => run.fetch("target"),
"os_track" => run.fetch("os_track"),
"execute" => run.fetch("execute"),
"device_selector" => device.fetch("device_selector"),
"resolved_device" => device.fetch("browserstack_device"),
"app_url" => app.fetch("app_url"),
"test_suite_url" => suite.fetch("test_suite_url"),
"build_id" => build.fetch("build_id"),
"status" => status,
"passed" => status == "passed" && failed_tests.empty?,
"failed_tests" => failed_tests
}
end
def multipart_post(path, file_path, custom_id)
boundary = "----checkout-kit-#{SecureRandom.hex(12)}"
file = File.binread(file_path)
body = +""
body << "--#{boundary}\r\n"
body << "Content-Disposition: form-data; name=\"file\"; filename=\"#{File.basename(file_path)}\"\r\n\r\n"
body << file
body << "\r\n--#{boundary}\r\n"
body << "Content-Disposition: form-data; name=\"custom_id\"\r\n\r\n"
body << custom_id
body << "\r\n--#{boundary}--\r\n"
request = Net::HTTP::Post.new(path)
request["Content-Type"] = "multipart/form-data; boundary=#{boundary}"
request.body = body
execute_request(request)
end
def get_json(path)
execute_request(Net::HTTP::Get.new(path))
end
def post_json(path, body)
request = Net::HTTP::Post.new(path)
request["Content-Type"] = "application/json"
request.body = JSON.generate(body)
execute_request(request)
end
def execute_request(request)
attempts = 0
retries = ENV.fetch("E2E_BROWSERSTACK_API_RETRIES", "1").to_i
loop do
attempts += 1
request.basic_auth(@username, @access_key)
response = Net::HTTP.start(API_HOST, 443, use_ssl: true) { |http| http.request(request) }
parsed = parse_response_body(response)
return parsed if response.is_a?(Net::HTTPSuccess)
raise "BrowserStack request failed #{response.code}: #{parsed}" unless retryable_browserstack_response?(response) && attempts <= retries
sleep attempts
end
end
def parse_response_body(response)
JSON.parse(response.body)
rescue JSON::ParserError
raise "BrowserStack request returned non-JSON response"
end
def retryable_browserstack_response?(response)
response.code.to_i == 429 || response.code.to_i >= 500
end
def custom_id(run, suffix)
["checkout-kit", run.fetch("id"), ENV.fetch("BITRISE_GIT_COMMIT", "local"), suffix].join("-").gsub(/[^A-Za-z0-9._-]/, "-")[0, 100]
end
def write_json(name, object)
File.write(File.join(output_dir, name), JSON.pretty_generate(object))
end
def output_dir
@options.fetch(:output_dir)
end
def matrix_path
@options.fetch(:matrix_path)
end
def run_index
@options.fetch(:run_index)
end
def suite_zip
@options.fetch(:suite_zip)
end
end
options = {
matrix_path: "e2e/config/matrix.yml",
run_index: Integer(ENV.fetch("BITRISE_IO_PARALLEL_INDEX", "0")),
suite_zip: ENV.fetch("E2E_MAESTRO_SUITE_ZIP"),
output_dir: ENV.fetch("E2E_BROWSERSTACK_RESULTS_DIR", File.join(Dir.pwd, "e2e-results"))
}
OptionParser.new do |opts|
opts.on("--matrix PATH") { |path| options[:matrix_path] = path }
opts.on("--index INDEX", Integer) { |index| options[:run_index] = index }
opts.on("--suite-zip PATH") { |path| options[:suite_zip] = path }
opts.on("--output-dir PATH") { |path| options[:output_dir] = path }
end.parse!
BrowserStackMaestro.new(options).run