Class: UIAutoMonkey::MonkeyRunner

Inherits:
Object
  • Object
show all
Includes:
CommandHelper
Defined in:
lib/smart_monkey/monkey_runner.rb

Constant Summary collapse

TRACE_TEMPLATE =
'/Applications/Xcode.app/Contents/Applications/Instruments.app/Contents/PlugIns/AutomationInstrument.xrplugin/Contents/Resources/Automation.tracetemplate'
RESULT_BASE_PATH =
File.expand_path('smart_monkey_result')
INSTRUMENTS_TRACE_PATH =
File.expand_path('*.trace')
TIME_STAP =
Time.new.strftime("%Y%m%d%H%M%S")

Instance Method Summary collapse

Methods included from CommandHelper

#kill_all, #relaunch_app, #run_process, #shell

Instance Method Details

#all_tests_ok?(result_list) ⇒ Boolean

Returns:

  • (Boolean)


155
156
157
# File 'lib/smart_monkey/monkey_runner.rb', line 155

def all_tests_ok?(result_list)
  result_list.select {|r| !r[:ok]}.empty?
end

#app_nameObject



204
205
206
# File 'lib/smart_monkey/monkey_runner.rb', line 204

def app_name
  File.basename(app_path).gsub(/\.app$/, '')
end

#app_pathObject



200
201
202
# File 'lib/smart_monkey/monkey_runner.rb', line 200

def app_path
  @app_path ||= find_app_path(@options)
end

#compress_image(path) ⇒ Object



267
268
269
270
271
272
# File 'lib/smart_monkey/monkey_runner.rb', line 267

def compress_image(path)
  puts 'Compress screenshot images...'
  compress_rate = @options[:compress_rate]
  # `find #{path} -name "*.png" -exec convert {} -resize 50% -sample 50% {} \\\;`
  `mogrify -resize #{compress_rate} "#{path}/*.png"`
end

#config_custom_pathObject



437
438
439
# File 'lib/smart_monkey/monkey_runner.rb', line 437

def config_custom_path
  @options[:custom_path] || ui_custom_original_path
end

#console_log_pathObject



403
404
405
# File 'lib/smart_monkey/monkey_runner.rb', line 403

def console_log_path
  "#{result_dir}/console.txt"
end

#copy_html_resourcesObject



148
149
150
151
152
153
# File 'lib/smart_monkey/monkey_runner.rb', line 148

def copy_html_resources
  bootstrap_dir = File.expand_path('../../bootstrap', __FILE__)
  FileUtils.copy("#{bootstrap_dir}/css/bootstrap.css", result_base_dir)
  FileUtils.copy("#{bootstrap_dir}/js/bootstrap.js", result_base_dir)
  FileUtils.copy(template_path('jquery.min.js'), result_base_dir)
end

#crash_report_list(times) ⇒ Object



383
384
385
386
387
# File 'lib/smart_monkey/monkey_runner.rb', line 383

def crash_report_list(times)
  # ios version >7.0  => *.ips
  `ls -t #{crash_save_dir(times)}/*.crash 2>&1;ls -t #{crash_save_dir(times)}/*.ips 2>&1;`.strip.split(/\n/)
  # `ls -t #{crash_save_dir}/#{app_name}_*.crash`.strip.split(/\n/)
end

#crash_save_dir(times) ⇒ Object



359
360
361
# File 'lib/smart_monkey/monkey_runner.rb', line 359

def crash_save_dir(times)
  "#{result_base_dir}/crash_#{times}"
end

#create_index_html(result_hash) ⇒ Object



137
138
139
140
141
142
143
144
145
146
# File 'lib/smart_monkey/monkey_runner.rb', line 137

def create_index_html(result_hash)
  er = Erubis::Eruby.new(File.read(template_path('index.html.erb')))
  result_hash[:test_count] = result_hash[:result_list].size
  result_hash[:ok_count] = result_hash[:result_list].select {|r| r[:ok]}.size
  result_hash[:cr_count] = result_hash[:result_list].select {|r| r[:crash]}.size
  result_hash[:nr_count] = result_hash[:test_count] - result_hash[:ok_count] - result_hash[:cr_count]
  open("#{result_base_dir}/index.html", 'w') {|f| f.write er.result(result_hash)}
  copy_html_resources
  puts "Monkey Test Report:#{result_base_dir}/index.html"
