Class: Appium::Driver

Inherits:
Object
  • Object
show all
Defined in:
lib/appium_lib/driver.rb,
lib/appium_lib/driver.rb,
lib/appium_lib/common/command.rb,
lib/appium_lib/common/search_context.rb

Defined Under Namespace

Modules: Capabilities, Commands, SearchContext

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}, global_driver = true) ⇒ Driver

Creates a new driver

Examples:


```ruby
require 'rubygems'
require 'appium_lib'

# platformName takes a string or a symbol.

# Start iOS driver
opts = {
         caps: {
           platformName: :ios,
           app: '/path/to/MyiOS.app'
         },
         appium_lib: {
           wait_timeout: 30
         }
       }
Appium::Driver.new(opts).start_driver

# Start Android driver
opts = {
         caps: {
           platformName: :android,
           app: '/path/to/my.apk'
         },
         appium_lib: {
           wait_timeout: 30,
           wait_interval: 1
         }
       }
Appium::Driver.new(opts).start_driver
# or Appium::Driver.new(opts, false).start_driver # Don't use global driver.
```

Parameters:

  • opts (Object) (defaults to: {})

    A hash containing various options.

  • global_driver (Bool) (defaults to: true)

    A bool require global driver before initialize.



375
376
377
378
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
# File 'lib/appium_lib/driver.rb', line 375

def initialize(opts = {}, global_driver = true)
  if global_driver
    $driver.driver_quit if $driver
  end
  raise 'opts must be a hash' unless opts.is_a? Hash

  opts              = Appium.symbolize_keys opts
  @caps             = Capabilities.init_caps_for_appium(opts[:caps] || {})

  appium_lib_opts   = opts[:appium_lib] || {}

  set_appium_lib_specific_values(appium_lib_opts)

  # Path to the .apk, .app or .app.zip.
  # The path can be local or remote for Sauce.
  if @caps && @caps[:app] && !@caps[:app].empty?
    @caps[:app] = self.class.absolute_app_path opts
  end

  # https://code.google.com/p/selenium/source/browse/spec-draft.md?repo=mobile
  @appium_device = @caps[:platformName]
  @appium_device = @appium_device.is_a?(Symbol) ? @appium_device : @appium_device.downcase.strip.intern if @appium_device

  @automation_name = @caps[:automationName] if @caps[:automationName]
  @automation_name = if @automation_name
                       @automation_name.is_a?(Symbol) ? @automation_name : @automation_name.downcase.strip.intern
                     end

  # load common methods
  extend Appium::Common
  extend Appium::Device

  if device_is_android?
    extend Appium::Android
    extend Appium::Android::Device
  else
    extend Appium::Ios
    if automation_name_is_xcuitest?
      # Override touch actions and patch_webdriver_element
      extend Appium::Ios::Xcuitest
      extend Appium::Ios::Xcuitest::Helper
      extend Appium::Ios::Xcuitest::Gesture
      extend Appium::Ios::Xcuitest::Device
      extend Appium::Ios::Xcuitest::Element
    end
  end

  # apply os specific patches
  patch_webdriver_element

  # for command
  patch_remote_driver_commands

  # enable debug patch
  # !!'constant' == true
  @appium_debug = appium_lib_opts.fetch :debug, !!defined?(Pry)

  if @appium_debug
    Appium::Logger.ap_debug opts unless opts.empty?
    Appium::Logger.debug "Debug is: #{@appium_debug}"
    Appium::Logger.debug "Device is: #{@appium_device}"
    patch_webdriver_bridge
  end

  # Save global reference to last created Appium driver for top level methods.
  $driver = self if global_driver

  self # return newly created driver
end

Instance Attribute Details

#appium_debugObject (readonly)

Boolean debug mode for the Appium Ruby bindings



315
316
317
# File 'lib/appium_lib/driver.rb', line 315

def appium_debug
  @appium_debug
end

#appium_deviceObject (readonly)

Device type to request from the appium server



308
309
310
# File 'lib/appium_lib/driver.rb', line 308

def appium_device
  @appium_device
end

#appium_portObject (readonly)

Appium's server port



306
307
308
# File 'lib/appium_lib/driver.rb', line 306

def appium_port
  @appium_port
