Class: Fastlane::Actions::AndroidTestlabScriptSwitAction

Inherits:
Action
  • Object
show all
Defined in:
lib/fastlane/plugin/android_testlab_script_swit/actions/android_testlab_script_swit_action.rb

Class Method Summary collapse

Class Method Details

.authorsObject

Authors



132
133
134
# File 'lib/fastlane/plugin/android_testlab_script_swit/actions/android_testlab_script_swit_action.rb', line 132

def self.authors
  ["나비이쁜이"]
end

.available_optionsObject

Option val



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
# File 'lib/fastlane/plugin/android_testlab_script_swit/actions/android_testlab_script_swit_action.rb', line 148

def self.available_options
  [
      # project_id (true)
      FastlaneCore::ConfigItem.new(key: :project_id,
                                   env_name: "PROJECT_ID",
                                   description: "Your Firebase project id",
                                   is_string: true,
                                   optional: false),

      # gcloud_key_file (true)
      FastlaneCore::ConfigItem.new(key: :gcloud_key_file,
                                   env_name: "GCLOUD_KEY_FILE",
                                   description: "File path containing the gcloud auth key. Default: Created from GCLOUD_SERVICE_KEY environment variable",
                                   is_string: true,
                                   optional: false),

      # test type (true)
      FastlaneCore::ConfigItem.new(key: :type,
                                   env_name: "TYPE",
                                   description: "Test type. Default: robo (robo/instrumentation)",
                                   is_string: true,
                                   optional: true,
                                   default_value: "robo",
                                   verify_block: proc do |value|
                                     if value != "robo" && value != "instrumentation"
                                       UI.user_error!("Unknown test type.")
                                     end
                                   end),

      # device (true)
      FastlaneCore::ConfigItem.new(key: :devices,
                                   description: "Devices to test the app on",
                                   type: Array,
                                   default_value: [{
                                                      model: "Nexus6",
                                                      version: "21",
                                                      locale: "en_US",
                                                      orientation: "portrait"
                                                   }],
                                   verify_block: proc do |value|
                                     if value.empty?
                                       UI.user_error!("Devices cannot be empty")
                                     end
                                     value.each do |current|
                                       if current.class != Hash
                                         UI.user_error!("Each device must be represented by a Hash object, " \
                                           "#{current.class} found")
                                       end
                                       check_has_property(current, :model)
                                       check_has_property(current, :version)
                                       set_default_property(current, :locale, "en_US")
                                       set_default_property(current, :orientation, "portrait")
                                      end
                                   end),

      # timeout (ture)
      FastlaneCore::ConfigItem.new(key: :timeout,
                                   env_name: "TIMEOUT",
                                   description: "The max time this test execution can run before it is cancelled. Default: 5m (this value must be greater than or equal to 1m)",
                                   type: String,
                                   optional: false,
                                   default_value: "3m"),

      # apk (true)
      FastlaneCore::ConfigItem.new(key: :app_apk,
                                   env_name: "APP_APK",
                                   description: "The path for your android app apk",
                                   type: String,
                                   optional: false),

      # swit_webhook url (false)
      FastlaneCore::ConfigItem.new(key: :swit_webhook_url,
                                   env_name: "SWIT_WEBHOOK_URL",
                                   description: "The Swit WebHOOK URL",
                                   type: String,
                                   optional: true),

      # swit_webhook payload (false)
      FastlaneCore::ConfigItem.new(key: :swit_webhook_payload,
                                   env_name: "SWIT_WEBHOOK_PAYLOAD",
                                   description: "The Swit WebHOOK PAYLOAD",
                                   type: String,
                                   optional: true),

      # test apk (false)
      FastlaneCore::ConfigItem.new(key: :app_test_apk,
                                   env_name: "APP_TEST_APK",
                                   description: "The path for your android test apk. Default: empty string",
                                   type: String,
                                   optional: true,
                                   default_value: nil),

      # orchestrator (false)
      FastlaneCore::ConfigItem.new(key: :use_orchestrator,
                                   env_name: "USE_ORCHESTRATOR",
                                   description: "If you use orchestrator when set instrumentation test. Default: false",
                                   type: Boolean,
                                   optional: true,
                                   default_value: false),

      # gcloud_components_channel (false)
      FastlaneCore::ConfigItem.new(key: :gcloud_components_channel,
                                   env_name: "gcloud_components_channel",
                                   description: "If you use beta or alpha components. Default stable (alpha/beta)",
                                   is_string: true,
                                   optional: true,
                                   default_value: "stable"),

      # console_log_file_name (false)
      FastlaneCore::ConfigItem.new(key: :console_log_file_name,
                                   env_name: "CONSOLE_LOG_FILE_NAME",
                                   description: "The filename to save the output results. Default: ./console_output.log",
                                   type: String,
                                   optional: true,
                                   default_value: "./console_output.log"),

      # extra_options (false)
      FastlaneCore::ConfigItem.new(key: :extra_options,
                                   env_name: "EXTRA_OPTIONS",
                                   description: "Extra options that you need to pass to the gcloud command. Default: empty string",
                                   type: String,
                                   optional: true,
                                   default_value: ""),

      # firebase_test_lab_results_bucket (false)
      FastlaneCore::ConfigItem.new(key: :firebase_test_lab_results_bucket,
                                   env_name: "FIREBASE_TEST_LAB_RESULTS_BUCKET",
                                   description: "Name of Firebase Test Lab results bucket",
                                   type: String,
                                   optional: true,
                                   default_value: nil),

      # firebase_test_lab_results_dir (false)
      FastlaneCore::ConfigItem.new(key: :firebase_test_lab_results_dir,
                                   env_name: "FIREBASE_TEST_LAB_RESULTS_DIR",
                                   description: "Name of Firebase Test Lab results directory",
                                   type: String,
                                   optional: true,
                                   default_value: nil),

      # download_dir (false)
      FastlaneCore::ConfigItem.new(key: :download_dir,
                                   env_name: "DOWNLOAD_DIR",
                                   description: "Target directory to download screenshots from firebase",
                                   type: String,
                                   optional: true,
                                   default_value: nil),

      # robo_script_path (false)
      FastlaneCore::ConfigItem.new(key: :robo_script_path,
                                   env_name: "ROBO_SCRIPT_PATH",
                                   description: "Path to Robo script JSON file",
                                   is_string: true,
                                   optional: true,
                                   verify_block: proc do |value|
                                   UI.user_error!("Couldn't find JSON file at path '#{value}'") unless File.exist?(value) end)
]
end