end

#create_result_html(log_list) ⇒ Object



473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
# File 'lib/smart_monkey/monkey_runner.rb', line 473

def create_result_html(log_list)
  latest_list = LogDecoder.new(log_list).decode_latest(@options[:detail_event_count], @options[:drop_useless_img], result_dir)
  hash = {}
  hash[:log_list] = latest_list.reverse
  hash[:log_list_json] = JSON.dump(hash[:log_list])
  crash_report = Dir.glob("#{result_dir}/*.crash")[0]
  hash[:crash_report] = crash_report ? File.basename(crash_report) : nil
  hash[:uia_trace] = @uia_trace
  hash[:crashed] = @crashed
  hash[:no_run] = @no_run

  er = Erubis::Eruby.new(File.read(template_path('result.html.erb')))
  open("#{result_dir}/result.html", 'w') do |f|
    f.write(er.result(hash))
  end
  FileUtils.copy(template_path('result_view.js'), "#{result_dir}/result_view.js")
end

#deviceObject



196
197
198
# File 'lib/smart_monkey/monkey_runner.rb', line 196

def device
  @options[:device] || (devices[0].strip.split("[")[1].delete "]")
end

#device_name(device) ⇒ Object



261
262
263
264
265
# File 'lib/smart_monkey/monkey_runner.rb', line 261

def device_name(device)
  if !is_simulator
    `ideviceinfo -u #{device} -k DeviceName`.strip
  end
end

#deviceconsole_original_pathObject



307
308
309
# File 'lib/smart_monkey/monkey_runner.rb', line 307

def deviceconsole_original_path
  File.expand_path('../../ios_device_log/deviceconsole', __FILE__)
end

#devicesObject



212
213
214
# File 'lib/smart_monkey/monkey_runner.rb', line 212

def devices
  `"instruments" -s devices`.strip.split(/\n/).drop(2)
end

#dsym_base_pathObject



335
336
337
# File 'lib/smart_monkey/monkey_runner.rb', line 335

def dsym_base_path
  @options[:dsym_file_path] || ""
end

#find_app_path(opts) ⇒ Object



280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
# File 'lib/smart_monkey/monkey_runner.rb', line 280

def find_app_path(opts)
  app_path = nil
  if opts[:app_path].include?('/')
    app_path = File.expand_path(opts[:app_path])
  elsif opts[:app_path] =~ /\.app$/
    apps = find_apps(opts[:app_path])
    app_path = apps[0]
    log "#{apps.size} apps are found, USE NEWEST APP: #{app_path}" if apps.size > 1
  else
    app_path = opts[:app_path]
    log "BundleID was found: #{app_path}"
  end
  
  unless app_path
    raise 'Invalid AppName'
  end
  app_path
end

#find_apps(app) ⇒ Object



208
209
210
# File 'lib/smart_monkey/monkey_runner.rb', line 208

def find_apps(app)
  `"ls" -dt #{ENV['HOME']}/Library/Developer/Xcode/DerivedData/*/Build/Products/*/#{app}`.strip.split(/\n/)
end

#finish_runningObject



124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/smart_monkey/monkey_runner.rb', line 124

def finish_running
  kill_all_need
  FileUtils.remove_dir(result_history_dir(@times), true)
  FileUtils.remove_dir(crash_save_dir(@times+1), true)
  FileUtils.move(result_dir, result_history_dir(@times))
  if @options[:compress_rate]
    compress_image(result_history_dir(@times))
  end
  rm_instruments_trace(INSTRUMENTS_TRACE_PATH)
  kill_all('iPhone Simulator')
  sleep 3
end

#generate_ui_auto_monkeyObject



419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
# File 'lib/smart_monkey/monkey_runner.rb', line 419

