How to use status method of Selenium.WebDriver.Remote Package

Best Selenium code snippet using Selenium.WebDriver.Remote.status

driver.rb

Source:driver.rb Github

copy

Full Screen

...19      @w3c = ((defined?(Selenium::WebDriver::Remote::W3CCapabilities) && @browser.capabilities.is_a?(Selenium::WebDriver::Remote::W3CCapabilities)) ||20              (defined?(Selenium::WebDriver::Remote::W3C::Capabilities) && @browser.capabilities.is_a?(Selenium::WebDriver::Remote::W3C::Capabilities)))21      main = Process.pid22      at_exit do23        # Store the exit status of the test run since it goes away after calling the at_exit proc...24        @exit_status = $!.status if $!.is_a?(SystemExit)25        quit if Process.pid == main26        exit @exit_status if @exit_status # Force exit with stored status27      end28    end29    @browser30  end31  def initialize(app, options={})32    load_selenium33    @session = nil34    @app = app35    @browser = nil36    @exit_status = nil37    @frame_handles = {}38    @options = DEFAULT_OPTIONS.merge(options)39  end40  def visit(path)41    browser.navigate.to(path)42  end43  def refresh44    accept_modal(nil, wait: 0.1) do45      browser.navigate.refresh46    end47  rescue Capybara::ModalNotFound48  end49  def go_back50    browser.navigate.back51  end52  def go_forward53    browser.navigate.forward54  end55  def html56    browser.page_source57  end58  def title59    browser.title60  end61  def current_url62    browser.current_url63  end64  def find_xpath(selector)65    browser.find_elements(:xpath, selector).map { |node| Capybara::Selenium::Node.new(self, node) }66  end67  def find_css(selector)68    browser.find_elements(:css, selector).map { |node| Capybara::Selenium::Node.new(self, node) }69  end70  def wait?; true; end71  def needs_server?; true; end72  def execute_script(script, *args)73    browser.execute_script(script, *args.map { |arg| arg.is_a?(Capybara::Selenium::Node) ?  arg.native : arg} )74  end75  def evaluate_script(script, *args)76    result = execute_script("return #{script}", *args)77    unwrap_script_result(result)78  end79  def evaluate_async_script(script, *args)80    browser.manage.timeouts.script_timeout = Capybara.default_max_wait_time81    result = browser.execute_async_script(script, *args.map { |arg| arg.is_a?(Capybara::Selenium::Node) ? arg.native : arg} )82    unwrap_script_result(result)83  end84  def save_screenshot(path, _options={})85    browser.save_screenshot(path)86  end87  def reset!88    # Use instance variable directly so we avoid starting the browser just to reset the session89    if @browser90      navigated = false91      start_time = Capybara::Helpers.monotonic_time92      begin93        if !navigated94          # Only trigger a navigation if we haven't done it already, otherwise it95          # can trigger an endless series of unload modals96          begin97            @browser.manage.delete_all_cookies98            if options[:clear_session_storage]99              if @browser.respond_to? :session_storage100                @browser.session_storage.clear101              else102                warn "sessionStorage clear requested but is not available for this driver"103              end104            end105            if options[:clear_local_storage]106              if @browser.respond_to? :local_storage107                @browser.local_storage.clear108              else109                warn "localStorage clear requested but is not available for this driver"110              end111            end112          rescue Selenium::WebDriver::Error::UnhandledError113            # delete_all_cookies fails when we've previously gone114            # to about:blank, so we rescue this error and do nothing115            # instead.116          end117          @browser.navigate.to("about:blank")118        end119        navigated = true120        #Ensure the page is empty and trigger an UnhandledAlertError for any modals that appear during unload121        until find_xpath("/html/body/*").empty? do122          raise Capybara::ExpectationNotMet.new('Timed out waiting for Selenium session reset') if (Capybara::Helpers.monotonic_time - start_time) >= 10123          sleep 0.05124        end125      rescue Selenium::WebDriver::Error::UnhandledAlertError, Selenium::WebDriver::Error::UnexpectedAlertOpenError126        # This error is thrown if an unhandled alert is on the page127        # Firefox appears to automatically dismiss this alert, chrome does not128        # We'll try to accept it129        begin130          @browser.switch_to.alert.accept131          sleep 0.25 # allow time for the modal to be handled132        rescue modal_error133          # The alert is now gone - nothing to do134        end135        # try cleaning up the browser again136        retry137      end138    end139  end140  def switch_to_frame(frame)141    case frame142    when :top143      @frame_handles[browser.window_handle] = []144      browser.switch_to.default_content145    when :parent146      # would love to use browser.switch_to.parent_frame here147      # but it has an issue if the current frame is removed from within it148      @frame_handles[browser.window_handle].pop149      browser.switch_to.default_content150      @frame_handles[browser.window_handle].each { |fh| browser.switch_to.frame(fh) }151    else152      @frame_handles[browser.window_handle] ||= []153      @frame_handles[browser.window_handle] << frame.native154      browser.switch_to.frame(frame.native)155    end156  end157  def current_window_handle158    browser.window_handle159  end160  def window_size(handle)161    within_given_window(handle) do162      size = browser.manage.window.size163      [size.width, size.height]164    end165  end166  def resize_window_to(handle, width, height)167    within_given_window(handle) do168      # Don't set the size if already set - See https://github.com/mozilla/geckodriver/issues/643169      if marionette? && (window_size(handle) == [width, height])170        {}171      else172        browser.manage.window.resize_to(width, height)173      end174    end175  end176  def maximize_window(handle)177    within_given_window(handle) do178      browser.manage.window.maximize179    end180    sleep 0.1 # work around for https://code.google.com/p/selenium/issues/detail?id=7405181  end182  def close_window(handle)183    within_given_window(handle) do184      browser.close185    end186  end187  def window_handles188    browser.window_handles189  end190  def open_new_window191    browser.execute_script('window.open();')192  end193  def switch_to_window(handle)194    browser.switch_to.window handle195  end196  def within_window(locator)197    handle = find_window(locator)198    browser.switch_to.window(handle) { yield }199  end200  def accept_modal(_type, options={})201    yield if block_given?202    modal = find_modal(options)203    modal.send_keys options[:with] if options[:with]204    message = modal.text205    modal.accept206    message207  end208  def dismiss_modal(_type, options={})209    yield if block_given?210    modal = find_modal(options)211    message = modal.text212    modal.dismiss213    message214  end215  def quit216    @browser.quit if @browser217  rescue Selenium::WebDriver::Error::SessionNotCreatedError, Errno::ECONNREFUSED218    # Browser must have already gone219  rescue Selenium::WebDriver::Error::UnknownError => e220    unless silenced_unknown_error_message?(e.message) # Most likely already gone221      # probably already gone but not sure - so warn222      warn "Ignoring Selenium UnknownError during driver quit: #{e.message}"223    end224  ensure225    @browser = nil226  end227  def invalid_element_errors228    [::Selenium::WebDriver::Error::StaleElementReferenceError,229     ::Selenium::WebDriver::Error::UnhandledError,230     ::Selenium::WebDriver::Error::ElementNotVisibleError,231     ::Selenium::WebDriver::Error::InvalidSelectorError, # Work around a race condition that can occur with chromedriver and #go_back/#go_forward232     ::Selenium::WebDriver::Error::ElementNotInteractableError,233     ::Selenium::WebDriver::Error::ElementClickInterceptedError,234     ::Selenium::WebDriver::Error::InvalidElementStateError,235     ::Selenium::WebDriver::Error::ElementNotSelectableError,236    ]237  end238  def no_such_window_error239    Selenium::WebDriver::Error::NoSuchWindowError240  end241  # @api private242  def marionette?243    firefox? && browser && @w3c244  end245  # @api private246  def firefox?247    browser_name == "firefox"248  end249  # @api private250  def chrome?251    browser_name == "chrome"252  end253  # @deprecated This method is being removed254  def browser_initialized?255    super && !@browser.nil?256  end257  private258  # @api private259  def browser_name260    options[:browser].to_s261  end262  def modal_error263    if defined?(Selenium::WebDriver::Error::NoSuchAlertError)264      Selenium::WebDriver::Error::NoSuchAlertError265    else266      Selenium::WebDriver::Error::NoAlertPresentError267    end268  end269  def find_window(locator)270    handles = browser.window_handles271    return locator if handles.include? locator272    original_handle = browser.window_handle273    handles.each do |handle|274      switch_to_window(handle)275      if (locator == browser.execute_script("return window.name") ||276          browser.title.include?(locator) ||277          browser.current_url.include?(locator))278        switch_to_window(original_handle)279        return handle280      end281    end282    raise Capybara::ElementNotFound, "Could not find a window identified by #{locator}"283  end284  def insert_modal_handlers(accept, response_text)285    prompt_response = if accept286      if response_text.nil?287        "default_text"288      else289        "'#{response_text.gsub("\\", "\\\\\\").gsub("'", "\\\\'")}'"290      end291    else292      'null'293    end294    script = <<-JS295      if (typeof window.capybara  === 'undefined') {296        window.capybara = {297          modal_handlers: [],298          current_modal_status: function() {299            return [this.modal_handlers[0].called, this.modal_handlers[0].modal_text];300          },301          add_handler: function(handler) {302            this.modal_handlers.unshift(handler);303          },304          remove_handler: function(handler) {305            window.alert = handler.alert;306            window.confirm = handler.confirm;307            window.prompt = handler.prompt;308          },309          handler_called: function(handler, str) {310            handler.called = true;311            handler.modal_text = str;312            this.remove_handler(handler);313          }314        };315      };316      var modal_handler = {317        prompt: window.prompt,318        confirm: window.confirm,319        alert: window.alert,320        called: false321      }322      window.capybara.add_handler(modal_handler);323      window.alert = window.confirm = function(str = "") {324        window.capybara.handler_called(modal_handler, str.toString());325        return #{accept ? 'true' : 'false'};326      }327      window.prompt = function(str = "", default_text = "") {328        window.capybara.handler_called(modal_handler, str.toString());329        return #{prompt_response};330      }331    JS332    execute_script script333  end334  def within_given_window(handle)335    original_handle = self.current_window_handle336    if handle == original_handle337      yield338    else339      switch_to_window(handle)340      result = yield341      switch_to_window(original_handle)342      result343    end344  end345  def find_modal(options={})346    # Selenium has its own built in wait (2 seconds)for a modal to show up, so this wait is really the minimum time347    # Actual wait time may be longer than specified348    wait = Selenium::WebDriver::Wait.new(349      timeout: options.fetch(:wait, session_options.default_max_wait_time) || 0 ,350      ignore: modal_error)351    begin352      wait.until do353        alert = @browser.switch_to.alert354        regexp = options[:text].is_a?(Regexp) ? options[:text] : Regexp.escape(options[:text].to_s)355        alert.text.match(regexp) ? alert : nil356      end357    rescue Selenium::WebDriver::Error::TimeOutError358      raise Capybara::ModalNotFound.new("Unable to find modal dialog#{" with #{options[:text]}" if options[:text]}")359    end360  end361  def find_headless_modal(options={})362    # Selenium has its own built in wait (2 seconds)for a modal to show up, so this wait is really the minimum time363    # Actual wait time may be longer than specified364    wait = Selenium::WebDriver::Wait.new(365      timeout: options.fetch(:wait, session_options.default_max_wait_time) || 0 ,366      ignore: modal_error)367    begin368      wait.until do369        called, alert_text = evaluate_script('window.capybara && window.capybara.current_modal_status()')370        if called371          execute_script('window.capybara && window.capybara.modal_handlers.shift()')372          regexp = options[:text].is_a?(Regexp) ? options[:text] : Regexp.escape(options[:text].to_s)373          if alert_text.match(regexp)374            alert_text375          else376            raise Capybara::ModalNotFound.new("Unable to find modal dialog#{" with #{options[:text]}" if options[:text]}")377          end378        elsif called.nil?379          # page changed so modal_handler data has gone away380          warn "Can't verify modal text when page change occurs - ignoring" if options[:text]381          ""382        else383          nil...

