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.



131
132
133
134
135
136
137
138
139
140
141
# File 'lib/calabash-android/operations.rb', line 131

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



274
275
276
277
278
279
280
# File 'lib/calabash-android/operations.rb', line 274

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)


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

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

#device_argsObject



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

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

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



203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/calabash-android/operations.rb', line 203

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



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

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)


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

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



127
128
129
# File 'lib/calabash-android/operations.rb', line 127

def make_default_device
  @cucumber_world.default_device = self
end

#perform_action(action, *arguments) ⇒ Object



179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# File 'lib/calabash-android/operations.rb', line 179

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



143
144
145
146
147
148
# File 'lib/calabash-android/operations.rb', line 143

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



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

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



356
357
358
# File 'lib/calabash-android/operations.rb', line 356

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

#set_gps_coordinates_from_location(location) ⇒ Object

location

Raises:

  • (Exception)


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

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



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

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



301
302
303
304
305
306
307
308
309
310
311
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
# File 'lib/calabash-android/operations.rb', line 301

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



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

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



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

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

#wake_upObject



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

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