def generate_ui_auto_monkey
  # extend_javascript_flag, extend_javascript_path =  show_extend_javascript
  # orig = File.read(ui_custom_original_path)
  # config = JSON.parse(File.read(config_json_path))
  # replace_str = "    this.config = #{JSON.pretty_generate(config, :indent => ' '*6)}; \n"
  # js = replace_text(orig, replace_str, '__UIAutoMonkey Configuration Begin__', '__UIAutoMonkey Configuration End__')
  # if extend_javascript_flag
  #   js = File.read(extend_javascript_path) + "\n" + js
  # end
  envs_str="UniqueDeviceID=\"#{device}\";"
  File.open(File.join(result_base_dir,"Env.js"), 'w') {|f| f.write(envs_str)}
  FileUtils.copy(config_custom_path, result_base_dir)
  FileUtils.copy(ui_auto_monkey_original_path, result_base_dir)
  FileUtils.cp_r(ui_hole_handler_original_path, result_base_dir)
  FileUtils.cp_r(ui_tuneup_original_path, result_base_dir)
  # FileUtils.copy("#{bootstrap_dir}/js/bootstrap.js", result_base_dir)
end

#grep_ios_syslogObject



393
394
395
396
397
398
399
400
401
# File 'lib/smart_monkey/monkey_runner.rb', line 393

def grep_ios_syslog
  if is_simulator
    puts "Attempting iOS Simulator system log capture via tail system.log."
    "tail -n 0 -f ~/Library/Logs/CoreSimulator/#{device}*/system.log"
  else
    puts "Attempting iOS device system log capture via deviceconsole."
    "#{deviceconsole_original_path} -u #{device}"
  end
end

#instruments_deviceinfo(device) ⇒ Object



216
217
218
# File 'lib/smart_monkey/monkey_runner.rb', line 216

def instruments_deviceinfo(device)
  `"instruments" -s devices | grep #{device}`.strip
end

#is_simulatorObject



220
221
222
223
224
225
226
227
# File 'lib/smart_monkey/monkey_runner.rb', line 220

def is_simulator
  deviceinfo = instruments_deviceinfo(device)
  if deviceinfo.include? "Simulator"
    true
  else
    false
  end
end

#kill_all_needObject



274
275
276
277
278
# File 'lib/smart_monkey/monkey_runner.rb', line 274

def kill_all_need
  kill_all('instruments', '9')
  kill_all('Instruments', '9')
  kill_all('idevicedebug', '9')
end

#list_appObject



170
171
172
173
174
175
176
177
# File 'lib/smart_monkey/monkey_runner.rb', line 170

def list_app
  puts "============For iPhone Simulator:"
  puts find_apps('*.app').map{|n| File.basename n}.uniq.sort.join("\n")
  puts "============For iPhone Device:"
  if device
    puts `ideviceinstaller -u #{device} -l`
  end
end

#list_devicesObject



179
180
181
# File 'lib/smart_monkey/monkey_runner.rb', line 179

def list_devices
  puts devices.join("\n")
end

#log(msg) ⇒ Object



183
184
185
# File 'lib/smart_monkey/monkey_runner.rb', line 183

def log(msg)
  puts msg
end

#parse_resultsObject



457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
# File 'lib/smart_monkey/monkey_runner.rb', line 457

def parse_results
  filename = "#{result_dir}/Automation Results.plist"
  log_list = []
  if File.exists?(filename)
    doc = REXML::Document.new(open(filename))
    doc.elements.each('plist/dict/array/dict') do |record|
      ary = record.elements.to_a.map{|a| a.text}
      log_list << Hash[*ary]
    end
    parse_uiautomation_plist
    @uia_trace = true
  end
  @no_run = true if log_list.empty? || log_list[-1][MESSAGE] =~ /target application is not frontmost/
  log_list
end

#parse_uiautomation_plistObject



415
416
417
# File 'lib/smart_monkey/monkey_runner.rb', line 415

def parse_uiautomation_plist
  `xsltproc --output "#{result_dir}/uiautomation.html" #{uiautomation_xsl_path} "#{result_dir}/Automation Results.plist"`
end

#product_type(device) ⇒ Object



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
# File 'lib/smart_monkey/monkey_runner.rb', line 229