Full Screen

Full Screen

test_environment.rb

Source:test_environment.rb Github

copy

Full Screen

...169          opt[:desired_capabilities] ||= remote_capabilities170          opt[:url] ||= ENV['WD_REMOTE_URL'] || remote_server.webdriver_url171          opt[:http_client] ||= keep_alive_client || http_client172          # https://bugs.chromium.org/p/chromedriver/issues/detail?id=2536173          # Current status can be found here (70% as of February 2019)174          # https://chromium.googlesource.com/chromium/src/+/master/docs/chromedriver_status.md175          # TODO: remove before Selenium 4 release176          opt[:options] ||= WebDriver::Chrome::Options.new(options: {w3c: true}) if browser == :chrome177          WebDriver::Driver.for(:remote, opt)178        end179        def create_firefox_driver(opt = {})180          WebDriver::Firefox::Binary.path = ENV['FIREFOX_BINARY'] if ENV['FIREFOX_BINARY']181          WebDriver::Driver.for :firefox, opt182        end183        def create_ie_driver(opt = {})184          opt[:desired_capabilities] ||= WebDriver::Remote::Capabilities.ie185          opt[:options] ||= WebDriver::IE::Options.new(require_window_focus: true)186          WebDriver::Driver.for :ie, opt187        end188        def create_chrome_driver(opt = {})189          binary = ENV['CHROME_BINARY']190          WebDriver::Chrome.path = binary if binary191          server = ENV['CHROMEDRIVER'] || ENV['chrome_server']192          WebDriver::Chrome::Service.driver_path = server if server193          # https://bugs.chromium.org/p/chromedriver/issues/detail?id=2536194          # Current status can be found here (70% as of February 2019)195          # https://chromium.googlesource.com/chromium/src/+/master/docs/chromedriver_status.md196          # TODO: remove before Selenium 4 release197          if opt[:options]198            opt[:options].add_option(:w3c, true)199          else200            opt[:options] = WebDriver::Chrome::Options.new(options: {w3c: true})201          end202          WebDriver::Driver.for :chrome, opt203        end204        def create_safari_preview_driver(opt = {})205          Safari.technology_preview!206          WebDriver::Driver.for :safari, opt207        end208        def keep_alive_client209          require 'selenium/webdriver/remote/http/persistent'...

