Class: Calabash::Android::Operations::Device
- Inherits:
-
Object
- Object
- Calabash::Android::Operations::Device
- Defined in:
- lib/calabash-android/operations.rb
Instance Attribute Summary collapse
-
#app_path ⇒ Object
readonly
Returns the value of attribute app_path.
-
#serial ⇒ Object
readonly
Returns the value of attribute serial.
-
#server_port ⇒ Object
readonly
Returns the value of attribute server_port.
-
#test_server_path ⇒ Object
readonly
Returns the value of attribute test_server_path.
-
#test_server_port ⇒ Object
readonly
Returns the value of attribute test_server_port.
Instance Method Summary collapse
- #adb_command ⇒ Object
- #app_running? ⇒ Boolean
- #clear_app_data ⇒ Object
- #clear_preferences(name) ⇒ Object
- #client_version ⇒ Object
- #configure_http(http, options) ⇒ Object
- #connected_devices ⇒ Object
- #default_serial ⇒ Object
- #default_server_port ⇒ Object
- #get_json_from_logcat(logcat_output) ⇒ Object
- #get_logcat_cmd(tag) ⇒ Object
- #get_logcat_id ⇒ Object
- #get_preferences(name) ⇒ Object
- #http(path, data = {}, options = {}) ⇒ Object
- #init_request(options) ⇒ Object
-
#initialize(cucumber_world, serial, server_port, app_path, test_server_path, test_server_port = 7102) ⇒ Device
constructor
A new instance of Device.
- #install_app(app_path) ⇒ Object
- #keyguard_enabled? ⇒ Boolean
- #make_http_request(options) ⇒ Object
- #perform_action(action, *arguments) ⇒ Object
- #pull(remote, local) ⇒ Object
- #push(local, remote) ⇒ Object
- #reinstall_apps ⇒ Object
- #reinstall_test_server ⇒ Object
- #screenshot(options = {:prefix => nil, :name => nil}) ⇒ Object
- #server_port_configuration ⇒ Object
- #server_version ⇒ Object
- #set_gps_coordinates(latitude, longitude) ⇒ Object
-
#set_gps_coordinates_from_location(location) ⇒ Object
location.
- #set_http(http) ⇒ Object
- #set_preferences(name, hash) ⇒ Object
- #shutdown_test_server ⇒ Object
- #start_test_server_in_background(options = {}) ⇒ Object
- #uninstall_app(package_name) ⇒ Object
- #update_app(app_path) ⇒ Object
- #url_for(method) ⇒ Object
- #wake_up ⇒ Object
Constructor Details
#initialize(cucumber_world, serial, server_port, app_path, test_server_path, test_server_port = 7102) ⇒ Device
Returns a new instance of Device.
270 271 272 273 274 275 276 277 278 279 280 281 282 |
# File 'lib/calabash-android/operations.rb', line 270 def initialize(cucumber_world, serial, server_port, app_path, test_server_path, test_server_port = 7102) @cucumber_world = cucumber_world @serial = serial || default_serial @server_port = server_port || default_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_path ⇒ Object (readonly)
Returns the value of attribute app_path.
268 269 270 |
# File 'lib/calabash-android/operations.rb', line 268 def app_path @app_path end |
#serial ⇒ Object (readonly)
Returns the value of attribute serial.
268 269 270 |
# File 'lib/calabash-android/operations.rb', line 268 def serial @serial end |
#server_port ⇒ Object (readonly)
Returns the value of attribute server_port.
268 269 270 |
# File 'lib/calabash-android/operations.rb', line 268 def server_port @server_port end |
#test_server_path ⇒ Object (readonly)
Returns the value of attribute test_server_path.
268 269 270 |
# File 'lib/calabash-android/operations.rb', line 268 def test_server_path @test_server_path end |
#test_server_port ⇒ Object (readonly)
Returns the value of attribute test_server_port.
268 269 270 |
# File 'lib/calabash-android/operations.rb', line 268 def test_server_port @test_server_port end |
Instance Method Details
#adb_command ⇒ Object
509 510 511 |
# File 'lib/calabash-android/operations.rb', line 509 def adb_command "#{Env.adb_path} -s #{serial}" end |
#app_running? ⇒ Boolean
335 336 337 338 339 340 341 |
# File 'lib/calabash-android/operations.rb', line 335 def app_running? begin http("/ping") == "pong" rescue false end end |
#clear_app_data ⇒ Object
563 564 565 566 |
# File 'lib/calabash-android/operations.rb', line 563 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 |
#clear_preferences(name) ⇒ Object
748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 |
# File 'lib/calabash-android/operations.rb', line 748 def clear_preferences(name) log "Clear preferences: #{name}, app running? #{app_running?}" if app_running? perform_action('clear_preferences', name); else logcat_id = get_logcat_id() cmd = "#{adb_command} shell am instrument -e logcat #{logcat_id} -e name \"#{name}\" #{package_name(@test_server_path)}/sh.calaba.instrumentationbackend.ClearPreferences" raise "Could not clear preferences" unless system(cmd) logcat_cmd = get_logcat_cmd(logcat_id) logcat_output = `#{logcat_cmd}` json = get_json_from_logcat(logcat_output) raise "Could not clear preferences" unless json != nil and json["success"] end end |
#client_version ⇒ Object
492 493 494 |
# File 'lib/calabash-android/operations.rb', line 492 def client_version Calabash::Android::VERSION end |
#configure_http(http, options) ⇒ Object
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 |
# File 'lib/calabash-android/operations.rb', line 441 def configure_http(http, ) return unless http http.connect_timeout = [:open_timeout] || 15 http.send_timeout = [:send_timeout] || 15 http.receive_timeout = [:read_timeout] || 15 if .has_key?(:debug) && [:debug] http.debug_dev= $stdout else if ENV['DEBUG_HTTP'] and (ENV['DEBUG_HTTP'] != '0') http.debug_dev = $stdout else http.debug_dev= nil end end http end |
#connected_devices ⇒ Object
546 547 548 549 550 |
# File 'lib/calabash-android/operations.rb', line 546 def connected_devices lines = `#{Env.adb_path} devices`.split("\n") start_index = lines.index{ |x| x =~ /List of devices attached/ } + 1 lines[start_index..-1].collect { |l| l.split("\t").first } end |
#default_serial ⇒ Object
513 514 515 516 517 518 519 |
# File 'lib/calabash-android/operations.rb', line 513 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 |
#default_server_port ⇒ Object
521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 |
# File 'lib/calabash-android/operations.rb', line 521 def default_server_port require 'yaml' File.open(File.(server_port_configuration), File::RDWR|File::CREAT) do |f| f.flock(File::LOCK_EX) state = YAML::load(f) || {} ports = state['server_ports'] ||= {} return ports[serial] if ports.has_key?(serial) port = 34777 port += 1 while ports.has_value?(port) ports[serial] = port f.rewind f.write(YAML::dump(state)) f.truncate(f.pos) log "Persistently allocated port #{port} to #{serial}" return port end end |
#get_json_from_logcat(logcat_output) ⇒ Object
769 770 771 772 773 774 775 776 777 778 779 780 781 |
# File 'lib/calabash-android/operations.rb', line 769 def get_json_from_logcat(logcat_output) logcat_output.split(/\r?\n/).each do |line| begin json = JSON.parse(line) return json rescue # nothing to do here, just discarding logcat rubbish end end return nil end |
#get_logcat_cmd(tag) ⇒ Object
792 793 794 795 796 797 |
# File 'lib/calabash-android/operations.rb', line 792 def get_logcat_cmd(tag) # returns raw logcat output for our tag # filtering out everthing else "#{adb_command} logcat -d -v raw #{tag}:* *:S" end |
#get_logcat_id ⇒ Object
783 784 785 786 787 788 789 790 |
# File 'lib/calabash-android/operations.rb', line 783 def get_logcat_id() # we need a unique logcat tag so we can later # query the logcat output and filter out everything # but what we are interested in random = (0..10000).to_a.sample "#{Time.now.strftime("%s")}_#{random}" end |
#get_preferences(name) ⇒ Object
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 |
# File 'lib/calabash-android/operations.rb', line 690 def get_preferences(name) log "Get preferences: #{name}, app running? #{app_running?}" preferences = {} if app_running? json = perform_action('get_preferences', name); else logcat_id = get_logcat_id() cmd = "#{adb_command} shell am instrument -e logcat #{logcat_id} -e name \"#{name}\" #{package_name(@test_server_path)}/sh.calaba.instrumentationbackend.GetPreferences" raise "Could not get preferences" unless system(cmd) logcat_cmd = get_logcat_cmd(logcat_id) logcat_output = `#{logcat_cmd}` json = get_json_from_logcat(logcat_output) raise "Could not get preferences" unless json != nil and json["success"] end # at this point we have valid json, coming from an action # or instrumentation, but we don't care, just parse if json["bonusInformation"].length > 0 json["bonusInformation"].each do |item| json_item = JSON.parse(item) preferences[json_item["key"]] = json_item["value"] end end preferences end |
#http(path, data = {}, options = {}) ⇒ Object
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 |
# File 'lib/calabash-android/operations.rb', line 373 def http(path, data = {}, = {}) begin configure_http(@http, ) make_http_request( :method => :post, :body => data.to_json, :uri => url_for(path), :header => {"Content-Type" => "application/json;charset=utf-8"}) rescue HTTPClient::TimeoutError, HTTPClient::KeepAliveDisconnected, Errno::ECONNREFUSED, Errno::ECONNRESET, Errno::ECONNABORTED, Errno::ETIMEDOUT => e log "It looks like your app is no longer running. \nIt could be because of a crash or because your test script shut it down." raise e end end |
#init_request(options) ⇒ Object
436 437 438 439 |
# File 'lib/calabash-android/operations.rb', line 436 def init_request() http = HTTPClient.new configure_http(http, ) end |
#install_app(app_path) ⇒ Object
296 297 298 299 300 301 302 303 304 305 306 307 308 |
# File 'lib/calabash-android/operations.rb', line 296 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`.lines.map{|line| line.chomp.sub("package:", "")}.include?(pn) unless succeeded ::Cucumber.wants_to_quit = true raise "#{pn} did not get installed. Reason: '#{result.lines.last.chomp}'. Aborting!" end end |
#keyguard_enabled? ⇒ Boolean
343 344 345 346 347 |
# File 'lib/calabash-android/operations.rb', line 343 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_http_request(options) ⇒ Object
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 |
# File 'lib/calabash-android/operations.rb', line 410 def make_http_request() begin unless @http @http = init_request() end header = [:header] || {} header["Content-Type"] = "application/json;charset=utf-8" [:header] = header response = if [:method] == :post @http.post([:uri], ) else @http.get([:uri], ) end raise Errno::ECONNREFUSED if response.status_code == 502 response.body rescue Exception => e if @http @http.reset_all @http=nil end raise e end end |
#perform_action(action, *arguments) ⇒ Object
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 |
# File 'lib/calabash-android/operations.rb', line 349 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 "Action '#{action}' unsuccessful: #{result["message"]}" end result end rescue Timeout::Error raise Exception, "Step timed out" end |
#pull(remote, local) ⇒ Object
568 569 570 571 |
# File 'lib/calabash-android/operations.rb', line 568 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
573 574 575 576 |
# File 'lib/calabash-android/operations.rb', line 573 def push(local, remote) cmd = "#{adb_command} push #{local} #{remote}" raise "Could not push #{local} to #{remote}" unless system(cmd) end |
#reinstall_apps ⇒ Object
284 285 286 287 288 289 |
# File 'lib/calabash-android/operations.rb', line 284 def reinstall_apps uninstall_app(package_name(@app_path)) uninstall_app(package_name(@test_server_path)) install_app(@app_path) install_app(@test_server_path) end |
#reinstall_test_server ⇒ Object
291 292 293 294 |
# File 'lib/calabash-android/operations.rb', line 291 def reinstall_test_server uninstall_app(package_name(@test_server_path)) install_app(@test_server_path) end |
#screenshot(options = {:prefix => nil, :name => nil}) ⇒ Object
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 |
# File 'lib/calabash-android/operations.rb', line 458 def screenshot(={:prefix => nil, :name => nil}) prefix = [:prefix] || ENV['SCREENSHOT_PATH'] || "" name = [: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 |
#server_port_configuration ⇒ Object
542 543 544 |
# File 'lib/calabash-android/operations.rb', line 542 def server_port_configuration File.(ENV['CALABASH_SERVER_PORTS'] || "~/.calabash.yaml") end |
#server_version ⇒ Object
496 497 498 499 500 501 502 503 504 505 506 507 |
# File 'lib/calabash-android/operations.rb', line 496 def server_version begin response = perform_action('version') raise 'Invalid response' unless response['success'] rescue => e log("Could not contact server") log(e && e.backtrace && e.backtrace.join("\n")) raise "The server did not respond. Make sure the server is running." end response['message'] end |
#set_gps_coordinates(latitude, longitude) ⇒ Object
686 687 688 |
# File 'lib/calabash-android/operations.rb', line 686 def set_gps_coordinates(latitude, longitude) perform_action('set_gps_coordinates', latitude, longitude) end |
#set_gps_coordinates_from_location(location) ⇒ Object
location
677 678 679 680 681 682 683 684 |
# File 'lib/calabash-android/operations.rb', line 677 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 |
#set_http(http) ⇒ Object
392 393 394 |
# File 'lib/calabash-android/operations.rb', line 392 def set_http(http) @http = http end |
#set_preferences(name, hash) ⇒ Object
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 |
# File 'lib/calabash-android/operations.rb', line 724 def set_preferences(name, hash) log "Set preferences: #{name}, #{hash}, app running? #{app_running?}" if app_running? perform_action('set_preferences', name, hash); else params = hash.map {|k,v| "-e \"#{k}\" \"#{v}\""}.join(" ") logcat_id = get_logcat_id() cmd = "#{adb_command} shell am instrument -e logcat #{logcat_id} -e name \"#{name}\" #{params} #{package_name(@test_server_path)}/sh.calaba.instrumentationbackend.SetPreferences" raise "Could not set preferences" unless system(cmd) logcat_cmd = get_logcat_cmd(logcat_id) logcat_output = `#{logcat_cmd}` json = get_json_from_logcat(logcat_output) raise "Could not set preferences" unless json != nil and json["success"] end end |
#shutdown_test_server ⇒ Object
661 662 663 664 665 666 667 668 669 670 671 672 673 674 |
# File 'lib/calabash-android/operations.rb', line 661 def shutdown_test_server begin http("/kill") Timeout::timeout(3) do sleep 0.3 while app_running? end rescue HTTPClient::KeepAliveDisconnected log ("Server not responding. Moving on.") 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
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 |
# File 'lib/calabash-android/operations.rb', line 578 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 = [:target_package] ||= package_name(@app_path) [:main_activity] ||= main_activity(@app_path) [:test_server_port] ||= @test_server_port [:class] ||= "sh.calaba.instrumentationbackend.InstrumentationBackend" cmd_arr = [adb_command, "shell am instrument"] .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..." begin server_version = server_version() rescue 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 client_version = client_version() unless server_version == client_version msg = ["Calabash Client and Test-server version mismatch."] msg << "Client version #{client_version}" msg << "Test-server version #{server_version}" msg << "Expected Test-server version #{client_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 (client: #{client_version}, server: #{server_version}). Proceeding...") end |
#uninstall_app(package_name) ⇒ Object
323 324 325 326 327 328 329 330 331 332 333 |
# File 'lib/calabash-android/operations.rb', line 323 def uninstall_app(package_name) log "Uninstalling: #{package_name}" log `#{adb_command} uninstall #{package_name}` succeeded = !(`#{adb_command} shell pm list packages`.lines.map{|line| line.chomp.sub("package:", "")}.include?(package_name)) unless succeeded ::Cucumber.wants_to_quit = true raise "#{package_name} was not uninstalled. Aborting!" end end |
#update_app(app_path) ⇒ Object
310 311 312 313 314 315 316 317 318 319 320 321 |
# File 'lib/calabash-android/operations.rb', line 310 def update_app(app_path) cmd = "#{adb_command} install -r \"#{app_path}\"" log "Updating: #{app_path}" result = `#{cmd}` log "result: #{result}" succeeded = result.include?("Success") unless succeeded ::Cucumber.wants_to_quit = true raise "#{pn} did not get updated. Aborting!" end end |
#url_for(method) ⇒ Object
396 397 398 399 400 401 402 403 404 405 406 |
# File 'lib/calabash-android/operations.rb', line 396 def url_for(method) url = URI.parse(ENV['DEVICE_ENDPOINT']|| "http://127.0.0.1:#{@server_port}") path = url.path if path.end_with? "/" path = "#{path}#{method}" else path = "#{path}/#{method}" end url.path = path url end |
#wake_up ⇒ Object
552 553 554 555 556 557 558 559 560 561 |
# File 'lib/calabash-android/operations.rb', line 552 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 |