def product_type(device)
  product_hash={
      "iPhone7,2"=>"iPhone 6",
      "iPhone7,1"=>"iPhone 6 Plus",
      "iPhone6,2"=>"iPhone 5S (CDMA)",
      "iPhone6,1"=>"iPhone 5S (GSM)",
      "iPhone5,4"=>"iPhone 5C (CDMA)",
      "iPhone5,3"=>"iPhone 5C (GSM)",
      "iPhone5,2"=>"iPhone 5",
      "iPhone5,1"=>"iPhone 5",
      "iPhone4,1"=>"iPhone 4S",
      "iPhone3,2"=>"iPhone 4 - CDMA",
      "iPhone3,1"=>"iPhone 4 - GSM",
      "iPhone2,1"=>"iPhone 3GS",
      "iPhone1,2"=>"iPhone 3G",
      "iPhone1,1"=>"iPhone",
    }

  if is_simulator
    instruments_deviceinfo(device).split("[")[0]
  else
    type = `ideviceinfo -u #{device} -k ProductType`.strip
    product_hash[type]
  end
end

#product_version(device) ⇒ Object



255
256
257
258
259
# File 'lib/smart_monkey/monkey_runner.rb', line 255

def product_version(device)
  if !is_simulator
    `ideviceinfo -u #{device} -k ProductVersion`.strip
  end
end

#pull_crash_files(times) ⇒ Object



375
376
377
378
379
380
381
# File 'lib/smart_monkey/monkey_runner.rb', line 375

def pull_crash_files(times)
  if !is_simulator
    `idevicecrashreport -u #{device} -e -k #{crash_save_dir(times)}`
  else
    `cp #{sim_crash_report_dir}/* #{crash_save_dir(times)}`
  end
end

#replace_text(orig, replace_str, marker_begin_line, marker_end_line) ⇒ Object



441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
# File 'lib/smart_monkey/monkey_runner.rb', line 441

def replace_text(orig, replace_str, marker_begin_line, marker_end_line)
  results = []
  status = 1
  orig.each_line do |line|
    if status == 1 && line =~ /#{marker_begin_line}/
      status = 2
      results << line
      results << replace_str
    elsif status == 2 && line =~/#{marker_end_line}/
      status = 3
    end
    results << line unless status == 2
  end
  results.join('')
end

#reset_iphone_simulatorObject



187
188
189
190
# File 'lib/smart_monkey/monkey_runner.rb', line 187

def reset_iphone_simulator
  FileUtils.rm_rf("#{Dir.home}/Library/Application\ Support/iPhone\ Simulator/")
  puts 'reset iPhone Simulator successful'
end

#result_base_dirObject



355
356
357
# File 'lib/smart_monkey/monkey_runner.rb', line 355

def result_base_dir
  File.join(@options[:result_base_dir] || RESULT_BASE_PATH, "report_#{TIME_STAP}")
end

#result_dirObject



363
364
365
# File 'lib/smart_monkey/monkey_runner.rb', line 363

def result_dir
  "#{result_base_dir}/Run 1"
end

#result_history_dir(times) ⇒ Object



367
368
369
# File 'lib/smart_monkey/monkey_runner.rb', line 367

def result_history_dir(times)
  "#{result_base_dir}/result_#{sprintf('%03d', times)}"
end

#rm_instruments_trace(traces) ⇒ Object



389
390
391
# File 'lib/smart_monkey/monkey_runner.rb', line 389

def rm_instruments_trace(traces)
  `rm -rf #{traces}`
end

#run(opts) ⇒ Object



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
# File 'lib/smart_monkey/monkey_runner.rb', line 18