Full Screen

Full Screen

bridge.rb

Source:bridge.rb Github

copy

Full Screen

...96        #97        def create_session(desired_capabilities)98          response = execute(:new_session, {}, merged_capabilities(desired_capabilities))99          @session_id = response['sessionId']100          oss_status = response['status'] # for compatibility with Appium 1.7.1-101          value = response['value']102          if value.is_a?(Hash) # include for W3C format103            @session_id = value['sessionId'] if value.key?('sessionId')104            if value.key?('capabilities')105              value = value['capabilities']106            elsif value.key?('value')107              value = value['value']108            end109          end110          raise ::Selenium::WebDriver::Error::WebDriverError, 'no sessionId in returned payload' unless @session_id111          json_create(oss_status, value)112        end113        # Append +appium:+ prefix for Appium following W3C spec114        # https://www.w3.org/TR/webdriver/#dfn-validate-capabilities115        #116        # @param [::Selenium::WebDriver::Remote::W3C::Capabilities, Hash] capabilities A capability117        # @return [::Selenium::WebDriver::Remote::W3C::Capabilities]118        def add_appium_prefix(capabilities)119          w3c_capabilities = ::Selenium::WebDriver::Remote::W3C::Capabilities.new120          capabilities = capabilities.__send__(:capabilities) unless capabilities.is_a?(Hash)121          capabilities.each do |name, value|122            next if value.nil?123            next if value.is_a?(String) && value.empty?124            capability_name = name.to_s125            w3c_name = extension_prefix?(capability_name) ? name : "#{APPIUM_PREFIX}#{capability_name}"126            w3c_capabilities[w3c_name] = value127          end128          w3c_capabilities129        end130        private131        def camel_case(str)132          str.gsub(/_([a-z])/) { Regexp.last_match(1).upcase }133        end134        def extension_prefix?(capability_name)135          snake_cased_capability_names = ::Selenium::WebDriver::Remote::W3C::Capabilities::KNOWN.map(&:to_s)136          camel_cased_capability_names = snake_cased_capability_names.map { |v| camel_case(v) }137          snake_cased_capability_names.include?(capability_name) ||138            camel_cased_capability_names.include?(capability_name) ||139            capability_name.match(::Selenium::WebDriver::Remote::W3C::Capabilities::EXTENSION_CAPABILITY_PATTERN)140        end141        def json_create(oss_status, value)142          if oss_status143            ::Selenium::WebDriver.logger.info 'Detected OSS dialect.'144            @dialect = :oss145            ::Selenium::WebDriver::Remote::Capabilities.json_create(value)146          else147            ::Selenium::WebDriver.logger.info 'Detected W3C dialect.'148            @dialect = :w3c149            ::Selenium::WebDriver::Remote::W3C::Capabilities.json_create(value)150          end151        end152        def delete_force_mjsonwp(capabilities)153          w3c_capabilities = ::Selenium::WebDriver::Remote::W3C::Capabilities.new154          capabilities = capabilities.__send__(:capabilities) unless capabilities.is_a?(Hash)155          capabilities.each do |name, value|156            next if value.nil?...