.check_has_property(hash_obj, property) ⇒ Object



307
308
309
# File 'lib/fastlane/plugin/android_testlab_script_swit/actions/android_testlab_script_swit_action.rb', line 307

def self.check_has_property(hash_obj, property)
  UI.user_error!("Each device must have #{property} property") unless hash_obj.key?(property)
end

.descriptionObject

Short Detils



127
128
129
# File 'lib/fastlane/plugin/android_testlab_script_swit/actions/android_testlab_script_swit_action.rb', line 127

def self.description
  "Android Firebase TestLab with Robo Script Test"
end

.detailsObject

Long Detils



143
144
145
# File 'lib/fastlane/plugin/android_testlab_script_swit/actions/android_testlab_script_swit_action.rb', line 143

def self.details
  "This plug-in uses Firebase TestLab. You can also include RoboScript files."
end

.example_codeObject



327
328
329
# File 'lib/fastlane/plugin/android_testlab_script_swit/actions/android_testlab_script_swit_action.rb', line 327

def self.example_code

end

.is_supported?(platform) ⇒ Boolean

android platform

Returns:

  • (Boolean)


318
319
320
# File 'lib/fastlane/plugin/android_testlab_script_swit/actions/android_testlab_script_swit_action.rb', line 318

def self.is_supported?(platform)
  platform == :android
end

.measure_timeObject



11
12
13
14
15
16
17
18
19
# File 'lib/fastlane/plugin/android_testlab_script_swit/actions/android_testlab_script_swit_action.rb', line 11

def self.measure_time
    start_time = Time.now
    yield
    end_time = Time.now
    duration_sec_total = (end_time - start_time).round(1)
    duration_min = (duration_sec_total / 60).round(1)
    duration_sec = duration_sec_total % 60
    return "총 #{duration_min}분 테스트"
end

.outputObject



323
324
325
# File 'lib/fastlane/plugin/android_testlab_script_swit/actions/android_testlab_script_swit_action.rb', line 323

def self.output
  [['console_output.log', 'A console log when running Firebase Test Lab with gcloud']]
end

.return_valueObject



136
137
138
139
140
# File 'lib/fastlane/plugin/android_testlab_script_swit/actions/android_testlab_script_swit_action.rb', line 136

def self.return_value
  ["Authenticates with Google Cloud.",
   "Runs tests in Firebase Test Lab.",
   "Fetches the results to a local directory."].join("\n")
end

.run(params) ⇒ Object

actions run



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
# File 'lib/fastlane/plugin/android_testlab_script_swit/actions/android_testlab_script_swit_action.rb', line 22