def run(opts)
  @options = opts
  if @options[:show_config]
    show_config
    return true
  elsif @options[:list_app]
    list_app
    return true
  elsif @options[:list_devices]
    list_devices
    return true
  elsif @options[:reset_iphone_simulator]
    reset_iphone_simulator
    return true
  end

  res_dir = @options[:result_base_dir] || RESULT_BASE_PATH
  puts "INSTRUMENTS_TRACE_PATH : #{INSTRUMENTS_TRACE_PATH}"
  puts "RESULT_BASE_PATH : #{res_dir}"

  ###########
  log @options.inspect
  FileUtils.remove_dir(result_base_dir, true)
  FileUtils.makedirs(result_base_dir)
  generate_ui_auto_monkey
  ###########
  start_time = Time.new.strftime("%Y-%m-%d %H:%M:%S")
  result_list = []
  total_test_count.times do |times|
    @times = times
    setup_running
    result = run_a_case
    finish_running
    result_list << result
  end
  create_index_html({
      :start_time => start_time,
      :end_time => Time.new.strftime("%Y-%m-%d %H:%M:%S"),
      :result_list => result_list,
      :ProductType => product_type(device),
      :ProductVersion => product_version(device),
      :UniqueDeviceID => device,
      :DeviceName => device_name(device),
      :Application => app_path
  })
  all_tests_ok?(result_list)
end

#run_a_caseObject



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
# File 'lib/smart_monkey/monkey_runner.rb', line 76