Full Screen

Full Screen

selenium_spec_chrome_remote.rb

Source:selenium_spec_chrome_remote.rb Github

copy

Full Screen

...46  # args => ["/path/to/file"]47  str = args.first.to_s48  str if File.exist?(str)49end50skipped_tests = %i[response_headers status_code trigger download]51Capybara::SpecHelper.run_specs TestSessions::Chrome, CHROME_REMOTE_DRIVER.to_s, capybara_skip: skipped_tests do |example|52  case example.metadata[:full_description]53  when 'Capybara::Session selenium_chrome_remote #attach_file with multipart form should not break when using HTML5 multiple file input uploading multiple files',54       'Capybara::Session selenium_chrome_remote #attach_file with multipart form should fire change once for each set of files uploaded',55       'Capybara::Session selenium_chrome_remote #attach_file with multipart form should fire change once when uploading multiple files from empty'56    pending "Selenium with Remote Chrome doesn't support multiple file upload" unless selenium_gte?(3.14)57  end58end59RSpec.describe 'Capybara::Session with remote Chrome' do60  include Capybara::SpecHelper61  include_examples  'Capybara::Session', TestSessions::Chrome, CHROME_REMOTE_DRIVER62  include_examples  Capybara::RSpecMatchers, TestSessions::Chrome, CHROME_REMOTE_DRIVER63  it 'is considered to be chrome' do64    expect(session.driver.browser.browser).to eq :chrome...

