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

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

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Device.



152
153
154
155
156
157
158
159
160
161
162
# File 'lib/calabash-android/operations.rb', line 152

def initialize(cucumber_world, serial, server_port, app_path, test_server_path)
  @cucumber_world = cucumber_world
  @serial = serial
  @server_port = server_port
  @app_path = app_path
  @test_server_path = test_server_path

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

Instance Method Details

#adb_commandObject



280
281
282
283
284
285
286
# File 'lib/calabash-android/operations.rb', line 280

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

#app_running?Boolean

Returns:

  • (Boolean)


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

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

#clear_app_dataObject



307
308
309
310
# File 'lib/calabash-android/operations.rb', line 307

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

#device_argsObject



288
289
290
291
292
293
294
# File 'lib/calabash-android/operations.rb', line 288

def device_args
  if @serial
    "-s #{@serial}"
  else
    ""
  end
end

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



228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
# File 'lib/calabash-android/operations.rb', line 228

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

#install_app(app_path) ⇒ Object



175
176
177
178
179
180
181
182
183
184
185
186
187
# File 'lib/calabash-android/operations.rb', line 175

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)


198
199
200
201
202
# File 'lib/calabash-android/operations.rb', line 198

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



204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
# File 'lib/calabash-android/operations.rb', line 204

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

#reinstall_appsObject



164
165
166
167
168
# File 'lib/calabash-android/operations.rb', line 164

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

#reinstall_test_serverObject



170
171
172
173
# File 'lib/calabash-android/operations.rb', line 170

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

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



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

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"] == "true"
    device_args = "-s #{@serial}" if @serial
    screenshot_cmd = "java -jar #{File.join(File.dirname(__FILE__), 'lib', 'screenShotTaker.jar')} #{path} #{device_args}"
    log screenshot_cmd
    raise "Could not take screenshot" unless system(screenshot_cmd)
  else
    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
  end


  @@screenshot_count += 1
  path
end

#set_gps_coordinates(latitude, longitude) ⇒ Object



408
409
410
# File 'lib/calabash-android/operations.rb', line 408

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

#set_gps_coordinates_from_location(location) ⇒ Object

location

Raises:

  • (Exception)


399
400
401
402
403
404
405
406
# File 'lib/calabash-android/operations.rb', line 399

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



390
391
392
393
394
395
396
# File 'lib/calabash-android/operations.rb', line 390

def shutdown_test_server
  begin
    http("/kill")
  rescue EOFError
    log ("Could not kill app. App is most likely not running anymore.")
  end
end

#start_test_server_in_background(options = {}) ⇒ Object



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

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 => options[:target_package] || package_name(@app_path),
                 :main_activity => options[:main_activity] || main_activity(@app_path),
                 :debug => options[:debug] || false,
                 :class => options[:class] || "sh.calaba.instrumentationbackend.InstrumentationBackend"}

  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 << "sh.calaba.android.test/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

#uninstall_app(package_name) ⇒ Object



189
190
191
192
# File 'lib/calabash-android/operations.rb', line 189

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

#wake_upObject



296
297
298
299
300
301
302
303
304
305
# File 'lib/calabash-android/operations.rb', line 296

def wake_up
  wake_up_cmd = "#{adb_command} shell am start -a android.intent.action.MAIN -n sh.calaba.android.test/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