def self.run(params)
  UI.message("********************************")
  UI.message("Start Action")
  UI.message("********************************")
  
  # TestLab 작업 및 작업 소요시간 측정
  duration = measure_time do
      
      # Result Bucket & Dir
      results_bucket = params[:firebase_test_lab_results_bucket] || "#{params[:project_id]}_test_results"
      results_dir = params[:firebase_test_lab_results_dir] || "firebase_test_result_#{DateTime.now.strftime('%Y-%m-%d-%H:%M:%S')}"

      # Set Target Project ID
      Helper.config(params[:project_id])

      # Activate service account
      Helper.authenticate(params[:gcloud_key_file])

      # RoboScriptOption
      robo_script_option = params[:robo_script_path].nil? ? "" : "--robo-script #{params[:robo_script_path]} "
      
      # Run Firebase Test Lab
      Helper.run_tests(params[:gcloud_components_channel], "--type #{params[:type]} "\
                "--app #{params[:app_apk]} "\
                "#{"--test #{params[:app_test_apk]} " unless params[:app_test_apk].nil?}"\
                "#{"--use-orchestrator " if params[:type] == "instrumentation" && params[:use_orchestrator]}"\
                "#{params[:devices].map { |d| "--device model=#{d[:model]},version=#{d[:version]},locale=#{d[:locale]},orientation=#{d[:orientation]} " }.join}"\
                "--timeout #{params[:timeout]} "\
                "--results-bucket #{results_bucket} "\
                "--results-dir #{results_dir} "\
                "#{params[:extra_options]} "\
                "#{robo_script_option}"\
                "--format=json 1>#{Helper.if_need_dir(params[:console_log_file_name])}"
      )
      
      # Fetch results
      download_dir = params[:download_dir]
      if download_dir
        UI.message("Fetch results from Firebase Test Lab results bucket")
        json.each do |status|
          axis = status["axis_value"]
          Helper.if_need_dir("#{download_dir}/#{axis}")
          Helper.copy_from_gcs("#{results_bucket}/#{results_dir}/#{axis}", download_dir)
          Helper.set_public("#{results_bucket}/#{results_dir}/#{axis}")
        end
      end
      
  end
  
  # Swit Result PayLoad
  swit_device_payload = ""

  # Swit Send PayLoad - 테스트 시간 추가
  swit_webhook_payload = params[:swit_webhook_payload][0..-5] + ','
  swit_device_payload += "{\"type\":\"rt_section\",\"indent\":1,\"elements\":[{\"type\":\"rt_text\",\"content\":\"테스트 시간 : \"},{\"type\":\"rt_text\",\"content\":\"#{duration}\",\"styles\":{\"bold\":true}}]},"

  # Firebase Test Lab Result Json
  resultJson = File.read(params[:console_log_file_name])

  swit_device_payload = resultJson.map.with_index do |item, device_index|
    axis_value_parts = item["axis_value"].split('-')
    outcome = item["outcome"]

    model         = axis_value_parts[0]
    version       = axis_value_parts[1]
    locale        = axis_value_parts[2]
    orientation   = axis_value_parts[3]
        
    # 디바이스 정보
    device_payload =
        "[{\"type\":\"rt_section\",\"indent\":1,\"elements\":[{\"type\":\"rt_text\",\"content\":\"#{model}\"}]}, " +
        "{\"type\":\"rt_section\",\"indent\":2,\"elements\":[{\"type\":\"rt_text\", \"content\": \"OS: #{version} / Locale: #{locale} / Orientation: #{orientation}\"}]}, "
        
    # 성공 여부
    if outcome == 'Passed'
      device_payload +=
        "{\"type\":\"rt_section\",\"elements\":[{\"type\":\"rt_text\",\"content\":\"결과 : \"},{\"type\":\"rt_emoji\",\"name\":\":tada:\"},{\"type\":\"rt_text\",\"content\":\" Passed \"},{\"type\":\"rt_emoji\",\"name\":\":tada:\"}]}"
    elsif outcome == 'Failed'
      device_payload +=
        "{\"type\":\"rt_section\",\"elements\":[{\"type\":\"rt_text\",\"content\":\"결과 : \"},{\"type\":\"rt_emoji\",\"name\":\":interrobang:\"},{\"type\":\"rt_text\",\"content\":\" Failed \"},{\"type\":\"rt_emoji\",\"name\": \":interrobang:\"}]}"
    else # Skip or other outcomes
      device_payload +=
        "{\"type\":\"rt_section\",\"elements\":[{\"type\":{\"name\": \":bulb:\"}},{\"text\":{\"content\": \" Skipped or other outcomes \"}}, {\"emoji\":{\"name\": \":bulb:\"}}]}"
    end

    device_payload += "]"
    
  end.join(',')

  swit_device_payload.chomp!(',')

  # Swit PayLoad 병합
  swit_webhook_payload += swit_device_payload + ']}]}'
  
  UI.message(swit_webhook_payload)
   
  # Swit WebHook
  HTTParty.post(params[:swit_webhook_url], body: { body_text: swit_webhook_payload }.to_json, headers: { 'Content-Type' => 'application/json' })

  UI.message("********************************")
  UI.message("Finish Action")
  UI.message("********************************")
end

.set_default_property(hash_obj, property, default) ⇒ Object



311
312
313
314
315
# File 'lib/fastlane/plugin/android_testlab_script_swit/actions/android_testlab_script_swit_action.rb', line 311

def self.set_default_property(hash_obj, property, default)
  unless hash_obj.key?(property)
    hash_obj[property] = default
  end
end