end

#appium_server_statusObject (readonly)

Appium's server version



313
314
315
# File 'lib/appium_lib/driver.rb', line 313

def appium_server_status
  @appium_server_status
end

#appium_wait_intervalInteger (readonly)

Return a time wait timeout Wait interval time for ::Appium::Common.wait or ::Appium::Common.wait_true. Provide Appium::Drive like { appium_lib: { wait_interval: 20 } }

Returns:

  • (Integer)


333
334
335
# File 'lib/appium_lib/driver.rb', line 333

def appium_wait_interval
  @appium_wait_interval
end

#appium_wait_timeoutInteger (readonly)

Return a time wait timeout Wait time for ::Appium::Common.wait or ::Appium::Common.wait_true. Provide Appium::Drive like { appium_lib: { wait_timeout: 20 } }

Returns:

  • (Integer)


328
329
330
# File 'lib/appium_lib/driver.rb', line 328

def appium_wait_timeout
  @appium_wait_timeout
end

#automation_nameObject (readonly)

Automation name sent to appium server or received from server If automation_name is nil, it is not set both client side and server side.



311
312
313
# File 'lib/appium_lib/driver.rb', line 311

def automation_name
  @automation_name
end

#capsObject (readonly)

Selenium webdriver capabilities



289
290
291
# File 'lib/appium_lib/driver.rb', line 289

def caps
  @caps
end

#custom_urlObject (readonly)

Custom URL for the selenium server



291
292
293
# File 'lib/appium_lib/driver.rb', line 291

def custom_url
  @custom_url
end

#default_waitInteger (readonly)

Default wait time for elements to appear Returns the default client side wait. This value is independent of what the server is using

Returns:

  • (Integer)


298
299
300
# File 'lib/appium_lib/driver.rb', line 298

def default_wait
  @default_wait
end

#driverDriver (readonly)

Returns the driver

Returns:



320
321
322
# File 'lib/appium_lib/driver.rb', line 320

def driver
  @driver
end

#export_sessionObject (readonly)

Export session id to textfile in /tmp for 3rd party tools



293
294
295
# File 'lib/appium_lib/driver.rb', line 293

def export_session
  @export_session
end

#global_webdriver_http_sleepObject

The amount to sleep in seconds before every webdriver http call.



287
288
289
# File 'lib/appium_lib/driver.rb', line 287

def global_webdriver_http_sleep
  @global_webdriver_http_sleep
end

#http_clientSelenium::WebDriver::Remote::Http::Default (readonly)

Return http client called in start_driver()

Returns:

  • (Selenium::WebDriver::Remote::Http::Default)

    the http client



323
324
325
# File 'lib/appium_lib/driver.rb', line 323

def http_client
  @http_client
end

#listenerObject (readonly)

instance of AbstractEventListener for logging support



317
318
319
# File 'lib/appium_lib/driver.rb', line 317

def listener
  @listener
end

#sauce_access_keyObject (readonly)

Access Key for use on Sauce Labs. Set `false` to disable Sauce, even when SAUCE_ACCESS_KEY is in ENV.



302
303
304
# File 'lib/appium_lib/driver.rb', line 302

def sauce_access_key
  @sauce_access_key
end

#sauce_endpointObject (readonly)

Override the Sauce Appium endpoint to allow e.g. TestObject tests



304
305
306
# File 'lib/appium_lib/driver.rb', line 304

def sauce_endpoint
  @sauce_endpoint
end

#sauce_usernameObject (readonly)

Username for use on Sauce Labs. Set `false` to disable Sauce, even when SAUCE_USERNAME is in ENV.



300
301
302
# File 'lib/appium_lib/driver.rb', line 300

def sauce_username
  @sauce_username
end

Class Method Details

.absolute_app_path(opts) ⇒ String

Converts app_path to an absolute path.

opts is the full options hash (caps and appium_lib). If server_url is set then the app path is used as is.

if app isn't set then an error is raised.

Returns:

  • (String)

    APP_PATH as an absolute path



571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
# File 'lib/appium_lib/driver.rb', line 571