Full Screen

Full Screen

status

Using AI Code Generation

copy

Full Screen

1element = driver.find_element(:name, 'q')2element = driver.find_element(:name, 'q')3element = driver.find_element(:name, 'q')4element = driver.find_element(:name, 'q')5element = driver.find_element(:name, 'q')

Full Screen

Full Screen

status

Using AI Code Generation

copy

Full Screen

1element = driver.find_element(:name, 'q')2ruby 1.9.3p194 (2012-04-20) [i386-mingw32]3selenium-webdriver (2.13.0)4selenium-webdriver (2.13.0)5selenium-webdriver (2.13.0)6selenium-webdriver (2.13.0)7selenium-webdriver (2.13.0)8selenium-webdriver (2.13.0)9selenium-webdriver (2.13.0)10selenium-webdriver (2.13.0)11selenium-webdriver (2.13.0)12selenium-webdriver (2.13.0)

Full Screen

Full Screen

status

Using AI Code Generation

copy

Full Screen

1element = driver.find_element(:name, 'q')2element = driver.find_element(:name, 'q')3element = driver.find_element(:name, 'q')4element = driver.find_element(:name, 'q')5element = driver.find_element(:name, 'q')6element = driver.find_element(:name, 'q')

Full Screen

Full Screen

status

Using AI Code Generation

copy

Full Screen

1find_element(how, what)2search_box = driver.find_element(:name, "q")3search_button = driver.find_element(:name, "btnK")4find_elements(how, what)5links = driver.find_elements(:tag_name, "a")6send_keys(*args)

Full Screen

Full Screen

status

Using AI Code Generation

copy

Full Screen

1find_element(how, what)2search_box = driver.find_element(:name, "q")3search_button = driver.find_element(:name, "btnK")4find_elements(how, what)5links = driver.find_elements(:tag_name, "a")6send_keys(*args)

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Selenium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful