Class: Calabash::Android::Operations::Device

Inherits:
Object
  • Object
show all
Defined in:
lib/calabash-android/operations.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(cucumber_world, serial, server_port, app_path, test_server_path, test_server_port = 7102) ⇒ Device

Returns a new instance of Device.



195
196
197
198
199
200
201
202
203
204
205
206
207
# File 'lib/calabash-android/operations.rb', line 195

def initialize(cucumber_world, serial, server_port, app_path, test_server_path, test_server_port = 7102)

  @cucumber_world = cucumber_world
  @serial = serial
  @server_port = server_port
  @app_path = app_path
  @test_server_path = test_server_path
  @test_server_port = test_server_port

  forward_cmd = "#{adb_command} forward tcp:#{@server_port} tcp:#{@test_server_port}"
  log forward_cmd
  log `#{forward_cmd}`
end

Instance Attribute Details

#app_pathObject (readonly)

Returns the value of attribute app_path.



193
194
195
# File 'lib/calabash-android/operations.rb', line 193

def app_path
  @app_path
end

#serialObject (readonly)

Returns the value of attribute serial.



193
194
195
# File 'lib/calabash-android/operations.rb', line 193

def serial
  @serial
end

#server_portObject (readonly)

Returns the value of attribute server_port.



193
194
195
# File 'lib/calabash-android/operations.rb', line 193

def server_port
  @server_port
end

#test_server_pathObject (readonly)

Returns the value of attribute test_server_path.



193
194
195
# File 'lib/calabash-android/operations.rb', line 193

def test_server_path
  @test_server_path
end

#test_server_portObject (readonly)

Returns the value of attribute test_server_port.



193
194
195
# File 'lib/calabash-android/operations.rb', line 193

def test_server_port
  @test_server_port
end

Instance Method Details

#adbObject



327
328
329
330
331
332
333
# File 'lib/calabash-android/operations.rb', line 327

def adb
  if is_windows?
    %Q("#{ENV["ANDROID_HOME"]}\\platform-tools\\adb.exe")
  else
    %Q("#{ENV["ANDROID_HOME"]}/platform-tools/adb")
  end
end

#adb_commandObject



323
324
325
# File 'lib/calabash-android/operations.rb', line 323

def adb_command
  "#{adb} -s #{serial}"
end

#app_running?Boolean

Returns:

  • (Boolean)


239
240
241
# File 'lib/calabash-android/operations.rb', line 239

def app_running?
  `#{adb_command} shell ps`.include?(ENV["PROCESS_NAME"] || package_name(@app_path))
end

#clear_app_dataObject



364
365
366
367
# File 'lib/calabash-android/operations.rb', line 364

def clear_app_data
  cmd = "#{adb_command} shell am instrument #{package_name(@test_server_path)}/sh.calaba.instrumentationbackend.ClearAppData"
  raise "Could not clear data" unless system(cmd)
end

#connected_devicesObject



347
348
349
350
351
# File 'lib/calabash-android/operations.rb', line 347

def connected_devices
  lines = `#{adb} devices`.split("\n")
  lines.shift
  lines.collect { |l| l.split("\t").first}
end

#default_serialObject



339
340
341
342
343
344
345
# File 'lib/calabash-android/operations.rb', line 339

def default_serial
  devices = connected_devices
  log "connected_devices: #{devices}"
  raise "No connected devices" if devices.empty?
  raise "More than one device connected. Specify device serial using ADB_DEVICE_ARG" if devices.length > 1
  devices.first
end

#http(path, data = {}, options = {}) ⇒ Object



273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
# File 'lib/calabash-android/operations.rb', line 273

def http(path, data = {}, options = {})
  begin
    http = Net::HTTP.new "127.0.0.1", @server_port
    http.open_timeout = options[:open_timeout] if options[:open_timeout]
    http.read_timeout = options[:read_timeout] if options[:read_timeout]
    resp = http.post(path, "#{data.to_json}", {"Content-Type" => "application/json;charset=utf-8"})
    resp.body
  rescue Exception => e
    if app_running?
      raise e
    else
      raise "App no longer running"
    end
  end
end

#input_keyevent(keycode) ⇒ Object



487
488
489
490
# File 'lib/calabash-android/operations.rb', line 487

def input_keyevent(keycode)
  cmd = "#{adb_command} shell input keyevent #{keycode.to_s}"
  result = `#{cmd}`
end

#install_app(app_path) ⇒ Object



220
221
222
223
224
225
226
227
228
229
230
231
232
# File 'lib/calabash-android/operations.rb', line 220

def install_app(app_path)
  cmd = "#{adb_command} install \"#{app_path}\""
  log "Installing: #{app_path}"
  result = `#{cmd}`
  log result
  pn = package_name(app_path)
  succeeded = `#{adb_command} shell pm list packages`.include?("package:#{pn}")

  unless succeeded
    ::Cucumber.wants_to_quit = true
    raise "#{pn} did not get installed. Aborting!"
  end
end

#keyguard_enabled?Boolean

Returns:

  • (Boolean)


243
244
245
246
247
# File 'lib/calabash-android/operations.rb', line 243

def keyguard_enabled?
  dumpsys = `#{adb_command} shell dumpsys window windows`
  #If a line containing mCurrentFocus and Keyguard exists the keyguard is enabled
  dumpsys.lines.any? { |l| l.include?("mCurrentFocus") and l.include?("Keyguard")}
end

#perform_action(action, *arguments) ⇒ Object



249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
# File 'lib/calabash-android/operations.rb', line 249

def perform_action(action, *arguments)
  log "Action: #{action} - Params: #{arguments.join(', ')}"

  params = {"command" => action, "arguments" => arguments}

  Timeout.timeout(300) do
    begin
      result = http("/", params, {:read_timeout => 350})
    rescue Exception => e
      log "Error communicating with test server: #{e}"
      raise e
    end
    log "Result:'" + result.strip + "'"
    raise "Empty result from TestServer" if result.chomp.empty?
    result = JSON.parse(result)
    if not result["success"] then
      raise "Step unsuccessful: #{result["message"]}"
    end
    result
  end
rescue Timeout::Error
  raise Exception, "Step timed out"
end

#press_back_keyObject



492
493
494
# File 'lib/calabash-android/operations.rb', line 492

def press_back_key
  input_keyevent(4)
end

#pull(remote, local) ⇒ Object



369
370
371
372
# File 'lib/calabash-android/operations.rb', line 369

def pull(remote, local)
  cmd = "#{adb_command} pull #{remote} #{local}"
  raise "Could not pull #{remote} to #{local}" unless system(cmd)
end

#push(local, remote) ⇒ Object



374
375
376
377
# File 'lib/calabash-android/operations.rb', line 374

def push(local, remote)
  cmd = "#{adb_command} push #{local} #{remote}"
  raise "Could not push #{local} to #{remote}" unless system(cmd)
end

#reinstall_appsObject



209
210
211
212
213
# File 'lib/calabash-android/operations.rb', line 209

def reinstall_apps()
  uninstall_app(package_name(@app_path))
  install_app(@app_path)
  reinstall_test_server()
end

#reinstall_test_serverObject



215
216
217
218
# File 'lib/calabash-android/operations.rb', line 215

def reinstall_test_server()
  uninstall_app(package_name(@test_server_path))
  install_app(@test_server_path)
end

#screenshot(options = {:prefix => nil, :name => nil}) ⇒ Object



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
# File 'lib/calabash-android/operations.rb', line 289

def screenshot(options={:prefix => nil, :name => nil})
  prefix = options[:prefix] || ENV['SCREENSHOT_PATH'] || ""
  name = options[:name]

  if name.nil?
    name = "screenshot"
  else
    if File.extname(name).downcase == ".png"
      name = name.split(".png")[0]
    end
  end

  @@screenshot_count ||= 0
  path = "#{prefix}#{name}_#{@@screenshot_count}.png"

  if ENV["SCREENSHOT_VIA_USB"] == "false"
    begin
      res = http("/screenshot")
    rescue EOFError
      raise "Could not take screenshot. App is most likely not running anymore."
    end
    File.open(path, 'wb') do |f|
      f.write res
    end
  else
    screenshot_cmd = "java -jar #{File.join(File.dirname(__FILE__), 'lib', 'screenshotTaker.jar')} #{serial} #{path}"
    log screenshot_cmd
    raise "Could not take screenshot" unless system(screenshot_cmd)
  end

  @@screenshot_count += 1
  path
end

#set_gps_coordinates(latitude, longitude) ⇒ Object



483
484
485
# File 'lib/calabash-android/operations.rb', line 483

def set_gps_coordinates(latitude, longitude)
  perform_action('set_gps_coordinates', latitude, longitude)
end

#set_gps_coordinates_from_location(location) ⇒ Object

location

Raises:

  • (Exception)


474
475
476
477
478
479
480
481
# File 'lib/calabash-android/operations.rb', line 474