def self.absolute_app_path(opts)
  raise 'opts must be a hash' unless opts.is_a? Hash
  caps            = opts[:caps] || {}
  appium_lib_opts = opts[:appium_lib] || {}
  server_url      = appium_lib_opts.fetch :server_url, false

  app_path        = caps[:app]
  raise 'absolute_app_path invoked and app is not set!' if app_path.nil? || app_path.empty?
  # may be absolute path to file on remote server.
  # if the file is on the remote server then we can't check if it exists
  return app_path if server_url
  # Sauce storage API. http://saucelabs.com/docs/rest#storage
  return app_path if app_path.start_with? 'sauce-storage:'
  return app_path if app_path =~ /^http/ # public URL for Sauce
  if app_path =~ /^(\/|[a-zA-Z]:)/ # absolute file path
    app_path = File.expand_path app_path unless File.exist? app_path
    raise "App doesn't exist. #{app_path}" unless File.exist? app_path
    return app_path
  end

  # if it doesn't contain a slash then it's a bundle id
  return app_path unless app_path =~ /[\/\\]/

  # relative path that must be expanded.
  # absolute_app_path is called from load_settings
  # and the txt file path is the base of the app path in that case.
  app_path = File.expand_path app_path
  raise "App doesn't exist #{app_path}" unless File.exist? app_path
  app_path
end

Instance Method Details

#appium_client_versionHash

Returns the client's version info

“`ruby

"version" => "9.1.1"

“`

Returns:

  • (Hash)


559
560
561
# File 'lib/appium_lib/driver.rb', line 559

def appium_client_version
  { version: ::Appium::VERSION }
end

#appium_server_versionHash

Returns the server's version info

“`ruby {

"build" => {
    "version" => "0.18.1",
    "revision" => "d242ebcfd92046a974347ccc3a28f0e898595198"
}

} “`

Returns blank hash for Selenium Grid since `remote_status` gets 500 error

“`ruby {} “`

Returns:

  • (Hash)


538
539
540
541
542
543
544
545
546
547
548
# File 'lib/appium_lib/driver.rb', line 538

def appium_server_version
  driver.remote_status
rescue Selenium::WebDriver::Error::WebDriverError => ex
  raise ::Appium::Error::ServerError unless ex.message.include?('content-type=""')
  # server (TestObject for instance) does not respond to status call
  {}
rescue Selenium::WebDriver::Error::ServerError => e
  raise ::Appium::Error::ServerError unless e.message.include?('status code 500')
  # driver.remote_status returns 500 error for using selenium grid
  {}
end

#automation_name_is_uiautomator2?Boolean

Return true if automationName is 'uiautomator2'

Returns:

  • (Boolean)


504
505
506
# File 'lib/appium_lib/driver.rb', line 504

def automation_name_is_uiautomator2?
  !@automation_name.nil? && @automation_name == :uiautomator2
end

#automation_name_is_xcuitest?Boolean

Return true if automationName is 'XCUITest'

Returns:

  • (Boolean)


498
499
500
# File 'lib/appium_lib/driver.rb', line 498

def automation_name_is_xcuitest?
  !@automation_name.nil? && @automation_name == :xcuitest
end

#check_server_version_xcuitestBoolean

Return true if the target Appium server is over REQUIRED_VERSION_XCUITEST. If the Appium server is under REQUIRED_VERSION_XCUITEST, then error is raised.

Returns:

  • (Boolean)


511
512
513
514
515
516
517
518
# File 'lib/appium_lib/driver.rb', line 511

def check_server_version_xcuitest
  if automation_name_is_xcuitest? &&
      !@appium_server_status.empty? &&
      (@appium_server_status['build']['version'] < REQUIRED_VERSION_XCUITEST)
    raise Appium::Error::NotSupportedAppiumServer, "XCUITest requires Appium version >= #{REQUIRED_VERSION_XCUITEST}"
  end
  true
end

#device_is_android?Boolean

Returns:

  • (Boolean)


492
493
494
# File 'lib/appium_lib/driver.rb', line 492

def device_is_android?
  @appium_device == :android
end

#driver_attributesObject

Returns a hash of the driver attributes



473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
# File 'lib/appium_lib/driver.rb', line 473

