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.



139
140
141
142
143
144
145
146
147
148
149
# File 'lib/calabash-android/operations.rb', line 139

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



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

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)


177
178
179
# File 'lib/calabash-android/operations.rb', line 177

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

#clear_app_dataObject



309
310
311
312
# File 'lib/calabash-android/operations.rb', line 309

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



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

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

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



211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
# File 'lib/calabash-android/operations.rb', line 211

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



158
159
160
161
162
163
164
165
166
167
168
169
170
# File 'lib/calabash-android/operations.rb', line 158

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)


181
182
183
184
185
# File 'lib/calabash-android/operations.rb', line 181

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

#make_default_deviceObject



135
136
137
# File 'lib/calabash-android/operations.rb', line 135

def make_default_device
  @cucumber_world.default_device = self
end

#perform_action(action, *arguments) ⇒ Object



187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
# File 'lib/calabash-android/operations.rb', line 187

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



151
152
153
154
155
156
# File 'lib/calabash-android/operations.rb', line 151

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

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



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

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



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

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

#set_gps_coordinates_from_location(location) ⇒ Object

location

Raises:

  • (Exception)


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

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



351
352
353
354
355
356
357
# File 'lib/calabash-android/operations.rb', line 351

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_backgroundObject



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

def start_test_server_in_background
  raise "Will not start test server because of previous failures." if Cucumber.wants_to_quit

  if keyguard_enabled?
    wake_up
  end

  cmd = "#{adb_command} shell am instrument -e target_package #{ENV["PACKAGE_NAME"]} -e main_activity #{ENV["MAIN_ACTIVITY"]} -e class sh.calaba.instrumentationbackend.InstrumentationBackend sh.calaba.android.test/sh.calaba.instrumentationbackend.CalabashInstrumentationTestRunner"
  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
    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
end

#take_screenshotObject



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

def take_screenshot
  puts "take_screenshot is deprecated. Use screenshot_embed instead."
  path = ENV["SCREENSHOT_PATH_PREFIX"] || "results"
  FileUtils.mkdir_p path unless File.exist? path
  filename_prefix = FeatureNameMemory.feature_name.gsub(/\s+/, '_').downcase
  begin
    Timeout.timeout(30) do
      file_name = "#{path}/#{filename_prefix}_#{FeatureNameMemory.invocation}_#{StepCounter.step_line}.png"
      image = http("/screenshot")
      open(file_name ,"wb") { |file|
        file.write(image)
      }
      log "Screenshot stored in: #{file_name}!!!"
    end
  rescue Timeout::Error
    raise Exception, "take_screenshot timed out"
  end
end

#uninstall_app(package_name) ⇒ Object



172
173
174
175
# File 'lib/calabash-android/operations.rb', line 172

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

#wake_upObject



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

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