def set_gps_coordinates_from_location(location)
  require 'geocoder'
  results = Geocoder.search(location)
  raise Exception, "Got no results for #{location}" if results.empty?

  best_result = results.first
  set_gps_coordinates(best_result.latitude, best_result.longitude)
end

#shutdown_test_serverObject



460
461
462
463
464
465
466
467
468
469
470
471
# File 'lib/calabash-android/operations.rb', line 460

def shutdown_test_server
  begin
    http("/kill")
    Timeout::timeout(3) do
      sleep 0.3 while app_running?
    end
  rescue Timeout::Error
    log ("Could not kill app. Waited to 3 seconds.")
  rescue EOFError
    log ("Could not kill app. App is most likely not running anymore.")
  end
end

#start_test_server_in_background(options = {}) ⇒ Object



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
# File 'lib/calabash-android/operations.rb', line 379

def start_test_server_in_background(options={})
  raise "Will not start test server because of previous failures." if ::Cucumber.wants_to_quit

  if keyguard_enabled?
    wake_up
  end

  env_options = {:target_package => package_name(@app_path),
                 :main_activity => main_activity(@app_path),
                 :test_server_port => @test_server_port,
                 :debug => false,
                 :class => "sh.calaba.instrumentationbackend.InstrumentationBackend"}

  env_options = env_options.merge(options)

  cmd_arr = [adb_command, "shell am instrument"]

  env_options.each_pair do |key, val|
    cmd_arr << "-e"
    cmd_arr << key.to_s
    cmd_arr << val.to_s
  end

  cmd_arr << "#{package_name(@test_server_path)}/sh.calaba.instrumentationbackend.CalabashInstrumentationTestRunner"

  cmd = cmd_arr.join(" ")

  log "Starting test server using:"
  log cmd
  raise "Could not execute command to start test server" unless system("#{cmd} 2>&1")

  retriable :tries => 10, :interval => 1 do
    raise "App did not start" unless app_running?
  end

  begin
    retriable :tries => 10, :interval => 3 do
        log "Checking if instrumentation backend is ready"

        log "Is app running? #{app_running?}"
        ready = http("/ready", {}, {:read_timeout => 1})
        if ready != "true"
          log "Instrumentation backend not yet ready"
          raise "Not ready"
        else
          log "Instrumentation backend is ready!"
        end
    end
  rescue Exception => e

    msg = "Unable to make connection to Calabash Test Server at http://127.0.0.1:#{@server_port}/\n"
    msg << "Please check the logcat output for more info about what happened\n"
    raise msg
  end

  log "Checking client-server version match..."
  response = perform_action('version')
  unless response['success']
    msg = ["Unable to obtain Test Server version. "]
    msg << "Please run 'reinstall_test_server' to make sure you have the correct version"
    msg_s = msg.join("\n")
    log(msg_s)
    raise msg_s
  end
  unless response['message'] == Calabash::Android::VERSION

    msg = ["Calabash Client and Test-server version mismatch."]
    msg << "Client version #{Calabash::Android::VERSION}"
    msg << "Test-server version #{response['message']}"
    msg << "Expected Test-server version #{Calabash::Android::VERSION}"
    msg << "\n\nSolution:\n\n"
    msg << "Run 'reinstall_test_server' to make sure you have the correct version"
    msg_s = msg.join("\n")
    log(msg_s)
    raise msg_s
  end
  log("Client and server versions match. Proceeding...")


end

#switch_wifi(on) ⇒ Object



496
497
498
499
# File 'lib/calabash-android/operations.rb', line 496

def switch_wifi(on)
    cmd = "#{adb_command} shell am start -n com.concur.wifiswitch/." + (on ? "On" : "Off") + "Activity"
    result = `#{cmd}`
end

#uninstall_app(package_name) ⇒ Object



234
235
236
237
# File 'lib/calabash-android/operations.rb', line 234

def uninstall_app(package_name)
  log "Uninstalling: #{package_name}"
  log `#{adb_command} uninstall #{package_name}`
end

#wake_upObject



353
354
355
356
357
358
359
360
361
362
# File 'lib/calabash-android/operations.rb', line 353

def wake_up
  wake_up_cmd = "#{adb_command} shell am start -a android.intent.action.MAIN -n #{package_name(@test_server_path)}/sh.calaba.instrumentationbackend.WakeUp"
  log "Waking up device using:"
  log wake_up_cmd
  raise "Could not wake up the device" unless system(wake_up_cmd)

  retriable :tries => 10, :interval => 1 do
    raise "Could not remove the keyguard" if keyguard_enabled?
  end
end