def driver_attributes
  {
      caps:             @caps,
      automation_name:  @automation_name,
      custom_url:       @custom_url,
      export_session:   @export_session,
      default_wait:     @default_wait,
      sauce_username:   @sauce_username,
      sauce_access_key: @sauce_access_key,
      sauce_endpoint:   @sauce_endpoint,
      port:             @appium_port,
      device:           @appium_device,
      debug:            @appium_debug,
      listener:         @listener,
      wait_timeout:     @appium_wait_timeout,
      wait_interval:    @appium_wait_interval
  }
end

#driver_quitvoid Also known as: quit_driver

This method returns an undefined value.

Quits the driver



633
634
635
636
637
638
# File 'lib/appium_lib/driver.rb', line 633

def driver_quit
  # rescue NoSuchDriverError or nil driver
  @driver.quit
rescue
  nil
end

#execute_script(script, *args) ⇒ Object

The same as @driver.execute_script

Parameters:

  • script (String)

    The script to execute

  • args (*args)

    The args to pass to the script

Returns:

  • (Object)


764
765
766
# File 'lib/appium_lib/driver.rb', line 764

def execute_script(script, *args)
  @driver.execute_script script, *args
end

#exists(pre_check = 0, post_check = @default_wait) { ... } ⇒ Boolean

Returns existence of element.

Example:

exists { button('sign in') } ? puts('true') : puts('false')

Parameters:

  • pre_check (Integer) (defaults to: 0)

    The amount in seconds to set the wait to before checking existence

  • post_check (Integer) (defaults to: @default_wait)

    The amount in seconds to set the wait to after checking existence

Yields:

  • The block to call

Returns:

  • (Boolean)


740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
# File 'lib/appium_lib/driver.rb', line 740

def exists(pre_check = 0, post_check = @default_wait)
  # do not uset set_wait here.
  # it will cause problems with other methods reading the default_wait of 0
  # which then gets converted to a 1 second wait.
  @driver.manage.timeouts.implicit_wait = pre_check
  # the element exists unless an error is raised.
  exists                                = true

  begin
    yield # search for element
  rescue
    exists = false # error means it's not there
  end

  # restore wait
  @driver.manage.timeouts.implicit_wait = post_check if post_check != pre_check

  exists
end

#find_element(*args) ⇒ Element

Calls @driver.find_element

“` “`

If you call `Appium.promote_appium_methods`, you can call `find_element` directly.

Parameters:

  • args (*args)

    The args to use

Returns:

  • (Element)


801
802
803
# File 'lib/appium_lib/driver.rb', line 801

def find_element(*args)
  @driver.find_element(*args)
end

#find_elements(*args) ⇒ Array<Element>

Calls @driver.find_elements_with_appium

“` “`

If you call `Appium.promote_appium_methods`, you can call `find_elements` directly.

“` “`

If you call `Appium.promote_appium_methods`, you can call `find_elements` directly.

Parameters:

  • args (*args)

    The args to use

Returns:

  • (Array<Element>)

    Array is empty when no elements are found.



786
787
788
# File 'lib/appium_lib/driver.rb', line 786

def find_elements(*args)
  @driver.find_elements(*args)
end

#no_waitObject

Set implicit wait to zero.



709
710
711
# File 'lib/appium_lib/driver.rb', line 709

def no_wait
  @driver.manage.timeouts.implicit_wait = 0
end

#restartDriver

Restarts the driver

Returns:



615
616
617
618
# File 'lib/appium_lib/driver.rb', line 615

def restart
  driver_quit
  start_driver
end

#screenshot(png_save_path) ⇒ nil

Takes a png screenshot and saves to the target path.

Example: screenshot '/tmp/hi.png'

Parameters:

  • png_save_path (String)

    the full path to save the png

Returns:

  • (nil)


626
627
628
629
# File 'lib/appium_lib/driver.rb', line 626

def screenshot(png_save_path)
  @driver.save_screenshot png_save_path
  nil
end

#server_urlString

Get the server url

Returns:

  • (String)

    the server url



604
605
606
607
608
609
610
611
# File 'lib/appium_lib/driver.rb', line 604

def server_url
  return @custom_url if @custom_url
  if !@sauce_username.nil? && !@sauce_access_key.nil?
    "https://#{@sauce_username}:#{@sauce_access_key}@#{@sauce_endpoint}"
  else
    "http://127.0.0.1:#{@appium_port}/wd/hub"
  end