def run_a_case
  log "=================================== Start Test (#{@times+1}/#{total_test_count}) ======================================="
  FileUtils.makedirs(crash_save_dir(@times+1)) unless File.exists?(crash_save_dir(@times+1))
  pull_crash_files(@times+1)
  cr_list = crash_report_list(@times+1)
  start_time = Time.now
  watch_syslog do
    begin
      unless time_limit_sec.nil?
        run_process(%W(instruments -w #{device} -l #{time_limit} -t #{TRACE_TEMPLATE} #{app_path} -e UIASCRIPT #{ui_custom_path} -e UIARESULTSPATH #{result_base_dir}))
      else
        run_process(%W(instruments -w #{device} -t #{TRACE_TEMPLATE} #{app_path} -e UIASCRIPT #{ui_custom_path} -e UIARESULTSPATH #{result_base_dir}))
      end
    rescue Timeout::Error
      kill_all('instruments', '9')
    end
  end

  pull_crash_files(@times+1)
  new_cr_list = crash_report_list(@times+1)
  # increase crash report?
  diff_cr_list = new_cr_list - cr_list
  
  if diff_cr_list.size > 0
    @crashed = true
    new_cr_name = File.basename(diff_cr_list[0]).gsub(/\.ips$/, '.crash')
    new_cr_path = File.join(result_dir, new_cr_name)
    log "Find new crash report: #{new_cr_path}"        
    if dsym_base_path != ''
      puts "Symbolicating crash report..."
      symbolicating_crash_report(diff_cr_list[0])
    end
    FileUtils.cp diff_cr_list[0], new_cr_path
  end
  # output result
  create_result_html(parse_results)

  {
    :start_time => start_time,
    :end_time => Time.now,
    :times => @times,
    :ok => !@crashed && !@no_run,
    :crash => @crashed,
    :result_dir => File.basename(result_history_dir(@times)),
    :message => nil
  }
end

#setup_runningObject



66
67
68
69
70
71
72
73
74
# File 'lib/smart_monkey/monkey_runner.rb', line 66

def setup_running
  kill_all_need
  # kill_all('iPhone Simulator')
  FileUtils.remove_dir(result_dir, true)
  ENV['UIARESULTSPATH'] = result_dir
  @crashed = false
  @no_run = false
  @uia_trace = false
end

#show_configObject



159
160
161
# File 'lib/smart_monkey/monkey_runner.rb', line 159

def show_config
  puts File.read(config_custom_path)
end

#show_extend_javascriptObject



163
164
165
166
167
168
# File 'lib/smart_monkey/monkey_runner.rb', line 163

def show_extend_javascript
  if @options[:extend_javascript_path]
    filename = @options[:extend_javascript_path]
    return File.exist?(filename), filename
  end
end

#sim_crash_report_dirObject



371
372
373
# File 'lib/smart_monkey/monkey_runner.rb', line 371

def sim_crash_report_dir
  "#{ENV['HOME']}/Library/Logs/DiagnosticReports"
end

#symbolicatecrash_base_pathObject



347
348
349
# File 'lib/smart_monkey/monkey_runner.rb', line 347

def symbolicatecrash_base_path()
  `find #{xcode_path} -name symbolicatecrash`.strip
end

#symbolicating_crash_report(crash_base_path) ⇒ Object



351
352
353
# File 'lib/smart_monkey/monkey_runner.rb', line 351

def symbolicating_crash_report(crash_base_path)
  `DEVELOPER_DIR=#{xcode_developer_path} #{symbolicatecrash_base_path} -o #{crash_base_path} #{crash_base_path} #{dsym_base_path};wait;`
end

#template_path(name) ⇒ Object



411
412
413
# File 'lib/smart_monkey/monkey_runner.rb', line 411

def template_path(name)
  File.expand_path("../templates/#{name}", __FILE__)
end

#time_limitObject



299
300
301
# File 'lib/smart_monkey/monkey_runner.rb', line 299

def time_limit
  time_limit_sec * 1000
end

#time_limit_secObject



303
304
305
# File 'lib/smart_monkey/monkey_runner.rb', line 303

def time_limit_sec
  @options[:time_limit_sec]
end

#total_test_countObject



192
193
194
# File 'lib/smart_monkey/monkey_runner.rb', line 192

def total_test_count
  (@options[:run_count] || 2)
end

#ui_auto_monkey_original_pathObject



311
312
313
# File 'lib/smart_monkey/monkey_runner.rb', line 311

def ui_auto_monkey_original_path
  File.expand_path('../../ui-auto-monkey/UIAutoMonkey.js', __FILE__)
end

#ui_auto_monkey_pathObject



327
328
329
# File 'lib/smart_monkey/monkey_runner.rb', line 327

def ui_auto_monkey_path
  "#{result_base_dir}/UIAutoMonkey.js"
end

#ui_custom_original_pathObject



315
316
317
# File 'lib/smart_monkey/monkey_runner.rb', line 315

def ui_custom_original_path
  File.expand_path('../../ui-auto-monkey/custom.js', __FILE__)
end

#ui_custom_pathObject



331
332
333
# File 'lib/smart_monkey/monkey_runner.rb', line 331

def ui_custom_path
  "#{result_base_dir}/custom.js"
end

#ui_hole_handler_original_pathObject



319
320
321
# File 'lib/smart_monkey/monkey_runner.rb', line 319

def ui_hole_handler_original_path
  File.expand_path('../../ui-auto-monkey/handler', __FILE__)
end

#ui_tuneup_original_pathObject



323
324
325
# File 'lib/smart_monkey/monkey_runner.rb', line 323

def ui_tuneup_original_path
  File.expand_path('../../ui-auto-monkey/tuneup', __FILE__)
end

#uiautomation_xsl_pathObject



407
408
409
# File 'lib/smart_monkey/monkey_runner.rb', line 407

def uiautomation_xsl_path
  File.expand_path("../templates/automation_result.xsl", __FILE__)
end

#watch_syslogObject



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
# File 'lib/smart_monkey/monkey_runner.rb', line 491

def watch_syslog
  STDOUT.sync = true
  stdin, stdout, stderr = Open3.popen3(grep_ios_syslog)
  log_filename = "#{result_base_dir}/console.txt"
  thread = Thread.new do
    File.open(log_filename, 'a') do |output|
      begin
        while true
          line = stdout.readline
          output.write(line) 
          # output.write(line) if line.include?(app_name)
        end
      rescue IOError
        log 'Stop iOS system log capture.'
        kill_all_need
      end
    end
  end
  yield
  sleep 3
  stdout.close; stderr.close; stdin.close
  thread.join
  FileUtils.makedirs(result_dir) unless File.exists?(result_dir)
  if File.exists?(log_filename)
    FileUtils.move(log_filename, console_log_path)
  end
end

#xcode_developer_pathObject



339
340
341
# File 'lib/smart_monkey/monkey_runner.rb', line 339

def xcode_developer_path
  `xcode-select --print-path`.strip
end

#xcode_pathObject



343
344
345
# File 'lib/smart_monkey/monkey_runner.rb', line 343

def xcode_path
  `dirname #{xcode_developer_path}`.strip
end