end

#set_location(opts = {}) ⇒ Selenium::WebDriver::Location

Note:

This method does not work on real devices.

Calls @driver.set_location

Parameters:

  • opts (Hash) (defaults to: {})

    consisting of:

Options Hash (opts):

  • :latitude (Float)

    the latitude in degrees (required)

  • :longitude (Float)

    the longitude in degees (required)

  • :altitude (Float)

    the altitude, defaulting to 75

Returns:

  • (Selenium::WebDriver::Location)

    the location constructed by the selenium webdriver



814
815
816
817
818
819
# File 'lib/appium_lib/driver.rb', line 814

def set_location(opts = {})
  latitude = opts.fetch(:latitude)
  longitude = opts.fetch(:longitude)
  altitude = opts.fetch(:altitude, 75)
  @driver.set_location(latitude, longitude, altitude)
end

#set_wait(timeout = nil) ⇒ void

This method returns an undefined value.

Set implicit wait. Default to @default_wait.

“`ruby set_wait 2 set_wait # @default_wait

“`

Parameters:

  • timeout (Integer) (defaults to: nil)

    the timeout in seconds



723
724
725
726
# File 'lib/appium_lib/driver.rb', line 723

def set_wait(timeout = nil)
  timeout = @default_wait if timeout.nil?
  @driver.manage.timeouts.implicit_wait = timeout
end

#start_driver(http_client_ops = { http_client: nil, open_timeout: 999_999, read_timeout: 999_999 }) ⇒ Selenium::WebDriver

Creates a new global driver and quits the old one if it exists. You can customise http_client as the following

Examples:

```ruby
require 'rubygems'
require 'appium_lib'

# platformName takes a string or a symbol.

# Start iOS driver
opts = {
         caps: {
           platformName: :ios,
           app: '/path/to/MyiOS.app'
         },
         appium_lib: {
           wait_timeout: 30
         }
       }
Appium::Driver.new(opts).start_driver

Parameters:

  • http_client_ops (Hash) (defaults to: { http_client: nil, open_timeout: 999_999, read_timeout: 999_999 })

    a customizable set of options

Options Hash (http_client_ops):

  • :http_client (Hash)

    Custom HTTP Client

  • :open_timeout (Hash)

    Custom open timeout for http client.

  • :read_timeout (Hash)

    Custom read timeout for http client.

Returns:

  • (Selenium::WebDriver)

    the new global driver



669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
# File 'lib/appium_lib/driver.rb', line 669

def start_driver(http_client_ops = { http_client: nil, open_timeout: 999_999, read_timeout: 999_999 })
  # open_timeout and read_timeout are explicit wait.
  open_timeout = http_client_ops.delete(:open_timeout)
  read_timeout = http_client_ops.delete(:read_timeout)

  http_client = http_client_ops.delete(:http_client)
  @http_client ||= http_client ? http_client : Selenium::WebDriver::Remote::Http::Default.new

  @http_client.open_timeout = open_timeout if open_timeout
  @http_client.read_timeout = read_timeout if read_timeout

  begin
    driver_quit
    @driver =  Selenium::WebDriver.for(:remote,
                                       http_client: @http_client,
                                       desired_capabilities: @caps,
                                       url: server_url,
                                       listener: @listener)

    # Load touch methods.
    @driver.extend Selenium::WebDriver::DriverExtensions::HasTouchScreen
    @driver.extend Selenium::WebDriver::DriverExtensions::HasLocation

    # export session
    write_session_id(@driver.session_id) if @export_session
  rescue Errno::ECONNREFUSED
    raise "ERROR: Unable to connect to Appium. Is the server running on #{server_url}?"
  end

  @appium_server_status = appium_server_version

  check_server_version_xcuitest
  set_automation_name_if_nil

  @driver.manage.timeouts.implicit_wait = @default_wait

  @driver
end

#xvoid

This method returns an undefined value.

Quit the driver and Pry. quit and exit are reserved by Pry.



824
825
826
827
# File 'lib/appium_lib/driver.rb', line 824

def x
  driver_quit
  exit # exit pry
end