function_name
stringlengths
2
43
file_path
stringlengths
20
71
focal_code
stringlengths
176
2.2k
file_content
stringlengths
428
89.7k
language
stringclasses
1 value
function_component
dict
metadata
dict
using_session
capybara/lib/capybara.rb
def using_session(name_or_session, &block) previous_session = current_session previous_session_info = { specified_session: specified_session, session_name: session_name, current_driver: current_driver, app: app } self.specified_session = self.session_name = nil if name_or_session.is_a? Capybara::Session self.specified_session = name_or_session else self.session_name = name_or_session end if block.arity.zero? yield else yield current_session, previous_session end ensure self.session_name, self.specified_session = previous_session_info.values_at(:session_name, :specified_session) self.current_driver, self.app = previous_session_info.values_at(:current_driver, :app) if threadsafe end
# frozen_string_literal: true require 'timeout' require 'nokogiri' require 'xpath' require 'forwardable' require 'capybara/config' require 'capybara/registration_container' module Capybara class CapybaraError < StandardError; end class DriverNotFoundError < CapybaraError; end class FrozenInTime < CapybaraError; end class ElementNotFound < CapybaraError; end class ModalNotFound < CapybaraError; end class Ambiguous < ElementNotFound; end class ExpectationNotMet < ElementNotFound; end class FileNotFound < CapybaraError; end class UnselectNotAllowed < CapybaraError; end class NotSupportedByDriverError < CapybaraError; end class InfiniteRedirectError < CapybaraError; end class ScopeError < CapybaraError; end class WindowError < CapybaraError; end class ReadOnlyElementError < CapybaraError; end class << self extend Forwardable # DelegateCapybara global configurations # @!method app # See {Capybara.configure} # @!method reuse_server # See {Capybara.configure} # @!method threadsafe # See {Capybara.configure} # @!method server # See {Capybara.configure} # @!method default_driver # See {Capybara.configure} # @!method javascript_driver # See {Capybara.configure} # @!method use_html5_parsing # See {Capybara.configure} Config::OPTIONS.each do |method| def_delegators :config, method, "#{method}=" end # Delegate Capybara global configurations # @!method default_selector # See {Capybara.configure} # @!method default_max_wait_time # See {Capybara.configure} # @!method app_host # See {Capybara.configure} # @!method always_include_port # See {Capybara.configure} SessionConfig::OPTIONS.each do |method| def_delegators :config, method, "#{method}=" end ## # # Configure Capybara to suit your needs. # # Capybara.configure do |config| # config.run_server = false # config.app_host = 'http://www.google.com' # end # # #### Configurable options # # - **use_html5_parsing** (Boolean = `false`) - When Nokogiri >= 1.12.0 or `nokogumbo` is installed, whether HTML5 parsing will be used for HTML strings. # - **always_include_port** (Boolean = `false`) - Whether the Rack server's port should automatically be inserted into every visited URL # unless another port is explicitly specified. # - **app_host** (String, `nil`) - The default host to use when giving a relative URL to visit, must be a valid URL e.g. `http://www.example.com`. # - **asset_host** (String = `nil`) - Where dynamic assets are hosted - will be prepended to relative asset locations if present. # - **automatic_label_click** (Boolean = `false`) - Whether {Capybara::Node::Element#choose Element#choose}, {Capybara::Node::Element#check Element#check}, # {Capybara::Node::Element#uncheck Element#uncheck} will attempt to click the associated `<label>` element if the checkbox/radio button are non-visible. # - **automatic_reload** (Boolean = `true`) - Whether to automatically reload elements as Capybara is waiting. # - **default_max_wait_time** (Numeric = `2`) - The maximum number of seconds to wait for asynchronous processes to finish. # - **default_normalize_ws** (Boolean = `false`) - Whether text predicates and matchers use normalize whitespace behavior. # - **default_retry_interval** (Numeric = `0.01`) - The number of seconds to delay the next check in asynchronous processes. # - **default_selector** (`:css`, `:xpath` = `:css`) - Methods which take a selector use the given type by default. See also {Capybara::Selector}. # - **default_set_options** (Hash = `{}`) - The default options passed to {Capybara::Node::Element#set Element#set}. # - **enable_aria_label** (Boolean = `false`) - Whether fields, links, and buttons will match against `aria-label` attribute. # - **enable_aria_role** (Boolean = `false`) - Selectors will check for relevant aria role (currently only `button`). # - **exact** (Boolean = `false`) - Whether locators are matched exactly or with substrings. Only affects selector conditions # written using the `XPath#is` method. # - **exact_text** (Boolean = `false`) - Whether the text matchers and `:text` filter match exactly or on substrings. # - **ignore_hidden_elements** (Boolean = `true`) - Whether to ignore hidden elements on the page. # - **match** (`:one`, `:first`, `:prefer_exact`, `:smart` = `:smart`) - The matching strategy to find nodes. # - **predicates_wait** (Boolean = `true`) - Whether Capybara's predicate matchers use waiting behavior by default. # - **raise_server_errors** (Boolean = `true`) - Should errors raised in the server be raised in the tests? # - **reuse_server** (Boolean = `true`) - Whether to reuse the server thread between multiple sessions using the same app object. # - **run_server** (Boolean = `true`) - Whether to start a Rack server for the given Rack app. # - **save_path** (String = `Dir.pwd`) - Where to put pages saved through {Capybara::Session#save_page save_page}, {Capybara::Session#save_screenshot save_screenshot}, # {Capybara::Session#save_and_open_page save_and_open_page}, or {Capybara::Session#save_and_open_screenshot save_and_open_screenshot}. # - **server** (Symbol = `:default` (which uses puma)) - The name of the registered server to use when running the app under test. # - **server_port** (Integer) - The port Capybara will run the application server on, if not specified a random port will be used. # - **server_host** (String = "127.0.0.1") - The IP address Capybara will bind the application server to. If the test application is to be accessed from an external host, you will want to change this to "0.0.0.0" or to a more specific IP address that your test client can reach. # - **server_errors** (Array\<Class> = `[Exception]`) - Error classes that should be raised in the tests if they are raised in the server # and {configure raise_server_errors} is `true`. # - **test_id** (Symbol, String, `nil` = `nil`) - Optional attribute to match locator against with built-in selectors along with id. # - **threadsafe** (Boolean = `false`) - Whether sessions can be configured individually. # - **w3c_click_offset** (Boolean = 'true') - Whether click offsets should be from element center (true) or top left (false) # # #### DSL Options # # When using `capybara/dsl`, the following options are also available: # # - **default_driver** (Symbol = `:rack_test`) - The name of the driver to use by default. # - **javascript_driver** (Symbol = `:selenium`) - The name of a driver to use for JavaScript enabled tests. # def configure yield config end ## # # Register a new driver for Capybara. # # Capybara.register_driver :rack_test do |app| # Capybara::RackTest::Driver.new(app) # end # # @param [Symbol] name The name of the new driver # @yield [app] This block takes a rack app and returns a Capybara driver # @yieldparam [<Rack>] app The rack application that this driver runs against. May be nil. # @yieldreturn [Capybara::Driver::Base] A Capybara driver instance # def register_driver(name, &block) drivers.send(:register, name, block) end ## # # Register a new server for Capybara. # # Capybara.register_server :webrick do |app, port, host| # require 'rack/handler/webrick' # Rack::Handler::WEBrick.run(app, ...) # end # # @param [Symbol] name The name of the new driver # @yield [app, port, host] This block takes a rack app and a port and returns a rack server listening on that port # @yieldparam [<Rack>] app The rack application that this server will contain. # @yieldparam port The port number the server should listen on # @yieldparam host The host/ip to bind to # def register_server(name, &block) servers.send(:register, name.to_sym, block) end ## # # Add a new selector to Capybara. Selectors can be used by various methods in Capybara # to find certain elements on the page in a more convenient way. For example adding a # selector to find certain table rows might look like this: # # Capybara.add_selector(:row) do # xpath { |num| ".//tbody/tr[#{num}]" } # end # # This makes it possible to use this selector in a variety of ways: # # find(:row, 3) # page.find('table#myTable').find(:row, 3).text # page.find('table#myTable').has_selector?(:row, 3) # within(:row, 3) { expect(page).to have_content('$100.000') } # # Here is another example: # # Capybara.add_selector(:id) do # xpath { |id| XPath.descendant[XPath.attr(:id) == id.to_s] } # end # # Note that this particular selector already ships with Capybara. # # @param [Symbol] name The name of the selector to add # @yield A block executed in the context of the new {Capybara::Selector} # def add_selector(name, **options, &block) Capybara::Selector.add(name, **options, &block) end ## # # Modify a selector previously created by {Capybara.add_selector}. # For example, adding a new filter to the :button selector to filter based on # button style (a class) might look like this # # Capybara.modify_selector(:button) do # filter (:btn_style, valid_values: [:primary, :secondary]) { |node, style| node[:class].split.include? "btn-#{style}" } # end # # # @param [Symbol] name The name of the selector to modify # @yield A block executed in the context of the existing {Capybara::Selector} # def modify_selector(name, &block) Capybara::Selector.update(name, &block) end def drivers @drivers ||= RegistrationContainer.new end def servers @servers ||= RegistrationContainer.new end # Wraps the given string, which should contain an HTML document or fragment # in a {Capybara::Node::Simple} which exposes all {Capybara::Node::Matchers}, # {Capybara::Node::Finders} and {Capybara::Node::DocumentMatchers}. This allows you to query # any string containing HTML in the exact same way you would query the current document in a Capybara # session. # # @example A single element # node = Capybara.string('<a href="foo">bar</a>') # anchor = node.first('a') # anchor[:href] #=> 'foo' # anchor.text #=> 'bar' # # @example Multiple elements # node = Capybara.string <<-HTML # <ul> # <li id="home">Home</li> # <li id="projects">Projects</li> # </ul> # HTML # # node.find('#projects').text # => 'Projects' # node.has_selector?('li#home', text: 'Home') # node.has_selector?('#projects') # node.find('ul').find('li:first-child').text # => 'Home' # # @param [String] html An html fragment or document # @return [Capybara::Node::Simple] A node which has Capybara's finders and matchers # def string(html) Capybara::Node::Simple.new(html) end ## # # Runs Capybara's default server for the given application and port # under most circumstances you should not have to call this method # manually. # # @param [Rack Application] app The rack application to run # @param [Integer] port The port to run the application on # def run_default_server(app, port) servers[:puma].call(app, port, server_host) end ## # # @return [Symbol] The name of the driver currently in use # def current_driver if threadsafe Thread.current.thread_variable_get :capybara_current_driver else @current_driver end || default_driver end alias_method :mode, :current_driver def current_driver=(name) if threadsafe Thread.current.thread_variable_set :capybara_current_driver, name else @current_driver = name end end ## # # Use the default driver as the current driver # def use_default_driver self.current_driver = nil end ## # # Yield a block using a specific driver # def using_driver(driver) previous_driver = Capybara.current_driver Capybara.current_driver = driver yield ensure self.current_driver = previous_driver end ## # # Yield a block using a specific wait time # def using_wait_time(seconds) previous_wait_time = Capybara.default_max_wait_time Capybara.default_max_wait_time = seconds yield ensure Capybara.default_max_wait_time = previous_wait_time end ## # # The current {Capybara::Session} based on what is set as {app} and {current_driver}. # # @return [Capybara::Session] The currently used session # def current_session specified_session || session_pool["#{current_driver}:#{session_name}:#{app.object_id}"] end ## # # Reset sessions, cleaning out the pool of sessions. This will remove any session information such # as cookies. # def reset_sessions! # reset in reverse so sessions that started servers are reset last session_pool.reverse_each { |_mode, session| session.reset! } end alias_method :reset!, :reset_sessions! ## # # The current session name. # # @return [Symbol] The name of the currently used session. # def session_name if threadsafe Thread.current.thread_variable_get(:capybara_session_name) || Thread.current.thread_variable_set(:capybara_session_name, :default) else @session_name ||= :default end end def session_name=(name) if threadsafe Thread.current.thread_variable_set :capybara_session_name, name else @session_name = name end end ## # # Yield a block using a specific session name or {Capybara::Session} instance. # def using_session(name_or_session, &block) previous_session = current_session previous_session_info = { specified_session: specified_session, session_name: session_name, current_driver: current_driver, app: app } self.specified_session = self.session_name = nil if name_or_session.is_a? Capybara::Session self.specified_session = name_or_session else self.session_name = name_or_session end if block.arity.zero? yield else yield current_session, previous_session end ensure self.session_name, self.specified_session = previous_session_info.values_at(:session_name, :specified_session) self.current_driver, self.app = previous_session_info.values_at(:current_driver, :app) if threadsafe end ## # # Parse raw html into a document using Nokogiri, and adjust textarea contents as defined by the spec. # # @param [String] html The raw html # @return [Nokogiri::HTML::Document] HTML document # def HTML(html) # rubocop:disable Naming/MethodName # Nokogiri >= 1.12.0 or Nokogumbo installed and allowed for use html_parser, using_html5 = if defined?(Nokogiri::HTML5) && Capybara.use_html5_parsing [Nokogiri::HTML5, true] else [defined?(Nokogiri::HTML4) ? Nokogiri::HTML4 : Nokogiri::HTML, false] end html_parser.parse(html).tap do |document| document.xpath('//template').each do |template| # template elements content is not part of the document template.inner_html = '' end document.xpath('//textarea').each do |textarea| # The Nokogiri HTML5 parser already returns spec compliant contents textarea['_capybara_raw_value'] = using_html5 ? textarea.content : textarea.content.delete_prefix("\n") end end end def session_options config.session_options end private def config @config ||= Capybara::Config.new end def session_pool @session_pool ||= Hash.new do |hash, name| hash[name] = Capybara::Session.new(current_driver, app) end end def specified_session if threadsafe Thread.current.thread_variable_get :capybara_specified_session else @specified_session ||= nil end end def specified_session=(session) if threadsafe Thread.current.thread_variable_set :capybara_specified_session, session else @specified_session = session end end end self.default_driver = nil self.current_driver = nil self.server_host = nil module Driver; end module RackTest; end module Selenium; end require 'capybara/helpers' require 'capybara/session' require 'capybara/window' require 'capybara/server' require 'capybara/selector' require 'capybara/result' require 'capybara/version' require 'capybara/queries/base_query' require 'capybara/queries/selector_query' require 'capybara/queries/text_query' require 'capybara/queries/title_query' require 'capybara/queries/current_path_query' require 'capybara/queries/match_query' require 'capybara/queries/ancestor_query' require 'capybara/queries/sibling_query' require 'capybara/queries/style_query' require 'capybara/queries/active_element_query' require 'capybara/node/finders' require 'capybara/node/matchers' require 'capybara/node/actions' require 'capybara/node/document_matchers' require 'capybara/node/simple' require 'capybara/node/base' require 'capybara/node/element' require 'capybara/node/document' require 'capybara/driver/base' require 'capybara/driver/node' require 'capybara/rack_test/driver' require 'capybara/rack_test/node' require 'capybara/rack_test/form' require 'capybara/rack_test/browser' require 'capybara/rack_test/css_handlers' require 'capybara/selenium/node' require 'capybara/selenium/driver' end require 'capybara/registrations/servers' require 'capybara/registrations/drivers' Capybara.configure do |config| config.always_include_port = false config.run_server = true config.server = :default config.default_selector = :css config.default_max_wait_time = 2 config.default_retry_interval = 0.01 config.ignore_hidden_elements = true config.default_host = 'http://www.example.com' config.automatic_reload = true config.match = :smart config.exact = false config.exact_text = false config.raise_server_errors = true config.server_errors = [Exception] config.visible_text_only = false config.automatic_label_click = false config.enable_aria_label = false config.enable_aria_role = false config.reuse_server = true config.default_set_options = {} config.test_id = nil config.predicates_wait = true config.default_normalize_ws = false config.use_html5_parsing = false config.w3c_click_offset = true end
Ruby
{ "end_line": 381, "name": "using_session", "signature": "def using_session(name_or_session, &block)", "start_line": 358 }
{ "class_name": "", "class_signature": "", "module": "Capybara" }
HTML
capybara/lib/capybara.rb
def HTML(html) # rubocop:disable Naming/MethodName # Nokogiri >= 1.12.0 or Nokogumbo installed and allowed for use html_parser, using_html5 = if defined?(Nokogiri::HTML5) && Capybara.use_html5_parsing [Nokogiri::HTML5, true] else [defined?(Nokogiri::HTML4) ? Nokogiri::HTML4 : Nokogiri::HTML, false] end html_parser.parse(html).tap do |document| document.xpath('//template').each do |template| # template elements content is not part of the document template.inner_html = '' end document.xpath('//textarea').each do |textarea| # The Nokogiri HTML5 parser already returns spec compliant contents textarea['_capybara_raw_value'] = using_html5 ? textarea.content : textarea.content.delete_prefix("\n") end end end
# frozen_string_literal: true require 'timeout' require 'nokogiri' require 'xpath' require 'forwardable' require 'capybara/config' require 'capybara/registration_container' module Capybara class CapybaraError < StandardError; end class DriverNotFoundError < CapybaraError; end class FrozenInTime < CapybaraError; end class ElementNotFound < CapybaraError; end class ModalNotFound < CapybaraError; end class Ambiguous < ElementNotFound; end class ExpectationNotMet < ElementNotFound; end class FileNotFound < CapybaraError; end class UnselectNotAllowed < CapybaraError; end class NotSupportedByDriverError < CapybaraError; end class InfiniteRedirectError < CapybaraError; end class ScopeError < CapybaraError; end class WindowError < CapybaraError; end class ReadOnlyElementError < CapybaraError; end class << self extend Forwardable # DelegateCapybara global configurations # @!method app # See {Capybara.configure} # @!method reuse_server # See {Capybara.configure} # @!method threadsafe # See {Capybara.configure} # @!method server # See {Capybara.configure} # @!method default_driver # See {Capybara.configure} # @!method javascript_driver # See {Capybara.configure} # @!method use_html5_parsing # See {Capybara.configure} Config::OPTIONS.each do |method| def_delegators :config, method, "#{method}=" end # Delegate Capybara global configurations # @!method default_selector # See {Capybara.configure} # @!method default_max_wait_time # See {Capybara.configure} # @!method app_host # See {Capybara.configure} # @!method always_include_port # See {Capybara.configure} SessionConfig::OPTIONS.each do |method| def_delegators :config, method, "#{method}=" end ## # # Configure Capybara to suit your needs. # # Capybara.configure do |config| # config.run_server = false # config.app_host = 'http://www.google.com' # end # # #### Configurable options # # - **use_html5_parsing** (Boolean = `false`) - When Nokogiri >= 1.12.0 or `nokogumbo` is installed, whether HTML5 parsing will be used for HTML strings. # - **always_include_port** (Boolean = `false`) - Whether the Rack server's port should automatically be inserted into every visited URL # unless another port is explicitly specified. # - **app_host** (String, `nil`) - The default host to use when giving a relative URL to visit, must be a valid URL e.g. `http://www.example.com`. # - **asset_host** (String = `nil`) - Where dynamic assets are hosted - will be prepended to relative asset locations if present. # - **automatic_label_click** (Boolean = `false`) - Whether {Capybara::Node::Element#choose Element#choose}, {Capybara::Node::Element#check Element#check}, # {Capybara::Node::Element#uncheck Element#uncheck} will attempt to click the associated `<label>` element if the checkbox/radio button are non-visible. # - **automatic_reload** (Boolean = `true`) - Whether to automatically reload elements as Capybara is waiting. # - **default_max_wait_time** (Numeric = `2`) - The maximum number of seconds to wait for asynchronous processes to finish. # - **default_normalize_ws** (Boolean = `false`) - Whether text predicates and matchers use normalize whitespace behavior. # - **default_retry_interval** (Numeric = `0.01`) - The number of seconds to delay the next check in asynchronous processes. # - **default_selector** (`:css`, `:xpath` = `:css`) - Methods which take a selector use the given type by default. See also {Capybara::Selector}. # - **default_set_options** (Hash = `{}`) - The default options passed to {Capybara::Node::Element#set Element#set}. # - **enable_aria_label** (Boolean = `false`) - Whether fields, links, and buttons will match against `aria-label` attribute. # - **enable_aria_role** (Boolean = `false`) - Selectors will check for relevant aria role (currently only `button`). # - **exact** (Boolean = `false`) - Whether locators are matched exactly or with substrings. Only affects selector conditions # written using the `XPath#is` method. # - **exact_text** (Boolean = `false`) - Whether the text matchers and `:text` filter match exactly or on substrings. # - **ignore_hidden_elements** (Boolean = `true`) - Whether to ignore hidden elements on the page. # - **match** (`:one`, `:first`, `:prefer_exact`, `:smart` = `:smart`) - The matching strategy to find nodes. # - **predicates_wait** (Boolean = `true`) - Whether Capybara's predicate matchers use waiting behavior by default. # - **raise_server_errors** (Boolean = `true`) - Should errors raised in the server be raised in the tests? # - **reuse_server** (Boolean = `true`) - Whether to reuse the server thread between multiple sessions using the same app object. # - **run_server** (Boolean = `true`) - Whether to start a Rack server for the given Rack app. # - **save_path** (String = `Dir.pwd`) - Where to put pages saved through {Capybara::Session#save_page save_page}, {Capybara::Session#save_screenshot save_screenshot}, # {Capybara::Session#save_and_open_page save_and_open_page}, or {Capybara::Session#save_and_open_screenshot save_and_open_screenshot}. # - **server** (Symbol = `:default` (which uses puma)) - The name of the registered server to use when running the app under test. # - **server_port** (Integer) - The port Capybara will run the application server on, if not specified a random port will be used. # - **server_host** (String = "127.0.0.1") - The IP address Capybara will bind the application server to. If the test application is to be accessed from an external host, you will want to change this to "0.0.0.0" or to a more specific IP address that your test client can reach. # - **server_errors** (Array\<Class> = `[Exception]`) - Error classes that should be raised in the tests if they are raised in the server # and {configure raise_server_errors} is `true`. # - **test_id** (Symbol, String, `nil` = `nil`) - Optional attribute to match locator against with built-in selectors along with id. # - **threadsafe** (Boolean = `false`) - Whether sessions can be configured individually. # - **w3c_click_offset** (Boolean = 'true') - Whether click offsets should be from element center (true) or top left (false) # # #### DSL Options # # When using `capybara/dsl`, the following options are also available: # # - **default_driver** (Symbol = `:rack_test`) - The name of the driver to use by default. # - **javascript_driver** (Symbol = `:selenium`) - The name of a driver to use for JavaScript enabled tests. # def configure yield config end ## # # Register a new driver for Capybara. # # Capybara.register_driver :rack_test do |app| # Capybara::RackTest::Driver.new(app) # end # # @param [Symbol] name The name of the new driver # @yield [app] This block takes a rack app and returns a Capybara driver # @yieldparam [<Rack>] app The rack application that this driver runs against. May be nil. # @yieldreturn [Capybara::Driver::Base] A Capybara driver instance # def register_driver(name, &block) drivers.send(:register, name, block) end ## # # Register a new server for Capybara. # # Capybara.register_server :webrick do |app, port, host| # require 'rack/handler/webrick' # Rack::Handler::WEBrick.run(app, ...) # end # # @param [Symbol] name The name of the new driver # @yield [app, port, host] This block takes a rack app and a port and returns a rack server listening on that port # @yieldparam [<Rack>] app The rack application that this server will contain. # @yieldparam port The port number the server should listen on # @yieldparam host The host/ip to bind to # def register_server(name, &block) servers.send(:register, name.to_sym, block) end ## # # Add a new selector to Capybara. Selectors can be used by various methods in Capybara # to find certain elements on the page in a more convenient way. For example adding a # selector to find certain table rows might look like this: # # Capybara.add_selector(:row) do # xpath { |num| ".//tbody/tr[#{num}]" } # end # # This makes it possible to use this selector in a variety of ways: # # find(:row, 3) # page.find('table#myTable').find(:row, 3).text # page.find('table#myTable').has_selector?(:row, 3) # within(:row, 3) { expect(page).to have_content('$100.000') } # # Here is another example: # # Capybara.add_selector(:id) do # xpath { |id| XPath.descendant[XPath.attr(:id) == id.to_s] } # end # # Note that this particular selector already ships with Capybara. # # @param [Symbol] name The name of the selector to add # @yield A block executed in the context of the new {Capybara::Selector} # def add_selector(name, **options, &block) Capybara::Selector.add(name, **options, &block) end ## # # Modify a selector previously created by {Capybara.add_selector}. # For example, adding a new filter to the :button selector to filter based on # button style (a class) might look like this # # Capybara.modify_selector(:button) do # filter (:btn_style, valid_values: [:primary, :secondary]) { |node, style| node[:class].split.include? "btn-#{style}" } # end # # # @param [Symbol] name The name of the selector to modify # @yield A block executed in the context of the existing {Capybara::Selector} # def modify_selector(name, &block) Capybara::Selector.update(name, &block) end def drivers @drivers ||= RegistrationContainer.new end def servers @servers ||= RegistrationContainer.new end # Wraps the given string, which should contain an HTML document or fragment # in a {Capybara::Node::Simple} which exposes all {Capybara::Node::Matchers}, # {Capybara::Node::Finders} and {Capybara::Node::DocumentMatchers}. This allows you to query # any string containing HTML in the exact same way you would query the current document in a Capybara # session. # # @example A single element # node = Capybara.string('<a href="foo">bar</a>') # anchor = node.first('a') # anchor[:href] #=> 'foo' # anchor.text #=> 'bar' # # @example Multiple elements # node = Capybara.string <<-HTML # <ul> # <li id="home">Home</li> # <li id="projects">Projects</li> # </ul> # HTML # # node.find('#projects').text # => 'Projects' # node.has_selector?('li#home', text: 'Home') # node.has_selector?('#projects') # node.find('ul').find('li:first-child').text # => 'Home' # # @param [String] html An html fragment or document # @return [Capybara::Node::Simple] A node which has Capybara's finders and matchers # def string(html) Capybara::Node::Simple.new(html) end ## # # Runs Capybara's default server for the given application and port # under most circumstances you should not have to call this method # manually. # # @param [Rack Application] app The rack application to run # @param [Integer] port The port to run the application on # def run_default_server(app, port) servers[:puma].call(app, port, server_host) end ## # # @return [Symbol] The name of the driver currently in use # def current_driver if threadsafe Thread.current.thread_variable_get :capybara_current_driver else @current_driver end || default_driver end alias_method :mode, :current_driver def current_driver=(name) if threadsafe Thread.current.thread_variable_set :capybara_current_driver, name else @current_driver = name end end ## # # Use the default driver as the current driver # def use_default_driver self.current_driver = nil end ## # # Yield a block using a specific driver # def using_driver(driver) previous_driver = Capybara.current_driver Capybara.current_driver = driver yield ensure self.current_driver = previous_driver end ## # # Yield a block using a specific wait time # def using_wait_time(seconds) previous_wait_time = Capybara.default_max_wait_time Capybara.default_max_wait_time = seconds yield ensure Capybara.default_max_wait_time = previous_wait_time end ## # # The current {Capybara::Session} based on what is set as {app} and {current_driver}. # # @return [Capybara::Session] The currently used session # def current_session specified_session || session_pool["#{current_driver}:#{session_name}:#{app.object_id}"] end ## # # Reset sessions, cleaning out the pool of sessions. This will remove any session information such # as cookies. # def reset_sessions! # reset in reverse so sessions that started servers are reset last session_pool.reverse_each { |_mode, session| session.reset! } end alias_method :reset!, :reset_sessions! ## # # The current session name. # # @return [Symbol] The name of the currently used session. # def session_name if threadsafe Thread.current.thread_variable_get(:capybara_session_name) || Thread.current.thread_variable_set(:capybara_session_name, :default) else @session_name ||= :default end end def session_name=(name) if threadsafe Thread.current.thread_variable_set :capybara_session_name, name else @session_name = name end end ## # # Yield a block using a specific session name or {Capybara::Session} instance. # def using_session(name_or_session, &block) previous_session = current_session previous_session_info = { specified_session: specified_session, session_name: session_name, current_driver: current_driver, app: app } self.specified_session = self.session_name = nil if name_or_session.is_a? Capybara::Session self.specified_session = name_or_session else self.session_name = name_or_session end if block.arity.zero? yield else yield current_session, previous_session end ensure self.session_name, self.specified_session = previous_session_info.values_at(:session_name, :specified_session) self.current_driver, self.app = previous_session_info.values_at(:current_driver, :app) if threadsafe end ## # # Parse raw html into a document using Nokogiri, and adjust textarea contents as defined by the spec. # # @param [String] html The raw html # @return [Nokogiri::HTML::Document] HTML document # def HTML(html) # rubocop:disable Naming/MethodName # Nokogiri >= 1.12.0 or Nokogumbo installed and allowed for use html_parser, using_html5 = if defined?(Nokogiri::HTML5) && Capybara.use_html5_parsing [Nokogiri::HTML5, true] else [defined?(Nokogiri::HTML4) ? Nokogiri::HTML4 : Nokogiri::HTML, false] end html_parser.parse(html).tap do |document| document.xpath('//template').each do |template| # template elements content is not part of the document template.inner_html = '' end document.xpath('//textarea').each do |textarea| # The Nokogiri HTML5 parser already returns spec compliant contents textarea['_capybara_raw_value'] = using_html5 ? textarea.content : textarea.content.delete_prefix("\n") end end end def session_options config.session_options end private def config @config ||= Capybara::Config.new end def session_pool @session_pool ||= Hash.new do |hash, name| hash[name] = Capybara::Session.new(current_driver, app) end end def specified_session if threadsafe Thread.current.thread_variable_get :capybara_specified_session else @specified_session ||= nil end end def specified_session=(session) if threadsafe Thread.current.thread_variable_set :capybara_specified_session, session else @specified_session = session end end end self.default_driver = nil self.current_driver = nil self.server_host = nil module Driver; end module RackTest; end module Selenium; end require 'capybara/helpers' require 'capybara/session' require 'capybara/window' require 'capybara/server' require 'capybara/selector' require 'capybara/result' require 'capybara/version' require 'capybara/queries/base_query' require 'capybara/queries/selector_query' require 'capybara/queries/text_query' require 'capybara/queries/title_query' require 'capybara/queries/current_path_query' require 'capybara/queries/match_query' require 'capybara/queries/ancestor_query' require 'capybara/queries/sibling_query' require 'capybara/queries/style_query' require 'capybara/queries/active_element_query' require 'capybara/node/finders' require 'capybara/node/matchers' require 'capybara/node/actions' require 'capybara/node/document_matchers' require 'capybara/node/simple' require 'capybara/node/base' require 'capybara/node/element' require 'capybara/node/document' require 'capybara/driver/base' require 'capybara/driver/node' require 'capybara/rack_test/driver' require 'capybara/rack_test/node' require 'capybara/rack_test/form' require 'capybara/rack_test/browser' require 'capybara/rack_test/css_handlers' require 'capybara/selenium/node' require 'capybara/selenium/driver' end require 'capybara/registrations/servers' require 'capybara/registrations/drivers' Capybara.configure do |config| config.always_include_port = false config.run_server = true config.server = :default config.default_selector = :css config.default_max_wait_time = 2 config.default_retry_interval = 0.01 config.ignore_hidden_elements = true config.default_host = 'http://www.example.com' config.automatic_reload = true config.match = :smart config.exact = false config.exact_text = false config.raise_server_errors = true config.server_errors = [Exception] config.visible_text_only = false config.automatic_label_click = false config.enable_aria_label = false config.enable_aria_role = false config.reuse_server = true config.default_set_options = {} config.test_id = nil config.predicates_wait = true config.default_normalize_ws = false config.use_html5_parsing = false config.w3c_click_offset = true end
Ruby
{ "end_line": 408, "name": "HTML", "signature": "def HTML(html) # rubocop:disable Naming/MethodName", "start_line": 390 }
{ "class_name": "", "class_signature": "", "module": "Capybara" }
server=
capybara/lib/capybara/config.rb
def server=(name) name, options = *name if name.is_a? Array @server = if name.respond_to? :call name elsif options proc { |app, port, host| Capybara.servers[name.to_sym].call(app, port, host, **options) } else Capybara.servers[name.to_sym] end end
# frozen_string_literal: true require 'forwardable' require 'capybara/session/config' module Capybara class Config extend Forwardable OPTIONS = %i[ app reuse_server threadsafe server default_driver javascript_driver use_html5_parsing allow_gumbo ].freeze attr_accessor :app, :use_html5_parsing attr_reader :reuse_server, :threadsafe, :session_options # rubocop:disable Style/BisectedAttrAccessor attr_writer :default_driver, :javascript_driver SessionConfig::OPTIONS.each do |method| def_delegators :session_options, method, "#{method}=" end def initialize @session_options = Capybara::SessionConfig.new @javascript_driver = nil end attr_writer :reuse_server # rubocop:disable Style/BisectedAttrAccessor def threadsafe=(bool) if (bool != threadsafe) && Session.instance_created? raise 'Threadsafe setting cannot be changed once a session is created' end @threadsafe = bool end ## # # Return the proc that Capybara will call to run the Rack application. # The block returned receives a rack app, port, and host/ip and should run a Rack handler # By default, Capybara will try to use puma. # attr_reader :server ## # # Set the server to use. # # Capybara.server = :webrick # Capybara.server = :puma, { Silent: true } # # @overload server=(name) # @param [Symbol] name Name of the server type to use # @overload server=([name, options]) # @param [Symbol] name Name of the server type to use # @param [Hash] options Options to pass to the server block # @see register_server # def server=(name) name, options = *name if name.is_a? Array @server = if name.respond_to? :call name elsif options proc { |app, port, host| Capybara.servers[name.to_sym].call(app, port, host, **options) } else Capybara.servers[name.to_sym] end end ## # # @return [Symbol] The name of the driver to use by default # def default_driver @default_driver || :rack_test end ## # # @return [Symbol] The name of the driver used when JavaScript is needed # def javascript_driver @javascript_driver || :selenium end def deprecate(method, alternate_method, once: false) @deprecation_notified ||= {} unless once && @deprecation_notified[method] Capybara::Helpers.warn "DEPRECATED: ##{method} is deprecated, please use ##{alternate_method} instead: #{Capybara::Helpers.filter_backtrace(caller)}" end @deprecation_notified[method] = true end def allow_gumbo=(val) deprecate('allow_gumbo=', 'use_html5_parsing=') self.use_html5_parsing = val end def allow_gumbo deprecate('allow_gumbo', 'use_html5_parsing') use_html5_parsing end end end
Ruby
{ "end_line": 68, "name": "server=", "signature": "def server=(name)", "start_line": 59 }
{ "class_name": "Config", "class_signature": "class Config", "module": "Capybara" }
each
capybara/lib/capybara/result.rb
def each(&block) return enum_for(:each) unless block @result_cache.each(&block) loop do next_result = @results_enum.next add_to_cache(next_result) yield next_result end self end
# frozen_string_literal: true require 'forwardable' module Capybara ## # A {Capybara::Result} represents a collection of {Capybara::Node::Element} on the page. It is possible to interact with this # collection similar to an Array because it implements Enumerable and offers the following Array methods through delegation: # # * \[\] # * each() # * at() # * size() # * count() # * length() # * first() # * last() # * empty?() # * values_at() # * sample() # # @see Capybara::Node::Element # class Result include Enumerable extend Forwardable def initialize(elements, query) @elements = elements @result_cache = [] @filter_errors = [] @results_enum = lazy_select_elements { |node| query.matches_filters?(node, @filter_errors) } @query = query @allow_reload = false end def_delegators :full_results, :size, :length, :last, :values_at, :inspect, :sample, :to_ary alias index find_index def each(&block) return enum_for(:each) unless block @result_cache.each(&block) loop do next_result = @results_enum.next add_to_cache(next_result) yield next_result end self end def [](*args) idx, length = args max_idx = case idx when Integer if idx.negative? nil else length.nil? ? idx : idx + length - 1 end when Range # idx.max is broken with beginless ranges # idx.end && idx.max # endless range will have end == nil max = idx.end max = nil if max&.negative? max -= 1 if max && idx.exclude_end? max end if max_idx.nil? full_results[*args] else load_up_to(max_idx + 1) @result_cache[*args] end end alias :at :[] def empty? !any? end def compare_count return 0 unless @query count, min, max, between = @query.options.values_at(:count, :minimum, :maximum, :between) # Only check filters for as many elements as necessary to determine result if count && (count = Integer(count)) return load_up_to(count + 1) <=> count end return -1 if min && (min = Integer(min)) && (load_up_to(min) < min) return 1 if max && (max = Integer(max)) && (load_up_to(max + 1) > max) if between min, max = (between.begin && between.min) || 1, between.end max -= 1 if max && between.exclude_end? size = load_up_to(max ? max + 1 : min) return size <=> min unless between.include?(size) end 0 end def matches_count? compare_count.zero? end def failure_message message = @query.failure_message if count.zero? message << ' but there were no matches' else message << ", found #{count} #{Capybara::Helpers.declension('match', 'matches', count)}: " \ << full_results.map { |r| r.text.inspect }.join(', ') end unless rest.empty? elements = rest.map { |el| el.text rescue '<<ERROR>>' }.map(&:inspect).join(', ') # rubocop:disable Style/RescueModifier message << '. Also found ' << elements << ', which matched the selector but not all filters. ' message << @filter_errors.join('. ') if (rest.size == 1) && count.zero? end message end def negative_failure_message failure_message.sub(/(to find)/, 'not \1') end def unfiltered_size @elements.length end ## # @api private # def allow_reload! @allow_reload = true self end private def add_to_cache(elem) elem.allow_reload!(@result_cache.size) if @allow_reload @result_cache << elem end def load_up_to(num) loop do break if @result_cache.size >= num add_to_cache(@results_enum.next) end @result_cache.size end def full_results loop { @result_cache << @results_enum.next } @result_cache end def rest @rest ||= @elements - full_results end if RUBY_PLATFORM == 'java' # JRuby < 9.2.8.0 has an issue with lazy enumerators which # causes a concurrency issue with network requests here # https://github.com/jruby/jruby/issues/4212 # while JRuby >= 9.2.8.0 leaks threads when using lazy enumerators # https://github.com/teamcapybara/capybara/issues/2349 # so disable the use and JRuby users will need to pay a performance penalty def lazy_select_elements(&block) @elements.select(&block).to_enum # non-lazy evaluation end else def lazy_select_elements(&block) @elements.lazy.select(&block) end end end end
Ruby
{ "end_line": 51, "name": "each", "signature": "def each(&block)", "start_line": 41 }
{ "class_name": "Result", "class_signature": "class Result", "module": "Capybara" }
[]
capybara/lib/capybara/result.rb
def [](*args) idx, length = args max_idx = case idx when Integer if idx.negative? nil else length.nil? ? idx : idx + length - 1 end when Range # idx.max is broken with beginless ranges # idx.end && idx.max # endless range will have end == nil max = idx.end max = nil if max&.negative? max -= 1 if max && idx.exclude_end? max end if max_idx.nil? full_results[*args] else load_up_to(max_idx + 1) @result_cache[*args] end end
# frozen_string_literal: true require 'forwardable' module Capybara ## # A {Capybara::Result} represents a collection of {Capybara::Node::Element} on the page. It is possible to interact with this # collection similar to an Array because it implements Enumerable and offers the following Array methods through delegation: # # * \[\] # * each() # * at() # * size() # * count() # * length() # * first() # * last() # * empty?() # * values_at() # * sample() # # @see Capybara::Node::Element # class Result include Enumerable extend Forwardable def initialize(elements, query) @elements = elements @result_cache = [] @filter_errors = [] @results_enum = lazy_select_elements { |node| query.matches_filters?(node, @filter_errors) } @query = query @allow_reload = false end def_delegators :full_results, :size, :length, :last, :values_at, :inspect, :sample, :to_ary alias index find_index def each(&block) return enum_for(:each) unless block @result_cache.each(&block) loop do next_result = @results_enum.next add_to_cache(next_result) yield next_result end self end def [](*args) idx, length = args max_idx = case idx when Integer if idx.negative? nil else length.nil? ? idx : idx + length - 1 end when Range # idx.max is broken with beginless ranges # idx.end && idx.max # endless range will have end == nil max = idx.end max = nil if max&.negative? max -= 1 if max && idx.exclude_end? max end if max_idx.nil? full_results[*args] else load_up_to(max_idx + 1) @result_cache[*args] end end alias :at :[] def empty? !any? end def compare_count return 0 unless @query count, min, max, between = @query.options.values_at(:count, :minimum, :maximum, :between) # Only check filters for as many elements as necessary to determine result if count && (count = Integer(count)) return load_up_to(count + 1) <=> count end return -1 if min && (min = Integer(min)) && (load_up_to(min) < min) return 1 if max && (max = Integer(max)) && (load_up_to(max + 1) > max) if between min, max = (between.begin && between.min) || 1, between.end max -= 1 if max && between.exclude_end? size = load_up_to(max ? max + 1 : min) return size <=> min unless between.include?(size) end 0 end def matches_count? compare_count.zero? end def failure_message message = @query.failure_message if count.zero? message << ' but there were no matches' else message << ", found #{count} #{Capybara::Helpers.declension('match', 'matches', count)}: " \ << full_results.map { |r| r.text.inspect }.join(', ') end unless rest.empty? elements = rest.map { |el| el.text rescue '<<ERROR>>' }.map(&:inspect).join(', ') # rubocop:disable Style/RescueModifier message << '. Also found ' << elements << ', which matched the selector but not all filters. ' message << @filter_errors.join('. ') if (rest.size == 1) && count.zero? end message end def negative_failure_message failure_message.sub(/(to find)/, 'not \1') end def unfiltered_size @elements.length end ## # @api private # def allow_reload! @allow_reload = true self end private def add_to_cache(elem) elem.allow_reload!(@result_cache.size) if @allow_reload @result_cache << elem end def load_up_to(num) loop do break if @result_cache.size >= num add_to_cache(@results_enum.next) end @result_cache.size end def full_results loop { @result_cache << @results_enum.next } @result_cache end def rest @rest ||= @elements - full_results end if RUBY_PLATFORM == 'java' # JRuby < 9.2.8.0 has an issue with lazy enumerators which # causes a concurrency issue with network requests here # https://github.com/jruby/jruby/issues/4212 # while JRuby >= 9.2.8.0 leaks threads when using lazy enumerators # https://github.com/teamcapybara/capybara/issues/2349 # so disable the use and JRuby users will need to pay a performance penalty def lazy_select_elements(&block) @elements.select(&block).to_enum # non-lazy evaluation end else def lazy_select_elements(&block) @elements.lazy.select(&block) end end end end
Ruby
{ "end_line": 77, "name": "[]", "signature": "def [](*args)", "start_line": 53 }
{ "class_name": "Result", "class_signature": "class Result", "module": "Capybara" }
compare_count
capybara/lib/capybara/result.rb
def compare_count return 0 unless @query count, min, max, between = @query.options.values_at(:count, :minimum, :maximum, :between) # Only check filters for as many elements as necessary to determine result if count && (count = Integer(count)) return load_up_to(count + 1) <=> count end return -1 if min && (min = Integer(min)) && (load_up_to(min) < min) return 1 if max && (max = Integer(max)) && (load_up_to(max + 1) > max) if between min, max = (between.begin && between.min) || 1, between.end max -= 1 if max && between.exclude_end? size = load_up_to(max ? max + 1 : min) return size <=> min unless between.include?(size) end 0 end
# frozen_string_literal: true require 'forwardable' module Capybara ## # A {Capybara::Result} represents a collection of {Capybara::Node::Element} on the page. It is possible to interact with this # collection similar to an Array because it implements Enumerable and offers the following Array methods through delegation: # # * \[\] # * each() # * at() # * size() # * count() # * length() # * first() # * last() # * empty?() # * values_at() # * sample() # # @see Capybara::Node::Element # class Result include Enumerable extend Forwardable def initialize(elements, query) @elements = elements @result_cache = [] @filter_errors = [] @results_enum = lazy_select_elements { |node| query.matches_filters?(node, @filter_errors) } @query = query @allow_reload = false end def_delegators :full_results, :size, :length, :last, :values_at, :inspect, :sample, :to_ary alias index find_index def each(&block) return enum_for(:each) unless block @result_cache.each(&block) loop do next_result = @results_enum.next add_to_cache(next_result) yield next_result end self end def [](*args) idx, length = args max_idx = case idx when Integer if idx.negative? nil else length.nil? ? idx : idx + length - 1 end when Range # idx.max is broken with beginless ranges # idx.end && idx.max # endless range will have end == nil max = idx.end max = nil if max&.negative? max -= 1 if max && idx.exclude_end? max end if max_idx.nil? full_results[*args] else load_up_to(max_idx + 1) @result_cache[*args] end end alias :at :[] def empty? !any? end def compare_count return 0 unless @query count, min, max, between = @query.options.values_at(:count, :minimum, :maximum, :between) # Only check filters for as many elements as necessary to determine result if count && (count = Integer(count)) return load_up_to(count + 1) <=> count end return -1 if min && (min = Integer(min)) && (load_up_to(min) < min) return 1 if max && (max = Integer(max)) && (load_up_to(max + 1) > max) if between min, max = (between.begin && between.min) || 1, between.end max -= 1 if max && between.exclude_end? size = load_up_to(max ? max + 1 : min) return size <=> min unless between.include?(size) end 0 end def matches_count? compare_count.zero? end def failure_message message = @query.failure_message if count.zero? message << ' but there were no matches' else message << ", found #{count} #{Capybara::Helpers.declension('match', 'matches', count)}: " \ << full_results.map { |r| r.text.inspect }.join(', ') end unless rest.empty? elements = rest.map { |el| el.text rescue '<<ERROR>>' }.map(&:inspect).join(', ') # rubocop:disable Style/RescueModifier message << '. Also found ' << elements << ', which matched the selector but not all filters. ' message << @filter_errors.join('. ') if (rest.size == 1) && count.zero? end message end def negative_failure_message failure_message.sub(/(to find)/, 'not \1') end def unfiltered_size @elements.length end ## # @api private # def allow_reload! @allow_reload = true self end private def add_to_cache(elem) elem.allow_reload!(@result_cache.size) if @allow_reload @result_cache << elem end def load_up_to(num) loop do break if @result_cache.size >= num add_to_cache(@results_enum.next) end @result_cache.size end def full_results loop { @result_cache << @results_enum.next } @result_cache end def rest @rest ||= @elements - full_results end if RUBY_PLATFORM == 'java' # JRuby < 9.2.8.0 has an issue with lazy enumerators which # causes a concurrency issue with network requests here # https://github.com/jruby/jruby/issues/4212 # while JRuby >= 9.2.8.0 leaks threads when using lazy enumerators # https://github.com/teamcapybara/capybara/issues/2349 # so disable the use and JRuby users will need to pay a performance penalty def lazy_select_elements(&block) @elements.select(&block).to_enum # non-lazy evaluation end else def lazy_select_elements(&block) @elements.lazy.select(&block) end end end end
Ruby
{ "end_line": 107, "name": "compare_count", "signature": "def compare_count", "start_line": 84 }
{ "class_name": "Result", "class_signature": "class Result", "module": "Capybara" }
failure_message
capybara/lib/capybara/result.rb
def failure_message message = @query.failure_message if count.zero? message << ' but there were no matches' else message << ", found #{count} #{Capybara::Helpers.declension('match', 'matches', count)}: " \ << full_results.map { |r| r.text.inspect }.join(', ') end unless rest.empty? elements = rest.map { |el| el.text rescue '<<ERROR>>' }.map(&:inspect).join(', ') # rubocop:disable Style/RescueModifier message << '. Also found ' << elements << ', which matched the selector but not all filters. ' message << @filter_errors.join('. ') if (rest.size == 1) && count.zero? end message end
# frozen_string_literal: true require 'forwardable' module Capybara ## # A {Capybara::Result} represents a collection of {Capybara::Node::Element} on the page. It is possible to interact with this # collection similar to an Array because it implements Enumerable and offers the following Array methods through delegation: # # * \[\] # * each() # * at() # * size() # * count() # * length() # * first() # * last() # * empty?() # * values_at() # * sample() # # @see Capybara::Node::Element # class Result include Enumerable extend Forwardable def initialize(elements, query) @elements = elements @result_cache = [] @filter_errors = [] @results_enum = lazy_select_elements { |node| query.matches_filters?(node, @filter_errors) } @query = query @allow_reload = false end def_delegators :full_results, :size, :length, :last, :values_at, :inspect, :sample, :to_ary alias index find_index def each(&block) return enum_for(:each) unless block @result_cache.each(&block) loop do next_result = @results_enum.next add_to_cache(next_result) yield next_result end self end def [](*args) idx, length = args max_idx = case idx when Integer if idx.negative? nil else length.nil? ? idx : idx + length - 1 end when Range # idx.max is broken with beginless ranges # idx.end && idx.max # endless range will have end == nil max = idx.end max = nil if max&.negative? max -= 1 if max && idx.exclude_end? max end if max_idx.nil? full_results[*args] else load_up_to(max_idx + 1) @result_cache[*args] end end alias :at :[] def empty? !any? end def compare_count return 0 unless @query count, min, max, between = @query.options.values_at(:count, :minimum, :maximum, :between) # Only check filters for as many elements as necessary to determine result if count && (count = Integer(count)) return load_up_to(count + 1) <=> count end return -1 if min && (min = Integer(min)) && (load_up_to(min) < min) return 1 if max && (max = Integer(max)) && (load_up_to(max + 1) > max) if between min, max = (between.begin && between.min) || 1, between.end max -= 1 if max && between.exclude_end? size = load_up_to(max ? max + 1 : min) return size <=> min unless between.include?(size) end 0 end def matches_count? compare_count.zero? end def failure_message message = @query.failure_message if count.zero? message << ' but there were no matches' else message << ", found #{count} #{Capybara::Helpers.declension('match', 'matches', count)}: " \ << full_results.map { |r| r.text.inspect }.join(', ') end unless rest.empty? elements = rest.map { |el| el.text rescue '<<ERROR>>' }.map(&:inspect).join(', ') # rubocop:disable Style/RescueModifier message << '. Also found ' << elements << ', which matched the selector but not all filters. ' message << @filter_errors.join('. ') if (rest.size == 1) && count.zero? end message end def negative_failure_message failure_message.sub(/(to find)/, 'not \1') end def unfiltered_size @elements.length end ## # @api private # def allow_reload! @allow_reload = true self end private def add_to_cache(elem) elem.allow_reload!(@result_cache.size) if @allow_reload @result_cache << elem end def load_up_to(num) loop do break if @result_cache.size >= num add_to_cache(@results_enum.next) end @result_cache.size end def full_results loop { @result_cache << @results_enum.next } @result_cache end def rest @rest ||= @elements - full_results end if RUBY_PLATFORM == 'java' # JRuby < 9.2.8.0 has an issue with lazy enumerators which # causes a concurrency issue with network requests here # https://github.com/jruby/jruby/issues/4212 # while JRuby >= 9.2.8.0 leaks threads when using lazy enumerators # https://github.com/teamcapybara/capybara/issues/2349 # so disable the use and JRuby users will need to pay a performance penalty def lazy_select_elements(&block) @elements.select(&block).to_enum # non-lazy evaluation end else def lazy_select_elements(&block) @elements.lazy.select(&block) end end end end
Ruby
{ "end_line": 127, "name": "failure_message", "signature": "def failure_message", "start_line": 113 }
{ "class_name": "Result", "class_signature": "class Result", "module": "Capybara" }
initialize
capybara/lib/capybara/server.rb
def initialize(app, *deprecated_options, port: Capybara.server_port, host: Capybara.server_host, reportable_errors: Capybara.server_errors, extra_middleware: []) unless deprecated_options.empty? warn 'Positional arguments, other than the application, to Server#new are deprecated, please use keyword arguments' end @app = app @extra_middleware = extra_middleware @server_thread = nil # suppress warnings @host = deprecated_options[1] || host @reportable_errors = deprecated_options[2] || reportable_errors @port = deprecated_options[0] || port @port ||= Capybara::Server.ports[port_key] @port ||= find_available_port(host) @checker = Checker.new(@host, @port) end
# frozen_string_literal: true require 'uri' require 'net/http' require 'rack' require 'capybara/server/middleware' require 'capybara/server/animation_disabler' require 'capybara/server/checker' module Capybara # @api private class Server class << self def ports @ports ||= {} end end attr_reader :app, :port, :host def initialize(app, *deprecated_options, port: Capybara.server_port, host: Capybara.server_host, reportable_errors: Capybara.server_errors, extra_middleware: []) unless deprecated_options.empty? warn 'Positional arguments, other than the application, to Server#new are deprecated, please use keyword arguments' end @app = app @extra_middleware = extra_middleware @server_thread = nil # suppress warnings @host = deprecated_options[1] || host @reportable_errors = deprecated_options[2] || reportable_errors @port = deprecated_options[0] || port @port ||= Capybara::Server.ports[port_key] @port ||= find_available_port(host) @checker = Checker.new(@host, @port) end def reset_error! middleware.clear_error end def error middleware.error end def using_ssl? @checker.ssl? end def responsive? return false if @server_thread&.join(0) res = @checker.request { |http| http.get('/__identify__') } res.body == app.object_id.to_s if res.is_a?(Net::HTTPSuccess) || res.is_a?(Net::HTTPRedirection) rescue SystemCallError, Net::ReadTimeout, OpenSSL::SSL::SSLError false end def wait_for_pending_requests timer = Capybara::Helpers.timer(expire_in: 60) while pending_requests? raise "Requests did not finish in 60 seconds: #{middleware.pending_requests}" if timer.expired? sleep 0.01 end end def boot unless responsive? Capybara::Server.ports[port_key] = port @server_thread = Thread.new do Capybara.server.call(middleware, port, host) end timer = Capybara::Helpers.timer(expire_in: 60) until responsive? raise 'Rack application timed out during boot' if timer.expired? @server_thread.join(0.1) end end self end def base_url "http#{'s' if using_ssl?}://#{host}:#{port}" end private def middleware @middleware ||= Middleware.new(app, @reportable_errors, @extra_middleware) end def port_key Capybara.reuse_server ? app.object_id : middleware.object_id end def pending_requests? middleware.pending_requests? end def find_available_port(host) server = TCPServer.new(host, 0) port = server.addr[1] server.close # Workaround issue where some platforms (mac, ???) when passed a host # of '0.0.0.0' will return a port that is only available on one of the # ip addresses that resolves to, but the next binding to that port requires # that port to be available on all ips server = TCPServer.new(host, port) port rescue Errno::EADDRINUSE retry ensure server&.close end end end
Ruby
{ "end_line": 39, "name": "initialize", "signature": "def initialize(app,", "start_line": 21 }
{ "class_name": "Server", "class_signature": "class Server", "module": "Capybara" }
boot
capybara/lib/capybara/server.rb
def boot unless responsive? Capybara::Server.ports[port_key] = port @server_thread = Thread.new do Capybara.server.call(middleware, port, host) end timer = Capybara::Helpers.timer(expire_in: 60) until responsive? raise 'Rack application timed out during boot' if timer.expired? @server_thread.join(0.1) end end self end
# frozen_string_literal: true require 'uri' require 'net/http' require 'rack' require 'capybara/server/middleware' require 'capybara/server/animation_disabler' require 'capybara/server/checker' module Capybara # @api private class Server class << self def ports @ports ||= {} end end attr_reader :app, :port, :host def initialize(app, *deprecated_options, port: Capybara.server_port, host: Capybara.server_host, reportable_errors: Capybara.server_errors, extra_middleware: []) unless deprecated_options.empty? warn 'Positional arguments, other than the application, to Server#new are deprecated, please use keyword arguments' end @app = app @extra_middleware = extra_middleware @server_thread = nil # suppress warnings @host = deprecated_options[1] || host @reportable_errors = deprecated_options[2] || reportable_errors @port = deprecated_options[0] || port @port ||= Capybara::Server.ports[port_key] @port ||= find_available_port(host) @checker = Checker.new(@host, @port) end def reset_error! middleware.clear_error end def error middleware.error end def using_ssl? @checker.ssl? end def responsive? return false if @server_thread&.join(0) res = @checker.request { |http| http.get('/__identify__') } res.body == app.object_id.to_s if res.is_a?(Net::HTTPSuccess) || res.is_a?(Net::HTTPRedirection) rescue SystemCallError, Net::ReadTimeout, OpenSSL::SSL::SSLError false end def wait_for_pending_requests timer = Capybara::Helpers.timer(expire_in: 60) while pending_requests? raise "Requests did not finish in 60 seconds: #{middleware.pending_requests}" if timer.expired? sleep 0.01 end end def boot unless responsive? Capybara::Server.ports[port_key] = port @server_thread = Thread.new do Capybara.server.call(middleware, port, host) end timer = Capybara::Helpers.timer(expire_in: 60) until responsive? raise 'Rack application timed out during boot' if timer.expired? @server_thread.join(0.1) end end self end def base_url "http#{'s' if using_ssl?}://#{host}:#{port}" end private def middleware @middleware ||= Middleware.new(app, @reportable_errors, @extra_middleware) end def port_key Capybara.reuse_server ? app.object_id : middleware.object_id end def pending_requests? middleware.pending_requests? end def find_available_port(host) server = TCPServer.new(host, 0) port = server.addr[1] server.close # Workaround issue where some platforms (mac, ???) when passed a host # of '0.0.0.0' will return a port that is only available on one of the # ip addresses that resolves to, but the next binding to that port requires # that port to be available on all ips server = TCPServer.new(host, port) port rescue Errno::EADDRINUSE retry ensure server&.close end end end
Ruby
{ "end_line": 89, "name": "boot", "signature": "def boot", "start_line": 72 }
{ "class_name": "Server", "class_signature": "class Server", "module": "Capybara" }
find_available_port
capybara/lib/capybara/server.rb
def find_available_port(host) server = TCPServer.new(host, 0) port = server.addr[1] server.close # Workaround issue where some platforms (mac, ???) when passed a host # of '0.0.0.0' will return a port that is only available on one of the # ip addresses that resolves to, but the next binding to that port requires # that port to be available on all ips server = TCPServer.new(host, port) port rescue Errno::EADDRINUSE retry ensure server&.close end
# frozen_string_literal: true require 'uri' require 'net/http' require 'rack' require 'capybara/server/middleware' require 'capybara/server/animation_disabler' require 'capybara/server/checker' module Capybara # @api private class Server class << self def ports @ports ||= {} end end attr_reader :app, :port, :host def initialize(app, *deprecated_options, port: Capybara.server_port, host: Capybara.server_host, reportable_errors: Capybara.server_errors, extra_middleware: []) unless deprecated_options.empty? warn 'Positional arguments, other than the application, to Server#new are deprecated, please use keyword arguments' end @app = app @extra_middleware = extra_middleware @server_thread = nil # suppress warnings @host = deprecated_options[1] || host @reportable_errors = deprecated_options[2] || reportable_errors @port = deprecated_options[0] || port @port ||= Capybara::Server.ports[port_key] @port ||= find_available_port(host) @checker = Checker.new(@host, @port) end def reset_error! middleware.clear_error end def error middleware.error end def using_ssl? @checker.ssl? end def responsive? return false if @server_thread&.join(0) res = @checker.request { |http| http.get('/__identify__') } res.body == app.object_id.to_s if res.is_a?(Net::HTTPSuccess) || res.is_a?(Net::HTTPRedirection) rescue SystemCallError, Net::ReadTimeout, OpenSSL::SSL::SSLError false end def wait_for_pending_requests timer = Capybara::Helpers.timer(expire_in: 60) while pending_requests? raise "Requests did not finish in 60 seconds: #{middleware.pending_requests}" if timer.expired? sleep 0.01 end end def boot unless responsive? Capybara::Server.ports[port_key] = port @server_thread = Thread.new do Capybara.server.call(middleware, port, host) end timer = Capybara::Helpers.timer(expire_in: 60) until responsive? raise 'Rack application timed out during boot' if timer.expired? @server_thread.join(0.1) end end self end def base_url "http#{'s' if using_ssl?}://#{host}:#{port}" end private def middleware @middleware ||= Middleware.new(app, @reportable_errors, @extra_middleware) end def port_key Capybara.reuse_server ? app.object_id : middleware.object_id end def pending_requests? middleware.pending_requests? end def find_available_port(host) server = TCPServer.new(host, 0) port = server.addr[1] server.close # Workaround issue where some platforms (mac, ???) when passed a host # of '0.0.0.0' will return a port that is only available on one of the # ip addresses that resolves to, but the next binding to that port requires # that port to be available on all ips server = TCPServer.new(host, port) port rescue Errno::EADDRINUSE retry ensure server&.close end end end
Ruby
{ "end_line": 124, "name": "find_available_port", "signature": "def find_available_port(host)", "start_line": 109 }
{ "class_name": "Server", "class_signature": "class Server", "module": "Capybara" }
initialize
capybara/lib/capybara/session.rb
def initialize(mode, app = nil) if app && !app.respond_to?(:call) raise TypeError, 'The second parameter to Session::new should be a rack app if passed.' end @@instance_created = true # rubocop:disable Style/ClassVars @mode = mode @app = app if block_given? raise 'A configuration block is only accepted when Capybara.threadsafe == true' unless Capybara.threadsafe yield config end @server = if config.run_server && @app && driver.needs_server? server_options = { port: config.server_port, host: config.server_host, reportable_errors: config.server_errors } server_options[:extra_middleware] = [Capybara::Server::AnimationDisabler] if config.disable_animation Capybara::Server.new(@app, **server_options).boot end @touched = false end
# frozen_string_literal: true require 'capybara/session/matchers' require 'addressable/uri' module Capybara ## # # The {Session} class represents a single user's interaction with the system. The {Session} can use # any of the underlying drivers. A session can be initialized manually like this: # # session = Capybara::Session.new(:culerity, MyRackApp) # # The application given as the second argument is optional. When running Capybara against an external # page, you might want to leave it out: # # session = Capybara::Session.new(:culerity) # session.visit('http://www.google.com') # # When {Capybara.configure threadsafe} is `true` the sessions options will be initially set to the # current values of the global options and a configuration block can be passed to the session initializer. # For available options see {Capybara::SessionConfig::OPTIONS}: # # session = Capybara::Session.new(:driver, MyRackApp) do |config| # config.app_host = "http://my_host.dev" # end # # The {Session} provides a number of methods for controlling the navigation of the page, such as {#visit}, # {#current_path}, and so on. It also delegates a number of methods to a {Capybara::Document}, representing # the current HTML document. This allows interaction: # # session.fill_in('q', with: 'Capybara') # session.click_button('Search') # expect(session).to have_content('Capybara') # # When using `capybara/dsl`, the {Session} is initialized automatically for you. # class Session include Capybara::SessionMatchers NODE_METHODS = %i[ all first attach_file text check choose scroll_to scroll_by click double_click right_click click_link_or_button click_button click_link fill_in find find_all find_button find_by_id find_field find_link has_content? has_text? has_css? has_no_content? has_no_text? has_no_css? has_no_xpath? has_xpath? select uncheck has_element? has_no_element? has_link? has_no_link? has_button? has_no_button? has_field? has_no_field? has_checked_field? has_unchecked_field? has_no_table? has_table? unselect has_select? has_no_select? has_selector? has_no_selector? click_on has_no_checked_field? has_no_unchecked_field? query assert_selector assert_no_selector assert_all_of_selectors assert_none_of_selectors assert_any_of_selectors refute_selector assert_text assert_no_text ].freeze # @api private DOCUMENT_METHODS = %i[ title assert_title assert_no_title has_title? has_no_title? ].freeze SESSION_METHODS = %i[ body html source current_url current_host current_path execute_script evaluate_script evaluate_async_script visit refresh go_back go_forward send_keys within within_element within_fieldset within_table within_frame switch_to_frame current_window windows open_new_window switch_to_window within_window window_opened_by save_page save_and_open_page save_screenshot save_and_open_screenshot reset_session! response_headers status_code current_scope assert_current_path assert_no_current_path has_current_path? has_no_current_path? ].freeze + DOCUMENT_METHODS MODAL_METHODS = %i[ accept_alert accept_confirm dismiss_confirm accept_prompt dismiss_prompt ].freeze DSL_METHODS = NODE_METHODS + SESSION_METHODS + MODAL_METHODS attr_reader :mode, :app, :server attr_accessor :synchronized def initialize(mode, app = nil) if app && !app.respond_to?(:call) raise TypeError, 'The second parameter to Session::new should be a rack app if passed.' end @@instance_created = true # rubocop:disable Style/ClassVars @mode = mode @app = app if block_given? raise 'A configuration block is only accepted when Capybara.threadsafe == true' unless Capybara.threadsafe yield config end @server = if config.run_server && @app && driver.needs_server? server_options = { port: config.server_port, host: config.server_host, reportable_errors: config.server_errors } server_options[:extra_middleware] = [Capybara::Server::AnimationDisabler] if config.disable_animation Capybara::Server.new(@app, **server_options).boot end @touched = false end def driver @driver ||= begin unless Capybara.drivers[mode] other_drivers = Capybara.drivers.names.map(&:inspect) raise Capybara::DriverNotFoundError, "no driver called #{mode.inspect} was found, available drivers: #{other_drivers.join(', ')}" end driver = Capybara.drivers[mode].call(app) driver.session = self if driver.respond_to?(:session=) driver end end ## # # Reset the session (i.e. remove cookies and navigate to blank page). # # This method does not: # # * accept modal dialogs if they are present (Selenium driver now does, others may not) # * clear browser cache/HTML 5 local storage/IndexedDB/Web SQL database/etc. # * modify state of the driver/underlying browser in any other way # # as doing so will result in performance downsides and it's not needed to do everything from the list above for most apps. # # If you want to do anything from the list above on a general basis you can: # # * write RSpec/Cucumber/etc. after hook # * monkeypatch this method # * use Ruby's `prepend` method # def reset! if @touched driver.reset! @touched = false switch_to_frame(:top) rescue nil # rubocop:disable Style/RescueModifier @scopes = [nil] end @server&.wait_for_pending_requests raise_server_error! end alias_method :cleanup!, :reset! alias_method :reset_session!, :reset! ## # # Disconnect from the current driver. A new driver will be instantiated on the next interaction. # def quit @driver.quit if @driver.respond_to? :quit @document = @driver = nil @touched = false @server&.reset_error! end ## # # Raise errors encountered in the server. # def raise_server_error! return unless @server&.error # Force an explanation for the error being raised as the exception cause begin if config.raise_server_errors raise CapybaraError, 'Your application server raised an error - It has been raised in your test code because Capybara.raise_server_errors == true' end rescue CapybaraError => capy_error # rubocop:disable Naming/RescuedExceptionsVariableName raise @server.error, cause: capy_error ensure @server.reset_error! end end ## # # Returns a hash of response headers. Not supported by all drivers (e.g. Selenium). # # @return [Hash<String, String>] A hash of response headers. # def response_headers driver.response_headers end ## # # Returns the current HTTP status code as an integer. Not supported by all drivers (e.g. Selenium). # # @return [Integer] Current HTTP status code # def status_code driver.status_code end ## # # @return [String] A snapshot of the DOM of the current document, as it looks right now (potentially modified by JavaScript). # def html driver.html || '' end alias_method :body, :html alias_method :source, :html ## # # @return [String] Path of the current page, without any domain information # def current_path # Addressable parsing is more lenient than URI uri = ::Addressable::URI.parse(current_url) # Addressable doesn't support opaque URIs - we want nil here return nil if uri&.scheme == 'about' path = uri&.path path unless path&.empty? end ## # # @return [String] Host of the current page # def current_host uri = URI.parse(current_url) "#{uri.scheme}://#{uri.host}" if uri.host end ## # # @return [String] Fully qualified URL of the current page # def current_url driver.current_url end ## # # Navigate to the given URL. The URL can either be a relative URL or an absolute URL # The behaviour of either depends on the driver. # # session.visit('/foo') # session.visit('http://google.com') # # For drivers which can run against an external application, such as the selenium driver # giving an absolute URL will navigate to that page. This allows testing applications # running on remote servers. For these drivers, setting {Capybara.configure app_host} will make the # remote server the default. For example: # # Capybara.app_host = 'http://google.com' # session.visit('/') # visits the google homepage # # If {Capybara.configure always_include_port} is set to `true` and this session is running against # a rack application, then the port that the rack application is running on will automatically # be inserted into the URL. Supposing the app is running on port `4567`, doing something like: # # visit("http://google.com/test") # # Will actually navigate to `http://google.com:4567/test`. # # @param [#to_s] visit_uri The URL to navigate to. The parameter will be cast to a String. # def visit(visit_uri) raise_server_error! @touched = true visit_uri = ::Addressable::URI.parse(visit_uri.to_s) base_uri = ::Addressable::URI.parse(config.app_host || server_url) if base_uri && [nil, 'http', 'https'].include?(visit_uri.scheme) if visit_uri.relative? visit_uri_parts = visit_uri.to_hash.compact # Useful to people deploying to a subdirectory # and/or single page apps where only the url fragment changes visit_uri_parts[:path] = base_uri.path + visit_uri.path visit_uri = base_uri.merge(visit_uri_parts) end adjust_server_port(visit_uri) end driver.visit(visit_uri.to_s) end ## # # Refresh the page. # def refresh raise_server_error! driver.refresh end ## # # Move back a single entry in the browser's history. # def go_back driver.go_back end ## # # Move forward a single entry in the browser's history. # def go_forward driver.go_forward end ## # @!method send_keys # @see Capybara::Node::Element#send_keys # def send_keys(...) driver.send_keys(...) end ## # # Returns the element with focus. # # Not supported by Rack Test # def active_element Capybara::Queries::ActiveElementQuery.new.resolve_for(self)[0].tap(&:allow_reload!) end ## # # Executes the given block within the context of a node. {#within} takes the # same options as {Capybara::Node::Finders#find #find}, as well as a block. For the duration of the # block, any command to Capybara will be handled as though it were scoped # to the given element. # # within(:xpath, './/div[@id="delivery-address"]') do # fill_in('Street', with: '12 Main Street') # end # # Just as with `#find`, if multiple elements match the selector given to # {#within}, an error will be raised, and just as with `#find`, this # behaviour can be controlled through the `:match` and `:exact` options. # # It is possible to omit the first parameter, in that case, the selector is # assumed to be of the type set in {Capybara.configure default_selector}. # # within('div#delivery-address') do # fill_in('Street', with: '12 Main Street') # end # # Note that a lot of uses of {#within} can be replaced more succinctly with # chaining: # # find('div#delivery-address').fill_in('Street', with: '12 Main Street') # # @overload within(*find_args) # @param (see Capybara::Node::Finders#all) # # @overload within(a_node) # @param [Capybara::Node::Base] a_node The node in whose scope the block should be evaluated # # @raise [Capybara::ElementNotFound] If the scope can't be found before time expires # def within(*args, **kw_args) new_scope = args.first.respond_to?(:to_capybara_node) ? args.first.to_capybara_node : find(*args, **kw_args) begin scopes.push(new_scope) yield new_scope if block_given? ensure scopes.pop end end alias_method :within_element, :within ## # # Execute the given block within the a specific fieldset given the id or legend of that fieldset. # # @param [String] locator Id or legend of the fieldset # def within_fieldset(locator, &block) within(:fieldset, locator, &block) end ## # # Execute the given block within the a specific table given the id or caption of that table. # # @param [String] locator Id or caption of the table # def within_table(locator, &block) within(:table, locator, &block) end ## # # Switch to the given frame. # # If you use this method you are responsible for making sure you switch back to the parent frame when done in the frame changed to. # {#within_frame} is preferred over this method and should be used when possible. # May not be supported by all drivers. # # @overload switch_to_frame(element) # @param [Capybara::Node::Element] element iframe/frame element to switch to # @overload switch_to_frame(location) # @param [Symbol] location relative location of the frame to switch to # * :parent - the parent frame # * :top - the top level document # def switch_to_frame(frame) case frame when Capybara::Node::Element driver.switch_to_frame(frame) scopes.push(:frame) when :parent if scopes.last != :frame raise Capybara::ScopeError, "`switch_to_frame(:parent)` cannot be called from inside a descendant frame's " \ '`within` block.' end scopes.pop driver.switch_to_frame(:parent) when :top idx = scopes.index(:frame) top_level_scopes = [:frame, nil] if idx if scopes.slice(idx..).any? { |scope| !top_level_scopes.include?(scope) } raise Capybara::ScopeError, "`switch_to_frame(:top)` cannot be called from inside a descendant frame's " \ '`within` block.' end scopes.slice!(idx..) driver.switch_to_frame(:top) end else raise ArgumentError, 'You must provide a frame element, :parent, or :top when calling switch_to_frame' end end ## # # Execute the given block within the given iframe using given frame, frame name/id or index. # May not be supported by all drivers. # # @overload within_frame(element) # @param [Capybara::Node::Element] frame element # @overload within_frame([kind = :frame], locator, **options) # @param [Symbol] kind Optional selector type (:frame, :css, :xpath, etc.) - Defaults to :frame # @param [String] locator The locator for the given selector kind. For :frame this is the name/id of a frame/iframe element # @overload within_frame(index) # @param [Integer] index index of a frame (0 based) def within_frame(*args, **kw_args) switch_to_frame(_find_frame(*args, **kw_args)) begin yield if block_given? ensure switch_to_frame(:parent) end end ## # @return [Capybara::Window] current window # def current_window Window.new(self, driver.current_window_handle) end ## # Get all opened windows. # The order of windows in returned array is not defined. # The driver may sort windows by their creation time but it's not required. # # @return [Array<Capybara::Window>] an array of all windows # def windows driver.window_handles.map do |handle| Window.new(self, handle) end end ## # Open a new window. # The current window doesn't change as the result of this call. # It should be switched to explicitly. # # @return [Capybara::Window] window that has been opened # def open_new_window(kind = :tab) window_opened_by do if driver.method(:open_new_window).arity.zero? driver.open_new_window else driver.open_new_window(kind) end end end ## # Switch to the given window. # # @overload switch_to_window(&block) # Switches to the first window for which given block returns a value other than false or nil. # If window that matches block can't be found, the window will be switched back and {Capybara::WindowError} will be raised. # @example # window = switch_to_window { title == 'Page title' } # @raise [Capybara::WindowError] if no window matches given block # @overload switch_to_window(window) # @param window [Capybara::Window] window that should be switched to # @raise [Capybara::Driver::Base#no_such_window_error] if nonexistent (e.g. closed) window was passed # # @return [Capybara::Window] window that has been switched to # @raise [Capybara::ScopeError] if this method is invoked inside {#within} or # {#within_frame} methods # @raise [ArgumentError] if both or neither arguments were provided # def switch_to_window(window = nil, **options, &window_locator) raise ArgumentError, '`switch_to_window` can take either a block or a window, not both' if window && window_locator raise ArgumentError, '`switch_to_window`: either window or block should be provided' if !window && !window_locator unless scopes.last.nil? raise Capybara::ScopeError, '`switch_to_window` is not supposed to be invoked from ' \ '`within` or `within_frame` blocks.' end _switch_to_window(window, **options, &window_locator) end ## # This method does the following: # # 1. Switches to the given window (it can be located by window instance/lambda/string). # 2. Executes the given block (within window located at previous step). # 3. Switches back (this step will be invoked even if an exception occurs at the second step). # # @overload within_window(window) { do_something } # @param window [Capybara::Window] instance of {Capybara::Window} class # that will be switched to # @raise [driver#no_such_window_error] if nonexistent (e.g. closed) window was passed # @overload within_window(proc_or_lambda) { do_something } # @param lambda [Proc] First window for which lambda # returns a value other than false or nil will be switched to. # @example # within_window(->{ page.title == 'Page title' }) { click_button 'Submit' } # @raise [Capybara::WindowError] if no window matching lambda was found # # @raise [Capybara::ScopeError] if this method is invoked inside {#within_frame} method # @return value returned by the block # def within_window(window_or_proc) original = current_window scopes << nil begin case window_or_proc when Capybara::Window _switch_to_window(window_or_proc) unless original == window_or_proc when Proc _switch_to_window { window_or_proc.call } else raise ArgumentError, '`#within_window` requires a `Capybara::Window` instance or a lambda' end begin yield if block_given? ensure _switch_to_window(original) unless original == window_or_proc end ensure scopes.pop end end ## # Get the window that has been opened by the passed block. # It will wait for it to be opened (in the same way as other Capybara methods wait). # It's better to use this method than `windows.last` # {https://dvcs.w3.org/hg/webdriver/raw-file/default/webdriver-spec.html#h_note_10 as order of windows isn't defined in some drivers}. # # @overload window_opened_by(**options, &block) # @param options [Hash] # @option options [Numeric] :wait maximum wait time. Defaults to {Capybara.configure default_max_wait_time} # @return [Capybara::Window] the window that has been opened within a block # @raise [Capybara::WindowError] if block passed to window hasn't opened window # or opened more than one window # def window_opened_by(**options) old_handles = driver.window_handles yield synchronize_windows(options) do opened_handles = (driver.window_handles - old_handles) if opened_handles.size != 1 raise Capybara::WindowError, 'block passed to #window_opened_by ' \ "opened #{opened_handles.size} windows instead of 1" end Window.new(self, opened_handles.first) end end ## # # Execute the given script, not returning a result. This is useful for scripts that return # complex objects, such as jQuery statements. {#execute_script} should be used over # {#evaluate_script} whenever possible. # # @param [String] script A string of JavaScript to execute # @param args Optional arguments that will be passed to the script. Driver support for this is optional and types of objects supported may differ between drivers # def execute_script(script, *args) @touched = true driver.execute_script(script, *driver_args(args)) end ## # # Evaluate the given JavaScript and return the result. Be careful when using this with # scripts that return complex objects, such as jQuery statements. {#execute_script} might # be a better alternative. # # @param [String] script A string of JavaScript to evaluate # @param args Optional arguments that will be passed to the script # @return [Object] The result of the evaluated JavaScript (may be driver specific) # def evaluate_script(script, *args) @touched = true result = driver.evaluate_script(script.strip, *driver_args(args)) element_script_result(result) end ## # # Evaluate the given JavaScript and obtain the result from a callback function which will be passed as the last argument to the script. # # @param [String] script A string of JavaScript to evaluate # @param args Optional arguments that will be passed to the script # @return [Object] The result of the evaluated JavaScript (may be driver specific) # def evaluate_async_script(script, *args) @touched = true result = driver.evaluate_async_script(script, *driver_args(args)) element_script_result(result) end ## # # Execute the block, accepting a alert. # # @!macro modal_params # Expects a block whose actions will trigger the display modal to appear. # @example # $0 do # click_link('link that triggers appearance of system modal') # end # @overload $0(text, **options, &blk) # @param text [String, Regexp] Text or regex to match against the text in the modal. If not provided any modal is matched. # @option options [Numeric] :wait Maximum time to wait for the modal to appear after executing the block. Defaults to {Capybara.configure default_max_wait_time}. # @yield Block whose actions will trigger the system modal # @overload $0(**options, &blk) # @option options [Numeric] :wait Maximum time to wait for the modal to appear after executing the block. Defaults to {Capybara.configure default_max_wait_time}. # @yield Block whose actions will trigger the system modal # @return [String] the message shown in the modal # @raise [Capybara::ModalNotFound] if modal dialog hasn't been found # def accept_alert(text = nil, **options, &blk) accept_modal(:alert, text, options, &blk) end ## # # Execute the block, accepting a confirm. # # @macro modal_params # def accept_confirm(text = nil, **options, &blk) accept_modal(:confirm, text, options, &blk) end ## # # Execute the block, dismissing a confirm. # # @macro modal_params # def dismiss_confirm(text = nil, **options, &blk) dismiss_modal(:confirm, text, options, &blk) end ## # # Execute the block, accepting a prompt, optionally responding to the prompt. # # @macro modal_params # @option options [String] :with Response to provide to the prompt # def accept_prompt(text = nil, **options, &blk) accept_modal(:prompt, text, options, &blk) end ## # # Execute the block, dismissing a prompt. # # @macro modal_params # def dismiss_prompt(text = nil, **options, &blk) dismiss_modal(:prompt, text, options, &blk) end ## # # Save a snapshot of the page. If {Capybara.configure asset_host} is set it will inject `base` tag # pointing to {Capybara.configure asset_host}. # # If invoked without arguments it will save file to {Capybara.configure save_path} # and file will be given randomly generated filename. If invoked with a relative path # the path will be relative to {Capybara.configure save_path}. # # @param [String] path the path to where it should be saved # @return [String] the path to which the file was saved # def save_page(path = nil) prepare_path(path, 'html').tap do |p_path| File.write(p_path, Capybara::Helpers.inject_asset_host(body, host: config.asset_host), mode: 'wb') end end ## # # Save a snapshot of the page and open it in a browser for inspection. # # If invoked without arguments it will save file to {Capybara.configure save_path} # and file will be given randomly generated filename. If invoked with a relative path # the path will be relative to {Capybara.configure save_path}. # # @param [String] path the path to where it should be saved # def save_and_open_page(path = nil) save_page(path).tap { |s_path| open_file(s_path) } end ## # # Save a screenshot of page. # # If invoked without arguments it will save file to {Capybara.configure save_path} # and file will be given randomly generated filename. If invoked with a relative path # the path will be relative to {Capybara.configure save_path}. # # @param [String] path the path to where it should be saved # @param [Hash] options a customizable set of options # @return [String] the path to which the file was saved def save_screenshot(path = nil, **options) prepare_path(path, 'png').tap { |p_path| driver.save_screenshot(p_path, **options) } end ## # # Save a screenshot of the page and open it for inspection. # # If invoked without arguments it will save file to {Capybara.configure save_path} # and file will be given randomly generated filename. If invoked with a relative path # the path will be relative to {Capybara.configure save_path}. # # @param [String] path the path to where it should be saved # @param [Hash] options a customizable set of options # def save_and_open_screenshot(path = nil, **options) save_screenshot(path, **options).tap { |s_path| open_file(s_path) } end def document @document ||= Capybara::Node::Document.new(self, driver) end NODE_METHODS.each do |method| class_eval <<~METHOD, __FILE__, __LINE__ + 1 def #{method}(...) @touched = true current_scope.#{method}(...) end METHOD end DOCUMENT_METHODS.each do |method| class_eval <<~METHOD, __FILE__, __LINE__ + 1 def #{method}(...) document.#{method}(...) end METHOD end def inspect %(#<Capybara::Session>) end def current_scope scope = scopes.last [nil, :frame].include?(scope) ? document : scope end ## # # Yield a block using a specific maximum wait time. # def using_wait_time(seconds, &block) if Capybara.threadsafe begin previous_wait_time = config.default_max_wait_time config.default_max_wait_time = seconds yield ensure config.default_max_wait_time = previous_wait_time end else Capybara.using_wait_time(seconds, &block) end end ## # # Accepts a block to set the configuration options if {Capybara.configure threadsafe} is `true`. Note that some options only have an effect # if set at initialization time, so look at the configuration block that can be passed to the initializer too. # def configure raise 'Session configuration is only supported when Capybara.threadsafe == true' unless Capybara.threadsafe yield config end def self.instance_created? @@instance_created end def config @config ||= if Capybara.threadsafe Capybara.session_options.dup else Capybara::ReadOnlySessionConfig.new(Capybara.session_options) end end def server_url @server&.base_url end private @@instance_created = false # rubocop:disable Style/ClassVars def driver_args(args) args.map { |arg| arg.is_a?(Capybara::Node::Element) ? arg.base : arg } end def accept_modal(type, text_or_options, options, &blk) driver.accept_modal(type, **modal_options(text_or_options, **options), &blk) end def dismiss_modal(type, text_or_options, options, &blk) driver.dismiss_modal(type, **modal_options(text_or_options, **options), &blk) end def modal_options(text = nil, **options) options[:text] ||= text unless text.nil? options[:wait] ||= config.default_max_wait_time options end def open_file(path) require 'launchy' Launchy.open(path) rescue LoadError warn "File saved to #{path}.\nPlease install the launchy gem to open the file automatically." end def prepare_path(path, extension) File.expand_path(path || default_fn(extension), config.save_path).tap do |p_path| FileUtils.mkdir_p(File.dirname(p_path)) end end def default_fn(extension) timestamp = Time.new.strftime('%Y%m%d%H%M%S') "capybara-#{timestamp}#{rand(10**10)}.#{extension}" end def scopes @scopes ||= [nil] end def element_script_result(arg) case arg when Array arg.map { |subarg| element_script_result(subarg) } when Hash arg.transform_values! { |value| element_script_result(value) } when Capybara::Driver::Node Capybara::Node::Element.new(self, arg, nil, nil) else arg end end def adjust_server_port(uri) uri.port ||= @server.port if @server && config.always_include_port end def _find_frame(*args, **kw_args) case args[0] when Capybara::Node::Element args[0] when String, nil find(:frame, *args, **kw_args) when Symbol find(*args, **kw_args) when Integer idx = args[0] all(:frame, minimum: idx + 1)[idx] else raise TypeError end end def _switch_to_window(window = nil, **options, &window_locator) raise Capybara::ScopeError, 'Window cannot be switched inside a `within_frame` block' if scopes.include?(:frame) raise Capybara::ScopeError, 'Window cannot be switched inside a `within` block' unless scopes.last.nil? if window driver.switch_to_window(window.handle) window else synchronize_windows(options) do original_window_handle = driver.current_window_handle begin _switch_to_window_by_locator(&window_locator) rescue StandardError driver.switch_to_window(original_window_handle) raise end end end end def _switch_to_window_by_locator driver.window_handles.each do |handle| driver.switch_to_window handle return Window.new(self, handle) if yield end raise Capybara::WindowError, 'Could not find a window matching block/lambda' end def synchronize_windows(options, &block) wait_time = Capybara::Queries::BaseQuery.wait(options, config.default_max_wait_time) document.synchronize(wait_time, errors: [Capybara::WindowError], &block) end end end
Ruby
{ "end_line": 98, "name": "initialize", "signature": "def initialize(mode, app = nil)", "start_line": 79 }
{ "class_name": "Session", "class_signature": "class Session", "module": "Capybara" }
driver
capybara/lib/capybara/session.rb
def driver @driver ||= begin unless Capybara.drivers[mode] other_drivers = Capybara.drivers.names.map(&:inspect) raise Capybara::DriverNotFoundError, "no driver called #{mode.inspect} was found, available drivers: #{other_drivers.join(', ')}" end driver = Capybara.drivers[mode].call(app) driver.session = self if driver.respond_to?(:session=) driver end end
# frozen_string_literal: true require 'capybara/session/matchers' require 'addressable/uri' module Capybara ## # # The {Session} class represents a single user's interaction with the system. The {Session} can use # any of the underlying drivers. A session can be initialized manually like this: # # session = Capybara::Session.new(:culerity, MyRackApp) # # The application given as the second argument is optional. When running Capybara against an external # page, you might want to leave it out: # # session = Capybara::Session.new(:culerity) # session.visit('http://www.google.com') # # When {Capybara.configure threadsafe} is `true` the sessions options will be initially set to the # current values of the global options and a configuration block can be passed to the session initializer. # For available options see {Capybara::SessionConfig::OPTIONS}: # # session = Capybara::Session.new(:driver, MyRackApp) do |config| # config.app_host = "http://my_host.dev" # end # # The {Session} provides a number of methods for controlling the navigation of the page, such as {#visit}, # {#current_path}, and so on. It also delegates a number of methods to a {Capybara::Document}, representing # the current HTML document. This allows interaction: # # session.fill_in('q', with: 'Capybara') # session.click_button('Search') # expect(session).to have_content('Capybara') # # When using `capybara/dsl`, the {Session} is initialized automatically for you. # class Session include Capybara::SessionMatchers NODE_METHODS = %i[ all first attach_file text check choose scroll_to scroll_by click double_click right_click click_link_or_button click_button click_link fill_in find find_all find_button find_by_id find_field find_link has_content? has_text? has_css? has_no_content? has_no_text? has_no_css? has_no_xpath? has_xpath? select uncheck has_element? has_no_element? has_link? has_no_link? has_button? has_no_button? has_field? has_no_field? has_checked_field? has_unchecked_field? has_no_table? has_table? unselect has_select? has_no_select? has_selector? has_no_selector? click_on has_no_checked_field? has_no_unchecked_field? query assert_selector assert_no_selector assert_all_of_selectors assert_none_of_selectors assert_any_of_selectors refute_selector assert_text assert_no_text ].freeze # @api private DOCUMENT_METHODS = %i[ title assert_title assert_no_title has_title? has_no_title? ].freeze SESSION_METHODS = %i[ body html source current_url current_host current_path execute_script evaluate_script evaluate_async_script visit refresh go_back go_forward send_keys within within_element within_fieldset within_table within_frame switch_to_frame current_window windows open_new_window switch_to_window within_window window_opened_by save_page save_and_open_page save_screenshot save_and_open_screenshot reset_session! response_headers status_code current_scope assert_current_path assert_no_current_path has_current_path? has_no_current_path? ].freeze + DOCUMENT_METHODS MODAL_METHODS = %i[ accept_alert accept_confirm dismiss_confirm accept_prompt dismiss_prompt ].freeze DSL_METHODS = NODE_METHODS + SESSION_METHODS + MODAL_METHODS attr_reader :mode, :app, :server attr_accessor :synchronized def initialize(mode, app = nil) if app && !app.respond_to?(:call) raise TypeError, 'The second parameter to Session::new should be a rack app if passed.' end @@instance_created = true # rubocop:disable Style/ClassVars @mode = mode @app = app if block_given? raise 'A configuration block is only accepted when Capybara.threadsafe == true' unless Capybara.threadsafe yield config end @server = if config.run_server && @app && driver.needs_server? server_options = { port: config.server_port, host: config.server_host, reportable_errors: config.server_errors } server_options[:extra_middleware] = [Capybara::Server::AnimationDisabler] if config.disable_animation Capybara::Server.new(@app, **server_options).boot end @touched = false end def driver @driver ||= begin unless Capybara.drivers[mode] other_drivers = Capybara.drivers.names.map(&:inspect) raise Capybara::DriverNotFoundError, "no driver called #{mode.inspect} was found, available drivers: #{other_drivers.join(', ')}" end driver = Capybara.drivers[mode].call(app) driver.session = self if driver.respond_to?(:session=) driver end end ## # # Reset the session (i.e. remove cookies and navigate to blank page). # # This method does not: # # * accept modal dialogs if they are present (Selenium driver now does, others may not) # * clear browser cache/HTML 5 local storage/IndexedDB/Web SQL database/etc. # * modify state of the driver/underlying browser in any other way # # as doing so will result in performance downsides and it's not needed to do everything from the list above for most apps. # # If you want to do anything from the list above on a general basis you can: # # * write RSpec/Cucumber/etc. after hook # * monkeypatch this method # * use Ruby's `prepend` method # def reset! if @touched driver.reset! @touched = false switch_to_frame(:top) rescue nil # rubocop:disable Style/RescueModifier @scopes = [nil] end @server&.wait_for_pending_requests raise_server_error! end alias_method :cleanup!, :reset! alias_method :reset_session!, :reset! ## # # Disconnect from the current driver. A new driver will be instantiated on the next interaction. # def quit @driver.quit if @driver.respond_to? :quit @document = @driver = nil @touched = false @server&.reset_error! end ## # # Raise errors encountered in the server. # def raise_server_error! return unless @server&.error # Force an explanation for the error being raised as the exception cause begin if config.raise_server_errors raise CapybaraError, 'Your application server raised an error - It has been raised in your test code because Capybara.raise_server_errors == true' end rescue CapybaraError => capy_error # rubocop:disable Naming/RescuedExceptionsVariableName raise @server.error, cause: capy_error ensure @server.reset_error! end end ## # # Returns a hash of response headers. Not supported by all drivers (e.g. Selenium). # # @return [Hash<String, String>] A hash of response headers. # def response_headers driver.response_headers end ## # # Returns the current HTTP status code as an integer. Not supported by all drivers (e.g. Selenium). # # @return [Integer] Current HTTP status code # def status_code driver.status_code end ## # # @return [String] A snapshot of the DOM of the current document, as it looks right now (potentially modified by JavaScript). # def html driver.html || '' end alias_method :body, :html alias_method :source, :html ## # # @return [String] Path of the current page, without any domain information # def current_path # Addressable parsing is more lenient than URI uri = ::Addressable::URI.parse(current_url) # Addressable doesn't support opaque URIs - we want nil here return nil if uri&.scheme == 'about' path = uri&.path path unless path&.empty? end ## # # @return [String] Host of the current page # def current_host uri = URI.parse(current_url) "#{uri.scheme}://#{uri.host}" if uri.host end ## # # @return [String] Fully qualified URL of the current page # def current_url driver.current_url end ## # # Navigate to the given URL. The URL can either be a relative URL or an absolute URL # The behaviour of either depends on the driver. # # session.visit('/foo') # session.visit('http://google.com') # # For drivers which can run against an external application, such as the selenium driver # giving an absolute URL will navigate to that page. This allows testing applications # running on remote servers. For these drivers, setting {Capybara.configure app_host} will make the # remote server the default. For example: # # Capybara.app_host = 'http://google.com' # session.visit('/') # visits the google homepage # # If {Capybara.configure always_include_port} is set to `true` and this session is running against # a rack application, then the port that the rack application is running on will automatically # be inserted into the URL. Supposing the app is running on port `4567`, doing something like: # # visit("http://google.com/test") # # Will actually navigate to `http://google.com:4567/test`. # # @param [#to_s] visit_uri The URL to navigate to. The parameter will be cast to a String. # def visit(visit_uri) raise_server_error! @touched = true visit_uri = ::Addressable::URI.parse(visit_uri.to_s) base_uri = ::Addressable::URI.parse(config.app_host || server_url) if base_uri && [nil, 'http', 'https'].include?(visit_uri.scheme) if visit_uri.relative? visit_uri_parts = visit_uri.to_hash.compact # Useful to people deploying to a subdirectory # and/or single page apps where only the url fragment changes visit_uri_parts[:path] = base_uri.path + visit_uri.path visit_uri = base_uri.merge(visit_uri_parts) end adjust_server_port(visit_uri) end driver.visit(visit_uri.to_s) end ## # # Refresh the page. # def refresh raise_server_error! driver.refresh end ## # # Move back a single entry in the browser's history. # def go_back driver.go_back end ## # # Move forward a single entry in the browser's history. # def go_forward driver.go_forward end ## # @!method send_keys # @see Capybara::Node::Element#send_keys # def send_keys(...) driver.send_keys(...) end ## # # Returns the element with focus. # # Not supported by Rack Test # def active_element Capybara::Queries::ActiveElementQuery.new.resolve_for(self)[0].tap(&:allow_reload!) end ## # # Executes the given block within the context of a node. {#within} takes the # same options as {Capybara::Node::Finders#find #find}, as well as a block. For the duration of the # block, any command to Capybara will be handled as though it were scoped # to the given element. # # within(:xpath, './/div[@id="delivery-address"]') do # fill_in('Street', with: '12 Main Street') # end # # Just as with `#find`, if multiple elements match the selector given to # {#within}, an error will be raised, and just as with `#find`, this # behaviour can be controlled through the `:match` and `:exact` options. # # It is possible to omit the first parameter, in that case, the selector is # assumed to be of the type set in {Capybara.configure default_selector}. # # within('div#delivery-address') do # fill_in('Street', with: '12 Main Street') # end # # Note that a lot of uses of {#within} can be replaced more succinctly with # chaining: # # find('div#delivery-address').fill_in('Street', with: '12 Main Street') # # @overload within(*find_args) # @param (see Capybara::Node::Finders#all) # # @overload within(a_node) # @param [Capybara::Node::Base] a_node The node in whose scope the block should be evaluated # # @raise [Capybara::ElementNotFound] If the scope can't be found before time expires # def within(*args, **kw_args) new_scope = args.first.respond_to?(:to_capybara_node) ? args.first.to_capybara_node : find(*args, **kw_args) begin scopes.push(new_scope) yield new_scope if block_given? ensure scopes.pop end end alias_method :within_element, :within ## # # Execute the given block within the a specific fieldset given the id or legend of that fieldset. # # @param [String] locator Id or legend of the fieldset # def within_fieldset(locator, &block) within(:fieldset, locator, &block) end ## # # Execute the given block within the a specific table given the id or caption of that table. # # @param [String] locator Id or caption of the table # def within_table(locator, &block) within(:table, locator, &block) end ## # # Switch to the given frame. # # If you use this method you are responsible for making sure you switch back to the parent frame when done in the frame changed to. # {#within_frame} is preferred over this method and should be used when possible. # May not be supported by all drivers. # # @overload switch_to_frame(element) # @param [Capybara::Node::Element] element iframe/frame element to switch to # @overload switch_to_frame(location) # @param [Symbol] location relative location of the frame to switch to # * :parent - the parent frame # * :top - the top level document # def switch_to_frame(frame) case frame when Capybara::Node::Element driver.switch_to_frame(frame) scopes.push(:frame) when :parent if scopes.last != :frame raise Capybara::ScopeError, "`switch_to_frame(:parent)` cannot be called from inside a descendant frame's " \ '`within` block.' end scopes.pop driver.switch_to_frame(:parent) when :top idx = scopes.index(:frame) top_level_scopes = [:frame, nil] if idx if scopes.slice(idx..).any? { |scope| !top_level_scopes.include?(scope) } raise Capybara::ScopeError, "`switch_to_frame(:top)` cannot be called from inside a descendant frame's " \ '`within` block.' end scopes.slice!(idx..) driver.switch_to_frame(:top) end else raise ArgumentError, 'You must provide a frame element, :parent, or :top when calling switch_to_frame' end end ## # # Execute the given block within the given iframe using given frame, frame name/id or index. # May not be supported by all drivers. # # @overload within_frame(element) # @param [Capybara::Node::Element] frame element # @overload within_frame([kind = :frame], locator, **options) # @param [Symbol] kind Optional selector type (:frame, :css, :xpath, etc.) - Defaults to :frame # @param [String] locator The locator for the given selector kind. For :frame this is the name/id of a frame/iframe element # @overload within_frame(index) # @param [Integer] index index of a frame (0 based) def within_frame(*args, **kw_args) switch_to_frame(_find_frame(*args, **kw_args)) begin yield if block_given? ensure switch_to_frame(:parent) end end ## # @return [Capybara::Window] current window # def current_window Window.new(self, driver.current_window_handle) end ## # Get all opened windows. # The order of windows in returned array is not defined. # The driver may sort windows by their creation time but it's not required. # # @return [Array<Capybara::Window>] an array of all windows # def windows driver.window_handles.map do |handle| Window.new(self, handle) end end ## # Open a new window. # The current window doesn't change as the result of this call. # It should be switched to explicitly. # # @return [Capybara::Window] window that has been opened # def open_new_window(kind = :tab) window_opened_by do if driver.method(:open_new_window).arity.zero? driver.open_new_window else driver.open_new_window(kind) end end end ## # Switch to the given window. # # @overload switch_to_window(&block) # Switches to the first window for which given block returns a value other than false or nil. # If window that matches block can't be found, the window will be switched back and {Capybara::WindowError} will be raised. # @example # window = switch_to_window { title == 'Page title' } # @raise [Capybara::WindowError] if no window matches given block # @overload switch_to_window(window) # @param window [Capybara::Window] window that should be switched to # @raise [Capybara::Driver::Base#no_such_window_error] if nonexistent (e.g. closed) window was passed # # @return [Capybara::Window] window that has been switched to # @raise [Capybara::ScopeError] if this method is invoked inside {#within} or # {#within_frame} methods # @raise [ArgumentError] if both or neither arguments were provided # def switch_to_window(window = nil, **options, &window_locator) raise ArgumentError, '`switch_to_window` can take either a block or a window, not both' if window && window_locator raise ArgumentError, '`switch_to_window`: either window or block should be provided' if !window && !window_locator unless scopes.last.nil? raise Capybara::ScopeError, '`switch_to_window` is not supposed to be invoked from ' \ '`within` or `within_frame` blocks.' end _switch_to_window(window, **options, &window_locator) end ## # This method does the following: # # 1. Switches to the given window (it can be located by window instance/lambda/string). # 2. Executes the given block (within window located at previous step). # 3. Switches back (this step will be invoked even if an exception occurs at the second step). # # @overload within_window(window) { do_something } # @param window [Capybara::Window] instance of {Capybara::Window} class # that will be switched to # @raise [driver#no_such_window_error] if nonexistent (e.g. closed) window was passed # @overload within_window(proc_or_lambda) { do_something } # @param lambda [Proc] First window for which lambda # returns a value other than false or nil will be switched to. # @example # within_window(->{ page.title == 'Page title' }) { click_button 'Submit' } # @raise [Capybara::WindowError] if no window matching lambda was found # # @raise [Capybara::ScopeError] if this method is invoked inside {#within_frame} method # @return value returned by the block # def within_window(window_or_proc) original = current_window scopes << nil begin case window_or_proc when Capybara::Window _switch_to_window(window_or_proc) unless original == window_or_proc when Proc _switch_to_window { window_or_proc.call } else raise ArgumentError, '`#within_window` requires a `Capybara::Window` instance or a lambda' end begin yield if block_given? ensure _switch_to_window(original) unless original == window_or_proc end ensure scopes.pop end end ## # Get the window that has been opened by the passed block. # It will wait for it to be opened (in the same way as other Capybara methods wait). # It's better to use this method than `windows.last` # {https://dvcs.w3.org/hg/webdriver/raw-file/default/webdriver-spec.html#h_note_10 as order of windows isn't defined in some drivers}. # # @overload window_opened_by(**options, &block) # @param options [Hash] # @option options [Numeric] :wait maximum wait time. Defaults to {Capybara.configure default_max_wait_time} # @return [Capybara::Window] the window that has been opened within a block # @raise [Capybara::WindowError] if block passed to window hasn't opened window # or opened more than one window # def window_opened_by(**options) old_handles = driver.window_handles yield synchronize_windows(options) do opened_handles = (driver.window_handles - old_handles) if opened_handles.size != 1 raise Capybara::WindowError, 'block passed to #window_opened_by ' \ "opened #{opened_handles.size} windows instead of 1" end Window.new(self, opened_handles.first) end end ## # # Execute the given script, not returning a result. This is useful for scripts that return # complex objects, such as jQuery statements. {#execute_script} should be used over # {#evaluate_script} whenever possible. # # @param [String] script A string of JavaScript to execute # @param args Optional arguments that will be passed to the script. Driver support for this is optional and types of objects supported may differ between drivers # def execute_script(script, *args) @touched = true driver.execute_script(script, *driver_args(args)) end ## # # Evaluate the given JavaScript and return the result. Be careful when using this with # scripts that return complex objects, such as jQuery statements. {#execute_script} might # be a better alternative. # # @param [String] script A string of JavaScript to evaluate # @param args Optional arguments that will be passed to the script # @return [Object] The result of the evaluated JavaScript (may be driver specific) # def evaluate_script(script, *args) @touched = true result = driver.evaluate_script(script.strip, *driver_args(args)) element_script_result(result) end ## # # Evaluate the given JavaScript and obtain the result from a callback function which will be passed as the last argument to the script. # # @param [String] script A string of JavaScript to evaluate # @param args Optional arguments that will be passed to the script # @return [Object] The result of the evaluated JavaScript (may be driver specific) # def evaluate_async_script(script, *args) @touched = true result = driver.evaluate_async_script(script, *driver_args(args)) element_script_result(result) end ## # # Execute the block, accepting a alert. # # @!macro modal_params # Expects a block whose actions will trigger the display modal to appear. # @example # $0 do # click_link('link that triggers appearance of system modal') # end # @overload $0(text, **options, &blk) # @param text [String, Regexp] Text or regex to match against the text in the modal. If not provided any modal is matched. # @option options [Numeric] :wait Maximum time to wait for the modal to appear after executing the block. Defaults to {Capybara.configure default_max_wait_time}. # @yield Block whose actions will trigger the system modal # @overload $0(**options, &blk) # @option options [Numeric] :wait Maximum time to wait for the modal to appear after executing the block. Defaults to {Capybara.configure default_max_wait_time}. # @yield Block whose actions will trigger the system modal # @return [String] the message shown in the modal # @raise [Capybara::ModalNotFound] if modal dialog hasn't been found # def accept_alert(text = nil, **options, &blk) accept_modal(:alert, text, options, &blk) end ## # # Execute the block, accepting a confirm. # # @macro modal_params # def accept_confirm(text = nil, **options, &blk) accept_modal(:confirm, text, options, &blk) end ## # # Execute the block, dismissing a confirm. # # @macro modal_params # def dismiss_confirm(text = nil, **options, &blk) dismiss_modal(:confirm, text, options, &blk) end ## # # Execute the block, accepting a prompt, optionally responding to the prompt. # # @macro modal_params # @option options [String] :with Response to provide to the prompt # def accept_prompt(text = nil, **options, &blk) accept_modal(:prompt, text, options, &blk) end ## # # Execute the block, dismissing a prompt. # # @macro modal_params # def dismiss_prompt(text = nil, **options, &blk) dismiss_modal(:prompt, text, options, &blk) end ## # # Save a snapshot of the page. If {Capybara.configure asset_host} is set it will inject `base` tag # pointing to {Capybara.configure asset_host}. # # If invoked without arguments it will save file to {Capybara.configure save_path} # and file will be given randomly generated filename. If invoked with a relative path # the path will be relative to {Capybara.configure save_path}. # # @param [String] path the path to where it should be saved # @return [String] the path to which the file was saved # def save_page(path = nil) prepare_path(path, 'html').tap do |p_path| File.write(p_path, Capybara::Helpers.inject_asset_host(body, host: config.asset_host), mode: 'wb') end end ## # # Save a snapshot of the page and open it in a browser for inspection. # # If invoked without arguments it will save file to {Capybara.configure save_path} # and file will be given randomly generated filename. If invoked with a relative path # the path will be relative to {Capybara.configure save_path}. # # @param [String] path the path to where it should be saved # def save_and_open_page(path = nil) save_page(path).tap { |s_path| open_file(s_path) } end ## # # Save a screenshot of page. # # If invoked without arguments it will save file to {Capybara.configure save_path} # and file will be given randomly generated filename. If invoked with a relative path # the path will be relative to {Capybara.configure save_path}. # # @param [String] path the path to where it should be saved # @param [Hash] options a customizable set of options # @return [String] the path to which the file was saved def save_screenshot(path = nil, **options) prepare_path(path, 'png').tap { |p_path| driver.save_screenshot(p_path, **options) } end ## # # Save a screenshot of the page and open it for inspection. # # If invoked without arguments it will save file to {Capybara.configure save_path} # and file will be given randomly generated filename. If invoked with a relative path # the path will be relative to {Capybara.configure save_path}. # # @param [String] path the path to where it should be saved # @param [Hash] options a customizable set of options # def save_and_open_screenshot(path = nil, **options) save_screenshot(path, **options).tap { |s_path| open_file(s_path) } end def document @document ||= Capybara::Node::Document.new(self, driver) end NODE_METHODS.each do |method| class_eval <<~METHOD, __FILE__, __LINE__ + 1 def #{method}(...) @touched = true current_scope.#{method}(...) end METHOD end DOCUMENT_METHODS.each do |method| class_eval <<~METHOD, __FILE__, __LINE__ + 1 def #{method}(...) document.#{method}(...) end METHOD end def inspect %(#<Capybara::Session>) end def current_scope scope = scopes.last [nil, :frame].include?(scope) ? document : scope end ## # # Yield a block using a specific maximum wait time. # def using_wait_time(seconds, &block) if Capybara.threadsafe begin previous_wait_time = config.default_max_wait_time config.default_max_wait_time = seconds yield ensure config.default_max_wait_time = previous_wait_time end else Capybara.using_wait_time(seconds, &block) end end ## # # Accepts a block to set the configuration options if {Capybara.configure threadsafe} is `true`. Note that some options only have an effect # if set at initialization time, so look at the configuration block that can be passed to the initializer too. # def configure raise 'Session configuration is only supported when Capybara.threadsafe == true' unless Capybara.threadsafe yield config end def self.instance_created? @@instance_created end def config @config ||= if Capybara.threadsafe Capybara.session_options.dup else Capybara::ReadOnlySessionConfig.new(Capybara.session_options) end end def server_url @server&.base_url end private @@instance_created = false # rubocop:disable Style/ClassVars def driver_args(args) args.map { |arg| arg.is_a?(Capybara::Node::Element) ? arg.base : arg } end def accept_modal(type, text_or_options, options, &blk) driver.accept_modal(type, **modal_options(text_or_options, **options), &blk) end def dismiss_modal(type, text_or_options, options, &blk) driver.dismiss_modal(type, **modal_options(text_or_options, **options), &blk) end def modal_options(text = nil, **options) options[:text] ||= text unless text.nil? options[:wait] ||= config.default_max_wait_time options end def open_file(path) require 'launchy' Launchy.open(path) rescue LoadError warn "File saved to #{path}.\nPlease install the launchy gem to open the file automatically." end def prepare_path(path, extension) File.expand_path(path || default_fn(extension), config.save_path).tap do |p_path| FileUtils.mkdir_p(File.dirname(p_path)) end end def default_fn(extension) timestamp = Time.new.strftime('%Y%m%d%H%M%S') "capybara-#{timestamp}#{rand(10**10)}.#{extension}" end def scopes @scopes ||= [nil] end def element_script_result(arg) case arg when Array arg.map { |subarg| element_script_result(subarg) } when Hash arg.transform_values! { |value| element_script_result(value) } when Capybara::Driver::Node Capybara::Node::Element.new(self, arg, nil, nil) else arg end end def adjust_server_port(uri) uri.port ||= @server.port if @server && config.always_include_port end def _find_frame(*args, **kw_args) case args[0] when Capybara::Node::Element args[0] when String, nil find(:frame, *args, **kw_args) when Symbol find(*args, **kw_args) when Integer idx = args[0] all(:frame, minimum: idx + 1)[idx] else raise TypeError end end def _switch_to_window(window = nil, **options, &window_locator) raise Capybara::ScopeError, 'Window cannot be switched inside a `within_frame` block' if scopes.include?(:frame) raise Capybara::ScopeError, 'Window cannot be switched inside a `within` block' unless scopes.last.nil? if window driver.switch_to_window(window.handle) window else synchronize_windows(options) do original_window_handle = driver.current_window_handle begin _switch_to_window_by_locator(&window_locator) rescue StandardError driver.switch_to_window(original_window_handle) raise end end end end def _switch_to_window_by_locator driver.window_handles.each do |handle| driver.switch_to_window handle return Window.new(self, handle) if yield end raise Capybara::WindowError, 'Could not find a window matching block/lambda' end def synchronize_windows(options, &block) wait_time = Capybara::Queries::BaseQuery.wait(options, config.default_max_wait_time) document.synchronize(wait_time, errors: [Capybara::WindowError], &block) end end end
Ruby
{ "end_line": 110, "name": "driver", "signature": "def driver", "start_line": 100 }
{ "class_name": "Session", "class_signature": "class Session", "module": "Capybara" }
reset!
capybara/lib/capybara/session.rb
def reset! if @touched driver.reset! @touched = false switch_to_frame(:top) rescue nil # rubocop:disable Style/RescueModifier @scopes = [nil] end @server&.wait_for_pending_requests raise_server_error! end
# frozen_string_literal: true require 'capybara/session/matchers' require 'addressable/uri' module Capybara ## # # The {Session} class represents a single user's interaction with the system. The {Session} can use # any of the underlying drivers. A session can be initialized manually like this: # # session = Capybara::Session.new(:culerity, MyRackApp) # # The application given as the second argument is optional. When running Capybara against an external # page, you might want to leave it out: # # session = Capybara::Session.new(:culerity) # session.visit('http://www.google.com') # # When {Capybara.configure threadsafe} is `true` the sessions options will be initially set to the # current values of the global options and a configuration block can be passed to the session initializer. # For available options see {Capybara::SessionConfig::OPTIONS}: # # session = Capybara::Session.new(:driver, MyRackApp) do |config| # config.app_host = "http://my_host.dev" # end # # The {Session} provides a number of methods for controlling the navigation of the page, such as {#visit}, # {#current_path}, and so on. It also delegates a number of methods to a {Capybara::Document}, representing # the current HTML document. This allows interaction: # # session.fill_in('q', with: 'Capybara') # session.click_button('Search') # expect(session).to have_content('Capybara') # # When using `capybara/dsl`, the {Session} is initialized automatically for you. # class Session include Capybara::SessionMatchers NODE_METHODS = %i[ all first attach_file text check choose scroll_to scroll_by click double_click right_click click_link_or_button click_button click_link fill_in find find_all find_button find_by_id find_field find_link has_content? has_text? has_css? has_no_content? has_no_text? has_no_css? has_no_xpath? has_xpath? select uncheck has_element? has_no_element? has_link? has_no_link? has_button? has_no_button? has_field? has_no_field? has_checked_field? has_unchecked_field? has_no_table? has_table? unselect has_select? has_no_select? has_selector? has_no_selector? click_on has_no_checked_field? has_no_unchecked_field? query assert_selector assert_no_selector assert_all_of_selectors assert_none_of_selectors assert_any_of_selectors refute_selector assert_text assert_no_text ].freeze # @api private DOCUMENT_METHODS = %i[ title assert_title assert_no_title has_title? has_no_title? ].freeze SESSION_METHODS = %i[ body html source current_url current_host current_path execute_script evaluate_script evaluate_async_script visit refresh go_back go_forward send_keys within within_element within_fieldset within_table within_frame switch_to_frame current_window windows open_new_window switch_to_window within_window window_opened_by save_page save_and_open_page save_screenshot save_and_open_screenshot reset_session! response_headers status_code current_scope assert_current_path assert_no_current_path has_current_path? has_no_current_path? ].freeze + DOCUMENT_METHODS MODAL_METHODS = %i[ accept_alert accept_confirm dismiss_confirm accept_prompt dismiss_prompt ].freeze DSL_METHODS = NODE_METHODS + SESSION_METHODS + MODAL_METHODS attr_reader :mode, :app, :server attr_accessor :synchronized def initialize(mode, app = nil) if app && !app.respond_to?(:call) raise TypeError, 'The second parameter to Session::new should be a rack app if passed.' end @@instance_created = true # rubocop:disable Style/ClassVars @mode = mode @app = app if block_given? raise 'A configuration block is only accepted when Capybara.threadsafe == true' unless Capybara.threadsafe yield config end @server = if config.run_server && @app && driver.needs_server? server_options = { port: config.server_port, host: config.server_host, reportable_errors: config.server_errors } server_options[:extra_middleware] = [Capybara::Server::AnimationDisabler] if config.disable_animation Capybara::Server.new(@app, **server_options).boot end @touched = false end def driver @driver ||= begin unless Capybara.drivers[mode] other_drivers = Capybara.drivers.names.map(&:inspect) raise Capybara::DriverNotFoundError, "no driver called #{mode.inspect} was found, available drivers: #{other_drivers.join(', ')}" end driver = Capybara.drivers[mode].call(app) driver.session = self if driver.respond_to?(:session=) driver end end ## # # Reset the session (i.e. remove cookies and navigate to blank page). # # This method does not: # # * accept modal dialogs if they are present (Selenium driver now does, others may not) # * clear browser cache/HTML 5 local storage/IndexedDB/Web SQL database/etc. # * modify state of the driver/underlying browser in any other way # # as doing so will result in performance downsides and it's not needed to do everything from the list above for most apps. # # If you want to do anything from the list above on a general basis you can: # # * write RSpec/Cucumber/etc. after hook # * monkeypatch this method # * use Ruby's `prepend` method # def reset! if @touched driver.reset! @touched = false switch_to_frame(:top) rescue nil # rubocop:disable Style/RescueModifier @scopes = [nil] end @server&.wait_for_pending_requests raise_server_error! end alias_method :cleanup!, :reset! alias_method :reset_session!, :reset! ## # # Disconnect from the current driver. A new driver will be instantiated on the next interaction. # def quit @driver.quit if @driver.respond_to? :quit @document = @driver = nil @touched = false @server&.reset_error! end ## # # Raise errors encountered in the server. # def raise_server_error! return unless @server&.error # Force an explanation for the error being raised as the exception cause begin if config.raise_server_errors raise CapybaraError, 'Your application server raised an error - It has been raised in your test code because Capybara.raise_server_errors == true' end rescue CapybaraError => capy_error # rubocop:disable Naming/RescuedExceptionsVariableName raise @server.error, cause: capy_error ensure @server.reset_error! end end ## # # Returns a hash of response headers. Not supported by all drivers (e.g. Selenium). # # @return [Hash<String, String>] A hash of response headers. # def response_headers driver.response_headers end ## # # Returns the current HTTP status code as an integer. Not supported by all drivers (e.g. Selenium). # # @return [Integer] Current HTTP status code # def status_code driver.status_code end ## # # @return [String] A snapshot of the DOM of the current document, as it looks right now (potentially modified by JavaScript). # def html driver.html || '' end alias_method :body, :html alias_method :source, :html ## # # @return [String] Path of the current page, without any domain information # def current_path # Addressable parsing is more lenient than URI uri = ::Addressable::URI.parse(current_url) # Addressable doesn't support opaque URIs - we want nil here return nil if uri&.scheme == 'about' path = uri&.path path unless path&.empty? end ## # # @return [String] Host of the current page # def current_host uri = URI.parse(current_url) "#{uri.scheme}://#{uri.host}" if uri.host end ## # # @return [String] Fully qualified URL of the current page # def current_url driver.current_url end ## # # Navigate to the given URL. The URL can either be a relative URL or an absolute URL # The behaviour of either depends on the driver. # # session.visit('/foo') # session.visit('http://google.com') # # For drivers which can run against an external application, such as the selenium driver # giving an absolute URL will navigate to that page. This allows testing applications # running on remote servers. For these drivers, setting {Capybara.configure app_host} will make the # remote server the default. For example: # # Capybara.app_host = 'http://google.com' # session.visit('/') # visits the google homepage # # If {Capybara.configure always_include_port} is set to `true` and this session is running against # a rack application, then the port that the rack application is running on will automatically # be inserted into the URL. Supposing the app is running on port `4567`, doing something like: # # visit("http://google.com/test") # # Will actually navigate to `http://google.com:4567/test`. # # @param [#to_s] visit_uri The URL to navigate to. The parameter will be cast to a String. # def visit(visit_uri) raise_server_error! @touched = true visit_uri = ::Addressable::URI.parse(visit_uri.to_s) base_uri = ::Addressable::URI.parse(config.app_host || server_url) if base_uri && [nil, 'http', 'https'].include?(visit_uri.scheme) if visit_uri.relative? visit_uri_parts = visit_uri.to_hash.compact # Useful to people deploying to a subdirectory # and/or single page apps where only the url fragment changes visit_uri_parts[:path] = base_uri.path + visit_uri.path visit_uri = base_uri.merge(visit_uri_parts) end adjust_server_port(visit_uri) end driver.visit(visit_uri.to_s) end ## # # Refresh the page. # def refresh raise_server_error! driver.refresh end ## # # Move back a single entry in the browser's history. # def go_back driver.go_back end ## # # Move forward a single entry in the browser's history. # def go_forward driver.go_forward end ## # @!method send_keys # @see Capybara::Node::Element#send_keys # def send_keys(...) driver.send_keys(...) end ## # # Returns the element with focus. # # Not supported by Rack Test # def active_element Capybara::Queries::ActiveElementQuery.new.resolve_for(self)[0].tap(&:allow_reload!) end ## # # Executes the given block within the context of a node. {#within} takes the # same options as {Capybara::Node::Finders#find #find}, as well as a block. For the duration of the # block, any command to Capybara will be handled as though it were scoped # to the given element. # # within(:xpath, './/div[@id="delivery-address"]') do # fill_in('Street', with: '12 Main Street') # end # # Just as with `#find`, if multiple elements match the selector given to # {#within}, an error will be raised, and just as with `#find`, this # behaviour can be controlled through the `:match` and `:exact` options. # # It is possible to omit the first parameter, in that case, the selector is # assumed to be of the type set in {Capybara.configure default_selector}. # # within('div#delivery-address') do # fill_in('Street', with: '12 Main Street') # end # # Note that a lot of uses of {#within} can be replaced more succinctly with # chaining: # # find('div#delivery-address').fill_in('Street', with: '12 Main Street') # # @overload within(*find_args) # @param (see Capybara::Node::Finders#all) # # @overload within(a_node) # @param [Capybara::Node::Base] a_node The node in whose scope the block should be evaluated # # @raise [Capybara::ElementNotFound] If the scope can't be found before time expires # def within(*args, **kw_args) new_scope = args.first.respond_to?(:to_capybara_node) ? args.first.to_capybara_node : find(*args, **kw_args) begin scopes.push(new_scope) yield new_scope if block_given? ensure scopes.pop end end alias_method :within_element, :within ## # # Execute the given block within the a specific fieldset given the id or legend of that fieldset. # # @param [String] locator Id or legend of the fieldset # def within_fieldset(locator, &block) within(:fieldset, locator, &block) end ## # # Execute the given block within the a specific table given the id or caption of that table. # # @param [String] locator Id or caption of the table # def within_table(locator, &block) within(:table, locator, &block) end ## # # Switch to the given frame. # # If you use this method you are responsible for making sure you switch back to the parent frame when done in the frame changed to. # {#within_frame} is preferred over this method and should be used when possible. # May not be supported by all drivers. # # @overload switch_to_frame(element) # @param [Capybara::Node::Element] element iframe/frame element to switch to # @overload switch_to_frame(location) # @param [Symbol] location relative location of the frame to switch to # * :parent - the parent frame # * :top - the top level document # def switch_to_frame(frame) case frame when Capybara::Node::Element driver.switch_to_frame(frame) scopes.push(:frame) when :parent if scopes.last != :frame raise Capybara::ScopeError, "`switch_to_frame(:parent)` cannot be called from inside a descendant frame's " \ '`within` block.' end scopes.pop driver.switch_to_frame(:parent) when :top idx = scopes.index(:frame) top_level_scopes = [:frame, nil] if idx if scopes.slice(idx..).any? { |scope| !top_level_scopes.include?(scope) } raise Capybara::ScopeError, "`switch_to_frame(:top)` cannot be called from inside a descendant frame's " \ '`within` block.' end scopes.slice!(idx..) driver.switch_to_frame(:top) end else raise ArgumentError, 'You must provide a frame element, :parent, or :top when calling switch_to_frame' end end ## # # Execute the given block within the given iframe using given frame, frame name/id or index. # May not be supported by all drivers. # # @overload within_frame(element) # @param [Capybara::Node::Element] frame element # @overload within_frame([kind = :frame], locator, **options) # @param [Symbol] kind Optional selector type (:frame, :css, :xpath, etc.) - Defaults to :frame # @param [String] locator The locator for the given selector kind. For :frame this is the name/id of a frame/iframe element # @overload within_frame(index) # @param [Integer] index index of a frame (0 based) def within_frame(*args, **kw_args) switch_to_frame(_find_frame(*args, **kw_args)) begin yield if block_given? ensure switch_to_frame(:parent) end end ## # @return [Capybara::Window] current window # def current_window Window.new(self, driver.current_window_handle) end ## # Get all opened windows. # The order of windows in returned array is not defined. # The driver may sort windows by their creation time but it's not required. # # @return [Array<Capybara::Window>] an array of all windows # def windows driver.window_handles.map do |handle| Window.new(self, handle) end end ## # Open a new window. # The current window doesn't change as the result of this call. # It should be switched to explicitly. # # @return [Capybara::Window] window that has been opened # def open_new_window(kind = :tab) window_opened_by do if driver.method(:open_new_window).arity.zero? driver.open_new_window else driver.open_new_window(kind) end end end ## # Switch to the given window. # # @overload switch_to_window(&block) # Switches to the first window for which given block returns a value other than false or nil. # If window that matches block can't be found, the window will be switched back and {Capybara::WindowError} will be raised. # @example # window = switch_to_window { title == 'Page title' } # @raise [Capybara::WindowError] if no window matches given block # @overload switch_to_window(window) # @param window [Capybara::Window] window that should be switched to # @raise [Capybara::Driver::Base#no_such_window_error] if nonexistent (e.g. closed) window was passed # # @return [Capybara::Window] window that has been switched to # @raise [Capybara::ScopeError] if this method is invoked inside {#within} or # {#within_frame} methods # @raise [ArgumentError] if both or neither arguments were provided # def switch_to_window(window = nil, **options, &window_locator) raise ArgumentError, '`switch_to_window` can take either a block or a window, not both' if window && window_locator raise ArgumentError, '`switch_to_window`: either window or block should be provided' if !window && !window_locator unless scopes.last.nil? raise Capybara::ScopeError, '`switch_to_window` is not supposed to be invoked from ' \ '`within` or `within_frame` blocks.' end _switch_to_window(window, **options, &window_locator) end ## # This method does the following: # # 1. Switches to the given window (it can be located by window instance/lambda/string). # 2. Executes the given block (within window located at previous step). # 3. Switches back (this step will be invoked even if an exception occurs at the second step). # # @overload within_window(window) { do_something } # @param window [Capybara::Window] instance of {Capybara::Window} class # that will be switched to # @raise [driver#no_such_window_error] if nonexistent (e.g. closed) window was passed # @overload within_window(proc_or_lambda) { do_something } # @param lambda [Proc] First window for which lambda # returns a value other than false or nil will be switched to. # @example # within_window(->{ page.title == 'Page title' }) { click_button 'Submit' } # @raise [Capybara::WindowError] if no window matching lambda was found # # @raise [Capybara::ScopeError] if this method is invoked inside {#within_frame} method # @return value returned by the block # def within_window(window_or_proc) original = current_window scopes << nil begin case window_or_proc when Capybara::Window _switch_to_window(window_or_proc) unless original == window_or_proc when Proc _switch_to_window { window_or_proc.call } else raise ArgumentError, '`#within_window` requires a `Capybara::Window` instance or a lambda' end begin yield if block_given? ensure _switch_to_window(original) unless original == window_or_proc end ensure scopes.pop end end ## # Get the window that has been opened by the passed block. # It will wait for it to be opened (in the same way as other Capybara methods wait). # It's better to use this method than `windows.last` # {https://dvcs.w3.org/hg/webdriver/raw-file/default/webdriver-spec.html#h_note_10 as order of windows isn't defined in some drivers}. # # @overload window_opened_by(**options, &block) # @param options [Hash] # @option options [Numeric] :wait maximum wait time. Defaults to {Capybara.configure default_max_wait_time} # @return [Capybara::Window] the window that has been opened within a block # @raise [Capybara::WindowError] if block passed to window hasn't opened window # or opened more than one window # def window_opened_by(**options) old_handles = driver.window_handles yield synchronize_windows(options) do opened_handles = (driver.window_handles - old_handles) if opened_handles.size != 1 raise Capybara::WindowError, 'block passed to #window_opened_by ' \ "opened #{opened_handles.size} windows instead of 1" end Window.new(self, opened_handles.first) end end ## # # Execute the given script, not returning a result. This is useful for scripts that return # complex objects, such as jQuery statements. {#execute_script} should be used over # {#evaluate_script} whenever possible. # # @param [String] script A string of JavaScript to execute # @param args Optional arguments that will be passed to the script. Driver support for this is optional and types of objects supported may differ between drivers # def execute_script(script, *args) @touched = true driver.execute_script(script, *driver_args(args)) end ## # # Evaluate the given JavaScript and return the result. Be careful when using this with # scripts that return complex objects, such as jQuery statements. {#execute_script} might # be a better alternative. # # @param [String] script A string of JavaScript to evaluate # @param args Optional arguments that will be passed to the script # @return [Object] The result of the evaluated JavaScript (may be driver specific) # def evaluate_script(script, *args) @touched = true result = driver.evaluate_script(script.strip, *driver_args(args)) element_script_result(result) end ## # # Evaluate the given JavaScript and obtain the result from a callback function which will be passed as the last argument to the script. # # @param [String] script A string of JavaScript to evaluate # @param args Optional arguments that will be passed to the script # @return [Object] The result of the evaluated JavaScript (may be driver specific) # def evaluate_async_script(script, *args) @touched = true result = driver.evaluate_async_script(script, *driver_args(args)) element_script_result(result) end ## # # Execute the block, accepting a alert. # # @!macro modal_params # Expects a block whose actions will trigger the display modal to appear. # @example # $0 do # click_link('link that triggers appearance of system modal') # end # @overload $0(text, **options, &blk) # @param text [String, Regexp] Text or regex to match against the text in the modal. If not provided any modal is matched. # @option options [Numeric] :wait Maximum time to wait for the modal to appear after executing the block. Defaults to {Capybara.configure default_max_wait_time}. # @yield Block whose actions will trigger the system modal # @overload $0(**options, &blk) # @option options [Numeric] :wait Maximum time to wait for the modal to appear after executing the block. Defaults to {Capybara.configure default_max_wait_time}. # @yield Block whose actions will trigger the system modal # @return [String] the message shown in the modal # @raise [Capybara::ModalNotFound] if modal dialog hasn't been found # def accept_alert(text = nil, **options, &blk) accept_modal(:alert, text, options, &blk) end ## # # Execute the block, accepting a confirm. # # @macro modal_params # def accept_confirm(text = nil, **options, &blk) accept_modal(:confirm, text, options, &blk) end ## # # Execute the block, dismissing a confirm. # # @macro modal_params # def dismiss_confirm(text = nil, **options, &blk) dismiss_modal(:confirm, text, options, &blk) end ## # # Execute the block, accepting a prompt, optionally responding to the prompt. # # @macro modal_params # @option options [String] :with Response to provide to the prompt # def accept_prompt(text = nil, **options, &blk) accept_modal(:prompt, text, options, &blk) end ## # # Execute the block, dismissing a prompt. # # @macro modal_params # def dismiss_prompt(text = nil, **options, &blk) dismiss_modal(:prompt, text, options, &blk) end ## # # Save a snapshot of the page. If {Capybara.configure asset_host} is set it will inject `base` tag # pointing to {Capybara.configure asset_host}. # # If invoked without arguments it will save file to {Capybara.configure save_path} # and file will be given randomly generated filename. If invoked with a relative path # the path will be relative to {Capybara.configure save_path}. # # @param [String] path the path to where it should be saved # @return [String] the path to which the file was saved # def save_page(path = nil) prepare_path(path, 'html').tap do |p_path| File.write(p_path, Capybara::Helpers.inject_asset_host(body, host: config.asset_host), mode: 'wb') end end ## # # Save a snapshot of the page and open it in a browser for inspection. # # If invoked without arguments it will save file to {Capybara.configure save_path} # and file will be given randomly generated filename. If invoked with a relative path # the path will be relative to {Capybara.configure save_path}. # # @param [String] path the path to where it should be saved # def save_and_open_page(path = nil) save_page(path).tap { |s_path| open_file(s_path) } end ## # # Save a screenshot of page. # # If invoked without arguments it will save file to {Capybara.configure save_path} # and file will be given randomly generated filename. If invoked with a relative path # the path will be relative to {Capybara.configure save_path}. # # @param [String] path the path to where it should be saved # @param [Hash] options a customizable set of options # @return [String] the path to which the file was saved def save_screenshot(path = nil, **options) prepare_path(path, 'png').tap { |p_path| driver.save_screenshot(p_path, **options) } end ## # # Save a screenshot of the page and open it for inspection. # # If invoked without arguments it will save file to {Capybara.configure save_path} # and file will be given randomly generated filename. If invoked with a relative path # the path will be relative to {Capybara.configure save_path}. # # @param [String] path the path to where it should be saved # @param [Hash] options a customizable set of options # def save_and_open_screenshot(path = nil, **options) save_screenshot(path, **options).tap { |s_path| open_file(s_path) } end def document @document ||= Capybara::Node::Document.new(self, driver) end NODE_METHODS.each do |method| class_eval <<~METHOD, __FILE__, __LINE__ + 1 def #{method}(...) @touched = true current_scope.#{method}(...) end METHOD end DOCUMENT_METHODS.each do |method| class_eval <<~METHOD, __FILE__, __LINE__ + 1 def #{method}(...) document.#{method}(...) end METHOD end def inspect %(#<Capybara::Session>) end def current_scope scope = scopes.last [nil, :frame].include?(scope) ? document : scope end ## # # Yield a block using a specific maximum wait time. # def using_wait_time(seconds, &block) if Capybara.threadsafe begin previous_wait_time = config.default_max_wait_time config.default_max_wait_time = seconds yield ensure config.default_max_wait_time = previous_wait_time end else Capybara.using_wait_time(seconds, &block) end end ## # # Accepts a block to set the configuration options if {Capybara.configure threadsafe} is `true`. Note that some options only have an effect # if set at initialization time, so look at the configuration block that can be passed to the initializer too. # def configure raise 'Session configuration is only supported when Capybara.threadsafe == true' unless Capybara.threadsafe yield config end def self.instance_created? @@instance_created end def config @config ||= if Capybara.threadsafe Capybara.session_options.dup else Capybara::ReadOnlySessionConfig.new(Capybara.session_options) end end def server_url @server&.base_url end private @@instance_created = false # rubocop:disable Style/ClassVars def driver_args(args) args.map { |arg| arg.is_a?(Capybara::Node::Element) ? arg.base : arg } end def accept_modal(type, text_or_options, options, &blk) driver.accept_modal(type, **modal_options(text_or_options, **options), &blk) end def dismiss_modal(type, text_or_options, options, &blk) driver.dismiss_modal(type, **modal_options(text_or_options, **options), &blk) end def modal_options(text = nil, **options) options[:text] ||= text unless text.nil? options[:wait] ||= config.default_max_wait_time options end def open_file(path) require 'launchy' Launchy.open(path) rescue LoadError warn "File saved to #{path}.\nPlease install the launchy gem to open the file automatically." end def prepare_path(path, extension) File.expand_path(path || default_fn(extension), config.save_path).tap do |p_path| FileUtils.mkdir_p(File.dirname(p_path)) end end def default_fn(extension) timestamp = Time.new.strftime('%Y%m%d%H%M%S') "capybara-#{timestamp}#{rand(10**10)}.#{extension}" end def scopes @scopes ||= [nil] end def element_script_result(arg) case arg when Array arg.map { |subarg| element_script_result(subarg) } when Hash arg.transform_values! { |value| element_script_result(value) } when Capybara::Driver::Node Capybara::Node::Element.new(self, arg, nil, nil) else arg end end def adjust_server_port(uri) uri.port ||= @server.port if @server && config.always_include_port end def _find_frame(*args, **kw_args) case args[0] when Capybara::Node::Element args[0] when String, nil find(:frame, *args, **kw_args) when Symbol find(*args, **kw_args) when Integer idx = args[0] all(:frame, minimum: idx + 1)[idx] else raise TypeError end end def _switch_to_window(window = nil, **options, &window_locator) raise Capybara::ScopeError, 'Window cannot be switched inside a `within_frame` block' if scopes.include?(:frame) raise Capybara::ScopeError, 'Window cannot be switched inside a `within` block' unless scopes.last.nil? if window driver.switch_to_window(window.handle) window else synchronize_windows(options) do original_window_handle = driver.current_window_handle begin _switch_to_window_by_locator(&window_locator) rescue StandardError driver.switch_to_window(original_window_handle) raise end end end end def _switch_to_window_by_locator driver.window_handles.each do |handle| driver.switch_to_window handle return Window.new(self, handle) if yield end raise Capybara::WindowError, 'Could not find a window matching block/lambda' end def synchronize_windows(options, &block) wait_time = Capybara::Queries::BaseQuery.wait(options, config.default_max_wait_time) document.synchronize(wait_time, errors: [Capybara::WindowError], &block) end end end
Ruby
{ "end_line": 139, "name": "reset!", "signature": "def reset!", "start_line": 130 }
{ "class_name": "Session", "class_signature": "class Session", "module": "Capybara" }
raise_server_error!
capybara/lib/capybara/session.rb
def raise_server_error! return unless @server&.error # Force an explanation for the error being raised as the exception cause begin if config.raise_server_errors raise CapybaraError, 'Your application server raised an error - It has been raised in your test code because Capybara.raise_server_errors == true' end rescue CapybaraError => capy_error # rubocop:disable Naming/RescuedExceptionsVariableName raise @server.error, cause: capy_error ensure @server.reset_error! end end
# frozen_string_literal: true require 'capybara/session/matchers' require 'addressable/uri' module Capybara ## # # The {Session} class represents a single user's interaction with the system. The {Session} can use # any of the underlying drivers. A session can be initialized manually like this: # # session = Capybara::Session.new(:culerity, MyRackApp) # # The application given as the second argument is optional. When running Capybara against an external # page, you might want to leave it out: # # session = Capybara::Session.new(:culerity) # session.visit('http://www.google.com') # # When {Capybara.configure threadsafe} is `true` the sessions options will be initially set to the # current values of the global options and a configuration block can be passed to the session initializer. # For available options see {Capybara::SessionConfig::OPTIONS}: # # session = Capybara::Session.new(:driver, MyRackApp) do |config| # config.app_host = "http://my_host.dev" # end # # The {Session} provides a number of methods for controlling the navigation of the page, such as {#visit}, # {#current_path}, and so on. It also delegates a number of methods to a {Capybara::Document}, representing # the current HTML document. This allows interaction: # # session.fill_in('q', with: 'Capybara') # session.click_button('Search') # expect(session).to have_content('Capybara') # # When using `capybara/dsl`, the {Session} is initialized automatically for you. # class Session include Capybara::SessionMatchers NODE_METHODS = %i[ all first attach_file text check choose scroll_to scroll_by click double_click right_click click_link_or_button click_button click_link fill_in find find_all find_button find_by_id find_field find_link has_content? has_text? has_css? has_no_content? has_no_text? has_no_css? has_no_xpath? has_xpath? select uncheck has_element? has_no_element? has_link? has_no_link? has_button? has_no_button? has_field? has_no_field? has_checked_field? has_unchecked_field? has_no_table? has_table? unselect has_select? has_no_select? has_selector? has_no_selector? click_on has_no_checked_field? has_no_unchecked_field? query assert_selector assert_no_selector assert_all_of_selectors assert_none_of_selectors assert_any_of_selectors refute_selector assert_text assert_no_text ].freeze # @api private DOCUMENT_METHODS = %i[ title assert_title assert_no_title has_title? has_no_title? ].freeze SESSION_METHODS = %i[ body html source current_url current_host current_path execute_script evaluate_script evaluate_async_script visit refresh go_back go_forward send_keys within within_element within_fieldset within_table within_frame switch_to_frame current_window windows open_new_window switch_to_window within_window window_opened_by save_page save_and_open_page save_screenshot save_and_open_screenshot reset_session! response_headers status_code current_scope assert_current_path assert_no_current_path has_current_path? has_no_current_path? ].freeze + DOCUMENT_METHODS MODAL_METHODS = %i[ accept_alert accept_confirm dismiss_confirm accept_prompt dismiss_prompt ].freeze DSL_METHODS = NODE_METHODS + SESSION_METHODS + MODAL_METHODS attr_reader :mode, :app, :server attr_accessor :synchronized def initialize(mode, app = nil) if app && !app.respond_to?(:call) raise TypeError, 'The second parameter to Session::new should be a rack app if passed.' end @@instance_created = true # rubocop:disable Style/ClassVars @mode = mode @app = app if block_given? raise 'A configuration block is only accepted when Capybara.threadsafe == true' unless Capybara.threadsafe yield config end @server = if config.run_server && @app && driver.needs_server? server_options = { port: config.server_port, host: config.server_host, reportable_errors: config.server_errors } server_options[:extra_middleware] = [Capybara::Server::AnimationDisabler] if config.disable_animation Capybara::Server.new(@app, **server_options).boot end @touched = false end def driver @driver ||= begin unless Capybara.drivers[mode] other_drivers = Capybara.drivers.names.map(&:inspect) raise Capybara::DriverNotFoundError, "no driver called #{mode.inspect} was found, available drivers: #{other_drivers.join(', ')}" end driver = Capybara.drivers[mode].call(app) driver.session = self if driver.respond_to?(:session=) driver end end ## # # Reset the session (i.e. remove cookies and navigate to blank page). # # This method does not: # # * accept modal dialogs if they are present (Selenium driver now does, others may not) # * clear browser cache/HTML 5 local storage/IndexedDB/Web SQL database/etc. # * modify state of the driver/underlying browser in any other way # # as doing so will result in performance downsides and it's not needed to do everything from the list above for most apps. # # If you want to do anything from the list above on a general basis you can: # # * write RSpec/Cucumber/etc. after hook # * monkeypatch this method # * use Ruby's `prepend` method # def reset! if @touched driver.reset! @touched = false switch_to_frame(:top) rescue nil # rubocop:disable Style/RescueModifier @scopes = [nil] end @server&.wait_for_pending_requests raise_server_error! end alias_method :cleanup!, :reset! alias_method :reset_session!, :reset! ## # # Disconnect from the current driver. A new driver will be instantiated on the next interaction. # def quit @driver.quit if @driver.respond_to? :quit @document = @driver = nil @touched = false @server&.reset_error! end ## # # Raise errors encountered in the server. # def raise_server_error! return unless @server&.error # Force an explanation for the error being raised as the exception cause begin if config.raise_server_errors raise CapybaraError, 'Your application server raised an error - It has been raised in your test code because Capybara.raise_server_errors == true' end rescue CapybaraError => capy_error # rubocop:disable Naming/RescuedExceptionsVariableName raise @server.error, cause: capy_error ensure @server.reset_error! end end ## # # Returns a hash of response headers. Not supported by all drivers (e.g. Selenium). # # @return [Hash<String, String>] A hash of response headers. # def response_headers driver.response_headers end ## # # Returns the current HTTP status code as an integer. Not supported by all drivers (e.g. Selenium). # # @return [Integer] Current HTTP status code # def status_code driver.status_code end ## # # @return [String] A snapshot of the DOM of the current document, as it looks right now (potentially modified by JavaScript). # def html driver.html || '' end alias_method :body, :html alias_method :source, :html ## # # @return [String] Path of the current page, without any domain information # def current_path # Addressable parsing is more lenient than URI uri = ::Addressable::URI.parse(current_url) # Addressable doesn't support opaque URIs - we want nil here return nil if uri&.scheme == 'about' path = uri&.path path unless path&.empty? end ## # # @return [String] Host of the current page # def current_host uri = URI.parse(current_url) "#{uri.scheme}://#{uri.host}" if uri.host end ## # # @return [String] Fully qualified URL of the current page # def current_url driver.current_url end ## # # Navigate to the given URL. The URL can either be a relative URL or an absolute URL # The behaviour of either depends on the driver. # # session.visit('/foo') # session.visit('http://google.com') # # For drivers which can run against an external application, such as the selenium driver # giving an absolute URL will navigate to that page. This allows testing applications # running on remote servers. For these drivers, setting {Capybara.configure app_host} will make the # remote server the default. For example: # # Capybara.app_host = 'http://google.com' # session.visit('/') # visits the google homepage # # If {Capybara.configure always_include_port} is set to `true` and this session is running against # a rack application, then the port that the rack application is running on will automatically # be inserted into the URL. Supposing the app is running on port `4567`, doing something like: # # visit("http://google.com/test") # # Will actually navigate to `http://google.com:4567/test`. # # @param [#to_s] visit_uri The URL to navigate to. The parameter will be cast to a String. # def visit(visit_uri) raise_server_error! @touched = true visit_uri = ::Addressable::URI.parse(visit_uri.to_s) base_uri = ::Addressable::URI.parse(config.app_host || server_url) if base_uri && [nil, 'http', 'https'].include?(visit_uri.scheme) if visit_uri.relative? visit_uri_parts = visit_uri.to_hash.compact # Useful to people deploying to a subdirectory # and/or single page apps where only the url fragment changes visit_uri_parts[:path] = base_uri.path + visit_uri.path visit_uri = base_uri.merge(visit_uri_parts) end adjust_server_port(visit_uri) end driver.visit(visit_uri.to_s) end ## # # Refresh the page. # def refresh raise_server_error! driver.refresh end ## # # Move back a single entry in the browser's history. # def go_back driver.go_back end ## # # Move forward a single entry in the browser's history. # def go_forward driver.go_forward end ## # @!method send_keys # @see Capybara::Node::Element#send_keys # def send_keys(...) driver.send_keys(...) end ## # # Returns the element with focus. # # Not supported by Rack Test # def active_element Capybara::Queries::ActiveElementQuery.new.resolve_for(self)[0].tap(&:allow_reload!) end ## # # Executes the given block within the context of a node. {#within} takes the # same options as {Capybara::Node::Finders#find #find}, as well as a block. For the duration of the # block, any command to Capybara will be handled as though it were scoped # to the given element. # # within(:xpath, './/div[@id="delivery-address"]') do # fill_in('Street', with: '12 Main Street') # end # # Just as with `#find`, if multiple elements match the selector given to # {#within}, an error will be raised, and just as with `#find`, this # behaviour can be controlled through the `:match` and `:exact` options. # # It is possible to omit the first parameter, in that case, the selector is # assumed to be of the type set in {Capybara.configure default_selector}. # # within('div#delivery-address') do # fill_in('Street', with: '12 Main Street') # end # # Note that a lot of uses of {#within} can be replaced more succinctly with # chaining: # # find('div#delivery-address').fill_in('Street', with: '12 Main Street') # # @overload within(*find_args) # @param (see Capybara::Node::Finders#all) # # @overload within(a_node) # @param [Capybara::Node::Base] a_node The node in whose scope the block should be evaluated # # @raise [Capybara::ElementNotFound] If the scope can't be found before time expires # def within(*args, **kw_args) new_scope = args.first.respond_to?(:to_capybara_node) ? args.first.to_capybara_node : find(*args, **kw_args) begin scopes.push(new_scope) yield new_scope if block_given? ensure scopes.pop end end alias_method :within_element, :within ## # # Execute the given block within the a specific fieldset given the id or legend of that fieldset. # # @param [String] locator Id or legend of the fieldset # def within_fieldset(locator, &block) within(:fieldset, locator, &block) end ## # # Execute the given block within the a specific table given the id or caption of that table. # # @param [String] locator Id or caption of the table # def within_table(locator, &block) within(:table, locator, &block) end ## # # Switch to the given frame. # # If you use this method you are responsible for making sure you switch back to the parent frame when done in the frame changed to. # {#within_frame} is preferred over this method and should be used when possible. # May not be supported by all drivers. # # @overload switch_to_frame(element) # @param [Capybara::Node::Element] element iframe/frame element to switch to # @overload switch_to_frame(location) # @param [Symbol] location relative location of the frame to switch to # * :parent - the parent frame # * :top - the top level document # def switch_to_frame(frame) case frame when Capybara::Node::Element driver.switch_to_frame(frame) scopes.push(:frame) when :parent if scopes.last != :frame raise Capybara::ScopeError, "`switch_to_frame(:parent)` cannot be called from inside a descendant frame's " \ '`within` block.' end scopes.pop driver.switch_to_frame(:parent) when :top idx = scopes.index(:frame) top_level_scopes = [:frame, nil] if idx if scopes.slice(idx..).any? { |scope| !top_level_scopes.include?(scope) } raise Capybara::ScopeError, "`switch_to_frame(:top)` cannot be called from inside a descendant frame's " \ '`within` block.' end scopes.slice!(idx..) driver.switch_to_frame(:top) end else raise ArgumentError, 'You must provide a frame element, :parent, or :top when calling switch_to_frame' end end ## # # Execute the given block within the given iframe using given frame, frame name/id or index. # May not be supported by all drivers. # # @overload within_frame(element) # @param [Capybara::Node::Element] frame element # @overload within_frame([kind = :frame], locator, **options) # @param [Symbol] kind Optional selector type (:frame, :css, :xpath, etc.) - Defaults to :frame # @param [String] locator The locator for the given selector kind. For :frame this is the name/id of a frame/iframe element # @overload within_frame(index) # @param [Integer] index index of a frame (0 based) def within_frame(*args, **kw_args) switch_to_frame(_find_frame(*args, **kw_args)) begin yield if block_given? ensure switch_to_frame(:parent) end end ## # @return [Capybara::Window] current window # def current_window Window.new(self, driver.current_window_handle) end ## # Get all opened windows. # The order of windows in returned array is not defined. # The driver may sort windows by their creation time but it's not required. # # @return [Array<Capybara::Window>] an array of all windows # def windows driver.window_handles.map do |handle| Window.new(self, handle) end end ## # Open a new window. # The current window doesn't change as the result of this call. # It should be switched to explicitly. # # @return [Capybara::Window] window that has been opened # def open_new_window(kind = :tab) window_opened_by do if driver.method(:open_new_window).arity.zero? driver.open_new_window else driver.open_new_window(kind) end end end ## # Switch to the given window. # # @overload switch_to_window(&block) # Switches to the first window for which given block returns a value other than false or nil. # If window that matches block can't be found, the window will be switched back and {Capybara::WindowError} will be raised. # @example # window = switch_to_window { title == 'Page title' } # @raise [Capybara::WindowError] if no window matches given block # @overload switch_to_window(window) # @param window [Capybara::Window] window that should be switched to # @raise [Capybara::Driver::Base#no_such_window_error] if nonexistent (e.g. closed) window was passed # # @return [Capybara::Window] window that has been switched to # @raise [Capybara::ScopeError] if this method is invoked inside {#within} or # {#within_frame} methods # @raise [ArgumentError] if both or neither arguments were provided # def switch_to_window(window = nil, **options, &window_locator) raise ArgumentError, '`switch_to_window` can take either a block or a window, not both' if window && window_locator raise ArgumentError, '`switch_to_window`: either window or block should be provided' if !window && !window_locator unless scopes.last.nil? raise Capybara::ScopeError, '`switch_to_window` is not supposed to be invoked from ' \ '`within` or `within_frame` blocks.' end _switch_to_window(window, **options, &window_locator) end ## # This method does the following: # # 1. Switches to the given window (it can be located by window instance/lambda/string). # 2. Executes the given block (within window located at previous step). # 3. Switches back (this step will be invoked even if an exception occurs at the second step). # # @overload within_window(window) { do_something } # @param window [Capybara::Window] instance of {Capybara::Window} class # that will be switched to # @raise [driver#no_such_window_error] if nonexistent (e.g. closed) window was passed # @overload within_window(proc_or_lambda) { do_something } # @param lambda [Proc] First window for which lambda # returns a value other than false or nil will be switched to. # @example # within_window(->{ page.title == 'Page title' }) { click_button 'Submit' } # @raise [Capybara::WindowError] if no window matching lambda was found # # @raise [Capybara::ScopeError] if this method is invoked inside {#within_frame} method # @return value returned by the block # def within_window(window_or_proc) original = current_window scopes << nil begin case window_or_proc when Capybara::Window _switch_to_window(window_or_proc) unless original == window_or_proc when Proc _switch_to_window { window_or_proc.call } else raise ArgumentError, '`#within_window` requires a `Capybara::Window` instance or a lambda' end begin yield if block_given? ensure _switch_to_window(original) unless original == window_or_proc end ensure scopes.pop end end ## # Get the window that has been opened by the passed block. # It will wait for it to be opened (in the same way as other Capybara methods wait). # It's better to use this method than `windows.last` # {https://dvcs.w3.org/hg/webdriver/raw-file/default/webdriver-spec.html#h_note_10 as order of windows isn't defined in some drivers}. # # @overload window_opened_by(**options, &block) # @param options [Hash] # @option options [Numeric] :wait maximum wait time. Defaults to {Capybara.configure default_max_wait_time} # @return [Capybara::Window] the window that has been opened within a block # @raise [Capybara::WindowError] if block passed to window hasn't opened window # or opened more than one window # def window_opened_by(**options) old_handles = driver.window_handles yield synchronize_windows(options) do opened_handles = (driver.window_handles - old_handles) if opened_handles.size != 1 raise Capybara::WindowError, 'block passed to #window_opened_by ' \ "opened #{opened_handles.size} windows instead of 1" end Window.new(self, opened_handles.first) end end ## # # Execute the given script, not returning a result. This is useful for scripts that return # complex objects, such as jQuery statements. {#execute_script} should be used over # {#evaluate_script} whenever possible. # # @param [String] script A string of JavaScript to execute # @param args Optional arguments that will be passed to the script. Driver support for this is optional and types of objects supported may differ between drivers # def execute_script(script, *args) @touched = true driver.execute_script(script, *driver_args(args)) end ## # # Evaluate the given JavaScript and return the result. Be careful when using this with # scripts that return complex objects, such as jQuery statements. {#execute_script} might # be a better alternative. # # @param [String] script A string of JavaScript to evaluate # @param args Optional arguments that will be passed to the script # @return [Object] The result of the evaluated JavaScript (may be driver specific) # def evaluate_script(script, *args) @touched = true result = driver.evaluate_script(script.strip, *driver_args(args)) element_script_result(result) end ## # # Evaluate the given JavaScript and obtain the result from a callback function which will be passed as the last argument to the script. # # @param [String] script A string of JavaScript to evaluate # @param args Optional arguments that will be passed to the script # @return [Object] The result of the evaluated JavaScript (may be driver specific) # def evaluate_async_script(script, *args) @touched = true result = driver.evaluate_async_script(script, *driver_args(args)) element_script_result(result) end ## # # Execute the block, accepting a alert. # # @!macro modal_params # Expects a block whose actions will trigger the display modal to appear. # @example # $0 do # click_link('link that triggers appearance of system modal') # end # @overload $0(text, **options, &blk) # @param text [String, Regexp] Text or regex to match against the text in the modal. If not provided any modal is matched. # @option options [Numeric] :wait Maximum time to wait for the modal to appear after executing the block. Defaults to {Capybara.configure default_max_wait_time}. # @yield Block whose actions will trigger the system modal # @overload $0(**options, &blk) # @option options [Numeric] :wait Maximum time to wait for the modal to appear after executing the block. Defaults to {Capybara.configure default_max_wait_time}. # @yield Block whose actions will trigger the system modal # @return [String] the message shown in the modal # @raise [Capybara::ModalNotFound] if modal dialog hasn't been found # def accept_alert(text = nil, **options, &blk) accept_modal(:alert, text, options, &blk) end ## # # Execute the block, accepting a confirm. # # @macro modal_params # def accept_confirm(text = nil, **options, &blk) accept_modal(:confirm, text, options, &blk) end ## # # Execute the block, dismissing a confirm. # # @macro modal_params # def dismiss_confirm(text = nil, **options, &blk) dismiss_modal(:confirm, text, options, &blk) end ## # # Execute the block, accepting a prompt, optionally responding to the prompt. # # @macro modal_params # @option options [String] :with Response to provide to the prompt # def accept_prompt(text = nil, **options, &blk) accept_modal(:prompt, text, options, &blk) end ## # # Execute the block, dismissing a prompt. # # @macro modal_params # def dismiss_prompt(text = nil, **options, &blk) dismiss_modal(:prompt, text, options, &blk) end ## # # Save a snapshot of the page. If {Capybara.configure asset_host} is set it will inject `base` tag # pointing to {Capybara.configure asset_host}. # # If invoked without arguments it will save file to {Capybara.configure save_path} # and file will be given randomly generated filename. If invoked with a relative path # the path will be relative to {Capybara.configure save_path}. # # @param [String] path the path to where it should be saved # @return [String] the path to which the file was saved # def save_page(path = nil) prepare_path(path, 'html').tap do |p_path| File.write(p_path, Capybara::Helpers.inject_asset_host(body, host: config.asset_host), mode: 'wb') end end ## # # Save a snapshot of the page and open it in a browser for inspection. # # If invoked without arguments it will save file to {Capybara.configure save_path} # and file will be given randomly generated filename. If invoked with a relative path # the path will be relative to {Capybara.configure save_path}. # # @param [String] path the path to where it should be saved # def save_and_open_page(path = nil) save_page(path).tap { |s_path| open_file(s_path) } end ## # # Save a screenshot of page. # # If invoked without arguments it will save file to {Capybara.configure save_path} # and file will be given randomly generated filename. If invoked with a relative path # the path will be relative to {Capybara.configure save_path}. # # @param [String] path the path to where it should be saved # @param [Hash] options a customizable set of options # @return [String] the path to which the file was saved def save_screenshot(path = nil, **options) prepare_path(path, 'png').tap { |p_path| driver.save_screenshot(p_path, **options) } end ## # # Save a screenshot of the page and open it for inspection. # # If invoked without arguments it will save file to {Capybara.configure save_path} # and file will be given randomly generated filename. If invoked with a relative path # the path will be relative to {Capybara.configure save_path}. # # @param [String] path the path to where it should be saved # @param [Hash] options a customizable set of options # def save_and_open_screenshot(path = nil, **options) save_screenshot(path, **options).tap { |s_path| open_file(s_path) } end def document @document ||= Capybara::Node::Document.new(self, driver) end NODE_METHODS.each do |method| class_eval <<~METHOD, __FILE__, __LINE__ + 1 def #{method}(...) @touched = true current_scope.#{method}(...) end METHOD end DOCUMENT_METHODS.each do |method| class_eval <<~METHOD, __FILE__, __LINE__ + 1 def #{method}(...) document.#{method}(...) end METHOD end def inspect %(#<Capybara::Session>) end def current_scope scope = scopes.last [nil, :frame].include?(scope) ? document : scope end ## # # Yield a block using a specific maximum wait time. # def using_wait_time(seconds, &block) if Capybara.threadsafe begin previous_wait_time = config.default_max_wait_time config.default_max_wait_time = seconds yield ensure config.default_max_wait_time = previous_wait_time end else Capybara.using_wait_time(seconds, &block) end end ## # # Accepts a block to set the configuration options if {Capybara.configure threadsafe} is `true`. Note that some options only have an effect # if set at initialization time, so look at the configuration block that can be passed to the initializer too. # def configure raise 'Session configuration is only supported when Capybara.threadsafe == true' unless Capybara.threadsafe yield config end def self.instance_created? @@instance_created end def config @config ||= if Capybara.threadsafe Capybara.session_options.dup else Capybara::ReadOnlySessionConfig.new(Capybara.session_options) end end def server_url @server&.base_url end private @@instance_created = false # rubocop:disable Style/ClassVars def driver_args(args) args.map { |arg| arg.is_a?(Capybara::Node::Element) ? arg.base : arg } end def accept_modal(type, text_or_options, options, &blk) driver.accept_modal(type, **modal_options(text_or_options, **options), &blk) end def dismiss_modal(type, text_or_options, options, &blk) driver.dismiss_modal(type, **modal_options(text_or_options, **options), &blk) end def modal_options(text = nil, **options) options[:text] ||= text unless text.nil? options[:wait] ||= config.default_max_wait_time options end def open_file(path) require 'launchy' Launchy.open(path) rescue LoadError warn "File saved to #{path}.\nPlease install the launchy gem to open the file automatically." end def prepare_path(path, extension) File.expand_path(path || default_fn(extension), config.save_path).tap do |p_path| FileUtils.mkdir_p(File.dirname(p_path)) end end def default_fn(extension) timestamp = Time.new.strftime('%Y%m%d%H%M%S') "capybara-#{timestamp}#{rand(10**10)}.#{extension}" end def scopes @scopes ||= [nil] end def element_script_result(arg) case arg when Array arg.map { |subarg| element_script_result(subarg) } when Hash arg.transform_values! { |value| element_script_result(value) } when Capybara::Driver::Node Capybara::Node::Element.new(self, arg, nil, nil) else arg end end def adjust_server_port(uri) uri.port ||= @server.port if @server && config.always_include_port end def _find_frame(*args, **kw_args) case args[0] when Capybara::Node::Element args[0] when String, nil find(:frame, *args, **kw_args) when Symbol find(*args, **kw_args) when Integer idx = args[0] all(:frame, minimum: idx + 1)[idx] else raise TypeError end end def _switch_to_window(window = nil, **options, &window_locator) raise Capybara::ScopeError, 'Window cannot be switched inside a `within_frame` block' if scopes.include?(:frame) raise Capybara::ScopeError, 'Window cannot be switched inside a `within` block' unless scopes.last.nil? if window driver.switch_to_window(window.handle) window else synchronize_windows(options) do original_window_handle = driver.current_window_handle begin _switch_to_window_by_locator(&window_locator) rescue StandardError driver.switch_to_window(original_window_handle) raise end end end end def _switch_to_window_by_locator driver.window_handles.each do |handle| driver.switch_to_window handle return Window.new(self, handle) if yield end raise Capybara::WindowError, 'Could not find a window matching block/lambda' end def synchronize_windows(options, &block) wait_time = Capybara::Queries::BaseQuery.wait(options, config.default_max_wait_time) document.synchronize(wait_time, errors: [Capybara::WindowError], &block) end end end
Ruby
{ "end_line": 171, "name": "raise_server_error!", "signature": "def raise_server_error!", "start_line": 158 }
{ "class_name": "Session", "class_signature": "class Session", "module": "Capybara" }
visit
capybara/lib/capybara/session.rb
def visit(visit_uri) raise_server_error! @touched = true visit_uri = ::Addressable::URI.parse(visit_uri.to_s) base_uri = ::Addressable::URI.parse(config.app_host || server_url) if base_uri && [nil, 'http', 'https'].include?(visit_uri.scheme) if visit_uri.relative? visit_uri_parts = visit_uri.to_hash.compact # Useful to people deploying to a subdirectory # and/or single page apps where only the url fragment changes visit_uri_parts[:path] = base_uri.path + visit_uri.path visit_uri = base_uri.merge(visit_uri_parts) end adjust_server_port(visit_uri) end driver.visit(visit_uri.to_s) end
# frozen_string_literal: true require 'capybara/session/matchers' require 'addressable/uri' module Capybara ## # # The {Session} class represents a single user's interaction with the system. The {Session} can use # any of the underlying drivers. A session can be initialized manually like this: # # session = Capybara::Session.new(:culerity, MyRackApp) # # The application given as the second argument is optional. When running Capybara against an external # page, you might want to leave it out: # # session = Capybara::Session.new(:culerity) # session.visit('http://www.google.com') # # When {Capybara.configure threadsafe} is `true` the sessions options will be initially set to the # current values of the global options and a configuration block can be passed to the session initializer. # For available options see {Capybara::SessionConfig::OPTIONS}: # # session = Capybara::Session.new(:driver, MyRackApp) do |config| # config.app_host = "http://my_host.dev" # end # # The {Session} provides a number of methods for controlling the navigation of the page, such as {#visit}, # {#current_path}, and so on. It also delegates a number of methods to a {Capybara::Document}, representing # the current HTML document. This allows interaction: # # session.fill_in('q', with: 'Capybara') # session.click_button('Search') # expect(session).to have_content('Capybara') # # When using `capybara/dsl`, the {Session} is initialized automatically for you. # class Session include Capybara::SessionMatchers NODE_METHODS = %i[ all first attach_file text check choose scroll_to scroll_by click double_click right_click click_link_or_button click_button click_link fill_in find find_all find_button find_by_id find_field find_link has_content? has_text? has_css? has_no_content? has_no_text? has_no_css? has_no_xpath? has_xpath? select uncheck has_element? has_no_element? has_link? has_no_link? has_button? has_no_button? has_field? has_no_field? has_checked_field? has_unchecked_field? has_no_table? has_table? unselect has_select? has_no_select? has_selector? has_no_selector? click_on has_no_checked_field? has_no_unchecked_field? query assert_selector assert_no_selector assert_all_of_selectors assert_none_of_selectors assert_any_of_selectors refute_selector assert_text assert_no_text ].freeze # @api private DOCUMENT_METHODS = %i[ title assert_title assert_no_title has_title? has_no_title? ].freeze SESSION_METHODS = %i[ body html source current_url current_host current_path execute_script evaluate_script evaluate_async_script visit refresh go_back go_forward send_keys within within_element within_fieldset within_table within_frame switch_to_frame current_window windows open_new_window switch_to_window within_window window_opened_by save_page save_and_open_page save_screenshot save_and_open_screenshot reset_session! response_headers status_code current_scope assert_current_path assert_no_current_path has_current_path? has_no_current_path? ].freeze + DOCUMENT_METHODS MODAL_METHODS = %i[ accept_alert accept_confirm dismiss_confirm accept_prompt dismiss_prompt ].freeze DSL_METHODS = NODE_METHODS + SESSION_METHODS + MODAL_METHODS attr_reader :mode, :app, :server attr_accessor :synchronized def initialize(mode, app = nil) if app && !app.respond_to?(:call) raise TypeError, 'The second parameter to Session::new should be a rack app if passed.' end @@instance_created = true # rubocop:disable Style/ClassVars @mode = mode @app = app if block_given? raise 'A configuration block is only accepted when Capybara.threadsafe == true' unless Capybara.threadsafe yield config end @server = if config.run_server && @app && driver.needs_server? server_options = { port: config.server_port, host: config.server_host, reportable_errors: config.server_errors } server_options[:extra_middleware] = [Capybara::Server::AnimationDisabler] if config.disable_animation Capybara::Server.new(@app, **server_options).boot end @touched = false end def driver @driver ||= begin unless Capybara.drivers[mode] other_drivers = Capybara.drivers.names.map(&:inspect) raise Capybara::DriverNotFoundError, "no driver called #{mode.inspect} was found, available drivers: #{other_drivers.join(', ')}" end driver = Capybara.drivers[mode].call(app) driver.session = self if driver.respond_to?(:session=) driver end end ## # # Reset the session (i.e. remove cookies and navigate to blank page). # # This method does not: # # * accept modal dialogs if they are present (Selenium driver now does, others may not) # * clear browser cache/HTML 5 local storage/IndexedDB/Web SQL database/etc. # * modify state of the driver/underlying browser in any other way # # as doing so will result in performance downsides and it's not needed to do everything from the list above for most apps. # # If you want to do anything from the list above on a general basis you can: # # * write RSpec/Cucumber/etc. after hook # * monkeypatch this method # * use Ruby's `prepend` method # def reset! if @touched driver.reset! @touched = false switch_to_frame(:top) rescue nil # rubocop:disable Style/RescueModifier @scopes = [nil] end @server&.wait_for_pending_requests raise_server_error! end alias_method :cleanup!, :reset! alias_method :reset_session!, :reset! ## # # Disconnect from the current driver. A new driver will be instantiated on the next interaction. # def quit @driver.quit if @driver.respond_to? :quit @document = @driver = nil @touched = false @server&.reset_error! end ## # # Raise errors encountered in the server. # def raise_server_error! return unless @server&.error # Force an explanation for the error being raised as the exception cause begin if config.raise_server_errors raise CapybaraError, 'Your application server raised an error - It has been raised in your test code because Capybara.raise_server_errors == true' end rescue CapybaraError => capy_error # rubocop:disable Naming/RescuedExceptionsVariableName raise @server.error, cause: capy_error ensure @server.reset_error! end end ## # # Returns a hash of response headers. Not supported by all drivers (e.g. Selenium). # # @return [Hash<String, String>] A hash of response headers. # def response_headers driver.response_headers end ## # # Returns the current HTTP status code as an integer. Not supported by all drivers (e.g. Selenium). # # @return [Integer] Current HTTP status code # def status_code driver.status_code end ## # # @return [String] A snapshot of the DOM of the current document, as it looks right now (potentially modified by JavaScript). # def html driver.html || '' end alias_method :body, :html alias_method :source, :html ## # # @return [String] Path of the current page, without any domain information # def current_path # Addressable parsing is more lenient than URI uri = ::Addressable::URI.parse(current_url) # Addressable doesn't support opaque URIs - we want nil here return nil if uri&.scheme == 'about' path = uri&.path path unless path&.empty? end ## # # @return [String] Host of the current page # def current_host uri = URI.parse(current_url) "#{uri.scheme}://#{uri.host}" if uri.host end ## # # @return [String] Fully qualified URL of the current page # def current_url driver.current_url end ## # # Navigate to the given URL. The URL can either be a relative URL or an absolute URL # The behaviour of either depends on the driver. # # session.visit('/foo') # session.visit('http://google.com') # # For drivers which can run against an external application, such as the selenium driver # giving an absolute URL will navigate to that page. This allows testing applications # running on remote servers. For these drivers, setting {Capybara.configure app_host} will make the # remote server the default. For example: # # Capybara.app_host = 'http://google.com' # session.visit('/') # visits the google homepage # # If {Capybara.configure always_include_port} is set to `true` and this session is running against # a rack application, then the port that the rack application is running on will automatically # be inserted into the URL. Supposing the app is running on port `4567`, doing something like: # # visit("http://google.com/test") # # Will actually navigate to `http://google.com:4567/test`. # # @param [#to_s] visit_uri The URL to navigate to. The parameter will be cast to a String. # def visit(visit_uri) raise_server_error! @touched = true visit_uri = ::Addressable::URI.parse(visit_uri.to_s) base_uri = ::Addressable::URI.parse(config.app_host || server_url) if base_uri && [nil, 'http', 'https'].include?(visit_uri.scheme) if visit_uri.relative? visit_uri_parts = visit_uri.to_hash.compact # Useful to people deploying to a subdirectory # and/or single page apps where only the url fragment changes visit_uri_parts[:path] = base_uri.path + visit_uri.path visit_uri = base_uri.merge(visit_uri_parts) end adjust_server_port(visit_uri) end driver.visit(visit_uri.to_s) end ## # # Refresh the page. # def refresh raise_server_error! driver.refresh end ## # # Move back a single entry in the browser's history. # def go_back driver.go_back end ## # # Move forward a single entry in the browser's history. # def go_forward driver.go_forward end ## # @!method send_keys # @see Capybara::Node::Element#send_keys # def send_keys(...) driver.send_keys(...) end ## # # Returns the element with focus. # # Not supported by Rack Test # def active_element Capybara::Queries::ActiveElementQuery.new.resolve_for(self)[0].tap(&:allow_reload!) end ## # # Executes the given block within the context of a node. {#within} takes the # same options as {Capybara::Node::Finders#find #find}, as well as a block. For the duration of the # block, any command to Capybara will be handled as though it were scoped # to the given element. # # within(:xpath, './/div[@id="delivery-address"]') do # fill_in('Street', with: '12 Main Street') # end # # Just as with `#find`, if multiple elements match the selector given to # {#within}, an error will be raised, and just as with `#find`, this # behaviour can be controlled through the `:match` and `:exact` options. # # It is possible to omit the first parameter, in that case, the selector is # assumed to be of the type set in {Capybara.configure default_selector}. # # within('div#delivery-address') do # fill_in('Street', with: '12 Main Street') # end # # Note that a lot of uses of {#within} can be replaced more succinctly with # chaining: # # find('div#delivery-address').fill_in('Street', with: '12 Main Street') # # @overload within(*find_args) # @param (see Capybara::Node::Finders#all) # # @overload within(a_node) # @param [Capybara::Node::Base] a_node The node in whose scope the block should be evaluated # # @raise [Capybara::ElementNotFound] If the scope can't be found before time expires # def within(*args, **kw_args) new_scope = args.first.respond_to?(:to_capybara_node) ? args.first.to_capybara_node : find(*args, **kw_args) begin scopes.push(new_scope) yield new_scope if block_given? ensure scopes.pop end end alias_method :within_element, :within ## # # Execute the given block within the a specific fieldset given the id or legend of that fieldset. # # @param [String] locator Id or legend of the fieldset # def within_fieldset(locator, &block) within(:fieldset, locator, &block) end ## # # Execute the given block within the a specific table given the id or caption of that table. # # @param [String] locator Id or caption of the table # def within_table(locator, &block) within(:table, locator, &block) end ## # # Switch to the given frame. # # If you use this method you are responsible for making sure you switch back to the parent frame when done in the frame changed to. # {#within_frame} is preferred over this method and should be used when possible. # May not be supported by all drivers. # # @overload switch_to_frame(element) # @param [Capybara::Node::Element] element iframe/frame element to switch to # @overload switch_to_frame(location) # @param [Symbol] location relative location of the frame to switch to # * :parent - the parent frame # * :top - the top level document # def switch_to_frame(frame) case frame when Capybara::Node::Element driver.switch_to_frame(frame) scopes.push(:frame) when :parent if scopes.last != :frame raise Capybara::ScopeError, "`switch_to_frame(:parent)` cannot be called from inside a descendant frame's " \ '`within` block.' end scopes.pop driver.switch_to_frame(:parent) when :top idx = scopes.index(:frame) top_level_scopes = [:frame, nil] if idx if scopes.slice(idx..).any? { |scope| !top_level_scopes.include?(scope) } raise Capybara::ScopeError, "`switch_to_frame(:top)` cannot be called from inside a descendant frame's " \ '`within` block.' end scopes.slice!(idx..) driver.switch_to_frame(:top) end else raise ArgumentError, 'You must provide a frame element, :parent, or :top when calling switch_to_frame' end end ## # # Execute the given block within the given iframe using given frame, frame name/id or index. # May not be supported by all drivers. # # @overload within_frame(element) # @param [Capybara::Node::Element] frame element # @overload within_frame([kind = :frame], locator, **options) # @param [Symbol] kind Optional selector type (:frame, :css, :xpath, etc.) - Defaults to :frame # @param [String] locator The locator for the given selector kind. For :frame this is the name/id of a frame/iframe element # @overload within_frame(index) # @param [Integer] index index of a frame (0 based) def within_frame(*args, **kw_args) switch_to_frame(_find_frame(*args, **kw_args)) begin yield if block_given? ensure switch_to_frame(:parent) end end ## # @return [Capybara::Window] current window # def current_window Window.new(self, driver.current_window_handle) end ## # Get all opened windows. # The order of windows in returned array is not defined. # The driver may sort windows by their creation time but it's not required. # # @return [Array<Capybara::Window>] an array of all windows # def windows driver.window_handles.map do |handle| Window.new(self, handle) end end ## # Open a new window. # The current window doesn't change as the result of this call. # It should be switched to explicitly. # # @return [Capybara::Window] window that has been opened # def open_new_window(kind = :tab) window_opened_by do if driver.method(:open_new_window).arity.zero? driver.open_new_window else driver.open_new_window(kind) end end end ## # Switch to the given window. # # @overload switch_to_window(&block) # Switches to the first window for which given block returns a value other than false or nil. # If window that matches block can't be found, the window will be switched back and {Capybara::WindowError} will be raised. # @example # window = switch_to_window { title == 'Page title' } # @raise [Capybara::WindowError] if no window matches given block # @overload switch_to_window(window) # @param window [Capybara::Window] window that should be switched to # @raise [Capybara::Driver::Base#no_such_window_error] if nonexistent (e.g. closed) window was passed # # @return [Capybara::Window] window that has been switched to # @raise [Capybara::ScopeError] if this method is invoked inside {#within} or # {#within_frame} methods # @raise [ArgumentError] if both or neither arguments were provided # def switch_to_window(window = nil, **options, &window_locator) raise ArgumentError, '`switch_to_window` can take either a block or a window, not both' if window && window_locator raise ArgumentError, '`switch_to_window`: either window or block should be provided' if !window && !window_locator unless scopes.last.nil? raise Capybara::ScopeError, '`switch_to_window` is not supposed to be invoked from ' \ '`within` or `within_frame` blocks.' end _switch_to_window(window, **options, &window_locator) end ## # This method does the following: # # 1. Switches to the given window (it can be located by window instance/lambda/string). # 2. Executes the given block (within window located at previous step). # 3. Switches back (this step will be invoked even if an exception occurs at the second step). # # @overload within_window(window) { do_something } # @param window [Capybara::Window] instance of {Capybara::Window} class # that will be switched to # @raise [driver#no_such_window_error] if nonexistent (e.g. closed) window was passed # @overload within_window(proc_or_lambda) { do_something } # @param lambda [Proc] First window for which lambda # returns a value other than false or nil will be switched to. # @example # within_window(->{ page.title == 'Page title' }) { click_button 'Submit' } # @raise [Capybara::WindowError] if no window matching lambda was found # # @raise [Capybara::ScopeError] if this method is invoked inside {#within_frame} method # @return value returned by the block # def within_window(window_or_proc) original = current_window scopes << nil begin case window_or_proc when Capybara::Window _switch_to_window(window_or_proc) unless original == window_or_proc when Proc _switch_to_window { window_or_proc.call } else raise ArgumentError, '`#within_window` requires a `Capybara::Window` instance or a lambda' end begin yield if block_given? ensure _switch_to_window(original) unless original == window_or_proc end ensure scopes.pop end end ## # Get the window that has been opened by the passed block. # It will wait for it to be opened (in the same way as other Capybara methods wait). # It's better to use this method than `windows.last` # {https://dvcs.w3.org/hg/webdriver/raw-file/default/webdriver-spec.html#h_note_10 as order of windows isn't defined in some drivers}. # # @overload window_opened_by(**options, &block) # @param options [Hash] # @option options [Numeric] :wait maximum wait time. Defaults to {Capybara.configure default_max_wait_time} # @return [Capybara::Window] the window that has been opened within a block # @raise [Capybara::WindowError] if block passed to window hasn't opened window # or opened more than one window # def window_opened_by(**options) old_handles = driver.window_handles yield synchronize_windows(options) do opened_handles = (driver.window_handles - old_handles) if opened_handles.size != 1 raise Capybara::WindowError, 'block passed to #window_opened_by ' \ "opened #{opened_handles.size} windows instead of 1" end Window.new(self, opened_handles.first) end end ## # # Execute the given script, not returning a result. This is useful for scripts that return # complex objects, such as jQuery statements. {#execute_script} should be used over # {#evaluate_script} whenever possible. # # @param [String] script A string of JavaScript to execute # @param args Optional arguments that will be passed to the script. Driver support for this is optional and types of objects supported may differ between drivers # def execute_script(script, *args) @touched = true driver.execute_script(script, *driver_args(args)) end ## # # Evaluate the given JavaScript and return the result. Be careful when using this with # scripts that return complex objects, such as jQuery statements. {#execute_script} might # be a better alternative. # # @param [String] script A string of JavaScript to evaluate # @param args Optional arguments that will be passed to the script # @return [Object] The result of the evaluated JavaScript (may be driver specific) # def evaluate_script(script, *args) @touched = true result = driver.evaluate_script(script.strip, *driver_args(args)) element_script_result(result) end ## # # Evaluate the given JavaScript and obtain the result from a callback function which will be passed as the last argument to the script. # # @param [String] script A string of JavaScript to evaluate # @param args Optional arguments that will be passed to the script # @return [Object] The result of the evaluated JavaScript (may be driver specific) # def evaluate_async_script(script, *args) @touched = true result = driver.evaluate_async_script(script, *driver_args(args)) element_script_result(result) end ## # # Execute the block, accepting a alert. # # @!macro modal_params # Expects a block whose actions will trigger the display modal to appear. # @example # $0 do # click_link('link that triggers appearance of system modal') # end # @overload $0(text, **options, &blk) # @param text [String, Regexp] Text or regex to match against the text in the modal. If not provided any modal is matched. # @option options [Numeric] :wait Maximum time to wait for the modal to appear after executing the block. Defaults to {Capybara.configure default_max_wait_time}. # @yield Block whose actions will trigger the system modal # @overload $0(**options, &blk) # @option options [Numeric] :wait Maximum time to wait for the modal to appear after executing the block. Defaults to {Capybara.configure default_max_wait_time}. # @yield Block whose actions will trigger the system modal # @return [String] the message shown in the modal # @raise [Capybara::ModalNotFound] if modal dialog hasn't been found # def accept_alert(text = nil, **options, &blk) accept_modal(:alert, text, options, &blk) end ## # # Execute the block, accepting a confirm. # # @macro modal_params # def accept_confirm(text = nil, **options, &blk) accept_modal(:confirm, text, options, &blk) end ## # # Execute the block, dismissing a confirm. # # @macro modal_params # def dismiss_confirm(text = nil, **options, &blk) dismiss_modal(:confirm, text, options, &blk) end ## # # Execute the block, accepting a prompt, optionally responding to the prompt. # # @macro modal_params # @option options [String] :with Response to provide to the prompt # def accept_prompt(text = nil, **options, &blk) accept_modal(:prompt, text, options, &blk) end ## # # Execute the block, dismissing a prompt. # # @macro modal_params # def dismiss_prompt(text = nil, **options, &blk) dismiss_modal(:prompt, text, options, &blk) end ## # # Save a snapshot of the page. If {Capybara.configure asset_host} is set it will inject `base` tag # pointing to {Capybara.configure asset_host}. # # If invoked without arguments it will save file to {Capybara.configure save_path} # and file will be given randomly generated filename. If invoked with a relative path # the path will be relative to {Capybara.configure save_path}. # # @param [String] path the path to where it should be saved # @return [String] the path to which the file was saved # def save_page(path = nil) prepare_path(path, 'html').tap do |p_path| File.write(p_path, Capybara::Helpers.inject_asset_host(body, host: config.asset_host), mode: 'wb') end end ## # # Save a snapshot of the page and open it in a browser for inspection. # # If invoked without arguments it will save file to {Capybara.configure save_path} # and file will be given randomly generated filename. If invoked with a relative path # the path will be relative to {Capybara.configure save_path}. # # @param [String] path the path to where it should be saved # def save_and_open_page(path = nil) save_page(path).tap { |s_path| open_file(s_path) } end ## # # Save a screenshot of page. # # If invoked without arguments it will save file to {Capybara.configure save_path} # and file will be given randomly generated filename. If invoked with a relative path # the path will be relative to {Capybara.configure save_path}. # # @param [String] path the path to where it should be saved # @param [Hash] options a customizable set of options # @return [String] the path to which the file was saved def save_screenshot(path = nil, **options) prepare_path(path, 'png').tap { |p_path| driver.save_screenshot(p_path, **options) } end ## # # Save a screenshot of the page and open it for inspection. # # If invoked without arguments it will save file to {Capybara.configure save_path} # and file will be given randomly generated filename. If invoked with a relative path # the path will be relative to {Capybara.configure save_path}. # # @param [String] path the path to where it should be saved # @param [Hash] options a customizable set of options # def save_and_open_screenshot(path = nil, **options) save_screenshot(path, **options).tap { |s_path| open_file(s_path) } end def document @document ||= Capybara::Node::Document.new(self, driver) end NODE_METHODS.each do |method| class_eval <<~METHOD, __FILE__, __LINE__ + 1 def #{method}(...) @touched = true current_scope.#{method}(...) end METHOD end DOCUMENT_METHODS.each do |method| class_eval <<~METHOD, __FILE__, __LINE__ + 1 def #{method}(...) document.#{method}(...) end METHOD end def inspect %(#<Capybara::Session>) end def current_scope scope = scopes.last [nil, :frame].include?(scope) ? document : scope end ## # # Yield a block using a specific maximum wait time. # def using_wait_time(seconds, &block) if Capybara.threadsafe begin previous_wait_time = config.default_max_wait_time config.default_max_wait_time = seconds yield ensure config.default_max_wait_time = previous_wait_time end else Capybara.using_wait_time(seconds, &block) end end ## # # Accepts a block to set the configuration options if {Capybara.configure threadsafe} is `true`. Note that some options only have an effect # if set at initialization time, so look at the configuration block that can be passed to the initializer too. # def configure raise 'Session configuration is only supported when Capybara.threadsafe == true' unless Capybara.threadsafe yield config end def self.instance_created? @@instance_created end def config @config ||= if Capybara.threadsafe Capybara.session_options.dup else Capybara::ReadOnlySessionConfig.new(Capybara.session_options) end end def server_url @server&.base_url end private @@instance_created = false # rubocop:disable Style/ClassVars def driver_args(args) args.map { |arg| arg.is_a?(Capybara::Node::Element) ? arg.base : arg } end def accept_modal(type, text_or_options, options, &blk) driver.accept_modal(type, **modal_options(text_or_options, **options), &blk) end def dismiss_modal(type, text_or_options, options, &blk) driver.dismiss_modal(type, **modal_options(text_or_options, **options), &blk) end def modal_options(text = nil, **options) options[:text] ||= text unless text.nil? options[:wait] ||= config.default_max_wait_time options end def open_file(path) require 'launchy' Launchy.open(path) rescue LoadError warn "File saved to #{path}.\nPlease install the launchy gem to open the file automatically." end def prepare_path(path, extension) File.expand_path(path || default_fn(extension), config.save_path).tap do |p_path| FileUtils.mkdir_p(File.dirname(p_path)) end end def default_fn(extension) timestamp = Time.new.strftime('%Y%m%d%H%M%S') "capybara-#{timestamp}#{rand(10**10)}.#{extension}" end def scopes @scopes ||= [nil] end def element_script_result(arg) case arg when Array arg.map { |subarg| element_script_result(subarg) } when Hash arg.transform_values! { |value| element_script_result(value) } when Capybara::Driver::Node Capybara::Node::Element.new(self, arg, nil, nil) else arg end end def adjust_server_port(uri) uri.port ||= @server.port if @server && config.always_include_port end def _find_frame(*args, **kw_args) case args[0] when Capybara::Node::Element args[0] when String, nil find(:frame, *args, **kw_args) when Symbol find(*args, **kw_args) when Integer idx = args[0] all(:frame, minimum: idx + 1)[idx] else raise TypeError end end def _switch_to_window(window = nil, **options, &window_locator) raise Capybara::ScopeError, 'Window cannot be switched inside a `within_frame` block' if scopes.include?(:frame) raise Capybara::ScopeError, 'Window cannot be switched inside a `within` block' unless scopes.last.nil? if window driver.switch_to_window(window.handle) window else synchronize_windows(options) do original_window_handle = driver.current_window_handle begin _switch_to_window_by_locator(&window_locator) rescue StandardError driver.switch_to_window(original_window_handle) raise end end end end def _switch_to_window_by_locator driver.window_handles.each do |handle| driver.switch_to_window handle return Window.new(self, handle) if yield end raise Capybara::WindowError, 'Could not find a window matching block/lambda' end def synchronize_windows(options, &block) wait_time = Capybara::Queries::BaseQuery.wait(options, config.default_max_wait_time) document.synchronize(wait_time, errors: [Capybara::WindowError], &block) end end end
Ruby
{ "end_line": 282, "name": "visit", "signature": "def visit(visit_uri)", "start_line": 261 }
{ "class_name": "Session", "class_signature": "class Session", "module": "Capybara" }
switch_to_frame
capybara/lib/capybara/session.rb
def switch_to_frame(frame) case frame when Capybara::Node::Element driver.switch_to_frame(frame) scopes.push(:frame) when :parent if scopes.last != :frame raise Capybara::ScopeError, "`switch_to_frame(:parent)` cannot be called from inside a descendant frame's " \ '`within` block.' end scopes.pop driver.switch_to_frame(:parent) when :top idx = scopes.index(:frame) top_level_scopes = [:frame, nil] if idx if scopes.slice(idx..).any? { |scope| !top_level_scopes.include?(scope) } raise Capybara::ScopeError, "`switch_to_frame(:top)` cannot be called from inside a descendant frame's " \ '`within` block.' end scopes.slice!(idx..) driver.switch_to_frame(:top) end else raise ArgumentError, 'You must provide a frame element, :parent, or :top when calling switch_to_frame' end end
# frozen_string_literal: true require 'capybara/session/matchers' require 'addressable/uri' module Capybara ## # # The {Session} class represents a single user's interaction with the system. The {Session} can use # any of the underlying drivers. A session can be initialized manually like this: # # session = Capybara::Session.new(:culerity, MyRackApp) # # The application given as the second argument is optional. When running Capybara against an external # page, you might want to leave it out: # # session = Capybara::Session.new(:culerity) # session.visit('http://www.google.com') # # When {Capybara.configure threadsafe} is `true` the sessions options will be initially set to the # current values of the global options and a configuration block can be passed to the session initializer. # For available options see {Capybara::SessionConfig::OPTIONS}: # # session = Capybara::Session.new(:driver, MyRackApp) do |config| # config.app_host = "http://my_host.dev" # end # # The {Session} provides a number of methods for controlling the navigation of the page, such as {#visit}, # {#current_path}, and so on. It also delegates a number of methods to a {Capybara::Document}, representing # the current HTML document. This allows interaction: # # session.fill_in('q', with: 'Capybara') # session.click_button('Search') # expect(session).to have_content('Capybara') # # When using `capybara/dsl`, the {Session} is initialized automatically for you. # class Session include Capybara::SessionMatchers NODE_METHODS = %i[ all first attach_file text check choose scroll_to scroll_by click double_click right_click click_link_or_button click_button click_link fill_in find find_all find_button find_by_id find_field find_link has_content? has_text? has_css? has_no_content? has_no_text? has_no_css? has_no_xpath? has_xpath? select uncheck has_element? has_no_element? has_link? has_no_link? has_button? has_no_button? has_field? has_no_field? has_checked_field? has_unchecked_field? has_no_table? has_table? unselect has_select? has_no_select? has_selector? has_no_selector? click_on has_no_checked_field? has_no_unchecked_field? query assert_selector assert_no_selector assert_all_of_selectors assert_none_of_selectors assert_any_of_selectors refute_selector assert_text assert_no_text ].freeze # @api private DOCUMENT_METHODS = %i[ title assert_title assert_no_title has_title? has_no_title? ].freeze SESSION_METHODS = %i[ body html source current_url current_host current_path execute_script evaluate_script evaluate_async_script visit refresh go_back go_forward send_keys within within_element within_fieldset within_table within_frame switch_to_frame current_window windows open_new_window switch_to_window within_window window_opened_by save_page save_and_open_page save_screenshot save_and_open_screenshot reset_session! response_headers status_code current_scope assert_current_path assert_no_current_path has_current_path? has_no_current_path? ].freeze + DOCUMENT_METHODS MODAL_METHODS = %i[ accept_alert accept_confirm dismiss_confirm accept_prompt dismiss_prompt ].freeze DSL_METHODS = NODE_METHODS + SESSION_METHODS + MODAL_METHODS attr_reader :mode, :app, :server attr_accessor :synchronized def initialize(mode, app = nil) if app && !app.respond_to?(:call) raise TypeError, 'The second parameter to Session::new should be a rack app if passed.' end @@instance_created = true # rubocop:disable Style/ClassVars @mode = mode @app = app if block_given? raise 'A configuration block is only accepted when Capybara.threadsafe == true' unless Capybara.threadsafe yield config end @server = if config.run_server && @app && driver.needs_server? server_options = { port: config.server_port, host: config.server_host, reportable_errors: config.server_errors } server_options[:extra_middleware] = [Capybara::Server::AnimationDisabler] if config.disable_animation Capybara::Server.new(@app, **server_options).boot end @touched = false end def driver @driver ||= begin unless Capybara.drivers[mode] other_drivers = Capybara.drivers.names.map(&:inspect) raise Capybara::DriverNotFoundError, "no driver called #{mode.inspect} was found, available drivers: #{other_drivers.join(', ')}" end driver = Capybara.drivers[mode].call(app) driver.session = self if driver.respond_to?(:session=) driver end end ## # # Reset the session (i.e. remove cookies and navigate to blank page). # # This method does not: # # * accept modal dialogs if they are present (Selenium driver now does, others may not) # * clear browser cache/HTML 5 local storage/IndexedDB/Web SQL database/etc. # * modify state of the driver/underlying browser in any other way # # as doing so will result in performance downsides and it's not needed to do everything from the list above for most apps. # # If you want to do anything from the list above on a general basis you can: # # * write RSpec/Cucumber/etc. after hook # * monkeypatch this method # * use Ruby's `prepend` method # def reset! if @touched driver.reset! @touched = false switch_to_frame(:top) rescue nil # rubocop:disable Style/RescueModifier @scopes = [nil] end @server&.wait_for_pending_requests raise_server_error! end alias_method :cleanup!, :reset! alias_method :reset_session!, :reset! ## # # Disconnect from the current driver. A new driver will be instantiated on the next interaction. # def quit @driver.quit if @driver.respond_to? :quit @document = @driver = nil @touched = false @server&.reset_error! end ## # # Raise errors encountered in the server. # def raise_server_error! return unless @server&.error # Force an explanation for the error being raised as the exception cause begin if config.raise_server_errors raise CapybaraError, 'Your application server raised an error - It has been raised in your test code because Capybara.raise_server_errors == true' end rescue CapybaraError => capy_error # rubocop:disable Naming/RescuedExceptionsVariableName raise @server.error, cause: capy_error ensure @server.reset_error! end end ## # # Returns a hash of response headers. Not supported by all drivers (e.g. Selenium). # # @return [Hash<String, String>] A hash of response headers. # def response_headers driver.response_headers end ## # # Returns the current HTTP status code as an integer. Not supported by all drivers (e.g. Selenium). # # @return [Integer] Current HTTP status code # def status_code driver.status_code end ## # # @return [String] A snapshot of the DOM of the current document, as it looks right now (potentially modified by JavaScript). # def html driver.html || '' end alias_method :body, :html alias_method :source, :html ## # # @return [String] Path of the current page, without any domain information # def current_path # Addressable parsing is more lenient than URI uri = ::Addressable::URI.parse(current_url) # Addressable doesn't support opaque URIs - we want nil here return nil if uri&.scheme == 'about' path = uri&.path path unless path&.empty? end ## # # @return [String] Host of the current page # def current_host uri = URI.parse(current_url) "#{uri.scheme}://#{uri.host}" if uri.host end ## # # @return [String] Fully qualified URL of the current page # def current_url driver.current_url end ## # # Navigate to the given URL. The URL can either be a relative URL or an absolute URL # The behaviour of either depends on the driver. # # session.visit('/foo') # session.visit('http://google.com') # # For drivers which can run against an external application, such as the selenium driver # giving an absolute URL will navigate to that page. This allows testing applications # running on remote servers. For these drivers, setting {Capybara.configure app_host} will make the # remote server the default. For example: # # Capybara.app_host = 'http://google.com' # session.visit('/') # visits the google homepage # # If {Capybara.configure always_include_port} is set to `true` and this session is running against # a rack application, then the port that the rack application is running on will automatically # be inserted into the URL. Supposing the app is running on port `4567`, doing something like: # # visit("http://google.com/test") # # Will actually navigate to `http://google.com:4567/test`. # # @param [#to_s] visit_uri The URL to navigate to. The parameter will be cast to a String. # def visit(visit_uri) raise_server_error! @touched = true visit_uri = ::Addressable::URI.parse(visit_uri.to_s) base_uri = ::Addressable::URI.parse(config.app_host || server_url) if base_uri && [nil, 'http', 'https'].include?(visit_uri.scheme) if visit_uri.relative? visit_uri_parts = visit_uri.to_hash.compact # Useful to people deploying to a subdirectory # and/or single page apps where only the url fragment changes visit_uri_parts[:path] = base_uri.path + visit_uri.path visit_uri = base_uri.merge(visit_uri_parts) end adjust_server_port(visit_uri) end driver.visit(visit_uri.to_s) end ## # # Refresh the page. # def refresh raise_server_error! driver.refresh end ## # # Move back a single entry in the browser's history. # def go_back driver.go_back end ## # # Move forward a single entry in the browser's history. # def go_forward driver.go_forward end ## # @!method send_keys # @see Capybara::Node::Element#send_keys # def send_keys(...) driver.send_keys(...) end ## # # Returns the element with focus. # # Not supported by Rack Test # def active_element Capybara::Queries::ActiveElementQuery.new.resolve_for(self)[0].tap(&:allow_reload!) end ## # # Executes the given block within the context of a node. {#within} takes the # same options as {Capybara::Node::Finders#find #find}, as well as a block. For the duration of the # block, any command to Capybara will be handled as though it were scoped # to the given element. # # within(:xpath, './/div[@id="delivery-address"]') do # fill_in('Street', with: '12 Main Street') # end # # Just as with `#find`, if multiple elements match the selector given to # {#within}, an error will be raised, and just as with `#find`, this # behaviour can be controlled through the `:match` and `:exact` options. # # It is possible to omit the first parameter, in that case, the selector is # assumed to be of the type set in {Capybara.configure default_selector}. # # within('div#delivery-address') do # fill_in('Street', with: '12 Main Street') # end # # Note that a lot of uses of {#within} can be replaced more succinctly with # chaining: # # find('div#delivery-address').fill_in('Street', with: '12 Main Street') # # @overload within(*find_args) # @param (see Capybara::Node::Finders#all) # # @overload within(a_node) # @param [Capybara::Node::Base] a_node The node in whose scope the block should be evaluated # # @raise [Capybara::ElementNotFound] If the scope can't be found before time expires # def within(*args, **kw_args) new_scope = args.first.respond_to?(:to_capybara_node) ? args.first.to_capybara_node : find(*args, **kw_args) begin scopes.push(new_scope) yield new_scope if block_given? ensure scopes.pop end end alias_method :within_element, :within ## # # Execute the given block within the a specific fieldset given the id or legend of that fieldset. # # @param [String] locator Id or legend of the fieldset # def within_fieldset(locator, &block) within(:fieldset, locator, &block) end ## # # Execute the given block within the a specific table given the id or caption of that table. # # @param [String] locator Id or caption of the table # def within_table(locator, &block) within(:table, locator, &block) end ## # # Switch to the given frame. # # If you use this method you are responsible for making sure you switch back to the parent frame when done in the frame changed to. # {#within_frame} is preferred over this method and should be used when possible. # May not be supported by all drivers. # # @overload switch_to_frame(element) # @param [Capybara::Node::Element] element iframe/frame element to switch to # @overload switch_to_frame(location) # @param [Symbol] location relative location of the frame to switch to # * :parent - the parent frame # * :top - the top level document # def switch_to_frame(frame) case frame when Capybara::Node::Element driver.switch_to_frame(frame) scopes.push(:frame) when :parent if scopes.last != :frame raise Capybara::ScopeError, "`switch_to_frame(:parent)` cannot be called from inside a descendant frame's " \ '`within` block.' end scopes.pop driver.switch_to_frame(:parent) when :top idx = scopes.index(:frame) top_level_scopes = [:frame, nil] if idx if scopes.slice(idx..).any? { |scope| !top_level_scopes.include?(scope) } raise Capybara::ScopeError, "`switch_to_frame(:top)` cannot be called from inside a descendant frame's " \ '`within` block.' end scopes.slice!(idx..) driver.switch_to_frame(:top) end else raise ArgumentError, 'You must provide a frame element, :parent, or :top when calling switch_to_frame' end end ## # # Execute the given block within the given iframe using given frame, frame name/id or index. # May not be supported by all drivers. # # @overload within_frame(element) # @param [Capybara::Node::Element] frame element # @overload within_frame([kind = :frame], locator, **options) # @param [Symbol] kind Optional selector type (:frame, :css, :xpath, etc.) - Defaults to :frame # @param [String] locator The locator for the given selector kind. For :frame this is the name/id of a frame/iframe element # @overload within_frame(index) # @param [Integer] index index of a frame (0 based) def within_frame(*args, **kw_args) switch_to_frame(_find_frame(*args, **kw_args)) begin yield if block_given? ensure switch_to_frame(:parent) end end ## # @return [Capybara::Window] current window # def current_window Window.new(self, driver.current_window_handle) end ## # Get all opened windows. # The order of windows in returned array is not defined. # The driver may sort windows by their creation time but it's not required. # # @return [Array<Capybara::Window>] an array of all windows # def windows driver.window_handles.map do |handle| Window.new(self, handle) end end ## # Open a new window. # The current window doesn't change as the result of this call. # It should be switched to explicitly. # # @return [Capybara::Window] window that has been opened # def open_new_window(kind = :tab) window_opened_by do if driver.method(:open_new_window).arity.zero? driver.open_new_window else driver.open_new_window(kind) end end end ## # Switch to the given window. # # @overload switch_to_window(&block) # Switches to the first window for which given block returns a value other than false or nil. # If window that matches block can't be found, the window will be switched back and {Capybara::WindowError} will be raised. # @example # window = switch_to_window { title == 'Page title' } # @raise [Capybara::WindowError] if no window matches given block # @overload switch_to_window(window) # @param window [Capybara::Window] window that should be switched to # @raise [Capybara::Driver::Base#no_such_window_error] if nonexistent (e.g. closed) window was passed # # @return [Capybara::Window] window that has been switched to # @raise [Capybara::ScopeError] if this method is invoked inside {#within} or # {#within_frame} methods # @raise [ArgumentError] if both or neither arguments were provided # def switch_to_window(window = nil, **options, &window_locator) raise ArgumentError, '`switch_to_window` can take either a block or a window, not both' if window && window_locator raise ArgumentError, '`switch_to_window`: either window or block should be provided' if !window && !window_locator unless scopes.last.nil? raise Capybara::ScopeError, '`switch_to_window` is not supposed to be invoked from ' \ '`within` or `within_frame` blocks.' end _switch_to_window(window, **options, &window_locator) end ## # This method does the following: # # 1. Switches to the given window (it can be located by window instance/lambda/string). # 2. Executes the given block (within window located at previous step). # 3. Switches back (this step will be invoked even if an exception occurs at the second step). # # @overload within_window(window) { do_something } # @param window [Capybara::Window] instance of {Capybara::Window} class # that will be switched to # @raise [driver#no_such_window_error] if nonexistent (e.g. closed) window was passed # @overload within_window(proc_or_lambda) { do_something } # @param lambda [Proc] First window for which lambda # returns a value other than false or nil will be switched to. # @example # within_window(->{ page.title == 'Page title' }) { click_button 'Submit' } # @raise [Capybara::WindowError] if no window matching lambda was found # # @raise [Capybara::ScopeError] if this method is invoked inside {#within_frame} method # @return value returned by the block # def within_window(window_or_proc) original = current_window scopes << nil begin case window_or_proc when Capybara::Window _switch_to_window(window_or_proc) unless original == window_or_proc when Proc _switch_to_window { window_or_proc.call } else raise ArgumentError, '`#within_window` requires a `Capybara::Window` instance or a lambda' end begin yield if block_given? ensure _switch_to_window(original) unless original == window_or_proc end ensure scopes.pop end end ## # Get the window that has been opened by the passed block. # It will wait for it to be opened (in the same way as other Capybara methods wait). # It's better to use this method than `windows.last` # {https://dvcs.w3.org/hg/webdriver/raw-file/default/webdriver-spec.html#h_note_10 as order of windows isn't defined in some drivers}. # # @overload window_opened_by(**options, &block) # @param options [Hash] # @option options [Numeric] :wait maximum wait time. Defaults to {Capybara.configure default_max_wait_time} # @return [Capybara::Window] the window that has been opened within a block # @raise [Capybara::WindowError] if block passed to window hasn't opened window # or opened more than one window # def window_opened_by(**options) old_handles = driver.window_handles yield synchronize_windows(options) do opened_handles = (driver.window_handles - old_handles) if opened_handles.size != 1 raise Capybara::WindowError, 'block passed to #window_opened_by ' \ "opened #{opened_handles.size} windows instead of 1" end Window.new(self, opened_handles.first) end end ## # # Execute the given script, not returning a result. This is useful for scripts that return # complex objects, such as jQuery statements. {#execute_script} should be used over # {#evaluate_script} whenever possible. # # @param [String] script A string of JavaScript to execute # @param args Optional arguments that will be passed to the script. Driver support for this is optional and types of objects supported may differ between drivers # def execute_script(script, *args) @touched = true driver.execute_script(script, *driver_args(args)) end ## # # Evaluate the given JavaScript and return the result. Be careful when using this with # scripts that return complex objects, such as jQuery statements. {#execute_script} might # be a better alternative. # # @param [String] script A string of JavaScript to evaluate # @param args Optional arguments that will be passed to the script # @return [Object] The result of the evaluated JavaScript (may be driver specific) # def evaluate_script(script, *args) @touched = true result = driver.evaluate_script(script.strip, *driver_args(args)) element_script_result(result) end ## # # Evaluate the given JavaScript and obtain the result from a callback function which will be passed as the last argument to the script. # # @param [String] script A string of JavaScript to evaluate # @param args Optional arguments that will be passed to the script # @return [Object] The result of the evaluated JavaScript (may be driver specific) # def evaluate_async_script(script, *args) @touched = true result = driver.evaluate_async_script(script, *driver_args(args)) element_script_result(result) end ## # # Execute the block, accepting a alert. # # @!macro modal_params # Expects a block whose actions will trigger the display modal to appear. # @example # $0 do # click_link('link that triggers appearance of system modal') # end # @overload $0(text, **options, &blk) # @param text [String, Regexp] Text or regex to match against the text in the modal. If not provided any modal is matched. # @option options [Numeric] :wait Maximum time to wait for the modal to appear after executing the block. Defaults to {Capybara.configure default_max_wait_time}. # @yield Block whose actions will trigger the system modal # @overload $0(**options, &blk) # @option options [Numeric] :wait Maximum time to wait for the modal to appear after executing the block. Defaults to {Capybara.configure default_max_wait_time}. # @yield Block whose actions will trigger the system modal # @return [String] the message shown in the modal # @raise [Capybara::ModalNotFound] if modal dialog hasn't been found # def accept_alert(text = nil, **options, &blk) accept_modal(:alert, text, options, &blk) end ## # # Execute the block, accepting a confirm. # # @macro modal_params # def accept_confirm(text = nil, **options, &blk) accept_modal(:confirm, text, options, &blk) end ## # # Execute the block, dismissing a confirm. # # @macro modal_params # def dismiss_confirm(text = nil, **options, &blk) dismiss_modal(:confirm, text, options, &blk) end ## # # Execute the block, accepting a prompt, optionally responding to the prompt. # # @macro modal_params # @option options [String] :with Response to provide to the prompt # def accept_prompt(text = nil, **options, &blk) accept_modal(:prompt, text, options, &blk) end ## # # Execute the block, dismissing a prompt. # # @macro modal_params # def dismiss_prompt(text = nil, **options, &blk) dismiss_modal(:prompt, text, options, &blk) end ## # # Save a snapshot of the page. If {Capybara.configure asset_host} is set it will inject `base` tag # pointing to {Capybara.configure asset_host}. # # If invoked without arguments it will save file to {Capybara.configure save_path} # and file will be given randomly generated filename. If invoked with a relative path # the path will be relative to {Capybara.configure save_path}. # # @param [String] path the path to where it should be saved # @return [String] the path to which the file was saved # def save_page(path = nil) prepare_path(path, 'html').tap do |p_path| File.write(p_path, Capybara::Helpers.inject_asset_host(body, host: config.asset_host), mode: 'wb') end end ## # # Save a snapshot of the page and open it in a browser for inspection. # # If invoked without arguments it will save file to {Capybara.configure save_path} # and file will be given randomly generated filename. If invoked with a relative path # the path will be relative to {Capybara.configure save_path}. # # @param [String] path the path to where it should be saved # def save_and_open_page(path = nil) save_page(path).tap { |s_path| open_file(s_path) } end ## # # Save a screenshot of page. # # If invoked without arguments it will save file to {Capybara.configure save_path} # and file will be given randomly generated filename. If invoked with a relative path # the path will be relative to {Capybara.configure save_path}. # # @param [String] path the path to where it should be saved # @param [Hash] options a customizable set of options # @return [String] the path to which the file was saved def save_screenshot(path = nil, **options) prepare_path(path, 'png').tap { |p_path| driver.save_screenshot(p_path, **options) } end ## # # Save a screenshot of the page and open it for inspection. # # If invoked without arguments it will save file to {Capybara.configure save_path} # and file will be given randomly generated filename. If invoked with a relative path # the path will be relative to {Capybara.configure save_path}. # # @param [String] path the path to where it should be saved # @param [Hash] options a customizable set of options # def save_and_open_screenshot(path = nil, **options) save_screenshot(path, **options).tap { |s_path| open_file(s_path) } end def document @document ||= Capybara::Node::Document.new(self, driver) end NODE_METHODS.each do |method| class_eval <<~METHOD, __FILE__, __LINE__ + 1 def #{method}(...) @touched = true current_scope.#{method}(...) end METHOD end DOCUMENT_METHODS.each do |method| class_eval <<~METHOD, __FILE__, __LINE__ + 1 def #{method}(...) document.#{method}(...) end METHOD end def inspect %(#<Capybara::Session>) end def current_scope scope = scopes.last [nil, :frame].include?(scope) ? document : scope end ## # # Yield a block using a specific maximum wait time. # def using_wait_time(seconds, &block) if Capybara.threadsafe begin previous_wait_time = config.default_max_wait_time config.default_max_wait_time = seconds yield ensure config.default_max_wait_time = previous_wait_time end else Capybara.using_wait_time(seconds, &block) end end ## # # Accepts a block to set the configuration options if {Capybara.configure threadsafe} is `true`. Note that some options only have an effect # if set at initialization time, so look at the configuration block that can be passed to the initializer too. # def configure raise 'Session configuration is only supported when Capybara.threadsafe == true' unless Capybara.threadsafe yield config end def self.instance_created? @@instance_created end def config @config ||= if Capybara.threadsafe Capybara.session_options.dup else Capybara::ReadOnlySessionConfig.new(Capybara.session_options) end end def server_url @server&.base_url end private @@instance_created = false # rubocop:disable Style/ClassVars def driver_args(args) args.map { |arg| arg.is_a?(Capybara::Node::Element) ? arg.base : arg } end def accept_modal(type, text_or_options, options, &blk) driver.accept_modal(type, **modal_options(text_or_options, **options), &blk) end def dismiss_modal(type, text_or_options, options, &blk) driver.dismiss_modal(type, **modal_options(text_or_options, **options), &blk) end def modal_options(text = nil, **options) options[:text] ||= text unless text.nil? options[:wait] ||= config.default_max_wait_time options end def open_file(path) require 'launchy' Launchy.open(path) rescue LoadError warn "File saved to #{path}.\nPlease install the launchy gem to open the file automatically." end def prepare_path(path, extension) File.expand_path(path || default_fn(extension), config.save_path).tap do |p_path| FileUtils.mkdir_p(File.dirname(p_path)) end end def default_fn(extension) timestamp = Time.new.strftime('%Y%m%d%H%M%S') "capybara-#{timestamp}#{rand(10**10)}.#{extension}" end def scopes @scopes ||= [nil] end def element_script_result(arg) case arg when Array arg.map { |subarg| element_script_result(subarg) } when Hash arg.transform_values! { |value| element_script_result(value) } when Capybara::Driver::Node Capybara::Node::Element.new(self, arg, nil, nil) else arg end end def adjust_server_port(uri) uri.port ||= @server.port if @server && config.always_include_port end def _find_frame(*args, **kw_args) case args[0] when Capybara::Node::Element args[0] when String, nil find(:frame, *args, **kw_args) when Symbol find(*args, **kw_args) when Integer idx = args[0] all(:frame, minimum: idx + 1)[idx] else raise TypeError end end def _switch_to_window(window = nil, **options, &window_locator) raise Capybara::ScopeError, 'Window cannot be switched inside a `within_frame` block' if scopes.include?(:frame) raise Capybara::ScopeError, 'Window cannot be switched inside a `within` block' unless scopes.last.nil? if window driver.switch_to_window(window.handle) window else synchronize_windows(options) do original_window_handle = driver.current_window_handle begin _switch_to_window_by_locator(&window_locator) rescue StandardError driver.switch_to_window(original_window_handle) raise end end end end def _switch_to_window_by_locator driver.window_handles.each do |handle| driver.switch_to_window handle return Window.new(self, handle) if yield end raise Capybara::WindowError, 'Could not find a window matching block/lambda' end def synchronize_windows(options, &block) wait_time = Capybara::Queries::BaseQuery.wait(options, config.default_max_wait_time) document.synchronize(wait_time, errors: [Capybara::WindowError], &block) end end end
Ruby
{ "end_line": 434, "name": "switch_to_frame", "signature": "def switch_to_frame(frame)", "start_line": 408 }
{ "class_name": "Session", "class_signature": "class Session", "module": "Capybara" }
within_window
capybara/lib/capybara/session.rb
def within_window(window_or_proc) original = current_window scopes << nil begin case window_or_proc when Capybara::Window _switch_to_window(window_or_proc) unless original == window_or_proc when Proc _switch_to_window { window_or_proc.call } else raise ArgumentError, '`#within_window` requires a `Capybara::Window` instance or a lambda' end begin yield if block_given? ensure _switch_to_window(original) unless original == window_or_proc end ensure scopes.pop end end
# frozen_string_literal: true require 'capybara/session/matchers' require 'addressable/uri' module Capybara ## # # The {Session} class represents a single user's interaction with the system. The {Session} can use # any of the underlying drivers. A session can be initialized manually like this: # # session = Capybara::Session.new(:culerity, MyRackApp) # # The application given as the second argument is optional. When running Capybara against an external # page, you might want to leave it out: # # session = Capybara::Session.new(:culerity) # session.visit('http://www.google.com') # # When {Capybara.configure threadsafe} is `true` the sessions options will be initially set to the # current values of the global options and a configuration block can be passed to the session initializer. # For available options see {Capybara::SessionConfig::OPTIONS}: # # session = Capybara::Session.new(:driver, MyRackApp) do |config| # config.app_host = "http://my_host.dev" # end # # The {Session} provides a number of methods for controlling the navigation of the page, such as {#visit}, # {#current_path}, and so on. It also delegates a number of methods to a {Capybara::Document}, representing # the current HTML document. This allows interaction: # # session.fill_in('q', with: 'Capybara') # session.click_button('Search') # expect(session).to have_content('Capybara') # # When using `capybara/dsl`, the {Session} is initialized automatically for you. # class Session include Capybara::SessionMatchers NODE_METHODS = %i[ all first attach_file text check choose scroll_to scroll_by click double_click right_click click_link_or_button click_button click_link fill_in find find_all find_button find_by_id find_field find_link has_content? has_text? has_css? has_no_content? has_no_text? has_no_css? has_no_xpath? has_xpath? select uncheck has_element? has_no_element? has_link? has_no_link? has_button? has_no_button? has_field? has_no_field? has_checked_field? has_unchecked_field? has_no_table? has_table? unselect has_select? has_no_select? has_selector? has_no_selector? click_on has_no_checked_field? has_no_unchecked_field? query assert_selector assert_no_selector assert_all_of_selectors assert_none_of_selectors assert_any_of_selectors refute_selector assert_text assert_no_text ].freeze # @api private DOCUMENT_METHODS = %i[ title assert_title assert_no_title has_title? has_no_title? ].freeze SESSION_METHODS = %i[ body html source current_url current_host current_path execute_script evaluate_script evaluate_async_script visit refresh go_back go_forward send_keys within within_element within_fieldset within_table within_frame switch_to_frame current_window windows open_new_window switch_to_window within_window window_opened_by save_page save_and_open_page save_screenshot save_and_open_screenshot reset_session! response_headers status_code current_scope assert_current_path assert_no_current_path has_current_path? has_no_current_path? ].freeze + DOCUMENT_METHODS MODAL_METHODS = %i[ accept_alert accept_confirm dismiss_confirm accept_prompt dismiss_prompt ].freeze DSL_METHODS = NODE_METHODS + SESSION_METHODS + MODAL_METHODS attr_reader :mode, :app, :server attr_accessor :synchronized def initialize(mode, app = nil) if app && !app.respond_to?(:call) raise TypeError, 'The second parameter to Session::new should be a rack app if passed.' end @@instance_created = true # rubocop:disable Style/ClassVars @mode = mode @app = app if block_given? raise 'A configuration block is only accepted when Capybara.threadsafe == true' unless Capybara.threadsafe yield config end @server = if config.run_server && @app && driver.needs_server? server_options = { port: config.server_port, host: config.server_host, reportable_errors: config.server_errors } server_options[:extra_middleware] = [Capybara::Server::AnimationDisabler] if config.disable_animation Capybara::Server.new(@app, **server_options).boot end @touched = false end def driver @driver ||= begin unless Capybara.drivers[mode] other_drivers = Capybara.drivers.names.map(&:inspect) raise Capybara::DriverNotFoundError, "no driver called #{mode.inspect} was found, available drivers: #{other_drivers.join(', ')}" end driver = Capybara.drivers[mode].call(app) driver.session = self if driver.respond_to?(:session=) driver end end ## # # Reset the session (i.e. remove cookies and navigate to blank page). # # This method does not: # # * accept modal dialogs if they are present (Selenium driver now does, others may not) # * clear browser cache/HTML 5 local storage/IndexedDB/Web SQL database/etc. # * modify state of the driver/underlying browser in any other way # # as doing so will result in performance downsides and it's not needed to do everything from the list above for most apps. # # If you want to do anything from the list above on a general basis you can: # # * write RSpec/Cucumber/etc. after hook # * monkeypatch this method # * use Ruby's `prepend` method # def reset! if @touched driver.reset! @touched = false switch_to_frame(:top) rescue nil # rubocop:disable Style/RescueModifier @scopes = [nil] end @server&.wait_for_pending_requests raise_server_error! end alias_method :cleanup!, :reset! alias_method :reset_session!, :reset! ## # # Disconnect from the current driver. A new driver will be instantiated on the next interaction. # def quit @driver.quit if @driver.respond_to? :quit @document = @driver = nil @touched = false @server&.reset_error! end ## # # Raise errors encountered in the server. # def raise_server_error! return unless @server&.error # Force an explanation for the error being raised as the exception cause begin if config.raise_server_errors raise CapybaraError, 'Your application server raised an error - It has been raised in your test code because Capybara.raise_server_errors == true' end rescue CapybaraError => capy_error # rubocop:disable Naming/RescuedExceptionsVariableName raise @server.error, cause: capy_error ensure @server.reset_error! end end ## # # Returns a hash of response headers. Not supported by all drivers (e.g. Selenium). # # @return [Hash<String, String>] A hash of response headers. # def response_headers driver.response_headers end ## # # Returns the current HTTP status code as an integer. Not supported by all drivers (e.g. Selenium). # # @return [Integer] Current HTTP status code # def status_code driver.status_code end ## # # @return [String] A snapshot of the DOM of the current document, as it looks right now (potentially modified by JavaScript). # def html driver.html || '' end alias_method :body, :html alias_method :source, :html ## # # @return [String] Path of the current page, without any domain information # def current_path # Addressable parsing is more lenient than URI uri = ::Addressable::URI.parse(current_url) # Addressable doesn't support opaque URIs - we want nil here return nil if uri&.scheme == 'about' path = uri&.path path unless path&.empty? end ## # # @return [String] Host of the current page # def current_host uri = URI.parse(current_url) "#{uri.scheme}://#{uri.host}" if uri.host end ## # # @return [String] Fully qualified URL of the current page # def current_url driver.current_url end ## # # Navigate to the given URL. The URL can either be a relative URL or an absolute URL # The behaviour of either depends on the driver. # # session.visit('/foo') # session.visit('http://google.com') # # For drivers which can run against an external application, such as the selenium driver # giving an absolute URL will navigate to that page. This allows testing applications # running on remote servers. For these drivers, setting {Capybara.configure app_host} will make the # remote server the default. For example: # # Capybara.app_host = 'http://google.com' # session.visit('/') # visits the google homepage # # If {Capybara.configure always_include_port} is set to `true` and this session is running against # a rack application, then the port that the rack application is running on will automatically # be inserted into the URL. Supposing the app is running on port `4567`, doing something like: # # visit("http://google.com/test") # # Will actually navigate to `http://google.com:4567/test`. # # @param [#to_s] visit_uri The URL to navigate to. The parameter will be cast to a String. # def visit(visit_uri) raise_server_error! @touched = true visit_uri = ::Addressable::URI.parse(visit_uri.to_s) base_uri = ::Addressable::URI.parse(config.app_host || server_url) if base_uri && [nil, 'http', 'https'].include?(visit_uri.scheme) if visit_uri.relative? visit_uri_parts = visit_uri.to_hash.compact # Useful to people deploying to a subdirectory # and/or single page apps where only the url fragment changes visit_uri_parts[:path] = base_uri.path + visit_uri.path visit_uri = base_uri.merge(visit_uri_parts) end adjust_server_port(visit_uri) end driver.visit(visit_uri.to_s) end ## # # Refresh the page. # def refresh raise_server_error! driver.refresh end ## # # Move back a single entry in the browser's history. # def go_back driver.go_back end ## # # Move forward a single entry in the browser's history. # def go_forward driver.go_forward end ## # @!method send_keys # @see Capybara::Node::Element#send_keys # def send_keys(...) driver.send_keys(...) end ## # # Returns the element with focus. # # Not supported by Rack Test # def active_element Capybara::Queries::ActiveElementQuery.new.resolve_for(self)[0].tap(&:allow_reload!) end ## # # Executes the given block within the context of a node. {#within} takes the # same options as {Capybara::Node::Finders#find #find}, as well as a block. For the duration of the # block, any command to Capybara will be handled as though it were scoped # to the given element. # # within(:xpath, './/div[@id="delivery-address"]') do # fill_in('Street', with: '12 Main Street') # end # # Just as with `#find`, if multiple elements match the selector given to # {#within}, an error will be raised, and just as with `#find`, this # behaviour can be controlled through the `:match` and `:exact` options. # # It is possible to omit the first parameter, in that case, the selector is # assumed to be of the type set in {Capybara.configure default_selector}. # # within('div#delivery-address') do # fill_in('Street', with: '12 Main Street') # end # # Note that a lot of uses of {#within} can be replaced more succinctly with # chaining: # # find('div#delivery-address').fill_in('Street', with: '12 Main Street') # # @overload within(*find_args) # @param (see Capybara::Node::Finders#all) # # @overload within(a_node) # @param [Capybara::Node::Base] a_node The node in whose scope the block should be evaluated # # @raise [Capybara::ElementNotFound] If the scope can't be found before time expires # def within(*args, **kw_args) new_scope = args.first.respond_to?(:to_capybara_node) ? args.first.to_capybara_node : find(*args, **kw_args) begin scopes.push(new_scope) yield new_scope if block_given? ensure scopes.pop end end alias_method :within_element, :within ## # # Execute the given block within the a specific fieldset given the id or legend of that fieldset. # # @param [String] locator Id or legend of the fieldset # def within_fieldset(locator, &block) within(:fieldset, locator, &block) end ## # # Execute the given block within the a specific table given the id or caption of that table. # # @param [String] locator Id or caption of the table # def within_table(locator, &block) within(:table, locator, &block) end ## # # Switch to the given frame. # # If you use this method you are responsible for making sure you switch back to the parent frame when done in the frame changed to. # {#within_frame} is preferred over this method and should be used when possible. # May not be supported by all drivers. # # @overload switch_to_frame(element) # @param [Capybara::Node::Element] element iframe/frame element to switch to # @overload switch_to_frame(location) # @param [Symbol] location relative location of the frame to switch to # * :parent - the parent frame # * :top - the top level document # def switch_to_frame(frame) case frame when Capybara::Node::Element driver.switch_to_frame(frame) scopes.push(:frame) when :parent if scopes.last != :frame raise Capybara::ScopeError, "`switch_to_frame(:parent)` cannot be called from inside a descendant frame's " \ '`within` block.' end scopes.pop driver.switch_to_frame(:parent) when :top idx = scopes.index(:frame) top_level_scopes = [:frame, nil] if idx if scopes.slice(idx..).any? { |scope| !top_level_scopes.include?(scope) } raise Capybara::ScopeError, "`switch_to_frame(:top)` cannot be called from inside a descendant frame's " \ '`within` block.' end scopes.slice!(idx..) driver.switch_to_frame(:top) end else raise ArgumentError, 'You must provide a frame element, :parent, or :top when calling switch_to_frame' end end ## # # Execute the given block within the given iframe using given frame, frame name/id or index. # May not be supported by all drivers. # # @overload within_frame(element) # @param [Capybara::Node::Element] frame element # @overload within_frame([kind = :frame], locator, **options) # @param [Symbol] kind Optional selector type (:frame, :css, :xpath, etc.) - Defaults to :frame # @param [String] locator The locator for the given selector kind. For :frame this is the name/id of a frame/iframe element # @overload within_frame(index) # @param [Integer] index index of a frame (0 based) def within_frame(*args, **kw_args) switch_to_frame(_find_frame(*args, **kw_args)) begin yield if block_given? ensure switch_to_frame(:parent) end end ## # @return [Capybara::Window] current window # def current_window Window.new(self, driver.current_window_handle) end ## # Get all opened windows. # The order of windows in returned array is not defined. # The driver may sort windows by their creation time but it's not required. # # @return [Array<Capybara::Window>] an array of all windows # def windows driver.window_handles.map do |handle| Window.new(self, handle) end end ## # Open a new window. # The current window doesn't change as the result of this call. # It should be switched to explicitly. # # @return [Capybara::Window] window that has been opened # def open_new_window(kind = :tab) window_opened_by do if driver.method(:open_new_window).arity.zero? driver.open_new_window else driver.open_new_window(kind) end end end ## # Switch to the given window. # # @overload switch_to_window(&block) # Switches to the first window for which given block returns a value other than false or nil. # If window that matches block can't be found, the window will be switched back and {Capybara::WindowError} will be raised. # @example # window = switch_to_window { title == 'Page title' } # @raise [Capybara::WindowError] if no window matches given block # @overload switch_to_window(window) # @param window [Capybara::Window] window that should be switched to # @raise [Capybara::Driver::Base#no_such_window_error] if nonexistent (e.g. closed) window was passed # # @return [Capybara::Window] window that has been switched to # @raise [Capybara::ScopeError] if this method is invoked inside {#within} or # {#within_frame} methods # @raise [ArgumentError] if both or neither arguments were provided # def switch_to_window(window = nil, **options, &window_locator) raise ArgumentError, '`switch_to_window` can take either a block or a window, not both' if window && window_locator raise ArgumentError, '`switch_to_window`: either window or block should be provided' if !window && !window_locator unless scopes.last.nil? raise Capybara::ScopeError, '`switch_to_window` is not supposed to be invoked from ' \ '`within` or `within_frame` blocks.' end _switch_to_window(window, **options, &window_locator) end ## # This method does the following: # # 1. Switches to the given window (it can be located by window instance/lambda/string). # 2. Executes the given block (within window located at previous step). # 3. Switches back (this step will be invoked even if an exception occurs at the second step). # # @overload within_window(window) { do_something } # @param window [Capybara::Window] instance of {Capybara::Window} class # that will be switched to # @raise [driver#no_such_window_error] if nonexistent (e.g. closed) window was passed # @overload within_window(proc_or_lambda) { do_something } # @param lambda [Proc] First window for which lambda # returns a value other than false or nil will be switched to. # @example # within_window(->{ page.title == 'Page title' }) { click_button 'Submit' } # @raise [Capybara::WindowError] if no window matching lambda was found # # @raise [Capybara::ScopeError] if this method is invoked inside {#within_frame} method # @return value returned by the block # def within_window(window_or_proc) original = current_window scopes << nil begin case window_or_proc when Capybara::Window _switch_to_window(window_or_proc) unless original == window_or_proc when Proc _switch_to_window { window_or_proc.call } else raise ArgumentError, '`#within_window` requires a `Capybara::Window` instance or a lambda' end begin yield if block_given? ensure _switch_to_window(original) unless original == window_or_proc end ensure scopes.pop end end ## # Get the window that has been opened by the passed block. # It will wait for it to be opened (in the same way as other Capybara methods wait). # It's better to use this method than `windows.last` # {https://dvcs.w3.org/hg/webdriver/raw-file/default/webdriver-spec.html#h_note_10 as order of windows isn't defined in some drivers}. # # @overload window_opened_by(**options, &block) # @param options [Hash] # @option options [Numeric] :wait maximum wait time. Defaults to {Capybara.configure default_max_wait_time} # @return [Capybara::Window] the window that has been opened within a block # @raise [Capybara::WindowError] if block passed to window hasn't opened window # or opened more than one window # def window_opened_by(**options) old_handles = driver.window_handles yield synchronize_windows(options) do opened_handles = (driver.window_handles - old_handles) if opened_handles.size != 1 raise Capybara::WindowError, 'block passed to #window_opened_by ' \ "opened #{opened_handles.size} windows instead of 1" end Window.new(self, opened_handles.first) end end ## # # Execute the given script, not returning a result. This is useful for scripts that return # complex objects, such as jQuery statements. {#execute_script} should be used over # {#evaluate_script} whenever possible. # # @param [String] script A string of JavaScript to execute # @param args Optional arguments that will be passed to the script. Driver support for this is optional and types of objects supported may differ between drivers # def execute_script(script, *args) @touched = true driver.execute_script(script, *driver_args(args)) end ## # # Evaluate the given JavaScript and return the result. Be careful when using this with # scripts that return complex objects, such as jQuery statements. {#execute_script} might # be a better alternative. # # @param [String] script A string of JavaScript to evaluate # @param args Optional arguments that will be passed to the script # @return [Object] The result of the evaluated JavaScript (may be driver specific) # def evaluate_script(script, *args) @touched = true result = driver.evaluate_script(script.strip, *driver_args(args)) element_script_result(result) end ## # # Evaluate the given JavaScript and obtain the result from a callback function which will be passed as the last argument to the script. # # @param [String] script A string of JavaScript to evaluate # @param args Optional arguments that will be passed to the script # @return [Object] The result of the evaluated JavaScript (may be driver specific) # def evaluate_async_script(script, *args) @touched = true result = driver.evaluate_async_script(script, *driver_args(args)) element_script_result(result) end ## # # Execute the block, accepting a alert. # # @!macro modal_params # Expects a block whose actions will trigger the display modal to appear. # @example # $0 do # click_link('link that triggers appearance of system modal') # end # @overload $0(text, **options, &blk) # @param text [String, Regexp] Text or regex to match against the text in the modal. If not provided any modal is matched. # @option options [Numeric] :wait Maximum time to wait for the modal to appear after executing the block. Defaults to {Capybara.configure default_max_wait_time}. # @yield Block whose actions will trigger the system modal # @overload $0(**options, &blk) # @option options [Numeric] :wait Maximum time to wait for the modal to appear after executing the block. Defaults to {Capybara.configure default_max_wait_time}. # @yield Block whose actions will trigger the system modal # @return [String] the message shown in the modal # @raise [Capybara::ModalNotFound] if modal dialog hasn't been found # def accept_alert(text = nil, **options, &blk) accept_modal(:alert, text, options, &blk) end ## # # Execute the block, accepting a confirm. # # @macro modal_params # def accept_confirm(text = nil, **options, &blk) accept_modal(:confirm, text, options, &blk) end ## # # Execute the block, dismissing a confirm. # # @macro modal_params # def dismiss_confirm(text = nil, **options, &blk) dismiss_modal(:confirm, text, options, &blk) end ## # # Execute the block, accepting a prompt, optionally responding to the prompt. # # @macro modal_params # @option options [String] :with Response to provide to the prompt # def accept_prompt(text = nil, **options, &blk) accept_modal(:prompt, text, options, &blk) end ## # # Execute the block, dismissing a prompt. # # @macro modal_params # def dismiss_prompt(text = nil, **options, &blk) dismiss_modal(:prompt, text, options, &blk) end ## # # Save a snapshot of the page. If {Capybara.configure asset_host} is set it will inject `base` tag # pointing to {Capybara.configure asset_host}. # # If invoked without arguments it will save file to {Capybara.configure save_path} # and file will be given randomly generated filename. If invoked with a relative path # the path will be relative to {Capybara.configure save_path}. # # @param [String] path the path to where it should be saved # @return [String] the path to which the file was saved # def save_page(path = nil) prepare_path(path, 'html').tap do |p_path| File.write(p_path, Capybara::Helpers.inject_asset_host(body, host: config.asset_host), mode: 'wb') end end ## # # Save a snapshot of the page and open it in a browser for inspection. # # If invoked without arguments it will save file to {Capybara.configure save_path} # and file will be given randomly generated filename. If invoked with a relative path # the path will be relative to {Capybara.configure save_path}. # # @param [String] path the path to where it should be saved # def save_and_open_page(path = nil) save_page(path).tap { |s_path| open_file(s_path) } end ## # # Save a screenshot of page. # # If invoked without arguments it will save file to {Capybara.configure save_path} # and file will be given randomly generated filename. If invoked with a relative path # the path will be relative to {Capybara.configure save_path}. # # @param [String] path the path to where it should be saved # @param [Hash] options a customizable set of options # @return [String] the path to which the file was saved def save_screenshot(path = nil, **options) prepare_path(path, 'png').tap { |p_path| driver.save_screenshot(p_path, **options) } end ## # # Save a screenshot of the page and open it for inspection. # # If invoked without arguments it will save file to {Capybara.configure save_path} # and file will be given randomly generated filename. If invoked with a relative path # the path will be relative to {Capybara.configure save_path}. # # @param [String] path the path to where it should be saved # @param [Hash] options a customizable set of options # def save_and_open_screenshot(path = nil, **options) save_screenshot(path, **options).tap { |s_path| open_file(s_path) } end def document @document ||= Capybara::Node::Document.new(self, driver) end NODE_METHODS.each do |method| class_eval <<~METHOD, __FILE__, __LINE__ + 1 def #{method}(...) @touched = true current_scope.#{method}(...) end METHOD end DOCUMENT_METHODS.each do |method| class_eval <<~METHOD, __FILE__, __LINE__ + 1 def #{method}(...) document.#{method}(...) end METHOD end def inspect %(#<Capybara::Session>) end def current_scope scope = scopes.last [nil, :frame].include?(scope) ? document : scope end ## # # Yield a block using a specific maximum wait time. # def using_wait_time(seconds, &block) if Capybara.threadsafe begin previous_wait_time = config.default_max_wait_time config.default_max_wait_time = seconds yield ensure config.default_max_wait_time = previous_wait_time end else Capybara.using_wait_time(seconds, &block) end end ## # # Accepts a block to set the configuration options if {Capybara.configure threadsafe} is `true`. Note that some options only have an effect # if set at initialization time, so look at the configuration block that can be passed to the initializer too. # def configure raise 'Session configuration is only supported when Capybara.threadsafe == true' unless Capybara.threadsafe yield config end def self.instance_created? @@instance_created end def config @config ||= if Capybara.threadsafe Capybara.session_options.dup else Capybara::ReadOnlySessionConfig.new(Capybara.session_options) end end def server_url @server&.base_url end private @@instance_created = false # rubocop:disable Style/ClassVars def driver_args(args) args.map { |arg| arg.is_a?(Capybara::Node::Element) ? arg.base : arg } end def accept_modal(type, text_or_options, options, &blk) driver.accept_modal(type, **modal_options(text_or_options, **options), &blk) end def dismiss_modal(type, text_or_options, options, &blk) driver.dismiss_modal(type, **modal_options(text_or_options, **options), &blk) end def modal_options(text = nil, **options) options[:text] ||= text unless text.nil? options[:wait] ||= config.default_max_wait_time options end def open_file(path) require 'launchy' Launchy.open(path) rescue LoadError warn "File saved to #{path}.\nPlease install the launchy gem to open the file automatically." end def prepare_path(path, extension) File.expand_path(path || default_fn(extension), config.save_path).tap do |p_path| FileUtils.mkdir_p(File.dirname(p_path)) end end def default_fn(extension) timestamp = Time.new.strftime('%Y%m%d%H%M%S') "capybara-#{timestamp}#{rand(10**10)}.#{extension}" end def scopes @scopes ||= [nil] end def element_script_result(arg) case arg when Array arg.map { |subarg| element_script_result(subarg) } when Hash arg.transform_values! { |value| element_script_result(value) } when Capybara::Driver::Node Capybara::Node::Element.new(self, arg, nil, nil) else arg end end def adjust_server_port(uri) uri.port ||= @server.port if @server && config.always_include_port end def _find_frame(*args, **kw_args) case args[0] when Capybara::Node::Element args[0] when String, nil find(:frame, *args, **kw_args) when Symbol find(*args, **kw_args) when Integer idx = args[0] all(:frame, minimum: idx + 1)[idx] else raise TypeError end end def _switch_to_window(window = nil, **options, &window_locator) raise Capybara::ScopeError, 'Window cannot be switched inside a `within_frame` block' if scopes.include?(:frame) raise Capybara::ScopeError, 'Window cannot be switched inside a `within` block' unless scopes.last.nil? if window driver.switch_to_window(window.handle) window else synchronize_windows(options) do original_window_handle = driver.current_window_handle begin _switch_to_window_by_locator(&window_locator) rescue StandardError driver.switch_to_window(original_window_handle) raise end end end end def _switch_to_window_by_locator driver.window_handles.each do |handle| driver.switch_to_window handle return Window.new(self, handle) if yield end raise Capybara::WindowError, 'Could not find a window matching block/lambda' end def synchronize_windows(options, &block) wait_time = Capybara::Queries::BaseQuery.wait(options, config.default_max_wait_time) document.synchronize(wait_time, errors: [Capybara::WindowError], &block) end end end
Ruby
{ "end_line": 566, "name": "within_window", "signature": "def within_window(window_or_proc)", "start_line": 545 }
{ "class_name": "Session", "class_signature": "class Session", "module": "Capybara" }
window_opened_by
capybara/lib/capybara/session.rb
def window_opened_by(**options) old_handles = driver.window_handles yield synchronize_windows(options) do opened_handles = (driver.window_handles - old_handles) if opened_handles.size != 1 raise Capybara::WindowError, 'block passed to #window_opened_by ' \ "opened #{opened_handles.size} windows instead of 1" end Window.new(self, opened_handles.first) end end
# frozen_string_literal: true require 'capybara/session/matchers' require 'addressable/uri' module Capybara ## # # The {Session} class represents a single user's interaction with the system. The {Session} can use # any of the underlying drivers. A session can be initialized manually like this: # # session = Capybara::Session.new(:culerity, MyRackApp) # # The application given as the second argument is optional. When running Capybara against an external # page, you might want to leave it out: # # session = Capybara::Session.new(:culerity) # session.visit('http://www.google.com') # # When {Capybara.configure threadsafe} is `true` the sessions options will be initially set to the # current values of the global options and a configuration block can be passed to the session initializer. # For available options see {Capybara::SessionConfig::OPTIONS}: # # session = Capybara::Session.new(:driver, MyRackApp) do |config| # config.app_host = "http://my_host.dev" # end # # The {Session} provides a number of methods for controlling the navigation of the page, such as {#visit}, # {#current_path}, and so on. It also delegates a number of methods to a {Capybara::Document}, representing # the current HTML document. This allows interaction: # # session.fill_in('q', with: 'Capybara') # session.click_button('Search') # expect(session).to have_content('Capybara') # # When using `capybara/dsl`, the {Session} is initialized automatically for you. # class Session include Capybara::SessionMatchers NODE_METHODS = %i[ all first attach_file text check choose scroll_to scroll_by click double_click right_click click_link_or_button click_button click_link fill_in find find_all find_button find_by_id find_field find_link has_content? has_text? has_css? has_no_content? has_no_text? has_no_css? has_no_xpath? has_xpath? select uncheck has_element? has_no_element? has_link? has_no_link? has_button? has_no_button? has_field? has_no_field? has_checked_field? has_unchecked_field? has_no_table? has_table? unselect has_select? has_no_select? has_selector? has_no_selector? click_on has_no_checked_field? has_no_unchecked_field? query assert_selector assert_no_selector assert_all_of_selectors assert_none_of_selectors assert_any_of_selectors refute_selector assert_text assert_no_text ].freeze # @api private DOCUMENT_METHODS = %i[ title assert_title assert_no_title has_title? has_no_title? ].freeze SESSION_METHODS = %i[ body html source current_url current_host current_path execute_script evaluate_script evaluate_async_script visit refresh go_back go_forward send_keys within within_element within_fieldset within_table within_frame switch_to_frame current_window windows open_new_window switch_to_window within_window window_opened_by save_page save_and_open_page save_screenshot save_and_open_screenshot reset_session! response_headers status_code current_scope assert_current_path assert_no_current_path has_current_path? has_no_current_path? ].freeze + DOCUMENT_METHODS MODAL_METHODS = %i[ accept_alert accept_confirm dismiss_confirm accept_prompt dismiss_prompt ].freeze DSL_METHODS = NODE_METHODS + SESSION_METHODS + MODAL_METHODS attr_reader :mode, :app, :server attr_accessor :synchronized def initialize(mode, app = nil) if app && !app.respond_to?(:call) raise TypeError, 'The second parameter to Session::new should be a rack app if passed.' end @@instance_created = true # rubocop:disable Style/ClassVars @mode = mode @app = app if block_given? raise 'A configuration block is only accepted when Capybara.threadsafe == true' unless Capybara.threadsafe yield config end @server = if config.run_server && @app && driver.needs_server? server_options = { port: config.server_port, host: config.server_host, reportable_errors: config.server_errors } server_options[:extra_middleware] = [Capybara::Server::AnimationDisabler] if config.disable_animation Capybara::Server.new(@app, **server_options).boot end @touched = false end def driver @driver ||= begin unless Capybara.drivers[mode] other_drivers = Capybara.drivers.names.map(&:inspect) raise Capybara::DriverNotFoundError, "no driver called #{mode.inspect} was found, available drivers: #{other_drivers.join(', ')}" end driver = Capybara.drivers[mode].call(app) driver.session = self if driver.respond_to?(:session=) driver end end ## # # Reset the session (i.e. remove cookies and navigate to blank page). # # This method does not: # # * accept modal dialogs if they are present (Selenium driver now does, others may not) # * clear browser cache/HTML 5 local storage/IndexedDB/Web SQL database/etc. # * modify state of the driver/underlying browser in any other way # # as doing so will result in performance downsides and it's not needed to do everything from the list above for most apps. # # If you want to do anything from the list above on a general basis you can: # # * write RSpec/Cucumber/etc. after hook # * monkeypatch this method # * use Ruby's `prepend` method # def reset! if @touched driver.reset! @touched = false switch_to_frame(:top) rescue nil # rubocop:disable Style/RescueModifier @scopes = [nil] end @server&.wait_for_pending_requests raise_server_error! end alias_method :cleanup!, :reset! alias_method :reset_session!, :reset! ## # # Disconnect from the current driver. A new driver will be instantiated on the next interaction. # def quit @driver.quit if @driver.respond_to? :quit @document = @driver = nil @touched = false @server&.reset_error! end ## # # Raise errors encountered in the server. # def raise_server_error! return unless @server&.error # Force an explanation for the error being raised as the exception cause begin if config.raise_server_errors raise CapybaraError, 'Your application server raised an error - It has been raised in your test code because Capybara.raise_server_errors == true' end rescue CapybaraError => capy_error # rubocop:disable Naming/RescuedExceptionsVariableName raise @server.error, cause: capy_error ensure @server.reset_error! end end ## # # Returns a hash of response headers. Not supported by all drivers (e.g. Selenium). # # @return [Hash<String, String>] A hash of response headers. # def response_headers driver.response_headers end ## # # Returns the current HTTP status code as an integer. Not supported by all drivers (e.g. Selenium). # # @return [Integer] Current HTTP status code # def status_code driver.status_code end ## # # @return [String] A snapshot of the DOM of the current document, as it looks right now (potentially modified by JavaScript). # def html driver.html || '' end alias_method :body, :html alias_method :source, :html ## # # @return [String] Path of the current page, without any domain information # def current_path # Addressable parsing is more lenient than URI uri = ::Addressable::URI.parse(current_url) # Addressable doesn't support opaque URIs - we want nil here return nil if uri&.scheme == 'about' path = uri&.path path unless path&.empty? end ## # # @return [String] Host of the current page # def current_host uri = URI.parse(current_url) "#{uri.scheme}://#{uri.host}" if uri.host end ## # # @return [String] Fully qualified URL of the current page # def current_url driver.current_url end ## # # Navigate to the given URL. The URL can either be a relative URL or an absolute URL # The behaviour of either depends on the driver. # # session.visit('/foo') # session.visit('http://google.com') # # For drivers which can run against an external application, such as the selenium driver # giving an absolute URL will navigate to that page. This allows testing applications # running on remote servers. For these drivers, setting {Capybara.configure app_host} will make the # remote server the default. For example: # # Capybara.app_host = 'http://google.com' # session.visit('/') # visits the google homepage # # If {Capybara.configure always_include_port} is set to `true` and this session is running against # a rack application, then the port that the rack application is running on will automatically # be inserted into the URL. Supposing the app is running on port `4567`, doing something like: # # visit("http://google.com/test") # # Will actually navigate to `http://google.com:4567/test`. # # @param [#to_s] visit_uri The URL to navigate to. The parameter will be cast to a String. # def visit(visit_uri) raise_server_error! @touched = true visit_uri = ::Addressable::URI.parse(visit_uri.to_s) base_uri = ::Addressable::URI.parse(config.app_host || server_url) if base_uri && [nil, 'http', 'https'].include?(visit_uri.scheme) if visit_uri.relative? visit_uri_parts = visit_uri.to_hash.compact # Useful to people deploying to a subdirectory # and/or single page apps where only the url fragment changes visit_uri_parts[:path] = base_uri.path + visit_uri.path visit_uri = base_uri.merge(visit_uri_parts) end adjust_server_port(visit_uri) end driver.visit(visit_uri.to_s) end ## # # Refresh the page. # def refresh raise_server_error! driver.refresh end ## # # Move back a single entry in the browser's history. # def go_back driver.go_back end ## # # Move forward a single entry in the browser's history. # def go_forward driver.go_forward end ## # @!method send_keys # @see Capybara::Node::Element#send_keys # def send_keys(...) driver.send_keys(...) end ## # # Returns the element with focus. # # Not supported by Rack Test # def active_element Capybara::Queries::ActiveElementQuery.new.resolve_for(self)[0].tap(&:allow_reload!) end ## # # Executes the given block within the context of a node. {#within} takes the # same options as {Capybara::Node::Finders#find #find}, as well as a block. For the duration of the # block, any command to Capybara will be handled as though it were scoped # to the given element. # # within(:xpath, './/div[@id="delivery-address"]') do # fill_in('Street', with: '12 Main Street') # end # # Just as with `#find`, if multiple elements match the selector given to # {#within}, an error will be raised, and just as with `#find`, this # behaviour can be controlled through the `:match` and `:exact` options. # # It is possible to omit the first parameter, in that case, the selector is # assumed to be of the type set in {Capybara.configure default_selector}. # # within('div#delivery-address') do # fill_in('Street', with: '12 Main Street') # end # # Note that a lot of uses of {#within} can be replaced more succinctly with # chaining: # # find('div#delivery-address').fill_in('Street', with: '12 Main Street') # # @overload within(*find_args) # @param (see Capybara::Node::Finders#all) # # @overload within(a_node) # @param [Capybara::Node::Base] a_node The node in whose scope the block should be evaluated # # @raise [Capybara::ElementNotFound] If the scope can't be found before time expires # def within(*args, **kw_args) new_scope = args.first.respond_to?(:to_capybara_node) ? args.first.to_capybara_node : find(*args, **kw_args) begin scopes.push(new_scope) yield new_scope if block_given? ensure scopes.pop end end alias_method :within_element, :within ## # # Execute the given block within the a specific fieldset given the id or legend of that fieldset. # # @param [String] locator Id or legend of the fieldset # def within_fieldset(locator, &block) within(:fieldset, locator, &block) end ## # # Execute the given block within the a specific table given the id or caption of that table. # # @param [String] locator Id or caption of the table # def within_table(locator, &block) within(:table, locator, &block) end ## # # Switch to the given frame. # # If you use this method you are responsible for making sure you switch back to the parent frame when done in the frame changed to. # {#within_frame} is preferred over this method and should be used when possible. # May not be supported by all drivers. # # @overload switch_to_frame(element) # @param [Capybara::Node::Element] element iframe/frame element to switch to # @overload switch_to_frame(location) # @param [Symbol] location relative location of the frame to switch to # * :parent - the parent frame # * :top - the top level document # def switch_to_frame(frame) case frame when Capybara::Node::Element driver.switch_to_frame(frame) scopes.push(:frame) when :parent if scopes.last != :frame raise Capybara::ScopeError, "`switch_to_frame(:parent)` cannot be called from inside a descendant frame's " \ '`within` block.' end scopes.pop driver.switch_to_frame(:parent) when :top idx = scopes.index(:frame) top_level_scopes = [:frame, nil] if idx if scopes.slice(idx..).any? { |scope| !top_level_scopes.include?(scope) } raise Capybara::ScopeError, "`switch_to_frame(:top)` cannot be called from inside a descendant frame's " \ '`within` block.' end scopes.slice!(idx..) driver.switch_to_frame(:top) end else raise ArgumentError, 'You must provide a frame element, :parent, or :top when calling switch_to_frame' end end ## # # Execute the given block within the given iframe using given frame, frame name/id or index. # May not be supported by all drivers. # # @overload within_frame(element) # @param [Capybara::Node::Element] frame element # @overload within_frame([kind = :frame], locator, **options) # @param [Symbol] kind Optional selector type (:frame, :css, :xpath, etc.) - Defaults to :frame # @param [String] locator The locator for the given selector kind. For :frame this is the name/id of a frame/iframe element # @overload within_frame(index) # @param [Integer] index index of a frame (0 based) def within_frame(*args, **kw_args) switch_to_frame(_find_frame(*args, **kw_args)) begin yield if block_given? ensure switch_to_frame(:parent) end end ## # @return [Capybara::Window] current window # def current_window Window.new(self, driver.current_window_handle) end ## # Get all opened windows. # The order of windows in returned array is not defined. # The driver may sort windows by their creation time but it's not required. # # @return [Array<Capybara::Window>] an array of all windows # def windows driver.window_handles.map do |handle| Window.new(self, handle) end end ## # Open a new window. # The current window doesn't change as the result of this call. # It should be switched to explicitly. # # @return [Capybara::Window] window that has been opened # def open_new_window(kind = :tab) window_opened_by do if driver.method(:open_new_window).arity.zero? driver.open_new_window else driver.open_new_window(kind) end end end ## # Switch to the given window. # # @overload switch_to_window(&block) # Switches to the first window for which given block returns a value other than false or nil. # If window that matches block can't be found, the window will be switched back and {Capybara::WindowError} will be raised. # @example # window = switch_to_window { title == 'Page title' } # @raise [Capybara::WindowError] if no window matches given block # @overload switch_to_window(window) # @param window [Capybara::Window] window that should be switched to # @raise [Capybara::Driver::Base#no_such_window_error] if nonexistent (e.g. closed) window was passed # # @return [Capybara::Window] window that has been switched to # @raise [Capybara::ScopeError] if this method is invoked inside {#within} or # {#within_frame} methods # @raise [ArgumentError] if both or neither arguments were provided # def switch_to_window(window = nil, **options, &window_locator) raise ArgumentError, '`switch_to_window` can take either a block or a window, not both' if window && window_locator raise ArgumentError, '`switch_to_window`: either window or block should be provided' if !window && !window_locator unless scopes.last.nil? raise Capybara::ScopeError, '`switch_to_window` is not supposed to be invoked from ' \ '`within` or `within_frame` blocks.' end _switch_to_window(window, **options, &window_locator) end ## # This method does the following: # # 1. Switches to the given window (it can be located by window instance/lambda/string). # 2. Executes the given block (within window located at previous step). # 3. Switches back (this step will be invoked even if an exception occurs at the second step). # # @overload within_window(window) { do_something } # @param window [Capybara::Window] instance of {Capybara::Window} class # that will be switched to # @raise [driver#no_such_window_error] if nonexistent (e.g. closed) window was passed # @overload within_window(proc_or_lambda) { do_something } # @param lambda [Proc] First window for which lambda # returns a value other than false or nil will be switched to. # @example # within_window(->{ page.title == 'Page title' }) { click_button 'Submit' } # @raise [Capybara::WindowError] if no window matching lambda was found # # @raise [Capybara::ScopeError] if this method is invoked inside {#within_frame} method # @return value returned by the block # def within_window(window_or_proc) original = current_window scopes << nil begin case window_or_proc when Capybara::Window _switch_to_window(window_or_proc) unless original == window_or_proc when Proc _switch_to_window { window_or_proc.call } else raise ArgumentError, '`#within_window` requires a `Capybara::Window` instance or a lambda' end begin yield if block_given? ensure _switch_to_window(original) unless original == window_or_proc end ensure scopes.pop end end ## # Get the window that has been opened by the passed block. # It will wait for it to be opened (in the same way as other Capybara methods wait). # It's better to use this method than `windows.last` # {https://dvcs.w3.org/hg/webdriver/raw-file/default/webdriver-spec.html#h_note_10 as order of windows isn't defined in some drivers}. # # @overload window_opened_by(**options, &block) # @param options [Hash] # @option options [Numeric] :wait maximum wait time. Defaults to {Capybara.configure default_max_wait_time} # @return [Capybara::Window] the window that has been opened within a block # @raise [Capybara::WindowError] if block passed to window hasn't opened window # or opened more than one window # def window_opened_by(**options) old_handles = driver.window_handles yield synchronize_windows(options) do opened_handles = (driver.window_handles - old_handles) if opened_handles.size != 1 raise Capybara::WindowError, 'block passed to #window_opened_by ' \ "opened #{opened_handles.size} windows instead of 1" end Window.new(self, opened_handles.first) end end ## # # Execute the given script, not returning a result. This is useful for scripts that return # complex objects, such as jQuery statements. {#execute_script} should be used over # {#evaluate_script} whenever possible. # # @param [String] script A string of JavaScript to execute # @param args Optional arguments that will be passed to the script. Driver support for this is optional and types of objects supported may differ between drivers # def execute_script(script, *args) @touched = true driver.execute_script(script, *driver_args(args)) end ## # # Evaluate the given JavaScript and return the result. Be careful when using this with # scripts that return complex objects, such as jQuery statements. {#execute_script} might # be a better alternative. # # @param [String] script A string of JavaScript to evaluate # @param args Optional arguments that will be passed to the script # @return [Object] The result of the evaluated JavaScript (may be driver specific) # def evaluate_script(script, *args) @touched = true result = driver.evaluate_script(script.strip, *driver_args(args)) element_script_result(result) end ## # # Evaluate the given JavaScript and obtain the result from a callback function which will be passed as the last argument to the script. # # @param [String] script A string of JavaScript to evaluate # @param args Optional arguments that will be passed to the script # @return [Object] The result of the evaluated JavaScript (may be driver specific) # def evaluate_async_script(script, *args) @touched = true result = driver.evaluate_async_script(script, *driver_args(args)) element_script_result(result) end ## # # Execute the block, accepting a alert. # # @!macro modal_params # Expects a block whose actions will trigger the display modal to appear. # @example # $0 do # click_link('link that triggers appearance of system modal') # end # @overload $0(text, **options, &blk) # @param text [String, Regexp] Text or regex to match against the text in the modal. If not provided any modal is matched. # @option options [Numeric] :wait Maximum time to wait for the modal to appear after executing the block. Defaults to {Capybara.configure default_max_wait_time}. # @yield Block whose actions will trigger the system modal # @overload $0(**options, &blk) # @option options [Numeric] :wait Maximum time to wait for the modal to appear after executing the block. Defaults to {Capybara.configure default_max_wait_time}. # @yield Block whose actions will trigger the system modal # @return [String] the message shown in the modal # @raise [Capybara::ModalNotFound] if modal dialog hasn't been found # def accept_alert(text = nil, **options, &blk) accept_modal(:alert, text, options, &blk) end ## # # Execute the block, accepting a confirm. # # @macro modal_params # def accept_confirm(text = nil, **options, &blk) accept_modal(:confirm, text, options, &blk) end ## # # Execute the block, dismissing a confirm. # # @macro modal_params # def dismiss_confirm(text = nil, **options, &blk) dismiss_modal(:confirm, text, options, &blk) end ## # # Execute the block, accepting a prompt, optionally responding to the prompt. # # @macro modal_params # @option options [String] :with Response to provide to the prompt # def accept_prompt(text = nil, **options, &blk) accept_modal(:prompt, text, options, &blk) end ## # # Execute the block, dismissing a prompt. # # @macro modal_params # def dismiss_prompt(text = nil, **options, &blk) dismiss_modal(:prompt, text, options, &blk) end ## # # Save a snapshot of the page. If {Capybara.configure asset_host} is set it will inject `base` tag # pointing to {Capybara.configure asset_host}. # # If invoked without arguments it will save file to {Capybara.configure save_path} # and file will be given randomly generated filename. If invoked with a relative path # the path will be relative to {Capybara.configure save_path}. # # @param [String] path the path to where it should be saved # @return [String] the path to which the file was saved # def save_page(path = nil) prepare_path(path, 'html').tap do |p_path| File.write(p_path, Capybara::Helpers.inject_asset_host(body, host: config.asset_host), mode: 'wb') end end ## # # Save a snapshot of the page and open it in a browser for inspection. # # If invoked without arguments it will save file to {Capybara.configure save_path} # and file will be given randomly generated filename. If invoked with a relative path # the path will be relative to {Capybara.configure save_path}. # # @param [String] path the path to where it should be saved # def save_and_open_page(path = nil) save_page(path).tap { |s_path| open_file(s_path) } end ## # # Save a screenshot of page. # # If invoked without arguments it will save file to {Capybara.configure save_path} # and file will be given randomly generated filename. If invoked with a relative path # the path will be relative to {Capybara.configure save_path}. # # @param [String] path the path to where it should be saved # @param [Hash] options a customizable set of options # @return [String] the path to which the file was saved def save_screenshot(path = nil, **options) prepare_path(path, 'png').tap { |p_path| driver.save_screenshot(p_path, **options) } end ## # # Save a screenshot of the page and open it for inspection. # # If invoked without arguments it will save file to {Capybara.configure save_path} # and file will be given randomly generated filename. If invoked with a relative path # the path will be relative to {Capybara.configure save_path}. # # @param [String] path the path to where it should be saved # @param [Hash] options a customizable set of options # def save_and_open_screenshot(path = nil, **options) save_screenshot(path, **options).tap { |s_path| open_file(s_path) } end def document @document ||= Capybara::Node::Document.new(self, driver) end NODE_METHODS.each do |method| class_eval <<~METHOD, __FILE__, __LINE__ + 1 def #{method}(...) @touched = true current_scope.#{method}(...) end METHOD end DOCUMENT_METHODS.each do |method| class_eval <<~METHOD, __FILE__, __LINE__ + 1 def #{method}(...) document.#{method}(...) end METHOD end def inspect %(#<Capybara::Session>) end def current_scope scope = scopes.last [nil, :frame].include?(scope) ? document : scope end ## # # Yield a block using a specific maximum wait time. # def using_wait_time(seconds, &block) if Capybara.threadsafe begin previous_wait_time = config.default_max_wait_time config.default_max_wait_time = seconds yield ensure config.default_max_wait_time = previous_wait_time end else Capybara.using_wait_time(seconds, &block) end end ## # # Accepts a block to set the configuration options if {Capybara.configure threadsafe} is `true`. Note that some options only have an effect # if set at initialization time, so look at the configuration block that can be passed to the initializer too. # def configure raise 'Session configuration is only supported when Capybara.threadsafe == true' unless Capybara.threadsafe yield config end def self.instance_created? @@instance_created end def config @config ||= if Capybara.threadsafe Capybara.session_options.dup else Capybara::ReadOnlySessionConfig.new(Capybara.session_options) end end def server_url @server&.base_url end private @@instance_created = false # rubocop:disable Style/ClassVars def driver_args(args) args.map { |arg| arg.is_a?(Capybara::Node::Element) ? arg.base : arg } end def accept_modal(type, text_or_options, options, &blk) driver.accept_modal(type, **modal_options(text_or_options, **options), &blk) end def dismiss_modal(type, text_or_options, options, &blk) driver.dismiss_modal(type, **modal_options(text_or_options, **options), &blk) end def modal_options(text = nil, **options) options[:text] ||= text unless text.nil? options[:wait] ||= config.default_max_wait_time options end def open_file(path) require 'launchy' Launchy.open(path) rescue LoadError warn "File saved to #{path}.\nPlease install the launchy gem to open the file automatically." end def prepare_path(path, extension) File.expand_path(path || default_fn(extension), config.save_path).tap do |p_path| FileUtils.mkdir_p(File.dirname(p_path)) end end def default_fn(extension) timestamp = Time.new.strftime('%Y%m%d%H%M%S') "capybara-#{timestamp}#{rand(10**10)}.#{extension}" end def scopes @scopes ||= [nil] end def element_script_result(arg) case arg when Array arg.map { |subarg| element_script_result(subarg) } when Hash arg.transform_values! { |value| element_script_result(value) } when Capybara::Driver::Node Capybara::Node::Element.new(self, arg, nil, nil) else arg end end def adjust_server_port(uri) uri.port ||= @server.port if @server && config.always_include_port end def _find_frame(*args, **kw_args) case args[0] when Capybara::Node::Element args[0] when String, nil find(:frame, *args, **kw_args) when Symbol find(*args, **kw_args) when Integer idx = args[0] all(:frame, minimum: idx + 1)[idx] else raise TypeError end end def _switch_to_window(window = nil, **options, &window_locator) raise Capybara::ScopeError, 'Window cannot be switched inside a `within_frame` block' if scopes.include?(:frame) raise Capybara::ScopeError, 'Window cannot be switched inside a `within` block' unless scopes.last.nil? if window driver.switch_to_window(window.handle) window else synchronize_windows(options) do original_window_handle = driver.current_window_handle begin _switch_to_window_by_locator(&window_locator) rescue StandardError driver.switch_to_window(original_window_handle) raise end end end end def _switch_to_window_by_locator driver.window_handles.each do |handle| driver.switch_to_window handle return Window.new(self, handle) if yield end raise Capybara::WindowError, 'Could not find a window matching block/lambda' end def synchronize_windows(options, &block) wait_time = Capybara::Queries::BaseQuery.wait(options, config.default_max_wait_time) document.synchronize(wait_time, errors: [Capybara::WindowError], &block) end end end
Ruby
{ "end_line": 593, "name": "window_opened_by", "signature": "def window_opened_by(**options)", "start_line": 581 }
{ "class_name": "Session", "class_signature": "class Session", "module": "Capybara" }
using_wait_time
capybara/lib/capybara/session.rb
def using_wait_time(seconds, &block) if Capybara.threadsafe begin previous_wait_time = config.default_max_wait_time config.default_max_wait_time = seconds yield ensure config.default_max_wait_time = previous_wait_time end else Capybara.using_wait_time(seconds, &block) end end
# frozen_string_literal: true require 'capybara/session/matchers' require 'addressable/uri' module Capybara ## # # The {Session} class represents a single user's interaction with the system. The {Session} can use # any of the underlying drivers. A session can be initialized manually like this: # # session = Capybara::Session.new(:culerity, MyRackApp) # # The application given as the second argument is optional. When running Capybara against an external # page, you might want to leave it out: # # session = Capybara::Session.new(:culerity) # session.visit('http://www.google.com') # # When {Capybara.configure threadsafe} is `true` the sessions options will be initially set to the # current values of the global options and a configuration block can be passed to the session initializer. # For available options see {Capybara::SessionConfig::OPTIONS}: # # session = Capybara::Session.new(:driver, MyRackApp) do |config| # config.app_host = "http://my_host.dev" # end # # The {Session} provides a number of methods for controlling the navigation of the page, such as {#visit}, # {#current_path}, and so on. It also delegates a number of methods to a {Capybara::Document}, representing # the current HTML document. This allows interaction: # # session.fill_in('q', with: 'Capybara') # session.click_button('Search') # expect(session).to have_content('Capybara') # # When using `capybara/dsl`, the {Session} is initialized automatically for you. # class Session include Capybara::SessionMatchers NODE_METHODS = %i[ all first attach_file text check choose scroll_to scroll_by click double_click right_click click_link_or_button click_button click_link fill_in find find_all find_button find_by_id find_field find_link has_content? has_text? has_css? has_no_content? has_no_text? has_no_css? has_no_xpath? has_xpath? select uncheck has_element? has_no_element? has_link? has_no_link? has_button? has_no_button? has_field? has_no_field? has_checked_field? has_unchecked_field? has_no_table? has_table? unselect has_select? has_no_select? has_selector? has_no_selector? click_on has_no_checked_field? has_no_unchecked_field? query assert_selector assert_no_selector assert_all_of_selectors assert_none_of_selectors assert_any_of_selectors refute_selector assert_text assert_no_text ].freeze # @api private DOCUMENT_METHODS = %i[ title assert_title assert_no_title has_title? has_no_title? ].freeze SESSION_METHODS = %i[ body html source current_url current_host current_path execute_script evaluate_script evaluate_async_script visit refresh go_back go_forward send_keys within within_element within_fieldset within_table within_frame switch_to_frame current_window windows open_new_window switch_to_window within_window window_opened_by save_page save_and_open_page save_screenshot save_and_open_screenshot reset_session! response_headers status_code current_scope assert_current_path assert_no_current_path has_current_path? has_no_current_path? ].freeze + DOCUMENT_METHODS MODAL_METHODS = %i[ accept_alert accept_confirm dismiss_confirm accept_prompt dismiss_prompt ].freeze DSL_METHODS = NODE_METHODS + SESSION_METHODS + MODAL_METHODS attr_reader :mode, :app, :server attr_accessor :synchronized def initialize(mode, app = nil) if app && !app.respond_to?(:call) raise TypeError, 'The second parameter to Session::new should be a rack app if passed.' end @@instance_created = true # rubocop:disable Style/ClassVars @mode = mode @app = app if block_given? raise 'A configuration block is only accepted when Capybara.threadsafe == true' unless Capybara.threadsafe yield config end @server = if config.run_server && @app && driver.needs_server? server_options = { port: config.server_port, host: config.server_host, reportable_errors: config.server_errors } server_options[:extra_middleware] = [Capybara::Server::AnimationDisabler] if config.disable_animation Capybara::Server.new(@app, **server_options).boot end @touched = false end def driver @driver ||= begin unless Capybara.drivers[mode] other_drivers = Capybara.drivers.names.map(&:inspect) raise Capybara::DriverNotFoundError, "no driver called #{mode.inspect} was found, available drivers: #{other_drivers.join(', ')}" end driver = Capybara.drivers[mode].call(app) driver.session = self if driver.respond_to?(:session=) driver end end ## # # Reset the session (i.e. remove cookies and navigate to blank page). # # This method does not: # # * accept modal dialogs if they are present (Selenium driver now does, others may not) # * clear browser cache/HTML 5 local storage/IndexedDB/Web SQL database/etc. # * modify state of the driver/underlying browser in any other way # # as doing so will result in performance downsides and it's not needed to do everything from the list above for most apps. # # If you want to do anything from the list above on a general basis you can: # # * write RSpec/Cucumber/etc. after hook # * monkeypatch this method # * use Ruby's `prepend` method # def reset! if @touched driver.reset! @touched = false switch_to_frame(:top) rescue nil # rubocop:disable Style/RescueModifier @scopes = [nil] end @server&.wait_for_pending_requests raise_server_error! end alias_method :cleanup!, :reset! alias_method :reset_session!, :reset! ## # # Disconnect from the current driver. A new driver will be instantiated on the next interaction. # def quit @driver.quit if @driver.respond_to? :quit @document = @driver = nil @touched = false @server&.reset_error! end ## # # Raise errors encountered in the server. # def raise_server_error! return unless @server&.error # Force an explanation for the error being raised as the exception cause begin if config.raise_server_errors raise CapybaraError, 'Your application server raised an error - It has been raised in your test code because Capybara.raise_server_errors == true' end rescue CapybaraError => capy_error # rubocop:disable Naming/RescuedExceptionsVariableName raise @server.error, cause: capy_error ensure @server.reset_error! end end ## # # Returns a hash of response headers. Not supported by all drivers (e.g. Selenium). # # @return [Hash<String, String>] A hash of response headers. # def response_headers driver.response_headers end ## # # Returns the current HTTP status code as an integer. Not supported by all drivers (e.g. Selenium). # # @return [Integer] Current HTTP status code # def status_code driver.status_code end ## # # @return [String] A snapshot of the DOM of the current document, as it looks right now (potentially modified by JavaScript). # def html driver.html || '' end alias_method :body, :html alias_method :source, :html ## # # @return [String] Path of the current page, without any domain information # def current_path # Addressable parsing is more lenient than URI uri = ::Addressable::URI.parse(current_url) # Addressable doesn't support opaque URIs - we want nil here return nil if uri&.scheme == 'about' path = uri&.path path unless path&.empty? end ## # # @return [String] Host of the current page # def current_host uri = URI.parse(current_url) "#{uri.scheme}://#{uri.host}" if uri.host end ## # # @return [String] Fully qualified URL of the current page # def current_url driver.current_url end ## # # Navigate to the given URL. The URL can either be a relative URL or an absolute URL # The behaviour of either depends on the driver. # # session.visit('/foo') # session.visit('http://google.com') # # For drivers which can run against an external application, such as the selenium driver # giving an absolute URL will navigate to that page. This allows testing applications # running on remote servers. For these drivers, setting {Capybara.configure app_host} will make the # remote server the default. For example: # # Capybara.app_host = 'http://google.com' # session.visit('/') # visits the google homepage # # If {Capybara.configure always_include_port} is set to `true` and this session is running against # a rack application, then the port that the rack application is running on will automatically # be inserted into the URL. Supposing the app is running on port `4567`, doing something like: # # visit("http://google.com/test") # # Will actually navigate to `http://google.com:4567/test`. # # @param [#to_s] visit_uri The URL to navigate to. The parameter will be cast to a String. # def visit(visit_uri) raise_server_error! @touched = true visit_uri = ::Addressable::URI.parse(visit_uri.to_s) base_uri = ::Addressable::URI.parse(config.app_host || server_url) if base_uri && [nil, 'http', 'https'].include?(visit_uri.scheme) if visit_uri.relative? visit_uri_parts = visit_uri.to_hash.compact # Useful to people deploying to a subdirectory # and/or single page apps where only the url fragment changes visit_uri_parts[:path] = base_uri.path + visit_uri.path visit_uri = base_uri.merge(visit_uri_parts) end adjust_server_port(visit_uri) end driver.visit(visit_uri.to_s) end ## # # Refresh the page. # def refresh raise_server_error! driver.refresh end ## # # Move back a single entry in the browser's history. # def go_back driver.go_back end ## # # Move forward a single entry in the browser's history. # def go_forward driver.go_forward end ## # @!method send_keys # @see Capybara::Node::Element#send_keys # def send_keys(...) driver.send_keys(...) end ## # # Returns the element with focus. # # Not supported by Rack Test # def active_element Capybara::Queries::ActiveElementQuery.new.resolve_for(self)[0].tap(&:allow_reload!) end ## # # Executes the given block within the context of a node. {#within} takes the # same options as {Capybara::Node::Finders#find #find}, as well as a block. For the duration of the # block, any command to Capybara will be handled as though it were scoped # to the given element. # # within(:xpath, './/div[@id="delivery-address"]') do # fill_in('Street', with: '12 Main Street') # end # # Just as with `#find`, if multiple elements match the selector given to # {#within}, an error will be raised, and just as with `#find`, this # behaviour can be controlled through the `:match` and `:exact` options. # # It is possible to omit the first parameter, in that case, the selector is # assumed to be of the type set in {Capybara.configure default_selector}. # # within('div#delivery-address') do # fill_in('Street', with: '12 Main Street') # end # # Note that a lot of uses of {#within} can be replaced more succinctly with # chaining: # # find('div#delivery-address').fill_in('Street', with: '12 Main Street') # # @overload within(*find_args) # @param (see Capybara::Node::Finders#all) # # @overload within(a_node) # @param [Capybara::Node::Base] a_node The node in whose scope the block should be evaluated # # @raise [Capybara::ElementNotFound] If the scope can't be found before time expires # def within(*args, **kw_args) new_scope = args.first.respond_to?(:to_capybara_node) ? args.first.to_capybara_node : find(*args, **kw_args) begin scopes.push(new_scope) yield new_scope if block_given? ensure scopes.pop end end alias_method :within_element, :within ## # # Execute the given block within the a specific fieldset given the id or legend of that fieldset. # # @param [String] locator Id or legend of the fieldset # def within_fieldset(locator, &block) within(:fieldset, locator, &block) end ## # # Execute the given block within the a specific table given the id or caption of that table. # # @param [String] locator Id or caption of the table # def within_table(locator, &block) within(:table, locator, &block) end ## # # Switch to the given frame. # # If you use this method you are responsible for making sure you switch back to the parent frame when done in the frame changed to. # {#within_frame} is preferred over this method and should be used when possible. # May not be supported by all drivers. # # @overload switch_to_frame(element) # @param [Capybara::Node::Element] element iframe/frame element to switch to # @overload switch_to_frame(location) # @param [Symbol] location relative location of the frame to switch to # * :parent - the parent frame # * :top - the top level document # def switch_to_frame(frame) case frame when Capybara::Node::Element driver.switch_to_frame(frame) scopes.push(:frame) when :parent if scopes.last != :frame raise Capybara::ScopeError, "`switch_to_frame(:parent)` cannot be called from inside a descendant frame's " \ '`within` block.' end scopes.pop driver.switch_to_frame(:parent) when :top idx = scopes.index(:frame) top_level_scopes = [:frame, nil] if idx if scopes.slice(idx..).any? { |scope| !top_level_scopes.include?(scope) } raise Capybara::ScopeError, "`switch_to_frame(:top)` cannot be called from inside a descendant frame's " \ '`within` block.' end scopes.slice!(idx..) driver.switch_to_frame(:top) end else raise ArgumentError, 'You must provide a frame element, :parent, or :top when calling switch_to_frame' end end ## # # Execute the given block within the given iframe using given frame, frame name/id or index. # May not be supported by all drivers. # # @overload within_frame(element) # @param [Capybara::Node::Element] frame element # @overload within_frame([kind = :frame], locator, **options) # @param [Symbol] kind Optional selector type (:frame, :css, :xpath, etc.) - Defaults to :frame # @param [String] locator The locator for the given selector kind. For :frame this is the name/id of a frame/iframe element # @overload within_frame(index) # @param [Integer] index index of a frame (0 based) def within_frame(*args, **kw_args) switch_to_frame(_find_frame(*args, **kw_args)) begin yield if block_given? ensure switch_to_frame(:parent) end end ## # @return [Capybara::Window] current window # def current_window Window.new(self, driver.current_window_handle) end ## # Get all opened windows. # The order of windows in returned array is not defined. # The driver may sort windows by their creation time but it's not required. # # @return [Array<Capybara::Window>] an array of all windows # def windows driver.window_handles.map do |handle| Window.new(self, handle) end end ## # Open a new window. # The current window doesn't change as the result of this call. # It should be switched to explicitly. # # @return [Capybara::Window] window that has been opened # def open_new_window(kind = :tab) window_opened_by do if driver.method(:open_new_window).arity.zero? driver.open_new_window else driver.open_new_window(kind) end end end ## # Switch to the given window. # # @overload switch_to_window(&block) # Switches to the first window for which given block returns a value other than false or nil. # If window that matches block can't be found, the window will be switched back and {Capybara::WindowError} will be raised. # @example # window = switch_to_window { title == 'Page title' } # @raise [Capybara::WindowError] if no window matches given block # @overload switch_to_window(window) # @param window [Capybara::Window] window that should be switched to # @raise [Capybara::Driver::Base#no_such_window_error] if nonexistent (e.g. closed) window was passed # # @return [Capybara::Window] window that has been switched to # @raise [Capybara::ScopeError] if this method is invoked inside {#within} or # {#within_frame} methods # @raise [ArgumentError] if both or neither arguments were provided # def switch_to_window(window = nil, **options, &window_locator) raise ArgumentError, '`switch_to_window` can take either a block or a window, not both' if window && window_locator raise ArgumentError, '`switch_to_window`: either window or block should be provided' if !window && !window_locator unless scopes.last.nil? raise Capybara::ScopeError, '`switch_to_window` is not supposed to be invoked from ' \ '`within` or `within_frame` blocks.' end _switch_to_window(window, **options, &window_locator) end ## # This method does the following: # # 1. Switches to the given window (it can be located by window instance/lambda/string). # 2. Executes the given block (within window located at previous step). # 3. Switches back (this step will be invoked even if an exception occurs at the second step). # # @overload within_window(window) { do_something } # @param window [Capybara::Window] instance of {Capybara::Window} class # that will be switched to # @raise [driver#no_such_window_error] if nonexistent (e.g. closed) window was passed # @overload within_window(proc_or_lambda) { do_something } # @param lambda [Proc] First window for which lambda # returns a value other than false or nil will be switched to. # @example # within_window(->{ page.title == 'Page title' }) { click_button 'Submit' } # @raise [Capybara::WindowError] if no window matching lambda was found # # @raise [Capybara::ScopeError] if this method is invoked inside {#within_frame} method # @return value returned by the block # def within_window(window_or_proc) original = current_window scopes << nil begin case window_or_proc when Capybara::Window _switch_to_window(window_or_proc) unless original == window_or_proc when Proc _switch_to_window { window_or_proc.call } else raise ArgumentError, '`#within_window` requires a `Capybara::Window` instance or a lambda' end begin yield if block_given? ensure _switch_to_window(original) unless original == window_or_proc end ensure scopes.pop end end ## # Get the window that has been opened by the passed block. # It will wait for it to be opened (in the same way as other Capybara methods wait). # It's better to use this method than `windows.last` # {https://dvcs.w3.org/hg/webdriver/raw-file/default/webdriver-spec.html#h_note_10 as order of windows isn't defined in some drivers}. # # @overload window_opened_by(**options, &block) # @param options [Hash] # @option options [Numeric] :wait maximum wait time. Defaults to {Capybara.configure default_max_wait_time} # @return [Capybara::Window] the window that has been opened within a block # @raise [Capybara::WindowError] if block passed to window hasn't opened window # or opened more than one window # def window_opened_by(**options) old_handles = driver.window_handles yield synchronize_windows(options) do opened_handles = (driver.window_handles - old_handles) if opened_handles.size != 1 raise Capybara::WindowError, 'block passed to #window_opened_by ' \ "opened #{opened_handles.size} windows instead of 1" end Window.new(self, opened_handles.first) end end ## # # Execute the given script, not returning a result. This is useful for scripts that return # complex objects, such as jQuery statements. {#execute_script} should be used over # {#evaluate_script} whenever possible. # # @param [String] script A string of JavaScript to execute # @param args Optional arguments that will be passed to the script. Driver support for this is optional and types of objects supported may differ between drivers # def execute_script(script, *args) @touched = true driver.execute_script(script, *driver_args(args)) end ## # # Evaluate the given JavaScript and return the result. Be careful when using this with # scripts that return complex objects, such as jQuery statements. {#execute_script} might # be a better alternative. # # @param [String] script A string of JavaScript to evaluate # @param args Optional arguments that will be passed to the script # @return [Object] The result of the evaluated JavaScript (may be driver specific) # def evaluate_script(script, *args) @touched = true result = driver.evaluate_script(script.strip, *driver_args(args)) element_script_result(result) end ## # # Evaluate the given JavaScript and obtain the result from a callback function which will be passed as the last argument to the script. # # @param [String] script A string of JavaScript to evaluate # @param args Optional arguments that will be passed to the script # @return [Object] The result of the evaluated JavaScript (may be driver specific) # def evaluate_async_script(script, *args) @touched = true result = driver.evaluate_async_script(script, *driver_args(args)) element_script_result(result) end ## # # Execute the block, accepting a alert. # # @!macro modal_params # Expects a block whose actions will trigger the display modal to appear. # @example # $0 do # click_link('link that triggers appearance of system modal') # end # @overload $0(text, **options, &blk) # @param text [String, Regexp] Text or regex to match against the text in the modal. If not provided any modal is matched. # @option options [Numeric] :wait Maximum time to wait for the modal to appear after executing the block. Defaults to {Capybara.configure default_max_wait_time}. # @yield Block whose actions will trigger the system modal # @overload $0(**options, &blk) # @option options [Numeric] :wait Maximum time to wait for the modal to appear after executing the block. Defaults to {Capybara.configure default_max_wait_time}. # @yield Block whose actions will trigger the system modal # @return [String] the message shown in the modal # @raise [Capybara::ModalNotFound] if modal dialog hasn't been found # def accept_alert(text = nil, **options, &blk) accept_modal(:alert, text, options, &blk) end ## # # Execute the block, accepting a confirm. # # @macro modal_params # def accept_confirm(text = nil, **options, &blk) accept_modal(:confirm, text, options, &blk) end ## # # Execute the block, dismissing a confirm. # # @macro modal_params # def dismiss_confirm(text = nil, **options, &blk) dismiss_modal(:confirm, text, options, &blk) end ## # # Execute the block, accepting a prompt, optionally responding to the prompt. # # @macro modal_params # @option options [String] :with Response to provide to the prompt # def accept_prompt(text = nil, **options, &blk) accept_modal(:prompt, text, options, &blk) end ## # # Execute the block, dismissing a prompt. # # @macro modal_params # def dismiss_prompt(text = nil, **options, &blk) dismiss_modal(:prompt, text, options, &blk) end ## # # Save a snapshot of the page. If {Capybara.configure asset_host} is set it will inject `base` tag # pointing to {Capybara.configure asset_host}. # # If invoked without arguments it will save file to {Capybara.configure save_path} # and file will be given randomly generated filename. If invoked with a relative path # the path will be relative to {Capybara.configure save_path}. # # @param [String] path the path to where it should be saved # @return [String] the path to which the file was saved # def save_page(path = nil) prepare_path(path, 'html').tap do |p_path| File.write(p_path, Capybara::Helpers.inject_asset_host(body, host: config.asset_host), mode: 'wb') end end ## # # Save a snapshot of the page and open it in a browser for inspection. # # If invoked without arguments it will save file to {Capybara.configure save_path} # and file will be given randomly generated filename. If invoked with a relative path # the path will be relative to {Capybara.configure save_path}. # # @param [String] path the path to where it should be saved # def save_and_open_page(path = nil) save_page(path).tap { |s_path| open_file(s_path) } end ## # # Save a screenshot of page. # # If invoked without arguments it will save file to {Capybara.configure save_path} # and file will be given randomly generated filename. If invoked with a relative path # the path will be relative to {Capybara.configure save_path}. # # @param [String] path the path to where it should be saved # @param [Hash] options a customizable set of options # @return [String] the path to which the file was saved def save_screenshot(path = nil, **options) prepare_path(path, 'png').tap { |p_path| driver.save_screenshot(p_path, **options) } end ## # # Save a screenshot of the page and open it for inspection. # # If invoked without arguments it will save file to {Capybara.configure save_path} # and file will be given randomly generated filename. If invoked with a relative path # the path will be relative to {Capybara.configure save_path}. # # @param [String] path the path to where it should be saved # @param [Hash] options a customizable set of options # def save_and_open_screenshot(path = nil, **options) save_screenshot(path, **options).tap { |s_path| open_file(s_path) } end def document @document ||= Capybara::Node::Document.new(self, driver) end NODE_METHODS.each do |method| class_eval <<~METHOD, __FILE__, __LINE__ + 1 def #{method}(...) @touched = true current_scope.#{method}(...) end METHOD end DOCUMENT_METHODS.each do |method| class_eval <<~METHOD, __FILE__, __LINE__ + 1 def #{method}(...) document.#{method}(...) end METHOD end def inspect %(#<Capybara::Session>) end def current_scope scope = scopes.last [nil, :frame].include?(scope) ? document : scope end ## # # Yield a block using a specific maximum wait time. # def using_wait_time(seconds, &block) if Capybara.threadsafe begin previous_wait_time = config.default_max_wait_time config.default_max_wait_time = seconds yield ensure config.default_max_wait_time = previous_wait_time end else Capybara.using_wait_time(seconds, &block) end end ## # # Accepts a block to set the configuration options if {Capybara.configure threadsafe} is `true`. Note that some options only have an effect # if set at initialization time, so look at the configuration block that can be passed to the initializer too. # def configure raise 'Session configuration is only supported when Capybara.threadsafe == true' unless Capybara.threadsafe yield config end def self.instance_created? @@instance_created end def config @config ||= if Capybara.threadsafe Capybara.session_options.dup else Capybara::ReadOnlySessionConfig.new(Capybara.session_options) end end def server_url @server&.base_url end private @@instance_created = false # rubocop:disable Style/ClassVars def driver_args(args) args.map { |arg| arg.is_a?(Capybara::Node::Element) ? arg.base : arg } end def accept_modal(type, text_or_options, options, &blk) driver.accept_modal(type, **modal_options(text_or_options, **options), &blk) end def dismiss_modal(type, text_or_options, options, &blk) driver.dismiss_modal(type, **modal_options(text_or_options, **options), &blk) end def modal_options(text = nil, **options) options[:text] ||= text unless text.nil? options[:wait] ||= config.default_max_wait_time options end def open_file(path) require 'launchy' Launchy.open(path) rescue LoadError warn "File saved to #{path}.\nPlease install the launchy gem to open the file automatically." end def prepare_path(path, extension) File.expand_path(path || default_fn(extension), config.save_path).tap do |p_path| FileUtils.mkdir_p(File.dirname(p_path)) end end def default_fn(extension) timestamp = Time.new.strftime('%Y%m%d%H%M%S') "capybara-#{timestamp}#{rand(10**10)}.#{extension}" end def scopes @scopes ||= [nil] end def element_script_result(arg) case arg when Array arg.map { |subarg| element_script_result(subarg) } when Hash arg.transform_values! { |value| element_script_result(value) } when Capybara::Driver::Node Capybara::Node::Element.new(self, arg, nil, nil) else arg end end def adjust_server_port(uri) uri.port ||= @server.port if @server && config.always_include_port end def _find_frame(*args, **kw_args) case args[0] when Capybara::Node::Element args[0] when String, nil find(:frame, *args, **kw_args) when Symbol find(*args, **kw_args) when Integer idx = args[0] all(:frame, minimum: idx + 1)[idx] else raise TypeError end end def _switch_to_window(window = nil, **options, &window_locator) raise Capybara::ScopeError, 'Window cannot be switched inside a `within_frame` block' if scopes.include?(:frame) raise Capybara::ScopeError, 'Window cannot be switched inside a `within` block' unless scopes.last.nil? if window driver.switch_to_window(window.handle) window else synchronize_windows(options) do original_window_handle = driver.current_window_handle begin _switch_to_window_by_locator(&window_locator) rescue StandardError driver.switch_to_window(original_window_handle) raise end end end end def _switch_to_window_by_locator driver.window_handles.each do |handle| driver.switch_to_window handle return Window.new(self, handle) if yield end raise Capybara::WindowError, 'Could not find a window matching block/lambda' end def synchronize_windows(options, &block) wait_time = Capybara::Queries::BaseQuery.wait(options, config.default_max_wait_time) document.synchronize(wait_time, errors: [Capybara::WindowError], &block) end end end
Ruby
{ "end_line": 812, "name": "using_wait_time", "signature": "def using_wait_time(seconds, &block)", "start_line": 800 }
{ "class_name": "Session", "class_signature": "class Session", "module": "Capybara" }
element_script_result
capybara/lib/capybara/session.rb
def element_script_result(arg) case arg when Array arg.map { |subarg| element_script_result(subarg) } when Hash arg.transform_values! { |value| element_script_result(value) } when Capybara::Driver::Node Capybara::Node::Element.new(self, arg, nil, nil) else arg end end
# frozen_string_literal: true require 'capybara/session/matchers' require 'addressable/uri' module Capybara ## # # The {Session} class represents a single user's interaction with the system. The {Session} can use # any of the underlying drivers. A session can be initialized manually like this: # # session = Capybara::Session.new(:culerity, MyRackApp) # # The application given as the second argument is optional. When running Capybara against an external # page, you might want to leave it out: # # session = Capybara::Session.new(:culerity) # session.visit('http://www.google.com') # # When {Capybara.configure threadsafe} is `true` the sessions options will be initially set to the # current values of the global options and a configuration block can be passed to the session initializer. # For available options see {Capybara::SessionConfig::OPTIONS}: # # session = Capybara::Session.new(:driver, MyRackApp) do |config| # config.app_host = "http://my_host.dev" # end # # The {Session} provides a number of methods for controlling the navigation of the page, such as {#visit}, # {#current_path}, and so on. It also delegates a number of methods to a {Capybara::Document}, representing # the current HTML document. This allows interaction: # # session.fill_in('q', with: 'Capybara') # session.click_button('Search') # expect(session).to have_content('Capybara') # # When using `capybara/dsl`, the {Session} is initialized automatically for you. # class Session include Capybara::SessionMatchers NODE_METHODS = %i[ all first attach_file text check choose scroll_to scroll_by click double_click right_click click_link_or_button click_button click_link fill_in find find_all find_button find_by_id find_field find_link has_content? has_text? has_css? has_no_content? has_no_text? has_no_css? has_no_xpath? has_xpath? select uncheck has_element? has_no_element? has_link? has_no_link? has_button? has_no_button? has_field? has_no_field? has_checked_field? has_unchecked_field? has_no_table? has_table? unselect has_select? has_no_select? has_selector? has_no_selector? click_on has_no_checked_field? has_no_unchecked_field? query assert_selector assert_no_selector assert_all_of_selectors assert_none_of_selectors assert_any_of_selectors refute_selector assert_text assert_no_text ].freeze # @api private DOCUMENT_METHODS = %i[ title assert_title assert_no_title has_title? has_no_title? ].freeze SESSION_METHODS = %i[ body html source current_url current_host current_path execute_script evaluate_script evaluate_async_script visit refresh go_back go_forward send_keys within within_element within_fieldset within_table within_frame switch_to_frame current_window windows open_new_window switch_to_window within_window window_opened_by save_page save_and_open_page save_screenshot save_and_open_screenshot reset_session! response_headers status_code current_scope assert_current_path assert_no_current_path has_current_path? has_no_current_path? ].freeze + DOCUMENT_METHODS MODAL_METHODS = %i[ accept_alert accept_confirm dismiss_confirm accept_prompt dismiss_prompt ].freeze DSL_METHODS = NODE_METHODS + SESSION_METHODS + MODAL_METHODS attr_reader :mode, :app, :server attr_accessor :synchronized def initialize(mode, app = nil) if app && !app.respond_to?(:call) raise TypeError, 'The second parameter to Session::new should be a rack app if passed.' end @@instance_created = true # rubocop:disable Style/ClassVars @mode = mode @app = app if block_given? raise 'A configuration block is only accepted when Capybara.threadsafe == true' unless Capybara.threadsafe yield config end @server = if config.run_server && @app && driver.needs_server? server_options = { port: config.server_port, host: config.server_host, reportable_errors: config.server_errors } server_options[:extra_middleware] = [Capybara::Server::AnimationDisabler] if config.disable_animation Capybara::Server.new(@app, **server_options).boot end @touched = false end def driver @driver ||= begin unless Capybara.drivers[mode] other_drivers = Capybara.drivers.names.map(&:inspect) raise Capybara::DriverNotFoundError, "no driver called #{mode.inspect} was found, available drivers: #{other_drivers.join(', ')}" end driver = Capybara.drivers[mode].call(app) driver.session = self if driver.respond_to?(:session=) driver end end ## # # Reset the session (i.e. remove cookies and navigate to blank page). # # This method does not: # # * accept modal dialogs if they are present (Selenium driver now does, others may not) # * clear browser cache/HTML 5 local storage/IndexedDB/Web SQL database/etc. # * modify state of the driver/underlying browser in any other way # # as doing so will result in performance downsides and it's not needed to do everything from the list above for most apps. # # If you want to do anything from the list above on a general basis you can: # # * write RSpec/Cucumber/etc. after hook # * monkeypatch this method # * use Ruby's `prepend` method # def reset! if @touched driver.reset! @touched = false switch_to_frame(:top) rescue nil # rubocop:disable Style/RescueModifier @scopes = [nil] end @server&.wait_for_pending_requests raise_server_error! end alias_method :cleanup!, :reset! alias_method :reset_session!, :reset! ## # # Disconnect from the current driver. A new driver will be instantiated on the next interaction. # def quit @driver.quit if @driver.respond_to? :quit @document = @driver = nil @touched = false @server&.reset_error! end ## # # Raise errors encountered in the server. # def raise_server_error! return unless @server&.error # Force an explanation for the error being raised as the exception cause begin if config.raise_server_errors raise CapybaraError, 'Your application server raised an error - It has been raised in your test code because Capybara.raise_server_errors == true' end rescue CapybaraError => capy_error # rubocop:disable Naming/RescuedExceptionsVariableName raise @server.error, cause: capy_error ensure @server.reset_error! end end ## # # Returns a hash of response headers. Not supported by all drivers (e.g. Selenium). # # @return [Hash<String, String>] A hash of response headers. # def response_headers driver.response_headers end ## # # Returns the current HTTP status code as an integer. Not supported by all drivers (e.g. Selenium). # # @return [Integer] Current HTTP status code # def status_code driver.status_code end ## # # @return [String] A snapshot of the DOM of the current document, as it looks right now (potentially modified by JavaScript). # def html driver.html || '' end alias_method :body, :html alias_method :source, :html ## # # @return [String] Path of the current page, without any domain information # def current_path # Addressable parsing is more lenient than URI uri = ::Addressable::URI.parse(current_url) # Addressable doesn't support opaque URIs - we want nil here return nil if uri&.scheme == 'about' path = uri&.path path unless path&.empty? end ## # # @return [String] Host of the current page # def current_host uri = URI.parse(current_url) "#{uri.scheme}://#{uri.host}" if uri.host end ## # # @return [String] Fully qualified URL of the current page # def current_url driver.current_url end ## # # Navigate to the given URL. The URL can either be a relative URL or an absolute URL # The behaviour of either depends on the driver. # # session.visit('/foo') # session.visit('http://google.com') # # For drivers which can run against an external application, such as the selenium driver # giving an absolute URL will navigate to that page. This allows testing applications # running on remote servers. For these drivers, setting {Capybara.configure app_host} will make the # remote server the default. For example: # # Capybara.app_host = 'http://google.com' # session.visit('/') # visits the google homepage # # If {Capybara.configure always_include_port} is set to `true` and this session is running against # a rack application, then the port that the rack application is running on will automatically # be inserted into the URL. Supposing the app is running on port `4567`, doing something like: # # visit("http://google.com/test") # # Will actually navigate to `http://google.com:4567/test`. # # @param [#to_s] visit_uri The URL to navigate to. The parameter will be cast to a String. # def visit(visit_uri) raise_server_error! @touched = true visit_uri = ::Addressable::URI.parse(visit_uri.to_s) base_uri = ::Addressable::URI.parse(config.app_host || server_url) if base_uri && [nil, 'http', 'https'].include?(visit_uri.scheme) if visit_uri.relative? visit_uri_parts = visit_uri.to_hash.compact # Useful to people deploying to a subdirectory # and/or single page apps where only the url fragment changes visit_uri_parts[:path] = base_uri.path + visit_uri.path visit_uri = base_uri.merge(visit_uri_parts) end adjust_server_port(visit_uri) end driver.visit(visit_uri.to_s) end ## # # Refresh the page. # def refresh raise_server_error! driver.refresh end ## # # Move back a single entry in the browser's history. # def go_back driver.go_back end ## # # Move forward a single entry in the browser's history. # def go_forward driver.go_forward end ## # @!method send_keys # @see Capybara::Node::Element#send_keys # def send_keys(...) driver.send_keys(...) end ## # # Returns the element with focus. # # Not supported by Rack Test # def active_element Capybara::Queries::ActiveElementQuery.new.resolve_for(self)[0].tap(&:allow_reload!) end ## # # Executes the given block within the context of a node. {#within} takes the # same options as {Capybara::Node::Finders#find #find}, as well as a block. For the duration of the # block, any command to Capybara will be handled as though it were scoped # to the given element. # # within(:xpath, './/div[@id="delivery-address"]') do # fill_in('Street', with: '12 Main Street') # end # # Just as with `#find`, if multiple elements match the selector given to # {#within}, an error will be raised, and just as with `#find`, this # behaviour can be controlled through the `:match` and `:exact` options. # # It is possible to omit the first parameter, in that case, the selector is # assumed to be of the type set in {Capybara.configure default_selector}. # # within('div#delivery-address') do # fill_in('Street', with: '12 Main Street') # end # # Note that a lot of uses of {#within} can be replaced more succinctly with # chaining: # # find('div#delivery-address').fill_in('Street', with: '12 Main Street') # # @overload within(*find_args) # @param (see Capybara::Node::Finders#all) # # @overload within(a_node) # @param [Capybara::Node::Base] a_node The node in whose scope the block should be evaluated # # @raise [Capybara::ElementNotFound] If the scope can't be found before time expires # def within(*args, **kw_args) new_scope = args.first.respond_to?(:to_capybara_node) ? args.first.to_capybara_node : find(*args, **kw_args) begin scopes.push(new_scope) yield new_scope if block_given? ensure scopes.pop end end alias_method :within_element, :within ## # # Execute the given block within the a specific fieldset given the id or legend of that fieldset. # # @param [String] locator Id or legend of the fieldset # def within_fieldset(locator, &block) within(:fieldset, locator, &block) end ## # # Execute the given block within the a specific table given the id or caption of that table. # # @param [String] locator Id or caption of the table # def within_table(locator, &block) within(:table, locator, &block) end ## # # Switch to the given frame. # # If you use this method you are responsible for making sure you switch back to the parent frame when done in the frame changed to. # {#within_frame} is preferred over this method and should be used when possible. # May not be supported by all drivers. # # @overload switch_to_frame(element) # @param [Capybara::Node::Element] element iframe/frame element to switch to # @overload switch_to_frame(location) # @param [Symbol] location relative location of the frame to switch to # * :parent - the parent frame # * :top - the top level document # def switch_to_frame(frame) case frame when Capybara::Node::Element driver.switch_to_frame(frame) scopes.push(:frame) when :parent if scopes.last != :frame raise Capybara::ScopeError, "`switch_to_frame(:parent)` cannot be called from inside a descendant frame's " \ '`within` block.' end scopes.pop driver.switch_to_frame(:parent) when :top idx = scopes.index(:frame) top_level_scopes = [:frame, nil] if idx if scopes.slice(idx..).any? { |scope| !top_level_scopes.include?(scope) } raise Capybara::ScopeError, "`switch_to_frame(:top)` cannot be called from inside a descendant frame's " \ '`within` block.' end scopes.slice!(idx..) driver.switch_to_frame(:top) end else raise ArgumentError, 'You must provide a frame element, :parent, or :top when calling switch_to_frame' end end ## # # Execute the given block within the given iframe using given frame, frame name/id or index. # May not be supported by all drivers. # # @overload within_frame(element) # @param [Capybara::Node::Element] frame element # @overload within_frame([kind = :frame], locator, **options) # @param [Symbol] kind Optional selector type (:frame, :css, :xpath, etc.) - Defaults to :frame # @param [String] locator The locator for the given selector kind. For :frame this is the name/id of a frame/iframe element # @overload within_frame(index) # @param [Integer] index index of a frame (0 based) def within_frame(*args, **kw_args) switch_to_frame(_find_frame(*args, **kw_args)) begin yield if block_given? ensure switch_to_frame(:parent) end end ## # @return [Capybara::Window] current window # def current_window Window.new(self, driver.current_window_handle) end ## # Get all opened windows. # The order of windows in returned array is not defined. # The driver may sort windows by their creation time but it's not required. # # @return [Array<Capybara::Window>] an array of all windows # def windows driver.window_handles.map do |handle| Window.new(self, handle) end end ## # Open a new window. # The current window doesn't change as the result of this call. # It should be switched to explicitly. # # @return [Capybara::Window] window that has been opened # def open_new_window(kind = :tab) window_opened_by do if driver.method(:open_new_window).arity.zero? driver.open_new_window else driver.open_new_window(kind) end end end ## # Switch to the given window. # # @overload switch_to_window(&block) # Switches to the first window for which given block returns a value other than false or nil. # If window that matches block can't be found, the window will be switched back and {Capybara::WindowError} will be raised. # @example # window = switch_to_window { title == 'Page title' } # @raise [Capybara::WindowError] if no window matches given block # @overload switch_to_window(window) # @param window [Capybara::Window] window that should be switched to # @raise [Capybara::Driver::Base#no_such_window_error] if nonexistent (e.g. closed) window was passed # # @return [Capybara::Window] window that has been switched to # @raise [Capybara::ScopeError] if this method is invoked inside {#within} or # {#within_frame} methods # @raise [ArgumentError] if both or neither arguments were provided # def switch_to_window(window = nil, **options, &window_locator) raise ArgumentError, '`switch_to_window` can take either a block or a window, not both' if window && window_locator raise ArgumentError, '`switch_to_window`: either window or block should be provided' if !window && !window_locator unless scopes.last.nil? raise Capybara::ScopeError, '`switch_to_window` is not supposed to be invoked from ' \ '`within` or `within_frame` blocks.' end _switch_to_window(window, **options, &window_locator) end ## # This method does the following: # # 1. Switches to the given window (it can be located by window instance/lambda/string). # 2. Executes the given block (within window located at previous step). # 3. Switches back (this step will be invoked even if an exception occurs at the second step). # # @overload within_window(window) { do_something } # @param window [Capybara::Window] instance of {Capybara::Window} class # that will be switched to # @raise [driver#no_such_window_error] if nonexistent (e.g. closed) window was passed # @overload within_window(proc_or_lambda) { do_something } # @param lambda [Proc] First window for which lambda # returns a value other than false or nil will be switched to. # @example # within_window(->{ page.title == 'Page title' }) { click_button 'Submit' } # @raise [Capybara::WindowError] if no window matching lambda was found # # @raise [Capybara::ScopeError] if this method is invoked inside {#within_frame} method # @return value returned by the block # def within_window(window_or_proc) original = current_window scopes << nil begin case window_or_proc when Capybara::Window _switch_to_window(window_or_proc) unless original == window_or_proc when Proc _switch_to_window { window_or_proc.call } else raise ArgumentError, '`#within_window` requires a `Capybara::Window` instance or a lambda' end begin yield if block_given? ensure _switch_to_window(original) unless original == window_or_proc end ensure scopes.pop end end ## # Get the window that has been opened by the passed block. # It will wait for it to be opened (in the same way as other Capybara methods wait). # It's better to use this method than `windows.last` # {https://dvcs.w3.org/hg/webdriver/raw-file/default/webdriver-spec.html#h_note_10 as order of windows isn't defined in some drivers}. # # @overload window_opened_by(**options, &block) # @param options [Hash] # @option options [Numeric] :wait maximum wait time. Defaults to {Capybara.configure default_max_wait_time} # @return [Capybara::Window] the window that has been opened within a block # @raise [Capybara::WindowError] if block passed to window hasn't opened window # or opened more than one window # def window_opened_by(**options) old_handles = driver.window_handles yield synchronize_windows(options) do opened_handles = (driver.window_handles - old_handles) if opened_handles.size != 1 raise Capybara::WindowError, 'block passed to #window_opened_by ' \ "opened #{opened_handles.size} windows instead of 1" end Window.new(self, opened_handles.first) end end ## # # Execute the given script, not returning a result. This is useful for scripts that return # complex objects, such as jQuery statements. {#execute_script} should be used over # {#evaluate_script} whenever possible. # # @param [String] script A string of JavaScript to execute # @param args Optional arguments that will be passed to the script. Driver support for this is optional and types of objects supported may differ between drivers # def execute_script(script, *args) @touched = true driver.execute_script(script, *driver_args(args)) end ## # # Evaluate the given JavaScript and return the result. Be careful when using this with # scripts that return complex objects, such as jQuery statements. {#execute_script} might # be a better alternative. # # @param [String] script A string of JavaScript to evaluate # @param args Optional arguments that will be passed to the script # @return [Object] The result of the evaluated JavaScript (may be driver specific) # def evaluate_script(script, *args) @touched = true result = driver.evaluate_script(script.strip, *driver_args(args)) element_script_result(result) end ## # # Evaluate the given JavaScript and obtain the result from a callback function which will be passed as the last argument to the script. # # @param [String] script A string of JavaScript to evaluate # @param args Optional arguments that will be passed to the script # @return [Object] The result of the evaluated JavaScript (may be driver specific) # def evaluate_async_script(script, *args) @touched = true result = driver.evaluate_async_script(script, *driver_args(args)) element_script_result(result) end ## # # Execute the block, accepting a alert. # # @!macro modal_params # Expects a block whose actions will trigger the display modal to appear. # @example # $0 do # click_link('link that triggers appearance of system modal') # end # @overload $0(text, **options, &blk) # @param text [String, Regexp] Text or regex to match against the text in the modal. If not provided any modal is matched. # @option options [Numeric] :wait Maximum time to wait for the modal to appear after executing the block. Defaults to {Capybara.configure default_max_wait_time}. # @yield Block whose actions will trigger the system modal # @overload $0(**options, &blk) # @option options [Numeric] :wait Maximum time to wait for the modal to appear after executing the block. Defaults to {Capybara.configure default_max_wait_time}. # @yield Block whose actions will trigger the system modal # @return [String] the message shown in the modal # @raise [Capybara::ModalNotFound] if modal dialog hasn't been found # def accept_alert(text = nil, **options, &blk) accept_modal(:alert, text, options, &blk) end ## # # Execute the block, accepting a confirm. # # @macro modal_params # def accept_confirm(text = nil, **options, &blk) accept_modal(:confirm, text, options, &blk) end ## # # Execute the block, dismissing a confirm. # # @macro modal_params # def dismiss_confirm(text = nil, **options, &blk) dismiss_modal(:confirm, text, options, &blk) end ## # # Execute the block, accepting a prompt, optionally responding to the prompt. # # @macro modal_params # @option options [String] :with Response to provide to the prompt # def accept_prompt(text = nil, **options, &blk) accept_modal(:prompt, text, options, &blk) end ## # # Execute the block, dismissing a prompt. # # @macro modal_params # def dismiss_prompt(text = nil, **options, &blk) dismiss_modal(:prompt, text, options, &blk) end ## # # Save a snapshot of the page. If {Capybara.configure asset_host} is set it will inject `base` tag # pointing to {Capybara.configure asset_host}. # # If invoked without arguments it will save file to {Capybara.configure save_path} # and file will be given randomly generated filename. If invoked with a relative path # the path will be relative to {Capybara.configure save_path}. # # @param [String] path the path to where it should be saved # @return [String] the path to which the file was saved # def save_page(path = nil) prepare_path(path, 'html').tap do |p_path| File.write(p_path, Capybara::Helpers.inject_asset_host(body, host: config.asset_host), mode: 'wb') end end ## # # Save a snapshot of the page and open it in a browser for inspection. # # If invoked without arguments it will save file to {Capybara.configure save_path} # and file will be given randomly generated filename. If invoked with a relative path # the path will be relative to {Capybara.configure save_path}. # # @param [String] path the path to where it should be saved # def save_and_open_page(path = nil) save_page(path).tap { |s_path| open_file(s_path) } end ## # # Save a screenshot of page. # # If invoked without arguments it will save file to {Capybara.configure save_path} # and file will be given randomly generated filename. If invoked with a relative path # the path will be relative to {Capybara.configure save_path}. # # @param [String] path the path to where it should be saved # @param [Hash] options a customizable set of options # @return [String] the path to which the file was saved def save_screenshot(path = nil, **options) prepare_path(path, 'png').tap { |p_path| driver.save_screenshot(p_path, **options) } end ## # # Save a screenshot of the page and open it for inspection. # # If invoked without arguments it will save file to {Capybara.configure save_path} # and file will be given randomly generated filename. If invoked with a relative path # the path will be relative to {Capybara.configure save_path}. # # @param [String] path the path to where it should be saved # @param [Hash] options a customizable set of options # def save_and_open_screenshot(path = nil, **options) save_screenshot(path, **options).tap { |s_path| open_file(s_path) } end def document @document ||= Capybara::Node::Document.new(self, driver) end NODE_METHODS.each do |method| class_eval <<~METHOD, __FILE__, __LINE__ + 1 def #{method}(...) @touched = true current_scope.#{method}(...) end METHOD end DOCUMENT_METHODS.each do |method| class_eval <<~METHOD, __FILE__, __LINE__ + 1 def #{method}(...) document.#{method}(...) end METHOD end def inspect %(#<Capybara::Session>) end def current_scope scope = scopes.last [nil, :frame].include?(scope) ? document : scope end ## # # Yield a block using a specific maximum wait time. # def using_wait_time(seconds, &block) if Capybara.threadsafe begin previous_wait_time = config.default_max_wait_time config.default_max_wait_time = seconds yield ensure config.default_max_wait_time = previous_wait_time end else Capybara.using_wait_time(seconds, &block) end end ## # # Accepts a block to set the configuration options if {Capybara.configure threadsafe} is `true`. Note that some options only have an effect # if set at initialization time, so look at the configuration block that can be passed to the initializer too. # def configure raise 'Session configuration is only supported when Capybara.threadsafe == true' unless Capybara.threadsafe yield config end def self.instance_created? @@instance_created end def config @config ||= if Capybara.threadsafe Capybara.session_options.dup else Capybara::ReadOnlySessionConfig.new(Capybara.session_options) end end def server_url @server&.base_url end private @@instance_created = false # rubocop:disable Style/ClassVars def driver_args(args) args.map { |arg| arg.is_a?(Capybara::Node::Element) ? arg.base : arg } end def accept_modal(type, text_or_options, options, &blk) driver.accept_modal(type, **modal_options(text_or_options, **options), &blk) end def dismiss_modal(type, text_or_options, options, &blk) driver.dismiss_modal(type, **modal_options(text_or_options, **options), &blk) end def modal_options(text = nil, **options) options[:text] ||= text unless text.nil? options[:wait] ||= config.default_max_wait_time options end def open_file(path) require 'launchy' Launchy.open(path) rescue LoadError warn "File saved to #{path}.\nPlease install the launchy gem to open the file automatically." end def prepare_path(path, extension) File.expand_path(path || default_fn(extension), config.save_path).tap do |p_path| FileUtils.mkdir_p(File.dirname(p_path)) end end def default_fn(extension) timestamp = Time.new.strftime('%Y%m%d%H%M%S') "capybara-#{timestamp}#{rand(10**10)}.#{extension}" end def scopes @scopes ||= [nil] end def element_script_result(arg) case arg when Array arg.map { |subarg| element_script_result(subarg) } when Hash arg.transform_values! { |value| element_script_result(value) } when Capybara::Driver::Node Capybara::Node::Element.new(self, arg, nil, nil) else arg end end def adjust_server_port(uri) uri.port ||= @server.port if @server && config.always_include_port end def _find_frame(*args, **kw_args) case args[0] when Capybara::Node::Element args[0] when String, nil find(:frame, *args, **kw_args) when Symbol find(*args, **kw_args) when Integer idx = args[0] all(:frame, minimum: idx + 1)[idx] else raise TypeError end end def _switch_to_window(window = nil, **options, &window_locator) raise Capybara::ScopeError, 'Window cannot be switched inside a `within_frame` block' if scopes.include?(:frame) raise Capybara::ScopeError, 'Window cannot be switched inside a `within` block' unless scopes.last.nil? if window driver.switch_to_window(window.handle) window else synchronize_windows(options) do original_window_handle = driver.current_window_handle begin _switch_to_window_by_locator(&window_locator) rescue StandardError driver.switch_to_window(original_window_handle) raise end end end end def _switch_to_window_by_locator driver.window_handles.each do |handle| driver.switch_to_window handle return Window.new(self, handle) if yield end raise Capybara::WindowError, 'Could not find a window matching block/lambda' end def synchronize_windows(options, &block) wait_time = Capybara::Queries::BaseQuery.wait(options, config.default_max_wait_time) document.synchronize(wait_time, errors: [Capybara::WindowError], &block) end end end
Ruby
{ "end_line": 896, "name": "element_script_result", "signature": "def element_script_result(arg)", "start_line": 885 }
{ "class_name": "Session", "class_signature": "class Session", "module": "Capybara" }
wait_for_stable_size
capybara/lib/capybara/window.rb
def wait_for_stable_size(seconds = session.config.default_max_wait_time) res = yield if block_given? timer = Capybara::Helpers.timer(expire_in: seconds) loop do prev_size = size sleep 0.025 return res if prev_size == size break if timer.expired? end raise Capybara::WindowError, "Window size not stable within #{seconds} seconds." end
# frozen_string_literal: true module Capybara ## # The {Window} class represents a browser window. # # You can get an instance of the class by calling any of: # # * {Capybara::Session#windows} # * {Capybara::Session#current_window} # * {Capybara::Session#window_opened_by} # * {Capybara::Session#switch_to_window} # # Note that some drivers (e.g. Selenium) support getting size of/resizing/closing only # current window. So if you invoke such method for: # # * window that is current, Capybara will make 2 Selenium method invocations # (get handle of current window + get size/resize/close). # * window that is not current, Capybara will make 4 Selenium method invocations # (get handle of current window + switch to given handle + get size/resize/close + switch to original handle) # class Window # @return [String] a string that uniquely identifies window within session attr_reader :handle # @return [Capybara::Session] session that this window belongs to attr_reader :session # @api private def initialize(session, handle) @session = session @driver = session.driver @handle = handle end ## # @return [Boolean] whether the window is not closed def exists? @driver.window_handles.include?(@handle) end ## # @return [Boolean] whether the window is closed def closed? !exists? end ## # @return [Boolean] whether this window is the window in which commands are being executed def current? @driver.current_window_handle == @handle rescue @driver.no_such_window_error false end ## # Close window. # # If this method was called for window that is current, then after calling this method # future invocations of other Capybara methods should raise # {Capybara::Driver::Base#no_such_window_error session.driver.no_such_window_error} until another window will be switched to. # # @!macro about_current # If this method was called for window that is not current, then after calling this method # current window should remain the same as it was before calling this method. # def close @driver.close_window(handle) end ## # Get window size. # # @macro about_current # @return [Array<(Integer, Integer)>] an array with width and height # def size @driver.window_size(handle) end ## # Resize window. # # @macro about_current # @param width [Integer] the new window width in pixels # @param height [Integer] the new window height in pixels # def resize_to(width, height) wait_for_stable_size { @driver.resize_window_to(handle, width, height) } end ## # Maximize window. # # If a particular driver (e.g. headless driver) doesn't have concept of maximizing it # may not support this method. # # @macro about_current # def maximize wait_for_stable_size { @driver.maximize_window(handle) } end ## # Fullscreen window. # # If a particular driver doesn't have concept of fullscreen it may not support this method. # # @macro about_current # def fullscreen @driver.fullscreen_window(handle) end def eql?(other) other.is_a?(self.class) && @session == other.session && @handle == other.handle end alias_method :==, :eql? def hash [@session, @handle].hash end def inspect "#<Window @handle=#{@handle.inspect}>" end private def wait_for_stable_size(seconds = session.config.default_max_wait_time) res = yield if block_given? timer = Capybara::Helpers.timer(expire_in: seconds) loop do prev_size = size sleep 0.025 return res if prev_size == size break if timer.expired? end raise Capybara::WindowError, "Window size not stable within #{seconds} seconds." end end end
Ruby
{ "end_line": 140, "name": "wait_for_stable_size", "signature": "def wait_for_stable_size(seconds = session.config.default_max_wait_time)", "start_line": 130 }
{ "class_name": "Window", "class_signature": "class Window", "module": "Capybara" }
attach_file
capybara/lib/capybara/node/actions.rb
def attach_file(locator = nil, paths, make_visible: nil, **options) # rubocop:disable Style/OptionalArguments if locator && block_given? raise ArgumentError, '`#attach_file` does not support passing both a locator and a block' end Array(paths).each do |path| raise Capybara::FileNotFound, "cannot attach file, #{path} does not exist" unless File.exist?(path.to_s) end options[:allow_self] = true if locator.nil? if block_given? begin execute_script CAPTURE_FILE_ELEMENT_SCRIPT yield file_field = evaluate_script 'window._capybara_clicked_file_input' raise ArgumentError, "Capybara was unable to determine the file input you're attaching to" unless file_field rescue ::Capybara::NotSupportedByDriverError warn 'Block mode of `#attach_file` is not supported by the current driver - ignoring.' end end # Allow user to update the CSS style of the file input since they are so often hidden on a page if make_visible ff = file_field || find(:file_field, locator, **options.merge(visible: :all)) while_visible(ff, make_visible) { |el| el.set(paths) } else (file_field || find(:file_field, locator, **options)).set(paths) end end
# frozen_string_literal: true module Capybara module Node module Actions # @!macro waiting_behavior # If the driver is capable of executing JavaScript, this method will wait for a set amount of time # and continuously retry finding the element until either the element is found or the time # expires. The length of time this method will wait is controlled through {Capybara.configure default_max_wait_time}. # # @option options [false, true, Numeric] wait # Maximum time to wait for matching element to appear. Defaults to {Capybara.configure default_max_wait_time}. ## # # Finds a button or link and clicks it. See {#click_button} and # {#click_link} for what locator will match against for each type of element. # # @overload click_link_or_button([locator], **options) # @macro waiting_behavior # @param [String] locator See {#click_button} and {#click_link} # # @return [Capybara::Node::Element] The element clicked # def click_link_or_button(locator = nil, **options) find(:link_or_button, locator, **options).click end alias_method :click_on, :click_link_or_button ## # # Finds a link by id, {Capybara.configure test_id} attribute, text or title and clicks it. Also looks at image # alt text inside the link. # # @overload click_link([locator], **options) # @macro waiting_behavior # @param [String] locator text, id, {Capybara.configure test_id} attribute, title or nested image's alt attribute # @param [Hash] options See {Capybara::Node::Finders#find_link} # # @return [Capybara::Node::Element] The element clicked def click_link(locator = nil, **options) find(:link, locator, **options).click end ## # # Finds a button on the page and clicks it. # This can be any `<input>` element of type submit, reset, image, button or it can be a # `<button>` element. All buttons can be found by their id, name, {Capybara.configure test_id} attribute, value, or title. `<button>` elements can also be found # by their text content, and image `<input>` elements by their alt attribute. # # @overload click_button([locator], **options) # @macro waiting_behavior # @param [String] locator Which button to find # @param [Hash] options See {Capybara::Node::Finders#find_button} # @return [Capybara::Node::Element] The element clicked def click_button(locator = nil, **options) find(:button, locator, **options).click end ## # # Locate a text field or text area and fill it in with the given text. # The field can be found via its name, id, {Capybara.configure test_id} attribute, placeholder, or label text. # If no locator is provided this will operate on self or a descendant. # # # will fill in a descendant fillable field with name, id, or label text matching 'Name' # page.fill_in 'Name', with: 'Bob' # # # will fill in `el` if it's a fillable field # el.fill_in with: 'Tom' # # # @overload fill_in([locator], with:, **options) # @param [String] locator Which field to fill in # @param [Hash] options # @param with: [String] The value to fill in # @macro waiting_behavior # @option options [String] currently_with The current value property of the field to fill in # @option options [Boolean] multiple Match fields that can have multiple values? # @option options [String, Regexp] id Match fields that match the id attribute # @option options [String] name Match fields that match the name attribute # @option options [String] placeholder Match fields that match the placeholder attribute # @option options [String, Array<String>, Regexp] class Match fields that match the class(es) provided # @option options [Hash] fill_options Driver specific options regarding how to fill fields (Defaults come from {Capybara.configure default_set_options}) # # @return [Capybara::Node::Element] The element filled in def fill_in(locator = nil, with:, currently_with: nil, fill_options: {}, **find_options) find_options[:with] = currently_with if currently_with find_options[:allow_self] = true if locator.nil? find(:fillable_field, locator, **find_options).set(with, **fill_options) end # @!macro label_click # @option options [Boolean, Hash] allow_label_click # Attempt to click the label to toggle state if element is non-visible. Defaults to {Capybara.configure automatic_label_click}. # If set to a Hash it is passed as options to the `click` on the label ## # # Find a descendant radio button and mark it as checked. The radio button can be found # via name, id, {Capybara.configure test_id} attribute or label text. If no locator is # provided this will match against self or a descendant. # # # will choose a descendant radio button with a name, id, or label text matching 'Male' # page.choose('Male') # # # will choose `el` if it's a radio button element # el.choose() # # @overload choose([locator], **options) # @param [String] locator Which radio button to choose # # @option options [String] option Value of the radio_button to choose # @option options [String, Regexp] id Match fields that match the id attribute # @option options [String] name Match fields that match the name attribute # @option options [String, Array<String>, Regexp] class Match fields that match the class(es) provided # @macro waiting_behavior # @macro label_click # # @return [Capybara::Node::Element] The element chosen or the label clicked def choose(locator = nil, **options) _check_with_label(:radio_button, true, locator, **options) end ## # # Find a descendant check box and mark it as checked. The check box can be found # via name, id, {Capybara.configure test_id} attribute, or label text. If no locator # is provided this will match against self or a descendant. # # # will check a descendant checkbox with a name, id, or label text matching 'German' # page.check('German') # # # will check `el` if it's a checkbox element # el.check() # # # @overload check([locator], **options) # @param [String] locator Which check box to check # # @option options [String] option Value of the checkbox to select # @option options [String, Regexp] id Match fields that match the id attribute # @option options [String] name Match fields that match the name attribute # @option options [String, Array<String>, Regexp] class Match fields that match the class(es) provided # @macro label_click # @macro waiting_behavior # # @return [Capybara::Node::Element] The element checked or the label clicked def check(locator = nil, **options) _check_with_label(:checkbox, true, locator, **options) end ## # # Find a descendant check box and uncheck it. The check box can be found # via name, id, {Capybara.configure test_id} attribute, or label text. If # no locator is provided this will match against self or a descendant. # # # will uncheck a descendant checkbox with a name, id, or label text matching 'German' # page.uncheck('German') # # # will uncheck `el` if it's a checkbox element # el.uncheck() # # # @overload uncheck([locator], **options) # @param [String] locator Which check box to uncheck # # @option options [String] option Value of the checkbox to deselect # @option options [String, Regexp] id Match fields that match the id attribute # @option options [String] name Match fields that match the name attribute # @option options [String, Array<String>, Regexp] class Match fields that match the class(es) provided # @macro label_click # @macro waiting_behavior # # @return [Capybara::Node::Element] The element unchecked or the label clicked def uncheck(locator = nil, **options) _check_with_label(:checkbox, false, locator, **options) end ## # # If `from` option is present, {#select} finds a select box, or text input with associated datalist, # on the page and selects a particular option from it. # Otherwise it finds an option inside current scope and selects it. # If the select box is a multiple select, {#select} can be called multiple times to select more than # one option. # The select box can be found via its name, id, {Capybara.configure test_id} attribute, or label text. # The option can be found by its text. # # page.select 'March', from: 'Month' # # @overload select(value = nil, from: nil, **options) # @macro waiting_behavior # # @param value [String] Which option to select # @param from [String] The id, {Capybara.configure test_id} attribute, name or label of the select box # # @return [Capybara::Node::Element] The option element selected def select(value = nil, from: nil, **options) raise ArgumentError, 'The :from option does not take an element' if from.is_a? Capybara::Node::Element el = from ? find_select_or_datalist_input(from, options) : self if el.respond_to?(:tag_name) && (el.tag_name == 'input') select_datalist_option(el, value) else el.find(:option, value, **options).select_option end end ## # # Find a select box on the page and unselect a particular option from it. If the select # box is a multiple select, {#unselect} can be called multiple times to unselect more than # one option. The select box can be found via its name, id, {Capybara.configure test_id} attribute, # or label text. # # page.unselect 'March', from: 'Month' # # @overload unselect(value = nil, from: nil, **options) # @macro waiting_behavior # # @param value [String] Which option to unselect # @param from [String] The id, {Capybara.configure test_id} attribute, name or label of the select box # # # @return [Capybara::Node::Element] The option element unselected def unselect(value = nil, from: nil, **options) raise ArgumentError, 'The :from option does not take an element' if from.is_a? Capybara::Node::Element scope = from ? find(:select, from, **options) : self scope.find(:option, value, **options).unselect_option end ## # # Find a descendant file field on the page and attach a file given its path. There are two ways to use # {#attach_file}, in the first method the file field can be found via its name, id, # {Capybara.configure test_id} attribute, or label text. In the case of the file field being hidden for # styling reasons the `make_visible` option can be used to temporarily change the CSS of # the file field, attach the file, and then revert the CSS back to original. If no locator is # passed this will match self or a descendant. # The second method, which is currently in beta and may be changed/removed, involves passing a block # which performs whatever actions would trigger the file chooser to appear. # # # will attach file to a descendant file input element that has a name, id, or label_text matching 'My File' # page.attach_file('My File', '/path/to/file.png') # # # will attach file to el if it's a file input element # el.attach_file('/path/to/file.png') # # # will attach file to whatever file input is triggered by the block # page.attach_file('/path/to/file.png') do # page.find('#upload_button').click # end # # @overload attach_file([locator], paths, **options) # @macro waiting_behavior # # @param [String] locator Which field to attach the file to # @param [String, Array<String>] paths The path(s) of the file(s) that will be attached # # @option options [Symbol] match # The matching strategy to use (:one, :first, :prefer_exact, :smart). Defaults to {Capybara.configure match}. # @option options [Boolean] exact # Match the exact label name/contents or accept a partial match. Defaults to {Capybara.configure exact}. # @option options [Boolean] multiple Match field which allows multiple file selection # @option options [String, Regexp] id Match fields that match the id attribute # @option options [String] name Match fields that match the name attribute # @option options [String, Array<String>, Regexp] class Match fields that match the class(es) provided # @option options [true, Hash] make_visible # A Hash of CSS styles to change before attempting to attach the file, if `true`, `{ opacity: 1, display: 'block', visibility: 'visible' }` is used (may not be supported by all drivers). # @overload attach_file(paths, &blk) # @param [String, Array<String>] paths The path(s) of the file(s) that will be attached # @yield Block whose actions will trigger the system file chooser to be shown # @return [Capybara::Node::Element] The file field element def attach_file(locator = nil, paths, make_visible: nil, **options) # rubocop:disable Style/OptionalArguments if locator && block_given? raise ArgumentError, '`#attach_file` does not support passing both a locator and a block' end Array(paths).each do |path| raise Capybara::FileNotFound, "cannot attach file, #{path} does not exist" unless File.exist?(path.to_s) end options[:allow_self] = true if locator.nil? if block_given? begin execute_script CAPTURE_FILE_ELEMENT_SCRIPT yield file_field = evaluate_script 'window._capybara_clicked_file_input' raise ArgumentError, "Capybara was unable to determine the file input you're attaching to" unless file_field rescue ::Capybara::NotSupportedByDriverError warn 'Block mode of `#attach_file` is not supported by the current driver - ignoring.' end end # Allow user to update the CSS style of the file input since they are so often hidden on a page if make_visible ff = file_field || find(:file_field, locator, **options.merge(visible: :all)) while_visible(ff, make_visible) { |el| el.set(paths) } else (file_field || find(:file_field, locator, **options)).set(paths) end end private def find_select_or_datalist_input(from, options) synchronize(Capybara::Queries::BaseQuery.wait(options, session_options.default_max_wait_time)) do find(:select, from, **options) rescue Capybara::ElementNotFound => select_error # rubocop:disable Naming/RescuedExceptionsVariableName raise if %i[selected with_selected multiple].any? { |option| options.key?(option) } begin find(:datalist_input, from, **options) rescue Capybara::ElementNotFound => dlinput_error raise Capybara::ElementNotFound, "#{select_error.message} and #{dlinput_error.message}" end end end def select_datalist_option(input, value) datalist_options = input.evaluate_script(DATALIST_OPTIONS_SCRIPT) option = datalist_options.find { |opt| opt.values_at('value', 'label').include?(value) } raise ::Capybara::ElementNotFound, %(Unable to find datalist option "#{value}") unless option input.set(option['value']) rescue ::Capybara::NotSupportedByDriverError # Implement for drivers that don't support JS datalist = find(:xpath, XPath.descendant(:datalist)[XPath.attr(:id) == input[:list]], visible: false) option = datalist.find(:datalist_option, value, disabled: false) input.set(option.value) end def while_visible(element, visible_css) if visible_css == true visible_css = { opacity: 1, display: 'block', visibility: 'visible', width: 'auto', height: 'auto' } end _update_style(element, visible_css) unless element.visible? raise ExpectationNotMet, 'The style changes in :make_visible did not make the file input visible' end begin yield element ensure _reset_style(element) end end def _update_style(element, style) element.execute_script(UPDATE_STYLE_SCRIPT, style) rescue Capybara::NotSupportedByDriverError warn 'The :make_visible option is not supported by the current driver - ignoring' end def _reset_style(element) element.execute_script(RESET_STYLE_SCRIPT) rescue StandardError # rubocop:disable Lint/SuppressedException -- swallow extra errors end def _check_with_label(selector, checked, locator, allow_label_click: session_options.automatic_label_click, **options) options[:allow_self] = true if locator.nil? synchronize(Capybara::Queries::BaseQuery.wait(options, session_options.default_max_wait_time)) do el = find(selector, locator, **options) el.set(checked) rescue StandardError => e raise unless allow_label_click && catch_error?(e) begin el ||= find(selector, locator, **options.merge(visible: :all)) unless el.checked? == checked el.session .find(:label, for: el, visible: true, match: :first) .click(**(Hash.try_convert(allow_label_click) || {})) end rescue StandardError # swallow extra errors - raise original raise e end end end UPDATE_STYLE_SCRIPT = <<~JS this.capybara_style_cache = this.style.cssText; var css = arguments[0]; for (var prop in css){ if (css.hasOwnProperty(prop)) { this.style.setProperty(prop, css[prop], "important"); } } JS RESET_STYLE_SCRIPT = <<~JS if (this.hasOwnProperty('capybara_style_cache')) { this.style.cssText = this.capybara_style_cache; delete this.capybara_style_cache; } JS DATALIST_OPTIONS_SCRIPT = <<~JS Array.prototype.slice.call((this.list||{}).options || []). filter(function(el){ return !el.disabled }). map(function(el){ return { "value": el.value, "label": el.label} }) JS CAPTURE_FILE_ELEMENT_SCRIPT = <<~JS document.addEventListener('click', function file_catcher(e){ if (e.target.matches("input[type='file']")) { window._capybara_clicked_file_input = e.target; this.removeEventListener('click', file_catcher); e.preventDefault(); } }, {capture: true}) JS end end end
Ruby
{ "end_line": 306, "name": "attach_file", "signature": "def attach_file(locator = nil, paths, make_visible: nil, **options) # rubocop:disable Style/OptionalArguments", "start_line": 279 }
{ "class_name": "", "class_signature": "", "module": "Capybara" }
find_select_or_datalist_input
capybara/lib/capybara/node/actions.rb
def find_select_or_datalist_input(from, options) synchronize(Capybara::Queries::BaseQuery.wait(options, session_options.default_max_wait_time)) do find(:select, from, **options) rescue Capybara::ElementNotFound => select_error # rubocop:disable Naming/RescuedExceptionsVariableName raise if %i[selected with_selected multiple].any? { |option| options.key?(option) } begin find(:datalist_input, from, **options) rescue Capybara::ElementNotFound => dlinput_error raise Capybara::ElementNotFound, "#{select_error.message} and #{dlinput_error.message}" end end end
# frozen_string_literal: true module Capybara module Node module Actions # @!macro waiting_behavior # If the driver is capable of executing JavaScript, this method will wait for a set amount of time # and continuously retry finding the element until either the element is found or the time # expires. The length of time this method will wait is controlled through {Capybara.configure default_max_wait_time}. # # @option options [false, true, Numeric] wait # Maximum time to wait for matching element to appear. Defaults to {Capybara.configure default_max_wait_time}. ## # # Finds a button or link and clicks it. See {#click_button} and # {#click_link} for what locator will match against for each type of element. # # @overload click_link_or_button([locator], **options) # @macro waiting_behavior # @param [String] locator See {#click_button} and {#click_link} # # @return [Capybara::Node::Element] The element clicked # def click_link_or_button(locator = nil, **options) find(:link_or_button, locator, **options).click end alias_method :click_on, :click_link_or_button ## # # Finds a link by id, {Capybara.configure test_id} attribute, text or title and clicks it. Also looks at image # alt text inside the link. # # @overload click_link([locator], **options) # @macro waiting_behavior # @param [String] locator text, id, {Capybara.configure test_id} attribute, title or nested image's alt attribute # @param [Hash] options See {Capybara::Node::Finders#find_link} # # @return [Capybara::Node::Element] The element clicked def click_link(locator = nil, **options) find(:link, locator, **options).click end ## # # Finds a button on the page and clicks it. # This can be any `<input>` element of type submit, reset, image, button or it can be a # `<button>` element. All buttons can be found by their id, name, {Capybara.configure test_id} attribute, value, or title. `<button>` elements can also be found # by their text content, and image `<input>` elements by their alt attribute. # # @overload click_button([locator], **options) # @macro waiting_behavior # @param [String] locator Which button to find # @param [Hash] options See {Capybara::Node::Finders#find_button} # @return [Capybara::Node::Element] The element clicked def click_button(locator = nil, **options) find(:button, locator, **options).click end ## # # Locate a text field or text area and fill it in with the given text. # The field can be found via its name, id, {Capybara.configure test_id} attribute, placeholder, or label text. # If no locator is provided this will operate on self or a descendant. # # # will fill in a descendant fillable field with name, id, or label text matching 'Name' # page.fill_in 'Name', with: 'Bob' # # # will fill in `el` if it's a fillable field # el.fill_in with: 'Tom' # # # @overload fill_in([locator], with:, **options) # @param [String] locator Which field to fill in # @param [Hash] options # @param with: [String] The value to fill in # @macro waiting_behavior # @option options [String] currently_with The current value property of the field to fill in # @option options [Boolean] multiple Match fields that can have multiple values? # @option options [String, Regexp] id Match fields that match the id attribute # @option options [String] name Match fields that match the name attribute # @option options [String] placeholder Match fields that match the placeholder attribute # @option options [String, Array<String>, Regexp] class Match fields that match the class(es) provided # @option options [Hash] fill_options Driver specific options regarding how to fill fields (Defaults come from {Capybara.configure default_set_options}) # # @return [Capybara::Node::Element] The element filled in def fill_in(locator = nil, with:, currently_with: nil, fill_options: {}, **find_options) find_options[:with] = currently_with if currently_with find_options[:allow_self] = true if locator.nil? find(:fillable_field, locator, **find_options).set(with, **fill_options) end # @!macro label_click # @option options [Boolean, Hash] allow_label_click # Attempt to click the label to toggle state if element is non-visible. Defaults to {Capybara.configure automatic_label_click}. # If set to a Hash it is passed as options to the `click` on the label ## # # Find a descendant radio button and mark it as checked. The radio button can be found # via name, id, {Capybara.configure test_id} attribute or label text. If no locator is # provided this will match against self or a descendant. # # # will choose a descendant radio button with a name, id, or label text matching 'Male' # page.choose('Male') # # # will choose `el` if it's a radio button element # el.choose() # # @overload choose([locator], **options) # @param [String] locator Which radio button to choose # # @option options [String] option Value of the radio_button to choose # @option options [String, Regexp] id Match fields that match the id attribute # @option options [String] name Match fields that match the name attribute # @option options [String, Array<String>, Regexp] class Match fields that match the class(es) provided # @macro waiting_behavior # @macro label_click # # @return [Capybara::Node::Element] The element chosen or the label clicked def choose(locator = nil, **options) _check_with_label(:radio_button, true, locator, **options) end ## # # Find a descendant check box and mark it as checked. The check box can be found # via name, id, {Capybara.configure test_id} attribute, or label text. If no locator # is provided this will match against self or a descendant. # # # will check a descendant checkbox with a name, id, or label text matching 'German' # page.check('German') # # # will check `el` if it's a checkbox element # el.check() # # # @overload check([locator], **options) # @param [String] locator Which check box to check # # @option options [String] option Value of the checkbox to select # @option options [String, Regexp] id Match fields that match the id attribute # @option options [String] name Match fields that match the name attribute # @option options [String, Array<String>, Regexp] class Match fields that match the class(es) provided # @macro label_click # @macro waiting_behavior # # @return [Capybara::Node::Element] The element checked or the label clicked def check(locator = nil, **options) _check_with_label(:checkbox, true, locator, **options) end ## # # Find a descendant check box and uncheck it. The check box can be found # via name, id, {Capybara.configure test_id} attribute, or label text. If # no locator is provided this will match against self or a descendant. # # # will uncheck a descendant checkbox with a name, id, or label text matching 'German' # page.uncheck('German') # # # will uncheck `el` if it's a checkbox element # el.uncheck() # # # @overload uncheck([locator], **options) # @param [String] locator Which check box to uncheck # # @option options [String] option Value of the checkbox to deselect # @option options [String, Regexp] id Match fields that match the id attribute # @option options [String] name Match fields that match the name attribute # @option options [String, Array<String>, Regexp] class Match fields that match the class(es) provided # @macro label_click # @macro waiting_behavior # # @return [Capybara::Node::Element] The element unchecked or the label clicked def uncheck(locator = nil, **options) _check_with_label(:checkbox, false, locator, **options) end ## # # If `from` option is present, {#select} finds a select box, or text input with associated datalist, # on the page and selects a particular option from it. # Otherwise it finds an option inside current scope and selects it. # If the select box is a multiple select, {#select} can be called multiple times to select more than # one option. # The select box can be found via its name, id, {Capybara.configure test_id} attribute, or label text. # The option can be found by its text. # # page.select 'March', from: 'Month' # # @overload select(value = nil, from: nil, **options) # @macro waiting_behavior # # @param value [String] Which option to select # @param from [String] The id, {Capybara.configure test_id} attribute, name or label of the select box # # @return [Capybara::Node::Element] The option element selected def select(value = nil, from: nil, **options) raise ArgumentError, 'The :from option does not take an element' if from.is_a? Capybara::Node::Element el = from ? find_select_or_datalist_input(from, options) : self if el.respond_to?(:tag_name) && (el.tag_name == 'input') select_datalist_option(el, value) else el.find(:option, value, **options).select_option end end ## # # Find a select box on the page and unselect a particular option from it. If the select # box is a multiple select, {#unselect} can be called multiple times to unselect more than # one option. The select box can be found via its name, id, {Capybara.configure test_id} attribute, # or label text. # # page.unselect 'March', from: 'Month' # # @overload unselect(value = nil, from: nil, **options) # @macro waiting_behavior # # @param value [String] Which option to unselect # @param from [String] The id, {Capybara.configure test_id} attribute, name or label of the select box # # # @return [Capybara::Node::Element] The option element unselected def unselect(value = nil, from: nil, **options) raise ArgumentError, 'The :from option does not take an element' if from.is_a? Capybara::Node::Element scope = from ? find(:select, from, **options) : self scope.find(:option, value, **options).unselect_option end ## # # Find a descendant file field on the page and attach a file given its path. There are two ways to use # {#attach_file}, in the first method the file field can be found via its name, id, # {Capybara.configure test_id} attribute, or label text. In the case of the file field being hidden for # styling reasons the `make_visible` option can be used to temporarily change the CSS of # the file field, attach the file, and then revert the CSS back to original. If no locator is # passed this will match self or a descendant. # The second method, which is currently in beta and may be changed/removed, involves passing a block # which performs whatever actions would trigger the file chooser to appear. # # # will attach file to a descendant file input element that has a name, id, or label_text matching 'My File' # page.attach_file('My File', '/path/to/file.png') # # # will attach file to el if it's a file input element # el.attach_file('/path/to/file.png') # # # will attach file to whatever file input is triggered by the block # page.attach_file('/path/to/file.png') do # page.find('#upload_button').click # end # # @overload attach_file([locator], paths, **options) # @macro waiting_behavior # # @param [String] locator Which field to attach the file to # @param [String, Array<String>] paths The path(s) of the file(s) that will be attached # # @option options [Symbol] match # The matching strategy to use (:one, :first, :prefer_exact, :smart). Defaults to {Capybara.configure match}. # @option options [Boolean] exact # Match the exact label name/contents or accept a partial match. Defaults to {Capybara.configure exact}. # @option options [Boolean] multiple Match field which allows multiple file selection # @option options [String, Regexp] id Match fields that match the id attribute # @option options [String] name Match fields that match the name attribute # @option options [String, Array<String>, Regexp] class Match fields that match the class(es) provided # @option options [true, Hash] make_visible # A Hash of CSS styles to change before attempting to attach the file, if `true`, `{ opacity: 1, display: 'block', visibility: 'visible' }` is used (may not be supported by all drivers). # @overload attach_file(paths, &blk) # @param [String, Array<String>] paths The path(s) of the file(s) that will be attached # @yield Block whose actions will trigger the system file chooser to be shown # @return [Capybara::Node::Element] The file field element def attach_file(locator = nil, paths, make_visible: nil, **options) # rubocop:disable Style/OptionalArguments if locator && block_given? raise ArgumentError, '`#attach_file` does not support passing both a locator and a block' end Array(paths).each do |path| raise Capybara::FileNotFound, "cannot attach file, #{path} does not exist" unless File.exist?(path.to_s) end options[:allow_self] = true if locator.nil? if block_given? begin execute_script CAPTURE_FILE_ELEMENT_SCRIPT yield file_field = evaluate_script 'window._capybara_clicked_file_input' raise ArgumentError, "Capybara was unable to determine the file input you're attaching to" unless file_field rescue ::Capybara::NotSupportedByDriverError warn 'Block mode of `#attach_file` is not supported by the current driver - ignoring.' end end # Allow user to update the CSS style of the file input since they are so often hidden on a page if make_visible ff = file_field || find(:file_field, locator, **options.merge(visible: :all)) while_visible(ff, make_visible) { |el| el.set(paths) } else (file_field || find(:file_field, locator, **options)).set(paths) end end private def find_select_or_datalist_input(from, options) synchronize(Capybara::Queries::BaseQuery.wait(options, session_options.default_max_wait_time)) do find(:select, from, **options) rescue Capybara::ElementNotFound => select_error # rubocop:disable Naming/RescuedExceptionsVariableName raise if %i[selected with_selected multiple].any? { |option| options.key?(option) } begin find(:datalist_input, from, **options) rescue Capybara::ElementNotFound => dlinput_error raise Capybara::ElementNotFound, "#{select_error.message} and #{dlinput_error.message}" end end end def select_datalist_option(input, value) datalist_options = input.evaluate_script(DATALIST_OPTIONS_SCRIPT) option = datalist_options.find { |opt| opt.values_at('value', 'label').include?(value) } raise ::Capybara::ElementNotFound, %(Unable to find datalist option "#{value}") unless option input.set(option['value']) rescue ::Capybara::NotSupportedByDriverError # Implement for drivers that don't support JS datalist = find(:xpath, XPath.descendant(:datalist)[XPath.attr(:id) == input[:list]], visible: false) option = datalist.find(:datalist_option, value, disabled: false) input.set(option.value) end def while_visible(element, visible_css) if visible_css == true visible_css = { opacity: 1, display: 'block', visibility: 'visible', width: 'auto', height: 'auto' } end _update_style(element, visible_css) unless element.visible? raise ExpectationNotMet, 'The style changes in :make_visible did not make the file input visible' end begin yield element ensure _reset_style(element) end end def _update_style(element, style) element.execute_script(UPDATE_STYLE_SCRIPT, style) rescue Capybara::NotSupportedByDriverError warn 'The :make_visible option is not supported by the current driver - ignoring' end def _reset_style(element) element.execute_script(RESET_STYLE_SCRIPT) rescue StandardError # rubocop:disable Lint/SuppressedException -- swallow extra errors end def _check_with_label(selector, checked, locator, allow_label_click: session_options.automatic_label_click, **options) options[:allow_self] = true if locator.nil? synchronize(Capybara::Queries::BaseQuery.wait(options, session_options.default_max_wait_time)) do el = find(selector, locator, **options) el.set(checked) rescue StandardError => e raise unless allow_label_click && catch_error?(e) begin el ||= find(selector, locator, **options.merge(visible: :all)) unless el.checked? == checked el.session .find(:label, for: el, visible: true, match: :first) .click(**(Hash.try_convert(allow_label_click) || {})) end rescue StandardError # swallow extra errors - raise original raise e end end end UPDATE_STYLE_SCRIPT = <<~JS this.capybara_style_cache = this.style.cssText; var css = arguments[0]; for (var prop in css){ if (css.hasOwnProperty(prop)) { this.style.setProperty(prop, css[prop], "important"); } } JS RESET_STYLE_SCRIPT = <<~JS if (this.hasOwnProperty('capybara_style_cache')) { this.style.cssText = this.capybara_style_cache; delete this.capybara_style_cache; } JS DATALIST_OPTIONS_SCRIPT = <<~JS Array.prototype.slice.call((this.list||{}).options || []). filter(function(el){ return !el.disabled }). map(function(el){ return { "value": el.value, "label": el.label} }) JS CAPTURE_FILE_ELEMENT_SCRIPT = <<~JS document.addEventListener('click', function file_catcher(e){ if (e.target.matches("input[type='file']")) { window._capybara_clicked_file_input = e.target; this.removeEventListener('click', file_catcher); e.preventDefault(); } }, {capture: true}) JS end end end
Ruby
{ "end_line": 322, "name": "find_select_or_datalist_input", "signature": "def find_select_or_datalist_input(from, options)", "start_line": 310 }
{ "class_name": "", "class_signature": "", "module": "Capybara" }
select_datalist_option
capybara/lib/capybara/node/actions.rb
def select_datalist_option(input, value) datalist_options = input.evaluate_script(DATALIST_OPTIONS_SCRIPT) option = datalist_options.find { |opt| opt.values_at('value', 'label').include?(value) } raise ::Capybara::ElementNotFound, %(Unable to find datalist option "#{value}") unless option input.set(option['value']) rescue ::Capybara::NotSupportedByDriverError # Implement for drivers that don't support JS datalist = find(:xpath, XPath.descendant(:datalist)[XPath.attr(:id) == input[:list]], visible: false) option = datalist.find(:datalist_option, value, disabled: false) input.set(option.value) end
# frozen_string_literal: true module Capybara module Node module Actions # @!macro waiting_behavior # If the driver is capable of executing JavaScript, this method will wait for a set amount of time # and continuously retry finding the element until either the element is found or the time # expires. The length of time this method will wait is controlled through {Capybara.configure default_max_wait_time}. # # @option options [false, true, Numeric] wait # Maximum time to wait for matching element to appear. Defaults to {Capybara.configure default_max_wait_time}. ## # # Finds a button or link and clicks it. See {#click_button} and # {#click_link} for what locator will match against for each type of element. # # @overload click_link_or_button([locator], **options) # @macro waiting_behavior # @param [String] locator See {#click_button} and {#click_link} # # @return [Capybara::Node::Element] The element clicked # def click_link_or_button(locator = nil, **options) find(:link_or_button, locator, **options).click end alias_method :click_on, :click_link_or_button ## # # Finds a link by id, {Capybara.configure test_id} attribute, text or title and clicks it. Also looks at image # alt text inside the link. # # @overload click_link([locator], **options) # @macro waiting_behavior # @param [String] locator text, id, {Capybara.configure test_id} attribute, title or nested image's alt attribute # @param [Hash] options See {Capybara::Node::Finders#find_link} # # @return [Capybara::Node::Element] The element clicked def click_link(locator = nil, **options) find(:link, locator, **options).click end ## # # Finds a button on the page and clicks it. # This can be any `<input>` element of type submit, reset, image, button or it can be a # `<button>` element. All buttons can be found by their id, name, {Capybara.configure test_id} attribute, value, or title. `<button>` elements can also be found # by their text content, and image `<input>` elements by their alt attribute. # # @overload click_button([locator], **options) # @macro waiting_behavior # @param [String] locator Which button to find # @param [Hash] options See {Capybara::Node::Finders#find_button} # @return [Capybara::Node::Element] The element clicked def click_button(locator = nil, **options) find(:button, locator, **options).click end ## # # Locate a text field or text area and fill it in with the given text. # The field can be found via its name, id, {Capybara.configure test_id} attribute, placeholder, or label text. # If no locator is provided this will operate on self or a descendant. # # # will fill in a descendant fillable field with name, id, or label text matching 'Name' # page.fill_in 'Name', with: 'Bob' # # # will fill in `el` if it's a fillable field # el.fill_in with: 'Tom' # # # @overload fill_in([locator], with:, **options) # @param [String] locator Which field to fill in # @param [Hash] options # @param with: [String] The value to fill in # @macro waiting_behavior # @option options [String] currently_with The current value property of the field to fill in # @option options [Boolean] multiple Match fields that can have multiple values? # @option options [String, Regexp] id Match fields that match the id attribute # @option options [String] name Match fields that match the name attribute # @option options [String] placeholder Match fields that match the placeholder attribute # @option options [String, Array<String>, Regexp] class Match fields that match the class(es) provided # @option options [Hash] fill_options Driver specific options regarding how to fill fields (Defaults come from {Capybara.configure default_set_options}) # # @return [Capybara::Node::Element] The element filled in def fill_in(locator = nil, with:, currently_with: nil, fill_options: {}, **find_options) find_options[:with] = currently_with if currently_with find_options[:allow_self] = true if locator.nil? find(:fillable_field, locator, **find_options).set(with, **fill_options) end # @!macro label_click # @option options [Boolean, Hash] allow_label_click # Attempt to click the label to toggle state if element is non-visible. Defaults to {Capybara.configure automatic_label_click}. # If set to a Hash it is passed as options to the `click` on the label ## # # Find a descendant radio button and mark it as checked. The radio button can be found # via name, id, {Capybara.configure test_id} attribute or label text. If no locator is # provided this will match against self or a descendant. # # # will choose a descendant radio button with a name, id, or label text matching 'Male' # page.choose('Male') # # # will choose `el` if it's a radio button element # el.choose() # # @overload choose([locator], **options) # @param [String] locator Which radio button to choose # # @option options [String] option Value of the radio_button to choose # @option options [String, Regexp] id Match fields that match the id attribute # @option options [String] name Match fields that match the name attribute # @option options [String, Array<String>, Regexp] class Match fields that match the class(es) provided # @macro waiting_behavior # @macro label_click # # @return [Capybara::Node::Element] The element chosen or the label clicked def choose(locator = nil, **options) _check_with_label(:radio_button, true, locator, **options) end ## # # Find a descendant check box and mark it as checked. The check box can be found # via name, id, {Capybara.configure test_id} attribute, or label text. If no locator # is provided this will match against self or a descendant. # # # will check a descendant checkbox with a name, id, or label text matching 'German' # page.check('German') # # # will check `el` if it's a checkbox element # el.check() # # # @overload check([locator], **options) # @param [String] locator Which check box to check # # @option options [String] option Value of the checkbox to select # @option options [String, Regexp] id Match fields that match the id attribute # @option options [String] name Match fields that match the name attribute # @option options [String, Array<String>, Regexp] class Match fields that match the class(es) provided # @macro label_click # @macro waiting_behavior # # @return [Capybara::Node::Element] The element checked or the label clicked def check(locator = nil, **options) _check_with_label(:checkbox, true, locator, **options) end ## # # Find a descendant check box and uncheck it. The check box can be found # via name, id, {Capybara.configure test_id} attribute, or label text. If # no locator is provided this will match against self or a descendant. # # # will uncheck a descendant checkbox with a name, id, or label text matching 'German' # page.uncheck('German') # # # will uncheck `el` if it's a checkbox element # el.uncheck() # # # @overload uncheck([locator], **options) # @param [String] locator Which check box to uncheck # # @option options [String] option Value of the checkbox to deselect # @option options [String, Regexp] id Match fields that match the id attribute # @option options [String] name Match fields that match the name attribute # @option options [String, Array<String>, Regexp] class Match fields that match the class(es) provided # @macro label_click # @macro waiting_behavior # # @return [Capybara::Node::Element] The element unchecked or the label clicked def uncheck(locator = nil, **options) _check_with_label(:checkbox, false, locator, **options) end ## # # If `from` option is present, {#select} finds a select box, or text input with associated datalist, # on the page and selects a particular option from it. # Otherwise it finds an option inside current scope and selects it. # If the select box is a multiple select, {#select} can be called multiple times to select more than # one option. # The select box can be found via its name, id, {Capybara.configure test_id} attribute, or label text. # The option can be found by its text. # # page.select 'March', from: 'Month' # # @overload select(value = nil, from: nil, **options) # @macro waiting_behavior # # @param value [String] Which option to select # @param from [String] The id, {Capybara.configure test_id} attribute, name or label of the select box # # @return [Capybara::Node::Element] The option element selected def select(value = nil, from: nil, **options) raise ArgumentError, 'The :from option does not take an element' if from.is_a? Capybara::Node::Element el = from ? find_select_or_datalist_input(from, options) : self if el.respond_to?(:tag_name) && (el.tag_name == 'input') select_datalist_option(el, value) else el.find(:option, value, **options).select_option end end ## # # Find a select box on the page and unselect a particular option from it. If the select # box is a multiple select, {#unselect} can be called multiple times to unselect more than # one option. The select box can be found via its name, id, {Capybara.configure test_id} attribute, # or label text. # # page.unselect 'March', from: 'Month' # # @overload unselect(value = nil, from: nil, **options) # @macro waiting_behavior # # @param value [String] Which option to unselect # @param from [String] The id, {Capybara.configure test_id} attribute, name or label of the select box # # # @return [Capybara::Node::Element] The option element unselected def unselect(value = nil, from: nil, **options) raise ArgumentError, 'The :from option does not take an element' if from.is_a? Capybara::Node::Element scope = from ? find(:select, from, **options) : self scope.find(:option, value, **options).unselect_option end ## # # Find a descendant file field on the page and attach a file given its path. There are two ways to use # {#attach_file}, in the first method the file field can be found via its name, id, # {Capybara.configure test_id} attribute, or label text. In the case of the file field being hidden for # styling reasons the `make_visible` option can be used to temporarily change the CSS of # the file field, attach the file, and then revert the CSS back to original. If no locator is # passed this will match self or a descendant. # The second method, which is currently in beta and may be changed/removed, involves passing a block # which performs whatever actions would trigger the file chooser to appear. # # # will attach file to a descendant file input element that has a name, id, or label_text matching 'My File' # page.attach_file('My File', '/path/to/file.png') # # # will attach file to el if it's a file input element # el.attach_file('/path/to/file.png') # # # will attach file to whatever file input is triggered by the block # page.attach_file('/path/to/file.png') do # page.find('#upload_button').click # end # # @overload attach_file([locator], paths, **options) # @macro waiting_behavior # # @param [String] locator Which field to attach the file to # @param [String, Array<String>] paths The path(s) of the file(s) that will be attached # # @option options [Symbol] match # The matching strategy to use (:one, :first, :prefer_exact, :smart). Defaults to {Capybara.configure match}. # @option options [Boolean] exact # Match the exact label name/contents or accept a partial match. Defaults to {Capybara.configure exact}. # @option options [Boolean] multiple Match field which allows multiple file selection # @option options [String, Regexp] id Match fields that match the id attribute # @option options [String] name Match fields that match the name attribute # @option options [String, Array<String>, Regexp] class Match fields that match the class(es) provided # @option options [true, Hash] make_visible # A Hash of CSS styles to change before attempting to attach the file, if `true`, `{ opacity: 1, display: 'block', visibility: 'visible' }` is used (may not be supported by all drivers). # @overload attach_file(paths, &blk) # @param [String, Array<String>] paths The path(s) of the file(s) that will be attached # @yield Block whose actions will trigger the system file chooser to be shown # @return [Capybara::Node::Element] The file field element def attach_file(locator = nil, paths, make_visible: nil, **options) # rubocop:disable Style/OptionalArguments if locator && block_given? raise ArgumentError, '`#attach_file` does not support passing both a locator and a block' end Array(paths).each do |path| raise Capybara::FileNotFound, "cannot attach file, #{path} does not exist" unless File.exist?(path.to_s) end options[:allow_self] = true if locator.nil? if block_given? begin execute_script CAPTURE_FILE_ELEMENT_SCRIPT yield file_field = evaluate_script 'window._capybara_clicked_file_input' raise ArgumentError, "Capybara was unable to determine the file input you're attaching to" unless file_field rescue ::Capybara::NotSupportedByDriverError warn 'Block mode of `#attach_file` is not supported by the current driver - ignoring.' end end # Allow user to update the CSS style of the file input since they are so often hidden on a page if make_visible ff = file_field || find(:file_field, locator, **options.merge(visible: :all)) while_visible(ff, make_visible) { |el| el.set(paths) } else (file_field || find(:file_field, locator, **options)).set(paths) end end private def find_select_or_datalist_input(from, options) synchronize(Capybara::Queries::BaseQuery.wait(options, session_options.default_max_wait_time)) do find(:select, from, **options) rescue Capybara::ElementNotFound => select_error # rubocop:disable Naming/RescuedExceptionsVariableName raise if %i[selected with_selected multiple].any? { |option| options.key?(option) } begin find(:datalist_input, from, **options) rescue Capybara::ElementNotFound => dlinput_error raise Capybara::ElementNotFound, "#{select_error.message} and #{dlinput_error.message}" end end end def select_datalist_option(input, value) datalist_options = input.evaluate_script(DATALIST_OPTIONS_SCRIPT) option = datalist_options.find { |opt| opt.values_at('value', 'label').include?(value) } raise ::Capybara::ElementNotFound, %(Unable to find datalist option "#{value}") unless option input.set(option['value']) rescue ::Capybara::NotSupportedByDriverError # Implement for drivers that don't support JS datalist = find(:xpath, XPath.descendant(:datalist)[XPath.attr(:id) == input[:list]], visible: false) option = datalist.find(:datalist_option, value, disabled: false) input.set(option.value) end def while_visible(element, visible_css) if visible_css == true visible_css = { opacity: 1, display: 'block', visibility: 'visible', width: 'auto', height: 'auto' } end _update_style(element, visible_css) unless element.visible? raise ExpectationNotMet, 'The style changes in :make_visible did not make the file input visible' end begin yield element ensure _reset_style(element) end end def _update_style(element, style) element.execute_script(UPDATE_STYLE_SCRIPT, style) rescue Capybara::NotSupportedByDriverError warn 'The :make_visible option is not supported by the current driver - ignoring' end def _reset_style(element) element.execute_script(RESET_STYLE_SCRIPT) rescue StandardError # rubocop:disable Lint/SuppressedException -- swallow extra errors end def _check_with_label(selector, checked, locator, allow_label_click: session_options.automatic_label_click, **options) options[:allow_self] = true if locator.nil? synchronize(Capybara::Queries::BaseQuery.wait(options, session_options.default_max_wait_time)) do el = find(selector, locator, **options) el.set(checked) rescue StandardError => e raise unless allow_label_click && catch_error?(e) begin el ||= find(selector, locator, **options.merge(visible: :all)) unless el.checked? == checked el.session .find(:label, for: el, visible: true, match: :first) .click(**(Hash.try_convert(allow_label_click) || {})) end rescue StandardError # swallow extra errors - raise original raise e end end end UPDATE_STYLE_SCRIPT = <<~JS this.capybara_style_cache = this.style.cssText; var css = arguments[0]; for (var prop in css){ if (css.hasOwnProperty(prop)) { this.style.setProperty(prop, css[prop], "important"); } } JS RESET_STYLE_SCRIPT = <<~JS if (this.hasOwnProperty('capybara_style_cache')) { this.style.cssText = this.capybara_style_cache; delete this.capybara_style_cache; } JS DATALIST_OPTIONS_SCRIPT = <<~JS Array.prototype.slice.call((this.list||{}).options || []). filter(function(el){ return !el.disabled }). map(function(el){ return { "value": el.value, "label": el.label} }) JS CAPTURE_FILE_ELEMENT_SCRIPT = <<~JS document.addEventListener('click', function file_catcher(e){ if (e.target.matches("input[type='file']")) { window._capybara_clicked_file_input = e.target; this.removeEventListener('click', file_catcher); e.preventDefault(); } }, {capture: true}) JS end end end
Ruby
{ "end_line": 335, "name": "select_datalist_option", "signature": "def select_datalist_option(input, value)", "start_line": 324 }
{ "class_name": "", "class_signature": "", "module": "Capybara" }
while_visible
capybara/lib/capybara/node/actions.rb
def while_visible(element, visible_css) if visible_css == true visible_css = { opacity: 1, display: 'block', visibility: 'visible', width: 'auto', height: 'auto' } end _update_style(element, visible_css) unless element.visible? raise ExpectationNotMet, 'The style changes in :make_visible did not make the file input visible' end begin yield element ensure _reset_style(element) end end
# frozen_string_literal: true module Capybara module Node module Actions # @!macro waiting_behavior # If the driver is capable of executing JavaScript, this method will wait for a set amount of time # and continuously retry finding the element until either the element is found or the time # expires. The length of time this method will wait is controlled through {Capybara.configure default_max_wait_time}. # # @option options [false, true, Numeric] wait # Maximum time to wait for matching element to appear. Defaults to {Capybara.configure default_max_wait_time}. ## # # Finds a button or link and clicks it. See {#click_button} and # {#click_link} for what locator will match against for each type of element. # # @overload click_link_or_button([locator], **options) # @macro waiting_behavior # @param [String] locator See {#click_button} and {#click_link} # # @return [Capybara::Node::Element] The element clicked # def click_link_or_button(locator = nil, **options) find(:link_or_button, locator, **options).click end alias_method :click_on, :click_link_or_button ## # # Finds a link by id, {Capybara.configure test_id} attribute, text or title and clicks it. Also looks at image # alt text inside the link. # # @overload click_link([locator], **options) # @macro waiting_behavior # @param [String] locator text, id, {Capybara.configure test_id} attribute, title or nested image's alt attribute # @param [Hash] options See {Capybara::Node::Finders#find_link} # # @return [Capybara::Node::Element] The element clicked def click_link(locator = nil, **options) find(:link, locator, **options).click end ## # # Finds a button on the page and clicks it. # This can be any `<input>` element of type submit, reset, image, button or it can be a # `<button>` element. All buttons can be found by their id, name, {Capybara.configure test_id} attribute, value, or title. `<button>` elements can also be found # by their text content, and image `<input>` elements by their alt attribute. # # @overload click_button([locator], **options) # @macro waiting_behavior # @param [String] locator Which button to find # @param [Hash] options See {Capybara::Node::Finders#find_button} # @return [Capybara::Node::Element] The element clicked def click_button(locator = nil, **options) find(:button, locator, **options).click end ## # # Locate a text field or text area and fill it in with the given text. # The field can be found via its name, id, {Capybara.configure test_id} attribute, placeholder, or label text. # If no locator is provided this will operate on self or a descendant. # # # will fill in a descendant fillable field with name, id, or label text matching 'Name' # page.fill_in 'Name', with: 'Bob' # # # will fill in `el` if it's a fillable field # el.fill_in with: 'Tom' # # # @overload fill_in([locator], with:, **options) # @param [String] locator Which field to fill in # @param [Hash] options # @param with: [String] The value to fill in # @macro waiting_behavior # @option options [String] currently_with The current value property of the field to fill in # @option options [Boolean] multiple Match fields that can have multiple values? # @option options [String, Regexp] id Match fields that match the id attribute # @option options [String] name Match fields that match the name attribute # @option options [String] placeholder Match fields that match the placeholder attribute # @option options [String, Array<String>, Regexp] class Match fields that match the class(es) provided # @option options [Hash] fill_options Driver specific options regarding how to fill fields (Defaults come from {Capybara.configure default_set_options}) # # @return [Capybara::Node::Element] The element filled in def fill_in(locator = nil, with:, currently_with: nil, fill_options: {}, **find_options) find_options[:with] = currently_with if currently_with find_options[:allow_self] = true if locator.nil? find(:fillable_field, locator, **find_options).set(with, **fill_options) end # @!macro label_click # @option options [Boolean, Hash] allow_label_click # Attempt to click the label to toggle state if element is non-visible. Defaults to {Capybara.configure automatic_label_click}. # If set to a Hash it is passed as options to the `click` on the label ## # # Find a descendant radio button and mark it as checked. The radio button can be found # via name, id, {Capybara.configure test_id} attribute or label text. If no locator is # provided this will match against self or a descendant. # # # will choose a descendant radio button with a name, id, or label text matching 'Male' # page.choose('Male') # # # will choose `el` if it's a radio button element # el.choose() # # @overload choose([locator], **options) # @param [String] locator Which radio button to choose # # @option options [String] option Value of the radio_button to choose # @option options [String, Regexp] id Match fields that match the id attribute # @option options [String] name Match fields that match the name attribute # @option options [String, Array<String>, Regexp] class Match fields that match the class(es) provided # @macro waiting_behavior # @macro label_click # # @return [Capybara::Node::Element] The element chosen or the label clicked def choose(locator = nil, **options) _check_with_label(:radio_button, true, locator, **options) end ## # # Find a descendant check box and mark it as checked. The check box can be found # via name, id, {Capybara.configure test_id} attribute, or label text. If no locator # is provided this will match against self or a descendant. # # # will check a descendant checkbox with a name, id, or label text matching 'German' # page.check('German') # # # will check `el` if it's a checkbox element # el.check() # # # @overload check([locator], **options) # @param [String] locator Which check box to check # # @option options [String] option Value of the checkbox to select # @option options [String, Regexp] id Match fields that match the id attribute # @option options [String] name Match fields that match the name attribute # @option options [String, Array<String>, Regexp] class Match fields that match the class(es) provided # @macro label_click # @macro waiting_behavior # # @return [Capybara::Node::Element] The element checked or the label clicked def check(locator = nil, **options) _check_with_label(:checkbox, true, locator, **options) end ## # # Find a descendant check box and uncheck it. The check box can be found # via name, id, {Capybara.configure test_id} attribute, or label text. If # no locator is provided this will match against self or a descendant. # # # will uncheck a descendant checkbox with a name, id, or label text matching 'German' # page.uncheck('German') # # # will uncheck `el` if it's a checkbox element # el.uncheck() # # # @overload uncheck([locator], **options) # @param [String] locator Which check box to uncheck # # @option options [String] option Value of the checkbox to deselect # @option options [String, Regexp] id Match fields that match the id attribute # @option options [String] name Match fields that match the name attribute # @option options [String, Array<String>, Regexp] class Match fields that match the class(es) provided # @macro label_click # @macro waiting_behavior # # @return [Capybara::Node::Element] The element unchecked or the label clicked def uncheck(locator = nil, **options) _check_with_label(:checkbox, false, locator, **options) end ## # # If `from` option is present, {#select} finds a select box, or text input with associated datalist, # on the page and selects a particular option from it. # Otherwise it finds an option inside current scope and selects it. # If the select box is a multiple select, {#select} can be called multiple times to select more than # one option. # The select box can be found via its name, id, {Capybara.configure test_id} attribute, or label text. # The option can be found by its text. # # page.select 'March', from: 'Month' # # @overload select(value = nil, from: nil, **options) # @macro waiting_behavior # # @param value [String] Which option to select # @param from [String] The id, {Capybara.configure test_id} attribute, name or label of the select box # # @return [Capybara::Node::Element] The option element selected def select(value = nil, from: nil, **options) raise ArgumentError, 'The :from option does not take an element' if from.is_a? Capybara::Node::Element el = from ? find_select_or_datalist_input(from, options) : self if el.respond_to?(:tag_name) && (el.tag_name == 'input') select_datalist_option(el, value) else el.find(:option, value, **options).select_option end end ## # # Find a select box on the page and unselect a particular option from it. If the select # box is a multiple select, {#unselect} can be called multiple times to unselect more than # one option. The select box can be found via its name, id, {Capybara.configure test_id} attribute, # or label text. # # page.unselect 'March', from: 'Month' # # @overload unselect(value = nil, from: nil, **options) # @macro waiting_behavior # # @param value [String] Which option to unselect # @param from [String] The id, {Capybara.configure test_id} attribute, name or label of the select box # # # @return [Capybara::Node::Element] The option element unselected def unselect(value = nil, from: nil, **options) raise ArgumentError, 'The :from option does not take an element' if from.is_a? Capybara::Node::Element scope = from ? find(:select, from, **options) : self scope.find(:option, value, **options).unselect_option end ## # # Find a descendant file field on the page and attach a file given its path. There are two ways to use # {#attach_file}, in the first method the file field can be found via its name, id, # {Capybara.configure test_id} attribute, or label text. In the case of the file field being hidden for # styling reasons the `make_visible` option can be used to temporarily change the CSS of # the file field, attach the file, and then revert the CSS back to original. If no locator is # passed this will match self or a descendant. # The second method, which is currently in beta and may be changed/removed, involves passing a block # which performs whatever actions would trigger the file chooser to appear. # # # will attach file to a descendant file input element that has a name, id, or label_text matching 'My File' # page.attach_file('My File', '/path/to/file.png') # # # will attach file to el if it's a file input element # el.attach_file('/path/to/file.png') # # # will attach file to whatever file input is triggered by the block # page.attach_file('/path/to/file.png') do # page.find('#upload_button').click # end # # @overload attach_file([locator], paths, **options) # @macro waiting_behavior # # @param [String] locator Which field to attach the file to # @param [String, Array<String>] paths The path(s) of the file(s) that will be attached # # @option options [Symbol] match # The matching strategy to use (:one, :first, :prefer_exact, :smart). Defaults to {Capybara.configure match}. # @option options [Boolean] exact # Match the exact label name/contents or accept a partial match. Defaults to {Capybara.configure exact}. # @option options [Boolean] multiple Match field which allows multiple file selection # @option options [String, Regexp] id Match fields that match the id attribute # @option options [String] name Match fields that match the name attribute # @option options [String, Array<String>, Regexp] class Match fields that match the class(es) provided # @option options [true, Hash] make_visible # A Hash of CSS styles to change before attempting to attach the file, if `true`, `{ opacity: 1, display: 'block', visibility: 'visible' }` is used (may not be supported by all drivers). # @overload attach_file(paths, &blk) # @param [String, Array<String>] paths The path(s) of the file(s) that will be attached # @yield Block whose actions will trigger the system file chooser to be shown # @return [Capybara::Node::Element] The file field element def attach_file(locator = nil, paths, make_visible: nil, **options) # rubocop:disable Style/OptionalArguments if locator && block_given? raise ArgumentError, '`#attach_file` does not support passing both a locator and a block' end Array(paths).each do |path| raise Capybara::FileNotFound, "cannot attach file, #{path} does not exist" unless File.exist?(path.to_s) end options[:allow_self] = true if locator.nil? if block_given? begin execute_script CAPTURE_FILE_ELEMENT_SCRIPT yield file_field = evaluate_script 'window._capybara_clicked_file_input' raise ArgumentError, "Capybara was unable to determine the file input you're attaching to" unless file_field rescue ::Capybara::NotSupportedByDriverError warn 'Block mode of `#attach_file` is not supported by the current driver - ignoring.' end end # Allow user to update the CSS style of the file input since they are so often hidden on a page if make_visible ff = file_field || find(:file_field, locator, **options.merge(visible: :all)) while_visible(ff, make_visible) { |el| el.set(paths) } else (file_field || find(:file_field, locator, **options)).set(paths) end end private def find_select_or_datalist_input(from, options) synchronize(Capybara::Queries::BaseQuery.wait(options, session_options.default_max_wait_time)) do find(:select, from, **options) rescue Capybara::ElementNotFound => select_error # rubocop:disable Naming/RescuedExceptionsVariableName raise if %i[selected with_selected multiple].any? { |option| options.key?(option) } begin find(:datalist_input, from, **options) rescue Capybara::ElementNotFound => dlinput_error raise Capybara::ElementNotFound, "#{select_error.message} and #{dlinput_error.message}" end end end def select_datalist_option(input, value) datalist_options = input.evaluate_script(DATALIST_OPTIONS_SCRIPT) option = datalist_options.find { |opt| opt.values_at('value', 'label').include?(value) } raise ::Capybara::ElementNotFound, %(Unable to find datalist option "#{value}") unless option input.set(option['value']) rescue ::Capybara::NotSupportedByDriverError # Implement for drivers that don't support JS datalist = find(:xpath, XPath.descendant(:datalist)[XPath.attr(:id) == input[:list]], visible: false) option = datalist.find(:datalist_option, value, disabled: false) input.set(option.value) end def while_visible(element, visible_css) if visible_css == true visible_css = { opacity: 1, display: 'block', visibility: 'visible', width: 'auto', height: 'auto' } end _update_style(element, visible_css) unless element.visible? raise ExpectationNotMet, 'The style changes in :make_visible did not make the file input visible' end begin yield element ensure _reset_style(element) end end def _update_style(element, style) element.execute_script(UPDATE_STYLE_SCRIPT, style) rescue Capybara::NotSupportedByDriverError warn 'The :make_visible option is not supported by the current driver - ignoring' end def _reset_style(element) element.execute_script(RESET_STYLE_SCRIPT) rescue StandardError # rubocop:disable Lint/SuppressedException -- swallow extra errors end def _check_with_label(selector, checked, locator, allow_label_click: session_options.automatic_label_click, **options) options[:allow_self] = true if locator.nil? synchronize(Capybara::Queries::BaseQuery.wait(options, session_options.default_max_wait_time)) do el = find(selector, locator, **options) el.set(checked) rescue StandardError => e raise unless allow_label_click && catch_error?(e) begin el ||= find(selector, locator, **options.merge(visible: :all)) unless el.checked? == checked el.session .find(:label, for: el, visible: true, match: :first) .click(**(Hash.try_convert(allow_label_click) || {})) end rescue StandardError # swallow extra errors - raise original raise e end end end UPDATE_STYLE_SCRIPT = <<~JS this.capybara_style_cache = this.style.cssText; var css = arguments[0]; for (var prop in css){ if (css.hasOwnProperty(prop)) { this.style.setProperty(prop, css[prop], "important"); } } JS RESET_STYLE_SCRIPT = <<~JS if (this.hasOwnProperty('capybara_style_cache')) { this.style.cssText = this.capybara_style_cache; delete this.capybara_style_cache; } JS DATALIST_OPTIONS_SCRIPT = <<~JS Array.prototype.slice.call((this.list||{}).options || []). filter(function(el){ return !el.disabled }). map(function(el){ return { "value": el.value, "label": el.label} }) JS CAPTURE_FILE_ELEMENT_SCRIPT = <<~JS document.addEventListener('click', function file_catcher(e){ if (e.target.matches("input[type='file']")) { window._capybara_clicked_file_input = e.target; this.removeEventListener('click', file_catcher); e.preventDefault(); } }, {capture: true}) JS end end end
Ruby
{ "end_line": 351, "name": "while_visible", "signature": "def while_visible(element, visible_css)", "start_line": 337 }
{ "class_name": "", "class_signature": "", "module": "Capybara" }
synchronize
capybara/lib/capybara/node/base.rb
def synchronize(seconds = nil, errors: nil) return yield if session.synchronized seconds = session_options.default_max_wait_time if [nil, true].include? seconds interval = session_options.default_retry_interval session.synchronized = true timer = Capybara::Helpers.timer(expire_in: seconds) begin yield rescue StandardError => e session.raise_server_error! raise e unless catch_error?(e, errors) if driver.wait? raise e if timer.expired? sleep interval reload if session_options.automatic_reload else old_base = @base reload if session_options.automatic_reload raise e if old_base == @base end retry ensure session.synchronized = false end end
# frozen_string_literal: true module Capybara module Node ## # # A {Capybara::Node::Base} represents either an element on a page through the subclass # {Capybara::Node::Element} or a document through {Capybara::Node::Document}. # # Both types of Node share the same methods, used for interacting with the # elements on the page. These methods are divided into three categories, # finders, actions and matchers. These are found in the modules # {Capybara::Node::Finders}, {Capybara::Node::Actions} and {Capybara::Node::Matchers} # respectively. # # A {Capybara::Session} exposes all methods from {Capybara::Node::Document} directly: # # session = Capybara::Session.new(:rack_test, my_app) # session.visit('/') # session.fill_in('Foo', with: 'Bar') # from Capybara::Node::Actions # bar = session.find('#bar') # from Capybara::Node::Finders # bar.select('Baz', from: 'Quox') # from Capybara::Node::Actions # session.has_css?('#foobar') # from Capybara::Node::Matchers # class Base attr_reader :session, :base, :query_scope include Capybara::Node::Finders include Capybara::Node::Actions include Capybara::Node::Matchers def initialize(session, base) @session = session @base = base end # overridden in subclasses, e.g. Capybara::Node::Element def reload self end ## # # This method is Capybara's primary defence against asynchronicity # problems. It works by attempting to run a given block of code until it # succeeds. The exact behaviour of this method depends on a number of # factors. Basically there are certain exceptions which, when raised # from the block, instead of bubbling up, are caught, and the block is # re-run. # # Certain drivers, such as RackTest, have no support for asynchronous # processes, these drivers run the block, and any error raised bubbles up # immediately. This allows faster turn around in the case where an # expectation fails. # # Only exceptions that are {Capybara::ElementNotFound} or any subclass # thereof cause the block to be rerun. Drivers may specify additional # exceptions which also cause reruns. This usually occurs when a node is # manipulated which no longer exists on the page. For example, the # Selenium driver specifies # `Selenium::WebDriver::Error::ObsoleteElementError`. # # As long as any of these exceptions are thrown, the block is re-run, # until a certain amount of time passes. The amount of time defaults to # {Capybara.default_max_wait_time} and can be overridden through the `seconds` # argument. This time is compared with the system time to see how much # time has passed. On rubies/platforms which don't support access to a monotonic process clock # if the return value of `Time.now` is stubbed out, Capybara will raise `Capybara::FrozenInTime`. # # @param [Integer] seconds (current sessions default_max_wait_time) Maximum number of seconds to retry this block # @param [Array<Exception>] errors (driver.invalid_element_errors + # [Capybara::ElementNotFound]) exception types that cause the block to be rerun # @return [Object] The result of the given block # @raise [Capybara::FrozenInTime] If the return value of `Time.now` appears stuck # def synchronize(seconds = nil, errors: nil) return yield if session.synchronized seconds = session_options.default_max_wait_time if [nil, true].include? seconds interval = session_options.default_retry_interval session.synchronized = true timer = Capybara::Helpers.timer(expire_in: seconds) begin yield rescue StandardError => e session.raise_server_error! raise e unless catch_error?(e, errors) if driver.wait? raise e if timer.expired? sleep interval reload if session_options.automatic_reload else old_base = @base reload if session_options.automatic_reload raise e if old_base == @base end retry ensure session.synchronized = false end end # @api private def find_css(css, **options) if base.method(:find_css).arity == 1 base.find_css(css) else base.find_css(css, **options) end end # @api private def find_xpath(xpath, **options) if base.method(:find_xpath).arity == 1 base.find_xpath(xpath) else base.find_xpath(xpath, **options) end end # @api private def session_options session.config end def to_capybara_node self end protected def catch_error?(error, errors = nil) errors ||= (driver.invalid_element_errors + [Capybara::ElementNotFound]) errors.any? { |type| error.is_a?(type) } end def driver session.driver end end end end
Ruby
{ "end_line": 103, "name": "synchronize", "signature": "def synchronize(seconds = nil, errors: nil)", "start_line": 76 }
{ "class_name": "Base", "class_signature": "class Base", "module": "Capybara" }
style
capybara/lib/capybara/node/element.rb
def style(*styles) styles = styles.flatten.map(&:to_s) raise ArgumentError, 'You must specify at least one CSS style' if styles.empty? begin synchronize { base.style(styles) } rescue NotImplementedError => e begin evaluate_script(STYLE_SCRIPT, *styles) rescue Capybara::NotSupportedByDriverError raise e end end end
# frozen_string_literal: true module Capybara module Node ## # # A {Capybara::Node::Element} represents a single element on the page. It is possible # to interact with the contents of this element the same as with a document: # # session = Capybara::Session.new(:rack_test, my_app) # # bar = session.find('#bar') # from Capybara::Node::Finders # bar.select('Baz', from: 'Quox') # from Capybara::Node::Actions # # {Capybara::Node::Element} also has access to HTML attributes and other properties of the # element: # # bar.value # bar.text # bar[:title] # # @see Capybara::Node # class Element < Base def initialize(session, base, query_scope, query) super(session, base) @query_scope = query_scope @query = query @allow_reload = false @query_idx = nil end def allow_reload!(idx = nil) @query_idx = idx @allow_reload = true end ## # # @return [Object] The native element from the driver, this allows access to driver specific methods # def native synchronize { base.native } end ## # # Retrieve the text of the element. If {Capybara.configure ignore_hidden_elements} # is `true`, which it is by default, then this will return only text # which is visible. The exact semantics of this may differ between # drivers, but generally any text within elements with `display:none` is # ignored. This behaviour can be overridden by passing `:all` to this # method. # # @param type [:all, :visible] Whether to return only visible or all text # @return [String] The text of the element # def text(type = nil, normalize_ws: false) type ||= :all unless session_options.ignore_hidden_elements || session_options.visible_text_only txt = synchronize { type == :all ? base.all_text : base.visible_text } normalize_ws ? txt.gsub(/[[:space:]]+/, ' ').strip : txt end ## # # Retrieve the given attribute. # # element[:title] # => HTML title attribute # # @param [Symbol] attribute The attribute to retrieve # @return [String] The value of the attribute # def [](attribute) synchronize { base[attribute] } end ## # # Retrieve the given CSS styles. # # element.style('color', 'font-size') # => Computed values of CSS 'color' and 'font-size' styles # # @param [Array<String>] styles Names of the desired CSS properties # @return [Hash] Hash of the CSS property names to computed values # def style(*styles) styles = styles.flatten.map(&:to_s) raise ArgumentError, 'You must specify at least one CSS style' if styles.empty? begin synchronize { base.style(styles) } rescue NotImplementedError => e begin evaluate_script(STYLE_SCRIPT, *styles) rescue Capybara::NotSupportedByDriverError raise e end end end ## # # @return [String] The value of the form element # def value synchronize { base.value } end ## # # Set the value of the form element to the given value. # # @param [String] value The new value # @param [Hash] options Driver specific options for how to set the value. Take default values from {Capybara.configure default_set_options}. # # @return [Capybara::Node::Element] The element def set(value, **options) if ENV.fetch('CAPYBARA_THOROUGH', nil) && readonly? raise Capybara::ReadOnlyElementError, "Attempt to set readonly element with value: #{value}" end options = session_options.default_set_options.to_h.merge(options) synchronize { base.set(value, **options) } self end ## # # Select this node if it is an option element inside a select tag. # # @!macro action_waiting_behavior # If the driver dynamic pages (JS) and the element is currently non-interactable, this method will # continuously retry the action until either the element becomes interactable or the maximum # wait time expires. # # @param [false, Numeric] wait # Maximum time to wait for the action to succeed. Defaults to {Capybara.configure default_max_wait_time}. # @return [Capybara::Node::Element] The element def select_option(wait: nil) synchronize(wait) { base.select_option } self end ## # # Unselect this node if it is an option element inside a multiple select tag. # # @macro action_waiting_behavior # @return [Capybara::Node::Element] The element def unselect_option(wait: nil) synchronize(wait) { base.unselect_option } self end ## # # Click the Element. # # @macro action_waiting_behavior # @!macro click_modifiers # Both x: and y: must be specified if an offset is wanted, if not specified the click will occur at the middle of the element. # @overload $0(*modifier_keys, wait: nil, **offset) # @param *modifier_keys [:alt, :control, :meta, :shift] ([]) Keys to be held down when clicking # @option options [Integer] x X coordinate to offset the click location. If {Capybara.configure w3c_click_offset} is `true` the # offset will be from the element center, otherwise it will be from the top left corner of the element # @option options [Integer] y Y coordinate to offset the click location. If {Capybara.configure w3c_click_offset} is `true` the # offset will be from the element center, otherwise it will be from the top left corner of the element # @option options [Float] delay Delay between the mouse down and mouse up events in seconds (0) # @return [Capybara::Node::Element] The element def click(*keys, **options) perform_click_action(keys, **options) do |k, opts| base.click(k, **opts) end end ## # # Right Click the Element. # # @macro action_waiting_behavior # @macro click_modifiers # @option options [Float] delay Delay between the mouse down and mouse up events in seconds (0) # @return [Capybara::Node::Element] The element def right_click(*keys, **options) perform_click_action(keys, **options) do |k, opts| base.right_click(k, **opts) end end ## # # Double Click the Element. # # @macro action_waiting_behavior # @macro click_modifiers # @return [Capybara::Node::Element] The element def double_click(*keys, **options) perform_click_action(keys, **options) do |k, opts| base.double_click(k, **opts) end end ## # # Send Keystrokes to the Element. # # @overload send_keys(keys, ...) # @param keys [String, Symbol, Array<String,Symbol>] # # Examples: # # element.send_keys "foo" #=> value: 'foo' # element.send_keys "tet", :left, "s" #=> value: 'test' # element.send_keys [:control, 'a'], :space #=> value: ' ' - assuming ctrl-a selects all contents # # Symbols supported for keys: # * :cancel # * :help # * :backspace # * :tab # * :clear # * :return # * :enter # * :shift # * :control # * :alt # * :pause # * :escape # * :space # * :page_up # * :page_down # * :end # * :home # * :left # * :up # * :right # * :down # * :insert # * :delete # * :semicolon # * :equals # * :numpad0 # * :numpad1 # * :numpad2 # * :numpad3 # * :numpad4 # * :numpad5 # * :numpad6 # * :numpad7 # * :numpad8 # * :numpad9 # * :multiply - numeric keypad * # * :add - numeric keypad + # * :separator - numeric keypad 'separator' key ?? # * :subtract - numeric keypad - # * :decimal - numeric keypad . # * :divide - numeric keypad / # * :f1 # * :f2 # * :f3 # * :f4 # * :f5 # * :f6 # * :f7 # * :f8 # * :f9 # * :f10 # * :f11 # * :f12 # * :meta # * :command - alias of :meta # # @return [Capybara::Node::Element] The element def send_keys(*args) synchronize { base.send_keys(*args) } self end ## # # Hover on the Element. # # @return [Capybara::Node::Element] The element def hover synchronize { base.hover } self end ## # # @return [String] The tag name of the element # def tag_name # Element type is immutable so cache it @tag_name ||= initial_cache[:tag_name] || synchronize { base.tag_name } end ## # # Whether or not the element is visible. Not all drivers support CSS, so # the result may be inaccurate. # # @return [Boolean] Whether the element is visible # def visible? synchronize { base.visible? } end ## # # Whether or not the element is currently in the viewport and it (or descendants) # would be considered clickable at the elements center point. # # @return [Boolean] Whether the elements center is obscured. # def obscured? synchronize { base.obscured? } end ## # # Whether or not the element is checked. # # @return [Boolean] Whether the element is checked # def checked? synchronize { base.checked? } end ## # # Whether or not the element is selected. # # @return [Boolean] Whether the element is selected # def selected? synchronize { base.selected? } end ## # # Whether or not the element is disabled. # # @return [Boolean] Whether the element is disabled # def disabled? synchronize { base.disabled? } end ## # # Whether or not the element is readonly. # # @return [Boolean] Whether the element is readonly # def readonly? synchronize { base.readonly? } end ## # # Whether or not the element supports multiple results. # # @return [Boolean] Whether the element supports multiple results. # def multiple? synchronize { base.multiple? } end ## # # An XPath expression describing where on the page the element can be found. # # @return [String] An XPath expression # def path synchronize { base.path } end def rect synchronize { base.rect } end ## # # Trigger any event on the current element, for example mouseover or focus # events. Not supported with the Selenium driver, and SHOULDN'T BE USED IN TESTING unless you # fully understand why you're using it, that it can allow actions a user could never # perform, and that it may completely invalidate your test. # # @param [String] event The name of the event to trigger # # @return [Capybara::Node::Element] The element def trigger(event) synchronize { base.trigger(event) } self end ## # # Drag the element to the given other element. # # source = page.find('#foo') # target = page.find('#bar') # source.drag_to(target) # # @param [Capybara::Node::Element] node The element to drag to # @param [Hash] options Driver specific options for dragging. May not be supported by all drivers. # @option options [Numeric] :delay (0.05) When using Chrome/Firefox with Selenium and HTML5 dragging this is the number # of seconds between each stage of the drag. # @option options [Boolean] :html5 When using Chrome/Firefox with Selenium enables to force the use of HTML5 # (true) or legacy (false) dragging. If not specified the driver will attempt to # detect the correct method to use. # @option options [Array<Symbol>,Symbol] :drop_modifiers Modifier keys which should be held while the dragged element is dropped. # # # @return [Capybara::Node::Element] The dragged element def drag_to(node, **options) synchronize { base.drag_to(node.base, **options) } self end ## # # Drop items on the current element. # # target = page.find('#foo') # target.drop('/some/path/file.csv') # # @overload drop(path, ...) # @param [String, #to_path] path Location of the file to drop on the element # # @overload drop(strings, ...) # @param [Hash] strings A hash of type to data to be dropped - `{ "text/url" => "https://www.google.com" }` # # @return [Capybara::Node::Element] The element def drop(*args) options = args.map { |arg| arg.respond_to?(:to_path) ? arg.to_path : arg } synchronize { base.drop(*options) } self end ## # # Scroll the page or element. # # @overload scroll_to(position, offset: [0,0]) # Scroll the page or element to its top, bottom or middle. # @param [:top, :bottom, :center, :current] position # @param [[Integer, Integer]] offset # # @overload scroll_to(element, align: :top) # Scroll the page or current element until the given element is aligned at the top, bottom, or center of it. # @param [Capybara::Node::Element] element The element to be scrolled into view # @param [:top, :bottom, :center] align Where to align the element being scrolled into view with relation to the current page/element if possible # # @overload scroll_to(x,y) # @param [Integer] x Horizontal scroll offset # @param [Integer] y Vertical scroll offset # # @return [Capybara::Node::Element] The element def scroll_to(pos_or_el_or_x, y = nil, align: :top, offset: nil) case pos_or_el_or_x when Symbol synchronize { base.scroll_to(nil, pos_or_el_or_x) } unless pos_or_el_or_x == :current when Capybara::Node::Element synchronize { base.scroll_to(pos_or_el_or_x.base, align) } else synchronize { base.scroll_to(nil, nil, [pos_or_el_or_x, y]) } end synchronize { base.scroll_by(*offset) } unless offset.nil? self end ## # # Return the shadow_root for the current element # # @return [Capybara::Node::Element] The shadow root def shadow_root root = synchronize { base.shadow_root } root && Capybara::Node::Element.new(session, root, nil, nil) end ## # # Execute the given JS in the context of the element not returning a result. This is useful for scripts that return # complex objects, such as jQuery statements. {#execute_script} should be used over # {#evaluate_script} whenever a result is not expected or needed. `this` in the script will refer to the element this is called on. # # @param [String] script A string of JavaScript to execute # @param args Optional arguments that will be passed to the script. Driver support for this is optional and types of objects supported may differ between drivers # def execute_script(script, *args) session.execute_script(<<~JS, self, *args) (function (){ #{script} }).apply(arguments[0], Array.prototype.slice.call(arguments,1)); JS end ## # # Evaluate the given JS in the context of the element and return the result. Be careful when using this with # scripts that return complex objects, such as jQuery statements. {#execute_script} might # be a better alternative. `this` in the script will refer to the element this is called on. # # @param [String] script A string of JavaScript to evaluate # @return [Object] The result of the evaluated JavaScript (may be driver specific) # def evaluate_script(script, *args) session.evaluate_script(<<~JS, self, *args) (function(){ return #{script.strip} }).apply(arguments[0], Array.prototype.slice.call(arguments,1)); JS end ## # # Evaluate the given JavaScript in the context of the element and obtain the result from a # callback function which will be passed as the last argument to the script. `this` in the # script will refer to the element this is called on. # # @param [String] script A string of JavaScript to evaluate # @return [Object] The result of the evaluated JavaScript (may be driver specific) # def evaluate_async_script(script, *args) session.evaluate_async_script(<<~JS, self, *args) (function (){ #{script} }).apply(arguments[0], Array.prototype.slice.call(arguments,1)); JS end ## # # Toggle the elements background color between white and black for a period of time. # # @return [Capybara::Node::Element] The element def flash execute_script(<<~JS, 100) async function flash(el, delay){ var old_bg = el.style.backgroundColor; var colors = ["black", "white"]; for(var i=0; i<20; i++){ el.style.backgroundColor = colors[i % colors.length]; await new Promise(resolve => setTimeout(resolve, delay)); } el.style.backgroundColor = old_bg; } flash(this, arguments[0]); JS self end # @api private def reload return self unless @allow_reload begin reloaded = @query.resolve_for(query_scope ? query_scope.reload : session)[@query_idx.to_i] @base = reloaded.base if reloaded rescue StandardError => e raise e unless catch_error?(e) end self end ## # # A human-readable representation of the element. # # @return [String] A string representation def inspect %(#<Capybara::Node::Element tag="#{base.tag_name}" path="#{base.path}">) rescue NotSupportedByDriverError %(#<Capybara::Node::Element tag="#{base.tag_name}">) rescue *session.driver.invalid_element_errors %(Obsolete #<Capybara::Node::Element>) end # @api private def initial_cache base.respond_to?(:initial_cache) ? base.initial_cache : {} end STYLE_SCRIPT = <<~JS (function(){ var s = window.getComputedStyle(this); var result = {}; for (var i = arguments.length; i--; ) { var property_name = arguments[i]; result[property_name] = s.getPropertyValue(property_name); } return result; }).apply(this, arguments) JS private def perform_click_action(keys, wait: nil, **options) raise ArgumentError, 'You must specify both x: and y: for a click offset' if nil ^ options[:x] ^ options[:y] options[:offset] ||= :center if session_options.w3c_click_offset synchronize(wait) { yield keys, options } self end end end end
Ruby
{ "end_line": 99, "name": "style", "signature": "def style(*styles)", "start_line": 86 }
{ "class_name": "Element", "class_signature": "class Element < < Base", "module": "Capybara" }
scroll_to
capybara/lib/capybara/node/element.rb
def scroll_to(pos_or_el_or_x, y = nil, align: :top, offset: nil) case pos_or_el_or_x when Symbol synchronize { base.scroll_to(nil, pos_or_el_or_x) } unless pos_or_el_or_x == :current when Capybara::Node::Element synchronize { base.scroll_to(pos_or_el_or_x.base, align) } else synchronize { base.scroll_to(nil, nil, [pos_or_el_or_x, y]) } end synchronize { base.scroll_by(*offset) } unless offset.nil? self end
# frozen_string_literal: true module Capybara module Node ## # # A {Capybara::Node::Element} represents a single element on the page. It is possible # to interact with the contents of this element the same as with a document: # # session = Capybara::Session.new(:rack_test, my_app) # # bar = session.find('#bar') # from Capybara::Node::Finders # bar.select('Baz', from: 'Quox') # from Capybara::Node::Actions # # {Capybara::Node::Element} also has access to HTML attributes and other properties of the # element: # # bar.value # bar.text # bar[:title] # # @see Capybara::Node # class Element < Base def initialize(session, base, query_scope, query) super(session, base) @query_scope = query_scope @query = query @allow_reload = false @query_idx = nil end def allow_reload!(idx = nil) @query_idx = idx @allow_reload = true end ## # # @return [Object] The native element from the driver, this allows access to driver specific methods # def native synchronize { base.native } end ## # # Retrieve the text of the element. If {Capybara.configure ignore_hidden_elements} # is `true`, which it is by default, then this will return only text # which is visible. The exact semantics of this may differ between # drivers, but generally any text within elements with `display:none` is # ignored. This behaviour can be overridden by passing `:all` to this # method. # # @param type [:all, :visible] Whether to return only visible or all text # @return [String] The text of the element # def text(type = nil, normalize_ws: false) type ||= :all unless session_options.ignore_hidden_elements || session_options.visible_text_only txt = synchronize { type == :all ? base.all_text : base.visible_text } normalize_ws ? txt.gsub(/[[:space:]]+/, ' ').strip : txt end ## # # Retrieve the given attribute. # # element[:title] # => HTML title attribute # # @param [Symbol] attribute The attribute to retrieve # @return [String] The value of the attribute # def [](attribute) synchronize { base[attribute] } end ## # # Retrieve the given CSS styles. # # element.style('color', 'font-size') # => Computed values of CSS 'color' and 'font-size' styles # # @param [Array<String>] styles Names of the desired CSS properties # @return [Hash] Hash of the CSS property names to computed values # def style(*styles) styles = styles.flatten.map(&:to_s) raise ArgumentError, 'You must specify at least one CSS style' if styles.empty? begin synchronize { base.style(styles) } rescue NotImplementedError => e begin evaluate_script(STYLE_SCRIPT, *styles) rescue Capybara::NotSupportedByDriverError raise e end end end ## # # @return [String] The value of the form element # def value synchronize { base.value } end ## # # Set the value of the form element to the given value. # # @param [String] value The new value # @param [Hash] options Driver specific options for how to set the value. Take default values from {Capybara.configure default_set_options}. # # @return [Capybara::Node::Element] The element def set(value, **options) if ENV.fetch('CAPYBARA_THOROUGH', nil) && readonly? raise Capybara::ReadOnlyElementError, "Attempt to set readonly element with value: #{value}" end options = session_options.default_set_options.to_h.merge(options) synchronize { base.set(value, **options) } self end ## # # Select this node if it is an option element inside a select tag. # # @!macro action_waiting_behavior # If the driver dynamic pages (JS) and the element is currently non-interactable, this method will # continuously retry the action until either the element becomes interactable or the maximum # wait time expires. # # @param [false, Numeric] wait # Maximum time to wait for the action to succeed. Defaults to {Capybara.configure default_max_wait_time}. # @return [Capybara::Node::Element] The element def select_option(wait: nil) synchronize(wait) { base.select_option } self end ## # # Unselect this node if it is an option element inside a multiple select tag. # # @macro action_waiting_behavior # @return [Capybara::Node::Element] The element def unselect_option(wait: nil) synchronize(wait) { base.unselect_option } self end ## # # Click the Element. # # @macro action_waiting_behavior # @!macro click_modifiers # Both x: and y: must be specified if an offset is wanted, if not specified the click will occur at the middle of the element. # @overload $0(*modifier_keys, wait: nil, **offset) # @param *modifier_keys [:alt, :control, :meta, :shift] ([]) Keys to be held down when clicking # @option options [Integer] x X coordinate to offset the click location. If {Capybara.configure w3c_click_offset} is `true` the # offset will be from the element center, otherwise it will be from the top left corner of the element # @option options [Integer] y Y coordinate to offset the click location. If {Capybara.configure w3c_click_offset} is `true` the # offset will be from the element center, otherwise it will be from the top left corner of the element # @option options [Float] delay Delay between the mouse down and mouse up events in seconds (0) # @return [Capybara::Node::Element] The element def click(*keys, **options) perform_click_action(keys, **options) do |k, opts| base.click(k, **opts) end end ## # # Right Click the Element. # # @macro action_waiting_behavior # @macro click_modifiers # @option options [Float] delay Delay between the mouse down and mouse up events in seconds (0) # @return [Capybara::Node::Element] The element def right_click(*keys, **options) perform_click_action(keys, **options) do |k, opts| base.right_click(k, **opts) end end ## # # Double Click the Element. # # @macro action_waiting_behavior # @macro click_modifiers # @return [Capybara::Node::Element] The element def double_click(*keys, **options) perform_click_action(keys, **options) do |k, opts| base.double_click(k, **opts) end end ## # # Send Keystrokes to the Element. # # @overload send_keys(keys, ...) # @param keys [String, Symbol, Array<String,Symbol>] # # Examples: # # element.send_keys "foo" #=> value: 'foo' # element.send_keys "tet", :left, "s" #=> value: 'test' # element.send_keys [:control, 'a'], :space #=> value: ' ' - assuming ctrl-a selects all contents # # Symbols supported for keys: # * :cancel # * :help # * :backspace # * :tab # * :clear # * :return # * :enter # * :shift # * :control # * :alt # * :pause # * :escape # * :space # * :page_up # * :page_down # * :end # * :home # * :left # * :up # * :right # * :down # * :insert # * :delete # * :semicolon # * :equals # * :numpad0 # * :numpad1 # * :numpad2 # * :numpad3 # * :numpad4 # * :numpad5 # * :numpad6 # * :numpad7 # * :numpad8 # * :numpad9 # * :multiply - numeric keypad * # * :add - numeric keypad + # * :separator - numeric keypad 'separator' key ?? # * :subtract - numeric keypad - # * :decimal - numeric keypad . # * :divide - numeric keypad / # * :f1 # * :f2 # * :f3 # * :f4 # * :f5 # * :f6 # * :f7 # * :f8 # * :f9 # * :f10 # * :f11 # * :f12 # * :meta # * :command - alias of :meta # # @return [Capybara::Node::Element] The element def send_keys(*args) synchronize { base.send_keys(*args) } self end ## # # Hover on the Element. # # @return [Capybara::Node::Element] The element def hover synchronize { base.hover } self end ## # # @return [String] The tag name of the element # def tag_name # Element type is immutable so cache it @tag_name ||= initial_cache[:tag_name] || synchronize { base.tag_name } end ## # # Whether or not the element is visible. Not all drivers support CSS, so # the result may be inaccurate. # # @return [Boolean] Whether the element is visible # def visible? synchronize { base.visible? } end ## # # Whether or not the element is currently in the viewport and it (or descendants) # would be considered clickable at the elements center point. # # @return [Boolean] Whether the elements center is obscured. # def obscured? synchronize { base.obscured? } end ## # # Whether or not the element is checked. # # @return [Boolean] Whether the element is checked # def checked? synchronize { base.checked? } end ## # # Whether or not the element is selected. # # @return [Boolean] Whether the element is selected # def selected? synchronize { base.selected? } end ## # # Whether or not the element is disabled. # # @return [Boolean] Whether the element is disabled # def disabled? synchronize { base.disabled? } end ## # # Whether or not the element is readonly. # # @return [Boolean] Whether the element is readonly # def readonly? synchronize { base.readonly? } end ## # # Whether or not the element supports multiple results. # # @return [Boolean] Whether the element supports multiple results. # def multiple? synchronize { base.multiple? } end ## # # An XPath expression describing where on the page the element can be found. # # @return [String] An XPath expression # def path synchronize { base.path } end def rect synchronize { base.rect } end ## # # Trigger any event on the current element, for example mouseover or focus # events. Not supported with the Selenium driver, and SHOULDN'T BE USED IN TESTING unless you # fully understand why you're using it, that it can allow actions a user could never # perform, and that it may completely invalidate your test. # # @param [String] event The name of the event to trigger # # @return [Capybara::Node::Element] The element def trigger(event) synchronize { base.trigger(event) } self end ## # # Drag the element to the given other element. # # source = page.find('#foo') # target = page.find('#bar') # source.drag_to(target) # # @param [Capybara::Node::Element] node The element to drag to # @param [Hash] options Driver specific options for dragging. May not be supported by all drivers. # @option options [Numeric] :delay (0.05) When using Chrome/Firefox with Selenium and HTML5 dragging this is the number # of seconds between each stage of the drag. # @option options [Boolean] :html5 When using Chrome/Firefox with Selenium enables to force the use of HTML5 # (true) or legacy (false) dragging. If not specified the driver will attempt to # detect the correct method to use. # @option options [Array<Symbol>,Symbol] :drop_modifiers Modifier keys which should be held while the dragged element is dropped. # # # @return [Capybara::Node::Element] The dragged element def drag_to(node, **options) synchronize { base.drag_to(node.base, **options) } self end ## # # Drop items on the current element. # # target = page.find('#foo') # target.drop('/some/path/file.csv') # # @overload drop(path, ...) # @param [String, #to_path] path Location of the file to drop on the element # # @overload drop(strings, ...) # @param [Hash] strings A hash of type to data to be dropped - `{ "text/url" => "https://www.google.com" }` # # @return [Capybara::Node::Element] The element def drop(*args) options = args.map { |arg| arg.respond_to?(:to_path) ? arg.to_path : arg } synchronize { base.drop(*options) } self end ## # # Scroll the page or element. # # @overload scroll_to(position, offset: [0,0]) # Scroll the page or element to its top, bottom or middle. # @param [:top, :bottom, :center, :current] position # @param [[Integer, Integer]] offset # # @overload scroll_to(element, align: :top) # Scroll the page or current element until the given element is aligned at the top, bottom, or center of it. # @param [Capybara::Node::Element] element The element to be scrolled into view # @param [:top, :bottom, :center] align Where to align the element being scrolled into view with relation to the current page/element if possible # # @overload scroll_to(x,y) # @param [Integer] x Horizontal scroll offset # @param [Integer] y Vertical scroll offset # # @return [Capybara::Node::Element] The element def scroll_to(pos_or_el_or_x, y = nil, align: :top, offset: nil) case pos_or_el_or_x when Symbol synchronize { base.scroll_to(nil, pos_or_el_or_x) } unless pos_or_el_or_x == :current when Capybara::Node::Element synchronize { base.scroll_to(pos_or_el_or_x.base, align) } else synchronize { base.scroll_to(nil, nil, [pos_or_el_or_x, y]) } end synchronize { base.scroll_by(*offset) } unless offset.nil? self end ## # # Return the shadow_root for the current element # # @return [Capybara::Node::Element] The shadow root def shadow_root root = synchronize { base.shadow_root } root && Capybara::Node::Element.new(session, root, nil, nil) end ## # # Execute the given JS in the context of the element not returning a result. This is useful for scripts that return # complex objects, such as jQuery statements. {#execute_script} should be used over # {#evaluate_script} whenever a result is not expected or needed. `this` in the script will refer to the element this is called on. # # @param [String] script A string of JavaScript to execute # @param args Optional arguments that will be passed to the script. Driver support for this is optional and types of objects supported may differ between drivers # def execute_script(script, *args) session.execute_script(<<~JS, self, *args) (function (){ #{script} }).apply(arguments[0], Array.prototype.slice.call(arguments,1)); JS end ## # # Evaluate the given JS in the context of the element and return the result. Be careful when using this with # scripts that return complex objects, such as jQuery statements. {#execute_script} might # be a better alternative. `this` in the script will refer to the element this is called on. # # @param [String] script A string of JavaScript to evaluate # @return [Object] The result of the evaluated JavaScript (may be driver specific) # def evaluate_script(script, *args) session.evaluate_script(<<~JS, self, *args) (function(){ return #{script.strip} }).apply(arguments[0], Array.prototype.slice.call(arguments,1)); JS end ## # # Evaluate the given JavaScript in the context of the element and obtain the result from a # callback function which will be passed as the last argument to the script. `this` in the # script will refer to the element this is called on. # # @param [String] script A string of JavaScript to evaluate # @return [Object] The result of the evaluated JavaScript (may be driver specific) # def evaluate_async_script(script, *args) session.evaluate_async_script(<<~JS, self, *args) (function (){ #{script} }).apply(arguments[0], Array.prototype.slice.call(arguments,1)); JS end ## # # Toggle the elements background color between white and black for a period of time. # # @return [Capybara::Node::Element] The element def flash execute_script(<<~JS, 100) async function flash(el, delay){ var old_bg = el.style.backgroundColor; var colors = ["black", "white"]; for(var i=0; i<20; i++){ el.style.backgroundColor = colors[i % colors.length]; await new Promise(resolve => setTimeout(resolve, delay)); } el.style.backgroundColor = old_bg; } flash(this, arguments[0]); JS self end # @api private def reload return self unless @allow_reload begin reloaded = @query.resolve_for(query_scope ? query_scope.reload : session)[@query_idx.to_i] @base = reloaded.base if reloaded rescue StandardError => e raise e unless catch_error?(e) end self end ## # # A human-readable representation of the element. # # @return [String] A string representation def inspect %(#<Capybara::Node::Element tag="#{base.tag_name}" path="#{base.path}">) rescue NotSupportedByDriverError %(#<Capybara::Node::Element tag="#{base.tag_name}">) rescue *session.driver.invalid_element_errors %(Obsolete #<Capybara::Node::Element>) end # @api private def initial_cache base.respond_to?(:initial_cache) ? base.initial_cache : {} end STYLE_SCRIPT = <<~JS (function(){ var s = window.getComputedStyle(this); var result = {}; for (var i = arguments.length; i--; ) { var property_name = arguments[i]; result[property_name] = s.getPropertyValue(property_name); } return result; }).apply(this, arguments) JS private def perform_click_action(keys, wait: nil, **options) raise ArgumentError, 'You must specify both x: and y: for a click offset' if nil ^ options[:x] ^ options[:y] options[:offset] ||= :center if session_options.w3c_click_offset synchronize(wait) { yield keys, options } self end end end end
Ruby
{ "end_line": 473, "name": "scroll_to", "signature": "def scroll_to(pos_or_el_or_x, y = nil, align: :top, offset: nil)", "start_line": 462 }
{ "class_name": "Element", "class_signature": "class Element < < Base", "module": "Capybara" }
flash
capybara/lib/capybara/node/element.rb
def flash execute_script(<<~JS, 100) async function flash(el, delay){ var old_bg = el.style.backgroundColor; var colors = ["black", "white"]; for(var i=0; i<20; i++){ el.style.backgroundColor = colors[i % colors.length]; await new Promise(resolve => setTimeout(resolve, delay)); } el.style.backgroundColor = old_bg; } flash(this, arguments[0]); JS self end
# frozen_string_literal: true module Capybara module Node ## # # A {Capybara::Node::Element} represents a single element on the page. It is possible # to interact with the contents of this element the same as with a document: # # session = Capybara::Session.new(:rack_test, my_app) # # bar = session.find('#bar') # from Capybara::Node::Finders # bar.select('Baz', from: 'Quox') # from Capybara::Node::Actions # # {Capybara::Node::Element} also has access to HTML attributes and other properties of the # element: # # bar.value # bar.text # bar[:title] # # @see Capybara::Node # class Element < Base def initialize(session, base, query_scope, query) super(session, base) @query_scope = query_scope @query = query @allow_reload = false @query_idx = nil end def allow_reload!(idx = nil) @query_idx = idx @allow_reload = true end ## # # @return [Object] The native element from the driver, this allows access to driver specific methods # def native synchronize { base.native } end ## # # Retrieve the text of the element. If {Capybara.configure ignore_hidden_elements} # is `true`, which it is by default, then this will return only text # which is visible. The exact semantics of this may differ between # drivers, but generally any text within elements with `display:none` is # ignored. This behaviour can be overridden by passing `:all` to this # method. # # @param type [:all, :visible] Whether to return only visible or all text # @return [String] The text of the element # def text(type = nil, normalize_ws: false) type ||= :all unless session_options.ignore_hidden_elements || session_options.visible_text_only txt = synchronize { type == :all ? base.all_text : base.visible_text } normalize_ws ? txt.gsub(/[[:space:]]+/, ' ').strip : txt end ## # # Retrieve the given attribute. # # element[:title] # => HTML title attribute # # @param [Symbol] attribute The attribute to retrieve # @return [String] The value of the attribute # def [](attribute) synchronize { base[attribute] } end ## # # Retrieve the given CSS styles. # # element.style('color', 'font-size') # => Computed values of CSS 'color' and 'font-size' styles # # @param [Array<String>] styles Names of the desired CSS properties # @return [Hash] Hash of the CSS property names to computed values # def style(*styles) styles = styles.flatten.map(&:to_s) raise ArgumentError, 'You must specify at least one CSS style' if styles.empty? begin synchronize { base.style(styles) } rescue NotImplementedError => e begin evaluate_script(STYLE_SCRIPT, *styles) rescue Capybara::NotSupportedByDriverError raise e end end end ## # # @return [String] The value of the form element # def value synchronize { base.value } end ## # # Set the value of the form element to the given value. # # @param [String] value The new value # @param [Hash] options Driver specific options for how to set the value. Take default values from {Capybara.configure default_set_options}. # # @return [Capybara::Node::Element] The element def set(value, **options) if ENV.fetch('CAPYBARA_THOROUGH', nil) && readonly? raise Capybara::ReadOnlyElementError, "Attempt to set readonly element with value: #{value}" end options = session_options.default_set_options.to_h.merge(options) synchronize { base.set(value, **options) } self end ## # # Select this node if it is an option element inside a select tag. # # @!macro action_waiting_behavior # If the driver dynamic pages (JS) and the element is currently non-interactable, this method will # continuously retry the action until either the element becomes interactable or the maximum # wait time expires. # # @param [false, Numeric] wait # Maximum time to wait for the action to succeed. Defaults to {Capybara.configure default_max_wait_time}. # @return [Capybara::Node::Element] The element def select_option(wait: nil) synchronize(wait) { base.select_option } self end ## # # Unselect this node if it is an option element inside a multiple select tag. # # @macro action_waiting_behavior # @return [Capybara::Node::Element] The element def unselect_option(wait: nil) synchronize(wait) { base.unselect_option } self end ## # # Click the Element. # # @macro action_waiting_behavior # @!macro click_modifiers # Both x: and y: must be specified if an offset is wanted, if not specified the click will occur at the middle of the element. # @overload $0(*modifier_keys, wait: nil, **offset) # @param *modifier_keys [:alt, :control, :meta, :shift] ([]) Keys to be held down when clicking # @option options [Integer] x X coordinate to offset the click location. If {Capybara.configure w3c_click_offset} is `true` the # offset will be from the element center, otherwise it will be from the top left corner of the element # @option options [Integer] y Y coordinate to offset the click location. If {Capybara.configure w3c_click_offset} is `true` the # offset will be from the element center, otherwise it will be from the top left corner of the element # @option options [Float] delay Delay between the mouse down and mouse up events in seconds (0) # @return [Capybara::Node::Element] The element def click(*keys, **options) perform_click_action(keys, **options) do |k, opts| base.click(k, **opts) end end ## # # Right Click the Element. # # @macro action_waiting_behavior # @macro click_modifiers # @option options [Float] delay Delay between the mouse down and mouse up events in seconds (0) # @return [Capybara::Node::Element] The element def right_click(*keys, **options) perform_click_action(keys, **options) do |k, opts| base.right_click(k, **opts) end end ## # # Double Click the Element. # # @macro action_waiting_behavior # @macro click_modifiers # @return [Capybara::Node::Element] The element def double_click(*keys, **options) perform_click_action(keys, **options) do |k, opts| base.double_click(k, **opts) end end ## # # Send Keystrokes to the Element. # # @overload send_keys(keys, ...) # @param keys [String, Symbol, Array<String,Symbol>] # # Examples: # # element.send_keys "foo" #=> value: 'foo' # element.send_keys "tet", :left, "s" #=> value: 'test' # element.send_keys [:control, 'a'], :space #=> value: ' ' - assuming ctrl-a selects all contents # # Symbols supported for keys: # * :cancel # * :help # * :backspace # * :tab # * :clear # * :return # * :enter # * :shift # * :control # * :alt # * :pause # * :escape # * :space # * :page_up # * :page_down # * :end # * :home # * :left # * :up # * :right # * :down # * :insert # * :delete # * :semicolon # * :equals # * :numpad0 # * :numpad1 # * :numpad2 # * :numpad3 # * :numpad4 # * :numpad5 # * :numpad6 # * :numpad7 # * :numpad8 # * :numpad9 # * :multiply - numeric keypad * # * :add - numeric keypad + # * :separator - numeric keypad 'separator' key ?? # * :subtract - numeric keypad - # * :decimal - numeric keypad . # * :divide - numeric keypad / # * :f1 # * :f2 # * :f3 # * :f4 # * :f5 # * :f6 # * :f7 # * :f8 # * :f9 # * :f10 # * :f11 # * :f12 # * :meta # * :command - alias of :meta # # @return [Capybara::Node::Element] The element def send_keys(*args) synchronize { base.send_keys(*args) } self end ## # # Hover on the Element. # # @return [Capybara::Node::Element] The element def hover synchronize { base.hover } self end ## # # @return [String] The tag name of the element # def tag_name # Element type is immutable so cache it @tag_name ||= initial_cache[:tag_name] || synchronize { base.tag_name } end ## # # Whether or not the element is visible. Not all drivers support CSS, so # the result may be inaccurate. # # @return [Boolean] Whether the element is visible # def visible? synchronize { base.visible? } end ## # # Whether or not the element is currently in the viewport and it (or descendants) # would be considered clickable at the elements center point. # # @return [Boolean] Whether the elements center is obscured. # def obscured? synchronize { base.obscured? } end ## # # Whether or not the element is checked. # # @return [Boolean] Whether the element is checked # def checked? synchronize { base.checked? } end ## # # Whether or not the element is selected. # # @return [Boolean] Whether the element is selected # def selected? synchronize { base.selected? } end ## # # Whether or not the element is disabled. # # @return [Boolean] Whether the element is disabled # def disabled? synchronize { base.disabled? } end ## # # Whether or not the element is readonly. # # @return [Boolean] Whether the element is readonly # def readonly? synchronize { base.readonly? } end ## # # Whether or not the element supports multiple results. # # @return [Boolean] Whether the element supports multiple results. # def multiple? synchronize { base.multiple? } end ## # # An XPath expression describing where on the page the element can be found. # # @return [String] An XPath expression # def path synchronize { base.path } end def rect synchronize { base.rect } end ## # # Trigger any event on the current element, for example mouseover or focus # events. Not supported with the Selenium driver, and SHOULDN'T BE USED IN TESTING unless you # fully understand why you're using it, that it can allow actions a user could never # perform, and that it may completely invalidate your test. # # @param [String] event The name of the event to trigger # # @return [Capybara::Node::Element] The element def trigger(event) synchronize { base.trigger(event) } self end ## # # Drag the element to the given other element. # # source = page.find('#foo') # target = page.find('#bar') # source.drag_to(target) # # @param [Capybara::Node::Element] node The element to drag to # @param [Hash] options Driver specific options for dragging. May not be supported by all drivers. # @option options [Numeric] :delay (0.05) When using Chrome/Firefox with Selenium and HTML5 dragging this is the number # of seconds between each stage of the drag. # @option options [Boolean] :html5 When using Chrome/Firefox with Selenium enables to force the use of HTML5 # (true) or legacy (false) dragging. If not specified the driver will attempt to # detect the correct method to use. # @option options [Array<Symbol>,Symbol] :drop_modifiers Modifier keys which should be held while the dragged element is dropped. # # # @return [Capybara::Node::Element] The dragged element def drag_to(node, **options) synchronize { base.drag_to(node.base, **options) } self end ## # # Drop items on the current element. # # target = page.find('#foo') # target.drop('/some/path/file.csv') # # @overload drop(path, ...) # @param [String, #to_path] path Location of the file to drop on the element # # @overload drop(strings, ...) # @param [Hash] strings A hash of type to data to be dropped - `{ "text/url" => "https://www.google.com" }` # # @return [Capybara::Node::Element] The element def drop(*args) options = args.map { |arg| arg.respond_to?(:to_path) ? arg.to_path : arg } synchronize { base.drop(*options) } self end ## # # Scroll the page or element. # # @overload scroll_to(position, offset: [0,0]) # Scroll the page or element to its top, bottom or middle. # @param [:top, :bottom, :center, :current] position # @param [[Integer, Integer]] offset # # @overload scroll_to(element, align: :top) # Scroll the page or current element until the given element is aligned at the top, bottom, or center of it. # @param [Capybara::Node::Element] element The element to be scrolled into view # @param [:top, :bottom, :center] align Where to align the element being scrolled into view with relation to the current page/element if possible # # @overload scroll_to(x,y) # @param [Integer] x Horizontal scroll offset # @param [Integer] y Vertical scroll offset # # @return [Capybara::Node::Element] The element def scroll_to(pos_or_el_or_x, y = nil, align: :top, offset: nil) case pos_or_el_or_x when Symbol synchronize { base.scroll_to(nil, pos_or_el_or_x) } unless pos_or_el_or_x == :current when Capybara::Node::Element synchronize { base.scroll_to(pos_or_el_or_x.base, align) } else synchronize { base.scroll_to(nil, nil, [pos_or_el_or_x, y]) } end synchronize { base.scroll_by(*offset) } unless offset.nil? self end ## # # Return the shadow_root for the current element # # @return [Capybara::Node::Element] The shadow root def shadow_root root = synchronize { base.shadow_root } root && Capybara::Node::Element.new(session, root, nil, nil) end ## # # Execute the given JS in the context of the element not returning a result. This is useful for scripts that return # complex objects, such as jQuery statements. {#execute_script} should be used over # {#evaluate_script} whenever a result is not expected or needed. `this` in the script will refer to the element this is called on. # # @param [String] script A string of JavaScript to execute # @param args Optional arguments that will be passed to the script. Driver support for this is optional and types of objects supported may differ between drivers # def execute_script(script, *args) session.execute_script(<<~JS, self, *args) (function (){ #{script} }).apply(arguments[0], Array.prototype.slice.call(arguments,1)); JS end ## # # Evaluate the given JS in the context of the element and return the result. Be careful when using this with # scripts that return complex objects, such as jQuery statements. {#execute_script} might # be a better alternative. `this` in the script will refer to the element this is called on. # # @param [String] script A string of JavaScript to evaluate # @return [Object] The result of the evaluated JavaScript (may be driver specific) # def evaluate_script(script, *args) session.evaluate_script(<<~JS, self, *args) (function(){ return #{script.strip} }).apply(arguments[0], Array.prototype.slice.call(arguments,1)); JS end ## # # Evaluate the given JavaScript in the context of the element and obtain the result from a # callback function which will be passed as the last argument to the script. `this` in the # script will refer to the element this is called on. # # @param [String] script A string of JavaScript to evaluate # @return [Object] The result of the evaluated JavaScript (may be driver specific) # def evaluate_async_script(script, *args) session.evaluate_async_script(<<~JS, self, *args) (function (){ #{script} }).apply(arguments[0], Array.prototype.slice.call(arguments,1)); JS end ## # # Toggle the elements background color between white and black for a period of time. # # @return [Capybara::Node::Element] The element def flash execute_script(<<~JS, 100) async function flash(el, delay){ var old_bg = el.style.backgroundColor; var colors = ["black", "white"]; for(var i=0; i<20; i++){ el.style.backgroundColor = colors[i % colors.length]; await new Promise(resolve => setTimeout(resolve, delay)); } el.style.backgroundColor = old_bg; } flash(this, arguments[0]); JS self end # @api private def reload return self unless @allow_reload begin reloaded = @query.resolve_for(query_scope ? query_scope.reload : session)[@query_idx.to_i] @base = reloaded.base if reloaded rescue StandardError => e raise e unless catch_error?(e) end self end ## # # A human-readable representation of the element. # # @return [String] A string representation def inspect %(#<Capybara::Node::Element tag="#{base.tag_name}" path="#{base.path}">) rescue NotSupportedByDriverError %(#<Capybara::Node::Element tag="#{base.tag_name}">) rescue *session.driver.invalid_element_errors %(Obsolete #<Capybara::Node::Element>) end # @api private def initial_cache base.respond_to?(:initial_cache) ? base.initial_cache : {} end STYLE_SCRIPT = <<~JS (function(){ var s = window.getComputedStyle(this); var result = {}; for (var i = arguments.length; i--; ) { var property_name = arguments[i]; result[property_name] = s.getPropertyValue(property_name); } return result; }).apply(this, arguments) JS private def perform_click_action(keys, wait: nil, **options) raise ArgumentError, 'You must specify both x: and y: for a click offset' if nil ^ options[:x] ^ options[:y] options[:offset] ||= :center if session_options.w3c_click_offset synchronize(wait) { yield keys, options } self end end end end
Ruby
{ "end_line": 557, "name": "flash", "signature": "def flash", "start_line": 542 }
{ "class_name": "Element", "class_signature": "class Element < < Base", "module": "Capybara" }
reload
capybara/lib/capybara/node/element.rb
def reload return self unless @allow_reload begin reloaded = @query.resolve_for(query_scope ? query_scope.reload : session)[@query_idx.to_i] @base = reloaded.base if reloaded rescue StandardError => e raise e unless catch_error?(e) end self end
# frozen_string_literal: true module Capybara module Node ## # # A {Capybara::Node::Element} represents a single element on the page. It is possible # to interact with the contents of this element the same as with a document: # # session = Capybara::Session.new(:rack_test, my_app) # # bar = session.find('#bar') # from Capybara::Node::Finders # bar.select('Baz', from: 'Quox') # from Capybara::Node::Actions # # {Capybara::Node::Element} also has access to HTML attributes and other properties of the # element: # # bar.value # bar.text # bar[:title] # # @see Capybara::Node # class Element < Base def initialize(session, base, query_scope, query) super(session, base) @query_scope = query_scope @query = query @allow_reload = false @query_idx = nil end def allow_reload!(idx = nil) @query_idx = idx @allow_reload = true end ## # # @return [Object] The native element from the driver, this allows access to driver specific methods # def native synchronize { base.native } end ## # # Retrieve the text of the element. If {Capybara.configure ignore_hidden_elements} # is `true`, which it is by default, then this will return only text # which is visible. The exact semantics of this may differ between # drivers, but generally any text within elements with `display:none` is # ignored. This behaviour can be overridden by passing `:all` to this # method. # # @param type [:all, :visible] Whether to return only visible or all text # @return [String] The text of the element # def text(type = nil, normalize_ws: false) type ||= :all unless session_options.ignore_hidden_elements || session_options.visible_text_only txt = synchronize { type == :all ? base.all_text : base.visible_text } normalize_ws ? txt.gsub(/[[:space:]]+/, ' ').strip : txt end ## # # Retrieve the given attribute. # # element[:title] # => HTML title attribute # # @param [Symbol] attribute The attribute to retrieve # @return [String] The value of the attribute # def [](attribute) synchronize { base[attribute] } end ## # # Retrieve the given CSS styles. # # element.style('color', 'font-size') # => Computed values of CSS 'color' and 'font-size' styles # # @param [Array<String>] styles Names of the desired CSS properties # @return [Hash] Hash of the CSS property names to computed values # def style(*styles) styles = styles.flatten.map(&:to_s) raise ArgumentError, 'You must specify at least one CSS style' if styles.empty? begin synchronize { base.style(styles) } rescue NotImplementedError => e begin evaluate_script(STYLE_SCRIPT, *styles) rescue Capybara::NotSupportedByDriverError raise e end end end ## # # @return [String] The value of the form element # def value synchronize { base.value } end ## # # Set the value of the form element to the given value. # # @param [String] value The new value # @param [Hash] options Driver specific options for how to set the value. Take default values from {Capybara.configure default_set_options}. # # @return [Capybara::Node::Element] The element def set(value, **options) if ENV.fetch('CAPYBARA_THOROUGH', nil) && readonly? raise Capybara::ReadOnlyElementError, "Attempt to set readonly element with value: #{value}" end options = session_options.default_set_options.to_h.merge(options) synchronize { base.set(value, **options) } self end ## # # Select this node if it is an option element inside a select tag. # # @!macro action_waiting_behavior # If the driver dynamic pages (JS) and the element is currently non-interactable, this method will # continuously retry the action until either the element becomes interactable or the maximum # wait time expires. # # @param [false, Numeric] wait # Maximum time to wait for the action to succeed. Defaults to {Capybara.configure default_max_wait_time}. # @return [Capybara::Node::Element] The element def select_option(wait: nil) synchronize(wait) { base.select_option } self end ## # # Unselect this node if it is an option element inside a multiple select tag. # # @macro action_waiting_behavior # @return [Capybara::Node::Element] The element def unselect_option(wait: nil) synchronize(wait) { base.unselect_option } self end ## # # Click the Element. # # @macro action_waiting_behavior # @!macro click_modifiers # Both x: and y: must be specified if an offset is wanted, if not specified the click will occur at the middle of the element. # @overload $0(*modifier_keys, wait: nil, **offset) # @param *modifier_keys [:alt, :control, :meta, :shift] ([]) Keys to be held down when clicking # @option options [Integer] x X coordinate to offset the click location. If {Capybara.configure w3c_click_offset} is `true` the # offset will be from the element center, otherwise it will be from the top left corner of the element # @option options [Integer] y Y coordinate to offset the click location. If {Capybara.configure w3c_click_offset} is `true` the # offset will be from the element center, otherwise it will be from the top left corner of the element # @option options [Float] delay Delay between the mouse down and mouse up events in seconds (0) # @return [Capybara::Node::Element] The element def click(*keys, **options) perform_click_action(keys, **options) do |k, opts| base.click(k, **opts) end end ## # # Right Click the Element. # # @macro action_waiting_behavior # @macro click_modifiers # @option options [Float] delay Delay between the mouse down and mouse up events in seconds (0) # @return [Capybara::Node::Element] The element def right_click(*keys, **options) perform_click_action(keys, **options) do |k, opts| base.right_click(k, **opts) end end ## # # Double Click the Element. # # @macro action_waiting_behavior # @macro click_modifiers # @return [Capybara::Node::Element] The element def double_click(*keys, **options) perform_click_action(keys, **options) do |k, opts| base.double_click(k, **opts) end end ## # # Send Keystrokes to the Element. # # @overload send_keys(keys, ...) # @param keys [String, Symbol, Array<String,Symbol>] # # Examples: # # element.send_keys "foo" #=> value: 'foo' # element.send_keys "tet", :left, "s" #=> value: 'test' # element.send_keys [:control, 'a'], :space #=> value: ' ' - assuming ctrl-a selects all contents # # Symbols supported for keys: # * :cancel # * :help # * :backspace # * :tab # * :clear # * :return # * :enter # * :shift # * :control # * :alt # * :pause # * :escape # * :space # * :page_up # * :page_down # * :end # * :home # * :left # * :up # * :right # * :down # * :insert # * :delete # * :semicolon # * :equals # * :numpad0 # * :numpad1 # * :numpad2 # * :numpad3 # * :numpad4 # * :numpad5 # * :numpad6 # * :numpad7 # * :numpad8 # * :numpad9 # * :multiply - numeric keypad * # * :add - numeric keypad + # * :separator - numeric keypad 'separator' key ?? # * :subtract - numeric keypad - # * :decimal - numeric keypad . # * :divide - numeric keypad / # * :f1 # * :f2 # * :f3 # * :f4 # * :f5 # * :f6 # * :f7 # * :f8 # * :f9 # * :f10 # * :f11 # * :f12 # * :meta # * :command - alias of :meta # # @return [Capybara::Node::Element] The element def send_keys(*args) synchronize { base.send_keys(*args) } self end ## # # Hover on the Element. # # @return [Capybara::Node::Element] The element def hover synchronize { base.hover } self end ## # # @return [String] The tag name of the element # def tag_name # Element type is immutable so cache it @tag_name ||= initial_cache[:tag_name] || synchronize { base.tag_name } end ## # # Whether or not the element is visible. Not all drivers support CSS, so # the result may be inaccurate. # # @return [Boolean] Whether the element is visible # def visible? synchronize { base.visible? } end ## # # Whether or not the element is currently in the viewport and it (or descendants) # would be considered clickable at the elements center point. # # @return [Boolean] Whether the elements center is obscured. # def obscured? synchronize { base.obscured? } end ## # # Whether or not the element is checked. # # @return [Boolean] Whether the element is checked # def checked? synchronize { base.checked? } end ## # # Whether or not the element is selected. # # @return [Boolean] Whether the element is selected # def selected? synchronize { base.selected? } end ## # # Whether or not the element is disabled. # # @return [Boolean] Whether the element is disabled # def disabled? synchronize { base.disabled? } end ## # # Whether or not the element is readonly. # # @return [Boolean] Whether the element is readonly # def readonly? synchronize { base.readonly? } end ## # # Whether or not the element supports multiple results. # # @return [Boolean] Whether the element supports multiple results. # def multiple? synchronize { base.multiple? } end ## # # An XPath expression describing where on the page the element can be found. # # @return [String] An XPath expression # def path synchronize { base.path } end def rect synchronize { base.rect } end ## # # Trigger any event on the current element, for example mouseover or focus # events. Not supported with the Selenium driver, and SHOULDN'T BE USED IN TESTING unless you # fully understand why you're using it, that it can allow actions a user could never # perform, and that it may completely invalidate your test. # # @param [String] event The name of the event to trigger # # @return [Capybara::Node::Element] The element def trigger(event) synchronize { base.trigger(event) } self end ## # # Drag the element to the given other element. # # source = page.find('#foo') # target = page.find('#bar') # source.drag_to(target) # # @param [Capybara::Node::Element] node The element to drag to # @param [Hash] options Driver specific options for dragging. May not be supported by all drivers. # @option options [Numeric] :delay (0.05) When using Chrome/Firefox with Selenium and HTML5 dragging this is the number # of seconds between each stage of the drag. # @option options [Boolean] :html5 When using Chrome/Firefox with Selenium enables to force the use of HTML5 # (true) or legacy (false) dragging. If not specified the driver will attempt to # detect the correct method to use. # @option options [Array<Symbol>,Symbol] :drop_modifiers Modifier keys which should be held while the dragged element is dropped. # # # @return [Capybara::Node::Element] The dragged element def drag_to(node, **options) synchronize { base.drag_to(node.base, **options) } self end ## # # Drop items on the current element. # # target = page.find('#foo') # target.drop('/some/path/file.csv') # # @overload drop(path, ...) # @param [String, #to_path] path Location of the file to drop on the element # # @overload drop(strings, ...) # @param [Hash] strings A hash of type to data to be dropped - `{ "text/url" => "https://www.google.com" }` # # @return [Capybara::Node::Element] The element def drop(*args) options = args.map { |arg| arg.respond_to?(:to_path) ? arg.to_path : arg } synchronize { base.drop(*options) } self end ## # # Scroll the page or element. # # @overload scroll_to(position, offset: [0,0]) # Scroll the page or element to its top, bottom or middle. # @param [:top, :bottom, :center, :current] position # @param [[Integer, Integer]] offset # # @overload scroll_to(element, align: :top) # Scroll the page or current element until the given element is aligned at the top, bottom, or center of it. # @param [Capybara::Node::Element] element The element to be scrolled into view # @param [:top, :bottom, :center] align Where to align the element being scrolled into view with relation to the current page/element if possible # # @overload scroll_to(x,y) # @param [Integer] x Horizontal scroll offset # @param [Integer] y Vertical scroll offset # # @return [Capybara::Node::Element] The element def scroll_to(pos_or_el_or_x, y = nil, align: :top, offset: nil) case pos_or_el_or_x when Symbol synchronize { base.scroll_to(nil, pos_or_el_or_x) } unless pos_or_el_or_x == :current when Capybara::Node::Element synchronize { base.scroll_to(pos_or_el_or_x.base, align) } else synchronize { base.scroll_to(nil, nil, [pos_or_el_or_x, y]) } end synchronize { base.scroll_by(*offset) } unless offset.nil? self end ## # # Return the shadow_root for the current element # # @return [Capybara::Node::Element] The shadow root def shadow_root root = synchronize { base.shadow_root } root && Capybara::Node::Element.new(session, root, nil, nil) end ## # # Execute the given JS in the context of the element not returning a result. This is useful for scripts that return # complex objects, such as jQuery statements. {#execute_script} should be used over # {#evaluate_script} whenever a result is not expected or needed. `this` in the script will refer to the element this is called on. # # @param [String] script A string of JavaScript to execute # @param args Optional arguments that will be passed to the script. Driver support for this is optional and types of objects supported may differ between drivers # def execute_script(script, *args) session.execute_script(<<~JS, self, *args) (function (){ #{script} }).apply(arguments[0], Array.prototype.slice.call(arguments,1)); JS end ## # # Evaluate the given JS in the context of the element and return the result. Be careful when using this with # scripts that return complex objects, such as jQuery statements. {#execute_script} might # be a better alternative. `this` in the script will refer to the element this is called on. # # @param [String] script A string of JavaScript to evaluate # @return [Object] The result of the evaluated JavaScript (may be driver specific) # def evaluate_script(script, *args) session.evaluate_script(<<~JS, self, *args) (function(){ return #{script.strip} }).apply(arguments[0], Array.prototype.slice.call(arguments,1)); JS end ## # # Evaluate the given JavaScript in the context of the element and obtain the result from a # callback function which will be passed as the last argument to the script. `this` in the # script will refer to the element this is called on. # # @param [String] script A string of JavaScript to evaluate # @return [Object] The result of the evaluated JavaScript (may be driver specific) # def evaluate_async_script(script, *args) session.evaluate_async_script(<<~JS, self, *args) (function (){ #{script} }).apply(arguments[0], Array.prototype.slice.call(arguments,1)); JS end ## # # Toggle the elements background color between white and black for a period of time. # # @return [Capybara::Node::Element] The element def flash execute_script(<<~JS, 100) async function flash(el, delay){ var old_bg = el.style.backgroundColor; var colors = ["black", "white"]; for(var i=0; i<20; i++){ el.style.backgroundColor = colors[i % colors.length]; await new Promise(resolve => setTimeout(resolve, delay)); } el.style.backgroundColor = old_bg; } flash(this, arguments[0]); JS self end # @api private def reload return self unless @allow_reload begin reloaded = @query.resolve_for(query_scope ? query_scope.reload : session)[@query_idx.to_i] @base = reloaded.base if reloaded rescue StandardError => e raise e unless catch_error?(e) end self end ## # # A human-readable representation of the element. # # @return [String] A string representation def inspect %(#<Capybara::Node::Element tag="#{base.tag_name}" path="#{base.path}">) rescue NotSupportedByDriverError %(#<Capybara::Node::Element tag="#{base.tag_name}">) rescue *session.driver.invalid_element_errors %(Obsolete #<Capybara::Node::Element>) end # @api private def initial_cache base.respond_to?(:initial_cache) ? base.initial_cache : {} end STYLE_SCRIPT = <<~JS (function(){ var s = window.getComputedStyle(this); var result = {}; for (var i = arguments.length; i--; ) { var property_name = arguments[i]; result[property_name] = s.getPropertyValue(property_name); } return result; }).apply(this, arguments) JS private def perform_click_action(keys, wait: nil, **options) raise ArgumentError, 'You must specify both x: and y: for a click offset' if nil ^ options[:x] ^ options[:y] options[:offset] ||= :center if session_options.w3c_click_offset synchronize(wait) { yield keys, options } self end end end end
Ruby
{ "end_line": 570, "name": "reload", "signature": "def reload", "start_line": 560 }
{ "class_name": "Element", "class_signature": "class Element < < Base", "module": "Capybara" }
find
capybara/lib/capybara/node/finders.rb
def find(*args, **options, &optional_filter_block) options[:session_options] = session_options count_options = options.slice(*Capybara::Queries::BaseQuery::COUNT_KEYS) unless count_options.empty? Capybara::Helpers.warn( "'find' does not support count options (#{count_options}) ignoring. " \ "Called from: #{Capybara::Helpers.filter_backtrace(caller)}" ) end synced_resolve Capybara::Queries::SelectorQuery.new(*args, **options, &optional_filter_block) end
# frozen_string_literal: true module Capybara module Node module Finders ## # # Find an {Capybara::Node::Element} based on the given arguments. {#find} will raise an error if the element # is not found. # # page.find('#foo').find('.bar') # page.find(:xpath, './/div[contains(., "bar")]') # page.find('li', text: 'Quox').click_link('Delete') # # @param (see #all) # # @macro waiting_behavior # # @!macro system_filters # @option options [String, Regexp] text Only find elements which contain this text or match this regexp # @option options [String, Regexp, String] exact_text # When String the elements contained text must match exactly, when Boolean controls whether the `text` option must match exactly. # Defaults to {Capybara.configure exact_text}. # @option options [Boolean] normalize_ws # Whether the `text`/`exact_text` options are compared against element text with whitespace normalized or as returned by the driver. # Defaults to {Capybara.configure default_normalize_ws}. # @option options [Boolean, Symbol] visible # Only find elements with the specified visibility. Defaults to behavior indicated by {Capybara.configure ignore_hidden_elements}. # * true - only finds visible elements. # * false - finds invisible _and_ visible elements. # * :all - same as false; finds visible and invisible elements. # * :hidden - only finds invisible elements. # * :visible - same as true; only finds visible elements. # @option options [Boolean] obscured Only find elements with the specified obscured state: # * true - only find elements whose centerpoint is not in the viewport or is obscured by another non-descendant element. # * false - only find elements whose centerpoint is in the viewport and is not obscured by other non-descendant elements. # @option options [String, Regexp] id Only find elements with an id that matches the value passed # @option options [String, Array<String>, Regexp] class Only find elements with matching class/classes. # * Absence of a class can be checked by prefixing the class name with `!` # * If you need to check for existence of a class name that starts with `!` then prefix with `!!` # # class:['a', '!b', '!!!c'] # limit to elements with class 'a' and '!c' but not class 'b' # # @option options [String, Regexp, Hash] style Only find elements with matching style. String and Regexp will be checked against text of the elements `style` attribute, while a Hash will be compared against the elements full style # @option options [Boolean] exact Control whether `is` expressions in the given XPath match exactly or partially. Defaults to {Capybara.configure exact}. # @option options [Symbol] match The matching strategy to use. Defaults to {Capybara.configure match}. # # @return [Capybara::Node::Element] The found element # @raise [Capybara::ElementNotFound] If the element can't be found before time expires # def find(*args, **options, &optional_filter_block) options[:session_options] = session_options count_options = options.slice(*Capybara::Queries::BaseQuery::COUNT_KEYS) unless count_options.empty? Capybara::Helpers.warn( "'find' does not support count options (#{count_options}) ignoring. " \ "Called from: #{Capybara::Helpers.filter_backtrace(caller)}" ) end synced_resolve Capybara::Queries::SelectorQuery.new(*args, **options, &optional_filter_block) end ## # # Find an {Capybara::Node::Element} based on the given arguments that is also an ancestor of the element called on. # {#ancestor} will raise an error if the element is not found. # # {#ancestor} takes the same options as {#find}. # # element.ancestor('#foo').find('.bar') # element.ancestor(:xpath, './/div[contains(., "bar")]') # element.ancestor('ul', text: 'Quox').click_link('Delete') # # @param (see #find) # # @macro waiting_behavior # # @return [Capybara::Node::Element] The found element # @raise [Capybara::ElementNotFound] If the element can't be found before time expires # def ancestor(*args, **options, &optional_filter_block) options[:session_options] = session_options synced_resolve Capybara::Queries::AncestorQuery.new(*args, **options, &optional_filter_block) end ## # # Find an {Capybara::Node::Element} based on the given arguments that is also a sibling of the element called on. # {#sibling} will raise an error if the element is not found. # # {#sibling} takes the same options as {#find}. # # element.sibling('#foo').find('.bar') # element.sibling(:xpath, './/div[contains(., "bar")]') # element.sibling('ul', text: 'Quox').click_link('Delete') # # @param (see #find) # # @macro waiting_behavior # # @return [Capybara::Node::Element] The found element # @raise [Capybara::ElementNotFound] If the element can't be found before time expires # def sibling(*args, **options, &optional_filter_block) options[:session_options] = session_options synced_resolve Capybara::Queries::SiblingQuery.new(*args, **options, &optional_filter_block) end ## # # Find a form field on the page. The field can be found by its name, id or label text. # # @overload find_field([locator], **options) # @param [String] locator name, id, {Capybara.configure test_id} attribute, placeholder or text of associated label element # # @macro waiting_behavior # # # @option options [Boolean] checked Match checked field? # @option options [Boolean] unchecked Match unchecked field? # @option options [Boolean, Symbol] disabled (false) Match disabled field? # * true - only finds a disabled field # * false - only finds an enabled field # * :all - finds either an enabled or disabled field # @option options [Boolean] readonly Match readonly field? # @option options [String, Regexp] with Value of field to match on # @option options [String] type Type of field to match on # @option options [Boolean] multiple Match fields that can have multiple values? # @option options [String, Regexp] id Match fields that match the id attribute # @option options [String] name Match fields that match the name attribute # @option options [String] placeholder Match fields that match the placeholder attribute # @option options [String, Array<String>, Regexp] class Match fields that match the class(es) passed # @return [Capybara::Node::Element] The found element # def find_field(locator = nil, **options, &optional_filter_block) find(:field, locator, **options, &optional_filter_block) end ## # # Find a link on the page. The link can be found by its id or text. # # @overload find_link([locator], **options) # @param [String] locator id, {Capybara.configure test_id} attribute, title, text, or alt of enclosed img element # # @macro waiting_behavior # # @option options [String,Regexp,nil] href Value to match against the links href, if `nil` finds link placeholders (`<a>` elements with no href attribute), if `false` ignores the href # @option options [String, Regexp] id Match links with the id provided # @option options [String] title Match links with the title provided # @option options [String] alt Match links with a contained img element whose alt matches # @option options [String, Boolean] download Match links with the download provided # @option options [String] target Match links with the target provided # @option options [String, Array<String>, Regexp] class Match links that match the class(es) provided # @return [Capybara::Node::Element] The found element # def find_link(locator = nil, **options, &optional_filter_block) find(:link, locator, **options, &optional_filter_block) end ## # # Find a button on the page. # This can be any `<input>` element of type submit, reset, image, button or it can be a # `<button>` element. All buttons can be found by their id, name, {Capybara.configure test_id} attribute, value, or title. # `<button>` elements can also be found by their text content, and image `<input>` elements by their alt attribute. # # @overload find_button([locator], **options) # @param [String] locator id, name, {Capybara.configure test_id} attribute, value, title, text content, alt of image # # @macro waiting_behavior # # @option options [Boolean, Symbol] disabled (false) Match disabled button? # * true - only finds a disabled button # * false - only finds an enabled button # * :all - finds either an enabled or disabled button # @option options [String, Regexp] id Match buttons with the id provided # @option options [String] name Match buttons with the name provided # @option options [String] title Match buttons with the title provided # @option options [String] value Match buttons with the value provided # @option options [String, Array<String>, Regexp] class Match buttons that match the class(es) provided # @return [Capybara::Node::Element] The found element # def find_button(locator = nil, **options, &optional_filter_block) find(:button, locator, **options, &optional_filter_block) end ## # # Find a element on the page, given its id. # # @macro waiting_behavior # # @param [String] id id of element # # @return [Capybara::Node::Element] The found element # def find_by_id(id, **options, &optional_filter_block) find(:id, id, **options, &optional_filter_block) end ## # @!method all([kind = Capybara.default_selector], locator = nil, **options) # # Find all elements on the page matching the given selector # and options. # # Both XPath and CSS expressions are supported, but Capybara # does not try to automatically distinguish between them. The # following statements are equivalent: # # page.all(:css, 'a#person_123') # page.all(:xpath, './/a[@id="person_123"]') # # If the type of selector is left out, Capybara uses # {Capybara.configure default_selector}. It's set to `:css` by default. # # page.all("a#person_123") # # Capybara.default_selector = :xpath # page.all('.//a[@id="person_123"]') # # The set of found elements can further be restricted by specifying # options. It's possible to select elements by their text or visibility: # # page.all('a', text: 'Home') # page.all('#menu li', visible: true) # # By default Capybara's waiting behavior will wait up to {Capybara.configure default_max_wait_time} # seconds for matching elements to be available and then return an empty result if none # are available. It is possible to set expectations on the number of results located and # Capybara will raise an exception if the number of elements located don't satisfy the # specified conditions. The expectations can be set using: # # page.assert_selector('p#foo', count: 4) # page.assert_selector('p#foo', maximum: 10) # page.assert_selector('p#foo', minimum: 1) # page.assert_selector('p#foo', between: 1..10) # # @param [Symbol] kind Optional selector type (:css, :xpath, :field, etc.). Defaults to {Capybara.configure default_selector}. # @param [String] locator The locator for the specified selector # @macro system_filters # @macro waiting_behavior # @option options [Integer] count Exact number of matches that are expected to be found # @option options [Integer] maximum Maximum number of matches that are expected to be found # @option options [Integer] minimum Minimum number of matches that are expected to be found # @option options [Range] between Number of matches found must be within the given range # @option options [Boolean] allow_reload Beta feature - May be removed in any version. # When `true` allows elements to be reloaded if they become stale. This is an advanced behavior and should only be used # if you fully understand the potential ramifications. The results can be confusing on dynamic pages. Defaults to `false` # @overload all([kind = Capybara.default_selector], locator = nil, **options) # @overload all([kind = Capybara.default_selector], locator = nil, **options, &filter_block) # @yieldparam element [Capybara::Node::Element] The element being considered for inclusion in the results # @yieldreturn [Boolean] Should the element be considered in the results? # @return [Capybara::Result] A collection of found elements # @raise [Capybara::ExpectationNotMet] The number of elements found doesn't match the specified conditions def all(*args, allow_reload: false, **options, &optional_filter_block) minimum_specified = options_include_minimum?(options) options = { minimum: 1 }.merge(options) unless minimum_specified options[:session_options] = session_options query = Capybara::Queries::SelectorQuery.new(*args, **options, &optional_filter_block) result = nil begin synchronize(query.wait) do result = query.resolve_for(self) result.allow_reload! if allow_reload raise Capybara::ExpectationNotMet, result.failure_message unless result.matches_count? result end rescue Capybara::ExpectationNotMet raise if minimum_specified || (result.compare_count == 1) Result.new([], nil) end end alias_method :find_all, :all ## # # Find the first element on the page matching the given selector # and options. By default {#first} will wait up to {Capybara.configure default_max_wait_time} # seconds for matching elements to appear and then raise an error if no matching # element is found, or `nil` if the provided count options allow for empty results. # # @overload first([kind], locator, options) # @param [Symbol] kind The type of selector # @param [String] locator The selector # @param [Hash] options Additional options; see {#all} # @return [Capybara::Node::Element] The found element or nil # @raise [Capybara::ElementNotFound] If element(s) matching the provided options can't be found before time expires # def first(*args, **options, &optional_filter_block) options = { minimum: 1 }.merge(options) unless options_include_minimum?(options) all(*args, **options, &optional_filter_block).first end private def synced_resolve(query) synchronize(query.wait) do if prefer_exact?(query) result = query.resolve_for(self, true) result = query.resolve_for(self, false) if result.empty? && query.supports_exact? && !query.exact? else result = query.resolve_for(self) end if ambiguous?(query, result) raise Capybara::Ambiguous, "Ambiguous match, found #{result.size} elements matching #{query.applied_description}" end raise Capybara::ElementNotFound, "Unable to find #{query.applied_description}" if result.empty? result.first end.tap(&:allow_reload!) end def ambiguous?(query, result) %i[one smart].include?(query.match) && (result.size > 1) end def prefer_exact?(query) %i[smart prefer_exact].include?(query.match) end def options_include_minimum?(opts) %i[count minimum between].any? { |key| opts.key?(key) } end def parent first(:xpath, './parent::*', minimum: 0) end end end end
Ruby
{ "end_line": 61, "name": "find", "signature": "def find(*args, **options, &optional_filter_block)", "start_line": 51 }
{ "class_name": "", "class_signature": "", "module": "Capybara" }
all
capybara/lib/capybara/node/finders.rb
def all(*args, allow_reload: false, **options, &optional_filter_block) minimum_specified = options_include_minimum?(options) options = { minimum: 1 }.merge(options) unless minimum_specified options[:session_options] = session_options query = Capybara::Queries::SelectorQuery.new(*args, **options, &optional_filter_block) result = nil begin synchronize(query.wait) do result = query.resolve_for(self) result.allow_reload! if allow_reload raise Capybara::ExpectationNotMet, result.failure_message unless result.matches_count? result end rescue Capybara::ExpectationNotMet raise if minimum_specified || (result.compare_count == 1) Result.new([], nil) end end
# frozen_string_literal: true module Capybara module Node module Finders ## # # Find an {Capybara::Node::Element} based on the given arguments. {#find} will raise an error if the element # is not found. # # page.find('#foo').find('.bar') # page.find(:xpath, './/div[contains(., "bar")]') # page.find('li', text: 'Quox').click_link('Delete') # # @param (see #all) # # @macro waiting_behavior # # @!macro system_filters # @option options [String, Regexp] text Only find elements which contain this text or match this regexp # @option options [String, Regexp, String] exact_text # When String the elements contained text must match exactly, when Boolean controls whether the `text` option must match exactly. # Defaults to {Capybara.configure exact_text}. # @option options [Boolean] normalize_ws # Whether the `text`/`exact_text` options are compared against element text with whitespace normalized or as returned by the driver. # Defaults to {Capybara.configure default_normalize_ws}. # @option options [Boolean, Symbol] visible # Only find elements with the specified visibility. Defaults to behavior indicated by {Capybara.configure ignore_hidden_elements}. # * true - only finds visible elements. # * false - finds invisible _and_ visible elements. # * :all - same as false; finds visible and invisible elements. # * :hidden - only finds invisible elements. # * :visible - same as true; only finds visible elements. # @option options [Boolean] obscured Only find elements with the specified obscured state: # * true - only find elements whose centerpoint is not in the viewport or is obscured by another non-descendant element. # * false - only find elements whose centerpoint is in the viewport and is not obscured by other non-descendant elements. # @option options [String, Regexp] id Only find elements with an id that matches the value passed # @option options [String, Array<String>, Regexp] class Only find elements with matching class/classes. # * Absence of a class can be checked by prefixing the class name with `!` # * If you need to check for existence of a class name that starts with `!` then prefix with `!!` # # class:['a', '!b', '!!!c'] # limit to elements with class 'a' and '!c' but not class 'b' # # @option options [String, Regexp, Hash] style Only find elements with matching style. String and Regexp will be checked against text of the elements `style` attribute, while a Hash will be compared against the elements full style # @option options [Boolean] exact Control whether `is` expressions in the given XPath match exactly or partially. Defaults to {Capybara.configure exact}. # @option options [Symbol] match The matching strategy to use. Defaults to {Capybara.configure match}. # # @return [Capybara::Node::Element] The found element # @raise [Capybara::ElementNotFound] If the element can't be found before time expires # def find(*args, **options, &optional_filter_block) options[:session_options] = session_options count_options = options.slice(*Capybara::Queries::BaseQuery::COUNT_KEYS) unless count_options.empty? Capybara::Helpers.warn( "'find' does not support count options (#{count_options}) ignoring. " \ "Called from: #{Capybara::Helpers.filter_backtrace(caller)}" ) end synced_resolve Capybara::Queries::SelectorQuery.new(*args, **options, &optional_filter_block) end ## # # Find an {Capybara::Node::Element} based on the given arguments that is also an ancestor of the element called on. # {#ancestor} will raise an error if the element is not found. # # {#ancestor} takes the same options as {#find}. # # element.ancestor('#foo').find('.bar') # element.ancestor(:xpath, './/div[contains(., "bar")]') # element.ancestor('ul', text: 'Quox').click_link('Delete') # # @param (see #find) # # @macro waiting_behavior # # @return [Capybara::Node::Element] The found element # @raise [Capybara::ElementNotFound] If the element can't be found before time expires # def ancestor(*args, **options, &optional_filter_block) options[:session_options] = session_options synced_resolve Capybara::Queries::AncestorQuery.new(*args, **options, &optional_filter_block) end ## # # Find an {Capybara::Node::Element} based on the given arguments that is also a sibling of the element called on. # {#sibling} will raise an error if the element is not found. # # {#sibling} takes the same options as {#find}. # # element.sibling('#foo').find('.bar') # element.sibling(:xpath, './/div[contains(., "bar")]') # element.sibling('ul', text: 'Quox').click_link('Delete') # # @param (see #find) # # @macro waiting_behavior # # @return [Capybara::Node::Element] The found element # @raise [Capybara::ElementNotFound] If the element can't be found before time expires # def sibling(*args, **options, &optional_filter_block) options[:session_options] = session_options synced_resolve Capybara::Queries::SiblingQuery.new(*args, **options, &optional_filter_block) end ## # # Find a form field on the page. The field can be found by its name, id or label text. # # @overload find_field([locator], **options) # @param [String] locator name, id, {Capybara.configure test_id} attribute, placeholder or text of associated label element # # @macro waiting_behavior # # # @option options [Boolean] checked Match checked field? # @option options [Boolean] unchecked Match unchecked field? # @option options [Boolean, Symbol] disabled (false) Match disabled field? # * true - only finds a disabled field # * false - only finds an enabled field # * :all - finds either an enabled or disabled field # @option options [Boolean] readonly Match readonly field? # @option options [String, Regexp] with Value of field to match on # @option options [String] type Type of field to match on # @option options [Boolean] multiple Match fields that can have multiple values? # @option options [String, Regexp] id Match fields that match the id attribute # @option options [String] name Match fields that match the name attribute # @option options [String] placeholder Match fields that match the placeholder attribute # @option options [String, Array<String>, Regexp] class Match fields that match the class(es) passed # @return [Capybara::Node::Element] The found element # def find_field(locator = nil, **options, &optional_filter_block) find(:field, locator, **options, &optional_filter_block) end ## # # Find a link on the page. The link can be found by its id or text. # # @overload find_link([locator], **options) # @param [String] locator id, {Capybara.configure test_id} attribute, title, text, or alt of enclosed img element # # @macro waiting_behavior # # @option options [String,Regexp,nil] href Value to match against the links href, if `nil` finds link placeholders (`<a>` elements with no href attribute), if `false` ignores the href # @option options [String, Regexp] id Match links with the id provided # @option options [String] title Match links with the title provided # @option options [String] alt Match links with a contained img element whose alt matches # @option options [String, Boolean] download Match links with the download provided # @option options [String] target Match links with the target provided # @option options [String, Array<String>, Regexp] class Match links that match the class(es) provided # @return [Capybara::Node::Element] The found element # def find_link(locator = nil, **options, &optional_filter_block) find(:link, locator, **options, &optional_filter_block) end ## # # Find a button on the page. # This can be any `<input>` element of type submit, reset, image, button or it can be a # `<button>` element. All buttons can be found by their id, name, {Capybara.configure test_id} attribute, value, or title. # `<button>` elements can also be found by their text content, and image `<input>` elements by their alt attribute. # # @overload find_button([locator], **options) # @param [String] locator id, name, {Capybara.configure test_id} attribute, value, title, text content, alt of image # # @macro waiting_behavior # # @option options [Boolean, Symbol] disabled (false) Match disabled button? # * true - only finds a disabled button # * false - only finds an enabled button # * :all - finds either an enabled or disabled button # @option options [String, Regexp] id Match buttons with the id provided # @option options [String] name Match buttons with the name provided # @option options [String] title Match buttons with the title provided # @option options [String] value Match buttons with the value provided # @option options [String, Array<String>, Regexp] class Match buttons that match the class(es) provided # @return [Capybara::Node::Element] The found element # def find_button(locator = nil, **options, &optional_filter_block) find(:button, locator, **options, &optional_filter_block) end ## # # Find a element on the page, given its id. # # @macro waiting_behavior # # @param [String] id id of element # # @return [Capybara::Node::Element] The found element # def find_by_id(id, **options, &optional_filter_block) find(:id, id, **options, &optional_filter_block) end ## # @!method all([kind = Capybara.default_selector], locator = nil, **options) # # Find all elements on the page matching the given selector # and options. # # Both XPath and CSS expressions are supported, but Capybara # does not try to automatically distinguish between them. The # following statements are equivalent: # # page.all(:css, 'a#person_123') # page.all(:xpath, './/a[@id="person_123"]') # # If the type of selector is left out, Capybara uses # {Capybara.configure default_selector}. It's set to `:css` by default. # # page.all("a#person_123") # # Capybara.default_selector = :xpath # page.all('.//a[@id="person_123"]') # # The set of found elements can further be restricted by specifying # options. It's possible to select elements by their text or visibility: # # page.all('a', text: 'Home') # page.all('#menu li', visible: true) # # By default Capybara's waiting behavior will wait up to {Capybara.configure default_max_wait_time} # seconds for matching elements to be available and then return an empty result if none # are available. It is possible to set expectations on the number of results located and # Capybara will raise an exception if the number of elements located don't satisfy the # specified conditions. The expectations can be set using: # # page.assert_selector('p#foo', count: 4) # page.assert_selector('p#foo', maximum: 10) # page.assert_selector('p#foo', minimum: 1) # page.assert_selector('p#foo', between: 1..10) # # @param [Symbol] kind Optional selector type (:css, :xpath, :field, etc.). Defaults to {Capybara.configure default_selector}. # @param [String] locator The locator for the specified selector # @macro system_filters # @macro waiting_behavior # @option options [Integer] count Exact number of matches that are expected to be found # @option options [Integer] maximum Maximum number of matches that are expected to be found # @option options [Integer] minimum Minimum number of matches that are expected to be found # @option options [Range] between Number of matches found must be within the given range # @option options [Boolean] allow_reload Beta feature - May be removed in any version. # When `true` allows elements to be reloaded if they become stale. This is an advanced behavior and should only be used # if you fully understand the potential ramifications. The results can be confusing on dynamic pages. Defaults to `false` # @overload all([kind = Capybara.default_selector], locator = nil, **options) # @overload all([kind = Capybara.default_selector], locator = nil, **options, &filter_block) # @yieldparam element [Capybara::Node::Element] The element being considered for inclusion in the results # @yieldreturn [Boolean] Should the element be considered in the results? # @return [Capybara::Result] A collection of found elements # @raise [Capybara::ExpectationNotMet] The number of elements found doesn't match the specified conditions def all(*args, allow_reload: false, **options, &optional_filter_block) minimum_specified = options_include_minimum?(options) options = { minimum: 1 }.merge(options) unless minimum_specified options[:session_options] = session_options query = Capybara::Queries::SelectorQuery.new(*args, **options, &optional_filter_block) result = nil begin synchronize(query.wait) do result = query.resolve_for(self) result.allow_reload! if allow_reload raise Capybara::ExpectationNotMet, result.failure_message unless result.matches_count? result end rescue Capybara::ExpectationNotMet raise if minimum_specified || (result.compare_count == 1) Result.new([], nil) end end alias_method :find_all, :all ## # # Find the first element on the page matching the given selector # and options. By default {#first} will wait up to {Capybara.configure default_max_wait_time} # seconds for matching elements to appear and then raise an error if no matching # element is found, or `nil` if the provided count options allow for empty results. # # @overload first([kind], locator, options) # @param [Symbol] kind The type of selector # @param [String] locator The selector # @param [Hash] options Additional options; see {#all} # @return [Capybara::Node::Element] The found element or nil # @raise [Capybara::ElementNotFound] If element(s) matching the provided options can't be found before time expires # def first(*args, **options, &optional_filter_block) options = { minimum: 1 }.merge(options) unless options_include_minimum?(options) all(*args, **options, &optional_filter_block).first end private def synced_resolve(query) synchronize(query.wait) do if prefer_exact?(query) result = query.resolve_for(self, true) result = query.resolve_for(self, false) if result.empty? && query.supports_exact? && !query.exact? else result = query.resolve_for(self) end if ambiguous?(query, result) raise Capybara::Ambiguous, "Ambiguous match, found #{result.size} elements matching #{query.applied_description}" end raise Capybara::ElementNotFound, "Unable to find #{query.applied_description}" if result.empty? result.first end.tap(&:allow_reload!) end def ambiguous?(query, result) %i[one smart].include?(query.match) && (result.size > 1) end def prefer_exact?(query) %i[smart prefer_exact].include?(query.match) end def options_include_minimum?(opts) %i[count minimum between].any? { |key| opts.key?(key) } end def parent first(:xpath, './parent::*', minimum: 0) end end end end
Ruby
{ "end_line": 276, "name": "all", "signature": "def all(*args, allow_reload: false, **options, &optional_filter_block)", "start_line": 257 }
{ "class_name": "", "class_signature": "", "module": "Capybara" }
synced_resolve
capybara/lib/capybara/node/finders.rb
def synced_resolve(query) synchronize(query.wait) do if prefer_exact?(query) result = query.resolve_for(self, true) result = query.resolve_for(self, false) if result.empty? && query.supports_exact? && !query.exact? else result = query.resolve_for(self) end if ambiguous?(query, result) raise Capybara::Ambiguous, "Ambiguous match, found #{result.size} elements matching #{query.applied_description}" end raise Capybara::ElementNotFound, "Unable to find #{query.applied_description}" if result.empty? result.first end.tap(&:allow_reload!) end
# frozen_string_literal: true module Capybara module Node module Finders ## # # Find an {Capybara::Node::Element} based on the given arguments. {#find} will raise an error if the element # is not found. # # page.find('#foo').find('.bar') # page.find(:xpath, './/div[contains(., "bar")]') # page.find('li', text: 'Quox').click_link('Delete') # # @param (see #all) # # @macro waiting_behavior # # @!macro system_filters # @option options [String, Regexp] text Only find elements which contain this text or match this regexp # @option options [String, Regexp, String] exact_text # When String the elements contained text must match exactly, when Boolean controls whether the `text` option must match exactly. # Defaults to {Capybara.configure exact_text}. # @option options [Boolean] normalize_ws # Whether the `text`/`exact_text` options are compared against element text with whitespace normalized or as returned by the driver. # Defaults to {Capybara.configure default_normalize_ws}. # @option options [Boolean, Symbol] visible # Only find elements with the specified visibility. Defaults to behavior indicated by {Capybara.configure ignore_hidden_elements}. # * true - only finds visible elements. # * false - finds invisible _and_ visible elements. # * :all - same as false; finds visible and invisible elements. # * :hidden - only finds invisible elements. # * :visible - same as true; only finds visible elements. # @option options [Boolean] obscured Only find elements with the specified obscured state: # * true - only find elements whose centerpoint is not in the viewport or is obscured by another non-descendant element. # * false - only find elements whose centerpoint is in the viewport and is not obscured by other non-descendant elements. # @option options [String, Regexp] id Only find elements with an id that matches the value passed # @option options [String, Array<String>, Regexp] class Only find elements with matching class/classes. # * Absence of a class can be checked by prefixing the class name with `!` # * If you need to check for existence of a class name that starts with `!` then prefix with `!!` # # class:['a', '!b', '!!!c'] # limit to elements with class 'a' and '!c' but not class 'b' # # @option options [String, Regexp, Hash] style Only find elements with matching style. String and Regexp will be checked against text of the elements `style` attribute, while a Hash will be compared against the elements full style # @option options [Boolean] exact Control whether `is` expressions in the given XPath match exactly or partially. Defaults to {Capybara.configure exact}. # @option options [Symbol] match The matching strategy to use. Defaults to {Capybara.configure match}. # # @return [Capybara::Node::Element] The found element # @raise [Capybara::ElementNotFound] If the element can't be found before time expires # def find(*args, **options, &optional_filter_block) options[:session_options] = session_options count_options = options.slice(*Capybara::Queries::BaseQuery::COUNT_KEYS) unless count_options.empty? Capybara::Helpers.warn( "'find' does not support count options (#{count_options}) ignoring. " \ "Called from: #{Capybara::Helpers.filter_backtrace(caller)}" ) end synced_resolve Capybara::Queries::SelectorQuery.new(*args, **options, &optional_filter_block) end ## # # Find an {Capybara::Node::Element} based on the given arguments that is also an ancestor of the element called on. # {#ancestor} will raise an error if the element is not found. # # {#ancestor} takes the same options as {#find}. # # element.ancestor('#foo').find('.bar') # element.ancestor(:xpath, './/div[contains(., "bar")]') # element.ancestor('ul', text: 'Quox').click_link('Delete') # # @param (see #find) # # @macro waiting_behavior # # @return [Capybara::Node::Element] The found element # @raise [Capybara::ElementNotFound] If the element can't be found before time expires # def ancestor(*args, **options, &optional_filter_block) options[:session_options] = session_options synced_resolve Capybara::Queries::AncestorQuery.new(*args, **options, &optional_filter_block) end ## # # Find an {Capybara::Node::Element} based on the given arguments that is also a sibling of the element called on. # {#sibling} will raise an error if the element is not found. # # {#sibling} takes the same options as {#find}. # # element.sibling('#foo').find('.bar') # element.sibling(:xpath, './/div[contains(., "bar")]') # element.sibling('ul', text: 'Quox').click_link('Delete') # # @param (see #find) # # @macro waiting_behavior # # @return [Capybara::Node::Element] The found element # @raise [Capybara::ElementNotFound] If the element can't be found before time expires # def sibling(*args, **options, &optional_filter_block) options[:session_options] = session_options synced_resolve Capybara::Queries::SiblingQuery.new(*args, **options, &optional_filter_block) end ## # # Find a form field on the page. The field can be found by its name, id or label text. # # @overload find_field([locator], **options) # @param [String] locator name, id, {Capybara.configure test_id} attribute, placeholder or text of associated label element # # @macro waiting_behavior # # # @option options [Boolean] checked Match checked field? # @option options [Boolean] unchecked Match unchecked field? # @option options [Boolean, Symbol] disabled (false) Match disabled field? # * true - only finds a disabled field # * false - only finds an enabled field # * :all - finds either an enabled or disabled field # @option options [Boolean] readonly Match readonly field? # @option options [String, Regexp] with Value of field to match on # @option options [String] type Type of field to match on # @option options [Boolean] multiple Match fields that can have multiple values? # @option options [String, Regexp] id Match fields that match the id attribute # @option options [String] name Match fields that match the name attribute # @option options [String] placeholder Match fields that match the placeholder attribute # @option options [String, Array<String>, Regexp] class Match fields that match the class(es) passed # @return [Capybara::Node::Element] The found element # def find_field(locator = nil, **options, &optional_filter_block) find(:field, locator, **options, &optional_filter_block) end ## # # Find a link on the page. The link can be found by its id or text. # # @overload find_link([locator], **options) # @param [String] locator id, {Capybara.configure test_id} attribute, title, text, or alt of enclosed img element # # @macro waiting_behavior # # @option options [String,Regexp,nil] href Value to match against the links href, if `nil` finds link placeholders (`<a>` elements with no href attribute), if `false` ignores the href # @option options [String, Regexp] id Match links with the id provided # @option options [String] title Match links with the title provided # @option options [String] alt Match links with a contained img element whose alt matches # @option options [String, Boolean] download Match links with the download provided # @option options [String] target Match links with the target provided # @option options [String, Array<String>, Regexp] class Match links that match the class(es) provided # @return [Capybara::Node::Element] The found element # def find_link(locator = nil, **options, &optional_filter_block) find(:link, locator, **options, &optional_filter_block) end ## # # Find a button on the page. # This can be any `<input>` element of type submit, reset, image, button or it can be a # `<button>` element. All buttons can be found by their id, name, {Capybara.configure test_id} attribute, value, or title. # `<button>` elements can also be found by their text content, and image `<input>` elements by their alt attribute. # # @overload find_button([locator], **options) # @param [String] locator id, name, {Capybara.configure test_id} attribute, value, title, text content, alt of image # # @macro waiting_behavior # # @option options [Boolean, Symbol] disabled (false) Match disabled button? # * true - only finds a disabled button # * false - only finds an enabled button # * :all - finds either an enabled or disabled button # @option options [String, Regexp] id Match buttons with the id provided # @option options [String] name Match buttons with the name provided # @option options [String] title Match buttons with the title provided # @option options [String] value Match buttons with the value provided # @option options [String, Array<String>, Regexp] class Match buttons that match the class(es) provided # @return [Capybara::Node::Element] The found element # def find_button(locator = nil, **options, &optional_filter_block) find(:button, locator, **options, &optional_filter_block) end ## # # Find a element on the page, given its id. # # @macro waiting_behavior # # @param [String] id id of element # # @return [Capybara::Node::Element] The found element # def find_by_id(id, **options, &optional_filter_block) find(:id, id, **options, &optional_filter_block) end ## # @!method all([kind = Capybara.default_selector], locator = nil, **options) # # Find all elements on the page matching the given selector # and options. # # Both XPath and CSS expressions are supported, but Capybara # does not try to automatically distinguish between them. The # following statements are equivalent: # # page.all(:css, 'a#person_123') # page.all(:xpath, './/a[@id="person_123"]') # # If the type of selector is left out, Capybara uses # {Capybara.configure default_selector}. It's set to `:css` by default. # # page.all("a#person_123") # # Capybara.default_selector = :xpath # page.all('.//a[@id="person_123"]') # # The set of found elements can further be restricted by specifying # options. It's possible to select elements by their text or visibility: # # page.all('a', text: 'Home') # page.all('#menu li', visible: true) # # By default Capybara's waiting behavior will wait up to {Capybara.configure default_max_wait_time} # seconds for matching elements to be available and then return an empty result if none # are available. It is possible to set expectations on the number of results located and # Capybara will raise an exception if the number of elements located don't satisfy the # specified conditions. The expectations can be set using: # # page.assert_selector('p#foo', count: 4) # page.assert_selector('p#foo', maximum: 10) # page.assert_selector('p#foo', minimum: 1) # page.assert_selector('p#foo', between: 1..10) # # @param [Symbol] kind Optional selector type (:css, :xpath, :field, etc.). Defaults to {Capybara.configure default_selector}. # @param [String] locator The locator for the specified selector # @macro system_filters # @macro waiting_behavior # @option options [Integer] count Exact number of matches that are expected to be found # @option options [Integer] maximum Maximum number of matches that are expected to be found # @option options [Integer] minimum Minimum number of matches that are expected to be found # @option options [Range] between Number of matches found must be within the given range # @option options [Boolean] allow_reload Beta feature - May be removed in any version. # When `true` allows elements to be reloaded if they become stale. This is an advanced behavior and should only be used # if you fully understand the potential ramifications. The results can be confusing on dynamic pages. Defaults to `false` # @overload all([kind = Capybara.default_selector], locator = nil, **options) # @overload all([kind = Capybara.default_selector], locator = nil, **options, &filter_block) # @yieldparam element [Capybara::Node::Element] The element being considered for inclusion in the results # @yieldreturn [Boolean] Should the element be considered in the results? # @return [Capybara::Result] A collection of found elements # @raise [Capybara::ExpectationNotMet] The number of elements found doesn't match the specified conditions def all(*args, allow_reload: false, **options, &optional_filter_block) minimum_specified = options_include_minimum?(options) options = { minimum: 1 }.merge(options) unless minimum_specified options[:session_options] = session_options query = Capybara::Queries::SelectorQuery.new(*args, **options, &optional_filter_block) result = nil begin synchronize(query.wait) do result = query.resolve_for(self) result.allow_reload! if allow_reload raise Capybara::ExpectationNotMet, result.failure_message unless result.matches_count? result end rescue Capybara::ExpectationNotMet raise if minimum_specified || (result.compare_count == 1) Result.new([], nil) end end alias_method :find_all, :all ## # # Find the first element on the page matching the given selector # and options. By default {#first} will wait up to {Capybara.configure default_max_wait_time} # seconds for matching elements to appear and then raise an error if no matching # element is found, or `nil` if the provided count options allow for empty results. # # @overload first([kind], locator, options) # @param [Symbol] kind The type of selector # @param [String] locator The selector # @param [Hash] options Additional options; see {#all} # @return [Capybara::Node::Element] The found element or nil # @raise [Capybara::ElementNotFound] If element(s) matching the provided options can't be found before time expires # def first(*args, **options, &optional_filter_block) options = { minimum: 1 }.merge(options) unless options_include_minimum?(options) all(*args, **options, &optional_filter_block).first end private def synced_resolve(query) synchronize(query.wait) do if prefer_exact?(query) result = query.resolve_for(self, true) result = query.resolve_for(self, false) if result.empty? && query.supports_exact? && !query.exact? else result = query.resolve_for(self) end if ambiguous?(query, result) raise Capybara::Ambiguous, "Ambiguous match, found #{result.size} elements matching #{query.applied_description}" end raise Capybara::ElementNotFound, "Unable to find #{query.applied_description}" if result.empty? result.first end.tap(&:allow_reload!) end def ambiguous?(query, result) %i[one smart].include?(query.match) && (result.size > 1) end def prefer_exact?(query) %i[smart prefer_exact].include?(query.match) end def options_include_minimum?(opts) %i[count minimum between].any? { |key| opts.key?(key) } end def parent first(:xpath, './parent::*', minimum: 0) end end end end
Ruby
{ "end_line": 316, "name": "synced_resolve", "signature": "def synced_resolve(query)", "start_line": 300 }
{ "class_name": "", "class_signature": "", "module": "Capybara" }
assert_any_of_selectors
capybara/lib/capybara/node/matchers.rb
def assert_any_of_selectors(*args, wait: nil, **options, &optional_filter_block) wait = session_options.default_max_wait_time if wait.nil? selector = extract_selector(args) synchronize(wait) do res = args.map do |locator| assert_selector(selector, locator, options, &optional_filter_block) break nil rescue Capybara::ExpectationNotMet => e e.message end raise Capybara::ExpectationNotMet, res.join(' or ') if res true end end
# frozen_string_literal: true module Capybara module Node module Matchers ## # # Checks if a given selector is on the page or a descendant of the current node. # # page.has_selector?('p#foo') # page.has_selector?(:xpath, './/p[@id="foo"]') # page.has_selector?(:foo) # # By default it will check if the expression occurs at least once, # but a different number can be specified. # # page.has_selector?('p.foo', count: 4) # # This will check if the expression occurs exactly 4 times. # # It also accepts all options that {Capybara::Node::Finders#all} accepts, # such as `:text` and `:visible`. # # page.has_selector?('li', text: 'Horse', visible: true) # # {#has_selector?} can also accept XPath expressions generated by the # XPath gem: # # page.has_selector?(:xpath, XPath.descendant(:p)) # # @param (see Capybara::Node::Finders#all) # @option options [Integer] :count (nil) Number of matching elements that should exist # @option options [Integer] :minimum (nil) Minimum number of matching elements that should exist # @option options [Integer] :maximum (nil) Maximum number of matching elements that should exist # @option options [Range] :between (nil) Range of number of matching elements that should exist # @return [Boolean] If the expression exists # def has_selector?(*args, **options, &optional_filter_block) make_predicate(options) { assert_selector(*args, options, &optional_filter_block) } end ## # # Checks if a given selector is not on the page or a descendant of the current node. # Usage is identical to {#has_selector?}. # # @param (see #has_selector?) # @return [Boolean] # def has_no_selector?(*args, **options, &optional_filter_block) make_predicate(options) { assert_no_selector(*args, options, &optional_filter_block) } end ## # # Checks if a an element has the specified CSS styles. # # element.matches_style?( 'color' => 'rgb(0,0,255)', 'font-size' => /px/ ) # # @param styles [Hash] # @return [Boolean] If the styles match # def matches_style?(styles = nil, **options) styles, options = options, {} if styles.nil? make_predicate(options) { assert_matches_style(styles, **options) } end ## # @deprecated Use {#matches_style?} instead. # def has_style?(styles = nil, **options) Capybara::Helpers.warn "DEPRECATED: has_style? is deprecated, please use matches_style? : #{Capybara::Helpers.filter_backtrace(caller)}" matches_style?(styles, **options) end ## # # Asserts that a given selector is on the page or a descendant of the current node. # # page.assert_selector('p#foo') # page.assert_selector(:xpath, './/p[@id="foo"]') # page.assert_selector(:foo) # # By default it will check if the expression occurs at least once, # but a different number can be specified. # # page.assert_selector('p#foo', count: 4) # # This will check if the expression occurs exactly 4 times. See # {Capybara::Node::Finders#all} for other available result size options. # # If a `:count` of 0 is specified, it will behave like {#assert_no_selector}; # however, use of that method is preferred over this one. # # It also accepts all options that {Capybara::Node::Finders#all} accepts, # such as `:text` and `:visible`. # # page.assert_selector('li', text: 'Horse', visible: true) # # {#assert_selector} can also accept XPath expressions generated by the # XPath gem: # # page.assert_selector(:xpath, XPath.descendant(:p)) # # @param (see Capybara::Node::Finders#all) # @option options [Integer] :count (nil) Number of times the expression should occur # @raise [Capybara::ExpectationNotMet] If the selector does not exist # def assert_selector(*args, &optional_filter_block) _verify_selector_result(args, optional_filter_block) do |result, query| unless result.matches_count? && (result.any? || query.expects_none?) raise Capybara::ExpectationNotMet, result.failure_message end end end ## # # Asserts that an element has the specified CSS styles. # # element.assert_matches_style( 'color' => 'rgb(0,0,255)', 'font-size' => /px/ ) # # @param styles [Hash] # @raise [Capybara::ExpectationNotMet] If the element doesn't have the specified styles # def assert_matches_style(styles = nil, **options) styles, options = options, {} if styles.nil? query_args, query_opts = _set_query_session_options(styles, options) query = Capybara::Queries::StyleQuery.new(*query_args, **query_opts) synchronize(query.wait) do raise Capybara::ExpectationNotMet, query.failure_message unless query.resolves_for?(self) end true end ## # @deprecated Use {#assert_matches_style} instead. # def assert_style(styles = nil, **options) warn 'assert_style is deprecated, please use assert_matches_style instead' assert_matches_style(styles, **options) end # Asserts that all of the provided selectors are present on the given page # or descendants of the current node. If options are provided, the assertion # will check that each locator is present with those options as well (other than `:wait`). # # page.assert_all_of_selectors(:custom, 'Tom', 'Joe', visible: all) # page.assert_all_of_selectors(:css, '#my_div', 'a.not_clicked') # # It accepts all options that {Capybara::Node::Finders#all} accepts, # such as `:text` and `:visible`. # # The `:wait` option applies to all of the selectors as a group, so all of the locators must be present # within `:wait` (defaults to {Capybara.configure default_max_wait_time}) seconds. # # @overload assert_all_of_selectors([kind = Capybara.default_selector], *locators, **options) # def assert_all_of_selectors(*args, **options, &optional_filter_block) _verify_multiple(*args, **options) do |selector, locator, opts| assert_selector(selector, locator, opts, &optional_filter_block) end end # Asserts that none of the provided selectors are present on the given page # or descendants of the current node. If options are provided, the assertion # will check that each locator is not present with those options as well (other than `:wait`). # # page.assert_none_of_selectors(:custom, 'Tom', 'Joe', visible: all) # page.assert_none_of_selectors(:css, '#my_div', 'a.not_clicked') # # It accepts all options that {Capybara::Node::Finders#all} accepts, # such as `:text` and `:visible`. # # The `:wait` option applies to all of the selectors as a group, so none of the locators must be present # within `:wait` (defaults to {Capybara.configure default_max_wait_time}) seconds. # # @overload assert_none_of_selectors([kind = Capybara.default_selector], *locators, **options) # def assert_none_of_selectors(*args, **options, &optional_filter_block) _verify_multiple(*args, **options) do |selector, locator, opts| assert_no_selector(selector, locator, opts, &optional_filter_block) end end # Asserts that any of the provided selectors are present on the given page # or descendants of the current node. If options are provided, the assertion # will check that each locator is present with those options as well (other than `:wait`). # # page.assert_any_of_selectors(:custom, 'Tom', 'Joe', visible: all) # page.assert_any_of_selectors(:css, '#my_div', 'a.not_clicked') # # It accepts all options that {Capybara::Node::Finders#all} accepts, # such as `:text` and `:visible`. # # The `:wait` option applies to all of the selectors as a group, so any of the locators must be present # within `:wait` (defaults to {Capybara.configure default_max_wait_time}) seconds. # # @overload assert_any_of_selectors([kind = Capybara.default_selector], *locators, **options) # def assert_any_of_selectors(*args, wait: nil, **options, &optional_filter_block) wait = session_options.default_max_wait_time if wait.nil? selector = extract_selector(args) synchronize(wait) do res = args.map do |locator| assert_selector(selector, locator, options, &optional_filter_block) break nil rescue Capybara::ExpectationNotMet => e e.message end raise Capybara::ExpectationNotMet, res.join(' or ') if res true end end ## # # Asserts that a given selector is not on the page or a descendant of the current node. # Usage is identical to {#assert_selector}. # # Query options such as `:count`, `:minimum`, `:maximum`, and `:between` are # considered to be an integral part of the selector. This will return # `true`, for example, if a page contains 4 anchors but the query expects 5: # # page.assert_no_selector('a', minimum: 1) # Found, raises Capybara::ExpectationNotMet # page.assert_no_selector('a', count: 4) # Found, raises Capybara::ExpectationNotMet # page.assert_no_selector('a', count: 5) # Not Found, returns true # # @param (see #assert_selector) # @raise [Capybara::ExpectationNotMet] If the selector exists # def assert_no_selector(*args, &optional_filter_block) _verify_selector_result(args, optional_filter_block) do |result, query| if result.matches_count? && (!result.empty? || query.expects_none?) raise Capybara::ExpectationNotMet, result.negative_failure_message end end end ## # # Checks if a given XPath expression is on the page or a descendant of the current node. # # page.has_xpath?('.//p[@id="foo"]') # # By default it will check if the expression occurs at least once, # but a different number can be specified. # # page.has_xpath?('.//p[@id="foo"]', count: 4) # # This will check if the expression occurs exactly 4 times. # # It also accepts all options that {Capybara::Node::Finders#all} accepts, # such as `:text` and `:visible`. # # page.has_xpath?('.//li', text: 'Horse', visible: true) # # {#has_xpath?} can also accept XPath expressions generated by the # XPath gem: # # xpath = XPath.generate { |x| x.descendant(:p) } # page.has_xpath?(xpath) # # @param [String] path An XPath expression # @param options (see Capybara::Node::Finders#all) # @option options [Integer] :count (nil) Number of times the expression should occur # @return [Boolean] If the expression exists # def has_xpath?(path, **options, &optional_filter_block) has_selector?(:xpath, path, **options, &optional_filter_block) end ## # # Checks if a given XPath expression is not on the page or a descendant of the current node. # Usage is identical to {#has_xpath?}. # # @param (see #has_xpath?) # @return [Boolean] # def has_no_xpath?(path, **options, &optional_filter_block) has_no_selector?(:xpath, path, **options, &optional_filter_block) end ## # # Checks if a given CSS selector is on the page or a descendant of the current node. # # page.has_css?('p#foo') # # By default it will check if the selector occurs at least once, # but a different number can be specified. # # page.has_css?('p#foo', count: 4) # # This will check if the selector occurs exactly 4 times. # # It also accepts all options that {Capybara::Node::Finders#all} accepts, # such as `:text` and `:visible`. # # page.has_css?('li', text: 'Horse', visible: true) # # @param [String] path A CSS selector # @param options (see Capybara::Node::Finders#all) # @option options [Integer] :count (nil) Number of times the selector should occur # @return [Boolean] If the selector exists # def has_css?(path, **options, &optional_filter_block) has_selector?(:css, path, **options, &optional_filter_block) end ## # # Checks if a given CSS selector is not on the page or a descendant of the current node. # Usage is identical to {#has_css?}. # # @param (see #has_css?) # @return [Boolean] # def has_no_css?(path, **options, &optional_filter_block) has_no_selector?(:css, path, **options, &optional_filter_block) end ## # # Checks if the page or current node has a element with the given # local name. # # @param [String] locator The local name of a element to check for # @option options [String, Regexp] The attributes values of matching elements # @return [Boolean] Whether it exists # def has_element?(locator = nil, **options, &optional_filter_block) has_selector?(:element, locator, **options, &optional_filter_block) end ## # # Checks if the page or current node has no element with the given # local name. # # @param (see #has_element?) # @return [Boolean] Whether it doesn't exist # def has_no_element?(locator = nil, **options, &optional_filter_block) has_no_selector?(:element, locator, **options, &optional_filter_block) end ## # # Checks if the page or current node has a link with the given # text or id. # # @param [String] locator The text or id of a link to check for # @option options [String, Regexp] :href The value the href attribute must be # @return [Boolean] Whether it exists # def has_link?(locator = nil, **options, &optional_filter_block) has_selector?(:link, locator, **options, &optional_filter_block) end ## # # Checks if the page or current node has no link with the given # text or id. # # @param (see #has_link?) # @return [Boolean] Whether it doesn't exist # def has_no_link?(locator = nil, **options, &optional_filter_block) has_no_selector?(:link, locator, **options, &optional_filter_block) end ## # # Checks if the page or current node has a button with the given # text, value or id. # # @param [String] locator The text, value or id of a button to check for # @return [Boolean] Whether it exists # def has_button?(locator = nil, **options, &optional_filter_block) has_selector?(:button, locator, **options, &optional_filter_block) end ## # # Checks if the page or current node has no button with the given # text, value or id. # # @param [String] locator The text, value or id of a button to check for # @return [Boolean] Whether it doesn't exist # def has_no_button?(locator = nil, **options, &optional_filter_block) has_no_selector?(:button, locator, **options, &optional_filter_block) end ## # # Checks if the page or current node has a form field with the given # label, name or id. # # For text fields and other textual fields, such as textareas and # HTML5 email/url/etc. fields, it's possible to specify a `:with` # option to specify the text the field should contain: # # page.has_field?('Name', with: 'Jonas') # # It is also possible to filter by the field type attribute: # # page.has_field?('Email', type: 'email') # # NOTE: 'textarea' and 'select' are valid type values, matching the associated tag names. # # @param [String] locator The label, name or id of a field to check for # @option options [String, Regexp] :with The text content of the field or a Regexp to match # @option options [String] :type The type attribute of the field # @return [Boolean] Whether it exists # def has_field?(locator = nil, **options, &optional_filter_block) has_selector?(:field, locator, **options, &optional_filter_block) end ## # # Checks if the page or current node has no form field with the given # label, name or id. See {#has_field?}. # # @param [String] locator The label, name or id of a field to check for # @option options [String, Regexp] :with The text content of the field or a Regexp to match # @option options [String] :type The type attribute of the field # @return [Boolean] Whether it doesn't exist # def has_no_field?(locator = nil, **options, &optional_filter_block) has_no_selector?(:field, locator, **options, &optional_filter_block) end ## # # Checks if the page or current node has a radio button or # checkbox with the given label, value, id, or {Capybara.configure test_id} attribute that is currently # checked. # # @param [String] locator The label, name or id of a checked field # @return [Boolean] Whether it exists # def has_checked_field?(locator = nil, **options, &optional_filter_block) has_selector?(:field, locator, **options.merge(checked: true), &optional_filter_block) end ## # # Checks if the page or current node has no radio button or # checkbox with the given label, value or id, or {Capybara.configure test_id} attribute that is currently # checked. # # @param [String] locator The label, name or id of a checked field # @return [Boolean] Whether it doesn't exist # def has_no_checked_field?(locator = nil, **options, &optional_filter_block) has_no_selector?(:field, locator, **options.merge(checked: true), &optional_filter_block) end ## # # Checks if the page or current node has a radio button or # checkbox with the given label, value or id, or {Capybara.configure test_id} attribute that is currently # unchecked. # # @param [String] locator The label, name or id of an unchecked field # @return [Boolean] Whether it exists # def has_unchecked_field?(locator = nil, **options, &optional_filter_block) has_selector?(:field, locator, **options.merge(unchecked: true), &optional_filter_block) end ## # # Checks if the page or current node has no radio button or # checkbox with the given label, value or id, or {Capybara.configure test_id} attribute that is currently # unchecked. # # @param [String] locator The label, name or id of an unchecked field # @return [Boolean] Whether it doesn't exist # def has_no_unchecked_field?(locator = nil, **options, &optional_filter_block) has_no_selector?(:field, locator, **options.merge(unchecked: true), &optional_filter_block) end ## # # Checks if the page or current node has a select field with the # given label, name or id. # # It can be specified which option should currently be selected: # # page.has_select?('Language', selected: 'German') # # For multiple select boxes, several options may be specified: # # page.has_select?('Language', selected: ['English', 'German']) # # It's also possible to check if the exact set of options exists for # this select box: # # page.has_select?('Language', options: ['English', 'German', 'Spanish']) # # You can also check for a partial set of options: # # page.has_select?('Language', with_options: ['English', 'German']) # # @param [String] locator The label, name or id of a select box # @option options [Array] :options Options which should be contained in this select box # @option options [Array] :with_options Partial set of options which should be contained in this select box # @option options [String, Array] :selected Options which should be selected # @option options [String, Array] :with_selected Partial set of options which should minimally be selected # @return [Boolean] Whether it exists # def has_select?(locator = nil, **options, &optional_filter_block) has_selector?(:select, locator, **options, &optional_filter_block) end ## # # Checks if the page or current node has no select field with the # given label, name or id. See {#has_select?}. # # @param (see #has_select?) # @return [Boolean] Whether it doesn't exist # def has_no_select?(locator = nil, **options, &optional_filter_block) has_no_selector?(:select, locator, **options, &optional_filter_block) end ## # # Checks if the page or current node has a table with the given id # or caption: # # page.has_table?('People') # # @param [String] locator The id or caption of a table # @option options [Array<Array<String>>] :rows # Text which should be contained in the tables `<td>` elements organized by row (`<td>` visibility is not considered) # @option options [Array<Array<String>>, Array<Hash<String,String>>] :with_rows # Partial set of text which should be contained in the tables `<td>` elements organized by row (`<td>` visibility is not considered) # @option options [Array<Array<String>>] :cols # Text which should be contained in the tables `<td>` elements organized by column (`<td>` visibility is not considered) # @option options [Array<Array<String>>, Array<Hash<String,String>>] :with_cols # Partial set of text which should be contained in the tables `<td>` elements organized by column (`<td>` visibility is not considered) # @return [Boolean] Whether it exists # def has_table?(locator = nil, **options, &optional_filter_block) has_selector?(:table, locator, **options, &optional_filter_block) end ## # # Checks if the page or current node has no table with the given id # or caption. See {#has_table?}. # # @param (see #has_table?) # @return [Boolean] Whether it doesn't exist # def has_no_table?(locator = nil, **options, &optional_filter_block) has_no_selector?(:table, locator, **options, &optional_filter_block) end ## # # Asserts that the current node matches a given selector. # # node.assert_matches_selector('p#foo') # node.assert_matches_selector(:xpath, '//p[@id="foo"]') # node.assert_matches_selector(:foo) # # It also accepts all options that {Capybara::Node::Finders#all} accepts, # such as `:text` and `:visible`. # # node.assert_matches_selector('li', text: 'Horse', visible: true) # # @param (see Capybara::Node::Finders#all) # @raise [Capybara::ExpectationNotMet] If the selector does not match # def assert_matches_selector(*args, &optional_filter_block) _verify_match_result(args, optional_filter_block) do |result| raise Capybara::ExpectationNotMet, 'Item does not match the provided selector' unless result.include? self end end ## # # Asserts that the current node does not match a given selector. # Usage is identical to {#assert_matches_selector}. # # @param (see #assert_matches_selector) # @raise [Capybara::ExpectationNotMet] If the selector matches # def assert_not_matches_selector(*args, &optional_filter_block) _verify_match_result(args, optional_filter_block) do |result| raise Capybara::ExpectationNotMet, 'Item matched the provided selector' if result.include? self end end ## # # Checks if the current node matches given selector. # # @param (see #has_selector?) # @return [Boolean] # def matches_selector?(*args, **options, &optional_filter_block) make_predicate(options) { assert_matches_selector(*args, options, &optional_filter_block) } end ## # # Checks if the current node matches given XPath expression. # # @param [String, XPath::Expression] xpath The XPath expression to match against the current code # @return [Boolean] # def matches_xpath?(xpath, **options, &optional_filter_block) matches_selector?(:xpath, xpath, **options, &optional_filter_block) end ## # # Checks if the current node matches given CSS selector. # # @param [String] css The CSS selector to match against the current code # @return [Boolean] # def matches_css?(css, **options, &optional_filter_block) matches_selector?(:css, css, **options, &optional_filter_block) end ## # # Checks if the current node does not match given selector. # Usage is identical to {#has_selector?}. # # @param (see #has_selector?) # @return [Boolean] # def not_matches_selector?(*args, **options, &optional_filter_block) make_predicate(options) { assert_not_matches_selector(*args, options, &optional_filter_block) } end ## # # Checks if the current node does not match given XPath expression. # # @param [String, XPath::Expression] xpath The XPath expression to match against the current code # @return [Boolean] # def not_matches_xpath?(xpath, **options, &optional_filter_block) not_matches_selector?(:xpath, xpath, **options, &optional_filter_block) end ## # # Checks if the current node does not match given CSS selector. # # @param [String] css The CSS selector to match against the current code # @return [Boolean] # def not_matches_css?(css, **options, &optional_filter_block) not_matches_selector?(:css, css, **options, &optional_filter_block) end ## # Asserts that the page or current node has the given text content, # ignoring any HTML tags. # # @!macro text_query_params # @overload $0(type, text, **options) # @param [:all, :visible] type Whether to check for only visible or all text. If this parameter is missing or nil then we use the value of {Capybara.configure ignore_hidden_elements}, which defaults to `true`, corresponding to `:visible`. # @param [String, Regexp] text The string/regexp to check for. If it's a string, text is expected to include it. If it's a regexp, text is expected to match it. # @option options [Integer] :count (nil) Number of times the text is expected to occur # @option options [Integer] :minimum (nil) Minimum number of times the text is expected to occur # @option options [Integer] :maximum (nil) Maximum number of times the text is expected to occur # @option options [Range] :between (nil) Range of times that is expected to contain number of times text occurs # @option options [Numeric] :wait Maximum time that Capybara will wait for text to eq/match given string/regexp argument. Defaults to {Capybara.configure default_max_wait_time}. # @option options [Boolean] :exact Whether text must be an exact match or just substring. Defaults to {Capybara.configure exact_text}. # @option options [Boolean] :normalize_ws (false) When `true` replace all whitespace with standard spaces and collapse consecutive whitespace to a single space # @overload $0(text, **options) # @param [String, Regexp] text The string/regexp to check for. If it's a string, text is expected to include it. If it's a regexp, text is expected to match it. # @option options [Integer] :count (nil) Number of times the text is expected to occur # @option options [Integer] :minimum (nil) Minimum number of times the text is expected to occur # @option options [Integer] :maximum (nil) Maximum number of times the text is expected to occur # @option options [Range] :between (nil) Range of times that is expected to contain number of times text occurs # @option options [Numeric] :wait Maximum time that Capybara will wait for text to eq/match given string/regexp argument. Defaults to {Capybara.configure default_max_wait_time}. # @option options [Boolean] :exact Whether text must be an exact match or just substring. Defaults to {Capybara.configure exact_text}. # @option options [Boolean] :normalize_ws (false) When `true` replace all whitespace with standard spaces and collapse consecutive whitespace to a single space # @raise [Capybara::ExpectationNotMet] if the assertion hasn't succeeded during wait time # @return [true] # def assert_text(type_or_text, *args, **opts) _verify_text(type_or_text, *args, **opts) do |count, query| unless query.matches_count?(count) && (count.positive? || query.expects_none?) raise Capybara::ExpectationNotMet, query.failure_message end end end ## # Asserts that the page or current node doesn't have the given text content, # ignoring any HTML tags. # # @macro text_query_params # @raise [Capybara::ExpectationNotMet] if the assertion hasn't succeeded during wait time # @return [true] # def assert_no_text(type_or_text, *args, **opts) _verify_text(type_or_text, *args, **opts) do |count, query| if query.matches_count?(count) && (count.positive? || query.expects_none?) raise Capybara::ExpectationNotMet, query.negative_failure_message end end end ## # Checks if the page or current node has the given text content, # ignoring any HTML tags. # # By default it will check if the text occurs at least once, # but a different number can be specified. # # page.has_text?('lorem ipsum', between: 2..4) # # This will check if the text occurs from 2 to 4 times. # # @macro text_query_params # @return [Boolean] Whether it exists # def has_text?(*args, **options) make_predicate(options) { assert_text(*args, **options) } end alias_method :has_content?, :has_text? ## # Checks if the page or current node does not have the given text # content, ignoring any HTML tags and normalizing whitespace. # # @macro text_query_params # @return [Boolean] Whether it doesn't exist # def has_no_text?(*args, **options) make_predicate(options) { assert_no_text(*args, **options) } end alias_method :has_no_content?, :has_no_text? ## # # Asserts that a given selector matches an ancestor of the current node. # # element.assert_ancestor('p#foo') # # Accepts the same options as {#assert_selector} # # @param (see Capybara::Node::Finders#find) # @raise [Capybara::ExpectationNotMet] If the selector does not exist # def assert_ancestor(*args, &optional_filter_block) _verify_selector_result(args, optional_filter_block, Capybara::Queries::AncestorQuery) do |result, query| unless result.matches_count? && (result.any? || query.expects_none?) raise Capybara::ExpectationNotMet, result.failure_message end end end def assert_no_ancestor(*args, &optional_filter_block) _verify_selector_result(args, optional_filter_block, Capybara::Queries::AncestorQuery) do |result, query| if result.matches_count? && (!result.empty? || query.expects_none?) raise Capybara::ExpectationNotMet, result.negative_failure_message end end end ## # # Predicate version of {#assert_ancestor} # def has_ancestor?(*args, **options, &optional_filter_block) make_predicate(options) { assert_ancestor(*args, options, &optional_filter_block) } end ## # # Predicate version of {#assert_no_ancestor} # def has_no_ancestor?(*args, **options, &optional_filter_block) make_predicate(options) { assert_no_ancestor(*args, options, &optional_filter_block) } end ## # # Asserts that a given selector matches a sibling of the current node. # # element.assert_sibling('p#foo') # # Accepts the same options as {#assert_selector} # # @param (see Capybara::Node::Finders#find) # @raise [Capybara::ExpectationNotMet] If the selector does not exist # def assert_sibling(*args, &optional_filter_block) _verify_selector_result(args, optional_filter_block, Capybara::Queries::SiblingQuery) do |result, query| unless result.matches_count? && (result.any? || query.expects_none?) raise Capybara::ExpectationNotMet, result.failure_message end end end def assert_no_sibling(*args, &optional_filter_block) _verify_selector_result(args, optional_filter_block, Capybara::Queries::SiblingQuery) do |result, query| if result.matches_count? && (!result.empty? || query.expects_none?) raise Capybara::ExpectationNotMet, result.negative_failure_message end end end ## # # Predicate version of {#assert_sibling} # def has_sibling?(*args, **options, &optional_filter_block) make_predicate(options) { assert_sibling(*args, options, &optional_filter_block) } end ## # # Predicate version of {#assert_no_sibling} # def has_no_sibling?(*args, **options, &optional_filter_block) make_predicate(options) { assert_no_sibling(*args, options, &optional_filter_block) } end def ==(other) eql?(other) || (other.respond_to?(:base) && base == other.base) end private def extract_selector(args) args.first.is_a?(Symbol) ? args.shift : session_options.default_selector end def _verify_multiple(*args, wait: nil, **options) wait = session_options.default_max_wait_time if wait.nil? selector = extract_selector(args) synchronize(wait) do args.each { |locator| yield(selector, locator, options) } end end def _verify_selector_result(query_args, optional_filter_block, query_type = Capybara::Queries::SelectorQuery) # query_args, query_opts = if query_args[0].is_a? Symbol # a,o = _set_query_session_options(*query_args.slice(2..)) # [query_args.slice(0..1).concat(a), o] # else # _set_query_session_options(*query_args) # end query_args, query_opts = _set_query_session_options(*query_args) query = query_type.new(*query_args, **query_opts, &optional_filter_block) synchronize(query.wait) do yield query.resolve_for(self), query end true end def _verify_match_result(query_args, optional_filter_block) query_args, query_opts = _set_query_session_options(*query_args) query = Capybara::Queries::MatchQuery.new(*query_args, **query_opts, &optional_filter_block) synchronize(query.wait) do yield query.resolve_for(parent || session&.document || query_scope) end true end def _verify_text(type = nil, expected_text, **query_options) # rubocop:disable Style/OptionalArguments query_options[:session_options] = session_options query = Capybara::Queries::TextQuery.new(type, expected_text, **query_options) synchronize(query.wait) do yield query.resolve_for(self), query end true end def _set_query_session_options(*query_args) query_args, query_options = query_args.dup, {} # query_options = query_args.pop if query_options.empty? && query_args.last.is_a?(Hash) query_options = query_args.pop if query_args.last.is_a?(Hash) query_options[:session_options] = session_options [query_args, query_options] end def make_predicate(options) options[:wait] = 0 unless options.key?(:wait) || session_options.predicates_wait yield rescue Capybara::ExpectationNotMet false end end end end
Ruby
{ "end_line": 215, "name": "assert_any_of_selectors", "signature": "def assert_any_of_selectors(*args, wait: nil, **options, &optional_filter_block)", "start_line": 201 }
{ "class_name": "", "class_signature": "", "module": "Capybara" }
[]
capybara/lib/capybara/node/simple.rb
def [](name) attr_name = name.to_s if attr_name == 'value' value elsif (tag_name == 'input') && (native[:type] == 'checkbox') && (attr_name == 'checked') native['checked'] == 'checked' else native[attr_name] end end
# frozen_string_literal: true module Capybara module Node ## # # A {Capybara::Node::Simple} is a simpler version of {Capybara::Node::Base} which # includes only {Capybara::Node::Finders} and {Capybara::Node::Matchers} and does # not include {Capybara::Node::Actions}. This type of node is returned when # using {Capybara.string}. # # It is useful in that it does not require a session, an application or a driver, # but can still use Capybara's finders and matchers on any string that contains HTML. # class Simple include Capybara::Node::Finders include Capybara::Node::Matchers include Capybara::Node::DocumentMatchers attr_reader :native def initialize(native) native = Capybara::HTML(native) if native.is_a?(String) @native = native end ## # # @return [String] The text of the element # def text(_type = nil, normalize_ws: false) txt = native.text normalize_ws ? txt.gsub(/[[:space:]]+/, ' ').strip : txt end ## # # Retrieve the given attribute # # element[:title] # => HTML title attribute # # @param [Symbol] name The attribute name to retrieve # @return [String] The value of the attribute # def [](name) attr_name = name.to_s if attr_name == 'value' value elsif (tag_name == 'input') && (native[:type] == 'checkbox') && (attr_name == 'checked') native['checked'] == 'checked' else native[attr_name] end end ## # # @return [String] The tag name of the element # def tag_name native.node_name end ## # # An XPath expression describing where on the page the element can be found # # @return [String] An XPath expression # def path native.path end ## # # @return [String] The value of the form element # def value if tag_name == 'textarea' native['_capybara_raw_value'] elsif tag_name == 'select' selected_options = find_xpath('.//option[@selected]') if multiple? selected_options.map(&method(:option_value)) else option_value(selected_options.first || find_xpath('.//option').first) end elsif tag_name == 'input' && %w[radio checkbox].include?(native[:type]) native[:value] || 'on' else native[:value] end end ## # # Whether or not the element is visible. Does not support CSS, so # the result may be inaccurate. # # @param [Boolean] check_ancestors Whether to inherit visibility from ancestors # @return [Boolean] Whether the element is visible # def visible?(check_ancestors = true) # rubocop:disable Style/OptionalBooleanParameter return false if (tag_name == 'input') && (native[:type] == 'hidden') return false if tag_name == 'template' if check_ancestors !find_xpath(VISIBILITY_XPATH) else # No need for an xpath if only checking the current element !(native.key?('hidden') || /display:\s?none/.match?(native[:style] || '') || %w[script head style].include?(tag_name)) end end ## # # Whether or not the element is checked. # # @return [Boolean] Whether the element is checked # def checked? native.has_attribute?('checked') end ## # # Whether or not the element is disabled. # # @return [Boolean] Whether the element is disabled def disabled? native.has_attribute?('disabled') && %w[button input select textarea optgroup option menuitem fieldset].include?(tag_name) end ## # # Whether or not the element is selected. # # @return [Boolean] Whether the element is selected # def selected? native.has_attribute?('selected') end def multiple? native.has_attribute?('multiple') end def readonly? native.has_attribute?('readonly') end def synchronize(_seconds = nil) yield # simple nodes don't need to wait end def allow_reload!(*) # no op end ## # # @return [String] The title of the document def title native.title end def inspect %(#<Capybara::Node::Simple tag="#{tag_name}" path="#{path}">) end # @api private def find_css(css, **_options) native.css(css) end # @api private def find_xpath(xpath, **_options) native.xpath(xpath) end # @api private def session_options Capybara.session_options end # @api private def initial_cache {} end def ==(other) eql?(other) || (other.respond_to?(:native) && native == other.native) end private def option_value(option) return nil if option.nil? option[:value] || option.content end VISIBILITY_XPATH = XPath.generate do |x| x.ancestor_or_self[ x.attr(:style)[x.contains('display:none') | x.contains('display: none')] | x.attr(:hidden) | x.qname.one_of('script', 'head') | (~x.self(:summary) & XPath.parent(:details)[!XPath.attr(:open)]) ].boolean end.to_s.freeze end end end
Ruby
{ "end_line": 54, "name": "[]", "signature": "def [](name)", "start_line": 45 }
{ "class_name": "Simple", "class_signature": "class Simple", "module": "Capybara" }
value
capybara/lib/capybara/node/simple.rb
def value if tag_name == 'textarea' native['_capybara_raw_value'] elsif tag_name == 'select' selected_options = find_xpath('.//option[@selected]') if multiple? selected_options.map(&method(:option_value)) else option_value(selected_options.first || find_xpath('.//option').first) end elsif tag_name == 'input' && %w[radio checkbox].include?(native[:type]) native[:value] || 'on' else native[:value] end end
# frozen_string_literal: true module Capybara module Node ## # # A {Capybara::Node::Simple} is a simpler version of {Capybara::Node::Base} which # includes only {Capybara::Node::Finders} and {Capybara::Node::Matchers} and does # not include {Capybara::Node::Actions}. This type of node is returned when # using {Capybara.string}. # # It is useful in that it does not require a session, an application or a driver, # but can still use Capybara's finders and matchers on any string that contains HTML. # class Simple include Capybara::Node::Finders include Capybara::Node::Matchers include Capybara::Node::DocumentMatchers attr_reader :native def initialize(native) native = Capybara::HTML(native) if native.is_a?(String) @native = native end ## # # @return [String] The text of the element # def text(_type = nil, normalize_ws: false) txt = native.text normalize_ws ? txt.gsub(/[[:space:]]+/, ' ').strip : txt end ## # # Retrieve the given attribute # # element[:title] # => HTML title attribute # # @param [Symbol] name The attribute name to retrieve # @return [String] The value of the attribute # def [](name) attr_name = name.to_s if attr_name == 'value' value elsif (tag_name == 'input') && (native[:type] == 'checkbox') && (attr_name == 'checked') native['checked'] == 'checked' else native[attr_name] end end ## # # @return [String] The tag name of the element # def tag_name native.node_name end ## # # An XPath expression describing where on the page the element can be found # # @return [String] An XPath expression # def path native.path end ## # # @return [String] The value of the form element # def value if tag_name == 'textarea' native['_capybara_raw_value'] elsif tag_name == 'select' selected_options = find_xpath('.//option[@selected]') if multiple? selected_options.map(&method(:option_value)) else option_value(selected_options.first || find_xpath('.//option').first) end elsif tag_name == 'input' && %w[radio checkbox].include?(native[:type]) native[:value] || 'on' else native[:value] end end ## # # Whether or not the element is visible. Does not support CSS, so # the result may be inaccurate. # # @param [Boolean] check_ancestors Whether to inherit visibility from ancestors # @return [Boolean] Whether the element is visible # def visible?(check_ancestors = true) # rubocop:disable Style/OptionalBooleanParameter return false if (tag_name == 'input') && (native[:type] == 'hidden') return false if tag_name == 'template' if check_ancestors !find_xpath(VISIBILITY_XPATH) else # No need for an xpath if only checking the current element !(native.key?('hidden') || /display:\s?none/.match?(native[:style] || '') || %w[script head style].include?(tag_name)) end end ## # # Whether or not the element is checked. # # @return [Boolean] Whether the element is checked # def checked? native.has_attribute?('checked') end ## # # Whether or not the element is disabled. # # @return [Boolean] Whether the element is disabled def disabled? native.has_attribute?('disabled') && %w[button input select textarea optgroup option menuitem fieldset].include?(tag_name) end ## # # Whether or not the element is selected. # # @return [Boolean] Whether the element is selected # def selected? native.has_attribute?('selected') end def multiple? native.has_attribute?('multiple') end def readonly? native.has_attribute?('readonly') end def synchronize(_seconds = nil) yield # simple nodes don't need to wait end def allow_reload!(*) # no op end ## # # @return [String] The title of the document def title native.title end def inspect %(#<Capybara::Node::Simple tag="#{tag_name}" path="#{path}">) end # @api private def find_css(css, **_options) native.css(css) end # @api private def find_xpath(xpath, **_options) native.xpath(xpath) end # @api private def session_options Capybara.session_options end # @api private def initial_cache {} end def ==(other) eql?(other) || (other.respond_to?(:native) && native == other.native) end private def option_value(option) return nil if option.nil? option[:value] || option.content end VISIBILITY_XPATH = XPath.generate do |x| x.ancestor_or_self[ x.attr(:style)[x.contains('display:none') | x.contains('display: none')] | x.attr(:hidden) | x.qname.one_of('script', 'head') | (~x.self(:summary) & XPath.parent(:details)[!XPath.attr(:open)]) ].boolean end.to_s.freeze end end end
Ruby
{ "end_line": 93, "name": "value", "signature": "def value", "start_line": 78 }
{ "class_name": "Simple", "class_signature": "class Simple", "module": "Capybara" }
visible?
capybara/lib/capybara/node/simple.rb
def visible?(check_ancestors = true) # rubocop:disable Style/OptionalBooleanParameter return false if (tag_name == 'input') && (native[:type] == 'hidden') return false if tag_name == 'template' if check_ancestors !find_xpath(VISIBILITY_XPATH) else # No need for an xpath if only checking the current element !(native.key?('hidden') || /display:\s?none/.match?(native[:style] || '') || %w[script head style].include?(tag_name)) end end
# frozen_string_literal: true module Capybara module Node ## # # A {Capybara::Node::Simple} is a simpler version of {Capybara::Node::Base} which # includes only {Capybara::Node::Finders} and {Capybara::Node::Matchers} and does # not include {Capybara::Node::Actions}. This type of node is returned when # using {Capybara.string}. # # It is useful in that it does not require a session, an application or a driver, # but can still use Capybara's finders and matchers on any string that contains HTML. # class Simple include Capybara::Node::Finders include Capybara::Node::Matchers include Capybara::Node::DocumentMatchers attr_reader :native def initialize(native) native = Capybara::HTML(native) if native.is_a?(String) @native = native end ## # # @return [String] The text of the element # def text(_type = nil, normalize_ws: false) txt = native.text normalize_ws ? txt.gsub(/[[:space:]]+/, ' ').strip : txt end ## # # Retrieve the given attribute # # element[:title] # => HTML title attribute # # @param [Symbol] name The attribute name to retrieve # @return [String] The value of the attribute # def [](name) attr_name = name.to_s if attr_name == 'value' value elsif (tag_name == 'input') && (native[:type] == 'checkbox') && (attr_name == 'checked') native['checked'] == 'checked' else native[attr_name] end end ## # # @return [String] The tag name of the element # def tag_name native.node_name end ## # # An XPath expression describing where on the page the element can be found # # @return [String] An XPath expression # def path native.path end ## # # @return [String] The value of the form element # def value if tag_name == 'textarea' native['_capybara_raw_value'] elsif tag_name == 'select' selected_options = find_xpath('.//option[@selected]') if multiple? selected_options.map(&method(:option_value)) else option_value(selected_options.first || find_xpath('.//option').first) end elsif tag_name == 'input' && %w[radio checkbox].include?(native[:type]) native[:value] || 'on' else native[:value] end end ## # # Whether or not the element is visible. Does not support CSS, so # the result may be inaccurate. # # @param [Boolean] check_ancestors Whether to inherit visibility from ancestors # @return [Boolean] Whether the element is visible # def visible?(check_ancestors = true) # rubocop:disable Style/OptionalBooleanParameter return false if (tag_name == 'input') && (native[:type] == 'hidden') return false if tag_name == 'template' if check_ancestors !find_xpath(VISIBILITY_XPATH) else # No need for an xpath if only checking the current element !(native.key?('hidden') || /display:\s?none/.match?(native[:style] || '') || %w[script head style].include?(tag_name)) end end ## # # Whether or not the element is checked. # # @return [Boolean] Whether the element is checked # def checked? native.has_attribute?('checked') end ## # # Whether or not the element is disabled. # # @return [Boolean] Whether the element is disabled def disabled? native.has_attribute?('disabled') && %w[button input select textarea optgroup option menuitem fieldset].include?(tag_name) end ## # # Whether or not the element is selected. # # @return [Boolean] Whether the element is selected # def selected? native.has_attribute?('selected') end def multiple? native.has_attribute?('multiple') end def readonly? native.has_attribute?('readonly') end def synchronize(_seconds = nil) yield # simple nodes don't need to wait end def allow_reload!(*) # no op end ## # # @return [String] The title of the document def title native.title end def inspect %(#<Capybara::Node::Simple tag="#{tag_name}" path="#{path}">) end # @api private def find_css(css, **_options) native.css(css) end # @api private def find_xpath(xpath, **_options) native.xpath(xpath) end # @api private def session_options Capybara.session_options end # @api private def initial_cache {} end def ==(other) eql?(other) || (other.respond_to?(:native) && native == other.native) end private def option_value(option) return nil if option.nil? option[:value] || option.content end VISIBILITY_XPATH = XPath.generate do |x| x.ancestor_or_self[ x.attr(:style)[x.contains('display:none') | x.contains('display: none')] | x.attr(:hidden) | x.qname.one_of('script', 'head') | (~x.self(:summary) & XPath.parent(:details)[!XPath.attr(:open)]) ].boolean end.to_s.freeze end end end
Ruby
{ "end_line": 115, "name": "visible?", "signature": "def visible?(check_ancestors = true) # rubocop:disable Style/OptionalBooleanParameter", "start_line": 103 }
{ "class_name": "Simple", "class_signature": "class Simple", "module": "Capybara" }
resolve_for
capybara/lib/capybara/queries/ancestor_query.rb
def resolve_for(node, exact = nil) @child_node = node node.synchronize do scope = node.respond_to?(:session) ? node.session.current_scope : node.find(:xpath, '/*') match_results = super(scope, exact) ancestors = node.find_xpath(XPath.ancestor.to_s) .map(&method(:to_element)) .select { |el| match_results.include?(el) } Capybara::Result.new(ordered_results(ancestors), self) end end
# frozen_string_literal: true module Capybara module Queries class AncestorQuery < Capybara::Queries::SelectorQuery # @api private def resolve_for(node, exact = nil) @child_node = node node.synchronize do scope = node.respond_to?(:session) ? node.session.current_scope : node.find(:xpath, '/*') match_results = super(scope, exact) ancestors = node.find_xpath(XPath.ancestor.to_s) .map(&method(:to_element)) .select { |el| match_results.include?(el) } Capybara::Result.new(ordered_results(ancestors), self) end end def description(applied = false) # rubocop:disable Style/OptionalBooleanParameter child_query = @child_node&.instance_variable_get(:@query) desc = super desc += " that is an ancestor of #{child_query.description}" if child_query desc end end end end
Ruby
{ "end_line": 18, "name": "resolve_for", "signature": "def resolve_for(node, exact = nil)", "start_line": 7 }
{ "class_name": "AncestorQuery", "class_signature": "class AncestorQuery < < Capybara::Queries::SelectorQuery", "module": "Capybara" }
count_message
capybara/lib/capybara/queries/base_query.rb
def count_message message = +'' count, between, maximum, minimum = options.values_at(:count, :between, :maximum, :minimum) if count message << " #{occurrences count}" elsif between message << " between #{between.begin ? between.first : 1} and " \ "#{between.end ? between.last : 'infinite'} times" elsif maximum message << " at most #{occurrences maximum}" elsif minimum message << " at least #{occurrences minimum}" end message end
# frozen_string_literal: true module Capybara # @api private module Queries class BaseQuery COUNT_KEYS = %i[count minimum maximum between].freeze attr_reader :options attr_writer :session_options def initialize(options) @session_options = options.delete(:session_options) end def session_options @session_options || Capybara.session_options end def wait self.class.wait(options, session_options.default_max_wait_time) end def self.wait(options, default = Capybara.default_max_wait_time) # if no value or nil for the :wait option is passed it should default to the default wait = options.fetch(:wait, nil) wait = default if wait.nil? wait || 0 end ## # # Checks if a count of 0 is valid for the query # Returns false if query does not have any count options specified. # def expects_none? count_specified? ? matches_count?(0) : false end ## # # Checks if the given count matches the query count options. # Defaults to true if no count options are specified. If multiple # count options exist, it tests that all conditions are met; # however, if :count is specified, all other options are ignored. # # @param [Integer] count The actual number. Should be coercible via Integer() # def matches_count?(count) return (Integer(options[:count]) == count) if options[:count] return false if options[:maximum] && (Integer(options[:maximum]) < count) return false if options[:minimum] && (Integer(options[:minimum]) > count) return false if options[:between] && !options[:between].include?(count) true end ## # # Generates a failure message from the query description and count options. # def failure_message "expected to find #{description}" << count_message end def negative_failure_message "expected not to find #{description}" << count_message end private def count_specified? COUNT_KEYS.any? { |key| options.key? key } end def count_message message = +'' count, between, maximum, minimum = options.values_at(:count, :between, :maximum, :minimum) if count message << " #{occurrences count}" elsif between message << " between #{between.begin ? between.first : 1} and " \ "#{between.end ? between.last : 'infinite'} times" elsif maximum message << " at most #{occurrences maximum}" elsif minimum message << " at least #{occurrences minimum}" end message end def occurrences(count) "#{count} #{Capybara::Helpers.declension('time', 'times', count)}" end def assert_valid_keys invalid_keys = @options.keys - valid_keys return if invalid_keys.empty? invalid_names = invalid_keys.map(&:inspect).join(', ') valid_names = valid_keys.map(&:inspect).join(', ') raise ArgumentError, "Invalid option(s) #{invalid_names}, should be one of #{valid_names}" end end end end
Ruby
{ "end_line": 90, "name": "count_message", "signature": "def count_message", "start_line": 76 }
{ "class_name": "BaseQuery", "class_signature": "class BaseQuery", "module": "Capybara" }
initialize
capybara/lib/capybara/queries/current_path_query.rb
def initialize(expected_path, **options, &optional_filter_block) super(options) @expected_path = expected_path @options = { url: !@expected_path.is_a?(Regexp) && !::Addressable::URI.parse(@expected_path || '').hostname.nil?, ignore_query: false }.merge(options) @filter_block = optional_filter_block assert_valid_keys end
# frozen_string_literal: true require 'addressable/uri' module Capybara # @api private module Queries class CurrentPathQuery < BaseQuery def initialize(expected_path, **options, &optional_filter_block) super(options) @expected_path = expected_path @options = { url: !@expected_path.is_a?(Regexp) && !::Addressable::URI.parse(@expected_path || '').hostname.nil?, ignore_query: false }.merge(options) @filter_block = optional_filter_block assert_valid_keys end def resolves_for?(session) uri = ::Addressable::URI.parse(session.current_url) @actual_path = (options[:ignore_query] ? uri&.omit(:query) : uri).then do |u| options[:url] ? u&.to_s : u&.request_uri end res = if @expected_path.is_a? Regexp @actual_path.to_s.match?(@expected_path) else ::Addressable::URI.parse(@expected_path) == ::Addressable::URI.parse(@actual_path) end res && matches_filter_block?(uri) end def failure_message failure_message_helper end def negative_failure_message failure_message_helper(' not') end private def matches_filter_block?(url) return true unless @filter_block @filter_block.call(url) end def failure_message_helper(negated = '') verb = @expected_path.is_a?(Regexp) ? 'match' : 'equal' "expected #{@actual_path.inspect}#{negated} to #{verb} #{@expected_path.inspect}" end def valid_keys %i[wait url ignore_query] end end end end
Ruby
{ "end_line": 18, "name": "initialize", "signature": "def initialize(expected_path, **options, &optional_filter_block)", "start_line": 9 }
{ "class_name": "CurrentPathQuery", "class_signature": "class CurrentPathQuery < < BaseQuery", "module": "Capybara" }
resolves_for?
capybara/lib/capybara/queries/current_path_query.rb
def resolves_for?(session) uri = ::Addressable::URI.parse(session.current_url) @actual_path = (options[:ignore_query] ? uri&.omit(:query) : uri).then do |u| options[:url] ? u&.to_s : u&.request_uri end res = if @expected_path.is_a? Regexp @actual_path.to_s.match?(@expected_path) else ::Addressable::URI.parse(@expected_path) == ::Addressable::URI.parse(@actual_path) end res && matches_filter_block?(uri) end
# frozen_string_literal: true require 'addressable/uri' module Capybara # @api private module Queries class CurrentPathQuery < BaseQuery def initialize(expected_path, **options, &optional_filter_block) super(options) @expected_path = expected_path @options = { url: !@expected_path.is_a?(Regexp) && !::Addressable::URI.parse(@expected_path || '').hostname.nil?, ignore_query: false }.merge(options) @filter_block = optional_filter_block assert_valid_keys end def resolves_for?(session) uri = ::Addressable::URI.parse(session.current_url) @actual_path = (options[:ignore_query] ? uri&.omit(:query) : uri).then do |u| options[:url] ? u&.to_s : u&.request_uri end res = if @expected_path.is_a? Regexp @actual_path.to_s.match?(@expected_path) else ::Addressable::URI.parse(@expected_path) == ::Addressable::URI.parse(@actual_path) end res && matches_filter_block?(uri) end def failure_message failure_message_helper end def negative_failure_message failure_message_helper(' not') end private def matches_filter_block?(url) return true unless @filter_block @filter_block.call(url) end def failure_message_helper(negated = '') verb = @expected_path.is_a?(Regexp) ? 'match' : 'equal' "expected #{@actual_path.inspect}#{negated} to #{verb} #{@expected_path.inspect}" end def valid_keys %i[wait url ignore_query] end end end end
Ruby
{ "end_line": 33, "name": "resolves_for?", "signature": "def resolves_for?(session)", "start_line": 20 }
{ "class_name": "CurrentPathQuery", "class_signature": "class CurrentPathQuery < < BaseQuery", "module": "Capybara" }
initialize
capybara/lib/capybara/queries/selector_query.rb
def initialize(*args, session_options:, enable_aria_label: session_options.enable_aria_label, enable_aria_role: session_options.enable_aria_role, test_id: session_options.test_id, selector_format: nil, order: nil, **options, &filter_block) @resolved_node = nil @resolved_count = 0 @options = options.dup @order = order @filter_cache = Hash.new { |hsh, key| hsh[key] = {} } if @options[:text].is_a?(Regexp) && [true, false].include?(@options[:exact_text]) Capybara::Helpers.warn( "Boolean 'exact_text' option is not supported when 'text' option is a Regexp - ignoring" ) end super(@options) self.session_options = session_options @selector = Selector.new( find_selector(args[0].is_a?(Symbol) ? args.shift : args[0]), config: { enable_aria_label: enable_aria_label, enable_aria_role: enable_aria_role, test_id: test_id }, format: selector_format ) @locator = args.shift @filter_block = filter_block raise ArgumentError, "Unused parameters passed to #{self.class.name} : #{args}" unless args.empty? @expression = selector.call(@locator, **@options) warn_exact_usage assert_valid_keys end
# frozen_string_literal: true require 'matrix' module Capybara module Queries class SelectorQuery < Queries::BaseQuery attr_reader :expression, :selector, :locator, :options SPATIAL_KEYS = %i[above below left_of right_of near].freeze VALID_KEYS = SPATIAL_KEYS + COUNT_KEYS + %i[text id class style visible obscured exact exact_text normalize_ws match wait filter_set focused] VALID_MATCH = %i[first smart prefer_exact one].freeze def initialize(*args, session_options:, enable_aria_label: session_options.enable_aria_label, enable_aria_role: session_options.enable_aria_role, test_id: session_options.test_id, selector_format: nil, order: nil, **options, &filter_block) @resolved_node = nil @resolved_count = 0 @options = options.dup @order = order @filter_cache = Hash.new { |hsh, key| hsh[key] = {} } if @options[:text].is_a?(Regexp) && [true, false].include?(@options[:exact_text]) Capybara::Helpers.warn( "Boolean 'exact_text' option is not supported when 'text' option is a Regexp - ignoring" ) end super(@options) self.session_options = session_options @selector = Selector.new( find_selector(args[0].is_a?(Symbol) ? args.shift : args[0]), config: { enable_aria_label: enable_aria_label, enable_aria_role: enable_aria_role, test_id: test_id }, format: selector_format ) @locator = args.shift @filter_block = filter_block raise ArgumentError, "Unused parameters passed to #{self.class.name} : #{args}" unless args.empty? @expression = selector.call(@locator, **@options) warn_exact_usage assert_valid_keys end def name; selector.name; end def label; selector.label || selector.name; end def description(only_applied = false) # rubocop:disable Style/OptionalBooleanParameter desc = +'' show_for = show_for_stage(only_applied) if show_for[:any] desc << 'visible ' if visible == :visible desc << 'non-visible ' if visible == :hidden end desc << label.to_s desc << " #{locator.inspect}" unless locator.nil? if show_for[:any] desc << " with#{' exact' if exact_text == true} text #{options[:text].inspect}" if options[:text] desc << " with exact text #{exact_text}" if exact_text.is_a?(String) end desc << " with id #{options[:id]}" if options[:id] desc << " with classes [#{Array(options[:class]).join(',')}]" if options[:class] desc << ' that is focused' if options[:focused] desc << ' that is not focused' if options[:focused] == false desc << case options[:style] when String " with style attribute #{options[:style].inspect}" when Regexp " with style attribute matching #{options[:style].inspect}" when Hash " with styles #{options[:style].inspect}" else '' end %i[above below left_of right_of near].each do |spatial_filter| if options[spatial_filter] && show_for[:spatial] desc << " #{spatial_filter} #{options[spatial_filter] rescue '<ERROR>'}" # rubocop:disable Style/RescueModifier end end desc << selector.description(node_filters: show_for[:node], **options) desc << ' that also matches the custom filter block' if @filter_block && show_for[:node] desc << " within #{@resolved_node.inspect}" if describe_within? if locator.is_a?(String) && locator.start_with?('#', './/', '//') && !selector.raw_locator? desc << "\nNote: It appears you may be passing a CSS selector or XPath expression rather than a locator. " \ "Please see the documentation for acceptable locator values.\n\n" end desc end def applied_description description(true) end def matches_filters?(node, node_filter_errors = []) return true if (@resolved_node&.== node) && options[:allow_self] matches_locator_filter?(node) && matches_system_filters?(node) && matches_spatial_filters?(node) && matches_node_filters?(node, node_filter_errors) && matches_filter_block?(node) rescue *(node.respond_to?(:session) ? node.session.driver.invalid_element_errors : []) false end def visible case (vis = options.fetch(:visible) { default_visibility }) when true then :visible when false then :all else vis end end def exact? supports_exact? ? options.fetch(:exact, session_options.exact) : false end def match options.fetch(:match, session_options.match) end def xpath(exact = nil) exact = exact? if exact.nil? expr = apply_expression_filters(@expression) expr = exact ? expr.to_xpath(:exact) : expr.to_s if expr.respond_to?(:to_xpath) expr = filtered_expression(expr) expr = "(#{expr})[#{xpath_text_conditions}]" if try_text_match_in_expression? expr end def css filtered_expression(apply_expression_filters(@expression)) end # @api private def resolve_for(node, exact = nil) applied_filters.clear @filter_cache.clear @resolved_node = node @resolved_count += 1 node.synchronize do children = find_nodes_by_selector_format(node, exact).map(&method(:to_element)) Capybara::Result.new(ordered_results(children), self) end end # @api private def supports_exact? return @expression.respond_to? :to_xpath if @selector.supports_exact?.nil? @selector.supports_exact? end def failure_message "expected to find #{applied_description}" << count_message end def negative_failure_message "expected not to find #{applied_description}" << count_message end private def selector_format @selector.format end def matching_text options[:text] || options[:exact_text] end def text_fragments (text = matching_text).is_a?(String) ? text.split : [] end def xpath_text_conditions case (text = matching_text) when String text.split.map { |txt| XPath.contains(txt) }.reduce(&:&) when Regexp condition = XPath.current condition = condition.uppercase if text.casefold? Selector::RegexpDisassembler.new(text).alternated_substrings.map do |strs| strs.flat_map(&:split).map { |str| condition.contains(str) }.reduce(:&) end.reduce(:|) end end def try_text_match_in_expression? first_try? && matching_text && @resolved_node.is_a?(Capybara::Node::Base) && @resolved_node.session&.driver&.wait? end def first_try? @resolved_count == 1 end def show_for_stage(only_applied) lambda do |stage = :any| !only_applied || (stage == :any ? applied_filters.any? : applied_filters.include?(stage)) end end def applied_filters @applied_filters ||= [] end def find_selector(locator) case locator when Symbol then Selector[locator] else Selector.for(locator) end || Selector[session_options.default_selector] end def find_nodes_by_selector_format(node, exact) hints = {} hints[:uses_visibility] = true unless visible == :all hints[:texts] = text_fragments unless selector_format == :xpath hints[:styles] = options[:style] if use_default_style_filter? hints[:position] = true if use_spatial_filter? case selector_format when :css if node.method(:find_css).arity == 1 node.find_css(css) else node.find_css(css, **hints) end when :xpath if node.method(:find_xpath).arity == 1 node.find_xpath(xpath(exact)) else node.find_xpath(xpath(exact), **hints) end else raise ArgumentError, "Unknown format: #{selector_format}" end end def to_element(node) if @resolved_node.is_a?(Capybara::Node::Base) Capybara::Node::Element.new(@resolved_node.session, node, @resolved_node, self) else Capybara::Node::Simple.new(node) end end def valid_keys (VALID_KEYS + custom_keys).uniq end def matches_node_filters?(node, errors) applied_filters << :node unapplied_options = options.keys - valid_keys @selector.with_filter_errors(errors) do node_filters.all? do |filter_name, filter| next true unless apply_filter?(filter) if filter.matcher? unapplied_options.select { |option_name| filter.handles_option?(option_name) }.all? do |option_name| unapplied_options.delete(option_name) filter.matches?(node, option_name, options[option_name], @selector) end elsif options.key?(filter_name) unapplied_options.delete(filter_name) filter.matches?(node, filter_name, options[filter_name], @selector) elsif filter.default? filter.matches?(node, filter_name, filter.default, @selector) else true end end end end def matches_filter_block?(node) return true unless @filter_block if node.respond_to?(:session) node.session.using_wait_time(0) { @filter_block.call(node) } else @filter_block.call(node) end end def filter_set(name) ::Capybara::Selector::FilterSet[name] end def node_filters if options.key?(:filter_set) filter_set(options[:filter_set]) else @selector end.node_filters end def expression_filters filters = @selector.expression_filters filters.merge filter_set(options[:filter_set]).expression_filters if options.key?(:filter_set) filters end def ordered_results(results) case @order when :reverse results.reverse else results end end def custom_keys @custom_keys ||= node_filters.keys + expression_filters.keys end def assert_valid_keys unless VALID_MATCH.include?(match) raise ArgumentError, "Invalid option #{match.inspect} for :match, should be one of #{VALID_MATCH.map(&:inspect).join(', ')}" end unhandled_options = @options.keys.reject do |option_name| valid_keys.include?(option_name) || expression_filters.any? { |_name, ef| ef.handles_option? option_name } || node_filters.any? { |_name, nf| nf.handles_option? option_name } end return if unhandled_options.empty? invalid_names = unhandled_options.map(&:inspect).join(', ') valid_names = (valid_keys - [:allow_self]).map(&:inspect).join(', ') raise ArgumentError, "Invalid option(s) #{invalid_names}, should be one of #{valid_names}" end def filtered_expression(expr) conditions = {} conditions[:id] = options[:id] if use_default_id_filter? conditions[:class] = options[:class] if use_default_class_filter? conditions[:style] = options[:style] if use_default_style_filter? && !options[:style].is_a?(Hash) builder(expr).add_attribute_conditions(**conditions) end def use_default_id_filter? options.key?(:id) && !custom_keys.include?(:id) end def use_default_class_filter? options.key?(:class) && !custom_keys.include?(:class) end def use_default_style_filter? options.key?(:style) && !custom_keys.include?(:style) end def use_default_focused_filter? options.key?(:focused) && !custom_keys.include?(:focused) end def use_spatial_filter? options.values_at(*SPATIAL_KEYS).compact.any? end def apply_expression_filters(expression) unapplied_options = options.keys - valid_keys expression_filters.inject(expression) do |expr, (name, ef)| next expr unless apply_filter?(ef) if ef.matcher? unapplied_options.select(&ef.method(:handles_option?)).inject(expr) do |memo, option_name| unapplied_options.delete(option_name) ef.apply_filter(memo, option_name, options[option_name], @selector) end elsif options.key?(name) unapplied_options.delete(name) ef.apply_filter(expr, name, options[name], @selector) elsif ef.default? ef.apply_filter(expr, name, ef.default, @selector) else expr end end end def warn_exact_usage return unless options.key?(:exact) && !supports_exact? warn "The :exact option only has an effect on queries using the XPath#is method. Using it with the query \"#{expression}\" has no effect." end def exact_text options.fetch(:exact_text, session_options.exact_text) end def describe_within? @resolved_node && !document?(@resolved_node) && !simple_root?(@resolved_node) end def document?(node) node.is_a?(::Capybara::Node::Document) end def simple_root?(node) node.is_a?(::Capybara::Node::Simple) && node.path == '/' end def apply_filter?(filter) filter.format.nil? || (filter.format == selector_format) end def matches_locator_filter?(node) return true unless @selector.locator_filter && apply_filter?(@selector.locator_filter) @selector.locator_filter.matches?(node, @locator, @selector, exact: exact?) end def matches_system_filters?(node) applied_filters << :system matches_visibility_filters?(node) && matches_id_filter?(node) && matches_class_filter?(node) && matches_style_filter?(node) && matches_focused_filter?(node) && matches_text_filter?(node) && matches_exact_text_filter?(node) end def matches_spatial_filters?(node) applied_filters << :spatial return true unless use_spatial_filter? node_rect = Rectangle.new(node.initial_cache[:position] || node.rect) if options[:above] el_rect = rect_cache(options[:above]) return false unless node_rect.above? el_rect end if options[:below] el_rect = rect_cache(options[:below]) return false unless node_rect.below? el_rect end if options[:left_of] el_rect = rect_cache(options[:left_of]) return false unless node_rect.left_of? el_rect end if options[:right_of] el_rect = rect_cache(options[:right_of]) return false unless node_rect.right_of? el_rect end if options[:near] return false if node == options[:near] el_rect = rect_cache(options[:near]) return false unless node_rect.near? el_rect end true end def matches_id_filter?(node) return true unless use_default_id_filter? && options[:id].is_a?(Regexp) options[:id].match? node[:id] end def matches_class_filter?(node) return true unless use_default_class_filter? && need_to_process_classes? if options[:class].is_a? Regexp options[:class].match? node[:class] else classes = (node[:class] || '').split options[:class].select { |c| c.is_a? Regexp }.all? do |r| classes.any? { |cls| r.match? cls } end end end def matches_focused_filter?(node) return true unless use_default_focused_filter? (node == node.session.active_element) == options[:focused] end def need_to_process_classes? case options[:class] when Regexp then true when Array then options[:class].any?(Regexp) else false end end def matches_style_filter?(node) case options[:style] when String, nil true when Regexp options[:style].match? node[:style] when Hash matches_style?(node, options[:style]) end end def matches_style?(node, styles) @actual_styles = node.initial_cache[:style] || node.style(*styles.keys) styles.all? do |style, value| if value.is_a? Regexp value.match? @actual_styles[style.to_s] else @actual_styles[style.to_s] == value end end end def matches_text_filter?(node) value = options[:text] return true unless value return matches_text_exactly?(node, value) if exact_text == true && !value.is_a?(Regexp) regexp = value.is_a?(Regexp) ? value : Regexp.escape(value.to_s) matches_text_regexp?(node, regexp) end def matches_exact_text_filter?(node) case exact_text when String, Regexp matches_text_exactly?(node, exact_text) else true end end def matches_visibility_filters?(node) obscured = options[:obscured] return (visible != :hidden) && (node.initial_cache[:visible] != false) && !node.obscured? if obscured == false vis = case visible when :visible node.initial_cache[:visible] || (node.initial_cache[:visible].nil? && node.visible?) when :hidden # TODO: check why the 'visbile' cache spelling mistake wasn't caught in a test # (node.initial_cache[:visible] == false) || (node.initial_cache[:visbile].nil? && !node.visible?) (node.initial_cache[:visible] == false) || (node.initial_cache[:visible].nil? && !node.visible?) else true end vis && case obscured when true node.obscured? when false !node.obscured? else true end end def matches_text_exactly?(node, value) regexp = value.is_a?(Regexp) ? value : /\A#{Regexp.escape(value.to_s)}\z/ matches_text_regexp(node, regexp).then { |m| m&.pre_match == '' && m&.post_match == '' } end def normalize_ws options.fetch(:normalize_ws, session_options.default_normalize_ws) end def matches_text_regexp(node, regexp) text_visible = visible text_visible = :all if text_visible == :hidden node.text(text_visible, normalize_ws: normalize_ws).match(regexp) end def matches_text_regexp?(node, regexp) !matches_text_regexp(node, regexp).nil? end def default_visibility @selector.default_visibility(session_options.ignore_hidden_elements, options) end def builder(expr) selector.builder(expr) end def position_cache(key) @filter_cache[key][:position] ||= key.rect end def rect_cache(key) @filter_cache[key][:rect] ||= Rectangle.new(position_cache(key)) end class Rectangle attr_reader :top, :bottom, :left, :right def initialize(position) # rubocop:disable Style/RescueModifier @top = position['top'] rescue position['y'] @bottom = position['bottom'] rescue (@top + position['height']) @left = position['left'] rescue position['x'] @right = position['right'] rescue (@left + position['width']) # rubocop:enable Style/RescueModifier end def distance(other) distance = Float::INFINITY line_segments.each do |ls1| other.line_segments.each do |ls2| distance = [ distance, distance_segment_segment(*ls1, *ls2) ].min end end distance end def above?(other) bottom <= other.top end def below?(other) top >= other.bottom end def left_of?(other) right <= other.left end def right_of?(other) left >= other.right end def near?(other) distance(other) <= 50 end protected def line_segments [ [Vector[top, left], Vector[top, right]], [Vector[top, right], Vector[bottom, left]], [Vector[bottom, left], Vector[bottom, right]], [Vector[bottom, right], Vector[top, left]] ] end private def distance_segment_segment(l1p1, l1p2, l2p1, l2p2) # See http://geomalgorithms.com/a07-_distance.html # rubocop:disable Naming/VariableName u = l1p2 - l1p1 v = l2p2 - l2p1 w = l1p1 - l2p1 a = u.dot u b = u.dot v c = v.dot v d = u.dot w e = v.dot w cap_d = (a * c) - (b**2) sD = tD = cap_d # compute the line parameters of the two closest points if cap_d < Float::EPSILON # the lines are almost parallel sN = 0.0 # force using point P0 on segment S1 sD = 1.0 # to prevent possible division by 0.0 later tN = e tD = c else # get the closest points on the infinite lines sN = (b * e) - (c * d) tN = (a * e) - (b * d) if sN.negative? # sc < 0 => the s=0 edge is visible sN = 0 tN = e tD = c elsif sN > sD # sc > 1 => the s=1 edge is visible sN = sD tN = e + b tD = c end end if tN.negative? # tc < 0 => the t=0 edge is visible tN = 0 # recompute sc for this edge if (-d).negative? sN = 0.0 elsif -d > a sN = sD else sN = -d sD = a end elsif tN > tD # tc > 1 => the t=1 edge is visible tN = tD # recompute sc for this edge if (-d + b).negative? sN = 0.0 elsif (-d + b) > a sN = sD else sN = (-d + b) sD = a end end # finally do the division to get sc and tc sc = sN.abs < Float::EPSILON ? 0.0 : sN / sD tc = tN.abs < Float::EPSILON ? 0.0 : tN / tD # difference of the two closest points dP = w + (u * sc) - (v * tc) Math.sqrt(dP.dot(dP)) # rubocop:enable Naming/VariableName end end private_constant :Rectangle end end end
Ruby
{ "end_line": 59, "name": "initialize", "signature": "def initialize(*args,", "start_line": 15 }
{ "class_name": "SelectorQuery", "class_signature": "class SelectorQuery < < Queries::BaseQuery", "module": "Capybara" }
description
capybara/lib/capybara/queries/selector_query.rb
def description(only_applied = false) # rubocop:disable Style/OptionalBooleanParameter desc = +'' show_for = show_for_stage(only_applied) if show_for[:any] desc << 'visible ' if visible == :visible desc << 'non-visible ' if visible == :hidden end desc << label.to_s desc << " #{locator.inspect}" unless locator.nil? if show_for[:any] desc << " with#{' exact' if exact_text == true} text #{options[:text].inspect}" if options[:text] desc << " with exact text #{exact_text}" if exact_text.is_a?(String) end desc << " with id #{options[:id]}" if options[:id] desc << " with classes [#{Array(options[:class]).join(',')}]" if options[:class] desc << ' that is focused' if options[:focused] desc << ' that is not focused' if options[:focused] == false desc << case options[:style] when String " with style attribute #{options[:style].inspect}" when Regexp " with style attribute matching #{options[:style].inspect}" when Hash " with styles #{options[:style].inspect}" else '' end %i[above below left_of right_of near].each do |spatial_filter| if options[spatial_filter] && show_for[:spatial] desc << " #{spatial_filter} #{options[spatial_filter] rescue '<ERROR>'}" # rubocop:disable Style/RescueModifier end end desc << selector.description(node_filters: show_for[:node], **options) desc << ' that also matches the custom filter block' if @filter_block && show_for[:node] desc << " within #{@resolved_node.inspect}" if describe_within? if locator.is_a?(String) && locator.start_with?('#', './/', '//') && !selector.raw_locator? desc << "\nNote: It appears you may be passing a CSS selector or XPath expression rather than a locator. " \ "Please see the documentation for acceptable locator values.\n\n" end desc end
# frozen_string_literal: true require 'matrix' module Capybara module Queries class SelectorQuery < Queries::BaseQuery attr_reader :expression, :selector, :locator, :options SPATIAL_KEYS = %i[above below left_of right_of near].freeze VALID_KEYS = SPATIAL_KEYS + COUNT_KEYS + %i[text id class style visible obscured exact exact_text normalize_ws match wait filter_set focused] VALID_MATCH = %i[first smart prefer_exact one].freeze def initialize(*args, session_options:, enable_aria_label: session_options.enable_aria_label, enable_aria_role: session_options.enable_aria_role, test_id: session_options.test_id, selector_format: nil, order: nil, **options, &filter_block) @resolved_node = nil @resolved_count = 0 @options = options.dup @order = order @filter_cache = Hash.new { |hsh, key| hsh[key] = {} } if @options[:text].is_a?(Regexp) && [true, false].include?(@options[:exact_text]) Capybara::Helpers.warn( "Boolean 'exact_text' option is not supported when 'text' option is a Regexp - ignoring" ) end super(@options) self.session_options = session_options @selector = Selector.new( find_selector(args[0].is_a?(Symbol) ? args.shift : args[0]), config: { enable_aria_label: enable_aria_label, enable_aria_role: enable_aria_role, test_id: test_id }, format: selector_format ) @locator = args.shift @filter_block = filter_block raise ArgumentError, "Unused parameters passed to #{self.class.name} : #{args}" unless args.empty? @expression = selector.call(@locator, **@options) warn_exact_usage assert_valid_keys end def name; selector.name; end def label; selector.label || selector.name; end def description(only_applied = false) # rubocop:disable Style/OptionalBooleanParameter desc = +'' show_for = show_for_stage(only_applied) if show_for[:any] desc << 'visible ' if visible == :visible desc << 'non-visible ' if visible == :hidden end desc << label.to_s desc << " #{locator.inspect}" unless locator.nil? if show_for[:any] desc << " with#{' exact' if exact_text == true} text #{options[:text].inspect}" if options[:text] desc << " with exact text #{exact_text}" if exact_text.is_a?(String) end desc << " with id #{options[:id]}" if options[:id] desc << " with classes [#{Array(options[:class]).join(',')}]" if options[:class] desc << ' that is focused' if options[:focused] desc << ' that is not focused' if options[:focused] == false desc << case options[:style] when String " with style attribute #{options[:style].inspect}" when Regexp " with style attribute matching #{options[:style].inspect}" when Hash " with styles #{options[:style].inspect}" else '' end %i[above below left_of right_of near].each do |spatial_filter| if options[spatial_filter] && show_for[:spatial] desc << " #{spatial_filter} #{options[spatial_filter] rescue '<ERROR>'}" # rubocop:disable Style/RescueModifier end end desc << selector.description(node_filters: show_for[:node], **options) desc << ' that also matches the custom filter block' if @filter_block && show_for[:node] desc << " within #{@resolved_node.inspect}" if describe_within? if locator.is_a?(String) && locator.start_with?('#', './/', '//') && !selector.raw_locator? desc << "\nNote: It appears you may be passing a CSS selector or XPath expression rather than a locator. " \ "Please see the documentation for acceptable locator values.\n\n" end desc end def applied_description description(true) end def matches_filters?(node, node_filter_errors = []) return true if (@resolved_node&.== node) && options[:allow_self] matches_locator_filter?(node) && matches_system_filters?(node) && matches_spatial_filters?(node) && matches_node_filters?(node, node_filter_errors) && matches_filter_block?(node) rescue *(node.respond_to?(:session) ? node.session.driver.invalid_element_errors : []) false end def visible case (vis = options.fetch(:visible) { default_visibility }) when true then :visible when false then :all else vis end end def exact? supports_exact? ? options.fetch(:exact, session_options.exact) : false end def match options.fetch(:match, session_options.match) end def xpath(exact = nil) exact = exact? if exact.nil? expr = apply_expression_filters(@expression) expr = exact ? expr.to_xpath(:exact) : expr.to_s if expr.respond_to?(:to_xpath) expr = filtered_expression(expr) expr = "(#{expr})[#{xpath_text_conditions}]" if try_text_match_in_expression? expr end def css filtered_expression(apply_expression_filters(@expression)) end # @api private def resolve_for(node, exact = nil) applied_filters.clear @filter_cache.clear @resolved_node = node @resolved_count += 1 node.synchronize do children = find_nodes_by_selector_format(node, exact).map(&method(:to_element)) Capybara::Result.new(ordered_results(children), self) end end # @api private def supports_exact? return @expression.respond_to? :to_xpath if @selector.supports_exact?.nil? @selector.supports_exact? end def failure_message "expected to find #{applied_description}" << count_message end def negative_failure_message "expected not to find #{applied_description}" << count_message end private def selector_format @selector.format end def matching_text options[:text] || options[:exact_text] end def text_fragments (text = matching_text).is_a?(String) ? text.split : [] end def xpath_text_conditions case (text = matching_text) when String text.split.map { |txt| XPath.contains(txt) }.reduce(&:&) when Regexp condition = XPath.current condition = condition.uppercase if text.casefold? Selector::RegexpDisassembler.new(text).alternated_substrings.map do |strs| strs.flat_map(&:split).map { |str| condition.contains(str) }.reduce(:&) end.reduce(:|) end end def try_text_match_in_expression? first_try? && matching_text && @resolved_node.is_a?(Capybara::Node::Base) && @resolved_node.session&.driver&.wait? end def first_try? @resolved_count == 1 end def show_for_stage(only_applied) lambda do |stage = :any| !only_applied || (stage == :any ? applied_filters.any? : applied_filters.include?(stage)) end end def applied_filters @applied_filters ||= [] end def find_selector(locator) case locator when Symbol then Selector[locator] else Selector.for(locator) end || Selector[session_options.default_selector] end def find_nodes_by_selector_format(node, exact) hints = {} hints[:uses_visibility] = true unless visible == :all hints[:texts] = text_fragments unless selector_format == :xpath hints[:styles] = options[:style] if use_default_style_filter? hints[:position] = true if use_spatial_filter? case selector_format when :css if node.method(:find_css).arity == 1 node.find_css(css) else node.find_css(css, **hints) end when :xpath if node.method(:find_xpath).arity == 1 node.find_xpath(xpath(exact)) else node.find_xpath(xpath(exact), **hints) end else raise ArgumentError, "Unknown format: #{selector_format}" end end def to_element(node) if @resolved_node.is_a?(Capybara::Node::Base) Capybara::Node::Element.new(@resolved_node.session, node, @resolved_node, self) else Capybara::Node::Simple.new(node) end end def valid_keys (VALID_KEYS + custom_keys).uniq end def matches_node_filters?(node, errors) applied_filters << :node unapplied_options = options.keys - valid_keys @selector.with_filter_errors(errors) do node_filters.all? do |filter_name, filter| next true unless apply_filter?(filter) if filter.matcher? unapplied_options.select { |option_name| filter.handles_option?(option_name) }.all? do |option_name| unapplied_options.delete(option_name) filter.matches?(node, option_name, options[option_name], @selector) end elsif options.key?(filter_name) unapplied_options.delete(filter_name) filter.matches?(node, filter_name, options[filter_name], @selector) elsif filter.default? filter.matches?(node, filter_name, filter.default, @selector) else true end end end end def matches_filter_block?(node) return true unless @filter_block if node.respond_to?(:session) node.session.using_wait_time(0) { @filter_block.call(node) } else @filter_block.call(node) end end def filter_set(name) ::Capybara::Selector::FilterSet[name] end def node_filters if options.key?(:filter_set) filter_set(options[:filter_set]) else @selector end.node_filters end def expression_filters filters = @selector.expression_filters filters.merge filter_set(options[:filter_set]).expression_filters if options.key?(:filter_set) filters end def ordered_results(results) case @order when :reverse results.reverse else results end end def custom_keys @custom_keys ||= node_filters.keys + expression_filters.keys end def assert_valid_keys unless VALID_MATCH.include?(match) raise ArgumentError, "Invalid option #{match.inspect} for :match, should be one of #{VALID_MATCH.map(&:inspect).join(', ')}" end unhandled_options = @options.keys.reject do |option_name| valid_keys.include?(option_name) || expression_filters.any? { |_name, ef| ef.handles_option? option_name } || node_filters.any? { |_name, nf| nf.handles_option? option_name } end return if unhandled_options.empty? invalid_names = unhandled_options.map(&:inspect).join(', ') valid_names = (valid_keys - [:allow_self]).map(&:inspect).join(', ') raise ArgumentError, "Invalid option(s) #{invalid_names}, should be one of #{valid_names}" end def filtered_expression(expr) conditions = {} conditions[:id] = options[:id] if use_default_id_filter? conditions[:class] = options[:class] if use_default_class_filter? conditions[:style] = options[:style] if use_default_style_filter? && !options[:style].is_a?(Hash) builder(expr).add_attribute_conditions(**conditions) end def use_default_id_filter? options.key?(:id) && !custom_keys.include?(:id) end def use_default_class_filter? options.key?(:class) && !custom_keys.include?(:class) end def use_default_style_filter? options.key?(:style) && !custom_keys.include?(:style) end def use_default_focused_filter? options.key?(:focused) && !custom_keys.include?(:focused) end def use_spatial_filter? options.values_at(*SPATIAL_KEYS).compact.any? end def apply_expression_filters(expression) unapplied_options = options.keys - valid_keys expression_filters.inject(expression) do |expr, (name, ef)| next expr unless apply_filter?(ef) if ef.matcher? unapplied_options.select(&ef.method(:handles_option?)).inject(expr) do |memo, option_name| unapplied_options.delete(option_name) ef.apply_filter(memo, option_name, options[option_name], @selector) end elsif options.key?(name) unapplied_options.delete(name) ef.apply_filter(expr, name, options[name], @selector) elsif ef.default? ef.apply_filter(expr, name, ef.default, @selector) else expr end end end def warn_exact_usage return unless options.key?(:exact) && !supports_exact? warn "The :exact option only has an effect on queries using the XPath#is method. Using it with the query \"#{expression}\" has no effect." end def exact_text options.fetch(:exact_text, session_options.exact_text) end def describe_within? @resolved_node && !document?(@resolved_node) && !simple_root?(@resolved_node) end def document?(node) node.is_a?(::Capybara::Node::Document) end def simple_root?(node) node.is_a?(::Capybara::Node::Simple) && node.path == '/' end def apply_filter?(filter) filter.format.nil? || (filter.format == selector_format) end def matches_locator_filter?(node) return true unless @selector.locator_filter && apply_filter?(@selector.locator_filter) @selector.locator_filter.matches?(node, @locator, @selector, exact: exact?) end def matches_system_filters?(node) applied_filters << :system matches_visibility_filters?(node) && matches_id_filter?(node) && matches_class_filter?(node) && matches_style_filter?(node) && matches_focused_filter?(node) && matches_text_filter?(node) && matches_exact_text_filter?(node) end def matches_spatial_filters?(node) applied_filters << :spatial return true unless use_spatial_filter? node_rect = Rectangle.new(node.initial_cache[:position] || node.rect) if options[:above] el_rect = rect_cache(options[:above]) return false unless node_rect.above? el_rect end if options[:below] el_rect = rect_cache(options[:below]) return false unless node_rect.below? el_rect end if options[:left_of] el_rect = rect_cache(options[:left_of]) return false unless node_rect.left_of? el_rect end if options[:right_of] el_rect = rect_cache(options[:right_of]) return false unless node_rect.right_of? el_rect end if options[:near] return false if node == options[:near] el_rect = rect_cache(options[:near]) return false unless node_rect.near? el_rect end true end def matches_id_filter?(node) return true unless use_default_id_filter? && options[:id].is_a?(Regexp) options[:id].match? node[:id] end def matches_class_filter?(node) return true unless use_default_class_filter? && need_to_process_classes? if options[:class].is_a? Regexp options[:class].match? node[:class] else classes = (node[:class] || '').split options[:class].select { |c| c.is_a? Regexp }.all? do |r| classes.any? { |cls| r.match? cls } end end end def matches_focused_filter?(node) return true unless use_default_focused_filter? (node == node.session.active_element) == options[:focused] end def need_to_process_classes? case options[:class] when Regexp then true when Array then options[:class].any?(Regexp) else false end end def matches_style_filter?(node) case options[:style] when String, nil true when Regexp options[:style].match? node[:style] when Hash matches_style?(node, options[:style]) end end def matches_style?(node, styles) @actual_styles = node.initial_cache[:style] || node.style(*styles.keys) styles.all? do |style, value| if value.is_a? Regexp value.match? @actual_styles[style.to_s] else @actual_styles[style.to_s] == value end end end def matches_text_filter?(node) value = options[:text] return true unless value return matches_text_exactly?(node, value) if exact_text == true && !value.is_a?(Regexp) regexp = value.is_a?(Regexp) ? value : Regexp.escape(value.to_s) matches_text_regexp?(node, regexp) end def matches_exact_text_filter?(node) case exact_text when String, Regexp matches_text_exactly?(node, exact_text) else true end end def matches_visibility_filters?(node) obscured = options[:obscured] return (visible != :hidden) && (node.initial_cache[:visible] != false) && !node.obscured? if obscured == false vis = case visible when :visible node.initial_cache[:visible] || (node.initial_cache[:visible].nil? && node.visible?) when :hidden # TODO: check why the 'visbile' cache spelling mistake wasn't caught in a test # (node.initial_cache[:visible] == false) || (node.initial_cache[:visbile].nil? && !node.visible?) (node.initial_cache[:visible] == false) || (node.initial_cache[:visible].nil? && !node.visible?) else true end vis && case obscured when true node.obscured? when false !node.obscured? else true end end def matches_text_exactly?(node, value) regexp = value.is_a?(Regexp) ? value : /\A#{Regexp.escape(value.to_s)}\z/ matches_text_regexp(node, regexp).then { |m| m&.pre_match == '' && m&.post_match == '' } end def normalize_ws options.fetch(:normalize_ws, session_options.default_normalize_ws) end def matches_text_regexp(node, regexp) text_visible = visible text_visible = :all if text_visible == :hidden node.text(text_visible, normalize_ws: normalize_ws).match(regexp) end def matches_text_regexp?(node, regexp) !matches_text_regexp(node, regexp).nil? end def default_visibility @selector.default_visibility(session_options.ignore_hidden_elements, options) end def builder(expr) selector.builder(expr) end def position_cache(key) @filter_cache[key][:position] ||= key.rect end def rect_cache(key) @filter_cache[key][:rect] ||= Rectangle.new(position_cache(key)) end class Rectangle attr_reader :top, :bottom, :left, :right def initialize(position) # rubocop:disable Style/RescueModifier @top = position['top'] rescue position['y'] @bottom = position['bottom'] rescue (@top + position['height']) @left = position['left'] rescue position['x'] @right = position['right'] rescue (@left + position['width']) # rubocop:enable Style/RescueModifier end def distance(other) distance = Float::INFINITY line_segments.each do |ls1| other.line_segments.each do |ls2| distance = [ distance, distance_segment_segment(*ls1, *ls2) ].min end end distance end def above?(other) bottom <= other.top end def below?(other) top >= other.bottom end def left_of?(other) right <= other.left end def right_of?(other) left >= other.right end def near?(other) distance(other) <= 50 end protected def line_segments [ [Vector[top, left], Vector[top, right]], [Vector[top, right], Vector[bottom, left]], [Vector[bottom, left], Vector[bottom, right]], [Vector[bottom, right], Vector[top, left]] ] end private def distance_segment_segment(l1p1, l1p2, l2p1, l2p2) # See http://geomalgorithms.com/a07-_distance.html # rubocop:disable Naming/VariableName u = l1p2 - l1p1 v = l2p2 - l2p1 w = l1p1 - l2p1 a = u.dot u b = u.dot v c = v.dot v d = u.dot w e = v.dot w cap_d = (a * c) - (b**2) sD = tD = cap_d # compute the line parameters of the two closest points if cap_d < Float::EPSILON # the lines are almost parallel sN = 0.0 # force using point P0 on segment S1 sD = 1.0 # to prevent possible division by 0.0 later tN = e tD = c else # get the closest points on the infinite lines sN = (b * e) - (c * d) tN = (a * e) - (b * d) if sN.negative? # sc < 0 => the s=0 edge is visible sN = 0 tN = e tD = c elsif sN > sD # sc > 1 => the s=1 edge is visible sN = sD tN = e + b tD = c end end if tN.negative? # tc < 0 => the t=0 edge is visible tN = 0 # recompute sc for this edge if (-d).negative? sN = 0.0 elsif -d > a sN = sD else sN = -d sD = a end elsif tN > tD # tc > 1 => the t=1 edge is visible tN = tD # recompute sc for this edge if (-d + b).negative? sN = 0.0 elsif (-d + b) > a sN = sD else sN = (-d + b) sD = a end end # finally do the division to get sc and tc sc = sN.abs < Float::EPSILON ? 0.0 : sN / sD tc = tN.abs < Float::EPSILON ? 0.0 : tN / tD # difference of the two closest points dP = w + (u * sc) - (v * tc) Math.sqrt(dP.dot(dP)) # rubocop:enable Naming/VariableName end end private_constant :Rectangle end end end
Ruby
{ "end_line": 112, "name": "description", "signature": "def description(only_applied = false) # rubocop:disable Style/OptionalBooleanParameter", "start_line": 64 }
{ "class_name": "SelectorQuery", "class_signature": "class SelectorQuery < < Queries::BaseQuery", "module": "Capybara" }
matches_filters?
capybara/lib/capybara/queries/selector_query.rb
def matches_filters?(node, node_filter_errors = []) return true if (@resolved_node&.== node) && options[:allow_self] matches_locator_filter?(node) && matches_system_filters?(node) && matches_spatial_filters?(node) && matches_node_filters?(node, node_filter_errors) && matches_filter_block?(node) rescue *(node.respond_to?(:session) ? node.session.driver.invalid_element_errors : []) false end
# frozen_string_literal: true require 'matrix' module Capybara module Queries class SelectorQuery < Queries::BaseQuery attr_reader :expression, :selector, :locator, :options SPATIAL_KEYS = %i[above below left_of right_of near].freeze VALID_KEYS = SPATIAL_KEYS + COUNT_KEYS + %i[text id class style visible obscured exact exact_text normalize_ws match wait filter_set focused] VALID_MATCH = %i[first smart prefer_exact one].freeze def initialize(*args, session_options:, enable_aria_label: session_options.enable_aria_label, enable_aria_role: session_options.enable_aria_role, test_id: session_options.test_id, selector_format: nil, order: nil, **options, &filter_block) @resolved_node = nil @resolved_count = 0 @options = options.dup @order = order @filter_cache = Hash.new { |hsh, key| hsh[key] = {} } if @options[:text].is_a?(Regexp) && [true, false].include?(@options[:exact_text]) Capybara::Helpers.warn( "Boolean 'exact_text' option is not supported when 'text' option is a Regexp - ignoring" ) end super(@options) self.session_options = session_options @selector = Selector.new( find_selector(args[0].is_a?(Symbol) ? args.shift : args[0]), config: { enable_aria_label: enable_aria_label, enable_aria_role: enable_aria_role, test_id: test_id }, format: selector_format ) @locator = args.shift @filter_block = filter_block raise ArgumentError, "Unused parameters passed to #{self.class.name} : #{args}" unless args.empty? @expression = selector.call(@locator, **@options) warn_exact_usage assert_valid_keys end def name; selector.name; end def label; selector.label || selector.name; end def description(only_applied = false) # rubocop:disable Style/OptionalBooleanParameter desc = +'' show_for = show_for_stage(only_applied) if show_for[:any] desc << 'visible ' if visible == :visible desc << 'non-visible ' if visible == :hidden end desc << label.to_s desc << " #{locator.inspect}" unless locator.nil? if show_for[:any] desc << " with#{' exact' if exact_text == true} text #{options[:text].inspect}" if options[:text] desc << " with exact text #{exact_text}" if exact_text.is_a?(String) end desc << " with id #{options[:id]}" if options[:id] desc << " with classes [#{Array(options[:class]).join(',')}]" if options[:class] desc << ' that is focused' if options[:focused] desc << ' that is not focused' if options[:focused] == false desc << case options[:style] when String " with style attribute #{options[:style].inspect}" when Regexp " with style attribute matching #{options[:style].inspect}" when Hash " with styles #{options[:style].inspect}" else '' end %i[above below left_of right_of near].each do |spatial_filter| if options[spatial_filter] && show_for[:spatial] desc << " #{spatial_filter} #{options[spatial_filter] rescue '<ERROR>'}" # rubocop:disable Style/RescueModifier end end desc << selector.description(node_filters: show_for[:node], **options) desc << ' that also matches the custom filter block' if @filter_block && show_for[:node] desc << " within #{@resolved_node.inspect}" if describe_within? if locator.is_a?(String) && locator.start_with?('#', './/', '//') && !selector.raw_locator? desc << "\nNote: It appears you may be passing a CSS selector or XPath expression rather than a locator. " \ "Please see the documentation for acceptable locator values.\n\n" end desc end def applied_description description(true) end def matches_filters?(node, node_filter_errors = []) return true if (@resolved_node&.== node) && options[:allow_self] matches_locator_filter?(node) && matches_system_filters?(node) && matches_spatial_filters?(node) && matches_node_filters?(node, node_filter_errors) && matches_filter_block?(node) rescue *(node.respond_to?(:session) ? node.session.driver.invalid_element_errors : []) false end def visible case (vis = options.fetch(:visible) { default_visibility }) when true then :visible when false then :all else vis end end def exact? supports_exact? ? options.fetch(:exact, session_options.exact) : false end def match options.fetch(:match, session_options.match) end def xpath(exact = nil) exact = exact? if exact.nil? expr = apply_expression_filters(@expression) expr = exact ? expr.to_xpath(:exact) : expr.to_s if expr.respond_to?(:to_xpath) expr = filtered_expression(expr) expr = "(#{expr})[#{xpath_text_conditions}]" if try_text_match_in_expression? expr end def css filtered_expression(apply_expression_filters(@expression)) end # @api private def resolve_for(node, exact = nil) applied_filters.clear @filter_cache.clear @resolved_node = node @resolved_count += 1 node.synchronize do children = find_nodes_by_selector_format(node, exact).map(&method(:to_element)) Capybara::Result.new(ordered_results(children), self) end end # @api private def supports_exact? return @expression.respond_to? :to_xpath if @selector.supports_exact?.nil? @selector.supports_exact? end def failure_message "expected to find #{applied_description}" << count_message end def negative_failure_message "expected not to find #{applied_description}" << count_message end private def selector_format @selector.format end def matching_text options[:text] || options[:exact_text] end def text_fragments (text = matching_text).is_a?(String) ? text.split : [] end def xpath_text_conditions case (text = matching_text) when String text.split.map { |txt| XPath.contains(txt) }.reduce(&:&) when Regexp condition = XPath.current condition = condition.uppercase if text.casefold? Selector::RegexpDisassembler.new(text).alternated_substrings.map do |strs| strs.flat_map(&:split).map { |str| condition.contains(str) }.reduce(:&) end.reduce(:|) end end def try_text_match_in_expression? first_try? && matching_text && @resolved_node.is_a?(Capybara::Node::Base) && @resolved_node.session&.driver&.wait? end def first_try? @resolved_count == 1 end def show_for_stage(only_applied) lambda do |stage = :any| !only_applied || (stage == :any ? applied_filters.any? : applied_filters.include?(stage)) end end def applied_filters @applied_filters ||= [] end def find_selector(locator) case locator when Symbol then Selector[locator] else Selector.for(locator) end || Selector[session_options.default_selector] end def find_nodes_by_selector_format(node, exact) hints = {} hints[:uses_visibility] = true unless visible == :all hints[:texts] = text_fragments unless selector_format == :xpath hints[:styles] = options[:style] if use_default_style_filter? hints[:position] = true if use_spatial_filter? case selector_format when :css if node.method(:find_css).arity == 1 node.find_css(css) else node.find_css(css, **hints) end when :xpath if node.method(:find_xpath).arity == 1 node.find_xpath(xpath(exact)) else node.find_xpath(xpath(exact), **hints) end else raise ArgumentError, "Unknown format: #{selector_format}" end end def to_element(node) if @resolved_node.is_a?(Capybara::Node::Base) Capybara::Node::Element.new(@resolved_node.session, node, @resolved_node, self) else Capybara::Node::Simple.new(node) end end def valid_keys (VALID_KEYS + custom_keys).uniq end def matches_node_filters?(node, errors) applied_filters << :node unapplied_options = options.keys - valid_keys @selector.with_filter_errors(errors) do node_filters.all? do |filter_name, filter| next true unless apply_filter?(filter) if filter.matcher? unapplied_options.select { |option_name| filter.handles_option?(option_name) }.all? do |option_name| unapplied_options.delete(option_name) filter.matches?(node, option_name, options[option_name], @selector) end elsif options.key?(filter_name) unapplied_options.delete(filter_name) filter.matches?(node, filter_name, options[filter_name], @selector) elsif filter.default? filter.matches?(node, filter_name, filter.default, @selector) else true end end end end def matches_filter_block?(node) return true unless @filter_block if node.respond_to?(:session) node.session.using_wait_time(0) { @filter_block.call(node) } else @filter_block.call(node) end end def filter_set(name) ::Capybara::Selector::FilterSet[name] end def node_filters if options.key?(:filter_set) filter_set(options[:filter_set]) else @selector end.node_filters end def expression_filters filters = @selector.expression_filters filters.merge filter_set(options[:filter_set]).expression_filters if options.key?(:filter_set) filters end def ordered_results(results) case @order when :reverse results.reverse else results end end def custom_keys @custom_keys ||= node_filters.keys + expression_filters.keys end def assert_valid_keys unless VALID_MATCH.include?(match) raise ArgumentError, "Invalid option #{match.inspect} for :match, should be one of #{VALID_MATCH.map(&:inspect).join(', ')}" end unhandled_options = @options.keys.reject do |option_name| valid_keys.include?(option_name) || expression_filters.any? { |_name, ef| ef.handles_option? option_name } || node_filters.any? { |_name, nf| nf.handles_option? option_name } end return if unhandled_options.empty? invalid_names = unhandled_options.map(&:inspect).join(', ') valid_names = (valid_keys - [:allow_self]).map(&:inspect).join(', ') raise ArgumentError, "Invalid option(s) #{invalid_names}, should be one of #{valid_names}" end def filtered_expression(expr) conditions = {} conditions[:id] = options[:id] if use_default_id_filter? conditions[:class] = options[:class] if use_default_class_filter? conditions[:style] = options[:style] if use_default_style_filter? && !options[:style].is_a?(Hash) builder(expr).add_attribute_conditions(**conditions) end def use_default_id_filter? options.key?(:id) && !custom_keys.include?(:id) end def use_default_class_filter? options.key?(:class) && !custom_keys.include?(:class) end def use_default_style_filter? options.key?(:style) && !custom_keys.include?(:style) end def use_default_focused_filter? options.key?(:focused) && !custom_keys.include?(:focused) end def use_spatial_filter? options.values_at(*SPATIAL_KEYS).compact.any? end def apply_expression_filters(expression) unapplied_options = options.keys - valid_keys expression_filters.inject(expression) do |expr, (name, ef)| next expr unless apply_filter?(ef) if ef.matcher? unapplied_options.select(&ef.method(:handles_option?)).inject(expr) do |memo, option_name| unapplied_options.delete(option_name) ef.apply_filter(memo, option_name, options[option_name], @selector) end elsif options.key?(name) unapplied_options.delete(name) ef.apply_filter(expr, name, options[name], @selector) elsif ef.default? ef.apply_filter(expr, name, ef.default, @selector) else expr end end end def warn_exact_usage return unless options.key?(:exact) && !supports_exact? warn "The :exact option only has an effect on queries using the XPath#is method. Using it with the query \"#{expression}\" has no effect." end def exact_text options.fetch(:exact_text, session_options.exact_text) end def describe_within? @resolved_node && !document?(@resolved_node) && !simple_root?(@resolved_node) end def document?(node) node.is_a?(::Capybara::Node::Document) end def simple_root?(node) node.is_a?(::Capybara::Node::Simple) && node.path == '/' end def apply_filter?(filter) filter.format.nil? || (filter.format == selector_format) end def matches_locator_filter?(node) return true unless @selector.locator_filter && apply_filter?(@selector.locator_filter) @selector.locator_filter.matches?(node, @locator, @selector, exact: exact?) end def matches_system_filters?(node) applied_filters << :system matches_visibility_filters?(node) && matches_id_filter?(node) && matches_class_filter?(node) && matches_style_filter?(node) && matches_focused_filter?(node) && matches_text_filter?(node) && matches_exact_text_filter?(node) end def matches_spatial_filters?(node) applied_filters << :spatial return true unless use_spatial_filter? node_rect = Rectangle.new(node.initial_cache[:position] || node.rect) if options[:above] el_rect = rect_cache(options[:above]) return false unless node_rect.above? el_rect end if options[:below] el_rect = rect_cache(options[:below]) return false unless node_rect.below? el_rect end if options[:left_of] el_rect = rect_cache(options[:left_of]) return false unless node_rect.left_of? el_rect end if options[:right_of] el_rect = rect_cache(options[:right_of]) return false unless node_rect.right_of? el_rect end if options[:near] return false if node == options[:near] el_rect = rect_cache(options[:near]) return false unless node_rect.near? el_rect end true end def matches_id_filter?(node) return true unless use_default_id_filter? && options[:id].is_a?(Regexp) options[:id].match? node[:id] end def matches_class_filter?(node) return true unless use_default_class_filter? && need_to_process_classes? if options[:class].is_a? Regexp options[:class].match? node[:class] else classes = (node[:class] || '').split options[:class].select { |c| c.is_a? Regexp }.all? do |r| classes.any? { |cls| r.match? cls } end end end def matches_focused_filter?(node) return true unless use_default_focused_filter? (node == node.session.active_element) == options[:focused] end def need_to_process_classes? case options[:class] when Regexp then true when Array then options[:class].any?(Regexp) else false end end def matches_style_filter?(node) case options[:style] when String, nil true when Regexp options[:style].match? node[:style] when Hash matches_style?(node, options[:style]) end end def matches_style?(node, styles) @actual_styles = node.initial_cache[:style] || node.style(*styles.keys) styles.all? do |style, value| if value.is_a? Regexp value.match? @actual_styles[style.to_s] else @actual_styles[style.to_s] == value end end end def matches_text_filter?(node) value = options[:text] return true unless value return matches_text_exactly?(node, value) if exact_text == true && !value.is_a?(Regexp) regexp = value.is_a?(Regexp) ? value : Regexp.escape(value.to_s) matches_text_regexp?(node, regexp) end def matches_exact_text_filter?(node) case exact_text when String, Regexp matches_text_exactly?(node, exact_text) else true end end def matches_visibility_filters?(node) obscured = options[:obscured] return (visible != :hidden) && (node.initial_cache[:visible] != false) && !node.obscured? if obscured == false vis = case visible when :visible node.initial_cache[:visible] || (node.initial_cache[:visible].nil? && node.visible?) when :hidden # TODO: check why the 'visbile' cache spelling mistake wasn't caught in a test # (node.initial_cache[:visible] == false) || (node.initial_cache[:visbile].nil? && !node.visible?) (node.initial_cache[:visible] == false) || (node.initial_cache[:visible].nil? && !node.visible?) else true end vis && case obscured when true node.obscured? when false !node.obscured? else true end end def matches_text_exactly?(node, value) regexp = value.is_a?(Regexp) ? value : /\A#{Regexp.escape(value.to_s)}\z/ matches_text_regexp(node, regexp).then { |m| m&.pre_match == '' && m&.post_match == '' } end def normalize_ws options.fetch(:normalize_ws, session_options.default_normalize_ws) end def matches_text_regexp(node, regexp) text_visible = visible text_visible = :all if text_visible == :hidden node.text(text_visible, normalize_ws: normalize_ws).match(regexp) end def matches_text_regexp?(node, regexp) !matches_text_regexp(node, regexp).nil? end def default_visibility @selector.default_visibility(session_options.ignore_hidden_elements, options) end def builder(expr) selector.builder(expr) end def position_cache(key) @filter_cache[key][:position] ||= key.rect end def rect_cache(key) @filter_cache[key][:rect] ||= Rectangle.new(position_cache(key)) end class Rectangle attr_reader :top, :bottom, :left, :right def initialize(position) # rubocop:disable Style/RescueModifier @top = position['top'] rescue position['y'] @bottom = position['bottom'] rescue (@top + position['height']) @left = position['left'] rescue position['x'] @right = position['right'] rescue (@left + position['width']) # rubocop:enable Style/RescueModifier end def distance(other) distance = Float::INFINITY line_segments.each do |ls1| other.line_segments.each do |ls2| distance = [ distance, distance_segment_segment(*ls1, *ls2) ].min end end distance end def above?(other) bottom <= other.top end def below?(other) top >= other.bottom end def left_of?(other) right <= other.left end def right_of?(other) left >= other.right end def near?(other) distance(other) <= 50 end protected def line_segments [ [Vector[top, left], Vector[top, right]], [Vector[top, right], Vector[bottom, left]], [Vector[bottom, left], Vector[bottom, right]], [Vector[bottom, right], Vector[top, left]] ] end private def distance_segment_segment(l1p1, l1p2, l2p1, l2p2) # See http://geomalgorithms.com/a07-_distance.html # rubocop:disable Naming/VariableName u = l1p2 - l1p1 v = l2p2 - l2p1 w = l1p1 - l2p1 a = u.dot u b = u.dot v c = v.dot v d = u.dot w e = v.dot w cap_d = (a * c) - (b**2) sD = tD = cap_d # compute the line parameters of the two closest points if cap_d < Float::EPSILON # the lines are almost parallel sN = 0.0 # force using point P0 on segment S1 sD = 1.0 # to prevent possible division by 0.0 later tN = e tD = c else # get the closest points on the infinite lines sN = (b * e) - (c * d) tN = (a * e) - (b * d) if sN.negative? # sc < 0 => the s=0 edge is visible sN = 0 tN = e tD = c elsif sN > sD # sc > 1 => the s=1 edge is visible sN = sD tN = e + b tD = c end end if tN.negative? # tc < 0 => the t=0 edge is visible tN = 0 # recompute sc for this edge if (-d).negative? sN = 0.0 elsif -d > a sN = sD else sN = -d sD = a end elsif tN > tD # tc > 1 => the t=1 edge is visible tN = tD # recompute sc for this edge if (-d + b).negative? sN = 0.0 elsif (-d + b) > a sN = sD else sN = (-d + b) sD = a end end # finally do the division to get sc and tc sc = sN.abs < Float::EPSILON ? 0.0 : sN / sD tc = tN.abs < Float::EPSILON ? 0.0 : tN / tD # difference of the two closest points dP = w + (u * sc) - (v * tc) Math.sqrt(dP.dot(dP)) # rubocop:enable Naming/VariableName end end private_constant :Rectangle end end end
Ruby
{ "end_line": 128, "name": "matches_filters?", "signature": "def matches_filters?(node, node_filter_errors = [])", "start_line": 118 }
{ "class_name": "SelectorQuery", "class_signature": "class SelectorQuery < < Queries::BaseQuery", "module": "Capybara" }
resolve_for
capybara/lib/capybara/queries/selector_query.rb
def resolve_for(node, exact = nil) applied_filters.clear @filter_cache.clear @resolved_node = node @resolved_count += 1 node.synchronize do children = find_nodes_by_selector_format(node, exact).map(&method(:to_element)) Capybara::Result.new(ordered_results(children), self) end end
# frozen_string_literal: true require 'matrix' module Capybara module Queries class SelectorQuery < Queries::BaseQuery attr_reader :expression, :selector, :locator, :options SPATIAL_KEYS = %i[above below left_of right_of near].freeze VALID_KEYS = SPATIAL_KEYS + COUNT_KEYS + %i[text id class style visible obscured exact exact_text normalize_ws match wait filter_set focused] VALID_MATCH = %i[first smart prefer_exact one].freeze def initialize(*args, session_options:, enable_aria_label: session_options.enable_aria_label, enable_aria_role: session_options.enable_aria_role, test_id: session_options.test_id, selector_format: nil, order: nil, **options, &filter_block) @resolved_node = nil @resolved_count = 0 @options = options.dup @order = order @filter_cache = Hash.new { |hsh, key| hsh[key] = {} } if @options[:text].is_a?(Regexp) && [true, false].include?(@options[:exact_text]) Capybara::Helpers.warn( "Boolean 'exact_text' option is not supported when 'text' option is a Regexp - ignoring" ) end super(@options) self.session_options = session_options @selector = Selector.new( find_selector(args[0].is_a?(Symbol) ? args.shift : args[0]), config: { enable_aria_label: enable_aria_label, enable_aria_role: enable_aria_role, test_id: test_id }, format: selector_format ) @locator = args.shift @filter_block = filter_block raise ArgumentError, "Unused parameters passed to #{self.class.name} : #{args}" unless args.empty? @expression = selector.call(@locator, **@options) warn_exact_usage assert_valid_keys end def name; selector.name; end def label; selector.label || selector.name; end def description(only_applied = false) # rubocop:disable Style/OptionalBooleanParameter desc = +'' show_for = show_for_stage(only_applied) if show_for[:any] desc << 'visible ' if visible == :visible desc << 'non-visible ' if visible == :hidden end desc << label.to_s desc << " #{locator.inspect}" unless locator.nil? if show_for[:any] desc << " with#{' exact' if exact_text == true} text #{options[:text].inspect}" if options[:text] desc << " with exact text #{exact_text}" if exact_text.is_a?(String) end desc << " with id #{options[:id]}" if options[:id] desc << " with classes [#{Array(options[:class]).join(',')}]" if options[:class] desc << ' that is focused' if options[:focused] desc << ' that is not focused' if options[:focused] == false desc << case options[:style] when String " with style attribute #{options[:style].inspect}" when Regexp " with style attribute matching #{options[:style].inspect}" when Hash " with styles #{options[:style].inspect}" else '' end %i[above below left_of right_of near].each do |spatial_filter| if options[spatial_filter] && show_for[:spatial] desc << " #{spatial_filter} #{options[spatial_filter] rescue '<ERROR>'}" # rubocop:disable Style/RescueModifier end end desc << selector.description(node_filters: show_for[:node], **options) desc << ' that also matches the custom filter block' if @filter_block && show_for[:node] desc << " within #{@resolved_node.inspect}" if describe_within? if locator.is_a?(String) && locator.start_with?('#', './/', '//') && !selector.raw_locator? desc << "\nNote: It appears you may be passing a CSS selector or XPath expression rather than a locator. " \ "Please see the documentation for acceptable locator values.\n\n" end desc end def applied_description description(true) end def matches_filters?(node, node_filter_errors = []) return true if (@resolved_node&.== node) && options[:allow_self] matches_locator_filter?(node) && matches_system_filters?(node) && matches_spatial_filters?(node) && matches_node_filters?(node, node_filter_errors) && matches_filter_block?(node) rescue *(node.respond_to?(:session) ? node.session.driver.invalid_element_errors : []) false end def visible case (vis = options.fetch(:visible) { default_visibility }) when true then :visible when false then :all else vis end end def exact? supports_exact? ? options.fetch(:exact, session_options.exact) : false end def match options.fetch(:match, session_options.match) end def xpath(exact = nil) exact = exact? if exact.nil? expr = apply_expression_filters(@expression) expr = exact ? expr.to_xpath(:exact) : expr.to_s if expr.respond_to?(:to_xpath) expr = filtered_expression(expr) expr = "(#{expr})[#{xpath_text_conditions}]" if try_text_match_in_expression? expr end def css filtered_expression(apply_expression_filters(@expression)) end # @api private def resolve_for(node, exact = nil) applied_filters.clear @filter_cache.clear @resolved_node = node @resolved_count += 1 node.synchronize do children = find_nodes_by_selector_format(node, exact).map(&method(:to_element)) Capybara::Result.new(ordered_results(children), self) end end # @api private def supports_exact? return @expression.respond_to? :to_xpath if @selector.supports_exact?.nil? @selector.supports_exact? end def failure_message "expected to find #{applied_description}" << count_message end def negative_failure_message "expected not to find #{applied_description}" << count_message end private def selector_format @selector.format end def matching_text options[:text] || options[:exact_text] end def text_fragments (text = matching_text).is_a?(String) ? text.split : [] end def xpath_text_conditions case (text = matching_text) when String text.split.map { |txt| XPath.contains(txt) }.reduce(&:&) when Regexp condition = XPath.current condition = condition.uppercase if text.casefold? Selector::RegexpDisassembler.new(text).alternated_substrings.map do |strs| strs.flat_map(&:split).map { |str| condition.contains(str) }.reduce(:&) end.reduce(:|) end end def try_text_match_in_expression? first_try? && matching_text && @resolved_node.is_a?(Capybara::Node::Base) && @resolved_node.session&.driver&.wait? end def first_try? @resolved_count == 1 end def show_for_stage(only_applied) lambda do |stage = :any| !only_applied || (stage == :any ? applied_filters.any? : applied_filters.include?(stage)) end end def applied_filters @applied_filters ||= [] end def find_selector(locator) case locator when Symbol then Selector[locator] else Selector.for(locator) end || Selector[session_options.default_selector] end def find_nodes_by_selector_format(node, exact) hints = {} hints[:uses_visibility] = true unless visible == :all hints[:texts] = text_fragments unless selector_format == :xpath hints[:styles] = options[:style] if use_default_style_filter? hints[:position] = true if use_spatial_filter? case selector_format when :css if node.method(:find_css).arity == 1 node.find_css(css) else node.find_css(css, **hints) end when :xpath if node.method(:find_xpath).arity == 1 node.find_xpath(xpath(exact)) else node.find_xpath(xpath(exact), **hints) end else raise ArgumentError, "Unknown format: #{selector_format}" end end def to_element(node) if @resolved_node.is_a?(Capybara::Node::Base) Capybara::Node::Element.new(@resolved_node.session, node, @resolved_node, self) else Capybara::Node::Simple.new(node) end end def valid_keys (VALID_KEYS + custom_keys).uniq end def matches_node_filters?(node, errors) applied_filters << :node unapplied_options = options.keys - valid_keys @selector.with_filter_errors(errors) do node_filters.all? do |filter_name, filter| next true unless apply_filter?(filter) if filter.matcher? unapplied_options.select { |option_name| filter.handles_option?(option_name) }.all? do |option_name| unapplied_options.delete(option_name) filter.matches?(node, option_name, options[option_name], @selector) end elsif options.key?(filter_name) unapplied_options.delete(filter_name) filter.matches?(node, filter_name, options[filter_name], @selector) elsif filter.default? filter.matches?(node, filter_name, filter.default, @selector) else true end end end end def matches_filter_block?(node) return true unless @filter_block if node.respond_to?(:session) node.session.using_wait_time(0) { @filter_block.call(node) } else @filter_block.call(node) end end def filter_set(name) ::Capybara::Selector::FilterSet[name] end def node_filters if options.key?(:filter_set) filter_set(options[:filter_set]) else @selector end.node_filters end def expression_filters filters = @selector.expression_filters filters.merge filter_set(options[:filter_set]).expression_filters if options.key?(:filter_set) filters end def ordered_results(results) case @order when :reverse results.reverse else results end end def custom_keys @custom_keys ||= node_filters.keys + expression_filters.keys end def assert_valid_keys unless VALID_MATCH.include?(match) raise ArgumentError, "Invalid option #{match.inspect} for :match, should be one of #{VALID_MATCH.map(&:inspect).join(', ')}" end unhandled_options = @options.keys.reject do |option_name| valid_keys.include?(option_name) || expression_filters.any? { |_name, ef| ef.handles_option? option_name } || node_filters.any? { |_name, nf| nf.handles_option? option_name } end return if unhandled_options.empty? invalid_names = unhandled_options.map(&:inspect).join(', ') valid_names = (valid_keys - [:allow_self]).map(&:inspect).join(', ') raise ArgumentError, "Invalid option(s) #{invalid_names}, should be one of #{valid_names}" end def filtered_expression(expr) conditions = {} conditions[:id] = options[:id] if use_default_id_filter? conditions[:class] = options[:class] if use_default_class_filter? conditions[:style] = options[:style] if use_default_style_filter? && !options[:style].is_a?(Hash) builder(expr).add_attribute_conditions(**conditions) end def use_default_id_filter? options.key?(:id) && !custom_keys.include?(:id) end def use_default_class_filter? options.key?(:class) && !custom_keys.include?(:class) end def use_default_style_filter? options.key?(:style) && !custom_keys.include?(:style) end def use_default_focused_filter? options.key?(:focused) && !custom_keys.include?(:focused) end def use_spatial_filter? options.values_at(*SPATIAL_KEYS).compact.any? end def apply_expression_filters(expression) unapplied_options = options.keys - valid_keys expression_filters.inject(expression) do |expr, (name, ef)| next expr unless apply_filter?(ef) if ef.matcher? unapplied_options.select(&ef.method(:handles_option?)).inject(expr) do |memo, option_name| unapplied_options.delete(option_name) ef.apply_filter(memo, option_name, options[option_name], @selector) end elsif options.key?(name) unapplied_options.delete(name) ef.apply_filter(expr, name, options[name], @selector) elsif ef.default? ef.apply_filter(expr, name, ef.default, @selector) else expr end end end def warn_exact_usage return unless options.key?(:exact) && !supports_exact? warn "The :exact option only has an effect on queries using the XPath#is method. Using it with the query \"#{expression}\" has no effect." end def exact_text options.fetch(:exact_text, session_options.exact_text) end def describe_within? @resolved_node && !document?(@resolved_node) && !simple_root?(@resolved_node) end def document?(node) node.is_a?(::Capybara::Node::Document) end def simple_root?(node) node.is_a?(::Capybara::Node::Simple) && node.path == '/' end def apply_filter?(filter) filter.format.nil? || (filter.format == selector_format) end def matches_locator_filter?(node) return true unless @selector.locator_filter && apply_filter?(@selector.locator_filter) @selector.locator_filter.matches?(node, @locator, @selector, exact: exact?) end def matches_system_filters?(node) applied_filters << :system matches_visibility_filters?(node) && matches_id_filter?(node) && matches_class_filter?(node) && matches_style_filter?(node) && matches_focused_filter?(node) && matches_text_filter?(node) && matches_exact_text_filter?(node) end def matches_spatial_filters?(node) applied_filters << :spatial return true unless use_spatial_filter? node_rect = Rectangle.new(node.initial_cache[:position] || node.rect) if options[:above] el_rect = rect_cache(options[:above]) return false unless node_rect.above? el_rect end if options[:below] el_rect = rect_cache(options[:below]) return false unless node_rect.below? el_rect end if options[:left_of] el_rect = rect_cache(options[:left_of]) return false unless node_rect.left_of? el_rect end if options[:right_of] el_rect = rect_cache(options[:right_of]) return false unless node_rect.right_of? el_rect end if options[:near] return false if node == options[:near] el_rect = rect_cache(options[:near]) return false unless node_rect.near? el_rect end true end def matches_id_filter?(node) return true unless use_default_id_filter? && options[:id].is_a?(Regexp) options[:id].match? node[:id] end def matches_class_filter?(node) return true unless use_default_class_filter? && need_to_process_classes? if options[:class].is_a? Regexp options[:class].match? node[:class] else classes = (node[:class] || '').split options[:class].select { |c| c.is_a? Regexp }.all? do |r| classes.any? { |cls| r.match? cls } end end end def matches_focused_filter?(node) return true unless use_default_focused_filter? (node == node.session.active_element) == options[:focused] end def need_to_process_classes? case options[:class] when Regexp then true when Array then options[:class].any?(Regexp) else false end end def matches_style_filter?(node) case options[:style] when String, nil true when Regexp options[:style].match? node[:style] when Hash matches_style?(node, options[:style]) end end def matches_style?(node, styles) @actual_styles = node.initial_cache[:style] || node.style(*styles.keys) styles.all? do |style, value| if value.is_a? Regexp value.match? @actual_styles[style.to_s] else @actual_styles[style.to_s] == value end end end def matches_text_filter?(node) value = options[:text] return true unless value return matches_text_exactly?(node, value) if exact_text == true && !value.is_a?(Regexp) regexp = value.is_a?(Regexp) ? value : Regexp.escape(value.to_s) matches_text_regexp?(node, regexp) end def matches_exact_text_filter?(node) case exact_text when String, Regexp matches_text_exactly?(node, exact_text) else true end end def matches_visibility_filters?(node) obscured = options[:obscured] return (visible != :hidden) && (node.initial_cache[:visible] != false) && !node.obscured? if obscured == false vis = case visible when :visible node.initial_cache[:visible] || (node.initial_cache[:visible].nil? && node.visible?) when :hidden # TODO: check why the 'visbile' cache spelling mistake wasn't caught in a test # (node.initial_cache[:visible] == false) || (node.initial_cache[:visbile].nil? && !node.visible?) (node.initial_cache[:visible] == false) || (node.initial_cache[:visible].nil? && !node.visible?) else true end vis && case obscured when true node.obscured? when false !node.obscured? else true end end def matches_text_exactly?(node, value) regexp = value.is_a?(Regexp) ? value : /\A#{Regexp.escape(value.to_s)}\z/ matches_text_regexp(node, regexp).then { |m| m&.pre_match == '' && m&.post_match == '' } end def normalize_ws options.fetch(:normalize_ws, session_options.default_normalize_ws) end def matches_text_regexp(node, regexp) text_visible = visible text_visible = :all if text_visible == :hidden node.text(text_visible, normalize_ws: normalize_ws).match(regexp) end def matches_text_regexp?(node, regexp) !matches_text_regexp(node, regexp).nil? end def default_visibility @selector.default_visibility(session_options.ignore_hidden_elements, options) end def builder(expr) selector.builder(expr) end def position_cache(key) @filter_cache[key][:position] ||= key.rect end def rect_cache(key) @filter_cache[key][:rect] ||= Rectangle.new(position_cache(key)) end class Rectangle attr_reader :top, :bottom, :left, :right def initialize(position) # rubocop:disable Style/RescueModifier @top = position['top'] rescue position['y'] @bottom = position['bottom'] rescue (@top + position['height']) @left = position['left'] rescue position['x'] @right = position['right'] rescue (@left + position['width']) # rubocop:enable Style/RescueModifier end def distance(other) distance = Float::INFINITY line_segments.each do |ls1| other.line_segments.each do |ls2| distance = [ distance, distance_segment_segment(*ls1, *ls2) ].min end end distance end def above?(other) bottom <= other.top end def below?(other) top >= other.bottom end def left_of?(other) right <= other.left end def right_of?(other) left >= other.right end def near?(other) distance(other) <= 50 end protected def line_segments [ [Vector[top, left], Vector[top, right]], [Vector[top, right], Vector[bottom, left]], [Vector[bottom, left], Vector[bottom, right]], [Vector[bottom, right], Vector[top, left]] ] end private def distance_segment_segment(l1p1, l1p2, l2p1, l2p2) # See http://geomalgorithms.com/a07-_distance.html # rubocop:disable Naming/VariableName u = l1p2 - l1p1 v = l2p2 - l2p1 w = l1p1 - l2p1 a = u.dot u b = u.dot v c = v.dot v d = u.dot w e = v.dot w cap_d = (a * c) - (b**2) sD = tD = cap_d # compute the line parameters of the two closest points if cap_d < Float::EPSILON # the lines are almost parallel sN = 0.0 # force using point P0 on segment S1 sD = 1.0 # to prevent possible division by 0.0 later tN = e tD = c else # get the closest points on the infinite lines sN = (b * e) - (c * d) tN = (a * e) - (b * d) if sN.negative? # sc < 0 => the s=0 edge is visible sN = 0 tN = e tD = c elsif sN > sD # sc > 1 => the s=1 edge is visible sN = sD tN = e + b tD = c end end if tN.negative? # tc < 0 => the t=0 edge is visible tN = 0 # recompute sc for this edge if (-d).negative? sN = 0.0 elsif -d > a sN = sD else sN = -d sD = a end elsif tN > tD # tc > 1 => the t=1 edge is visible tN = tD # recompute sc for this edge if (-d + b).negative? sN = 0.0 elsif (-d + b) > a sN = sD else sN = (-d + b) sD = a end end # finally do the division to get sc and tc sc = sN.abs < Float::EPSILON ? 0.0 : sN / sD tc = tN.abs < Float::EPSILON ? 0.0 : tN / tD # difference of the two closest points dP = w + (u * sc) - (v * tc) Math.sqrt(dP.dot(dP)) # rubocop:enable Naming/VariableName end end private_constant :Rectangle end end end
Ruby
{ "end_line": 170, "name": "resolve_for", "signature": "def resolve_for(node, exact = nil)", "start_line": 160 }
{ "class_name": "SelectorQuery", "class_signature": "class SelectorQuery < < Queries::BaseQuery", "module": "Capybara" }
xpath_text_conditions
capybara/lib/capybara/queries/selector_query.rb
def xpath_text_conditions case (text = matching_text) when String text.split.map { |txt| XPath.contains(txt) }.reduce(&:&) when Regexp condition = XPath.current condition = condition.uppercase if text.casefold? Selector::RegexpDisassembler.new(text).alternated_substrings.map do |strs| strs.flat_map(&:split).map { |str| condition.contains(str) }.reduce(:&) end.reduce(:|) end end
# frozen_string_literal: true require 'matrix' module Capybara module Queries class SelectorQuery < Queries::BaseQuery attr_reader :expression, :selector, :locator, :options SPATIAL_KEYS = %i[above below left_of right_of near].freeze VALID_KEYS = SPATIAL_KEYS + COUNT_KEYS + %i[text id class style visible obscured exact exact_text normalize_ws match wait filter_set focused] VALID_MATCH = %i[first smart prefer_exact one].freeze def initialize(*args, session_options:, enable_aria_label: session_options.enable_aria_label, enable_aria_role: session_options.enable_aria_role, test_id: session_options.test_id, selector_format: nil, order: nil, **options, &filter_block) @resolved_node = nil @resolved_count = 0 @options = options.dup @order = order @filter_cache = Hash.new { |hsh, key| hsh[key] = {} } if @options[:text].is_a?(Regexp) && [true, false].include?(@options[:exact_text]) Capybara::Helpers.warn( "Boolean 'exact_text' option is not supported when 'text' option is a Regexp - ignoring" ) end super(@options) self.session_options = session_options @selector = Selector.new( find_selector(args[0].is_a?(Symbol) ? args.shift : args[0]), config: { enable_aria_label: enable_aria_label, enable_aria_role: enable_aria_role, test_id: test_id }, format: selector_format ) @locator = args.shift @filter_block = filter_block raise ArgumentError, "Unused parameters passed to #{self.class.name} : #{args}" unless args.empty? @expression = selector.call(@locator, **@options) warn_exact_usage assert_valid_keys end def name; selector.name; end def label; selector.label || selector.name; end def description(only_applied = false) # rubocop:disable Style/OptionalBooleanParameter desc = +'' show_for = show_for_stage(only_applied) if show_for[:any] desc << 'visible ' if visible == :visible desc << 'non-visible ' if visible == :hidden end desc << label.to_s desc << " #{locator.inspect}" unless locator.nil? if show_for[:any] desc << " with#{' exact' if exact_text == true} text #{options[:text].inspect}" if options[:text] desc << " with exact text #{exact_text}" if exact_text.is_a?(String) end desc << " with id #{options[:id]}" if options[:id] desc << " with classes [#{Array(options[:class]).join(',')}]" if options[:class] desc << ' that is focused' if options[:focused] desc << ' that is not focused' if options[:focused] == false desc << case options[:style] when String " with style attribute #{options[:style].inspect}" when Regexp " with style attribute matching #{options[:style].inspect}" when Hash " with styles #{options[:style].inspect}" else '' end %i[above below left_of right_of near].each do |spatial_filter| if options[spatial_filter] && show_for[:spatial] desc << " #{spatial_filter} #{options[spatial_filter] rescue '<ERROR>'}" # rubocop:disable Style/RescueModifier end end desc << selector.description(node_filters: show_for[:node], **options) desc << ' that also matches the custom filter block' if @filter_block && show_for[:node] desc << " within #{@resolved_node.inspect}" if describe_within? if locator.is_a?(String) && locator.start_with?('#', './/', '//') && !selector.raw_locator? desc << "\nNote: It appears you may be passing a CSS selector or XPath expression rather than a locator. " \ "Please see the documentation for acceptable locator values.\n\n" end desc end def applied_description description(true) end def matches_filters?(node, node_filter_errors = []) return true if (@resolved_node&.== node) && options[:allow_self] matches_locator_filter?(node) && matches_system_filters?(node) && matches_spatial_filters?(node) && matches_node_filters?(node, node_filter_errors) && matches_filter_block?(node) rescue *(node.respond_to?(:session) ? node.session.driver.invalid_element_errors : []) false end def visible case (vis = options.fetch(:visible) { default_visibility }) when true then :visible when false then :all else vis end end def exact? supports_exact? ? options.fetch(:exact, session_options.exact) : false end def match options.fetch(:match, session_options.match) end def xpath(exact = nil) exact = exact? if exact.nil? expr = apply_expression_filters(@expression) expr = exact ? expr.to_xpath(:exact) : expr.to_s if expr.respond_to?(:to_xpath) expr = filtered_expression(expr) expr = "(#{expr})[#{xpath_text_conditions}]" if try_text_match_in_expression? expr end def css filtered_expression(apply_expression_filters(@expression)) end # @api private def resolve_for(node, exact = nil) applied_filters.clear @filter_cache.clear @resolved_node = node @resolved_count += 1 node.synchronize do children = find_nodes_by_selector_format(node, exact).map(&method(:to_element)) Capybara::Result.new(ordered_results(children), self) end end # @api private def supports_exact? return @expression.respond_to? :to_xpath if @selector.supports_exact?.nil? @selector.supports_exact? end def failure_message "expected to find #{applied_description}" << count_message end def negative_failure_message "expected not to find #{applied_description}" << count_message end private def selector_format @selector.format end def matching_text options[:text] || options[:exact_text] end def text_fragments (text = matching_text).is_a?(String) ? text.split : [] end def xpath_text_conditions case (text = matching_text) when String text.split.map { |txt| XPath.contains(txt) }.reduce(&:&) when Regexp condition = XPath.current condition = condition.uppercase if text.casefold? Selector::RegexpDisassembler.new(text).alternated_substrings.map do |strs| strs.flat_map(&:split).map { |str| condition.contains(str) }.reduce(:&) end.reduce(:|) end end def try_text_match_in_expression? first_try? && matching_text && @resolved_node.is_a?(Capybara::Node::Base) && @resolved_node.session&.driver&.wait? end def first_try? @resolved_count == 1 end def show_for_stage(only_applied) lambda do |stage = :any| !only_applied || (stage == :any ? applied_filters.any? : applied_filters.include?(stage)) end end def applied_filters @applied_filters ||= [] end def find_selector(locator) case locator when Symbol then Selector[locator] else Selector.for(locator) end || Selector[session_options.default_selector] end def find_nodes_by_selector_format(node, exact) hints = {} hints[:uses_visibility] = true unless visible == :all hints[:texts] = text_fragments unless selector_format == :xpath hints[:styles] = options[:style] if use_default_style_filter? hints[:position] = true if use_spatial_filter? case selector_format when :css if node.method(:find_css).arity == 1 node.find_css(css) else node.find_css(css, **hints) end when :xpath if node.method(:find_xpath).arity == 1 node.find_xpath(xpath(exact)) else node.find_xpath(xpath(exact), **hints) end else raise ArgumentError, "Unknown format: #{selector_format}" end end def to_element(node) if @resolved_node.is_a?(Capybara::Node::Base) Capybara::Node::Element.new(@resolved_node.session, node, @resolved_node, self) else Capybara::Node::Simple.new(node) end end def valid_keys (VALID_KEYS + custom_keys).uniq end def matches_node_filters?(node, errors) applied_filters << :node unapplied_options = options.keys - valid_keys @selector.with_filter_errors(errors) do node_filters.all? do |filter_name, filter| next true unless apply_filter?(filter) if filter.matcher? unapplied_options.select { |option_name| filter.handles_option?(option_name) }.all? do |option_name| unapplied_options.delete(option_name) filter.matches?(node, option_name, options[option_name], @selector) end elsif options.key?(filter_name) unapplied_options.delete(filter_name) filter.matches?(node, filter_name, options[filter_name], @selector) elsif filter.default? filter.matches?(node, filter_name, filter.default, @selector) else true end end end end def matches_filter_block?(node) return true unless @filter_block if node.respond_to?(:session) node.session.using_wait_time(0) { @filter_block.call(node) } else @filter_block.call(node) end end def filter_set(name) ::Capybara::Selector::FilterSet[name] end def node_filters if options.key?(:filter_set) filter_set(options[:filter_set]) else @selector end.node_filters end def expression_filters filters = @selector.expression_filters filters.merge filter_set(options[:filter_set]).expression_filters if options.key?(:filter_set) filters end def ordered_results(results) case @order when :reverse results.reverse else results end end def custom_keys @custom_keys ||= node_filters.keys + expression_filters.keys end def assert_valid_keys unless VALID_MATCH.include?(match) raise ArgumentError, "Invalid option #{match.inspect} for :match, should be one of #{VALID_MATCH.map(&:inspect).join(', ')}" end unhandled_options = @options.keys.reject do |option_name| valid_keys.include?(option_name) || expression_filters.any? { |_name, ef| ef.handles_option? option_name } || node_filters.any? { |_name, nf| nf.handles_option? option_name } end return if unhandled_options.empty? invalid_names = unhandled_options.map(&:inspect).join(', ') valid_names = (valid_keys - [:allow_self]).map(&:inspect).join(', ') raise ArgumentError, "Invalid option(s) #{invalid_names}, should be one of #{valid_names}" end def filtered_expression(expr) conditions = {} conditions[:id] = options[:id] if use_default_id_filter? conditions[:class] = options[:class] if use_default_class_filter? conditions[:style] = options[:style] if use_default_style_filter? && !options[:style].is_a?(Hash) builder(expr).add_attribute_conditions(**conditions) end def use_default_id_filter? options.key?(:id) && !custom_keys.include?(:id) end def use_default_class_filter? options.key?(:class) && !custom_keys.include?(:class) end def use_default_style_filter? options.key?(:style) && !custom_keys.include?(:style) end def use_default_focused_filter? options.key?(:focused) && !custom_keys.include?(:focused) end def use_spatial_filter? options.values_at(*SPATIAL_KEYS).compact.any? end def apply_expression_filters(expression) unapplied_options = options.keys - valid_keys expression_filters.inject(expression) do |expr, (name, ef)| next expr unless apply_filter?(ef) if ef.matcher? unapplied_options.select(&ef.method(:handles_option?)).inject(expr) do |memo, option_name| unapplied_options.delete(option_name) ef.apply_filter(memo, option_name, options[option_name], @selector) end elsif options.key?(name) unapplied_options.delete(name) ef.apply_filter(expr, name, options[name], @selector) elsif ef.default? ef.apply_filter(expr, name, ef.default, @selector) else expr end end end def warn_exact_usage return unless options.key?(:exact) && !supports_exact? warn "The :exact option only has an effect on queries using the XPath#is method. Using it with the query \"#{expression}\" has no effect." end def exact_text options.fetch(:exact_text, session_options.exact_text) end def describe_within? @resolved_node && !document?(@resolved_node) && !simple_root?(@resolved_node) end def document?(node) node.is_a?(::Capybara::Node::Document) end def simple_root?(node) node.is_a?(::Capybara::Node::Simple) && node.path == '/' end def apply_filter?(filter) filter.format.nil? || (filter.format == selector_format) end def matches_locator_filter?(node) return true unless @selector.locator_filter && apply_filter?(@selector.locator_filter) @selector.locator_filter.matches?(node, @locator, @selector, exact: exact?) end def matches_system_filters?(node) applied_filters << :system matches_visibility_filters?(node) && matches_id_filter?(node) && matches_class_filter?(node) && matches_style_filter?(node) && matches_focused_filter?(node) && matches_text_filter?(node) && matches_exact_text_filter?(node) end def matches_spatial_filters?(node) applied_filters << :spatial return true unless use_spatial_filter? node_rect = Rectangle.new(node.initial_cache[:position] || node.rect) if options[:above] el_rect = rect_cache(options[:above]) return false unless node_rect.above? el_rect end if options[:below] el_rect = rect_cache(options[:below]) return false unless node_rect.below? el_rect end if options[:left_of] el_rect = rect_cache(options[:left_of]) return false unless node_rect.left_of? el_rect end if options[:right_of] el_rect = rect_cache(options[:right_of]) return false unless node_rect.right_of? el_rect end if options[:near] return false if node == options[:near] el_rect = rect_cache(options[:near]) return false unless node_rect.near? el_rect end true end def matches_id_filter?(node) return true unless use_default_id_filter? && options[:id].is_a?(Regexp) options[:id].match? node[:id] end def matches_class_filter?(node) return true unless use_default_class_filter? && need_to_process_classes? if options[:class].is_a? Regexp options[:class].match? node[:class] else classes = (node[:class] || '').split options[:class].select { |c| c.is_a? Regexp }.all? do |r| classes.any? { |cls| r.match? cls } end end end def matches_focused_filter?(node) return true unless use_default_focused_filter? (node == node.session.active_element) == options[:focused] end def need_to_process_classes? case options[:class] when Regexp then true when Array then options[:class].any?(Regexp) else false end end def matches_style_filter?(node) case options[:style] when String, nil true when Regexp options[:style].match? node[:style] when Hash matches_style?(node, options[:style]) end end def matches_style?(node, styles) @actual_styles = node.initial_cache[:style] || node.style(*styles.keys) styles.all? do |style, value| if value.is_a? Regexp value.match? @actual_styles[style.to_s] else @actual_styles[style.to_s] == value end end end def matches_text_filter?(node) value = options[:text] return true unless value return matches_text_exactly?(node, value) if exact_text == true && !value.is_a?(Regexp) regexp = value.is_a?(Regexp) ? value : Regexp.escape(value.to_s) matches_text_regexp?(node, regexp) end def matches_exact_text_filter?(node) case exact_text when String, Regexp matches_text_exactly?(node, exact_text) else true end end def matches_visibility_filters?(node) obscured = options[:obscured] return (visible != :hidden) && (node.initial_cache[:visible] != false) && !node.obscured? if obscured == false vis = case visible when :visible node.initial_cache[:visible] || (node.initial_cache[:visible].nil? && node.visible?) when :hidden # TODO: check why the 'visbile' cache spelling mistake wasn't caught in a test # (node.initial_cache[:visible] == false) || (node.initial_cache[:visbile].nil? && !node.visible?) (node.initial_cache[:visible] == false) || (node.initial_cache[:visible].nil? && !node.visible?) else true end vis && case obscured when true node.obscured? when false !node.obscured? else true end end def matches_text_exactly?(node, value) regexp = value.is_a?(Regexp) ? value : /\A#{Regexp.escape(value.to_s)}\z/ matches_text_regexp(node, regexp).then { |m| m&.pre_match == '' && m&.post_match == '' } end def normalize_ws options.fetch(:normalize_ws, session_options.default_normalize_ws) end def matches_text_regexp(node, regexp) text_visible = visible text_visible = :all if text_visible == :hidden node.text(text_visible, normalize_ws: normalize_ws).match(regexp) end def matches_text_regexp?(node, regexp) !matches_text_regexp(node, regexp).nil? end def default_visibility @selector.default_visibility(session_options.ignore_hidden_elements, options) end def builder(expr) selector.builder(expr) end def position_cache(key) @filter_cache[key][:position] ||= key.rect end def rect_cache(key) @filter_cache[key][:rect] ||= Rectangle.new(position_cache(key)) end class Rectangle attr_reader :top, :bottom, :left, :right def initialize(position) # rubocop:disable Style/RescueModifier @top = position['top'] rescue position['y'] @bottom = position['bottom'] rescue (@top + position['height']) @left = position['left'] rescue position['x'] @right = position['right'] rescue (@left + position['width']) # rubocop:enable Style/RescueModifier end def distance(other) distance = Float::INFINITY line_segments.each do |ls1| other.line_segments.each do |ls2| distance = [ distance, distance_segment_segment(*ls1, *ls2) ].min end end distance end def above?(other) bottom <= other.top end def below?(other) top >= other.bottom end def left_of?(other) right <= other.left end def right_of?(other) left >= other.right end def near?(other) distance(other) <= 50 end protected def line_segments [ [Vector[top, left], Vector[top, right]], [Vector[top, right], Vector[bottom, left]], [Vector[bottom, left], Vector[bottom, right]], [Vector[bottom, right], Vector[top, left]] ] end private def distance_segment_segment(l1p1, l1p2, l2p1, l2p2) # See http://geomalgorithms.com/a07-_distance.html # rubocop:disable Naming/VariableName u = l1p2 - l1p1 v = l2p2 - l2p1 w = l1p1 - l2p1 a = u.dot u b = u.dot v c = v.dot v d = u.dot w e = v.dot w cap_d = (a * c) - (b**2) sD = tD = cap_d # compute the line parameters of the two closest points if cap_d < Float::EPSILON # the lines are almost parallel sN = 0.0 # force using point P0 on segment S1 sD = 1.0 # to prevent possible division by 0.0 later tN = e tD = c else # get the closest points on the infinite lines sN = (b * e) - (c * d) tN = (a * e) - (b * d) if sN.negative? # sc < 0 => the s=0 edge is visible sN = 0 tN = e tD = c elsif sN > sD # sc > 1 => the s=1 edge is visible sN = sD tN = e + b tD = c end end if tN.negative? # tc < 0 => the t=0 edge is visible tN = 0 # recompute sc for this edge if (-d).negative? sN = 0.0 elsif -d > a sN = sD else sN = -d sD = a end elsif tN > tD # tc > 1 => the t=1 edge is visible tN = tD # recompute sc for this edge if (-d + b).negative? sN = 0.0 elsif (-d + b) > a sN = sD else sN = (-d + b) sD = a end end # finally do the division to get sc and tc sc = sN.abs < Float::EPSILON ? 0.0 : sN / sD tc = tN.abs < Float::EPSILON ? 0.0 : tN / tD # difference of the two closest points dP = w + (u * sc) - (v * tc) Math.sqrt(dP.dot(dP)) # rubocop:enable Naming/VariableName end end private_constant :Rectangle end end end
Ruby
{ "end_line": 212, "name": "xpath_text_conditions", "signature": "def xpath_text_conditions", "start_line": 201 }
{ "class_name": "SelectorQuery", "class_signature": "class SelectorQuery < < Queries::BaseQuery", "module": "Capybara" }
find_nodes_by_selector_format
capybara/lib/capybara/queries/selector_query.rb
def find_nodes_by_selector_format(node, exact) hints = {} hints[:uses_visibility] = true unless visible == :all hints[:texts] = text_fragments unless selector_format == :xpath hints[:styles] = options[:style] if use_default_style_filter? hints[:position] = true if use_spatial_filter? case selector_format when :css if node.method(:find_css).arity == 1 node.find_css(css) else node.find_css(css, **hints) end when :xpath if node.method(:find_xpath).arity == 1 node.find_xpath(xpath(exact)) else node.find_xpath(xpath(exact), **hints) end else raise ArgumentError, "Unknown format: #{selector_format}" end end
# frozen_string_literal: true require 'matrix' module Capybara module Queries class SelectorQuery < Queries::BaseQuery attr_reader :expression, :selector, :locator, :options SPATIAL_KEYS = %i[above below left_of right_of near].freeze VALID_KEYS = SPATIAL_KEYS + COUNT_KEYS + %i[text id class style visible obscured exact exact_text normalize_ws match wait filter_set focused] VALID_MATCH = %i[first smart prefer_exact one].freeze def initialize(*args, session_options:, enable_aria_label: session_options.enable_aria_label, enable_aria_role: session_options.enable_aria_role, test_id: session_options.test_id, selector_format: nil, order: nil, **options, &filter_block) @resolved_node = nil @resolved_count = 0 @options = options.dup @order = order @filter_cache = Hash.new { |hsh, key| hsh[key] = {} } if @options[:text].is_a?(Regexp) && [true, false].include?(@options[:exact_text]) Capybara::Helpers.warn( "Boolean 'exact_text' option is not supported when 'text' option is a Regexp - ignoring" ) end super(@options) self.session_options = session_options @selector = Selector.new( find_selector(args[0].is_a?(Symbol) ? args.shift : args[0]), config: { enable_aria_label: enable_aria_label, enable_aria_role: enable_aria_role, test_id: test_id }, format: selector_format ) @locator = args.shift @filter_block = filter_block raise ArgumentError, "Unused parameters passed to #{self.class.name} : #{args}" unless args.empty? @expression = selector.call(@locator, **@options) warn_exact_usage assert_valid_keys end def name; selector.name; end def label; selector.label || selector.name; end def description(only_applied = false) # rubocop:disable Style/OptionalBooleanParameter desc = +'' show_for = show_for_stage(only_applied) if show_for[:any] desc << 'visible ' if visible == :visible desc << 'non-visible ' if visible == :hidden end desc << label.to_s desc << " #{locator.inspect}" unless locator.nil? if show_for[:any] desc << " with#{' exact' if exact_text == true} text #{options[:text].inspect}" if options[:text] desc << " with exact text #{exact_text}" if exact_text.is_a?(String) end desc << " with id #{options[:id]}" if options[:id] desc << " with classes [#{Array(options[:class]).join(',')}]" if options[:class] desc << ' that is focused' if options[:focused] desc << ' that is not focused' if options[:focused] == false desc << case options[:style] when String " with style attribute #{options[:style].inspect}" when Regexp " with style attribute matching #{options[:style].inspect}" when Hash " with styles #{options[:style].inspect}" else '' end %i[above below left_of right_of near].each do |spatial_filter| if options[spatial_filter] && show_for[:spatial] desc << " #{spatial_filter} #{options[spatial_filter] rescue '<ERROR>'}" # rubocop:disable Style/RescueModifier end end desc << selector.description(node_filters: show_for[:node], **options) desc << ' that also matches the custom filter block' if @filter_block && show_for[:node] desc << " within #{@resolved_node.inspect}" if describe_within? if locator.is_a?(String) && locator.start_with?('#', './/', '//') && !selector.raw_locator? desc << "\nNote: It appears you may be passing a CSS selector or XPath expression rather than a locator. " \ "Please see the documentation for acceptable locator values.\n\n" end desc end def applied_description description(true) end def matches_filters?(node, node_filter_errors = []) return true if (@resolved_node&.== node) && options[:allow_self] matches_locator_filter?(node) && matches_system_filters?(node) && matches_spatial_filters?(node) && matches_node_filters?(node, node_filter_errors) && matches_filter_block?(node) rescue *(node.respond_to?(:session) ? node.session.driver.invalid_element_errors : []) false end def visible case (vis = options.fetch(:visible) { default_visibility }) when true then :visible when false then :all else vis end end def exact? supports_exact? ? options.fetch(:exact, session_options.exact) : false end def match options.fetch(:match, session_options.match) end def xpath(exact = nil) exact = exact? if exact.nil? expr = apply_expression_filters(@expression) expr = exact ? expr.to_xpath(:exact) : expr.to_s if expr.respond_to?(:to_xpath) expr = filtered_expression(expr) expr = "(#{expr})[#{xpath_text_conditions}]" if try_text_match_in_expression? expr end def css filtered_expression(apply_expression_filters(@expression)) end # @api private def resolve_for(node, exact = nil) applied_filters.clear @filter_cache.clear @resolved_node = node @resolved_count += 1 node.synchronize do children = find_nodes_by_selector_format(node, exact).map(&method(:to_element)) Capybara::Result.new(ordered_results(children), self) end end # @api private def supports_exact? return @expression.respond_to? :to_xpath if @selector.supports_exact?.nil? @selector.supports_exact? end def failure_message "expected to find #{applied_description}" << count_message end def negative_failure_message "expected not to find #{applied_description}" << count_message end private def selector_format @selector.format end def matching_text options[:text] || options[:exact_text] end def text_fragments (text = matching_text).is_a?(String) ? text.split : [] end def xpath_text_conditions case (text = matching_text) when String text.split.map { |txt| XPath.contains(txt) }.reduce(&:&) when Regexp condition = XPath.current condition = condition.uppercase if text.casefold? Selector::RegexpDisassembler.new(text).alternated_substrings.map do |strs| strs.flat_map(&:split).map { |str| condition.contains(str) }.reduce(:&) end.reduce(:|) end end def try_text_match_in_expression? first_try? && matching_text && @resolved_node.is_a?(Capybara::Node::Base) && @resolved_node.session&.driver&.wait? end def first_try? @resolved_count == 1 end def show_for_stage(only_applied) lambda do |stage = :any| !only_applied || (stage == :any ? applied_filters.any? : applied_filters.include?(stage)) end end def applied_filters @applied_filters ||= [] end def find_selector(locator) case locator when Symbol then Selector[locator] else Selector.for(locator) end || Selector[session_options.default_selector] end def find_nodes_by_selector_format(node, exact) hints = {} hints[:uses_visibility] = true unless visible == :all hints[:texts] = text_fragments unless selector_format == :xpath hints[:styles] = options[:style] if use_default_style_filter? hints[:position] = true if use_spatial_filter? case selector_format when :css if node.method(:find_css).arity == 1 node.find_css(css) else node.find_css(css, **hints) end when :xpath if node.method(:find_xpath).arity == 1 node.find_xpath(xpath(exact)) else node.find_xpath(xpath(exact), **hints) end else raise ArgumentError, "Unknown format: #{selector_format}" end end def to_element(node) if @resolved_node.is_a?(Capybara::Node::Base) Capybara::Node::Element.new(@resolved_node.session, node, @resolved_node, self) else Capybara::Node::Simple.new(node) end end def valid_keys (VALID_KEYS + custom_keys).uniq end def matches_node_filters?(node, errors) applied_filters << :node unapplied_options = options.keys - valid_keys @selector.with_filter_errors(errors) do node_filters.all? do |filter_name, filter| next true unless apply_filter?(filter) if filter.matcher? unapplied_options.select { |option_name| filter.handles_option?(option_name) }.all? do |option_name| unapplied_options.delete(option_name) filter.matches?(node, option_name, options[option_name], @selector) end elsif options.key?(filter_name) unapplied_options.delete(filter_name) filter.matches?(node, filter_name, options[filter_name], @selector) elsif filter.default? filter.matches?(node, filter_name, filter.default, @selector) else true end end end end def matches_filter_block?(node) return true unless @filter_block if node.respond_to?(:session) node.session.using_wait_time(0) { @filter_block.call(node) } else @filter_block.call(node) end end def filter_set(name) ::Capybara::Selector::FilterSet[name] end def node_filters if options.key?(:filter_set) filter_set(options[:filter_set]) else @selector end.node_filters end def expression_filters filters = @selector.expression_filters filters.merge filter_set(options[:filter_set]).expression_filters if options.key?(:filter_set) filters end def ordered_results(results) case @order when :reverse results.reverse else results end end def custom_keys @custom_keys ||= node_filters.keys + expression_filters.keys end def assert_valid_keys unless VALID_MATCH.include?(match) raise ArgumentError, "Invalid option #{match.inspect} for :match, should be one of #{VALID_MATCH.map(&:inspect).join(', ')}" end unhandled_options = @options.keys.reject do |option_name| valid_keys.include?(option_name) || expression_filters.any? { |_name, ef| ef.handles_option? option_name } || node_filters.any? { |_name, nf| nf.handles_option? option_name } end return if unhandled_options.empty? invalid_names = unhandled_options.map(&:inspect).join(', ') valid_names = (valid_keys - [:allow_self]).map(&:inspect).join(', ') raise ArgumentError, "Invalid option(s) #{invalid_names}, should be one of #{valid_names}" end def filtered_expression(expr) conditions = {} conditions[:id] = options[:id] if use_default_id_filter? conditions[:class] = options[:class] if use_default_class_filter? conditions[:style] = options[:style] if use_default_style_filter? && !options[:style].is_a?(Hash) builder(expr).add_attribute_conditions(**conditions) end def use_default_id_filter? options.key?(:id) && !custom_keys.include?(:id) end def use_default_class_filter? options.key?(:class) && !custom_keys.include?(:class) end def use_default_style_filter? options.key?(:style) && !custom_keys.include?(:style) end def use_default_focused_filter? options.key?(:focused) && !custom_keys.include?(:focused) end def use_spatial_filter? options.values_at(*SPATIAL_KEYS).compact.any? end def apply_expression_filters(expression) unapplied_options = options.keys - valid_keys expression_filters.inject(expression) do |expr, (name, ef)| next expr unless apply_filter?(ef) if ef.matcher? unapplied_options.select(&ef.method(:handles_option?)).inject(expr) do |memo, option_name| unapplied_options.delete(option_name) ef.apply_filter(memo, option_name, options[option_name], @selector) end elsif options.key?(name) unapplied_options.delete(name) ef.apply_filter(expr, name, options[name], @selector) elsif ef.default? ef.apply_filter(expr, name, ef.default, @selector) else expr end end end def warn_exact_usage return unless options.key?(:exact) && !supports_exact? warn "The :exact option only has an effect on queries using the XPath#is method. Using it with the query \"#{expression}\" has no effect." end def exact_text options.fetch(:exact_text, session_options.exact_text) end def describe_within? @resolved_node && !document?(@resolved_node) && !simple_root?(@resolved_node) end def document?(node) node.is_a?(::Capybara::Node::Document) end def simple_root?(node) node.is_a?(::Capybara::Node::Simple) && node.path == '/' end def apply_filter?(filter) filter.format.nil? || (filter.format == selector_format) end def matches_locator_filter?(node) return true unless @selector.locator_filter && apply_filter?(@selector.locator_filter) @selector.locator_filter.matches?(node, @locator, @selector, exact: exact?) end def matches_system_filters?(node) applied_filters << :system matches_visibility_filters?(node) && matches_id_filter?(node) && matches_class_filter?(node) && matches_style_filter?(node) && matches_focused_filter?(node) && matches_text_filter?(node) && matches_exact_text_filter?(node) end def matches_spatial_filters?(node) applied_filters << :spatial return true unless use_spatial_filter? node_rect = Rectangle.new(node.initial_cache[:position] || node.rect) if options[:above] el_rect = rect_cache(options[:above]) return false unless node_rect.above? el_rect end if options[:below] el_rect = rect_cache(options[:below]) return false unless node_rect.below? el_rect end if options[:left_of] el_rect = rect_cache(options[:left_of]) return false unless node_rect.left_of? el_rect end if options[:right_of] el_rect = rect_cache(options[:right_of]) return false unless node_rect.right_of? el_rect end if options[:near] return false if node == options[:near] el_rect = rect_cache(options[:near]) return false unless node_rect.near? el_rect end true end def matches_id_filter?(node) return true unless use_default_id_filter? && options[:id].is_a?(Regexp) options[:id].match? node[:id] end def matches_class_filter?(node) return true unless use_default_class_filter? && need_to_process_classes? if options[:class].is_a? Regexp options[:class].match? node[:class] else classes = (node[:class] || '').split options[:class].select { |c| c.is_a? Regexp }.all? do |r| classes.any? { |cls| r.match? cls } end end end def matches_focused_filter?(node) return true unless use_default_focused_filter? (node == node.session.active_element) == options[:focused] end def need_to_process_classes? case options[:class] when Regexp then true when Array then options[:class].any?(Regexp) else false end end def matches_style_filter?(node) case options[:style] when String, nil true when Regexp options[:style].match? node[:style] when Hash matches_style?(node, options[:style]) end end def matches_style?(node, styles) @actual_styles = node.initial_cache[:style] || node.style(*styles.keys) styles.all? do |style, value| if value.is_a? Regexp value.match? @actual_styles[style.to_s] else @actual_styles[style.to_s] == value end end end def matches_text_filter?(node) value = options[:text] return true unless value return matches_text_exactly?(node, value) if exact_text == true && !value.is_a?(Regexp) regexp = value.is_a?(Regexp) ? value : Regexp.escape(value.to_s) matches_text_regexp?(node, regexp) end def matches_exact_text_filter?(node) case exact_text when String, Regexp matches_text_exactly?(node, exact_text) else true end end def matches_visibility_filters?(node) obscured = options[:obscured] return (visible != :hidden) && (node.initial_cache[:visible] != false) && !node.obscured? if obscured == false vis = case visible when :visible node.initial_cache[:visible] || (node.initial_cache[:visible].nil? && node.visible?) when :hidden # TODO: check why the 'visbile' cache spelling mistake wasn't caught in a test # (node.initial_cache[:visible] == false) || (node.initial_cache[:visbile].nil? && !node.visible?) (node.initial_cache[:visible] == false) || (node.initial_cache[:visible].nil? && !node.visible?) else true end vis && case obscured when true node.obscured? when false !node.obscured? else true end end def matches_text_exactly?(node, value) regexp = value.is_a?(Regexp) ? value : /\A#{Regexp.escape(value.to_s)}\z/ matches_text_regexp(node, regexp).then { |m| m&.pre_match == '' && m&.post_match == '' } end def normalize_ws options.fetch(:normalize_ws, session_options.default_normalize_ws) end def matches_text_regexp(node, regexp) text_visible = visible text_visible = :all if text_visible == :hidden node.text(text_visible, normalize_ws: normalize_ws).match(regexp) end def matches_text_regexp?(node, regexp) !matches_text_regexp(node, regexp).nil? end def default_visibility @selector.default_visibility(session_options.ignore_hidden_elements, options) end def builder(expr) selector.builder(expr) end def position_cache(key) @filter_cache[key][:position] ||= key.rect end def rect_cache(key) @filter_cache[key][:rect] ||= Rectangle.new(position_cache(key)) end class Rectangle attr_reader :top, :bottom, :left, :right def initialize(position) # rubocop:disable Style/RescueModifier @top = position['top'] rescue position['y'] @bottom = position['bottom'] rescue (@top + position['height']) @left = position['left'] rescue position['x'] @right = position['right'] rescue (@left + position['width']) # rubocop:enable Style/RescueModifier end def distance(other) distance = Float::INFINITY line_segments.each do |ls1| other.line_segments.each do |ls2| distance = [ distance, distance_segment_segment(*ls1, *ls2) ].min end end distance end def above?(other) bottom <= other.top end def below?(other) top >= other.bottom end def left_of?(other) right <= other.left end def right_of?(other) left >= other.right end def near?(other) distance(other) <= 50 end protected def line_segments [ [Vector[top, left], Vector[top, right]], [Vector[top, right], Vector[bottom, left]], [Vector[bottom, left], Vector[bottom, right]], [Vector[bottom, right], Vector[top, left]] ] end private def distance_segment_segment(l1p1, l1p2, l2p1, l2p2) # See http://geomalgorithms.com/a07-_distance.html # rubocop:disable Naming/VariableName u = l1p2 - l1p1 v = l2p2 - l2p1 w = l1p1 - l2p1 a = u.dot u b = u.dot v c = v.dot v d = u.dot w e = v.dot w cap_d = (a * c) - (b**2) sD = tD = cap_d # compute the line parameters of the two closest points if cap_d < Float::EPSILON # the lines are almost parallel sN = 0.0 # force using point P0 on segment S1 sD = 1.0 # to prevent possible division by 0.0 later tN = e tD = c else # get the closest points on the infinite lines sN = (b * e) - (c * d) tN = (a * e) - (b * d) if sN.negative? # sc < 0 => the s=0 edge is visible sN = 0 tN = e tD = c elsif sN > sD # sc > 1 => the s=1 edge is visible sN = sD tN = e + b tD = c end end if tN.negative? # tc < 0 => the t=0 edge is visible tN = 0 # recompute sc for this edge if (-d).negative? sN = 0.0 elsif -d > a sN = sD else sN = -d sD = a end elsif tN > tD # tc > 1 => the t=1 edge is visible tN = tD # recompute sc for this edge if (-d + b).negative? sN = 0.0 elsif (-d + b) > a sN = sD else sN = (-d + b) sD = a end end # finally do the division to get sc and tc sc = sN.abs < Float::EPSILON ? 0.0 : sN / sD tc = tN.abs < Float::EPSILON ? 0.0 : tN / tD # difference of the two closest points dP = w + (u * sc) - (v * tc) Math.sqrt(dP.dot(dP)) # rubocop:enable Naming/VariableName end end private_constant :Rectangle end end end
Ruby
{ "end_line": 265, "name": "find_nodes_by_selector_format", "signature": "def find_nodes_by_selector_format(node, exact)", "start_line": 242 }
{ "class_name": "SelectorQuery", "class_signature": "class SelectorQuery < < Queries::BaseQuery", "module": "Capybara" }
matches_node_filters?
capybara/lib/capybara/queries/selector_query.rb
def matches_node_filters?(node, errors) applied_filters << :node unapplied_options = options.keys - valid_keys @selector.with_filter_errors(errors) do node_filters.all? do |filter_name, filter| next true unless apply_filter?(filter) if filter.matcher? unapplied_options.select { |option_name| filter.handles_option?(option_name) }.all? do |option_name| unapplied_options.delete(option_name) filter.matches?(node, option_name, options[option_name], @selector) end elsif options.key?(filter_name) unapplied_options.delete(filter_name) filter.matches?(node, filter_name, options[filter_name], @selector) elsif filter.default? filter.matches?(node, filter_name, filter.default, @selector) else true end end end end
# frozen_string_literal: true require 'matrix' module Capybara module Queries class SelectorQuery < Queries::BaseQuery attr_reader :expression, :selector, :locator, :options SPATIAL_KEYS = %i[above below left_of right_of near].freeze VALID_KEYS = SPATIAL_KEYS + COUNT_KEYS + %i[text id class style visible obscured exact exact_text normalize_ws match wait filter_set focused] VALID_MATCH = %i[first smart prefer_exact one].freeze def initialize(*args, session_options:, enable_aria_label: session_options.enable_aria_label, enable_aria_role: session_options.enable_aria_role, test_id: session_options.test_id, selector_format: nil, order: nil, **options, &filter_block) @resolved_node = nil @resolved_count = 0 @options = options.dup @order = order @filter_cache = Hash.new { |hsh, key| hsh[key] = {} } if @options[:text].is_a?(Regexp) && [true, false].include?(@options[:exact_text]) Capybara::Helpers.warn( "Boolean 'exact_text' option is not supported when 'text' option is a Regexp - ignoring" ) end super(@options) self.session_options = session_options @selector = Selector.new( find_selector(args[0].is_a?(Symbol) ? args.shift : args[0]), config: { enable_aria_label: enable_aria_label, enable_aria_role: enable_aria_role, test_id: test_id }, format: selector_format ) @locator = args.shift @filter_block = filter_block raise ArgumentError, "Unused parameters passed to #{self.class.name} : #{args}" unless args.empty? @expression = selector.call(@locator, **@options) warn_exact_usage assert_valid_keys end def name; selector.name; end def label; selector.label || selector.name; end def description(only_applied = false) # rubocop:disable Style/OptionalBooleanParameter desc = +'' show_for = show_for_stage(only_applied) if show_for[:any] desc << 'visible ' if visible == :visible desc << 'non-visible ' if visible == :hidden end desc << label.to_s desc << " #{locator.inspect}" unless locator.nil? if show_for[:any] desc << " with#{' exact' if exact_text == true} text #{options[:text].inspect}" if options[:text] desc << " with exact text #{exact_text}" if exact_text.is_a?(String) end desc << " with id #{options[:id]}" if options[:id] desc << " with classes [#{Array(options[:class]).join(',')}]" if options[:class] desc << ' that is focused' if options[:focused] desc << ' that is not focused' if options[:focused] == false desc << case options[:style] when String " with style attribute #{options[:style].inspect}" when Regexp " with style attribute matching #{options[:style].inspect}" when Hash " with styles #{options[:style].inspect}" else '' end %i[above below left_of right_of near].each do |spatial_filter| if options[spatial_filter] && show_for[:spatial] desc << " #{spatial_filter} #{options[spatial_filter] rescue '<ERROR>'}" # rubocop:disable Style/RescueModifier end end desc << selector.description(node_filters: show_for[:node], **options) desc << ' that also matches the custom filter block' if @filter_block && show_for[:node] desc << " within #{@resolved_node.inspect}" if describe_within? if locator.is_a?(String) && locator.start_with?('#', './/', '//') && !selector.raw_locator? desc << "\nNote: It appears you may be passing a CSS selector or XPath expression rather than a locator. " \ "Please see the documentation for acceptable locator values.\n\n" end desc end def applied_description description(true) end def matches_filters?(node, node_filter_errors = []) return true if (@resolved_node&.== node) && options[:allow_self] matches_locator_filter?(node) && matches_system_filters?(node) && matches_spatial_filters?(node) && matches_node_filters?(node, node_filter_errors) && matches_filter_block?(node) rescue *(node.respond_to?(:session) ? node.session.driver.invalid_element_errors : []) false end def visible case (vis = options.fetch(:visible) { default_visibility }) when true then :visible when false then :all else vis end end def exact? supports_exact? ? options.fetch(:exact, session_options.exact) : false end def match options.fetch(:match, session_options.match) end def xpath(exact = nil) exact = exact? if exact.nil? expr = apply_expression_filters(@expression) expr = exact ? expr.to_xpath(:exact) : expr.to_s if expr.respond_to?(:to_xpath) expr = filtered_expression(expr) expr = "(#{expr})[#{xpath_text_conditions}]" if try_text_match_in_expression? expr end def css filtered_expression(apply_expression_filters(@expression)) end # @api private def resolve_for(node, exact = nil) applied_filters.clear @filter_cache.clear @resolved_node = node @resolved_count += 1 node.synchronize do children = find_nodes_by_selector_format(node, exact).map(&method(:to_element)) Capybara::Result.new(ordered_results(children), self) end end # @api private def supports_exact? return @expression.respond_to? :to_xpath if @selector.supports_exact?.nil? @selector.supports_exact? end def failure_message "expected to find #{applied_description}" << count_message end def negative_failure_message "expected not to find #{applied_description}" << count_message end private def selector_format @selector.format end def matching_text options[:text] || options[:exact_text] end def text_fragments (text = matching_text).is_a?(String) ? text.split : [] end def xpath_text_conditions case (text = matching_text) when String text.split.map { |txt| XPath.contains(txt) }.reduce(&:&) when Regexp condition = XPath.current condition = condition.uppercase if text.casefold? Selector::RegexpDisassembler.new(text).alternated_substrings.map do |strs| strs.flat_map(&:split).map { |str| condition.contains(str) }.reduce(:&) end.reduce(:|) end end def try_text_match_in_expression? first_try? && matching_text && @resolved_node.is_a?(Capybara::Node::Base) && @resolved_node.session&.driver&.wait? end def first_try? @resolved_count == 1 end def show_for_stage(only_applied) lambda do |stage = :any| !only_applied || (stage == :any ? applied_filters.any? : applied_filters.include?(stage)) end end def applied_filters @applied_filters ||= [] end def find_selector(locator) case locator when Symbol then Selector[locator] else Selector.for(locator) end || Selector[session_options.default_selector] end def find_nodes_by_selector_format(node, exact) hints = {} hints[:uses_visibility] = true unless visible == :all hints[:texts] = text_fragments unless selector_format == :xpath hints[:styles] = options[:style] if use_default_style_filter? hints[:position] = true if use_spatial_filter? case selector_format when :css if node.method(:find_css).arity == 1 node.find_css(css) else node.find_css(css, **hints) end when :xpath if node.method(:find_xpath).arity == 1 node.find_xpath(xpath(exact)) else node.find_xpath(xpath(exact), **hints) end else raise ArgumentError, "Unknown format: #{selector_format}" end end def to_element(node) if @resolved_node.is_a?(Capybara::Node::Base) Capybara::Node::Element.new(@resolved_node.session, node, @resolved_node, self) else Capybara::Node::Simple.new(node) end end def valid_keys (VALID_KEYS + custom_keys).uniq end def matches_node_filters?(node, errors) applied_filters << :node unapplied_options = options.keys - valid_keys @selector.with_filter_errors(errors) do node_filters.all? do |filter_name, filter| next true unless apply_filter?(filter) if filter.matcher? unapplied_options.select { |option_name| filter.handles_option?(option_name) }.all? do |option_name| unapplied_options.delete(option_name) filter.matches?(node, option_name, options[option_name], @selector) end elsif options.key?(filter_name) unapplied_options.delete(filter_name) filter.matches?(node, filter_name, options[filter_name], @selector) elsif filter.default? filter.matches?(node, filter_name, filter.default, @selector) else true end end end end def matches_filter_block?(node) return true unless @filter_block if node.respond_to?(:session) node.session.using_wait_time(0) { @filter_block.call(node) } else @filter_block.call(node) end end def filter_set(name) ::Capybara::Selector::FilterSet[name] end def node_filters if options.key?(:filter_set) filter_set(options[:filter_set]) else @selector end.node_filters end def expression_filters filters = @selector.expression_filters filters.merge filter_set(options[:filter_set]).expression_filters if options.key?(:filter_set) filters end def ordered_results(results) case @order when :reverse results.reverse else results end end def custom_keys @custom_keys ||= node_filters.keys + expression_filters.keys end def assert_valid_keys unless VALID_MATCH.include?(match) raise ArgumentError, "Invalid option #{match.inspect} for :match, should be one of #{VALID_MATCH.map(&:inspect).join(', ')}" end unhandled_options = @options.keys.reject do |option_name| valid_keys.include?(option_name) || expression_filters.any? { |_name, ef| ef.handles_option? option_name } || node_filters.any? { |_name, nf| nf.handles_option? option_name } end return if unhandled_options.empty? invalid_names = unhandled_options.map(&:inspect).join(', ') valid_names = (valid_keys - [:allow_self]).map(&:inspect).join(', ') raise ArgumentError, "Invalid option(s) #{invalid_names}, should be one of #{valid_names}" end def filtered_expression(expr) conditions = {} conditions[:id] = options[:id] if use_default_id_filter? conditions[:class] = options[:class] if use_default_class_filter? conditions[:style] = options[:style] if use_default_style_filter? && !options[:style].is_a?(Hash) builder(expr).add_attribute_conditions(**conditions) end def use_default_id_filter? options.key?(:id) && !custom_keys.include?(:id) end def use_default_class_filter? options.key?(:class) && !custom_keys.include?(:class) end def use_default_style_filter? options.key?(:style) && !custom_keys.include?(:style) end def use_default_focused_filter? options.key?(:focused) && !custom_keys.include?(:focused) end def use_spatial_filter? options.values_at(*SPATIAL_KEYS).compact.any? end def apply_expression_filters(expression) unapplied_options = options.keys - valid_keys expression_filters.inject(expression) do |expr, (name, ef)| next expr unless apply_filter?(ef) if ef.matcher? unapplied_options.select(&ef.method(:handles_option?)).inject(expr) do |memo, option_name| unapplied_options.delete(option_name) ef.apply_filter(memo, option_name, options[option_name], @selector) end elsif options.key?(name) unapplied_options.delete(name) ef.apply_filter(expr, name, options[name], @selector) elsif ef.default? ef.apply_filter(expr, name, ef.default, @selector) else expr end end end def warn_exact_usage return unless options.key?(:exact) && !supports_exact? warn "The :exact option only has an effect on queries using the XPath#is method. Using it with the query \"#{expression}\" has no effect." end def exact_text options.fetch(:exact_text, session_options.exact_text) end def describe_within? @resolved_node && !document?(@resolved_node) && !simple_root?(@resolved_node) end def document?(node) node.is_a?(::Capybara::Node::Document) end def simple_root?(node) node.is_a?(::Capybara::Node::Simple) && node.path == '/' end def apply_filter?(filter) filter.format.nil? || (filter.format == selector_format) end def matches_locator_filter?(node) return true unless @selector.locator_filter && apply_filter?(@selector.locator_filter) @selector.locator_filter.matches?(node, @locator, @selector, exact: exact?) end def matches_system_filters?(node) applied_filters << :system matches_visibility_filters?(node) && matches_id_filter?(node) && matches_class_filter?(node) && matches_style_filter?(node) && matches_focused_filter?(node) && matches_text_filter?(node) && matches_exact_text_filter?(node) end def matches_spatial_filters?(node) applied_filters << :spatial return true unless use_spatial_filter? node_rect = Rectangle.new(node.initial_cache[:position] || node.rect) if options[:above] el_rect = rect_cache(options[:above]) return false unless node_rect.above? el_rect end if options[:below] el_rect = rect_cache(options[:below]) return false unless node_rect.below? el_rect end if options[:left_of] el_rect = rect_cache(options[:left_of]) return false unless node_rect.left_of? el_rect end if options[:right_of] el_rect = rect_cache(options[:right_of]) return false unless node_rect.right_of? el_rect end if options[:near] return false if node == options[:near] el_rect = rect_cache(options[:near]) return false unless node_rect.near? el_rect end true end def matches_id_filter?(node) return true unless use_default_id_filter? && options[:id].is_a?(Regexp) options[:id].match? node[:id] end def matches_class_filter?(node) return true unless use_default_class_filter? && need_to_process_classes? if options[:class].is_a? Regexp options[:class].match? node[:class] else classes = (node[:class] || '').split options[:class].select { |c| c.is_a? Regexp }.all? do |r| classes.any? { |cls| r.match? cls } end end end def matches_focused_filter?(node) return true unless use_default_focused_filter? (node == node.session.active_element) == options[:focused] end def need_to_process_classes? case options[:class] when Regexp then true when Array then options[:class].any?(Regexp) else false end end def matches_style_filter?(node) case options[:style] when String, nil true when Regexp options[:style].match? node[:style] when Hash matches_style?(node, options[:style]) end end def matches_style?(node, styles) @actual_styles = node.initial_cache[:style] || node.style(*styles.keys) styles.all? do |style, value| if value.is_a? Regexp value.match? @actual_styles[style.to_s] else @actual_styles[style.to_s] == value end end end def matches_text_filter?(node) value = options[:text] return true unless value return matches_text_exactly?(node, value) if exact_text == true && !value.is_a?(Regexp) regexp = value.is_a?(Regexp) ? value : Regexp.escape(value.to_s) matches_text_regexp?(node, regexp) end def matches_exact_text_filter?(node) case exact_text when String, Regexp matches_text_exactly?(node, exact_text) else true end end def matches_visibility_filters?(node) obscured = options[:obscured] return (visible != :hidden) && (node.initial_cache[:visible] != false) && !node.obscured? if obscured == false vis = case visible when :visible node.initial_cache[:visible] || (node.initial_cache[:visible].nil? && node.visible?) when :hidden # TODO: check why the 'visbile' cache spelling mistake wasn't caught in a test # (node.initial_cache[:visible] == false) || (node.initial_cache[:visbile].nil? && !node.visible?) (node.initial_cache[:visible] == false) || (node.initial_cache[:visible].nil? && !node.visible?) else true end vis && case obscured when true node.obscured? when false !node.obscured? else true end end def matches_text_exactly?(node, value) regexp = value.is_a?(Regexp) ? value : /\A#{Regexp.escape(value.to_s)}\z/ matches_text_regexp(node, regexp).then { |m| m&.pre_match == '' && m&.post_match == '' } end def normalize_ws options.fetch(:normalize_ws, session_options.default_normalize_ws) end def matches_text_regexp(node, regexp) text_visible = visible text_visible = :all if text_visible == :hidden node.text(text_visible, normalize_ws: normalize_ws).match(regexp) end def matches_text_regexp?(node, regexp) !matches_text_regexp(node, regexp).nil? end def default_visibility @selector.default_visibility(session_options.ignore_hidden_elements, options) end def builder(expr) selector.builder(expr) end def position_cache(key) @filter_cache[key][:position] ||= key.rect end def rect_cache(key) @filter_cache[key][:rect] ||= Rectangle.new(position_cache(key)) end class Rectangle attr_reader :top, :bottom, :left, :right def initialize(position) # rubocop:disable Style/RescueModifier @top = position['top'] rescue position['y'] @bottom = position['bottom'] rescue (@top + position['height']) @left = position['left'] rescue position['x'] @right = position['right'] rescue (@left + position['width']) # rubocop:enable Style/RescueModifier end def distance(other) distance = Float::INFINITY line_segments.each do |ls1| other.line_segments.each do |ls2| distance = [ distance, distance_segment_segment(*ls1, *ls2) ].min end end distance end def above?(other) bottom <= other.top end def below?(other) top >= other.bottom end def left_of?(other) right <= other.left end def right_of?(other) left >= other.right end def near?(other) distance(other) <= 50 end protected def line_segments [ [Vector[top, left], Vector[top, right]], [Vector[top, right], Vector[bottom, left]], [Vector[bottom, left], Vector[bottom, right]], [Vector[bottom, right], Vector[top, left]] ] end private def distance_segment_segment(l1p1, l1p2, l2p1, l2p2) # See http://geomalgorithms.com/a07-_distance.html # rubocop:disable Naming/VariableName u = l1p2 - l1p1 v = l2p2 - l2p1 w = l1p1 - l2p1 a = u.dot u b = u.dot v c = v.dot v d = u.dot w e = v.dot w cap_d = (a * c) - (b**2) sD = tD = cap_d # compute the line parameters of the two closest points if cap_d < Float::EPSILON # the lines are almost parallel sN = 0.0 # force using point P0 on segment S1 sD = 1.0 # to prevent possible division by 0.0 later tN = e tD = c else # get the closest points on the infinite lines sN = (b * e) - (c * d) tN = (a * e) - (b * d) if sN.negative? # sc < 0 => the s=0 edge is visible sN = 0 tN = e tD = c elsif sN > sD # sc > 1 => the s=1 edge is visible sN = sD tN = e + b tD = c end end if tN.negative? # tc < 0 => the t=0 edge is visible tN = 0 # recompute sc for this edge if (-d).negative? sN = 0.0 elsif -d > a sN = sD else sN = -d sD = a end elsif tN > tD # tc > 1 => the t=1 edge is visible tN = tD # recompute sc for this edge if (-d + b).negative? sN = 0.0 elsif (-d + b) > a sN = sD else sN = (-d + b) sD = a end end # finally do the division to get sc and tc sc = sN.abs < Float::EPSILON ? 0.0 : sN / sD tc = tN.abs < Float::EPSILON ? 0.0 : tN / tD # difference of the two closest points dP = w + (u * sc) - (v * tc) Math.sqrt(dP.dot(dP)) # rubocop:enable Naming/VariableName end end private_constant :Rectangle end end end
Ruby
{ "end_line": 302, "name": "matches_node_filters?", "signature": "def matches_node_filters?(node, errors)", "start_line": 279 }
{ "class_name": "SelectorQuery", "class_signature": "class SelectorQuery < < Queries::BaseQuery", "module": "Capybara" }
assert_valid_keys
capybara/lib/capybara/queries/selector_query.rb
def assert_valid_keys unless VALID_MATCH.include?(match) raise ArgumentError, "Invalid option #{match.inspect} for :match, should be one of #{VALID_MATCH.map(&:inspect).join(', ')}" end unhandled_options = @options.keys.reject do |option_name| valid_keys.include?(option_name) || expression_filters.any? { |_name, ef| ef.handles_option? option_name } || node_filters.any? { |_name, nf| nf.handles_option? option_name } end return if unhandled_options.empty? invalid_names = unhandled_options.map(&:inspect).join(', ') valid_names = (valid_keys - [:allow_self]).map(&:inspect).join(', ') raise ArgumentError, "Invalid option(s) #{invalid_names}, should be one of #{valid_names}" end
# frozen_string_literal: true require 'matrix' module Capybara module Queries class SelectorQuery < Queries::BaseQuery attr_reader :expression, :selector, :locator, :options SPATIAL_KEYS = %i[above below left_of right_of near].freeze VALID_KEYS = SPATIAL_KEYS + COUNT_KEYS + %i[text id class style visible obscured exact exact_text normalize_ws match wait filter_set focused] VALID_MATCH = %i[first smart prefer_exact one].freeze def initialize(*args, session_options:, enable_aria_label: session_options.enable_aria_label, enable_aria_role: session_options.enable_aria_role, test_id: session_options.test_id, selector_format: nil, order: nil, **options, &filter_block) @resolved_node = nil @resolved_count = 0 @options = options.dup @order = order @filter_cache = Hash.new { |hsh, key| hsh[key] = {} } if @options[:text].is_a?(Regexp) && [true, false].include?(@options[:exact_text]) Capybara::Helpers.warn( "Boolean 'exact_text' option is not supported when 'text' option is a Regexp - ignoring" ) end super(@options) self.session_options = session_options @selector = Selector.new( find_selector(args[0].is_a?(Symbol) ? args.shift : args[0]), config: { enable_aria_label: enable_aria_label, enable_aria_role: enable_aria_role, test_id: test_id }, format: selector_format ) @locator = args.shift @filter_block = filter_block raise ArgumentError, "Unused parameters passed to #{self.class.name} : #{args}" unless args.empty? @expression = selector.call(@locator, **@options) warn_exact_usage assert_valid_keys end def name; selector.name; end def label; selector.label || selector.name; end def description(only_applied = false) # rubocop:disable Style/OptionalBooleanParameter desc = +'' show_for = show_for_stage(only_applied) if show_for[:any] desc << 'visible ' if visible == :visible desc << 'non-visible ' if visible == :hidden end desc << label.to_s desc << " #{locator.inspect}" unless locator.nil? if show_for[:any] desc << " with#{' exact' if exact_text == true} text #{options[:text].inspect}" if options[:text] desc << " with exact text #{exact_text}" if exact_text.is_a?(String) end desc << " with id #{options[:id]}" if options[:id] desc << " with classes [#{Array(options[:class]).join(',')}]" if options[:class] desc << ' that is focused' if options[:focused] desc << ' that is not focused' if options[:focused] == false desc << case options[:style] when String " with style attribute #{options[:style].inspect}" when Regexp " with style attribute matching #{options[:style].inspect}" when Hash " with styles #{options[:style].inspect}" else '' end %i[above below left_of right_of near].each do |spatial_filter| if options[spatial_filter] && show_for[:spatial] desc << " #{spatial_filter} #{options[spatial_filter] rescue '<ERROR>'}" # rubocop:disable Style/RescueModifier end end desc << selector.description(node_filters: show_for[:node], **options) desc << ' that also matches the custom filter block' if @filter_block && show_for[:node] desc << " within #{@resolved_node.inspect}" if describe_within? if locator.is_a?(String) && locator.start_with?('#', './/', '//') && !selector.raw_locator? desc << "\nNote: It appears you may be passing a CSS selector or XPath expression rather than a locator. " \ "Please see the documentation for acceptable locator values.\n\n" end desc end def applied_description description(true) end def matches_filters?(node, node_filter_errors = []) return true if (@resolved_node&.== node) && options[:allow_self] matches_locator_filter?(node) && matches_system_filters?(node) && matches_spatial_filters?(node) && matches_node_filters?(node, node_filter_errors) && matches_filter_block?(node) rescue *(node.respond_to?(:session) ? node.session.driver.invalid_element_errors : []) false end def visible case (vis = options.fetch(:visible) { default_visibility }) when true then :visible when false then :all else vis end end def exact? supports_exact? ? options.fetch(:exact, session_options.exact) : false end def match options.fetch(:match, session_options.match) end def xpath(exact = nil) exact = exact? if exact.nil? expr = apply_expression_filters(@expression) expr = exact ? expr.to_xpath(:exact) : expr.to_s if expr.respond_to?(:to_xpath) expr = filtered_expression(expr) expr = "(#{expr})[#{xpath_text_conditions}]" if try_text_match_in_expression? expr end def css filtered_expression(apply_expression_filters(@expression)) end # @api private def resolve_for(node, exact = nil) applied_filters.clear @filter_cache.clear @resolved_node = node @resolved_count += 1 node.synchronize do children = find_nodes_by_selector_format(node, exact).map(&method(:to_element)) Capybara::Result.new(ordered_results(children), self) end end # @api private def supports_exact? return @expression.respond_to? :to_xpath if @selector.supports_exact?.nil? @selector.supports_exact? end def failure_message "expected to find #{applied_description}" << count_message end def negative_failure_message "expected not to find #{applied_description}" << count_message end private def selector_format @selector.format end def matching_text options[:text] || options[:exact_text] end def text_fragments (text = matching_text).is_a?(String) ? text.split : [] end def xpath_text_conditions case (text = matching_text) when String text.split.map { |txt| XPath.contains(txt) }.reduce(&:&) when Regexp condition = XPath.current condition = condition.uppercase if text.casefold? Selector::RegexpDisassembler.new(text).alternated_substrings.map do |strs| strs.flat_map(&:split).map { |str| condition.contains(str) }.reduce(:&) end.reduce(:|) end end def try_text_match_in_expression? first_try? && matching_text && @resolved_node.is_a?(Capybara::Node::Base) && @resolved_node.session&.driver&.wait? end def first_try? @resolved_count == 1 end def show_for_stage(only_applied) lambda do |stage = :any| !only_applied || (stage == :any ? applied_filters.any? : applied_filters.include?(stage)) end end def applied_filters @applied_filters ||= [] end def find_selector(locator) case locator when Symbol then Selector[locator] else Selector.for(locator) end || Selector[session_options.default_selector] end def find_nodes_by_selector_format(node, exact) hints = {} hints[:uses_visibility] = true unless visible == :all hints[:texts] = text_fragments unless selector_format == :xpath hints[:styles] = options[:style] if use_default_style_filter? hints[:position] = true if use_spatial_filter? case selector_format when :css if node.method(:find_css).arity == 1 node.find_css(css) else node.find_css(css, **hints) end when :xpath if node.method(:find_xpath).arity == 1 node.find_xpath(xpath(exact)) else node.find_xpath(xpath(exact), **hints) end else raise ArgumentError, "Unknown format: #{selector_format}" end end def to_element(node) if @resolved_node.is_a?(Capybara::Node::Base) Capybara::Node::Element.new(@resolved_node.session, node, @resolved_node, self) else Capybara::Node::Simple.new(node) end end def valid_keys (VALID_KEYS + custom_keys).uniq end def matches_node_filters?(node, errors) applied_filters << :node unapplied_options = options.keys - valid_keys @selector.with_filter_errors(errors) do node_filters.all? do |filter_name, filter| next true unless apply_filter?(filter) if filter.matcher? unapplied_options.select { |option_name| filter.handles_option?(option_name) }.all? do |option_name| unapplied_options.delete(option_name) filter.matches?(node, option_name, options[option_name], @selector) end elsif options.key?(filter_name) unapplied_options.delete(filter_name) filter.matches?(node, filter_name, options[filter_name], @selector) elsif filter.default? filter.matches?(node, filter_name, filter.default, @selector) else true end end end end def matches_filter_block?(node) return true unless @filter_block if node.respond_to?(:session) node.session.using_wait_time(0) { @filter_block.call(node) } else @filter_block.call(node) end end def filter_set(name) ::Capybara::Selector::FilterSet[name] end def node_filters if options.key?(:filter_set) filter_set(options[:filter_set]) else @selector end.node_filters end def expression_filters filters = @selector.expression_filters filters.merge filter_set(options[:filter_set]).expression_filters if options.key?(:filter_set) filters end def ordered_results(results) case @order when :reverse results.reverse else results end end def custom_keys @custom_keys ||= node_filters.keys + expression_filters.keys end def assert_valid_keys unless VALID_MATCH.include?(match) raise ArgumentError, "Invalid option #{match.inspect} for :match, should be one of #{VALID_MATCH.map(&:inspect).join(', ')}" end unhandled_options = @options.keys.reject do |option_name| valid_keys.include?(option_name) || expression_filters.any? { |_name, ef| ef.handles_option? option_name } || node_filters.any? { |_name, nf| nf.handles_option? option_name } end return if unhandled_options.empty? invalid_names = unhandled_options.map(&:inspect).join(', ') valid_names = (valid_keys - [:allow_self]).map(&:inspect).join(', ') raise ArgumentError, "Invalid option(s) #{invalid_names}, should be one of #{valid_names}" end def filtered_expression(expr) conditions = {} conditions[:id] = options[:id] if use_default_id_filter? conditions[:class] = options[:class] if use_default_class_filter? conditions[:style] = options[:style] if use_default_style_filter? && !options[:style].is_a?(Hash) builder(expr).add_attribute_conditions(**conditions) end def use_default_id_filter? options.key?(:id) && !custom_keys.include?(:id) end def use_default_class_filter? options.key?(:class) && !custom_keys.include?(:class) end def use_default_style_filter? options.key?(:style) && !custom_keys.include?(:style) end def use_default_focused_filter? options.key?(:focused) && !custom_keys.include?(:focused) end def use_spatial_filter? options.values_at(*SPATIAL_KEYS).compact.any? end def apply_expression_filters(expression) unapplied_options = options.keys - valid_keys expression_filters.inject(expression) do |expr, (name, ef)| next expr unless apply_filter?(ef) if ef.matcher? unapplied_options.select(&ef.method(:handles_option?)).inject(expr) do |memo, option_name| unapplied_options.delete(option_name) ef.apply_filter(memo, option_name, options[option_name], @selector) end elsif options.key?(name) unapplied_options.delete(name) ef.apply_filter(expr, name, options[name], @selector) elsif ef.default? ef.apply_filter(expr, name, ef.default, @selector) else expr end end end def warn_exact_usage return unless options.key?(:exact) && !supports_exact? warn "The :exact option only has an effect on queries using the XPath#is method. Using it with the query \"#{expression}\" has no effect." end def exact_text options.fetch(:exact_text, session_options.exact_text) end def describe_within? @resolved_node && !document?(@resolved_node) && !simple_root?(@resolved_node) end def document?(node) node.is_a?(::Capybara::Node::Document) end def simple_root?(node) node.is_a?(::Capybara::Node::Simple) && node.path == '/' end def apply_filter?(filter) filter.format.nil? || (filter.format == selector_format) end def matches_locator_filter?(node) return true unless @selector.locator_filter && apply_filter?(@selector.locator_filter) @selector.locator_filter.matches?(node, @locator, @selector, exact: exact?) end def matches_system_filters?(node) applied_filters << :system matches_visibility_filters?(node) && matches_id_filter?(node) && matches_class_filter?(node) && matches_style_filter?(node) && matches_focused_filter?(node) && matches_text_filter?(node) && matches_exact_text_filter?(node) end def matches_spatial_filters?(node) applied_filters << :spatial return true unless use_spatial_filter? node_rect = Rectangle.new(node.initial_cache[:position] || node.rect) if options[:above] el_rect = rect_cache(options[:above]) return false unless node_rect.above? el_rect end if options[:below] el_rect = rect_cache(options[:below]) return false unless node_rect.below? el_rect end if options[:left_of] el_rect = rect_cache(options[:left_of]) return false unless node_rect.left_of? el_rect end if options[:right_of] el_rect = rect_cache(options[:right_of]) return false unless node_rect.right_of? el_rect end if options[:near] return false if node == options[:near] el_rect = rect_cache(options[:near]) return false unless node_rect.near? el_rect end true end def matches_id_filter?(node) return true unless use_default_id_filter? && options[:id].is_a?(Regexp) options[:id].match? node[:id] end def matches_class_filter?(node) return true unless use_default_class_filter? && need_to_process_classes? if options[:class].is_a? Regexp options[:class].match? node[:class] else classes = (node[:class] || '').split options[:class].select { |c| c.is_a? Regexp }.all? do |r| classes.any? { |cls| r.match? cls } end end end def matches_focused_filter?(node) return true unless use_default_focused_filter? (node == node.session.active_element) == options[:focused] end def need_to_process_classes? case options[:class] when Regexp then true when Array then options[:class].any?(Regexp) else false end end def matches_style_filter?(node) case options[:style] when String, nil true when Regexp options[:style].match? node[:style] when Hash matches_style?(node, options[:style]) end end def matches_style?(node, styles) @actual_styles = node.initial_cache[:style] || node.style(*styles.keys) styles.all? do |style, value| if value.is_a? Regexp value.match? @actual_styles[style.to_s] else @actual_styles[style.to_s] == value end end end def matches_text_filter?(node) value = options[:text] return true unless value return matches_text_exactly?(node, value) if exact_text == true && !value.is_a?(Regexp) regexp = value.is_a?(Regexp) ? value : Regexp.escape(value.to_s) matches_text_regexp?(node, regexp) end def matches_exact_text_filter?(node) case exact_text when String, Regexp matches_text_exactly?(node, exact_text) else true end end def matches_visibility_filters?(node) obscured = options[:obscured] return (visible != :hidden) && (node.initial_cache[:visible] != false) && !node.obscured? if obscured == false vis = case visible when :visible node.initial_cache[:visible] || (node.initial_cache[:visible].nil? && node.visible?) when :hidden # TODO: check why the 'visbile' cache spelling mistake wasn't caught in a test # (node.initial_cache[:visible] == false) || (node.initial_cache[:visbile].nil? && !node.visible?) (node.initial_cache[:visible] == false) || (node.initial_cache[:visible].nil? && !node.visible?) else true end vis && case obscured when true node.obscured? when false !node.obscured? else true end end def matches_text_exactly?(node, value) regexp = value.is_a?(Regexp) ? value : /\A#{Regexp.escape(value.to_s)}\z/ matches_text_regexp(node, regexp).then { |m| m&.pre_match == '' && m&.post_match == '' } end def normalize_ws options.fetch(:normalize_ws, session_options.default_normalize_ws) end def matches_text_regexp(node, regexp) text_visible = visible text_visible = :all if text_visible == :hidden node.text(text_visible, normalize_ws: normalize_ws).match(regexp) end def matches_text_regexp?(node, regexp) !matches_text_regexp(node, regexp).nil? end def default_visibility @selector.default_visibility(session_options.ignore_hidden_elements, options) end def builder(expr) selector.builder(expr) end def position_cache(key) @filter_cache[key][:position] ||= key.rect end def rect_cache(key) @filter_cache[key][:rect] ||= Rectangle.new(position_cache(key)) end class Rectangle attr_reader :top, :bottom, :left, :right def initialize(position) # rubocop:disable Style/RescueModifier @top = position['top'] rescue position['y'] @bottom = position['bottom'] rescue (@top + position['height']) @left = position['left'] rescue position['x'] @right = position['right'] rescue (@left + position['width']) # rubocop:enable Style/RescueModifier end def distance(other) distance = Float::INFINITY line_segments.each do |ls1| other.line_segments.each do |ls2| distance = [ distance, distance_segment_segment(*ls1, *ls2) ].min end end distance end def above?(other) bottom <= other.top end def below?(other) top >= other.bottom end def left_of?(other) right <= other.left end def right_of?(other) left >= other.right end def near?(other) distance(other) <= 50 end protected def line_segments [ [Vector[top, left], Vector[top, right]], [Vector[top, right], Vector[bottom, left]], [Vector[bottom, left], Vector[bottom, right]], [Vector[bottom, right], Vector[top, left]] ] end private def distance_segment_segment(l1p1, l1p2, l2p1, l2p2) # See http://geomalgorithms.com/a07-_distance.html # rubocop:disable Naming/VariableName u = l1p2 - l1p1 v = l2p2 - l2p1 w = l1p1 - l2p1 a = u.dot u b = u.dot v c = v.dot v d = u.dot w e = v.dot w cap_d = (a * c) - (b**2) sD = tD = cap_d # compute the line parameters of the two closest points if cap_d < Float::EPSILON # the lines are almost parallel sN = 0.0 # force using point P0 on segment S1 sD = 1.0 # to prevent possible division by 0.0 later tN = e tD = c else # get the closest points on the infinite lines sN = (b * e) - (c * d) tN = (a * e) - (b * d) if sN.negative? # sc < 0 => the s=0 edge is visible sN = 0 tN = e tD = c elsif sN > sD # sc > 1 => the s=1 edge is visible sN = sD tN = e + b tD = c end end if tN.negative? # tc < 0 => the t=0 edge is visible tN = 0 # recompute sc for this edge if (-d).negative? sN = 0.0 elsif -d > a sN = sD else sN = -d sD = a end elsif tN > tD # tc > 1 => the t=1 edge is visible tN = tD # recompute sc for this edge if (-d + b).negative? sN = 0.0 elsif (-d + b) > a sN = sD else sN = (-d + b) sD = a end end # finally do the division to get sc and tc sc = sN.abs < Float::EPSILON ? 0.0 : sN / sD tc = tN.abs < Float::EPSILON ? 0.0 : tN / tD # difference of the two closest points dP = w + (u * sc) - (v * tc) Math.sqrt(dP.dot(dP)) # rubocop:enable Naming/VariableName end end private_constant :Rectangle end end end
Ruby
{ "end_line": 361, "name": "assert_valid_keys", "signature": "def assert_valid_keys", "start_line": 345 }
{ "class_name": "SelectorQuery", "class_signature": "class SelectorQuery < < Queries::BaseQuery", "module": "Capybara" }
apply_expression_filters
capybara/lib/capybara/queries/selector_query.rb
def apply_expression_filters(expression) unapplied_options = options.keys - valid_keys expression_filters.inject(expression) do |expr, (name, ef)| next expr unless apply_filter?(ef) if ef.matcher? unapplied_options.select(&ef.method(:handles_option?)).inject(expr) do |memo, option_name| unapplied_options.delete(option_name) ef.apply_filter(memo, option_name, options[option_name], @selector) end elsif options.key?(name) unapplied_options.delete(name) ef.apply_filter(expr, name, options[name], @selector) elsif ef.default? ef.apply_filter(expr, name, ef.default, @selector) else expr end end end
# frozen_string_literal: true require 'matrix' module Capybara module Queries class SelectorQuery < Queries::BaseQuery attr_reader :expression, :selector, :locator, :options SPATIAL_KEYS = %i[above below left_of right_of near].freeze VALID_KEYS = SPATIAL_KEYS + COUNT_KEYS + %i[text id class style visible obscured exact exact_text normalize_ws match wait filter_set focused] VALID_MATCH = %i[first smart prefer_exact one].freeze def initialize(*args, session_options:, enable_aria_label: session_options.enable_aria_label, enable_aria_role: session_options.enable_aria_role, test_id: session_options.test_id, selector_format: nil, order: nil, **options, &filter_block) @resolved_node = nil @resolved_count = 0 @options = options.dup @order = order @filter_cache = Hash.new { |hsh, key| hsh[key] = {} } if @options[:text].is_a?(Regexp) && [true, false].include?(@options[:exact_text]) Capybara::Helpers.warn( "Boolean 'exact_text' option is not supported when 'text' option is a Regexp - ignoring" ) end super(@options) self.session_options = session_options @selector = Selector.new( find_selector(args[0].is_a?(Symbol) ? args.shift : args[0]), config: { enable_aria_label: enable_aria_label, enable_aria_role: enable_aria_role, test_id: test_id }, format: selector_format ) @locator = args.shift @filter_block = filter_block raise ArgumentError, "Unused parameters passed to #{self.class.name} : #{args}" unless args.empty? @expression = selector.call(@locator, **@options) warn_exact_usage assert_valid_keys end def name; selector.name; end def label; selector.label || selector.name; end def description(only_applied = false) # rubocop:disable Style/OptionalBooleanParameter desc = +'' show_for = show_for_stage(only_applied) if show_for[:any] desc << 'visible ' if visible == :visible desc << 'non-visible ' if visible == :hidden end desc << label.to_s desc << " #{locator.inspect}" unless locator.nil? if show_for[:any] desc << " with#{' exact' if exact_text == true} text #{options[:text].inspect}" if options[:text] desc << " with exact text #{exact_text}" if exact_text.is_a?(String) end desc << " with id #{options[:id]}" if options[:id] desc << " with classes [#{Array(options[:class]).join(',')}]" if options[:class] desc << ' that is focused' if options[:focused] desc << ' that is not focused' if options[:focused] == false desc << case options[:style] when String " with style attribute #{options[:style].inspect}" when Regexp " with style attribute matching #{options[:style].inspect}" when Hash " with styles #{options[:style].inspect}" else '' end %i[above below left_of right_of near].each do |spatial_filter| if options[spatial_filter] && show_for[:spatial] desc << " #{spatial_filter} #{options[spatial_filter] rescue '<ERROR>'}" # rubocop:disable Style/RescueModifier end end desc << selector.description(node_filters: show_for[:node], **options) desc << ' that also matches the custom filter block' if @filter_block && show_for[:node] desc << " within #{@resolved_node.inspect}" if describe_within? if locator.is_a?(String) && locator.start_with?('#', './/', '//') && !selector.raw_locator? desc << "\nNote: It appears you may be passing a CSS selector or XPath expression rather than a locator. " \ "Please see the documentation for acceptable locator values.\n\n" end desc end def applied_description description(true) end def matches_filters?(node, node_filter_errors = []) return true if (@resolved_node&.== node) && options[:allow_self] matches_locator_filter?(node) && matches_system_filters?(node) && matches_spatial_filters?(node) && matches_node_filters?(node, node_filter_errors) && matches_filter_block?(node) rescue *(node.respond_to?(:session) ? node.session.driver.invalid_element_errors : []) false end def visible case (vis = options.fetch(:visible) { default_visibility }) when true then :visible when false then :all else vis end end def exact? supports_exact? ? options.fetch(:exact, session_options.exact) : false end def match options.fetch(:match, session_options.match) end def xpath(exact = nil) exact = exact? if exact.nil? expr = apply_expression_filters(@expression) expr = exact ? expr.to_xpath(:exact) : expr.to_s if expr.respond_to?(:to_xpath) expr = filtered_expression(expr) expr = "(#{expr})[#{xpath_text_conditions}]" if try_text_match_in_expression? expr end def css filtered_expression(apply_expression_filters(@expression)) end # @api private def resolve_for(node, exact = nil) applied_filters.clear @filter_cache.clear @resolved_node = node @resolved_count += 1 node.synchronize do children = find_nodes_by_selector_format(node, exact).map(&method(:to_element)) Capybara::Result.new(ordered_results(children), self) end end # @api private def supports_exact? return @expression.respond_to? :to_xpath if @selector.supports_exact?.nil? @selector.supports_exact? end def failure_message "expected to find #{applied_description}" << count_message end def negative_failure_message "expected not to find #{applied_description}" << count_message end private def selector_format @selector.format end def matching_text options[:text] || options[:exact_text] end def text_fragments (text = matching_text).is_a?(String) ? text.split : [] end def xpath_text_conditions case (text = matching_text) when String text.split.map { |txt| XPath.contains(txt) }.reduce(&:&) when Regexp condition = XPath.current condition = condition.uppercase if text.casefold? Selector::RegexpDisassembler.new(text).alternated_substrings.map do |strs| strs.flat_map(&:split).map { |str| condition.contains(str) }.reduce(:&) end.reduce(:|) end end def try_text_match_in_expression? first_try? && matching_text && @resolved_node.is_a?(Capybara::Node::Base) && @resolved_node.session&.driver&.wait? end def first_try? @resolved_count == 1 end def show_for_stage(only_applied) lambda do |stage = :any| !only_applied || (stage == :any ? applied_filters.any? : applied_filters.include?(stage)) end end def applied_filters @applied_filters ||= [] end def find_selector(locator) case locator when Symbol then Selector[locator] else Selector.for(locator) end || Selector[session_options.default_selector] end def find_nodes_by_selector_format(node, exact) hints = {} hints[:uses_visibility] = true unless visible == :all hints[:texts] = text_fragments unless selector_format == :xpath hints[:styles] = options[:style] if use_default_style_filter? hints[:position] = true if use_spatial_filter? case selector_format when :css if node.method(:find_css).arity == 1 node.find_css(css) else node.find_css(css, **hints) end when :xpath if node.method(:find_xpath).arity == 1 node.find_xpath(xpath(exact)) else node.find_xpath(xpath(exact), **hints) end else raise ArgumentError, "Unknown format: #{selector_format}" end end def to_element(node) if @resolved_node.is_a?(Capybara::Node::Base) Capybara::Node::Element.new(@resolved_node.session, node, @resolved_node, self) else Capybara::Node::Simple.new(node) end end def valid_keys (VALID_KEYS + custom_keys).uniq end def matches_node_filters?(node, errors) applied_filters << :node unapplied_options = options.keys - valid_keys @selector.with_filter_errors(errors) do node_filters.all? do |filter_name, filter| next true unless apply_filter?(filter) if filter.matcher? unapplied_options.select { |option_name| filter.handles_option?(option_name) }.all? do |option_name| unapplied_options.delete(option_name) filter.matches?(node, option_name, options[option_name], @selector) end elsif options.key?(filter_name) unapplied_options.delete(filter_name) filter.matches?(node, filter_name, options[filter_name], @selector) elsif filter.default? filter.matches?(node, filter_name, filter.default, @selector) else true end end end end def matches_filter_block?(node) return true unless @filter_block if node.respond_to?(:session) node.session.using_wait_time(0) { @filter_block.call(node) } else @filter_block.call(node) end end def filter_set(name) ::Capybara::Selector::FilterSet[name] end def node_filters if options.key?(:filter_set) filter_set(options[:filter_set]) else @selector end.node_filters end def expression_filters filters = @selector.expression_filters filters.merge filter_set(options[:filter_set]).expression_filters if options.key?(:filter_set) filters end def ordered_results(results) case @order when :reverse results.reverse else results end end def custom_keys @custom_keys ||= node_filters.keys + expression_filters.keys end def assert_valid_keys unless VALID_MATCH.include?(match) raise ArgumentError, "Invalid option #{match.inspect} for :match, should be one of #{VALID_MATCH.map(&:inspect).join(', ')}" end unhandled_options = @options.keys.reject do |option_name| valid_keys.include?(option_name) || expression_filters.any? { |_name, ef| ef.handles_option? option_name } || node_filters.any? { |_name, nf| nf.handles_option? option_name } end return if unhandled_options.empty? invalid_names = unhandled_options.map(&:inspect).join(', ') valid_names = (valid_keys - [:allow_self]).map(&:inspect).join(', ') raise ArgumentError, "Invalid option(s) #{invalid_names}, should be one of #{valid_names}" end def filtered_expression(expr) conditions = {} conditions[:id] = options[:id] if use_default_id_filter? conditions[:class] = options[:class] if use_default_class_filter? conditions[:style] = options[:style] if use_default_style_filter? && !options[:style].is_a?(Hash) builder(expr).add_attribute_conditions(**conditions) end def use_default_id_filter? options.key?(:id) && !custom_keys.include?(:id) end def use_default_class_filter? options.key?(:class) && !custom_keys.include?(:class) end def use_default_style_filter? options.key?(:style) && !custom_keys.include?(:style) end def use_default_focused_filter? options.key?(:focused) && !custom_keys.include?(:focused) end def use_spatial_filter? options.values_at(*SPATIAL_KEYS).compact.any? end def apply_expression_filters(expression) unapplied_options = options.keys - valid_keys expression_filters.inject(expression) do |expr, (name, ef)| next expr unless apply_filter?(ef) if ef.matcher? unapplied_options.select(&ef.method(:handles_option?)).inject(expr) do |memo, option_name| unapplied_options.delete(option_name) ef.apply_filter(memo, option_name, options[option_name], @selector) end elsif options.key?(name) unapplied_options.delete(name) ef.apply_filter(expr, name, options[name], @selector) elsif ef.default? ef.apply_filter(expr, name, ef.default, @selector) else expr end end end def warn_exact_usage return unless options.key?(:exact) && !supports_exact? warn "The :exact option only has an effect on queries using the XPath#is method. Using it with the query \"#{expression}\" has no effect." end def exact_text options.fetch(:exact_text, session_options.exact_text) end def describe_within? @resolved_node && !document?(@resolved_node) && !simple_root?(@resolved_node) end def document?(node) node.is_a?(::Capybara::Node::Document) end def simple_root?(node) node.is_a?(::Capybara::Node::Simple) && node.path == '/' end def apply_filter?(filter) filter.format.nil? || (filter.format == selector_format) end def matches_locator_filter?(node) return true unless @selector.locator_filter && apply_filter?(@selector.locator_filter) @selector.locator_filter.matches?(node, @locator, @selector, exact: exact?) end def matches_system_filters?(node) applied_filters << :system matches_visibility_filters?(node) && matches_id_filter?(node) && matches_class_filter?(node) && matches_style_filter?(node) && matches_focused_filter?(node) && matches_text_filter?(node) && matches_exact_text_filter?(node) end def matches_spatial_filters?(node) applied_filters << :spatial return true unless use_spatial_filter? node_rect = Rectangle.new(node.initial_cache[:position] || node.rect) if options[:above] el_rect = rect_cache(options[:above]) return false unless node_rect.above? el_rect end if options[:below] el_rect = rect_cache(options[:below]) return false unless node_rect.below? el_rect end if options[:left_of] el_rect = rect_cache(options[:left_of]) return false unless node_rect.left_of? el_rect end if options[:right_of] el_rect = rect_cache(options[:right_of]) return false unless node_rect.right_of? el_rect end if options[:near] return false if node == options[:near] el_rect = rect_cache(options[:near]) return false unless node_rect.near? el_rect end true end def matches_id_filter?(node) return true unless use_default_id_filter? && options[:id].is_a?(Regexp) options[:id].match? node[:id] end def matches_class_filter?(node) return true unless use_default_class_filter? && need_to_process_classes? if options[:class].is_a? Regexp options[:class].match? node[:class] else classes = (node[:class] || '').split options[:class].select { |c| c.is_a? Regexp }.all? do |r| classes.any? { |cls| r.match? cls } end end end def matches_focused_filter?(node) return true unless use_default_focused_filter? (node == node.session.active_element) == options[:focused] end def need_to_process_classes? case options[:class] when Regexp then true when Array then options[:class].any?(Regexp) else false end end def matches_style_filter?(node) case options[:style] when String, nil true when Regexp options[:style].match? node[:style] when Hash matches_style?(node, options[:style]) end end def matches_style?(node, styles) @actual_styles = node.initial_cache[:style] || node.style(*styles.keys) styles.all? do |style, value| if value.is_a? Regexp value.match? @actual_styles[style.to_s] else @actual_styles[style.to_s] == value end end end def matches_text_filter?(node) value = options[:text] return true unless value return matches_text_exactly?(node, value) if exact_text == true && !value.is_a?(Regexp) regexp = value.is_a?(Regexp) ? value : Regexp.escape(value.to_s) matches_text_regexp?(node, regexp) end def matches_exact_text_filter?(node) case exact_text when String, Regexp matches_text_exactly?(node, exact_text) else true end end def matches_visibility_filters?(node) obscured = options[:obscured] return (visible != :hidden) && (node.initial_cache[:visible] != false) && !node.obscured? if obscured == false vis = case visible when :visible node.initial_cache[:visible] || (node.initial_cache[:visible].nil? && node.visible?) when :hidden # TODO: check why the 'visbile' cache spelling mistake wasn't caught in a test # (node.initial_cache[:visible] == false) || (node.initial_cache[:visbile].nil? && !node.visible?) (node.initial_cache[:visible] == false) || (node.initial_cache[:visible].nil? && !node.visible?) else true end vis && case obscured when true node.obscured? when false !node.obscured? else true end end def matches_text_exactly?(node, value) regexp = value.is_a?(Regexp) ? value : /\A#{Regexp.escape(value.to_s)}\z/ matches_text_regexp(node, regexp).then { |m| m&.pre_match == '' && m&.post_match == '' } end def normalize_ws options.fetch(:normalize_ws, session_options.default_normalize_ws) end def matches_text_regexp(node, regexp) text_visible = visible text_visible = :all if text_visible == :hidden node.text(text_visible, normalize_ws: normalize_ws).match(regexp) end def matches_text_regexp?(node, regexp) !matches_text_regexp(node, regexp).nil? end def default_visibility @selector.default_visibility(session_options.ignore_hidden_elements, options) end def builder(expr) selector.builder(expr) end def position_cache(key) @filter_cache[key][:position] ||= key.rect end def rect_cache(key) @filter_cache[key][:rect] ||= Rectangle.new(position_cache(key)) end class Rectangle attr_reader :top, :bottom, :left, :right def initialize(position) # rubocop:disable Style/RescueModifier @top = position['top'] rescue position['y'] @bottom = position['bottom'] rescue (@top + position['height']) @left = position['left'] rescue position['x'] @right = position['right'] rescue (@left + position['width']) # rubocop:enable Style/RescueModifier end def distance(other) distance = Float::INFINITY line_segments.each do |ls1| other.line_segments.each do |ls2| distance = [ distance, distance_segment_segment(*ls1, *ls2) ].min end end distance end def above?(other) bottom <= other.top end def below?(other) top >= other.bottom end def left_of?(other) right <= other.left end def right_of?(other) left >= other.right end def near?(other) distance(other) <= 50 end protected def line_segments [ [Vector[top, left], Vector[top, right]], [Vector[top, right], Vector[bottom, left]], [Vector[bottom, left], Vector[bottom, right]], [Vector[bottom, right], Vector[top, left]] ] end private def distance_segment_segment(l1p1, l1p2, l2p1, l2p2) # See http://geomalgorithms.com/a07-_distance.html # rubocop:disable Naming/VariableName u = l1p2 - l1p1 v = l2p2 - l2p1 w = l1p1 - l2p1 a = u.dot u b = u.dot v c = v.dot v d = u.dot w e = v.dot w cap_d = (a * c) - (b**2) sD = tD = cap_d # compute the line parameters of the two closest points if cap_d < Float::EPSILON # the lines are almost parallel sN = 0.0 # force using point P0 on segment S1 sD = 1.0 # to prevent possible division by 0.0 later tN = e tD = c else # get the closest points on the infinite lines sN = (b * e) - (c * d) tN = (a * e) - (b * d) if sN.negative? # sc < 0 => the s=0 edge is visible sN = 0 tN = e tD = c elsif sN > sD # sc > 1 => the s=1 edge is visible sN = sD tN = e + b tD = c end end if tN.negative? # tc < 0 => the t=0 edge is visible tN = 0 # recompute sc for this edge if (-d).negative? sN = 0.0 elsif -d > a sN = sD else sN = -d sD = a end elsif tN > tD # tc > 1 => the t=1 edge is visible tN = tD # recompute sc for this edge if (-d + b).negative? sN = 0.0 elsif (-d + b) > a sN = sD else sN = (-d + b) sD = a end end # finally do the division to get sc and tc sc = sN.abs < Float::EPSILON ? 0.0 : sN / sD tc = tN.abs < Float::EPSILON ? 0.0 : tN / tD # difference of the two closest points dP = w + (u * sc) - (v * tc) Math.sqrt(dP.dot(dP)) # rubocop:enable Naming/VariableName end end private_constant :Rectangle end end end
Ruby
{ "end_line": 410, "name": "apply_expression_filters", "signature": "def apply_expression_filters(expression)", "start_line": 391 }
{ "class_name": "SelectorQuery", "class_signature": "class SelectorQuery < < Queries::BaseQuery", "module": "Capybara" }
matches_system_filters?
capybara/lib/capybara/queries/selector_query.rb
def matches_system_filters?(node) applied_filters << :system matches_visibility_filters?(node) && matches_id_filter?(node) && matches_class_filter?(node) && matches_style_filter?(node) && matches_focused_filter?(node) && matches_text_filter?(node) && matches_exact_text_filter?(node) end
# frozen_string_literal: true require 'matrix' module Capybara module Queries class SelectorQuery < Queries::BaseQuery attr_reader :expression, :selector, :locator, :options SPATIAL_KEYS = %i[above below left_of right_of near].freeze VALID_KEYS = SPATIAL_KEYS + COUNT_KEYS + %i[text id class style visible obscured exact exact_text normalize_ws match wait filter_set focused] VALID_MATCH = %i[first smart prefer_exact one].freeze def initialize(*args, session_options:, enable_aria_label: session_options.enable_aria_label, enable_aria_role: session_options.enable_aria_role, test_id: session_options.test_id, selector_format: nil, order: nil, **options, &filter_block) @resolved_node = nil @resolved_count = 0 @options = options.dup @order = order @filter_cache = Hash.new { |hsh, key| hsh[key] = {} } if @options[:text].is_a?(Regexp) && [true, false].include?(@options[:exact_text]) Capybara::Helpers.warn( "Boolean 'exact_text' option is not supported when 'text' option is a Regexp - ignoring" ) end super(@options) self.session_options = session_options @selector = Selector.new( find_selector(args[0].is_a?(Symbol) ? args.shift : args[0]), config: { enable_aria_label: enable_aria_label, enable_aria_role: enable_aria_role, test_id: test_id }, format: selector_format ) @locator = args.shift @filter_block = filter_block raise ArgumentError, "Unused parameters passed to #{self.class.name} : #{args}" unless args.empty? @expression = selector.call(@locator, **@options) warn_exact_usage assert_valid_keys end def name; selector.name; end def label; selector.label || selector.name; end def description(only_applied = false) # rubocop:disable Style/OptionalBooleanParameter desc = +'' show_for = show_for_stage(only_applied) if show_for[:any] desc << 'visible ' if visible == :visible desc << 'non-visible ' if visible == :hidden end desc << label.to_s desc << " #{locator.inspect}" unless locator.nil? if show_for[:any] desc << " with#{' exact' if exact_text == true} text #{options[:text].inspect}" if options[:text] desc << " with exact text #{exact_text}" if exact_text.is_a?(String) end desc << " with id #{options[:id]}" if options[:id] desc << " with classes [#{Array(options[:class]).join(',')}]" if options[:class] desc << ' that is focused' if options[:focused] desc << ' that is not focused' if options[:focused] == false desc << case options[:style] when String " with style attribute #{options[:style].inspect}" when Regexp " with style attribute matching #{options[:style].inspect}" when Hash " with styles #{options[:style].inspect}" else '' end %i[above below left_of right_of near].each do |spatial_filter| if options[spatial_filter] && show_for[:spatial] desc << " #{spatial_filter} #{options[spatial_filter] rescue '<ERROR>'}" # rubocop:disable Style/RescueModifier end end desc << selector.description(node_filters: show_for[:node], **options) desc << ' that also matches the custom filter block' if @filter_block && show_for[:node] desc << " within #{@resolved_node.inspect}" if describe_within? if locator.is_a?(String) && locator.start_with?('#', './/', '//') && !selector.raw_locator? desc << "\nNote: It appears you may be passing a CSS selector or XPath expression rather than a locator. " \ "Please see the documentation for acceptable locator values.\n\n" end desc end def applied_description description(true) end def matches_filters?(node, node_filter_errors = []) return true if (@resolved_node&.== node) && options[:allow_self] matches_locator_filter?(node) && matches_system_filters?(node) && matches_spatial_filters?(node) && matches_node_filters?(node, node_filter_errors) && matches_filter_block?(node) rescue *(node.respond_to?(:session) ? node.session.driver.invalid_element_errors : []) false end def visible case (vis = options.fetch(:visible) { default_visibility }) when true then :visible when false then :all else vis end end def exact? supports_exact? ? options.fetch(:exact, session_options.exact) : false end def match options.fetch(:match, session_options.match) end def xpath(exact = nil) exact = exact? if exact.nil? expr = apply_expression_filters(@expression) expr = exact ? expr.to_xpath(:exact) : expr.to_s if expr.respond_to?(:to_xpath) expr = filtered_expression(expr) expr = "(#{expr})[#{xpath_text_conditions}]" if try_text_match_in_expression? expr end def css filtered_expression(apply_expression_filters(@expression)) end # @api private def resolve_for(node, exact = nil) applied_filters.clear @filter_cache.clear @resolved_node = node @resolved_count += 1 node.synchronize do children = find_nodes_by_selector_format(node, exact).map(&method(:to_element)) Capybara::Result.new(ordered_results(children), self) end end # @api private def supports_exact? return @expression.respond_to? :to_xpath if @selector.supports_exact?.nil? @selector.supports_exact? end def failure_message "expected to find #{applied_description}" << count_message end def negative_failure_message "expected not to find #{applied_description}" << count_message end private def selector_format @selector.format end def matching_text options[:text] || options[:exact_text] end def text_fragments (text = matching_text).is_a?(String) ? text.split : [] end def xpath_text_conditions case (text = matching_text) when String text.split.map { |txt| XPath.contains(txt) }.reduce(&:&) when Regexp condition = XPath.current condition = condition.uppercase if text.casefold? Selector::RegexpDisassembler.new(text).alternated_substrings.map do |strs| strs.flat_map(&:split).map { |str| condition.contains(str) }.reduce(:&) end.reduce(:|) end end def try_text_match_in_expression? first_try? && matching_text && @resolved_node.is_a?(Capybara::Node::Base) && @resolved_node.session&.driver&.wait? end def first_try? @resolved_count == 1 end def show_for_stage(only_applied) lambda do |stage = :any| !only_applied || (stage == :any ? applied_filters.any? : applied_filters.include?(stage)) end end def applied_filters @applied_filters ||= [] end def find_selector(locator) case locator when Symbol then Selector[locator] else Selector.for(locator) end || Selector[session_options.default_selector] end def find_nodes_by_selector_format(node, exact) hints = {} hints[:uses_visibility] = true unless visible == :all hints[:texts] = text_fragments unless selector_format == :xpath hints[:styles] = options[:style] if use_default_style_filter? hints[:position] = true if use_spatial_filter? case selector_format when :css if node.method(:find_css).arity == 1 node.find_css(css) else node.find_css(css, **hints) end when :xpath if node.method(:find_xpath).arity == 1 node.find_xpath(xpath(exact)) else node.find_xpath(xpath(exact), **hints) end else raise ArgumentError, "Unknown format: #{selector_format}" end end def to_element(node) if @resolved_node.is_a?(Capybara::Node::Base) Capybara::Node::Element.new(@resolved_node.session, node, @resolved_node, self) else Capybara::Node::Simple.new(node) end end def valid_keys (VALID_KEYS + custom_keys).uniq end def matches_node_filters?(node, errors) applied_filters << :node unapplied_options = options.keys - valid_keys @selector.with_filter_errors(errors) do node_filters.all? do |filter_name, filter| next true unless apply_filter?(filter) if filter.matcher? unapplied_options.select { |option_name| filter.handles_option?(option_name) }.all? do |option_name| unapplied_options.delete(option_name) filter.matches?(node, option_name, options[option_name], @selector) end elsif options.key?(filter_name) unapplied_options.delete(filter_name) filter.matches?(node, filter_name, options[filter_name], @selector) elsif filter.default? filter.matches?(node, filter_name, filter.default, @selector) else true end end end end def matches_filter_block?(node) return true unless @filter_block if node.respond_to?(:session) node.session.using_wait_time(0) { @filter_block.call(node) } else @filter_block.call(node) end end def filter_set(name) ::Capybara::Selector::FilterSet[name] end def node_filters if options.key?(:filter_set) filter_set(options[:filter_set]) else @selector end.node_filters end def expression_filters filters = @selector.expression_filters filters.merge filter_set(options[:filter_set]).expression_filters if options.key?(:filter_set) filters end def ordered_results(results) case @order when :reverse results.reverse else results end end def custom_keys @custom_keys ||= node_filters.keys + expression_filters.keys end def assert_valid_keys unless VALID_MATCH.include?(match) raise ArgumentError, "Invalid option #{match.inspect} for :match, should be one of #{VALID_MATCH.map(&:inspect).join(', ')}" end unhandled_options = @options.keys.reject do |option_name| valid_keys.include?(option_name) || expression_filters.any? { |_name, ef| ef.handles_option? option_name } || node_filters.any? { |_name, nf| nf.handles_option? option_name } end return if unhandled_options.empty? invalid_names = unhandled_options.map(&:inspect).join(', ') valid_names = (valid_keys - [:allow_self]).map(&:inspect).join(', ') raise ArgumentError, "Invalid option(s) #{invalid_names}, should be one of #{valid_names}" end def filtered_expression(expr) conditions = {} conditions[:id] = options[:id] if use_default_id_filter? conditions[:class] = options[:class] if use_default_class_filter? conditions[:style] = options[:style] if use_default_style_filter? && !options[:style].is_a?(Hash) builder(expr).add_attribute_conditions(**conditions) end def use_default_id_filter? options.key?(:id) && !custom_keys.include?(:id) end def use_default_class_filter? options.key?(:class) && !custom_keys.include?(:class) end def use_default_style_filter? options.key?(:style) && !custom_keys.include?(:style) end def use_default_focused_filter? options.key?(:focused) && !custom_keys.include?(:focused) end def use_spatial_filter? options.values_at(*SPATIAL_KEYS).compact.any? end def apply_expression_filters(expression) unapplied_options = options.keys - valid_keys expression_filters.inject(expression) do |expr, (name, ef)| next expr unless apply_filter?(ef) if ef.matcher? unapplied_options.select(&ef.method(:handles_option?)).inject(expr) do |memo, option_name| unapplied_options.delete(option_name) ef.apply_filter(memo, option_name, options[option_name], @selector) end elsif options.key?(name) unapplied_options.delete(name) ef.apply_filter(expr, name, options[name], @selector) elsif ef.default? ef.apply_filter(expr, name, ef.default, @selector) else expr end end end def warn_exact_usage return unless options.key?(:exact) && !supports_exact? warn "The :exact option only has an effect on queries using the XPath#is method. Using it with the query \"#{expression}\" has no effect." end def exact_text options.fetch(:exact_text, session_options.exact_text) end def describe_within? @resolved_node && !document?(@resolved_node) && !simple_root?(@resolved_node) end def document?(node) node.is_a?(::Capybara::Node::Document) end def simple_root?(node) node.is_a?(::Capybara::Node::Simple) && node.path == '/' end def apply_filter?(filter) filter.format.nil? || (filter.format == selector_format) end def matches_locator_filter?(node) return true unless @selector.locator_filter && apply_filter?(@selector.locator_filter) @selector.locator_filter.matches?(node, @locator, @selector, exact: exact?) end def matches_system_filters?(node) applied_filters << :system matches_visibility_filters?(node) && matches_id_filter?(node) && matches_class_filter?(node) && matches_style_filter?(node) && matches_focused_filter?(node) && matches_text_filter?(node) && matches_exact_text_filter?(node) end def matches_spatial_filters?(node) applied_filters << :spatial return true unless use_spatial_filter? node_rect = Rectangle.new(node.initial_cache[:position] || node.rect) if options[:above] el_rect = rect_cache(options[:above]) return false unless node_rect.above? el_rect end if options[:below] el_rect = rect_cache(options[:below]) return false unless node_rect.below? el_rect end if options[:left_of] el_rect = rect_cache(options[:left_of]) return false unless node_rect.left_of? el_rect end if options[:right_of] el_rect = rect_cache(options[:right_of]) return false unless node_rect.right_of? el_rect end if options[:near] return false if node == options[:near] el_rect = rect_cache(options[:near]) return false unless node_rect.near? el_rect end true end def matches_id_filter?(node) return true unless use_default_id_filter? && options[:id].is_a?(Regexp) options[:id].match? node[:id] end def matches_class_filter?(node) return true unless use_default_class_filter? && need_to_process_classes? if options[:class].is_a? Regexp options[:class].match? node[:class] else classes = (node[:class] || '').split options[:class].select { |c| c.is_a? Regexp }.all? do |r| classes.any? { |cls| r.match? cls } end end end def matches_focused_filter?(node) return true unless use_default_focused_filter? (node == node.session.active_element) == options[:focused] end def need_to_process_classes? case options[:class] when Regexp then true when Array then options[:class].any?(Regexp) else false end end def matches_style_filter?(node) case options[:style] when String, nil true when Regexp options[:style].match? node[:style] when Hash matches_style?(node, options[:style]) end end def matches_style?(node, styles) @actual_styles = node.initial_cache[:style] || node.style(*styles.keys) styles.all? do |style, value| if value.is_a? Regexp value.match? @actual_styles[style.to_s] else @actual_styles[style.to_s] == value end end end def matches_text_filter?(node) value = options[:text] return true unless value return matches_text_exactly?(node, value) if exact_text == true && !value.is_a?(Regexp) regexp = value.is_a?(Regexp) ? value : Regexp.escape(value.to_s) matches_text_regexp?(node, regexp) end def matches_exact_text_filter?(node) case exact_text when String, Regexp matches_text_exactly?(node, exact_text) else true end end def matches_visibility_filters?(node) obscured = options[:obscured] return (visible != :hidden) && (node.initial_cache[:visible] != false) && !node.obscured? if obscured == false vis = case visible when :visible node.initial_cache[:visible] || (node.initial_cache[:visible].nil? && node.visible?) when :hidden # TODO: check why the 'visbile' cache spelling mistake wasn't caught in a test # (node.initial_cache[:visible] == false) || (node.initial_cache[:visbile].nil? && !node.visible?) (node.initial_cache[:visible] == false) || (node.initial_cache[:visible].nil? && !node.visible?) else true end vis && case obscured when true node.obscured? when false !node.obscured? else true end end def matches_text_exactly?(node, value) regexp = value.is_a?(Regexp) ? value : /\A#{Regexp.escape(value.to_s)}\z/ matches_text_regexp(node, regexp).then { |m| m&.pre_match == '' && m&.post_match == '' } end def normalize_ws options.fetch(:normalize_ws, session_options.default_normalize_ws) end def matches_text_regexp(node, regexp) text_visible = visible text_visible = :all if text_visible == :hidden node.text(text_visible, normalize_ws: normalize_ws).match(regexp) end def matches_text_regexp?(node, regexp) !matches_text_regexp(node, regexp).nil? end def default_visibility @selector.default_visibility(session_options.ignore_hidden_elements, options) end def builder(expr) selector.builder(expr) end def position_cache(key) @filter_cache[key][:position] ||= key.rect end def rect_cache(key) @filter_cache[key][:rect] ||= Rectangle.new(position_cache(key)) end class Rectangle attr_reader :top, :bottom, :left, :right def initialize(position) # rubocop:disable Style/RescueModifier @top = position['top'] rescue position['y'] @bottom = position['bottom'] rescue (@top + position['height']) @left = position['left'] rescue position['x'] @right = position['right'] rescue (@left + position['width']) # rubocop:enable Style/RescueModifier end def distance(other) distance = Float::INFINITY line_segments.each do |ls1| other.line_segments.each do |ls2| distance = [ distance, distance_segment_segment(*ls1, *ls2) ].min end end distance end def above?(other) bottom <= other.top end def below?(other) top >= other.bottom end def left_of?(other) right <= other.left end def right_of?(other) left >= other.right end def near?(other) distance(other) <= 50 end protected def line_segments [ [Vector[top, left], Vector[top, right]], [Vector[top, right], Vector[bottom, left]], [Vector[bottom, left], Vector[bottom, right]], [Vector[bottom, right], Vector[top, left]] ] end private def distance_segment_segment(l1p1, l1p2, l2p1, l2p2) # See http://geomalgorithms.com/a07-_distance.html # rubocop:disable Naming/VariableName u = l1p2 - l1p1 v = l2p2 - l2p1 w = l1p1 - l2p1 a = u.dot u b = u.dot v c = v.dot v d = u.dot w e = v.dot w cap_d = (a * c) - (b**2) sD = tD = cap_d # compute the line parameters of the two closest points if cap_d < Float::EPSILON # the lines are almost parallel sN = 0.0 # force using point P0 on segment S1 sD = 1.0 # to prevent possible division by 0.0 later tN = e tD = c else # get the closest points on the infinite lines sN = (b * e) - (c * d) tN = (a * e) - (b * d) if sN.negative? # sc < 0 => the s=0 edge is visible sN = 0 tN = e tD = c elsif sN > sD # sc > 1 => the s=1 edge is visible sN = sD tN = e + b tD = c end end if tN.negative? # tc < 0 => the t=0 edge is visible tN = 0 # recompute sc for this edge if (-d).negative? sN = 0.0 elsif -d > a sN = sD else sN = -d sD = a end elsif tN > tD # tc > 1 => the t=1 edge is visible tN = tD # recompute sc for this edge if (-d + b).negative? sN = 0.0 elsif (-d + b) > a sN = sD else sN = (-d + b) sD = a end end # finally do the division to get sc and tc sc = sN.abs < Float::EPSILON ? 0.0 : sN / sD tc = tN.abs < Float::EPSILON ? 0.0 : tN / tD # difference of the two closest points dP = w + (u * sc) - (v * tc) Math.sqrt(dP.dot(dP)) # rubocop:enable Naming/VariableName end end private_constant :Rectangle end end end
Ruby
{ "end_line": 454, "name": "matches_system_filters?", "signature": "def matches_system_filters?(node)", "start_line": 444 }
{ "class_name": "SelectorQuery", "class_signature": "class SelectorQuery < < Queries::BaseQuery", "module": "Capybara" }
matches_spatial_filters?
capybara/lib/capybara/queries/selector_query.rb
def matches_spatial_filters?(node) applied_filters << :spatial return true unless use_spatial_filter? node_rect = Rectangle.new(node.initial_cache[:position] || node.rect) if options[:above] el_rect = rect_cache(options[:above]) return false unless node_rect.above? el_rect end if options[:below] el_rect = rect_cache(options[:below]) return false unless node_rect.below? el_rect end if options[:left_of] el_rect = rect_cache(options[:left_of]) return false unless node_rect.left_of? el_rect end if options[:right_of] el_rect = rect_cache(options[:right_of]) return false unless node_rect.right_of? el_rect end if options[:near] return false if node == options[:near] el_rect = rect_cache(options[:near]) return false unless node_rect.near? el_rect end true end
# frozen_string_literal: true require 'matrix' module Capybara module Queries class SelectorQuery < Queries::BaseQuery attr_reader :expression, :selector, :locator, :options SPATIAL_KEYS = %i[above below left_of right_of near].freeze VALID_KEYS = SPATIAL_KEYS + COUNT_KEYS + %i[text id class style visible obscured exact exact_text normalize_ws match wait filter_set focused] VALID_MATCH = %i[first smart prefer_exact one].freeze def initialize(*args, session_options:, enable_aria_label: session_options.enable_aria_label, enable_aria_role: session_options.enable_aria_role, test_id: session_options.test_id, selector_format: nil, order: nil, **options, &filter_block) @resolved_node = nil @resolved_count = 0 @options = options.dup @order = order @filter_cache = Hash.new { |hsh, key| hsh[key] = {} } if @options[:text].is_a?(Regexp) && [true, false].include?(@options[:exact_text]) Capybara::Helpers.warn( "Boolean 'exact_text' option is not supported when 'text' option is a Regexp - ignoring" ) end super(@options) self.session_options = session_options @selector = Selector.new( find_selector(args[0].is_a?(Symbol) ? args.shift : args[0]), config: { enable_aria_label: enable_aria_label, enable_aria_role: enable_aria_role, test_id: test_id }, format: selector_format ) @locator = args.shift @filter_block = filter_block raise ArgumentError, "Unused parameters passed to #{self.class.name} : #{args}" unless args.empty? @expression = selector.call(@locator, **@options) warn_exact_usage assert_valid_keys end def name; selector.name; end def label; selector.label || selector.name; end def description(only_applied = false) # rubocop:disable Style/OptionalBooleanParameter desc = +'' show_for = show_for_stage(only_applied) if show_for[:any] desc << 'visible ' if visible == :visible desc << 'non-visible ' if visible == :hidden end desc << label.to_s desc << " #{locator.inspect}" unless locator.nil? if show_for[:any] desc << " with#{' exact' if exact_text == true} text #{options[:text].inspect}" if options[:text] desc << " with exact text #{exact_text}" if exact_text.is_a?(String) end desc << " with id #{options[:id]}" if options[:id] desc << " with classes [#{Array(options[:class]).join(',')}]" if options[:class] desc << ' that is focused' if options[:focused] desc << ' that is not focused' if options[:focused] == false desc << case options[:style] when String " with style attribute #{options[:style].inspect}" when Regexp " with style attribute matching #{options[:style].inspect}" when Hash " with styles #{options[:style].inspect}" else '' end %i[above below left_of right_of near].each do |spatial_filter| if options[spatial_filter] && show_for[:spatial] desc << " #{spatial_filter} #{options[spatial_filter] rescue '<ERROR>'}" # rubocop:disable Style/RescueModifier end end desc << selector.description(node_filters: show_for[:node], **options) desc << ' that also matches the custom filter block' if @filter_block && show_for[:node] desc << " within #{@resolved_node.inspect}" if describe_within? if locator.is_a?(String) && locator.start_with?('#', './/', '//') && !selector.raw_locator? desc << "\nNote: It appears you may be passing a CSS selector or XPath expression rather than a locator. " \ "Please see the documentation for acceptable locator values.\n\n" end desc end def applied_description description(true) end def matches_filters?(node, node_filter_errors = []) return true if (@resolved_node&.== node) && options[:allow_self] matches_locator_filter?(node) && matches_system_filters?(node) && matches_spatial_filters?(node) && matches_node_filters?(node, node_filter_errors) && matches_filter_block?(node) rescue *(node.respond_to?(:session) ? node.session.driver.invalid_element_errors : []) false end def visible case (vis = options.fetch(:visible) { default_visibility }) when true then :visible when false then :all else vis end end def exact? supports_exact? ? options.fetch(:exact, session_options.exact) : false end def match options.fetch(:match, session_options.match) end def xpath(exact = nil) exact = exact? if exact.nil? expr = apply_expression_filters(@expression) expr = exact ? expr.to_xpath(:exact) : expr.to_s if expr.respond_to?(:to_xpath) expr = filtered_expression(expr) expr = "(#{expr})[#{xpath_text_conditions}]" if try_text_match_in_expression? expr end def css filtered_expression(apply_expression_filters(@expression)) end # @api private def resolve_for(node, exact = nil) applied_filters.clear @filter_cache.clear @resolved_node = node @resolved_count += 1 node.synchronize do children = find_nodes_by_selector_format(node, exact).map(&method(:to_element)) Capybara::Result.new(ordered_results(children), self) end end # @api private def supports_exact? return @expression.respond_to? :to_xpath if @selector.supports_exact?.nil? @selector.supports_exact? end def failure_message "expected to find #{applied_description}" << count_message end def negative_failure_message "expected not to find #{applied_description}" << count_message end private def selector_format @selector.format end def matching_text options[:text] || options[:exact_text] end def text_fragments (text = matching_text).is_a?(String) ? text.split : [] end def xpath_text_conditions case (text = matching_text) when String text.split.map { |txt| XPath.contains(txt) }.reduce(&:&) when Regexp condition = XPath.current condition = condition.uppercase if text.casefold? Selector::RegexpDisassembler.new(text).alternated_substrings.map do |strs| strs.flat_map(&:split).map { |str| condition.contains(str) }.reduce(:&) end.reduce(:|) end end def try_text_match_in_expression? first_try? && matching_text && @resolved_node.is_a?(Capybara::Node::Base) && @resolved_node.session&.driver&.wait? end def first_try? @resolved_count == 1 end def show_for_stage(only_applied) lambda do |stage = :any| !only_applied || (stage == :any ? applied_filters.any? : applied_filters.include?(stage)) end end def applied_filters @applied_filters ||= [] end def find_selector(locator) case locator when Symbol then Selector[locator] else Selector.for(locator) end || Selector[session_options.default_selector] end def find_nodes_by_selector_format(node, exact) hints = {} hints[:uses_visibility] = true unless visible == :all hints[:texts] = text_fragments unless selector_format == :xpath hints[:styles] = options[:style] if use_default_style_filter? hints[:position] = true if use_spatial_filter? case selector_format when :css if node.method(:find_css).arity == 1 node.find_css(css) else node.find_css(css, **hints) end when :xpath if node.method(:find_xpath).arity == 1 node.find_xpath(xpath(exact)) else node.find_xpath(xpath(exact), **hints) end else raise ArgumentError, "Unknown format: #{selector_format}" end end def to_element(node) if @resolved_node.is_a?(Capybara::Node::Base) Capybara::Node::Element.new(@resolved_node.session, node, @resolved_node, self) else Capybara::Node::Simple.new(node) end end def valid_keys (VALID_KEYS + custom_keys).uniq end def matches_node_filters?(node, errors) applied_filters << :node unapplied_options = options.keys - valid_keys @selector.with_filter_errors(errors) do node_filters.all? do |filter_name, filter| next true unless apply_filter?(filter) if filter.matcher? unapplied_options.select { |option_name| filter.handles_option?(option_name) }.all? do |option_name| unapplied_options.delete(option_name) filter.matches?(node, option_name, options[option_name], @selector) end elsif options.key?(filter_name) unapplied_options.delete(filter_name) filter.matches?(node, filter_name, options[filter_name], @selector) elsif filter.default? filter.matches?(node, filter_name, filter.default, @selector) else true end end end end def matches_filter_block?(node) return true unless @filter_block if node.respond_to?(:session) node.session.using_wait_time(0) { @filter_block.call(node) } else @filter_block.call(node) end end def filter_set(name) ::Capybara::Selector::FilterSet[name] end def node_filters if options.key?(:filter_set) filter_set(options[:filter_set]) else @selector end.node_filters end def expression_filters filters = @selector.expression_filters filters.merge filter_set(options[:filter_set]).expression_filters if options.key?(:filter_set) filters end def ordered_results(results) case @order when :reverse results.reverse else results end end def custom_keys @custom_keys ||= node_filters.keys + expression_filters.keys end def assert_valid_keys unless VALID_MATCH.include?(match) raise ArgumentError, "Invalid option #{match.inspect} for :match, should be one of #{VALID_MATCH.map(&:inspect).join(', ')}" end unhandled_options = @options.keys.reject do |option_name| valid_keys.include?(option_name) || expression_filters.any? { |_name, ef| ef.handles_option? option_name } || node_filters.any? { |_name, nf| nf.handles_option? option_name } end return if unhandled_options.empty? invalid_names = unhandled_options.map(&:inspect).join(', ') valid_names = (valid_keys - [:allow_self]).map(&:inspect).join(', ') raise ArgumentError, "Invalid option(s) #{invalid_names}, should be one of #{valid_names}" end def filtered_expression(expr) conditions = {} conditions[:id] = options[:id] if use_default_id_filter? conditions[:class] = options[:class] if use_default_class_filter? conditions[:style] = options[:style] if use_default_style_filter? && !options[:style].is_a?(Hash) builder(expr).add_attribute_conditions(**conditions) end def use_default_id_filter? options.key?(:id) && !custom_keys.include?(:id) end def use_default_class_filter? options.key?(:class) && !custom_keys.include?(:class) end def use_default_style_filter? options.key?(:style) && !custom_keys.include?(:style) end def use_default_focused_filter? options.key?(:focused) && !custom_keys.include?(:focused) end def use_spatial_filter? options.values_at(*SPATIAL_KEYS).compact.any? end def apply_expression_filters(expression) unapplied_options = options.keys - valid_keys expression_filters.inject(expression) do |expr, (name, ef)| next expr unless apply_filter?(ef) if ef.matcher? unapplied_options.select(&ef.method(:handles_option?)).inject(expr) do |memo, option_name| unapplied_options.delete(option_name) ef.apply_filter(memo, option_name, options[option_name], @selector) end elsif options.key?(name) unapplied_options.delete(name) ef.apply_filter(expr, name, options[name], @selector) elsif ef.default? ef.apply_filter(expr, name, ef.default, @selector) else expr end end end def warn_exact_usage return unless options.key?(:exact) && !supports_exact? warn "The :exact option only has an effect on queries using the XPath#is method. Using it with the query \"#{expression}\" has no effect." end def exact_text options.fetch(:exact_text, session_options.exact_text) end def describe_within? @resolved_node && !document?(@resolved_node) && !simple_root?(@resolved_node) end def document?(node) node.is_a?(::Capybara::Node::Document) end def simple_root?(node) node.is_a?(::Capybara::Node::Simple) && node.path == '/' end def apply_filter?(filter) filter.format.nil? || (filter.format == selector_format) end def matches_locator_filter?(node) return true unless @selector.locator_filter && apply_filter?(@selector.locator_filter) @selector.locator_filter.matches?(node, @locator, @selector, exact: exact?) end def matches_system_filters?(node) applied_filters << :system matches_visibility_filters?(node) && matches_id_filter?(node) && matches_class_filter?(node) && matches_style_filter?(node) && matches_focused_filter?(node) && matches_text_filter?(node) && matches_exact_text_filter?(node) end def matches_spatial_filters?(node) applied_filters << :spatial return true unless use_spatial_filter? node_rect = Rectangle.new(node.initial_cache[:position] || node.rect) if options[:above] el_rect = rect_cache(options[:above]) return false unless node_rect.above? el_rect end if options[:below] el_rect = rect_cache(options[:below]) return false unless node_rect.below? el_rect end if options[:left_of] el_rect = rect_cache(options[:left_of]) return false unless node_rect.left_of? el_rect end if options[:right_of] el_rect = rect_cache(options[:right_of]) return false unless node_rect.right_of? el_rect end if options[:near] return false if node == options[:near] el_rect = rect_cache(options[:near]) return false unless node_rect.near? el_rect end true end def matches_id_filter?(node) return true unless use_default_id_filter? && options[:id].is_a?(Regexp) options[:id].match? node[:id] end def matches_class_filter?(node) return true unless use_default_class_filter? && need_to_process_classes? if options[:class].is_a? Regexp options[:class].match? node[:class] else classes = (node[:class] || '').split options[:class].select { |c| c.is_a? Regexp }.all? do |r| classes.any? { |cls| r.match? cls } end end end def matches_focused_filter?(node) return true unless use_default_focused_filter? (node == node.session.active_element) == options[:focused] end def need_to_process_classes? case options[:class] when Regexp then true when Array then options[:class].any?(Regexp) else false end end def matches_style_filter?(node) case options[:style] when String, nil true when Regexp options[:style].match? node[:style] when Hash matches_style?(node, options[:style]) end end def matches_style?(node, styles) @actual_styles = node.initial_cache[:style] || node.style(*styles.keys) styles.all? do |style, value| if value.is_a? Regexp value.match? @actual_styles[style.to_s] else @actual_styles[style.to_s] == value end end end def matches_text_filter?(node) value = options[:text] return true unless value return matches_text_exactly?(node, value) if exact_text == true && !value.is_a?(Regexp) regexp = value.is_a?(Regexp) ? value : Regexp.escape(value.to_s) matches_text_regexp?(node, regexp) end def matches_exact_text_filter?(node) case exact_text when String, Regexp matches_text_exactly?(node, exact_text) else true end end def matches_visibility_filters?(node) obscured = options[:obscured] return (visible != :hidden) && (node.initial_cache[:visible] != false) && !node.obscured? if obscured == false vis = case visible when :visible node.initial_cache[:visible] || (node.initial_cache[:visible].nil? && node.visible?) when :hidden # TODO: check why the 'visbile' cache spelling mistake wasn't caught in a test # (node.initial_cache[:visible] == false) || (node.initial_cache[:visbile].nil? && !node.visible?) (node.initial_cache[:visible] == false) || (node.initial_cache[:visible].nil? && !node.visible?) else true end vis && case obscured when true node.obscured? when false !node.obscured? else true end end def matches_text_exactly?(node, value) regexp = value.is_a?(Regexp) ? value : /\A#{Regexp.escape(value.to_s)}\z/ matches_text_regexp(node, regexp).then { |m| m&.pre_match == '' && m&.post_match == '' } end def normalize_ws options.fetch(:normalize_ws, session_options.default_normalize_ws) end def matches_text_regexp(node, regexp) text_visible = visible text_visible = :all if text_visible == :hidden node.text(text_visible, normalize_ws: normalize_ws).match(regexp) end def matches_text_regexp?(node, regexp) !matches_text_regexp(node, regexp).nil? end def default_visibility @selector.default_visibility(session_options.ignore_hidden_elements, options) end def builder(expr) selector.builder(expr) end def position_cache(key) @filter_cache[key][:position] ||= key.rect end def rect_cache(key) @filter_cache[key][:rect] ||= Rectangle.new(position_cache(key)) end class Rectangle attr_reader :top, :bottom, :left, :right def initialize(position) # rubocop:disable Style/RescueModifier @top = position['top'] rescue position['y'] @bottom = position['bottom'] rescue (@top + position['height']) @left = position['left'] rescue position['x'] @right = position['right'] rescue (@left + position['width']) # rubocop:enable Style/RescueModifier end def distance(other) distance = Float::INFINITY line_segments.each do |ls1| other.line_segments.each do |ls2| distance = [ distance, distance_segment_segment(*ls1, *ls2) ].min end end distance end def above?(other) bottom <= other.top end def below?(other) top >= other.bottom end def left_of?(other) right <= other.left end def right_of?(other) left >= other.right end def near?(other) distance(other) <= 50 end protected def line_segments [ [Vector[top, left], Vector[top, right]], [Vector[top, right], Vector[bottom, left]], [Vector[bottom, left], Vector[bottom, right]], [Vector[bottom, right], Vector[top, left]] ] end private def distance_segment_segment(l1p1, l1p2, l2p1, l2p2) # See http://geomalgorithms.com/a07-_distance.html # rubocop:disable Naming/VariableName u = l1p2 - l1p1 v = l2p2 - l2p1 w = l1p1 - l2p1 a = u.dot u b = u.dot v c = v.dot v d = u.dot w e = v.dot w cap_d = (a * c) - (b**2) sD = tD = cap_d # compute the line parameters of the two closest points if cap_d < Float::EPSILON # the lines are almost parallel sN = 0.0 # force using point P0 on segment S1 sD = 1.0 # to prevent possible division by 0.0 later tN = e tD = c else # get the closest points on the infinite lines sN = (b * e) - (c * d) tN = (a * e) - (b * d) if sN.negative? # sc < 0 => the s=0 edge is visible sN = 0 tN = e tD = c elsif sN > sD # sc > 1 => the s=1 edge is visible sN = sD tN = e + b tD = c end end if tN.negative? # tc < 0 => the t=0 edge is visible tN = 0 # recompute sc for this edge if (-d).negative? sN = 0.0 elsif -d > a sN = sD else sN = -d sD = a end elsif tN > tD # tc > 1 => the t=1 edge is visible tN = tD # recompute sc for this edge if (-d + b).negative? sN = 0.0 elsif (-d + b) > a sN = sD else sN = (-d + b) sD = a end end # finally do the division to get sc and tc sc = sN.abs < Float::EPSILON ? 0.0 : sN / sD tc = tN.abs < Float::EPSILON ? 0.0 : tN / tD # difference of the two closest points dP = w + (u * sc) - (v * tc) Math.sqrt(dP.dot(dP)) # rubocop:enable Naming/VariableName end end private_constant :Rectangle end end end
Ruby
{ "end_line": 490, "name": "matches_spatial_filters?", "signature": "def matches_spatial_filters?(node)", "start_line": 456 }
{ "class_name": "SelectorQuery", "class_signature": "class SelectorQuery < < Queries::BaseQuery", "module": "Capybara" }
matches_class_filter?
capybara/lib/capybara/queries/selector_query.rb
def matches_class_filter?(node) return true unless use_default_class_filter? && need_to_process_classes? if options[:class].is_a? Regexp options[:class].match? node[:class] else classes = (node[:class] || '').split options[:class].select { |c| c.is_a? Regexp }.all? do |r| classes.any? { |cls| r.match? cls } end end end
# frozen_string_literal: true require 'matrix' module Capybara module Queries class SelectorQuery < Queries::BaseQuery attr_reader :expression, :selector, :locator, :options SPATIAL_KEYS = %i[above below left_of right_of near].freeze VALID_KEYS = SPATIAL_KEYS + COUNT_KEYS + %i[text id class style visible obscured exact exact_text normalize_ws match wait filter_set focused] VALID_MATCH = %i[first smart prefer_exact one].freeze def initialize(*args, session_options:, enable_aria_label: session_options.enable_aria_label, enable_aria_role: session_options.enable_aria_role, test_id: session_options.test_id, selector_format: nil, order: nil, **options, &filter_block) @resolved_node = nil @resolved_count = 0 @options = options.dup @order = order @filter_cache = Hash.new { |hsh, key| hsh[key] = {} } if @options[:text].is_a?(Regexp) && [true, false].include?(@options[:exact_text]) Capybara::Helpers.warn( "Boolean 'exact_text' option is not supported when 'text' option is a Regexp - ignoring" ) end super(@options) self.session_options = session_options @selector = Selector.new( find_selector(args[0].is_a?(Symbol) ? args.shift : args[0]), config: { enable_aria_label: enable_aria_label, enable_aria_role: enable_aria_role, test_id: test_id }, format: selector_format ) @locator = args.shift @filter_block = filter_block raise ArgumentError, "Unused parameters passed to #{self.class.name} : #{args}" unless args.empty? @expression = selector.call(@locator, **@options) warn_exact_usage assert_valid_keys end def name; selector.name; end def label; selector.label || selector.name; end def description(only_applied = false) # rubocop:disable Style/OptionalBooleanParameter desc = +'' show_for = show_for_stage(only_applied) if show_for[:any] desc << 'visible ' if visible == :visible desc << 'non-visible ' if visible == :hidden end desc << label.to_s desc << " #{locator.inspect}" unless locator.nil? if show_for[:any] desc << " with#{' exact' if exact_text == true} text #{options[:text].inspect}" if options[:text] desc << " with exact text #{exact_text}" if exact_text.is_a?(String) end desc << " with id #{options[:id]}" if options[:id] desc << " with classes [#{Array(options[:class]).join(',')}]" if options[:class] desc << ' that is focused' if options[:focused] desc << ' that is not focused' if options[:focused] == false desc << case options[:style] when String " with style attribute #{options[:style].inspect}" when Regexp " with style attribute matching #{options[:style].inspect}" when Hash " with styles #{options[:style].inspect}" else '' end %i[above below left_of right_of near].each do |spatial_filter| if options[spatial_filter] && show_for[:spatial] desc << " #{spatial_filter} #{options[spatial_filter] rescue '<ERROR>'}" # rubocop:disable Style/RescueModifier end end desc << selector.description(node_filters: show_for[:node], **options) desc << ' that also matches the custom filter block' if @filter_block && show_for[:node] desc << " within #{@resolved_node.inspect}" if describe_within? if locator.is_a?(String) && locator.start_with?('#', './/', '//') && !selector.raw_locator? desc << "\nNote: It appears you may be passing a CSS selector or XPath expression rather than a locator. " \ "Please see the documentation for acceptable locator values.\n\n" end desc end def applied_description description(true) end def matches_filters?(node, node_filter_errors = []) return true if (@resolved_node&.== node) && options[:allow_self] matches_locator_filter?(node) && matches_system_filters?(node) && matches_spatial_filters?(node) && matches_node_filters?(node, node_filter_errors) && matches_filter_block?(node) rescue *(node.respond_to?(:session) ? node.session.driver.invalid_element_errors : []) false end def visible case (vis = options.fetch(:visible) { default_visibility }) when true then :visible when false then :all else vis end end def exact? supports_exact? ? options.fetch(:exact, session_options.exact) : false end def match options.fetch(:match, session_options.match) end def xpath(exact = nil) exact = exact? if exact.nil? expr = apply_expression_filters(@expression) expr = exact ? expr.to_xpath(:exact) : expr.to_s if expr.respond_to?(:to_xpath) expr = filtered_expression(expr) expr = "(#{expr})[#{xpath_text_conditions}]" if try_text_match_in_expression? expr end def css filtered_expression(apply_expression_filters(@expression)) end # @api private def resolve_for(node, exact = nil) applied_filters.clear @filter_cache.clear @resolved_node = node @resolved_count += 1 node.synchronize do children = find_nodes_by_selector_format(node, exact).map(&method(:to_element)) Capybara::Result.new(ordered_results(children), self) end end # @api private def supports_exact? return @expression.respond_to? :to_xpath if @selector.supports_exact?.nil? @selector.supports_exact? end def failure_message "expected to find #{applied_description}" << count_message end def negative_failure_message "expected not to find #{applied_description}" << count_message end private def selector_format @selector.format end def matching_text options[:text] || options[:exact_text] end def text_fragments (text = matching_text).is_a?(String) ? text.split : [] end def xpath_text_conditions case (text = matching_text) when String text.split.map { |txt| XPath.contains(txt) }.reduce(&:&) when Regexp condition = XPath.current condition = condition.uppercase if text.casefold? Selector::RegexpDisassembler.new(text).alternated_substrings.map do |strs| strs.flat_map(&:split).map { |str| condition.contains(str) }.reduce(:&) end.reduce(:|) end end def try_text_match_in_expression? first_try? && matching_text && @resolved_node.is_a?(Capybara::Node::Base) && @resolved_node.session&.driver&.wait? end def first_try? @resolved_count == 1 end def show_for_stage(only_applied) lambda do |stage = :any| !only_applied || (stage == :any ? applied_filters.any? : applied_filters.include?(stage)) end end def applied_filters @applied_filters ||= [] end def find_selector(locator) case locator when Symbol then Selector[locator] else Selector.for(locator) end || Selector[session_options.default_selector] end def find_nodes_by_selector_format(node, exact) hints = {} hints[:uses_visibility] = true unless visible == :all hints[:texts] = text_fragments unless selector_format == :xpath hints[:styles] = options[:style] if use_default_style_filter? hints[:position] = true if use_spatial_filter? case selector_format when :css if node.method(:find_css).arity == 1 node.find_css(css) else node.find_css(css, **hints) end when :xpath if node.method(:find_xpath).arity == 1 node.find_xpath(xpath(exact)) else node.find_xpath(xpath(exact), **hints) end else raise ArgumentError, "Unknown format: #{selector_format}" end end def to_element(node) if @resolved_node.is_a?(Capybara::Node::Base) Capybara::Node::Element.new(@resolved_node.session, node, @resolved_node, self) else Capybara::Node::Simple.new(node) end end def valid_keys (VALID_KEYS + custom_keys).uniq end def matches_node_filters?(node, errors) applied_filters << :node unapplied_options = options.keys - valid_keys @selector.with_filter_errors(errors) do node_filters.all? do |filter_name, filter| next true unless apply_filter?(filter) if filter.matcher? unapplied_options.select { |option_name| filter.handles_option?(option_name) }.all? do |option_name| unapplied_options.delete(option_name) filter.matches?(node, option_name, options[option_name], @selector) end elsif options.key?(filter_name) unapplied_options.delete(filter_name) filter.matches?(node, filter_name, options[filter_name], @selector) elsif filter.default? filter.matches?(node, filter_name, filter.default, @selector) else true end end end end def matches_filter_block?(node) return true unless @filter_block if node.respond_to?(:session) node.session.using_wait_time(0) { @filter_block.call(node) } else @filter_block.call(node) end end def filter_set(name) ::Capybara::Selector::FilterSet[name] end def node_filters if options.key?(:filter_set) filter_set(options[:filter_set]) else @selector end.node_filters end def expression_filters filters = @selector.expression_filters filters.merge filter_set(options[:filter_set]).expression_filters if options.key?(:filter_set) filters end def ordered_results(results) case @order when :reverse results.reverse else results end end def custom_keys @custom_keys ||= node_filters.keys + expression_filters.keys end def assert_valid_keys unless VALID_MATCH.include?(match) raise ArgumentError, "Invalid option #{match.inspect} for :match, should be one of #{VALID_MATCH.map(&:inspect).join(', ')}" end unhandled_options = @options.keys.reject do |option_name| valid_keys.include?(option_name) || expression_filters.any? { |_name, ef| ef.handles_option? option_name } || node_filters.any? { |_name, nf| nf.handles_option? option_name } end return if unhandled_options.empty? invalid_names = unhandled_options.map(&:inspect).join(', ') valid_names = (valid_keys - [:allow_self]).map(&:inspect).join(', ') raise ArgumentError, "Invalid option(s) #{invalid_names}, should be one of #{valid_names}" end def filtered_expression(expr) conditions = {} conditions[:id] = options[:id] if use_default_id_filter? conditions[:class] = options[:class] if use_default_class_filter? conditions[:style] = options[:style] if use_default_style_filter? && !options[:style].is_a?(Hash) builder(expr).add_attribute_conditions(**conditions) end def use_default_id_filter? options.key?(:id) && !custom_keys.include?(:id) end def use_default_class_filter? options.key?(:class) && !custom_keys.include?(:class) end def use_default_style_filter? options.key?(:style) && !custom_keys.include?(:style) end def use_default_focused_filter? options.key?(:focused) && !custom_keys.include?(:focused) end def use_spatial_filter? options.values_at(*SPATIAL_KEYS).compact.any? end def apply_expression_filters(expression) unapplied_options = options.keys - valid_keys expression_filters.inject(expression) do |expr, (name, ef)| next expr unless apply_filter?(ef) if ef.matcher? unapplied_options.select(&ef.method(:handles_option?)).inject(expr) do |memo, option_name| unapplied_options.delete(option_name) ef.apply_filter(memo, option_name, options[option_name], @selector) end elsif options.key?(name) unapplied_options.delete(name) ef.apply_filter(expr, name, options[name], @selector) elsif ef.default? ef.apply_filter(expr, name, ef.default, @selector) else expr end end end def warn_exact_usage return unless options.key?(:exact) && !supports_exact? warn "The :exact option only has an effect on queries using the XPath#is method. Using it with the query \"#{expression}\" has no effect." end def exact_text options.fetch(:exact_text, session_options.exact_text) end def describe_within? @resolved_node && !document?(@resolved_node) && !simple_root?(@resolved_node) end def document?(node) node.is_a?(::Capybara::Node::Document) end def simple_root?(node) node.is_a?(::Capybara::Node::Simple) && node.path == '/' end def apply_filter?(filter) filter.format.nil? || (filter.format == selector_format) end def matches_locator_filter?(node) return true unless @selector.locator_filter && apply_filter?(@selector.locator_filter) @selector.locator_filter.matches?(node, @locator, @selector, exact: exact?) end def matches_system_filters?(node) applied_filters << :system matches_visibility_filters?(node) && matches_id_filter?(node) && matches_class_filter?(node) && matches_style_filter?(node) && matches_focused_filter?(node) && matches_text_filter?(node) && matches_exact_text_filter?(node) end def matches_spatial_filters?(node) applied_filters << :spatial return true unless use_spatial_filter? node_rect = Rectangle.new(node.initial_cache[:position] || node.rect) if options[:above] el_rect = rect_cache(options[:above]) return false unless node_rect.above? el_rect end if options[:below] el_rect = rect_cache(options[:below]) return false unless node_rect.below? el_rect end if options[:left_of] el_rect = rect_cache(options[:left_of]) return false unless node_rect.left_of? el_rect end if options[:right_of] el_rect = rect_cache(options[:right_of]) return false unless node_rect.right_of? el_rect end if options[:near] return false if node == options[:near] el_rect = rect_cache(options[:near]) return false unless node_rect.near? el_rect end true end def matches_id_filter?(node) return true unless use_default_id_filter? && options[:id].is_a?(Regexp) options[:id].match? node[:id] end def matches_class_filter?(node) return true unless use_default_class_filter? && need_to_process_classes? if options[:class].is_a? Regexp options[:class].match? node[:class] else classes = (node[:class] || '').split options[:class].select { |c| c.is_a? Regexp }.all? do |r| classes.any? { |cls| r.match? cls } end end end def matches_focused_filter?(node) return true unless use_default_focused_filter? (node == node.session.active_element) == options[:focused] end def need_to_process_classes? case options[:class] when Regexp then true when Array then options[:class].any?(Regexp) else false end end def matches_style_filter?(node) case options[:style] when String, nil true when Regexp options[:style].match? node[:style] when Hash matches_style?(node, options[:style]) end end def matches_style?(node, styles) @actual_styles = node.initial_cache[:style] || node.style(*styles.keys) styles.all? do |style, value| if value.is_a? Regexp value.match? @actual_styles[style.to_s] else @actual_styles[style.to_s] == value end end end def matches_text_filter?(node) value = options[:text] return true unless value return matches_text_exactly?(node, value) if exact_text == true && !value.is_a?(Regexp) regexp = value.is_a?(Regexp) ? value : Regexp.escape(value.to_s) matches_text_regexp?(node, regexp) end def matches_exact_text_filter?(node) case exact_text when String, Regexp matches_text_exactly?(node, exact_text) else true end end def matches_visibility_filters?(node) obscured = options[:obscured] return (visible != :hidden) && (node.initial_cache[:visible] != false) && !node.obscured? if obscured == false vis = case visible when :visible node.initial_cache[:visible] || (node.initial_cache[:visible].nil? && node.visible?) when :hidden # TODO: check why the 'visbile' cache spelling mistake wasn't caught in a test # (node.initial_cache[:visible] == false) || (node.initial_cache[:visbile].nil? && !node.visible?) (node.initial_cache[:visible] == false) || (node.initial_cache[:visible].nil? && !node.visible?) else true end vis && case obscured when true node.obscured? when false !node.obscured? else true end end def matches_text_exactly?(node, value) regexp = value.is_a?(Regexp) ? value : /\A#{Regexp.escape(value.to_s)}\z/ matches_text_regexp(node, regexp).then { |m| m&.pre_match == '' && m&.post_match == '' } end def normalize_ws options.fetch(:normalize_ws, session_options.default_normalize_ws) end def matches_text_regexp(node, regexp) text_visible = visible text_visible = :all if text_visible == :hidden node.text(text_visible, normalize_ws: normalize_ws).match(regexp) end def matches_text_regexp?(node, regexp) !matches_text_regexp(node, regexp).nil? end def default_visibility @selector.default_visibility(session_options.ignore_hidden_elements, options) end def builder(expr) selector.builder(expr) end def position_cache(key) @filter_cache[key][:position] ||= key.rect end def rect_cache(key) @filter_cache[key][:rect] ||= Rectangle.new(position_cache(key)) end class Rectangle attr_reader :top, :bottom, :left, :right def initialize(position) # rubocop:disable Style/RescueModifier @top = position['top'] rescue position['y'] @bottom = position['bottom'] rescue (@top + position['height']) @left = position['left'] rescue position['x'] @right = position['right'] rescue (@left + position['width']) # rubocop:enable Style/RescueModifier end def distance(other) distance = Float::INFINITY line_segments.each do |ls1| other.line_segments.each do |ls2| distance = [ distance, distance_segment_segment(*ls1, *ls2) ].min end end distance end def above?(other) bottom <= other.top end def below?(other) top >= other.bottom end def left_of?(other) right <= other.left end def right_of?(other) left >= other.right end def near?(other) distance(other) <= 50 end protected def line_segments [ [Vector[top, left], Vector[top, right]], [Vector[top, right], Vector[bottom, left]], [Vector[bottom, left], Vector[bottom, right]], [Vector[bottom, right], Vector[top, left]] ] end private def distance_segment_segment(l1p1, l1p2, l2p1, l2p2) # See http://geomalgorithms.com/a07-_distance.html # rubocop:disable Naming/VariableName u = l1p2 - l1p1 v = l2p2 - l2p1 w = l1p1 - l2p1 a = u.dot u b = u.dot v c = v.dot v d = u.dot w e = v.dot w cap_d = (a * c) - (b**2) sD = tD = cap_d # compute the line parameters of the two closest points if cap_d < Float::EPSILON # the lines are almost parallel sN = 0.0 # force using point P0 on segment S1 sD = 1.0 # to prevent possible division by 0.0 later tN = e tD = c else # get the closest points on the infinite lines sN = (b * e) - (c * d) tN = (a * e) - (b * d) if sN.negative? # sc < 0 => the s=0 edge is visible sN = 0 tN = e tD = c elsif sN > sD # sc > 1 => the s=1 edge is visible sN = sD tN = e + b tD = c end end if tN.negative? # tc < 0 => the t=0 edge is visible tN = 0 # recompute sc for this edge if (-d).negative? sN = 0.0 elsif -d > a sN = sD else sN = -d sD = a end elsif tN > tD # tc > 1 => the t=1 edge is visible tN = tD # recompute sc for this edge if (-d + b).negative? sN = 0.0 elsif (-d + b) > a sN = sD else sN = (-d + b) sD = a end end # finally do the division to get sc and tc sc = sN.abs < Float::EPSILON ? 0.0 : sN / sD tc = tN.abs < Float::EPSILON ? 0.0 : tN / tD # difference of the two closest points dP = w + (u * sc) - (v * tc) Math.sqrt(dP.dot(dP)) # rubocop:enable Naming/VariableName end end private_constant :Rectangle end end end
Ruby
{ "end_line": 509, "name": "matches_class_filter?", "signature": "def matches_class_filter?(node)", "start_line": 498 }
{ "class_name": "SelectorQuery", "class_signature": "class SelectorQuery < < Queries::BaseQuery", "module": "Capybara" }
matches_style_filter?
capybara/lib/capybara/queries/selector_query.rb
def matches_style_filter?(node) case options[:style] when String, nil true when Regexp options[:style].match? node[:style] when Hash matches_style?(node, options[:style]) end end
# frozen_string_literal: true require 'matrix' module Capybara module Queries class SelectorQuery < Queries::BaseQuery attr_reader :expression, :selector, :locator, :options SPATIAL_KEYS = %i[above below left_of right_of near].freeze VALID_KEYS = SPATIAL_KEYS + COUNT_KEYS + %i[text id class style visible obscured exact exact_text normalize_ws match wait filter_set focused] VALID_MATCH = %i[first smart prefer_exact one].freeze def initialize(*args, session_options:, enable_aria_label: session_options.enable_aria_label, enable_aria_role: session_options.enable_aria_role, test_id: session_options.test_id, selector_format: nil, order: nil, **options, &filter_block) @resolved_node = nil @resolved_count = 0 @options = options.dup @order = order @filter_cache = Hash.new { |hsh, key| hsh[key] = {} } if @options[:text].is_a?(Regexp) && [true, false].include?(@options[:exact_text]) Capybara::Helpers.warn( "Boolean 'exact_text' option is not supported when 'text' option is a Regexp - ignoring" ) end super(@options) self.session_options = session_options @selector = Selector.new( find_selector(args[0].is_a?(Symbol) ? args.shift : args[0]), config: { enable_aria_label: enable_aria_label, enable_aria_role: enable_aria_role, test_id: test_id }, format: selector_format ) @locator = args.shift @filter_block = filter_block raise ArgumentError, "Unused parameters passed to #{self.class.name} : #{args}" unless args.empty? @expression = selector.call(@locator, **@options) warn_exact_usage assert_valid_keys end def name; selector.name; end def label; selector.label || selector.name; end def description(only_applied = false) # rubocop:disable Style/OptionalBooleanParameter desc = +'' show_for = show_for_stage(only_applied) if show_for[:any] desc << 'visible ' if visible == :visible desc << 'non-visible ' if visible == :hidden end desc << label.to_s desc << " #{locator.inspect}" unless locator.nil? if show_for[:any] desc << " with#{' exact' if exact_text == true} text #{options[:text].inspect}" if options[:text] desc << " with exact text #{exact_text}" if exact_text.is_a?(String) end desc << " with id #{options[:id]}" if options[:id] desc << " with classes [#{Array(options[:class]).join(',')}]" if options[:class] desc << ' that is focused' if options[:focused] desc << ' that is not focused' if options[:focused] == false desc << case options[:style] when String " with style attribute #{options[:style].inspect}" when Regexp " with style attribute matching #{options[:style].inspect}" when Hash " with styles #{options[:style].inspect}" else '' end %i[above below left_of right_of near].each do |spatial_filter| if options[spatial_filter] && show_for[:spatial] desc << " #{spatial_filter} #{options[spatial_filter] rescue '<ERROR>'}" # rubocop:disable Style/RescueModifier end end desc << selector.description(node_filters: show_for[:node], **options) desc << ' that also matches the custom filter block' if @filter_block && show_for[:node] desc << " within #{@resolved_node.inspect}" if describe_within? if locator.is_a?(String) && locator.start_with?('#', './/', '//') && !selector.raw_locator? desc << "\nNote: It appears you may be passing a CSS selector or XPath expression rather than a locator. " \ "Please see the documentation for acceptable locator values.\n\n" end desc end def applied_description description(true) end def matches_filters?(node, node_filter_errors = []) return true if (@resolved_node&.== node) && options[:allow_self] matches_locator_filter?(node) && matches_system_filters?(node) && matches_spatial_filters?(node) && matches_node_filters?(node, node_filter_errors) && matches_filter_block?(node) rescue *(node.respond_to?(:session) ? node.session.driver.invalid_element_errors : []) false end def visible case (vis = options.fetch(:visible) { default_visibility }) when true then :visible when false then :all else vis end end def exact? supports_exact? ? options.fetch(:exact, session_options.exact) : false end def match options.fetch(:match, session_options.match) end def xpath(exact = nil) exact = exact? if exact.nil? expr = apply_expression_filters(@expression) expr = exact ? expr.to_xpath(:exact) : expr.to_s if expr.respond_to?(:to_xpath) expr = filtered_expression(expr) expr = "(#{expr})[#{xpath_text_conditions}]" if try_text_match_in_expression? expr end def css filtered_expression(apply_expression_filters(@expression)) end # @api private def resolve_for(node, exact = nil) applied_filters.clear @filter_cache.clear @resolved_node = node @resolved_count += 1 node.synchronize do children = find_nodes_by_selector_format(node, exact).map(&method(:to_element)) Capybara::Result.new(ordered_results(children), self) end end # @api private def supports_exact? return @expression.respond_to? :to_xpath if @selector.supports_exact?.nil? @selector.supports_exact? end def failure_message "expected to find #{applied_description}" << count_message end def negative_failure_message "expected not to find #{applied_description}" << count_message end private def selector_format @selector.format end def matching_text options[:text] || options[:exact_text] end def text_fragments (text = matching_text).is_a?(String) ? text.split : [] end def xpath_text_conditions case (text = matching_text) when String text.split.map { |txt| XPath.contains(txt) }.reduce(&:&) when Regexp condition = XPath.current condition = condition.uppercase if text.casefold? Selector::RegexpDisassembler.new(text).alternated_substrings.map do |strs| strs.flat_map(&:split).map { |str| condition.contains(str) }.reduce(:&) end.reduce(:|) end end def try_text_match_in_expression? first_try? && matching_text && @resolved_node.is_a?(Capybara::Node::Base) && @resolved_node.session&.driver&.wait? end def first_try? @resolved_count == 1 end def show_for_stage(only_applied) lambda do |stage = :any| !only_applied || (stage == :any ? applied_filters.any? : applied_filters.include?(stage)) end end def applied_filters @applied_filters ||= [] end def find_selector(locator) case locator when Symbol then Selector[locator] else Selector.for(locator) end || Selector[session_options.default_selector] end def find_nodes_by_selector_format(node, exact) hints = {} hints[:uses_visibility] = true unless visible == :all hints[:texts] = text_fragments unless selector_format == :xpath hints[:styles] = options[:style] if use_default_style_filter? hints[:position] = true if use_spatial_filter? case selector_format when :css if node.method(:find_css).arity == 1 node.find_css(css) else node.find_css(css, **hints) end when :xpath if node.method(:find_xpath).arity == 1 node.find_xpath(xpath(exact)) else node.find_xpath(xpath(exact), **hints) end else raise ArgumentError, "Unknown format: #{selector_format}" end end def to_element(node) if @resolved_node.is_a?(Capybara::Node::Base) Capybara::Node::Element.new(@resolved_node.session, node, @resolved_node, self) else Capybara::Node::Simple.new(node) end end def valid_keys (VALID_KEYS + custom_keys).uniq end def matches_node_filters?(node, errors) applied_filters << :node unapplied_options = options.keys - valid_keys @selector.with_filter_errors(errors) do node_filters.all? do |filter_name, filter| next true unless apply_filter?(filter) if filter.matcher? unapplied_options.select { |option_name| filter.handles_option?(option_name) }.all? do |option_name| unapplied_options.delete(option_name) filter.matches?(node, option_name, options[option_name], @selector) end elsif options.key?(filter_name) unapplied_options.delete(filter_name) filter.matches?(node, filter_name, options[filter_name], @selector) elsif filter.default? filter.matches?(node, filter_name, filter.default, @selector) else true end end end end def matches_filter_block?(node) return true unless @filter_block if node.respond_to?(:session) node.session.using_wait_time(0) { @filter_block.call(node) } else @filter_block.call(node) end end def filter_set(name) ::Capybara::Selector::FilterSet[name] end def node_filters if options.key?(:filter_set) filter_set(options[:filter_set]) else @selector end.node_filters end def expression_filters filters = @selector.expression_filters filters.merge filter_set(options[:filter_set]).expression_filters if options.key?(:filter_set) filters end def ordered_results(results) case @order when :reverse results.reverse else results end end def custom_keys @custom_keys ||= node_filters.keys + expression_filters.keys end def assert_valid_keys unless VALID_MATCH.include?(match) raise ArgumentError, "Invalid option #{match.inspect} for :match, should be one of #{VALID_MATCH.map(&:inspect).join(', ')}" end unhandled_options = @options.keys.reject do |option_name| valid_keys.include?(option_name) || expression_filters.any? { |_name, ef| ef.handles_option? option_name } || node_filters.any? { |_name, nf| nf.handles_option? option_name } end return if unhandled_options.empty? invalid_names = unhandled_options.map(&:inspect).join(', ') valid_names = (valid_keys - [:allow_self]).map(&:inspect).join(', ') raise ArgumentError, "Invalid option(s) #{invalid_names}, should be one of #{valid_names}" end def filtered_expression(expr) conditions = {} conditions[:id] = options[:id] if use_default_id_filter? conditions[:class] = options[:class] if use_default_class_filter? conditions[:style] = options[:style] if use_default_style_filter? && !options[:style].is_a?(Hash) builder(expr).add_attribute_conditions(**conditions) end def use_default_id_filter? options.key?(:id) && !custom_keys.include?(:id) end def use_default_class_filter? options.key?(:class) && !custom_keys.include?(:class) end def use_default_style_filter? options.key?(:style) && !custom_keys.include?(:style) end def use_default_focused_filter? options.key?(:focused) && !custom_keys.include?(:focused) end def use_spatial_filter? options.values_at(*SPATIAL_KEYS).compact.any? end def apply_expression_filters(expression) unapplied_options = options.keys - valid_keys expression_filters.inject(expression) do |expr, (name, ef)| next expr unless apply_filter?(ef) if ef.matcher? unapplied_options.select(&ef.method(:handles_option?)).inject(expr) do |memo, option_name| unapplied_options.delete(option_name) ef.apply_filter(memo, option_name, options[option_name], @selector) end elsif options.key?(name) unapplied_options.delete(name) ef.apply_filter(expr, name, options[name], @selector) elsif ef.default? ef.apply_filter(expr, name, ef.default, @selector) else expr end end end def warn_exact_usage return unless options.key?(:exact) && !supports_exact? warn "The :exact option only has an effect on queries using the XPath#is method. Using it with the query \"#{expression}\" has no effect." end def exact_text options.fetch(:exact_text, session_options.exact_text) end def describe_within? @resolved_node && !document?(@resolved_node) && !simple_root?(@resolved_node) end def document?(node) node.is_a?(::Capybara::Node::Document) end def simple_root?(node) node.is_a?(::Capybara::Node::Simple) && node.path == '/' end def apply_filter?(filter) filter.format.nil? || (filter.format == selector_format) end def matches_locator_filter?(node) return true unless @selector.locator_filter && apply_filter?(@selector.locator_filter) @selector.locator_filter.matches?(node, @locator, @selector, exact: exact?) end def matches_system_filters?(node) applied_filters << :system matches_visibility_filters?(node) && matches_id_filter?(node) && matches_class_filter?(node) && matches_style_filter?(node) && matches_focused_filter?(node) && matches_text_filter?(node) && matches_exact_text_filter?(node) end def matches_spatial_filters?(node) applied_filters << :spatial return true unless use_spatial_filter? node_rect = Rectangle.new(node.initial_cache[:position] || node.rect) if options[:above] el_rect = rect_cache(options[:above]) return false unless node_rect.above? el_rect end if options[:below] el_rect = rect_cache(options[:below]) return false unless node_rect.below? el_rect end if options[:left_of] el_rect = rect_cache(options[:left_of]) return false unless node_rect.left_of? el_rect end if options[:right_of] el_rect = rect_cache(options[:right_of]) return false unless node_rect.right_of? el_rect end if options[:near] return false if node == options[:near] el_rect = rect_cache(options[:near]) return false unless node_rect.near? el_rect end true end def matches_id_filter?(node) return true unless use_default_id_filter? && options[:id].is_a?(Regexp) options[:id].match? node[:id] end def matches_class_filter?(node) return true unless use_default_class_filter? && need_to_process_classes? if options[:class].is_a? Regexp options[:class].match? node[:class] else classes = (node[:class] || '').split options[:class].select { |c| c.is_a? Regexp }.all? do |r| classes.any? { |cls| r.match? cls } end end end def matches_focused_filter?(node) return true unless use_default_focused_filter? (node == node.session.active_element) == options[:focused] end def need_to_process_classes? case options[:class] when Regexp then true when Array then options[:class].any?(Regexp) else false end end def matches_style_filter?(node) case options[:style] when String, nil true when Regexp options[:style].match? node[:style] when Hash matches_style?(node, options[:style]) end end def matches_style?(node, styles) @actual_styles = node.initial_cache[:style] || node.style(*styles.keys) styles.all? do |style, value| if value.is_a? Regexp value.match? @actual_styles[style.to_s] else @actual_styles[style.to_s] == value end end end def matches_text_filter?(node) value = options[:text] return true unless value return matches_text_exactly?(node, value) if exact_text == true && !value.is_a?(Regexp) regexp = value.is_a?(Regexp) ? value : Regexp.escape(value.to_s) matches_text_regexp?(node, regexp) end def matches_exact_text_filter?(node) case exact_text when String, Regexp matches_text_exactly?(node, exact_text) else true end end def matches_visibility_filters?(node) obscured = options[:obscured] return (visible != :hidden) && (node.initial_cache[:visible] != false) && !node.obscured? if obscured == false vis = case visible when :visible node.initial_cache[:visible] || (node.initial_cache[:visible].nil? && node.visible?) when :hidden # TODO: check why the 'visbile' cache spelling mistake wasn't caught in a test # (node.initial_cache[:visible] == false) || (node.initial_cache[:visbile].nil? && !node.visible?) (node.initial_cache[:visible] == false) || (node.initial_cache[:visible].nil? && !node.visible?) else true end vis && case obscured when true node.obscured? when false !node.obscured? else true end end def matches_text_exactly?(node, value) regexp = value.is_a?(Regexp) ? value : /\A#{Regexp.escape(value.to_s)}\z/ matches_text_regexp(node, regexp).then { |m| m&.pre_match == '' && m&.post_match == '' } end def normalize_ws options.fetch(:normalize_ws, session_options.default_normalize_ws) end def matches_text_regexp(node, regexp) text_visible = visible text_visible = :all if text_visible == :hidden node.text(text_visible, normalize_ws: normalize_ws).match(regexp) end def matches_text_regexp?(node, regexp) !matches_text_regexp(node, regexp).nil? end def default_visibility @selector.default_visibility(session_options.ignore_hidden_elements, options) end def builder(expr) selector.builder(expr) end def position_cache(key) @filter_cache[key][:position] ||= key.rect end def rect_cache(key) @filter_cache[key][:rect] ||= Rectangle.new(position_cache(key)) end class Rectangle attr_reader :top, :bottom, :left, :right def initialize(position) # rubocop:disable Style/RescueModifier @top = position['top'] rescue position['y'] @bottom = position['bottom'] rescue (@top + position['height']) @left = position['left'] rescue position['x'] @right = position['right'] rescue (@left + position['width']) # rubocop:enable Style/RescueModifier end def distance(other) distance = Float::INFINITY line_segments.each do |ls1| other.line_segments.each do |ls2| distance = [ distance, distance_segment_segment(*ls1, *ls2) ].min end end distance end def above?(other) bottom <= other.top end def below?(other) top >= other.bottom end def left_of?(other) right <= other.left end def right_of?(other) left >= other.right end def near?(other) distance(other) <= 50 end protected def line_segments [ [Vector[top, left], Vector[top, right]], [Vector[top, right], Vector[bottom, left]], [Vector[bottom, left], Vector[bottom, right]], [Vector[bottom, right], Vector[top, left]] ] end private def distance_segment_segment(l1p1, l1p2, l2p1, l2p2) # See http://geomalgorithms.com/a07-_distance.html # rubocop:disable Naming/VariableName u = l1p2 - l1p1 v = l2p2 - l2p1 w = l1p1 - l2p1 a = u.dot u b = u.dot v c = v.dot v d = u.dot w e = v.dot w cap_d = (a * c) - (b**2) sD = tD = cap_d # compute the line parameters of the two closest points if cap_d < Float::EPSILON # the lines are almost parallel sN = 0.0 # force using point P0 on segment S1 sD = 1.0 # to prevent possible division by 0.0 later tN = e tD = c else # get the closest points on the infinite lines sN = (b * e) - (c * d) tN = (a * e) - (b * d) if sN.negative? # sc < 0 => the s=0 edge is visible sN = 0 tN = e tD = c elsif sN > sD # sc > 1 => the s=1 edge is visible sN = sD tN = e + b tD = c end end if tN.negative? # tc < 0 => the t=0 edge is visible tN = 0 # recompute sc for this edge if (-d).negative? sN = 0.0 elsif -d > a sN = sD else sN = -d sD = a end elsif tN > tD # tc > 1 => the t=1 edge is visible tN = tD # recompute sc for this edge if (-d + b).negative? sN = 0.0 elsif (-d + b) > a sN = sD else sN = (-d + b) sD = a end end # finally do the division to get sc and tc sc = sN.abs < Float::EPSILON ? 0.0 : sN / sD tc = tN.abs < Float::EPSILON ? 0.0 : tN / tD # difference of the two closest points dP = w + (u * sc) - (v * tc) Math.sqrt(dP.dot(dP)) # rubocop:enable Naming/VariableName end end private_constant :Rectangle end end end
Ruby
{ "end_line": 535, "name": "matches_style_filter?", "signature": "def matches_style_filter?(node)", "start_line": 526 }
{ "class_name": "SelectorQuery", "class_signature": "class SelectorQuery < < Queries::BaseQuery", "module": "Capybara" }
matches_style?
capybara/lib/capybara/queries/selector_query.rb
def matches_style?(node, styles) @actual_styles = node.initial_cache[:style] || node.style(*styles.keys) styles.all? do |style, value| if value.is_a? Regexp value.match? @actual_styles[style.to_s] else @actual_styles[style.to_s] == value end end end
# frozen_string_literal: true require 'matrix' module Capybara module Queries class SelectorQuery < Queries::BaseQuery attr_reader :expression, :selector, :locator, :options SPATIAL_KEYS = %i[above below left_of right_of near].freeze VALID_KEYS = SPATIAL_KEYS + COUNT_KEYS + %i[text id class style visible obscured exact exact_text normalize_ws match wait filter_set focused] VALID_MATCH = %i[first smart prefer_exact one].freeze def initialize(*args, session_options:, enable_aria_label: session_options.enable_aria_label, enable_aria_role: session_options.enable_aria_role, test_id: session_options.test_id, selector_format: nil, order: nil, **options, &filter_block) @resolved_node = nil @resolved_count = 0 @options = options.dup @order = order @filter_cache = Hash.new { |hsh, key| hsh[key] = {} } if @options[:text].is_a?(Regexp) && [true, false].include?(@options[:exact_text]) Capybara::Helpers.warn( "Boolean 'exact_text' option is not supported when 'text' option is a Regexp - ignoring" ) end super(@options) self.session_options = session_options @selector = Selector.new( find_selector(args[0].is_a?(Symbol) ? args.shift : args[0]), config: { enable_aria_label: enable_aria_label, enable_aria_role: enable_aria_role, test_id: test_id }, format: selector_format ) @locator = args.shift @filter_block = filter_block raise ArgumentError, "Unused parameters passed to #{self.class.name} : #{args}" unless args.empty? @expression = selector.call(@locator, **@options) warn_exact_usage assert_valid_keys end def name; selector.name; end def label; selector.label || selector.name; end def description(only_applied = false) # rubocop:disable Style/OptionalBooleanParameter desc = +'' show_for = show_for_stage(only_applied) if show_for[:any] desc << 'visible ' if visible == :visible desc << 'non-visible ' if visible == :hidden end desc << label.to_s desc << " #{locator.inspect}" unless locator.nil? if show_for[:any] desc << " with#{' exact' if exact_text == true} text #{options[:text].inspect}" if options[:text] desc << " with exact text #{exact_text}" if exact_text.is_a?(String) end desc << " with id #{options[:id]}" if options[:id] desc << " with classes [#{Array(options[:class]).join(',')}]" if options[:class] desc << ' that is focused' if options[:focused] desc << ' that is not focused' if options[:focused] == false desc << case options[:style] when String " with style attribute #{options[:style].inspect}" when Regexp " with style attribute matching #{options[:style].inspect}" when Hash " with styles #{options[:style].inspect}" else '' end %i[above below left_of right_of near].each do |spatial_filter| if options[spatial_filter] && show_for[:spatial] desc << " #{spatial_filter} #{options[spatial_filter] rescue '<ERROR>'}" # rubocop:disable Style/RescueModifier end end desc << selector.description(node_filters: show_for[:node], **options) desc << ' that also matches the custom filter block' if @filter_block && show_for[:node] desc << " within #{@resolved_node.inspect}" if describe_within? if locator.is_a?(String) && locator.start_with?('#', './/', '//') && !selector.raw_locator? desc << "\nNote: It appears you may be passing a CSS selector or XPath expression rather than a locator. " \ "Please see the documentation for acceptable locator values.\n\n" end desc end def applied_description description(true) end def matches_filters?(node, node_filter_errors = []) return true if (@resolved_node&.== node) && options[:allow_self] matches_locator_filter?(node) && matches_system_filters?(node) && matches_spatial_filters?(node) && matches_node_filters?(node, node_filter_errors) && matches_filter_block?(node) rescue *(node.respond_to?(:session) ? node.session.driver.invalid_element_errors : []) false end def visible case (vis = options.fetch(:visible) { default_visibility }) when true then :visible when false then :all else vis end end def exact? supports_exact? ? options.fetch(:exact, session_options.exact) : false end def match options.fetch(:match, session_options.match) end def xpath(exact = nil) exact = exact? if exact.nil? expr = apply_expression_filters(@expression) expr = exact ? expr.to_xpath(:exact) : expr.to_s if expr.respond_to?(:to_xpath) expr = filtered_expression(expr) expr = "(#{expr})[#{xpath_text_conditions}]" if try_text_match_in_expression? expr end def css filtered_expression(apply_expression_filters(@expression)) end # @api private def resolve_for(node, exact = nil) applied_filters.clear @filter_cache.clear @resolved_node = node @resolved_count += 1 node.synchronize do children = find_nodes_by_selector_format(node, exact).map(&method(:to_element)) Capybara::Result.new(ordered_results(children), self) end end # @api private def supports_exact? return @expression.respond_to? :to_xpath if @selector.supports_exact?.nil? @selector.supports_exact? end def failure_message "expected to find #{applied_description}" << count_message end def negative_failure_message "expected not to find #{applied_description}" << count_message end private def selector_format @selector.format end def matching_text options[:text] || options[:exact_text] end def text_fragments (text = matching_text).is_a?(String) ? text.split : [] end def xpath_text_conditions case (text = matching_text) when String text.split.map { |txt| XPath.contains(txt) }.reduce(&:&) when Regexp condition = XPath.current condition = condition.uppercase if text.casefold? Selector::RegexpDisassembler.new(text).alternated_substrings.map do |strs| strs.flat_map(&:split).map { |str| condition.contains(str) }.reduce(:&) end.reduce(:|) end end def try_text_match_in_expression? first_try? && matching_text && @resolved_node.is_a?(Capybara::Node::Base) && @resolved_node.session&.driver&.wait? end def first_try? @resolved_count == 1 end def show_for_stage(only_applied) lambda do |stage = :any| !only_applied || (stage == :any ? applied_filters.any? : applied_filters.include?(stage)) end end def applied_filters @applied_filters ||= [] end def find_selector(locator) case locator when Symbol then Selector[locator] else Selector.for(locator) end || Selector[session_options.default_selector] end def find_nodes_by_selector_format(node, exact) hints = {} hints[:uses_visibility] = true unless visible == :all hints[:texts] = text_fragments unless selector_format == :xpath hints[:styles] = options[:style] if use_default_style_filter? hints[:position] = true if use_spatial_filter? case selector_format when :css if node.method(:find_css).arity == 1 node.find_css(css) else node.find_css(css, **hints) end when :xpath if node.method(:find_xpath).arity == 1 node.find_xpath(xpath(exact)) else node.find_xpath(xpath(exact), **hints) end else raise ArgumentError, "Unknown format: #{selector_format}" end end def to_element(node) if @resolved_node.is_a?(Capybara::Node::Base) Capybara::Node::Element.new(@resolved_node.session, node, @resolved_node, self) else Capybara::Node::Simple.new(node) end end def valid_keys (VALID_KEYS + custom_keys).uniq end def matches_node_filters?(node, errors) applied_filters << :node unapplied_options = options.keys - valid_keys @selector.with_filter_errors(errors) do node_filters.all? do |filter_name, filter| next true unless apply_filter?(filter) if filter.matcher? unapplied_options.select { |option_name| filter.handles_option?(option_name) }.all? do |option_name| unapplied_options.delete(option_name) filter.matches?(node, option_name, options[option_name], @selector) end elsif options.key?(filter_name) unapplied_options.delete(filter_name) filter.matches?(node, filter_name, options[filter_name], @selector) elsif filter.default? filter.matches?(node, filter_name, filter.default, @selector) else true end end end end def matches_filter_block?(node) return true unless @filter_block if node.respond_to?(:session) node.session.using_wait_time(0) { @filter_block.call(node) } else @filter_block.call(node) end end def filter_set(name) ::Capybara::Selector::FilterSet[name] end def node_filters if options.key?(:filter_set) filter_set(options[:filter_set]) else @selector end.node_filters end def expression_filters filters = @selector.expression_filters filters.merge filter_set(options[:filter_set]).expression_filters if options.key?(:filter_set) filters end def ordered_results(results) case @order when :reverse results.reverse else results end end def custom_keys @custom_keys ||= node_filters.keys + expression_filters.keys end def assert_valid_keys unless VALID_MATCH.include?(match) raise ArgumentError, "Invalid option #{match.inspect} for :match, should be one of #{VALID_MATCH.map(&:inspect).join(', ')}" end unhandled_options = @options.keys.reject do |option_name| valid_keys.include?(option_name) || expression_filters.any? { |_name, ef| ef.handles_option? option_name } || node_filters.any? { |_name, nf| nf.handles_option? option_name } end return if unhandled_options.empty? invalid_names = unhandled_options.map(&:inspect).join(', ') valid_names = (valid_keys - [:allow_self]).map(&:inspect).join(', ') raise ArgumentError, "Invalid option(s) #{invalid_names}, should be one of #{valid_names}" end def filtered_expression(expr) conditions = {} conditions[:id] = options[:id] if use_default_id_filter? conditions[:class] = options[:class] if use_default_class_filter? conditions[:style] = options[:style] if use_default_style_filter? && !options[:style].is_a?(Hash) builder(expr).add_attribute_conditions(**conditions) end def use_default_id_filter? options.key?(:id) && !custom_keys.include?(:id) end def use_default_class_filter? options.key?(:class) && !custom_keys.include?(:class) end def use_default_style_filter? options.key?(:style) && !custom_keys.include?(:style) end def use_default_focused_filter? options.key?(:focused) && !custom_keys.include?(:focused) end def use_spatial_filter? options.values_at(*SPATIAL_KEYS).compact.any? end def apply_expression_filters(expression) unapplied_options = options.keys - valid_keys expression_filters.inject(expression) do |expr, (name, ef)| next expr unless apply_filter?(ef) if ef.matcher? unapplied_options.select(&ef.method(:handles_option?)).inject(expr) do |memo, option_name| unapplied_options.delete(option_name) ef.apply_filter(memo, option_name, options[option_name], @selector) end elsif options.key?(name) unapplied_options.delete(name) ef.apply_filter(expr, name, options[name], @selector) elsif ef.default? ef.apply_filter(expr, name, ef.default, @selector) else expr end end end def warn_exact_usage return unless options.key?(:exact) && !supports_exact? warn "The :exact option only has an effect on queries using the XPath#is method. Using it with the query \"#{expression}\" has no effect." end def exact_text options.fetch(:exact_text, session_options.exact_text) end def describe_within? @resolved_node && !document?(@resolved_node) && !simple_root?(@resolved_node) end def document?(node) node.is_a?(::Capybara::Node::Document) end def simple_root?(node) node.is_a?(::Capybara::Node::Simple) && node.path == '/' end def apply_filter?(filter) filter.format.nil? || (filter.format == selector_format) end def matches_locator_filter?(node) return true unless @selector.locator_filter && apply_filter?(@selector.locator_filter) @selector.locator_filter.matches?(node, @locator, @selector, exact: exact?) end def matches_system_filters?(node) applied_filters << :system matches_visibility_filters?(node) && matches_id_filter?(node) && matches_class_filter?(node) && matches_style_filter?(node) && matches_focused_filter?(node) && matches_text_filter?(node) && matches_exact_text_filter?(node) end def matches_spatial_filters?(node) applied_filters << :spatial return true unless use_spatial_filter? node_rect = Rectangle.new(node.initial_cache[:position] || node.rect) if options[:above] el_rect = rect_cache(options[:above]) return false unless node_rect.above? el_rect end if options[:below] el_rect = rect_cache(options[:below]) return false unless node_rect.below? el_rect end if options[:left_of] el_rect = rect_cache(options[:left_of]) return false unless node_rect.left_of? el_rect end if options[:right_of] el_rect = rect_cache(options[:right_of]) return false unless node_rect.right_of? el_rect end if options[:near] return false if node == options[:near] el_rect = rect_cache(options[:near]) return false unless node_rect.near? el_rect end true end def matches_id_filter?(node) return true unless use_default_id_filter? && options[:id].is_a?(Regexp) options[:id].match? node[:id] end def matches_class_filter?(node) return true unless use_default_class_filter? && need_to_process_classes? if options[:class].is_a? Regexp options[:class].match? node[:class] else classes = (node[:class] || '').split options[:class].select { |c| c.is_a? Regexp }.all? do |r| classes.any? { |cls| r.match? cls } end end end def matches_focused_filter?(node) return true unless use_default_focused_filter? (node == node.session.active_element) == options[:focused] end def need_to_process_classes? case options[:class] when Regexp then true when Array then options[:class].any?(Regexp) else false end end def matches_style_filter?(node) case options[:style] when String, nil true when Regexp options[:style].match? node[:style] when Hash matches_style?(node, options[:style]) end end def matches_style?(node, styles) @actual_styles = node.initial_cache[:style] || node.style(*styles.keys) styles.all? do |style, value| if value.is_a? Regexp value.match? @actual_styles[style.to_s] else @actual_styles[style.to_s] == value end end end def matches_text_filter?(node) value = options[:text] return true unless value return matches_text_exactly?(node, value) if exact_text == true && !value.is_a?(Regexp) regexp = value.is_a?(Regexp) ? value : Regexp.escape(value.to_s) matches_text_regexp?(node, regexp) end def matches_exact_text_filter?(node) case exact_text when String, Regexp matches_text_exactly?(node, exact_text) else true end end def matches_visibility_filters?(node) obscured = options[:obscured] return (visible != :hidden) && (node.initial_cache[:visible] != false) && !node.obscured? if obscured == false vis = case visible when :visible node.initial_cache[:visible] || (node.initial_cache[:visible].nil? && node.visible?) when :hidden # TODO: check why the 'visbile' cache spelling mistake wasn't caught in a test # (node.initial_cache[:visible] == false) || (node.initial_cache[:visbile].nil? && !node.visible?) (node.initial_cache[:visible] == false) || (node.initial_cache[:visible].nil? && !node.visible?) else true end vis && case obscured when true node.obscured? when false !node.obscured? else true end end def matches_text_exactly?(node, value) regexp = value.is_a?(Regexp) ? value : /\A#{Regexp.escape(value.to_s)}\z/ matches_text_regexp(node, regexp).then { |m| m&.pre_match == '' && m&.post_match == '' } end def normalize_ws options.fetch(:normalize_ws, session_options.default_normalize_ws) end def matches_text_regexp(node, regexp) text_visible = visible text_visible = :all if text_visible == :hidden node.text(text_visible, normalize_ws: normalize_ws).match(regexp) end def matches_text_regexp?(node, regexp) !matches_text_regexp(node, regexp).nil? end def default_visibility @selector.default_visibility(session_options.ignore_hidden_elements, options) end def builder(expr) selector.builder(expr) end def position_cache(key) @filter_cache[key][:position] ||= key.rect end def rect_cache(key) @filter_cache[key][:rect] ||= Rectangle.new(position_cache(key)) end class Rectangle attr_reader :top, :bottom, :left, :right def initialize(position) # rubocop:disable Style/RescueModifier @top = position['top'] rescue position['y'] @bottom = position['bottom'] rescue (@top + position['height']) @left = position['left'] rescue position['x'] @right = position['right'] rescue (@left + position['width']) # rubocop:enable Style/RescueModifier end def distance(other) distance = Float::INFINITY line_segments.each do |ls1| other.line_segments.each do |ls2| distance = [ distance, distance_segment_segment(*ls1, *ls2) ].min end end distance end def above?(other) bottom <= other.top end def below?(other) top >= other.bottom end def left_of?(other) right <= other.left end def right_of?(other) left >= other.right end def near?(other) distance(other) <= 50 end protected def line_segments [ [Vector[top, left], Vector[top, right]], [Vector[top, right], Vector[bottom, left]], [Vector[bottom, left], Vector[bottom, right]], [Vector[bottom, right], Vector[top, left]] ] end private def distance_segment_segment(l1p1, l1p2, l2p1, l2p2) # See http://geomalgorithms.com/a07-_distance.html # rubocop:disable Naming/VariableName u = l1p2 - l1p1 v = l2p2 - l2p1 w = l1p1 - l2p1 a = u.dot u b = u.dot v c = v.dot v d = u.dot w e = v.dot w cap_d = (a * c) - (b**2) sD = tD = cap_d # compute the line parameters of the two closest points if cap_d < Float::EPSILON # the lines are almost parallel sN = 0.0 # force using point P0 on segment S1 sD = 1.0 # to prevent possible division by 0.0 later tN = e tD = c else # get the closest points on the infinite lines sN = (b * e) - (c * d) tN = (a * e) - (b * d) if sN.negative? # sc < 0 => the s=0 edge is visible sN = 0 tN = e tD = c elsif sN > sD # sc > 1 => the s=1 edge is visible sN = sD tN = e + b tD = c end end if tN.negative? # tc < 0 => the t=0 edge is visible tN = 0 # recompute sc for this edge if (-d).negative? sN = 0.0 elsif -d > a sN = sD else sN = -d sD = a end elsif tN > tD # tc > 1 => the t=1 edge is visible tN = tD # recompute sc for this edge if (-d + b).negative? sN = 0.0 elsif (-d + b) > a sN = sD else sN = (-d + b) sD = a end end # finally do the division to get sc and tc sc = sN.abs < Float::EPSILON ? 0.0 : sN / sD tc = tN.abs < Float::EPSILON ? 0.0 : tN / tD # difference of the two closest points dP = w + (u * sc) - (v * tc) Math.sqrt(dP.dot(dP)) # rubocop:enable Naming/VariableName end end private_constant :Rectangle end end end
Ruby
{ "end_line": 546, "name": "matches_style?", "signature": "def matches_style?(node, styles)", "start_line": 537 }
{ "class_name": "SelectorQuery", "class_signature": "class SelectorQuery < < Queries::BaseQuery", "module": "Capybara" }
matches_visibility_filters?
capybara/lib/capybara/queries/selector_query.rb
def matches_visibility_filters?(node) obscured = options[:obscured] return (visible != :hidden) && (node.initial_cache[:visible] != false) && !node.obscured? if obscured == false vis = case visible when :visible node.initial_cache[:visible] || (node.initial_cache[:visible].nil? && node.visible?) when :hidden # TODO: check why the 'visbile' cache spelling mistake wasn't caught in a test # (node.initial_cache[:visible] == false) || (node.initial_cache[:visbile].nil? && !node.visible?) (node.initial_cache[:visible] == false) || (node.initial_cache[:visible].nil? && !node.visible?) else true end vis && case obscured when true node.obscured? when false !node.obscured? else true end end
# frozen_string_literal: true require 'matrix' module Capybara module Queries class SelectorQuery < Queries::BaseQuery attr_reader :expression, :selector, :locator, :options SPATIAL_KEYS = %i[above below left_of right_of near].freeze VALID_KEYS = SPATIAL_KEYS + COUNT_KEYS + %i[text id class style visible obscured exact exact_text normalize_ws match wait filter_set focused] VALID_MATCH = %i[first smart prefer_exact one].freeze def initialize(*args, session_options:, enable_aria_label: session_options.enable_aria_label, enable_aria_role: session_options.enable_aria_role, test_id: session_options.test_id, selector_format: nil, order: nil, **options, &filter_block) @resolved_node = nil @resolved_count = 0 @options = options.dup @order = order @filter_cache = Hash.new { |hsh, key| hsh[key] = {} } if @options[:text].is_a?(Regexp) && [true, false].include?(@options[:exact_text]) Capybara::Helpers.warn( "Boolean 'exact_text' option is not supported when 'text' option is a Regexp - ignoring" ) end super(@options) self.session_options = session_options @selector = Selector.new( find_selector(args[0].is_a?(Symbol) ? args.shift : args[0]), config: { enable_aria_label: enable_aria_label, enable_aria_role: enable_aria_role, test_id: test_id }, format: selector_format ) @locator = args.shift @filter_block = filter_block raise ArgumentError, "Unused parameters passed to #{self.class.name} : #{args}" unless args.empty? @expression = selector.call(@locator, **@options) warn_exact_usage assert_valid_keys end def name; selector.name; end def label; selector.label || selector.name; end def description(only_applied = false) # rubocop:disable Style/OptionalBooleanParameter desc = +'' show_for = show_for_stage(only_applied) if show_for[:any] desc << 'visible ' if visible == :visible desc << 'non-visible ' if visible == :hidden end desc << label.to_s desc << " #{locator.inspect}" unless locator.nil? if show_for[:any] desc << " with#{' exact' if exact_text == true} text #{options[:text].inspect}" if options[:text] desc << " with exact text #{exact_text}" if exact_text.is_a?(String) end desc << " with id #{options[:id]}" if options[:id] desc << " with classes [#{Array(options[:class]).join(',')}]" if options[:class] desc << ' that is focused' if options[:focused] desc << ' that is not focused' if options[:focused] == false desc << case options[:style] when String " with style attribute #{options[:style].inspect}" when Regexp " with style attribute matching #{options[:style].inspect}" when Hash " with styles #{options[:style].inspect}" else '' end %i[above below left_of right_of near].each do |spatial_filter| if options[spatial_filter] && show_for[:spatial] desc << " #{spatial_filter} #{options[spatial_filter] rescue '<ERROR>'}" # rubocop:disable Style/RescueModifier end end desc << selector.description(node_filters: show_for[:node], **options) desc << ' that also matches the custom filter block' if @filter_block && show_for[:node] desc << " within #{@resolved_node.inspect}" if describe_within? if locator.is_a?(String) && locator.start_with?('#', './/', '//') && !selector.raw_locator? desc << "\nNote: It appears you may be passing a CSS selector or XPath expression rather than a locator. " \ "Please see the documentation for acceptable locator values.\n\n" end desc end def applied_description description(true) end def matches_filters?(node, node_filter_errors = []) return true if (@resolved_node&.== node) && options[:allow_self] matches_locator_filter?(node) && matches_system_filters?(node) && matches_spatial_filters?(node) && matches_node_filters?(node, node_filter_errors) && matches_filter_block?(node) rescue *(node.respond_to?(:session) ? node.session.driver.invalid_element_errors : []) false end def visible case (vis = options.fetch(:visible) { default_visibility }) when true then :visible when false then :all else vis end end def exact? supports_exact? ? options.fetch(:exact, session_options.exact) : false end def match options.fetch(:match, session_options.match) end def xpath(exact = nil) exact = exact? if exact.nil? expr = apply_expression_filters(@expression) expr = exact ? expr.to_xpath(:exact) : expr.to_s if expr.respond_to?(:to_xpath) expr = filtered_expression(expr) expr = "(#{expr})[#{xpath_text_conditions}]" if try_text_match_in_expression? expr end def css filtered_expression(apply_expression_filters(@expression)) end # @api private def resolve_for(node, exact = nil) applied_filters.clear @filter_cache.clear @resolved_node = node @resolved_count += 1 node.synchronize do children = find_nodes_by_selector_format(node, exact).map(&method(:to_element)) Capybara::Result.new(ordered_results(children), self) end end # @api private def supports_exact? return @expression.respond_to? :to_xpath if @selector.supports_exact?.nil? @selector.supports_exact? end def failure_message "expected to find #{applied_description}" << count_message end def negative_failure_message "expected not to find #{applied_description}" << count_message end private def selector_format @selector.format end def matching_text options[:text] || options[:exact_text] end def text_fragments (text = matching_text).is_a?(String) ? text.split : [] end def xpath_text_conditions case (text = matching_text) when String text.split.map { |txt| XPath.contains(txt) }.reduce(&:&) when Regexp condition = XPath.current condition = condition.uppercase if text.casefold? Selector::RegexpDisassembler.new(text).alternated_substrings.map do |strs| strs.flat_map(&:split).map { |str| condition.contains(str) }.reduce(:&) end.reduce(:|) end end def try_text_match_in_expression? first_try? && matching_text && @resolved_node.is_a?(Capybara::Node::Base) && @resolved_node.session&.driver&.wait? end def first_try? @resolved_count == 1 end def show_for_stage(only_applied) lambda do |stage = :any| !only_applied || (stage == :any ? applied_filters.any? : applied_filters.include?(stage)) end end def applied_filters @applied_filters ||= [] end def find_selector(locator) case locator when Symbol then Selector[locator] else Selector.for(locator) end || Selector[session_options.default_selector] end def find_nodes_by_selector_format(node, exact) hints = {} hints[:uses_visibility] = true unless visible == :all hints[:texts] = text_fragments unless selector_format == :xpath hints[:styles] = options[:style] if use_default_style_filter? hints[:position] = true if use_spatial_filter? case selector_format when :css if node.method(:find_css).arity == 1 node.find_css(css) else node.find_css(css, **hints) end when :xpath if node.method(:find_xpath).arity == 1 node.find_xpath(xpath(exact)) else node.find_xpath(xpath(exact), **hints) end else raise ArgumentError, "Unknown format: #{selector_format}" end end def to_element(node) if @resolved_node.is_a?(Capybara::Node::Base) Capybara::Node::Element.new(@resolved_node.session, node, @resolved_node, self) else Capybara::Node::Simple.new(node) end end def valid_keys (VALID_KEYS + custom_keys).uniq end def matches_node_filters?(node, errors) applied_filters << :node unapplied_options = options.keys - valid_keys @selector.with_filter_errors(errors) do node_filters.all? do |filter_name, filter| next true unless apply_filter?(filter) if filter.matcher? unapplied_options.select { |option_name| filter.handles_option?(option_name) }.all? do |option_name| unapplied_options.delete(option_name) filter.matches?(node, option_name, options[option_name], @selector) end elsif options.key?(filter_name) unapplied_options.delete(filter_name) filter.matches?(node, filter_name, options[filter_name], @selector) elsif filter.default? filter.matches?(node, filter_name, filter.default, @selector) else true end end end end def matches_filter_block?(node) return true unless @filter_block if node.respond_to?(:session) node.session.using_wait_time(0) { @filter_block.call(node) } else @filter_block.call(node) end end def filter_set(name) ::Capybara::Selector::FilterSet[name] end def node_filters if options.key?(:filter_set) filter_set(options[:filter_set]) else @selector end.node_filters end def expression_filters filters = @selector.expression_filters filters.merge filter_set(options[:filter_set]).expression_filters if options.key?(:filter_set) filters end def ordered_results(results) case @order when :reverse results.reverse else results end end def custom_keys @custom_keys ||= node_filters.keys + expression_filters.keys end def assert_valid_keys unless VALID_MATCH.include?(match) raise ArgumentError, "Invalid option #{match.inspect} for :match, should be one of #{VALID_MATCH.map(&:inspect).join(', ')}" end unhandled_options = @options.keys.reject do |option_name| valid_keys.include?(option_name) || expression_filters.any? { |_name, ef| ef.handles_option? option_name } || node_filters.any? { |_name, nf| nf.handles_option? option_name } end return if unhandled_options.empty? invalid_names = unhandled_options.map(&:inspect).join(', ') valid_names = (valid_keys - [:allow_self]).map(&:inspect).join(', ') raise ArgumentError, "Invalid option(s) #{invalid_names}, should be one of #{valid_names}" end def filtered_expression(expr) conditions = {} conditions[:id] = options[:id] if use_default_id_filter? conditions[:class] = options[:class] if use_default_class_filter? conditions[:style] = options[:style] if use_default_style_filter? && !options[:style].is_a?(Hash) builder(expr).add_attribute_conditions(**conditions) end def use_default_id_filter? options.key?(:id) && !custom_keys.include?(:id) end def use_default_class_filter? options.key?(:class) && !custom_keys.include?(:class) end def use_default_style_filter? options.key?(:style) && !custom_keys.include?(:style) end def use_default_focused_filter? options.key?(:focused) && !custom_keys.include?(:focused) end def use_spatial_filter? options.values_at(*SPATIAL_KEYS).compact.any? end def apply_expression_filters(expression) unapplied_options = options.keys - valid_keys expression_filters.inject(expression) do |expr, (name, ef)| next expr unless apply_filter?(ef) if ef.matcher? unapplied_options.select(&ef.method(:handles_option?)).inject(expr) do |memo, option_name| unapplied_options.delete(option_name) ef.apply_filter(memo, option_name, options[option_name], @selector) end elsif options.key?(name) unapplied_options.delete(name) ef.apply_filter(expr, name, options[name], @selector) elsif ef.default? ef.apply_filter(expr, name, ef.default, @selector) else expr end end end def warn_exact_usage return unless options.key?(:exact) && !supports_exact? warn "The :exact option only has an effect on queries using the XPath#is method. Using it with the query \"#{expression}\" has no effect." end def exact_text options.fetch(:exact_text, session_options.exact_text) end def describe_within? @resolved_node && !document?(@resolved_node) && !simple_root?(@resolved_node) end def document?(node) node.is_a?(::Capybara::Node::Document) end def simple_root?(node) node.is_a?(::Capybara::Node::Simple) && node.path == '/' end def apply_filter?(filter) filter.format.nil? || (filter.format == selector_format) end def matches_locator_filter?(node) return true unless @selector.locator_filter && apply_filter?(@selector.locator_filter) @selector.locator_filter.matches?(node, @locator, @selector, exact: exact?) end def matches_system_filters?(node) applied_filters << :system matches_visibility_filters?(node) && matches_id_filter?(node) && matches_class_filter?(node) && matches_style_filter?(node) && matches_focused_filter?(node) && matches_text_filter?(node) && matches_exact_text_filter?(node) end def matches_spatial_filters?(node) applied_filters << :spatial return true unless use_spatial_filter? node_rect = Rectangle.new(node.initial_cache[:position] || node.rect) if options[:above] el_rect = rect_cache(options[:above]) return false unless node_rect.above? el_rect end if options[:below] el_rect = rect_cache(options[:below]) return false unless node_rect.below? el_rect end if options[:left_of] el_rect = rect_cache(options[:left_of]) return false unless node_rect.left_of? el_rect end if options[:right_of] el_rect = rect_cache(options[:right_of]) return false unless node_rect.right_of? el_rect end if options[:near] return false if node == options[:near] el_rect = rect_cache(options[:near]) return false unless node_rect.near? el_rect end true end def matches_id_filter?(node) return true unless use_default_id_filter? && options[:id].is_a?(Regexp) options[:id].match? node[:id] end def matches_class_filter?(node) return true unless use_default_class_filter? && need_to_process_classes? if options[:class].is_a? Regexp options[:class].match? node[:class] else classes = (node[:class] || '').split options[:class].select { |c| c.is_a? Regexp }.all? do |r| classes.any? { |cls| r.match? cls } end end end def matches_focused_filter?(node) return true unless use_default_focused_filter? (node == node.session.active_element) == options[:focused] end def need_to_process_classes? case options[:class] when Regexp then true when Array then options[:class].any?(Regexp) else false end end def matches_style_filter?(node) case options[:style] when String, nil true when Regexp options[:style].match? node[:style] when Hash matches_style?(node, options[:style]) end end def matches_style?(node, styles) @actual_styles = node.initial_cache[:style] || node.style(*styles.keys) styles.all? do |style, value| if value.is_a? Regexp value.match? @actual_styles[style.to_s] else @actual_styles[style.to_s] == value end end end def matches_text_filter?(node) value = options[:text] return true unless value return matches_text_exactly?(node, value) if exact_text == true && !value.is_a?(Regexp) regexp = value.is_a?(Regexp) ? value : Regexp.escape(value.to_s) matches_text_regexp?(node, regexp) end def matches_exact_text_filter?(node) case exact_text when String, Regexp matches_text_exactly?(node, exact_text) else true end end def matches_visibility_filters?(node) obscured = options[:obscured] return (visible != :hidden) && (node.initial_cache[:visible] != false) && !node.obscured? if obscured == false vis = case visible when :visible node.initial_cache[:visible] || (node.initial_cache[:visible].nil? && node.visible?) when :hidden # TODO: check why the 'visbile' cache spelling mistake wasn't caught in a test # (node.initial_cache[:visible] == false) || (node.initial_cache[:visbile].nil? && !node.visible?) (node.initial_cache[:visible] == false) || (node.initial_cache[:visible].nil? && !node.visible?) else true end vis && case obscured when true node.obscured? when false !node.obscured? else true end end def matches_text_exactly?(node, value) regexp = value.is_a?(Regexp) ? value : /\A#{Regexp.escape(value.to_s)}\z/ matches_text_regexp(node, regexp).then { |m| m&.pre_match == '' && m&.post_match == '' } end def normalize_ws options.fetch(:normalize_ws, session_options.default_normalize_ws) end def matches_text_regexp(node, regexp) text_visible = visible text_visible = :all if text_visible == :hidden node.text(text_visible, normalize_ws: normalize_ws).match(regexp) end def matches_text_regexp?(node, regexp) !matches_text_regexp(node, regexp).nil? end def default_visibility @selector.default_visibility(session_options.ignore_hidden_elements, options) end def builder(expr) selector.builder(expr) end def position_cache(key) @filter_cache[key][:position] ||= key.rect end def rect_cache(key) @filter_cache[key][:rect] ||= Rectangle.new(position_cache(key)) end class Rectangle attr_reader :top, :bottom, :left, :right def initialize(position) # rubocop:disable Style/RescueModifier @top = position['top'] rescue position['y'] @bottom = position['bottom'] rescue (@top + position['height']) @left = position['left'] rescue position['x'] @right = position['right'] rescue (@left + position['width']) # rubocop:enable Style/RescueModifier end def distance(other) distance = Float::INFINITY line_segments.each do |ls1| other.line_segments.each do |ls2| distance = [ distance, distance_segment_segment(*ls1, *ls2) ].min end end distance end def above?(other) bottom <= other.top end def below?(other) top >= other.bottom end def left_of?(other) right <= other.left end def right_of?(other) left >= other.right end def near?(other) distance(other) <= 50 end protected def line_segments [ [Vector[top, left], Vector[top, right]], [Vector[top, right], Vector[bottom, left]], [Vector[bottom, left], Vector[bottom, right]], [Vector[bottom, right], Vector[top, left]] ] end private def distance_segment_segment(l1p1, l1p2, l2p1, l2p2) # See http://geomalgorithms.com/a07-_distance.html # rubocop:disable Naming/VariableName u = l1p2 - l1p1 v = l2p2 - l2p1 w = l1p1 - l2p1 a = u.dot u b = u.dot v c = v.dot v d = u.dot w e = v.dot w cap_d = (a * c) - (b**2) sD = tD = cap_d # compute the line parameters of the two closest points if cap_d < Float::EPSILON # the lines are almost parallel sN = 0.0 # force using point P0 on segment S1 sD = 1.0 # to prevent possible division by 0.0 later tN = e tD = c else # get the closest points on the infinite lines sN = (b * e) - (c * d) tN = (a * e) - (b * d) if sN.negative? # sc < 0 => the s=0 edge is visible sN = 0 tN = e tD = c elsif sN > sD # sc > 1 => the s=1 edge is visible sN = sD tN = e + b tD = c end end if tN.negative? # tc < 0 => the t=0 edge is visible tN = 0 # recompute sc for this edge if (-d).negative? sN = 0.0 elsif -d > a sN = sD else sN = -d sD = a end elsif tN > tD # tc > 1 => the t=1 edge is visible tN = tD # recompute sc for this edge if (-d + b).negative? sN = 0.0 elsif (-d + b) > a sN = sD else sN = (-d + b) sD = a end end # finally do the division to get sc and tc sc = sN.abs < Float::EPSILON ? 0.0 : sN / sD tc = tN.abs < Float::EPSILON ? 0.0 : tN / tD # difference of the two closest points dP = w + (u * sc) - (v * tc) Math.sqrt(dP.dot(dP)) # rubocop:enable Naming/VariableName end end private_constant :Rectangle end end end
Ruby
{ "end_line": 589, "name": "matches_visibility_filters?", "signature": "def matches_visibility_filters?(node)", "start_line": 566 }
{ "class_name": "SelectorQuery", "class_signature": "class SelectorQuery < < Queries::BaseQuery", "module": "Capybara" }
distance
capybara/lib/capybara/queries/selector_query.rb
def distance(other) distance = Float::INFINITY line_segments.each do |ls1| other.line_segments.each do |ls2| distance = [ distance, distance_segment_segment(*ls1, *ls2) ].min end end distance end
# frozen_string_literal: true require 'matrix' module Capybara module Queries class SelectorQuery < Queries::BaseQuery attr_reader :expression, :selector, :locator, :options SPATIAL_KEYS = %i[above below left_of right_of near].freeze VALID_KEYS = SPATIAL_KEYS + COUNT_KEYS + %i[text id class style visible obscured exact exact_text normalize_ws match wait filter_set focused] VALID_MATCH = %i[first smart prefer_exact one].freeze def initialize(*args, session_options:, enable_aria_label: session_options.enable_aria_label, enable_aria_role: session_options.enable_aria_role, test_id: session_options.test_id, selector_format: nil, order: nil, **options, &filter_block) @resolved_node = nil @resolved_count = 0 @options = options.dup @order = order @filter_cache = Hash.new { |hsh, key| hsh[key] = {} } if @options[:text].is_a?(Regexp) && [true, false].include?(@options[:exact_text]) Capybara::Helpers.warn( "Boolean 'exact_text' option is not supported when 'text' option is a Regexp - ignoring" ) end super(@options) self.session_options = session_options @selector = Selector.new( find_selector(args[0].is_a?(Symbol) ? args.shift : args[0]), config: { enable_aria_label: enable_aria_label, enable_aria_role: enable_aria_role, test_id: test_id }, format: selector_format ) @locator = args.shift @filter_block = filter_block raise ArgumentError, "Unused parameters passed to #{self.class.name} : #{args}" unless args.empty? @expression = selector.call(@locator, **@options) warn_exact_usage assert_valid_keys end def name; selector.name; end def label; selector.label || selector.name; end def description(only_applied = false) # rubocop:disable Style/OptionalBooleanParameter desc = +'' show_for = show_for_stage(only_applied) if show_for[:any] desc << 'visible ' if visible == :visible desc << 'non-visible ' if visible == :hidden end desc << label.to_s desc << " #{locator.inspect}" unless locator.nil? if show_for[:any] desc << " with#{' exact' if exact_text == true} text #{options[:text].inspect}" if options[:text] desc << " with exact text #{exact_text}" if exact_text.is_a?(String) end desc << " with id #{options[:id]}" if options[:id] desc << " with classes [#{Array(options[:class]).join(',')}]" if options[:class] desc << ' that is focused' if options[:focused] desc << ' that is not focused' if options[:focused] == false desc << case options[:style] when String " with style attribute #{options[:style].inspect}" when Regexp " with style attribute matching #{options[:style].inspect}" when Hash " with styles #{options[:style].inspect}" else '' end %i[above below left_of right_of near].each do |spatial_filter| if options[spatial_filter] && show_for[:spatial] desc << " #{spatial_filter} #{options[spatial_filter] rescue '<ERROR>'}" # rubocop:disable Style/RescueModifier end end desc << selector.description(node_filters: show_for[:node], **options) desc << ' that also matches the custom filter block' if @filter_block && show_for[:node] desc << " within #{@resolved_node.inspect}" if describe_within? if locator.is_a?(String) && locator.start_with?('#', './/', '//') && !selector.raw_locator? desc << "\nNote: It appears you may be passing a CSS selector or XPath expression rather than a locator. " \ "Please see the documentation for acceptable locator values.\n\n" end desc end def applied_description description(true) end def matches_filters?(node, node_filter_errors = []) return true if (@resolved_node&.== node) && options[:allow_self] matches_locator_filter?(node) && matches_system_filters?(node) && matches_spatial_filters?(node) && matches_node_filters?(node, node_filter_errors) && matches_filter_block?(node) rescue *(node.respond_to?(:session) ? node.session.driver.invalid_element_errors : []) false end def visible case (vis = options.fetch(:visible) { default_visibility }) when true then :visible when false then :all else vis end end def exact? supports_exact? ? options.fetch(:exact, session_options.exact) : false end def match options.fetch(:match, session_options.match) end def xpath(exact = nil) exact = exact? if exact.nil? expr = apply_expression_filters(@expression) expr = exact ? expr.to_xpath(:exact) : expr.to_s if expr.respond_to?(:to_xpath) expr = filtered_expression(expr) expr = "(#{expr})[#{xpath_text_conditions}]" if try_text_match_in_expression? expr end def css filtered_expression(apply_expression_filters(@expression)) end # @api private def resolve_for(node, exact = nil) applied_filters.clear @filter_cache.clear @resolved_node = node @resolved_count += 1 node.synchronize do children = find_nodes_by_selector_format(node, exact).map(&method(:to_element)) Capybara::Result.new(ordered_results(children), self) end end # @api private def supports_exact? return @expression.respond_to? :to_xpath if @selector.supports_exact?.nil? @selector.supports_exact? end def failure_message "expected to find #{applied_description}" << count_message end def negative_failure_message "expected not to find #{applied_description}" << count_message end private def selector_format @selector.format end def matching_text options[:text] || options[:exact_text] end def text_fragments (text = matching_text).is_a?(String) ? text.split : [] end def xpath_text_conditions case (text = matching_text) when String text.split.map { |txt| XPath.contains(txt) }.reduce(&:&) when Regexp condition = XPath.current condition = condition.uppercase if text.casefold? Selector::RegexpDisassembler.new(text).alternated_substrings.map do |strs| strs.flat_map(&:split).map { |str| condition.contains(str) }.reduce(:&) end.reduce(:|) end end def try_text_match_in_expression? first_try? && matching_text && @resolved_node.is_a?(Capybara::Node::Base) && @resolved_node.session&.driver&.wait? end def first_try? @resolved_count == 1 end def show_for_stage(only_applied) lambda do |stage = :any| !only_applied || (stage == :any ? applied_filters.any? : applied_filters.include?(stage)) end end def applied_filters @applied_filters ||= [] end def find_selector(locator) case locator when Symbol then Selector[locator] else Selector.for(locator) end || Selector[session_options.default_selector] end def find_nodes_by_selector_format(node, exact) hints = {} hints[:uses_visibility] = true unless visible == :all hints[:texts] = text_fragments unless selector_format == :xpath hints[:styles] = options[:style] if use_default_style_filter? hints[:position] = true if use_spatial_filter? case selector_format when :css if node.method(:find_css).arity == 1 node.find_css(css) else node.find_css(css, **hints) end when :xpath if node.method(:find_xpath).arity == 1 node.find_xpath(xpath(exact)) else node.find_xpath(xpath(exact), **hints) end else raise ArgumentError, "Unknown format: #{selector_format}" end end def to_element(node) if @resolved_node.is_a?(Capybara::Node::Base) Capybara::Node::Element.new(@resolved_node.session, node, @resolved_node, self) else Capybara::Node::Simple.new(node) end end def valid_keys (VALID_KEYS + custom_keys).uniq end def matches_node_filters?(node, errors) applied_filters << :node unapplied_options = options.keys - valid_keys @selector.with_filter_errors(errors) do node_filters.all? do |filter_name, filter| next true unless apply_filter?(filter) if filter.matcher? unapplied_options.select { |option_name| filter.handles_option?(option_name) }.all? do |option_name| unapplied_options.delete(option_name) filter.matches?(node, option_name, options[option_name], @selector) end elsif options.key?(filter_name) unapplied_options.delete(filter_name) filter.matches?(node, filter_name, options[filter_name], @selector) elsif filter.default? filter.matches?(node, filter_name, filter.default, @selector) else true end end end end def matches_filter_block?(node) return true unless @filter_block if node.respond_to?(:session) node.session.using_wait_time(0) { @filter_block.call(node) } else @filter_block.call(node) end end def filter_set(name) ::Capybara::Selector::FilterSet[name] end def node_filters if options.key?(:filter_set) filter_set(options[:filter_set]) else @selector end.node_filters end def expression_filters filters = @selector.expression_filters filters.merge filter_set(options[:filter_set]).expression_filters if options.key?(:filter_set) filters end def ordered_results(results) case @order when :reverse results.reverse else results end end def custom_keys @custom_keys ||= node_filters.keys + expression_filters.keys end def assert_valid_keys unless VALID_MATCH.include?(match) raise ArgumentError, "Invalid option #{match.inspect} for :match, should be one of #{VALID_MATCH.map(&:inspect).join(', ')}" end unhandled_options = @options.keys.reject do |option_name| valid_keys.include?(option_name) || expression_filters.any? { |_name, ef| ef.handles_option? option_name } || node_filters.any? { |_name, nf| nf.handles_option? option_name } end return if unhandled_options.empty? invalid_names = unhandled_options.map(&:inspect).join(', ') valid_names = (valid_keys - [:allow_self]).map(&:inspect).join(', ') raise ArgumentError, "Invalid option(s) #{invalid_names}, should be one of #{valid_names}" end def filtered_expression(expr) conditions = {} conditions[:id] = options[:id] if use_default_id_filter? conditions[:class] = options[:class] if use_default_class_filter? conditions[:style] = options[:style] if use_default_style_filter? && !options[:style].is_a?(Hash) builder(expr).add_attribute_conditions(**conditions) end def use_default_id_filter? options.key?(:id) && !custom_keys.include?(:id) end def use_default_class_filter? options.key?(:class) && !custom_keys.include?(:class) end def use_default_style_filter? options.key?(:style) && !custom_keys.include?(:style) end def use_default_focused_filter? options.key?(:focused) && !custom_keys.include?(:focused) end def use_spatial_filter? options.values_at(*SPATIAL_KEYS).compact.any? end def apply_expression_filters(expression) unapplied_options = options.keys - valid_keys expression_filters.inject(expression) do |expr, (name, ef)| next expr unless apply_filter?(ef) if ef.matcher? unapplied_options.select(&ef.method(:handles_option?)).inject(expr) do |memo, option_name| unapplied_options.delete(option_name) ef.apply_filter(memo, option_name, options[option_name], @selector) end elsif options.key?(name) unapplied_options.delete(name) ef.apply_filter(expr, name, options[name], @selector) elsif ef.default? ef.apply_filter(expr, name, ef.default, @selector) else expr end end end def warn_exact_usage return unless options.key?(:exact) && !supports_exact? warn "The :exact option only has an effect on queries using the XPath#is method. Using it with the query \"#{expression}\" has no effect." end def exact_text options.fetch(:exact_text, session_options.exact_text) end def describe_within? @resolved_node && !document?(@resolved_node) && !simple_root?(@resolved_node) end def document?(node) node.is_a?(::Capybara::Node::Document) end def simple_root?(node) node.is_a?(::Capybara::Node::Simple) && node.path == '/' end def apply_filter?(filter) filter.format.nil? || (filter.format == selector_format) end def matches_locator_filter?(node) return true unless @selector.locator_filter && apply_filter?(@selector.locator_filter) @selector.locator_filter.matches?(node, @locator, @selector, exact: exact?) end def matches_system_filters?(node) applied_filters << :system matches_visibility_filters?(node) && matches_id_filter?(node) && matches_class_filter?(node) && matches_style_filter?(node) && matches_focused_filter?(node) && matches_text_filter?(node) && matches_exact_text_filter?(node) end def matches_spatial_filters?(node) applied_filters << :spatial return true unless use_spatial_filter? node_rect = Rectangle.new(node.initial_cache[:position] || node.rect) if options[:above] el_rect = rect_cache(options[:above]) return false unless node_rect.above? el_rect end if options[:below] el_rect = rect_cache(options[:below]) return false unless node_rect.below? el_rect end if options[:left_of] el_rect = rect_cache(options[:left_of]) return false unless node_rect.left_of? el_rect end if options[:right_of] el_rect = rect_cache(options[:right_of]) return false unless node_rect.right_of? el_rect end if options[:near] return false if node == options[:near] el_rect = rect_cache(options[:near]) return false unless node_rect.near? el_rect end true end def matches_id_filter?(node) return true unless use_default_id_filter? && options[:id].is_a?(Regexp) options[:id].match? node[:id] end def matches_class_filter?(node) return true unless use_default_class_filter? && need_to_process_classes? if options[:class].is_a? Regexp options[:class].match? node[:class] else classes = (node[:class] || '').split options[:class].select { |c| c.is_a? Regexp }.all? do |r| classes.any? { |cls| r.match? cls } end end end def matches_focused_filter?(node) return true unless use_default_focused_filter? (node == node.session.active_element) == options[:focused] end def need_to_process_classes? case options[:class] when Regexp then true when Array then options[:class].any?(Regexp) else false end end def matches_style_filter?(node) case options[:style] when String, nil true when Regexp options[:style].match? node[:style] when Hash matches_style?(node, options[:style]) end end def matches_style?(node, styles) @actual_styles = node.initial_cache[:style] || node.style(*styles.keys) styles.all? do |style, value| if value.is_a? Regexp value.match? @actual_styles[style.to_s] else @actual_styles[style.to_s] == value end end end def matches_text_filter?(node) value = options[:text] return true unless value return matches_text_exactly?(node, value) if exact_text == true && !value.is_a?(Regexp) regexp = value.is_a?(Regexp) ? value : Regexp.escape(value.to_s) matches_text_regexp?(node, regexp) end def matches_exact_text_filter?(node) case exact_text when String, Regexp matches_text_exactly?(node, exact_text) else true end end def matches_visibility_filters?(node) obscured = options[:obscured] return (visible != :hidden) && (node.initial_cache[:visible] != false) && !node.obscured? if obscured == false vis = case visible when :visible node.initial_cache[:visible] || (node.initial_cache[:visible].nil? && node.visible?) when :hidden # TODO: check why the 'visbile' cache spelling mistake wasn't caught in a test # (node.initial_cache[:visible] == false) || (node.initial_cache[:visbile].nil? && !node.visible?) (node.initial_cache[:visible] == false) || (node.initial_cache[:visible].nil? && !node.visible?) else true end vis && case obscured when true node.obscured? when false !node.obscured? else true end end def matches_text_exactly?(node, value) regexp = value.is_a?(Regexp) ? value : /\A#{Regexp.escape(value.to_s)}\z/ matches_text_regexp(node, regexp).then { |m| m&.pre_match == '' && m&.post_match == '' } end def normalize_ws options.fetch(:normalize_ws, session_options.default_normalize_ws) end def matches_text_regexp(node, regexp) text_visible = visible text_visible = :all if text_visible == :hidden node.text(text_visible, normalize_ws: normalize_ws).match(regexp) end def matches_text_regexp?(node, regexp) !matches_text_regexp(node, regexp).nil? end def default_visibility @selector.default_visibility(session_options.ignore_hidden_elements, options) end def builder(expr) selector.builder(expr) end def position_cache(key) @filter_cache[key][:position] ||= key.rect end def rect_cache(key) @filter_cache[key][:rect] ||= Rectangle.new(position_cache(key)) end class Rectangle attr_reader :top, :bottom, :left, :right def initialize(position) # rubocop:disable Style/RescueModifier @top = position['top'] rescue position['y'] @bottom = position['bottom'] rescue (@top + position['height']) @left = position['left'] rescue position['x'] @right = position['right'] rescue (@left + position['width']) # rubocop:enable Style/RescueModifier end def distance(other) distance = Float::INFINITY line_segments.each do |ls1| other.line_segments.each do |ls2| distance = [ distance, distance_segment_segment(*ls1, *ls2) ].min end end distance end def above?(other) bottom <= other.top end def below?(other) top >= other.bottom end def left_of?(other) right <= other.left end def right_of?(other) left >= other.right end def near?(other) distance(other) <= 50 end protected def line_segments [ [Vector[top, left], Vector[top, right]], [Vector[top, right], Vector[bottom, left]], [Vector[bottom, left], Vector[bottom, right]], [Vector[bottom, right], Vector[top, left]] ] end private def distance_segment_segment(l1p1, l1p2, l2p1, l2p2) # See http://geomalgorithms.com/a07-_distance.html # rubocop:disable Naming/VariableName u = l1p2 - l1p1 v = l2p2 - l2p1 w = l1p1 - l2p1 a = u.dot u b = u.dot v c = v.dot v d = u.dot w e = v.dot w cap_d = (a * c) - (b**2) sD = tD = cap_d # compute the line parameters of the two closest points if cap_d < Float::EPSILON # the lines are almost parallel sN = 0.0 # force using point P0 on segment S1 sD = 1.0 # to prevent possible division by 0.0 later tN = e tD = c else # get the closest points on the infinite lines sN = (b * e) - (c * d) tN = (a * e) - (b * d) if sN.negative? # sc < 0 => the s=0 edge is visible sN = 0 tN = e tD = c elsif sN > sD # sc > 1 => the s=1 edge is visible sN = sD tN = e + b tD = c end end if tN.negative? # tc < 0 => the t=0 edge is visible tN = 0 # recompute sc for this edge if (-d).negative? sN = 0.0 elsif -d > a sN = sD else sN = -d sD = a end elsif tN > tD # tc > 1 => the t=1 edge is visible tN = tD # recompute sc for this edge if (-d + b).negative? sN = 0.0 elsif (-d + b) > a sN = sD else sN = (-d + b) sD = a end end # finally do the division to get sc and tc sc = sN.abs < Float::EPSILON ? 0.0 : sN / sD tc = tN.abs < Float::EPSILON ? 0.0 : tN / tD # difference of the two closest points dP = w + (u * sc) - (v * tc) Math.sqrt(dP.dot(dP)) # rubocop:enable Naming/VariableName end end private_constant :Rectangle end end end
Ruby
{ "end_line": 651, "name": "distance", "signature": "def distance(other)", "start_line": 638 }
{ "class_name": "SelectorQuery", "class_signature": "class SelectorQuery < < Queries::BaseQuery", "module": "Capybara" }
distance_segment_segment
capybara/lib/capybara/queries/selector_query.rb
def distance_segment_segment(l1p1, l1p2, l2p1, l2p2) # See http://geomalgorithms.com/a07-_distance.html # rubocop:disable Naming/VariableName u = l1p2 - l1p1 v = l2p2 - l2p1 w = l1p1 - l2p1 a = u.dot u b = u.dot v c = v.dot v d = u.dot w e = v.dot w cap_d = (a * c) - (b**2) sD = tD = cap_d # compute the line parameters of the two closest points if cap_d < Float::EPSILON # the lines are almost parallel sN = 0.0 # force using point P0 on segment S1 sD = 1.0 # to prevent possible division by 0.0 later tN = e tD = c else # get the closest points on the infinite lines sN = (b * e) - (c * d) tN = (a * e) - (b * d) if sN.negative? # sc < 0 => the s=0 edge is visible sN = 0 tN = e tD = c elsif sN > sD # sc > 1 => the s=1 edge is visible sN = sD tN = e + b tD = c end end if tN.negative? # tc < 0 => the t=0 edge is visible tN = 0 # recompute sc for this edge if (-d).negative? sN = 0.0 elsif -d > a sN = sD else sN = -d sD = a end elsif tN > tD # tc > 1 => the t=1 edge is visible tN = tD # recompute sc for this edge if (-d + b).negative? sN = 0.0 elsif (-d + b) > a sN = sD else sN = (-d + b) sD = a end end # finally do the division to get sc and tc sc = sN.abs < Float::EPSILON ? 0.0 : sN / sD tc = tN.abs < Float::EPSILON ? 0.0 : tN / tD # difference of the two closest points dP = w + (u * sc) - (v * tc) Math.sqrt(dP.dot(dP)) # rubocop:enable Naming/VariableName end
# frozen_string_literal: true require 'matrix' module Capybara module Queries class SelectorQuery < Queries::BaseQuery attr_reader :expression, :selector, :locator, :options SPATIAL_KEYS = %i[above below left_of right_of near].freeze VALID_KEYS = SPATIAL_KEYS + COUNT_KEYS + %i[text id class style visible obscured exact exact_text normalize_ws match wait filter_set focused] VALID_MATCH = %i[first smart prefer_exact one].freeze def initialize(*args, session_options:, enable_aria_label: session_options.enable_aria_label, enable_aria_role: session_options.enable_aria_role, test_id: session_options.test_id, selector_format: nil, order: nil, **options, &filter_block) @resolved_node = nil @resolved_count = 0 @options = options.dup @order = order @filter_cache = Hash.new { |hsh, key| hsh[key] = {} } if @options[:text].is_a?(Regexp) && [true, false].include?(@options[:exact_text]) Capybara::Helpers.warn( "Boolean 'exact_text' option is not supported when 'text' option is a Regexp - ignoring" ) end super(@options) self.session_options = session_options @selector = Selector.new( find_selector(args[0].is_a?(Symbol) ? args.shift : args[0]), config: { enable_aria_label: enable_aria_label, enable_aria_role: enable_aria_role, test_id: test_id }, format: selector_format ) @locator = args.shift @filter_block = filter_block raise ArgumentError, "Unused parameters passed to #{self.class.name} : #{args}" unless args.empty? @expression = selector.call(@locator, **@options) warn_exact_usage assert_valid_keys end def name; selector.name; end def label; selector.label || selector.name; end def description(only_applied = false) # rubocop:disable Style/OptionalBooleanParameter desc = +'' show_for = show_for_stage(only_applied) if show_for[:any] desc << 'visible ' if visible == :visible desc << 'non-visible ' if visible == :hidden end desc << label.to_s desc << " #{locator.inspect}" unless locator.nil? if show_for[:any] desc << " with#{' exact' if exact_text == true} text #{options[:text].inspect}" if options[:text] desc << " with exact text #{exact_text}" if exact_text.is_a?(String) end desc << " with id #{options[:id]}" if options[:id] desc << " with classes [#{Array(options[:class]).join(',')}]" if options[:class] desc << ' that is focused' if options[:focused] desc << ' that is not focused' if options[:focused] == false desc << case options[:style] when String " with style attribute #{options[:style].inspect}" when Regexp " with style attribute matching #{options[:style].inspect}" when Hash " with styles #{options[:style].inspect}" else '' end %i[above below left_of right_of near].each do |spatial_filter| if options[spatial_filter] && show_for[:spatial] desc << " #{spatial_filter} #{options[spatial_filter] rescue '<ERROR>'}" # rubocop:disable Style/RescueModifier end end desc << selector.description(node_filters: show_for[:node], **options) desc << ' that also matches the custom filter block' if @filter_block && show_for[:node] desc << " within #{@resolved_node.inspect}" if describe_within? if locator.is_a?(String) && locator.start_with?('#', './/', '//') && !selector.raw_locator? desc << "\nNote: It appears you may be passing a CSS selector or XPath expression rather than a locator. " \ "Please see the documentation for acceptable locator values.\n\n" end desc end def applied_description description(true) end def matches_filters?(node, node_filter_errors = []) return true if (@resolved_node&.== node) && options[:allow_self] matches_locator_filter?(node) && matches_system_filters?(node) && matches_spatial_filters?(node) && matches_node_filters?(node, node_filter_errors) && matches_filter_block?(node) rescue *(node.respond_to?(:session) ? node.session.driver.invalid_element_errors : []) false end def visible case (vis = options.fetch(:visible) { default_visibility }) when true then :visible when false then :all else vis end end def exact? supports_exact? ? options.fetch(:exact, session_options.exact) : false end def match options.fetch(:match, session_options.match) end def xpath(exact = nil) exact = exact? if exact.nil? expr = apply_expression_filters(@expression) expr = exact ? expr.to_xpath(:exact) : expr.to_s if expr.respond_to?(:to_xpath) expr = filtered_expression(expr) expr = "(#{expr})[#{xpath_text_conditions}]" if try_text_match_in_expression? expr end def css filtered_expression(apply_expression_filters(@expression)) end # @api private def resolve_for(node, exact = nil) applied_filters.clear @filter_cache.clear @resolved_node = node @resolved_count += 1 node.synchronize do children = find_nodes_by_selector_format(node, exact).map(&method(:to_element)) Capybara::Result.new(ordered_results(children), self) end end # @api private def supports_exact? return @expression.respond_to? :to_xpath if @selector.supports_exact?.nil? @selector.supports_exact? end def failure_message "expected to find #{applied_description}" << count_message end def negative_failure_message "expected not to find #{applied_description}" << count_message end private def selector_format @selector.format end def matching_text options[:text] || options[:exact_text] end def text_fragments (text = matching_text).is_a?(String) ? text.split : [] end def xpath_text_conditions case (text = matching_text) when String text.split.map { |txt| XPath.contains(txt) }.reduce(&:&) when Regexp condition = XPath.current condition = condition.uppercase if text.casefold? Selector::RegexpDisassembler.new(text).alternated_substrings.map do |strs| strs.flat_map(&:split).map { |str| condition.contains(str) }.reduce(:&) end.reduce(:|) end end def try_text_match_in_expression? first_try? && matching_text && @resolved_node.is_a?(Capybara::Node::Base) && @resolved_node.session&.driver&.wait? end def first_try? @resolved_count == 1 end def show_for_stage(only_applied) lambda do |stage = :any| !only_applied || (stage == :any ? applied_filters.any? : applied_filters.include?(stage)) end end def applied_filters @applied_filters ||= [] end def find_selector(locator) case locator when Symbol then Selector[locator] else Selector.for(locator) end || Selector[session_options.default_selector] end def find_nodes_by_selector_format(node, exact) hints = {} hints[:uses_visibility] = true unless visible == :all hints[:texts] = text_fragments unless selector_format == :xpath hints[:styles] = options[:style] if use_default_style_filter? hints[:position] = true if use_spatial_filter? case selector_format when :css if node.method(:find_css).arity == 1 node.find_css(css) else node.find_css(css, **hints) end when :xpath if node.method(:find_xpath).arity == 1 node.find_xpath(xpath(exact)) else node.find_xpath(xpath(exact), **hints) end else raise ArgumentError, "Unknown format: #{selector_format}" end end def to_element(node) if @resolved_node.is_a?(Capybara::Node::Base) Capybara::Node::Element.new(@resolved_node.session, node, @resolved_node, self) else Capybara::Node::Simple.new(node) end end def valid_keys (VALID_KEYS + custom_keys).uniq end def matches_node_filters?(node, errors) applied_filters << :node unapplied_options = options.keys - valid_keys @selector.with_filter_errors(errors) do node_filters.all? do |filter_name, filter| next true unless apply_filter?(filter) if filter.matcher? unapplied_options.select { |option_name| filter.handles_option?(option_name) }.all? do |option_name| unapplied_options.delete(option_name) filter.matches?(node, option_name, options[option_name], @selector) end elsif options.key?(filter_name) unapplied_options.delete(filter_name) filter.matches?(node, filter_name, options[filter_name], @selector) elsif filter.default? filter.matches?(node, filter_name, filter.default, @selector) else true end end end end def matches_filter_block?(node) return true unless @filter_block if node.respond_to?(:session) node.session.using_wait_time(0) { @filter_block.call(node) } else @filter_block.call(node) end end def filter_set(name) ::Capybara::Selector::FilterSet[name] end def node_filters if options.key?(:filter_set) filter_set(options[:filter_set]) else @selector end.node_filters end def expression_filters filters = @selector.expression_filters filters.merge filter_set(options[:filter_set]).expression_filters if options.key?(:filter_set) filters end def ordered_results(results) case @order when :reverse results.reverse else results end end def custom_keys @custom_keys ||= node_filters.keys + expression_filters.keys end def assert_valid_keys unless VALID_MATCH.include?(match) raise ArgumentError, "Invalid option #{match.inspect} for :match, should be one of #{VALID_MATCH.map(&:inspect).join(', ')}" end unhandled_options = @options.keys.reject do |option_name| valid_keys.include?(option_name) || expression_filters.any? { |_name, ef| ef.handles_option? option_name } || node_filters.any? { |_name, nf| nf.handles_option? option_name } end return if unhandled_options.empty? invalid_names = unhandled_options.map(&:inspect).join(', ') valid_names = (valid_keys - [:allow_self]).map(&:inspect).join(', ') raise ArgumentError, "Invalid option(s) #{invalid_names}, should be one of #{valid_names}" end def filtered_expression(expr) conditions = {} conditions[:id] = options[:id] if use_default_id_filter? conditions[:class] = options[:class] if use_default_class_filter? conditions[:style] = options[:style] if use_default_style_filter? && !options[:style].is_a?(Hash) builder(expr).add_attribute_conditions(**conditions) end def use_default_id_filter? options.key?(:id) && !custom_keys.include?(:id) end def use_default_class_filter? options.key?(:class) && !custom_keys.include?(:class) end def use_default_style_filter? options.key?(:style) && !custom_keys.include?(:style) end def use_default_focused_filter? options.key?(:focused) && !custom_keys.include?(:focused) end def use_spatial_filter? options.values_at(*SPATIAL_KEYS).compact.any? end def apply_expression_filters(expression) unapplied_options = options.keys - valid_keys expression_filters.inject(expression) do |expr, (name, ef)| next expr unless apply_filter?(ef) if ef.matcher? unapplied_options.select(&ef.method(:handles_option?)).inject(expr) do |memo, option_name| unapplied_options.delete(option_name) ef.apply_filter(memo, option_name, options[option_name], @selector) end elsif options.key?(name) unapplied_options.delete(name) ef.apply_filter(expr, name, options[name], @selector) elsif ef.default? ef.apply_filter(expr, name, ef.default, @selector) else expr end end end def warn_exact_usage return unless options.key?(:exact) && !supports_exact? warn "The :exact option only has an effect on queries using the XPath#is method. Using it with the query \"#{expression}\" has no effect." end def exact_text options.fetch(:exact_text, session_options.exact_text) end def describe_within? @resolved_node && !document?(@resolved_node) && !simple_root?(@resolved_node) end def document?(node) node.is_a?(::Capybara::Node::Document) end def simple_root?(node) node.is_a?(::Capybara::Node::Simple) && node.path == '/' end def apply_filter?(filter) filter.format.nil? || (filter.format == selector_format) end def matches_locator_filter?(node) return true unless @selector.locator_filter && apply_filter?(@selector.locator_filter) @selector.locator_filter.matches?(node, @locator, @selector, exact: exact?) end def matches_system_filters?(node) applied_filters << :system matches_visibility_filters?(node) && matches_id_filter?(node) && matches_class_filter?(node) && matches_style_filter?(node) && matches_focused_filter?(node) && matches_text_filter?(node) && matches_exact_text_filter?(node) end def matches_spatial_filters?(node) applied_filters << :spatial return true unless use_spatial_filter? node_rect = Rectangle.new(node.initial_cache[:position] || node.rect) if options[:above] el_rect = rect_cache(options[:above]) return false unless node_rect.above? el_rect end if options[:below] el_rect = rect_cache(options[:below]) return false unless node_rect.below? el_rect end if options[:left_of] el_rect = rect_cache(options[:left_of]) return false unless node_rect.left_of? el_rect end if options[:right_of] el_rect = rect_cache(options[:right_of]) return false unless node_rect.right_of? el_rect end if options[:near] return false if node == options[:near] el_rect = rect_cache(options[:near]) return false unless node_rect.near? el_rect end true end def matches_id_filter?(node) return true unless use_default_id_filter? && options[:id].is_a?(Regexp) options[:id].match? node[:id] end def matches_class_filter?(node) return true unless use_default_class_filter? && need_to_process_classes? if options[:class].is_a? Regexp options[:class].match? node[:class] else classes = (node[:class] || '').split options[:class].select { |c| c.is_a? Regexp }.all? do |r| classes.any? { |cls| r.match? cls } end end end def matches_focused_filter?(node) return true unless use_default_focused_filter? (node == node.session.active_element) == options[:focused] end def need_to_process_classes? case options[:class] when Regexp then true when Array then options[:class].any?(Regexp) else false end end def matches_style_filter?(node) case options[:style] when String, nil true when Regexp options[:style].match? node[:style] when Hash matches_style?(node, options[:style]) end end def matches_style?(node, styles) @actual_styles = node.initial_cache[:style] || node.style(*styles.keys) styles.all? do |style, value| if value.is_a? Regexp value.match? @actual_styles[style.to_s] else @actual_styles[style.to_s] == value end end end def matches_text_filter?(node) value = options[:text] return true unless value return matches_text_exactly?(node, value) if exact_text == true && !value.is_a?(Regexp) regexp = value.is_a?(Regexp) ? value : Regexp.escape(value.to_s) matches_text_regexp?(node, regexp) end def matches_exact_text_filter?(node) case exact_text when String, Regexp matches_text_exactly?(node, exact_text) else true end end def matches_visibility_filters?(node) obscured = options[:obscured] return (visible != :hidden) && (node.initial_cache[:visible] != false) && !node.obscured? if obscured == false vis = case visible when :visible node.initial_cache[:visible] || (node.initial_cache[:visible].nil? && node.visible?) when :hidden # TODO: check why the 'visbile' cache spelling mistake wasn't caught in a test # (node.initial_cache[:visible] == false) || (node.initial_cache[:visbile].nil? && !node.visible?) (node.initial_cache[:visible] == false) || (node.initial_cache[:visible].nil? && !node.visible?) else true end vis && case obscured when true node.obscured? when false !node.obscured? else true end end def matches_text_exactly?(node, value) regexp = value.is_a?(Regexp) ? value : /\A#{Regexp.escape(value.to_s)}\z/ matches_text_regexp(node, regexp).then { |m| m&.pre_match == '' && m&.post_match == '' } end def normalize_ws options.fetch(:normalize_ws, session_options.default_normalize_ws) end def matches_text_regexp(node, regexp) text_visible = visible text_visible = :all if text_visible == :hidden node.text(text_visible, normalize_ws: normalize_ws).match(regexp) end def matches_text_regexp?(node, regexp) !matches_text_regexp(node, regexp).nil? end def default_visibility @selector.default_visibility(session_options.ignore_hidden_elements, options) end def builder(expr) selector.builder(expr) end def position_cache(key) @filter_cache[key][:position] ||= key.rect end def rect_cache(key) @filter_cache[key][:rect] ||= Rectangle.new(position_cache(key)) end class Rectangle attr_reader :top, :bottom, :left, :right def initialize(position) # rubocop:disable Style/RescueModifier @top = position['top'] rescue position['y'] @bottom = position['bottom'] rescue (@top + position['height']) @left = position['left'] rescue position['x'] @right = position['right'] rescue (@left + position['width']) # rubocop:enable Style/RescueModifier end def distance(other) distance = Float::INFINITY line_segments.each do |ls1| other.line_segments.each do |ls2| distance = [ distance, distance_segment_segment(*ls1, *ls2) ].min end end distance end def above?(other) bottom <= other.top end def below?(other) top >= other.bottom end def left_of?(other) right <= other.left end def right_of?(other) left >= other.right end def near?(other) distance(other) <= 50 end protected def line_segments [ [Vector[top, left], Vector[top, right]], [Vector[top, right], Vector[bottom, left]], [Vector[bottom, left], Vector[bottom, right]], [Vector[bottom, right], Vector[top, left]] ] end private def distance_segment_segment(l1p1, l1p2, l2p1, l2p2) # See http://geomalgorithms.com/a07-_distance.html # rubocop:disable Naming/VariableName u = l1p2 - l1p1 v = l2p2 - l2p1 w = l1p1 - l2p1 a = u.dot u b = u.dot v c = v.dot v d = u.dot w e = v.dot w cap_d = (a * c) - (b**2) sD = tD = cap_d # compute the line parameters of the two closest points if cap_d < Float::EPSILON # the lines are almost parallel sN = 0.0 # force using point P0 on segment S1 sD = 1.0 # to prevent possible division by 0.0 later tN = e tD = c else # get the closest points on the infinite lines sN = (b * e) - (c * d) tN = (a * e) - (b * d) if sN.negative? # sc < 0 => the s=0 edge is visible sN = 0 tN = e tD = c elsif sN > sD # sc > 1 => the s=1 edge is visible sN = sD tN = e + b tD = c end end if tN.negative? # tc < 0 => the t=0 edge is visible tN = 0 # recompute sc for this edge if (-d).negative? sN = 0.0 elsif -d > a sN = sD else sN = -d sD = a end elsif tN > tD # tc > 1 => the t=1 edge is visible tN = tD # recompute sc for this edge if (-d + b).negative? sN = 0.0 elsif (-d + b) > a sN = sD else sN = (-d + b) sD = a end end # finally do the division to get sc and tc sc = sN.abs < Float::EPSILON ? 0.0 : sN / sD tc = tN.abs < Float::EPSILON ? 0.0 : tN / tD # difference of the two closest points dP = w + (u * sc) - (v * tc) Math.sqrt(dP.dot(dP)) # rubocop:enable Naming/VariableName end end private_constant :Rectangle end end end
Ruby
{ "end_line": 755, "name": "distance_segment_segment", "signature": "def distance_segment_segment(l1p1, l1p2, l2p1, l2p2)", "start_line": 686 }
{ "class_name": "SelectorQuery", "class_signature": "class SelectorQuery < < Queries::BaseQuery", "module": "Capybara" }
resolve_for
capybara/lib/capybara/queries/sibling_query.rb
def resolve_for(node, exact = nil) @sibling_node = node node.synchronize do scope = node.respond_to?(:session) ? node.session.current_scope : node.find(:xpath, '/*') match_results = super(scope, exact) siblings = node.find_xpath((XPath.preceding_sibling + XPath.following_sibling).to_s) .map(&method(:to_element)) .select { |el| match_results.include?(el) } Capybara::Result.new(ordered_results(siblings), self) end end
# frozen_string_literal: true module Capybara module Queries class SiblingQuery < SelectorQuery # @api private def resolve_for(node, exact = nil) @sibling_node = node node.synchronize do scope = node.respond_to?(:session) ? node.session.current_scope : node.find(:xpath, '/*') match_results = super(scope, exact) siblings = node.find_xpath((XPath.preceding_sibling + XPath.following_sibling).to_s) .map(&method(:to_element)) .select { |el| match_results.include?(el) } Capybara::Result.new(ordered_results(siblings), self) end end def description(applied = false) # rubocop:disable Style/OptionalBooleanParameter desc = super sibling_query = @sibling_node&.instance_variable_get(:@query) desc += " that is a sibling of #{sibling_query.description}" if sibling_query desc end end end end
Ruby
{ "end_line": 17, "name": "resolve_for", "signature": "def resolve_for(node, exact = nil)", "start_line": 7 }
{ "class_name": "SiblingQuery", "class_signature": "class SiblingQuery < < SelectorQuery", "module": "Capybara" }
resolves_for?
capybara/lib/capybara/queries/style_query.rb
def resolves_for?(node) @node = node @actual_styles = node.style(*@expected_styles.keys) @expected_styles.all? do |style, value| if value.is_a? Regexp value.match? @actual_styles[style] else @actual_styles[style] == value end end end
# frozen_string_literal: true module Capybara # @api private module Queries class StyleQuery < BaseQuery def initialize(expected_styles, session_options:, **options) @expected_styles = stringify_keys(expected_styles) @options = options @actual_styles = {} super(@options) self.session_options = session_options assert_valid_keys end def resolves_for?(node) @node = node @actual_styles = node.style(*@expected_styles.keys) @expected_styles.all? do |style, value| if value.is_a? Regexp value.match? @actual_styles[style] else @actual_styles[style] == value end end end def failure_message "Expected node to have styles #{@expected_styles.inspect}. " \ "Actual styles were #{@actual_styles.inspect}" end private def stringify_keys(hsh) hsh.transform_keys(&:to_s) end def valid_keys %i[wait] end end end end
Ruby
{ "end_line": 27, "name": "resolves_for?", "signature": "def resolves_for?(node)", "start_line": 17 }
{ "class_name": "StyleQuery", "class_signature": "class StyleQuery < < BaseQuery", "module": "Capybara" }
initialize
capybara/lib/capybara/queries/text_query.rb
def initialize(type = nil, expected_text, session_options:, **options) # rubocop:disable Style/OptionalArguments @type = type.nil? ? default_type : type raise ArgumentError, "#{@type} is not a valid type for a text query" unless valid_types.include?(@type) @options = options super(@options) self.session_options = session_options if expected_text.nil? && !exact? warn 'Checking for expected text of nil is confusing and/or pointless since it will always match. ' \ "Please specify a string or regexp instead. #{Capybara::Helpers.filter_backtrace(caller)}" end @expected_text = expected_text.is_a?(Regexp) ? expected_text : expected_text.to_s @search_regexp = Capybara::Helpers.to_regexp(@expected_text, exact: exact?) assert_valid_keys end
# frozen_string_literal: true module Capybara # @api private module Queries class TextQuery < BaseQuery def initialize(type = nil, expected_text, session_options:, **options) # rubocop:disable Style/OptionalArguments @type = type.nil? ? default_type : type raise ArgumentError, "#{@type} is not a valid type for a text query" unless valid_types.include?(@type) @options = options super(@options) self.session_options = session_options if expected_text.nil? && !exact? warn 'Checking for expected text of nil is confusing and/or pointless since it will always match. ' \ "Please specify a string or regexp instead. #{Capybara::Helpers.filter_backtrace(caller)}" end @expected_text = expected_text.is_a?(Regexp) ? expected_text : expected_text.to_s @search_regexp = Capybara::Helpers.to_regexp(@expected_text, exact: exact?) assert_valid_keys end def resolve_for(node) @node = node @actual_text = text @count = @actual_text.scan(@search_regexp).size end def failure_message super << build_message(true) end def negative_failure_message super << build_message(false) end def description if @expected_text.is_a?(Regexp) "text matching #{@expected_text.inspect}" else "#{'exact ' if exact?}text #{@expected_text.inspect}" end end private def exact? options.fetch(:exact, session_options.exact_text) end def build_message(report_on_invisible) message = +'' unless (COUNT_KEYS & @options.keys).empty? message << " but found #{@count} #{Capybara::Helpers.declension('time', 'times', @count)}" end message << " in #{@actual_text.inspect}" details_message = [] details_message << case_insensitive_message if @node && check_case_insensitive? details_message << invisible_message if @node && check_visible_text? && report_on_invisible details_message.compact! message << ". (However, #{details_message.join(' and ')}.)" unless details_message.empty? message end def case_insensitive_message insensitive_regexp = Capybara::Helpers.to_regexp(@expected_text, options: Regexp::IGNORECASE) insensitive_count = @actual_text.scan(insensitive_regexp).size return if insensitive_count == @count "it was found #{occurrences insensitive_count} using a case insensitive search" end def invisible_message invisible_text = text(query_type: :all) invisible_count = invisible_text.scan(@search_regexp).size return if invisible_count == @count "it was found #{occurrences invisible_count} including non-visible text" rescue StandardError # An error getting the non-visible text (if element goes out of scope) should not affect the response nil end def valid_keys COUNT_KEYS + %i[wait exact normalize_ws] end def valid_types %i[all visible] end def check_visible_text? @type == :visible end def check_case_insensitive? !@expected_text.is_a?(Regexp) end def text(node: @node, query_type: @type) normalize_ws = options.fetch(:normalize_ws, session_options.default_normalize_ws) node.text(query_type, normalize_ws: normalize_ws) end def default_type Capybara.ignore_hidden_elements || Capybara.visible_text_only ? :visible : :all end end end end
Ruby
{ "end_line": 25, "name": "initialize", "signature": "def initialize(type = nil, expected_text, session_options:, **options) # rubocop:disable Style/OptionalArguments", "start_line": 7 }
{ "class_name": "TextQuery", "class_signature": "class TextQuery < < BaseQuery", "module": "Capybara" }
build_message
capybara/lib/capybara/queries/text_query.rb
def build_message(report_on_invisible) message = +'' unless (COUNT_KEYS & @options.keys).empty? message << " but found #{@count} #{Capybara::Helpers.declension('time', 'times', @count)}" end message << " in #{@actual_text.inspect}" details_message = [] details_message << case_insensitive_message if @node && check_case_insensitive? details_message << invisible_message if @node && check_visible_text? && report_on_invisible details_message.compact! message << ". (However, #{details_message.join(' and ')}.)" unless details_message.empty? message end
# frozen_string_literal: true module Capybara # @api private module Queries class TextQuery < BaseQuery def initialize(type = nil, expected_text, session_options:, **options) # rubocop:disable Style/OptionalArguments @type = type.nil? ? default_type : type raise ArgumentError, "#{@type} is not a valid type for a text query" unless valid_types.include?(@type) @options = options super(@options) self.session_options = session_options if expected_text.nil? && !exact? warn 'Checking for expected text of nil is confusing and/or pointless since it will always match. ' \ "Please specify a string or regexp instead. #{Capybara::Helpers.filter_backtrace(caller)}" end @expected_text = expected_text.is_a?(Regexp) ? expected_text : expected_text.to_s @search_regexp = Capybara::Helpers.to_regexp(@expected_text, exact: exact?) assert_valid_keys end def resolve_for(node) @node = node @actual_text = text @count = @actual_text.scan(@search_regexp).size end def failure_message super << build_message(true) end def negative_failure_message super << build_message(false) end def description if @expected_text.is_a?(Regexp) "text matching #{@expected_text.inspect}" else "#{'exact ' if exact?}text #{@expected_text.inspect}" end end private def exact? options.fetch(:exact, session_options.exact_text) end def build_message(report_on_invisible) message = +'' unless (COUNT_KEYS & @options.keys).empty? message << " but found #{@count} #{Capybara::Helpers.declension('time', 'times', @count)}" end message << " in #{@actual_text.inspect}" details_message = [] details_message << case_insensitive_message if @node && check_case_insensitive? details_message << invisible_message if @node && check_visible_text? && report_on_invisible details_message.compact! message << ". (However, #{details_message.join(' and ')}.)" unless details_message.empty? message end def case_insensitive_message insensitive_regexp = Capybara::Helpers.to_regexp(@expected_text, options: Regexp::IGNORECASE) insensitive_count = @actual_text.scan(insensitive_regexp).size return if insensitive_count == @count "it was found #{occurrences insensitive_count} using a case insensitive search" end def invisible_message invisible_text = text(query_type: :all) invisible_count = invisible_text.scan(@search_regexp).size return if invisible_count == @count "it was found #{occurrences invisible_count} including non-visible text" rescue StandardError # An error getting the non-visible text (if element goes out of scope) should not affect the response nil end def valid_keys COUNT_KEYS + %i[wait exact normalize_ws] end def valid_types %i[all visible] end def check_visible_text? @type == :visible end def check_case_insensitive? !@expected_text.is_a?(Regexp) end def text(node: @node, query_type: @type) normalize_ws = options.fetch(:normalize_ws, session_options.default_normalize_ws) node.text(query_type, normalize_ws: normalize_ws) end def default_type Capybara.ignore_hidden_elements || Capybara.visible_text_only ? :visible : :all end end end end
Ruby
{ "end_line": 69, "name": "build_message", "signature": "def build_message(report_on_invisible)", "start_line": 55 }
{ "class_name": "TextQuery", "class_signature": "class TextQuery < < BaseQuery", "module": "Capybara" }
submit
capybara/lib/capybara/rack_test/browser.rb
def submit(method, path, attributes, content_type: nil) path = request_path if path.nil? || path.empty? uri = build_uri(path) uri.query = '' if method.to_s.casecmp('get').zero? env = { 'HTTP_REFERER' => referer_url } env['CONTENT_TYPE'] = content_type if content_type process_and_follow_redirects( method, uri.to_s, attributes, env ) end
# frozen_string_literal: true class Capybara::RackTest::Browser include ::Rack::Test::Methods attr_reader :driver attr_accessor :current_host def initialize(driver) @driver = driver @current_fragment = nil end def app driver.app end def options driver.options end def visit(path, **attributes) @new_visit_request = true reset_cache! reset_host! process_and_follow_redirects(:get, path, attributes) end def refresh reset_cache! request(last_request.fullpath, last_request.env) end def submit(method, path, attributes, content_type: nil) path = request_path if path.nil? || path.empty? uri = build_uri(path) uri.query = '' if method.to_s.casecmp('get').zero? env = { 'HTTP_REFERER' => referer_url } env['CONTENT_TYPE'] = content_type if content_type process_and_follow_redirects( method, uri.to_s, attributes, env ) end def follow(method, path, **attributes) return if fragment_or_script?(path) process_and_follow_redirects(method, path, attributes, 'HTTP_REFERER' => referer_url) end def process_and_follow_redirects(method, path, attributes = {}, env = {}) @current_fragment = build_uri(path).fragment process(method, path, attributes, env) return unless driver.follow_redirects? driver.redirect_limit.times do if last_response.redirect? if [307, 308].include? last_response.status process(last_request.request_method, last_response['Location'], last_request.params, env) else process(:get, last_response['Location'], {}, env) end end end if last_response.redirect? # rubocop:disable Style/GuardClause raise Capybara::InfiniteRedirectError, "redirected more than #{driver.redirect_limit} times, check for infinite redirects." end end def process(method, path, attributes = {}, env = {}) method = method.downcase new_uri = build_uri(path) @current_scheme, @current_host, @current_port = new_uri.select(:scheme, :host, :port) @current_fragment = new_uri.fragment || @current_fragment reset_cache! @new_visit_request = false send(method, new_uri.to_s, attributes, env.merge(options[:headers] || {})) end def build_uri(path) uri = URI.parse(path) base_uri = base_relative_uri_for(uri) uri.path = base_uri.path + uri.path unless uri.absolute? || uri.path.start_with?('/') if base_uri.absolute? base_uri.merge(uri) else uri.scheme ||= @current_scheme uri.host ||= @current_host uri.port ||= @current_port unless uri.default_port == @current_port uri end end def current_url uri = build_uri(last_request.url) uri.fragment = @current_fragment if @current_fragment uri.to_s rescue Rack::Test::Error '' end def reset_host! uri = URI.parse(driver.session_options.app_host || driver.session_options.default_host) @current_scheme, @current_host, @current_port = uri.select(:scheme, :host, :port) end def reset_cache! @dom = nil end def dom @dom ||= Capybara::HTML(html) end def find(format, selector) if format == :css dom.css(selector, Capybara::RackTest::CSSHandlers.new) else dom.xpath(selector) end.map { |node| Capybara::RackTest::Node.new(self, node) } end def html last_response.body rescue Rack::Test::Error '' end def title dom.title end def last_request raise Rack::Test::Error if @new_visit_request super end def last_response raise Rack::Test::Error if @new_visit_request super end protected def base_href find(:css, 'head > base').first&.[](:href).to_s end def base_relative_uri_for(uri) base_uri = URI.parse(base_href) current_uri = URI.parse(safe_last_request&.url.to_s).tap do |c| c.path.sub!(%r{/[^/]*$}, '/') unless uri.path.empty? c.path = '/' if c.path.empty? end if [current_uri, base_uri].any?(&:absolute?) current_uri.merge(base_uri) else base_uri.path = current_uri.path if base_uri.path.empty? base_uri end end def build_rack_mock_session reset_host! unless current_host Rack::MockSession.new(app, current_host) end def request_path last_request.path rescue Rack::Test::Error '/' end def safe_last_request last_request rescue Rack::Test::Error nil end private def fragment_or_script?(path) path.gsub(/^#{Regexp.escape(request_path)}/, '').start_with?('#') || path.downcase.start_with?('javascript:') end def referer_url build_uri(last_request.url).to_s rescue Rack::Test::Error '' end end
Ruby
{ "end_line": 46, "name": "submit", "signature": "def submit(method, path, attributes, content_type: nil)", "start_line": 34 }
{ "class_name": "Capybara::RackTest::Browser", "class_signature": "class Capybara::RackTest::Browser", "module": "" }
process_and_follow_redirects
capybara/lib/capybara/rack_test/browser.rb
def process_and_follow_redirects(method, path, attributes = {}, env = {}) @current_fragment = build_uri(path).fragment process(method, path, attributes, env) return unless driver.follow_redirects? driver.redirect_limit.times do if last_response.redirect? if [307, 308].include? last_response.status process(last_request.request_method, last_response['Location'], last_request.params, env) else process(:get, last_response['Location'], {}, env) end end end if last_response.redirect? # rubocop:disable Style/GuardClause raise Capybara::InfiniteRedirectError, "redirected more than #{driver.redirect_limit} times, check for infinite redirects." end end
# frozen_string_literal: true class Capybara::RackTest::Browser include ::Rack::Test::Methods attr_reader :driver attr_accessor :current_host def initialize(driver) @driver = driver @current_fragment = nil end def app driver.app end def options driver.options end def visit(path, **attributes) @new_visit_request = true reset_cache! reset_host! process_and_follow_redirects(:get, path, attributes) end def refresh reset_cache! request(last_request.fullpath, last_request.env) end def submit(method, path, attributes, content_type: nil) path = request_path if path.nil? || path.empty? uri = build_uri(path) uri.query = '' if method.to_s.casecmp('get').zero? env = { 'HTTP_REFERER' => referer_url } env['CONTENT_TYPE'] = content_type if content_type process_and_follow_redirects( method, uri.to_s, attributes, env ) end def follow(method, path, **attributes) return if fragment_or_script?(path) process_and_follow_redirects(method, path, attributes, 'HTTP_REFERER' => referer_url) end def process_and_follow_redirects(method, path, attributes = {}, env = {}) @current_fragment = build_uri(path).fragment process(method, path, attributes, env) return unless driver.follow_redirects? driver.redirect_limit.times do if last_response.redirect? if [307, 308].include? last_response.status process(last_request.request_method, last_response['Location'], last_request.params, env) else process(:get, last_response['Location'], {}, env) end end end if last_response.redirect? # rubocop:disable Style/GuardClause raise Capybara::InfiniteRedirectError, "redirected more than #{driver.redirect_limit} times, check for infinite redirects." end end def process(method, path, attributes = {}, env = {}) method = method.downcase new_uri = build_uri(path) @current_scheme, @current_host, @current_port = new_uri.select(:scheme, :host, :port) @current_fragment = new_uri.fragment || @current_fragment reset_cache! @new_visit_request = false send(method, new_uri.to_s, attributes, env.merge(options[:headers] || {})) end def build_uri(path) uri = URI.parse(path) base_uri = base_relative_uri_for(uri) uri.path = base_uri.path + uri.path unless uri.absolute? || uri.path.start_with?('/') if base_uri.absolute? base_uri.merge(uri) else uri.scheme ||= @current_scheme uri.host ||= @current_host uri.port ||= @current_port unless uri.default_port == @current_port uri end end def current_url uri = build_uri(last_request.url) uri.fragment = @current_fragment if @current_fragment uri.to_s rescue Rack::Test::Error '' end def reset_host! uri = URI.parse(driver.session_options.app_host || driver.session_options.default_host) @current_scheme, @current_host, @current_port = uri.select(:scheme, :host, :port) end def reset_cache! @dom = nil end def dom @dom ||= Capybara::HTML(html) end def find(format, selector) if format == :css dom.css(selector, Capybara::RackTest::CSSHandlers.new) else dom.xpath(selector) end.map { |node| Capybara::RackTest::Node.new(self, node) } end def html last_response.body rescue Rack::Test::Error '' end def title dom.title end def last_request raise Rack::Test::Error if @new_visit_request super end def last_response raise Rack::Test::Error if @new_visit_request super end protected def base_href find(:css, 'head > base').first&.[](:href).to_s end def base_relative_uri_for(uri) base_uri = URI.parse(base_href) current_uri = URI.parse(safe_last_request&.url.to_s).tap do |c| c.path.sub!(%r{/[^/]*$}, '/') unless uri.path.empty? c.path = '/' if c.path.empty? end if [current_uri, base_uri].any?(&:absolute?) current_uri.merge(base_uri) else base_uri.path = current_uri.path if base_uri.path.empty? base_uri end end def build_rack_mock_session reset_host! unless current_host Rack::MockSession.new(app, current_host) end def request_path last_request.path rescue Rack::Test::Error '/' end def safe_last_request last_request rescue Rack::Test::Error nil end private def fragment_or_script?(path) path.gsub(/^#{Regexp.escape(request_path)}/, '').start_with?('#') || path.downcase.start_with?('javascript:') end def referer_url build_uri(last_request.url).to_s rescue Rack::Test::Error '' end end
Ruby
{ "end_line": 72, "name": "process_and_follow_redirects", "signature": "def process_and_follow_redirects(method, path, attributes = {}, env = {})", "start_line": 54 }
{ "class_name": "Capybara::RackTest::Browser", "class_signature": "class Capybara::RackTest::Browser", "module": "" }
build_uri
capybara/lib/capybara/rack_test/browser.rb
def build_uri(path) uri = URI.parse(path) base_uri = base_relative_uri_for(uri) uri.path = base_uri.path + uri.path unless uri.absolute? || uri.path.start_with?('/') if base_uri.absolute? base_uri.merge(uri) else uri.scheme ||= @current_scheme uri.host ||= @current_host uri.port ||= @current_port unless uri.default_port == @current_port uri end end
# frozen_string_literal: true class Capybara::RackTest::Browser include ::Rack::Test::Methods attr_reader :driver attr_accessor :current_host def initialize(driver) @driver = driver @current_fragment = nil end def app driver.app end def options driver.options end def visit(path, **attributes) @new_visit_request = true reset_cache! reset_host! process_and_follow_redirects(:get, path, attributes) end def refresh reset_cache! request(last_request.fullpath, last_request.env) end def submit(method, path, attributes, content_type: nil) path = request_path if path.nil? || path.empty? uri = build_uri(path) uri.query = '' if method.to_s.casecmp('get').zero? env = { 'HTTP_REFERER' => referer_url } env['CONTENT_TYPE'] = content_type if content_type process_and_follow_redirects( method, uri.to_s, attributes, env ) end def follow(method, path, **attributes) return if fragment_or_script?(path) process_and_follow_redirects(method, path, attributes, 'HTTP_REFERER' => referer_url) end def process_and_follow_redirects(method, path, attributes = {}, env = {}) @current_fragment = build_uri(path).fragment process(method, path, attributes, env) return unless driver.follow_redirects? driver.redirect_limit.times do if last_response.redirect? if [307, 308].include? last_response.status process(last_request.request_method, last_response['Location'], last_request.params, env) else process(:get, last_response['Location'], {}, env) end end end if last_response.redirect? # rubocop:disable Style/GuardClause raise Capybara::InfiniteRedirectError, "redirected more than #{driver.redirect_limit} times, check for infinite redirects." end end def process(method, path, attributes = {}, env = {}) method = method.downcase new_uri = build_uri(path) @current_scheme, @current_host, @current_port = new_uri.select(:scheme, :host, :port) @current_fragment = new_uri.fragment || @current_fragment reset_cache! @new_visit_request = false send(method, new_uri.to_s, attributes, env.merge(options[:headers] || {})) end def build_uri(path) uri = URI.parse(path) base_uri = base_relative_uri_for(uri) uri.path = base_uri.path + uri.path unless uri.absolute? || uri.path.start_with?('/') if base_uri.absolute? base_uri.merge(uri) else uri.scheme ||= @current_scheme uri.host ||= @current_host uri.port ||= @current_port unless uri.default_port == @current_port uri end end def current_url uri = build_uri(last_request.url) uri.fragment = @current_fragment if @current_fragment uri.to_s rescue Rack::Test::Error '' end def reset_host! uri = URI.parse(driver.session_options.app_host || driver.session_options.default_host) @current_scheme, @current_host, @current_port = uri.select(:scheme, :host, :port) end def reset_cache! @dom = nil end def dom @dom ||= Capybara::HTML(html) end def find(format, selector) if format == :css dom.css(selector, Capybara::RackTest::CSSHandlers.new) else dom.xpath(selector) end.map { |node| Capybara::RackTest::Node.new(self, node) } end def html last_response.body rescue Rack::Test::Error '' end def title dom.title end def last_request raise Rack::Test::Error if @new_visit_request super end def last_response raise Rack::Test::Error if @new_visit_request super end protected def base_href find(:css, 'head > base').first&.[](:href).to_s end def base_relative_uri_for(uri) base_uri = URI.parse(base_href) current_uri = URI.parse(safe_last_request&.url.to_s).tap do |c| c.path.sub!(%r{/[^/]*$}, '/') unless uri.path.empty? c.path = '/' if c.path.empty? end if [current_uri, base_uri].any?(&:absolute?) current_uri.merge(base_uri) else base_uri.path = current_uri.path if base_uri.path.empty? base_uri end end def build_rack_mock_session reset_host! unless current_host Rack::MockSession.new(app, current_host) end def request_path last_request.path rescue Rack::Test::Error '/' end def safe_last_request last_request rescue Rack::Test::Error nil end private def fragment_or_script?(path) path.gsub(/^#{Regexp.escape(request_path)}/, '').start_with?('#') || path.downcase.start_with?('javascript:') end def referer_url build_uri(last_request.url).to_s rescue Rack::Test::Error '' end end
Ruby
{ "end_line": 98, "name": "build_uri", "signature": "def build_uri(path)", "start_line": 84 }
{ "class_name": "Capybara::RackTest::Browser", "class_signature": "class Capybara::RackTest::Browser", "module": "" }
base_relative_uri_for
capybara/lib/capybara/rack_test/browser.rb
def base_relative_uri_for(uri) base_uri = URI.parse(base_href) current_uri = URI.parse(safe_last_request&.url.to_s).tap do |c| c.path.sub!(%r{/[^/]*$}, '/') unless uri.path.empty? c.path = '/' if c.path.empty? end if [current_uri, base_uri].any?(&:absolute?) current_uri.merge(base_uri) else base_uri.path = current_uri.path if base_uri.path.empty? base_uri end end
# frozen_string_literal: true class Capybara::RackTest::Browser include ::Rack::Test::Methods attr_reader :driver attr_accessor :current_host def initialize(driver) @driver = driver @current_fragment = nil end def app driver.app end def options driver.options end def visit(path, **attributes) @new_visit_request = true reset_cache! reset_host! process_and_follow_redirects(:get, path, attributes) end def refresh reset_cache! request(last_request.fullpath, last_request.env) end def submit(method, path, attributes, content_type: nil) path = request_path if path.nil? || path.empty? uri = build_uri(path) uri.query = '' if method.to_s.casecmp('get').zero? env = { 'HTTP_REFERER' => referer_url } env['CONTENT_TYPE'] = content_type if content_type process_and_follow_redirects( method, uri.to_s, attributes, env ) end def follow(method, path, **attributes) return if fragment_or_script?(path) process_and_follow_redirects(method, path, attributes, 'HTTP_REFERER' => referer_url) end def process_and_follow_redirects(method, path, attributes = {}, env = {}) @current_fragment = build_uri(path).fragment process(method, path, attributes, env) return unless driver.follow_redirects? driver.redirect_limit.times do if last_response.redirect? if [307, 308].include? last_response.status process(last_request.request_method, last_response['Location'], last_request.params, env) else process(:get, last_response['Location'], {}, env) end end end if last_response.redirect? # rubocop:disable Style/GuardClause raise Capybara::InfiniteRedirectError, "redirected more than #{driver.redirect_limit} times, check for infinite redirects." end end def process(method, path, attributes = {}, env = {}) method = method.downcase new_uri = build_uri(path) @current_scheme, @current_host, @current_port = new_uri.select(:scheme, :host, :port) @current_fragment = new_uri.fragment || @current_fragment reset_cache! @new_visit_request = false send(method, new_uri.to_s, attributes, env.merge(options[:headers] || {})) end def build_uri(path) uri = URI.parse(path) base_uri = base_relative_uri_for(uri) uri.path = base_uri.path + uri.path unless uri.absolute? || uri.path.start_with?('/') if base_uri.absolute? base_uri.merge(uri) else uri.scheme ||= @current_scheme uri.host ||= @current_host uri.port ||= @current_port unless uri.default_port == @current_port uri end end def current_url uri = build_uri(last_request.url) uri.fragment = @current_fragment if @current_fragment uri.to_s rescue Rack::Test::Error '' end def reset_host! uri = URI.parse(driver.session_options.app_host || driver.session_options.default_host) @current_scheme, @current_host, @current_port = uri.select(:scheme, :host, :port) end def reset_cache! @dom = nil end def dom @dom ||= Capybara::HTML(html) end def find(format, selector) if format == :css dom.css(selector, Capybara::RackTest::CSSHandlers.new) else dom.xpath(selector) end.map { |node| Capybara::RackTest::Node.new(self, node) } end def html last_response.body rescue Rack::Test::Error '' end def title dom.title end def last_request raise Rack::Test::Error if @new_visit_request super end def last_response raise Rack::Test::Error if @new_visit_request super end protected def base_href find(:css, 'head > base').first&.[](:href).to_s end def base_relative_uri_for(uri) base_uri = URI.parse(base_href) current_uri = URI.parse(safe_last_request&.url.to_s).tap do |c| c.path.sub!(%r{/[^/]*$}, '/') unless uri.path.empty? c.path = '/' if c.path.empty? end if [current_uri, base_uri].any?(&:absolute?) current_uri.merge(base_uri) else base_uri.path = current_uri.path if base_uri.path.empty? base_uri end end def build_rack_mock_session reset_host! unless current_host Rack::MockSession.new(app, current_host) end def request_path last_request.path rescue Rack::Test::Error '/' end def safe_last_request last_request rescue Rack::Test::Error nil end private def fragment_or_script?(path) path.gsub(/^#{Regexp.escape(request_path)}/, '').start_with?('#') || path.downcase.start_with?('javascript:') end def referer_url build_uri(last_request.url).to_s rescue Rack::Test::Error '' end end
Ruby
{ "end_line": 170, "name": "base_relative_uri_for", "signature": "def base_relative_uri_for(uri)", "start_line": 157 }
{ "class_name": "Capybara::RackTest::Browser", "class_signature": "class Capybara::RackTest::Browser", "module": "" }
params
capybara/lib/capybara/rack_test/form.rb
def params(button) form_element_types = %i[input select textarea button] form_elements_xpath = XPath.generate do |xp| xpath = xp.descendant(*form_element_types).where(!xp.attr(:form)) xpath += xp.anywhere(*form_element_types).where(xp.attr(:form) == native[:id]) if native[:id] xpath.where(!xp.attr(:disabled)) end.to_s form_elements = native.xpath(form_elements_xpath).reject { |el| submitter?(el) && (el != button.native) } form_params = form_elements.each_with_object({}.compare_by_identity) do |field, params| case field.name when 'input', 'button' then add_input_param(field, params) when 'select' then add_select_param(field, params) when 'textarea' then add_textarea_param(field, params) end end form_params.each_with_object(make_params) do |(name, value), params| merge_param!(params, name, value) end.to_params_hash # form_elements.each_with_object(make_params) do |field, params| # case field.name # when 'input', 'button' then add_input_param(field, params) # when 'select' then add_select_param(field, params) # when 'textarea' then add_textarea_param(field, params) # end # end.to_params_hash end
# frozen_string_literal: true class Capybara::RackTest::Form < Capybara::RackTest::Node # This only needs to inherit from Rack::Test::UploadedFile because Rack::Test checks for # the class specifically when determining whether to construct the request as multipart. # That check should be based solely on the form element's 'enctype' attribute value, # which should probably be provided to Rack::Test in its non-GET request methods. class NilUploadedFile < Rack::Test::UploadedFile def initialize # rubocop:disable Lint/MissingSuper @empty_file = Tempfile.new('nil_uploaded_file') @empty_file.close end def original_filename; ''; end def content_type; 'application/octet-stream'; end def path; @empty_file.path; end def size; 0; end def read; ''; end def append_to(_); end def set_encoding(_); end # rubocop:disable Naming/AccessorMethodName end def params(button) form_element_types = %i[input select textarea button] form_elements_xpath = XPath.generate do |xp| xpath = xp.descendant(*form_element_types).where(!xp.attr(:form)) xpath += xp.anywhere(*form_element_types).where(xp.attr(:form) == native[:id]) if native[:id] xpath.where(!xp.attr(:disabled)) end.to_s form_elements = native.xpath(form_elements_xpath).reject { |el| submitter?(el) && (el != button.native) } form_params = form_elements.each_with_object({}.compare_by_identity) do |field, params| case field.name when 'input', 'button' then add_input_param(field, params) when 'select' then add_select_param(field, params) when 'textarea' then add_textarea_param(field, params) end end form_params.each_with_object(make_params) do |(name, value), params| merge_param!(params, name, value) end.to_params_hash # form_elements.each_with_object(make_params) do |field, params| # case field.name # when 'input', 'button' then add_input_param(field, params) # when 'select' then add_select_param(field, params) # when 'textarea' then add_textarea_param(field, params) # end # end.to_params_hash end def submit(button) action = button&.[]('formaction') || native['action'] method = button&.[]('formmethod') || request_method driver.submit(method, action.to_s, params(button), content_type: native['enctype']) end def multipart? self[:enctype] == 'multipart/form-data' end private class ParamsHash < Hash def to_params_hash self end end def request_method /post/i.match?(self[:method] || '') ? :post : :get end def merge_param!(params, key, value) key = key.to_s if Rack::Utils.respond_to?(:default_query_parser) Rack::Utils.default_query_parser.normalize_params(params, key, value, Rack::Utils.param_depth_limit) else Rack::Utils.normalize_params(params, key, value) end end def make_params if Rack::Utils.respond_to?(:default_query_parser) Rack::Utils.default_query_parser.make_params else ParamsHash.new end end def add_input_param(field, params) name, value = field['name'].to_s, field['value'].to_s return if name.empty? value = case field['type'] when 'radio', 'checkbox' return unless field['checked'] Capybara::RackTest::Node.new(driver, field).value.to_s when 'file' return if value.empty? && params.keys.include?(name) && Rack::Test::VERSION.to_f >= 2.0 # rubocop:disable Performance/InefficientHashSearch if multipart? file_to_upload(value) else File.basename(value) end else value end # merge_param!(params, name, value) params[name] = value end def file_to_upload(filename) if filename.empty? NilUploadedFile.new else mime_info = MiniMime.lookup_by_filename(filename) Rack::Test::UploadedFile.new(filename, mime_info&.content_type&.to_s) end end def add_select_param(field, params) name = field['name'] if field.has_attribute?('multiple') value = field.xpath('.//option[@selected]').map do |option| # merge_param!(params, field['name'], (option['value'] || option.text).to_s) (option['value'] || option.text).to_s end params[name] = value unless value.empty? else option = field.xpath('.//option[@selected]').first || field.xpath('.//option').first # merge_param!(params, field['name'], (option['value'] || option.text).to_s) if option params[name] = (option['value'] || option.text).to_s if option end end def add_textarea_param(field, params) # merge_param!(params, field['name'], field['_capybara_raw_value'].to_s.gsub(/\r?\n/, "\r\n")) params[field['name']] = field['_capybara_raw_value'].to_s.gsub(/\r?\n/, "\r\n") end def submitter?(el) (%w[submit image].include? el['type']) || (el.name == 'button') end end
Ruby
{ "end_line": 52, "name": "params", "signature": "def params(button)", "start_line": 23 }
{ "class_name": "Capybara::RackTest::Form", "class_signature": "class Capybara::RackTest::Form < < Capybara::RackTest::Node", "module": "" }
add_input_param
capybara/lib/capybara/rack_test/form.rb
def add_input_param(field, params) name, value = field['name'].to_s, field['value'].to_s return if name.empty? value = case field['type'] when 'radio', 'checkbox' return unless field['checked'] Capybara::RackTest::Node.new(driver, field).value.to_s when 'file' return if value.empty? && params.keys.include?(name) && Rack::Test::VERSION.to_f >= 2.0 # rubocop:disable Performance/InefficientHashSearch if multipart? file_to_upload(value) else File.basename(value) end else value end # merge_param!(params, name, value) params[name] = value end
# frozen_string_literal: true class Capybara::RackTest::Form < Capybara::RackTest::Node # This only needs to inherit from Rack::Test::UploadedFile because Rack::Test checks for # the class specifically when determining whether to construct the request as multipart. # That check should be based solely on the form element's 'enctype' attribute value, # which should probably be provided to Rack::Test in its non-GET request methods. class NilUploadedFile < Rack::Test::UploadedFile def initialize # rubocop:disable Lint/MissingSuper @empty_file = Tempfile.new('nil_uploaded_file') @empty_file.close end def original_filename; ''; end def content_type; 'application/octet-stream'; end def path; @empty_file.path; end def size; 0; end def read; ''; end def append_to(_); end def set_encoding(_); end # rubocop:disable Naming/AccessorMethodName end def params(button) form_element_types = %i[input select textarea button] form_elements_xpath = XPath.generate do |xp| xpath = xp.descendant(*form_element_types).where(!xp.attr(:form)) xpath += xp.anywhere(*form_element_types).where(xp.attr(:form) == native[:id]) if native[:id] xpath.where(!xp.attr(:disabled)) end.to_s form_elements = native.xpath(form_elements_xpath).reject { |el| submitter?(el) && (el != button.native) } form_params = form_elements.each_with_object({}.compare_by_identity) do |field, params| case field.name when 'input', 'button' then add_input_param(field, params) when 'select' then add_select_param(field, params) when 'textarea' then add_textarea_param(field, params) end end form_params.each_with_object(make_params) do |(name, value), params| merge_param!(params, name, value) end.to_params_hash # form_elements.each_with_object(make_params) do |field, params| # case field.name # when 'input', 'button' then add_input_param(field, params) # when 'select' then add_select_param(field, params) # when 'textarea' then add_textarea_param(field, params) # end # end.to_params_hash end def submit(button) action = button&.[]('formaction') || native['action'] method = button&.[]('formmethod') || request_method driver.submit(method, action.to_s, params(button), content_type: native['enctype']) end def multipart? self[:enctype] == 'multipart/form-data' end private class ParamsHash < Hash def to_params_hash self end end def request_method /post/i.match?(self[:method] || '') ? :post : :get end def merge_param!(params, key, value) key = key.to_s if Rack::Utils.respond_to?(:default_query_parser) Rack::Utils.default_query_parser.normalize_params(params, key, value, Rack::Utils.param_depth_limit) else Rack::Utils.normalize_params(params, key, value) end end def make_params if Rack::Utils.respond_to?(:default_query_parser) Rack::Utils.default_query_parser.make_params else ParamsHash.new end end def add_input_param(field, params) name, value = field['name'].to_s, field['value'].to_s return if name.empty? value = case field['type'] when 'radio', 'checkbox' return unless field['checked'] Capybara::RackTest::Node.new(driver, field).value.to_s when 'file' return if value.empty? && params.keys.include?(name) && Rack::Test::VERSION.to_f >= 2.0 # rubocop:disable Performance/InefficientHashSearch if multipart? file_to_upload(value) else File.basename(value) end else value end # merge_param!(params, name, value) params[name] = value end def file_to_upload(filename) if filename.empty? NilUploadedFile.new else mime_info = MiniMime.lookup_by_filename(filename) Rack::Test::UploadedFile.new(filename, mime_info&.content_type&.to_s) end end def add_select_param(field, params) name = field['name'] if field.has_attribute?('multiple') value = field.xpath('.//option[@selected]').map do |option| # merge_param!(params, field['name'], (option['value'] || option.text).to_s) (option['value'] || option.text).to_s end params[name] = value unless value.empty? else option = field.xpath('.//option[@selected]').first || field.xpath('.//option').first # merge_param!(params, field['name'], (option['value'] || option.text).to_s) if option params[name] = (option['value'] || option.text).to_s if option end end def add_textarea_param(field, params) # merge_param!(params, field['name'], field['_capybara_raw_value'].to_s.gsub(/\r?\n/, "\r\n")) params[field['name']] = field['_capybara_raw_value'].to_s.gsub(/\r?\n/, "\r\n") end def submitter?(el) (%w[submit image].include? el['type']) || (el.name == 'button') end end
Ruby
{ "end_line": 115, "name": "add_input_param", "signature": "def add_input_param(field, params)", "start_line": 93 }
{ "class_name": "Capybara::RackTest::Form", "class_signature": "class Capybara::RackTest::Form < < Capybara::RackTest::Node", "module": "" }
add_select_param
capybara/lib/capybara/rack_test/form.rb
def add_select_param(field, params) name = field['name'] if field.has_attribute?('multiple') value = field.xpath('.//option[@selected]').map do |option| # merge_param!(params, field['name'], (option['value'] || option.text).to_s) (option['value'] || option.text).to_s end params[name] = value unless value.empty? else option = field.xpath('.//option[@selected]').first || field.xpath('.//option').first # merge_param!(params, field['name'], (option['value'] || option.text).to_s) if option params[name] = (option['value'] || option.text).to_s if option end end
# frozen_string_literal: true class Capybara::RackTest::Form < Capybara::RackTest::Node # This only needs to inherit from Rack::Test::UploadedFile because Rack::Test checks for # the class specifically when determining whether to construct the request as multipart. # That check should be based solely on the form element's 'enctype' attribute value, # which should probably be provided to Rack::Test in its non-GET request methods. class NilUploadedFile < Rack::Test::UploadedFile def initialize # rubocop:disable Lint/MissingSuper @empty_file = Tempfile.new('nil_uploaded_file') @empty_file.close end def original_filename; ''; end def content_type; 'application/octet-stream'; end def path; @empty_file.path; end def size; 0; end def read; ''; end def append_to(_); end def set_encoding(_); end # rubocop:disable Naming/AccessorMethodName end def params(button) form_element_types = %i[input select textarea button] form_elements_xpath = XPath.generate do |xp| xpath = xp.descendant(*form_element_types).where(!xp.attr(:form)) xpath += xp.anywhere(*form_element_types).where(xp.attr(:form) == native[:id]) if native[:id] xpath.where(!xp.attr(:disabled)) end.to_s form_elements = native.xpath(form_elements_xpath).reject { |el| submitter?(el) && (el != button.native) } form_params = form_elements.each_with_object({}.compare_by_identity) do |field, params| case field.name when 'input', 'button' then add_input_param(field, params) when 'select' then add_select_param(field, params) when 'textarea' then add_textarea_param(field, params) end end form_params.each_with_object(make_params) do |(name, value), params| merge_param!(params, name, value) end.to_params_hash # form_elements.each_with_object(make_params) do |field, params| # case field.name # when 'input', 'button' then add_input_param(field, params) # when 'select' then add_select_param(field, params) # when 'textarea' then add_textarea_param(field, params) # end # end.to_params_hash end def submit(button) action = button&.[]('formaction') || native['action'] method = button&.[]('formmethod') || request_method driver.submit(method, action.to_s, params(button), content_type: native['enctype']) end def multipart? self[:enctype] == 'multipart/form-data' end private class ParamsHash < Hash def to_params_hash self end end def request_method /post/i.match?(self[:method] || '') ? :post : :get end def merge_param!(params, key, value) key = key.to_s if Rack::Utils.respond_to?(:default_query_parser) Rack::Utils.default_query_parser.normalize_params(params, key, value, Rack::Utils.param_depth_limit) else Rack::Utils.normalize_params(params, key, value) end end def make_params if Rack::Utils.respond_to?(:default_query_parser) Rack::Utils.default_query_parser.make_params else ParamsHash.new end end def add_input_param(field, params) name, value = field['name'].to_s, field['value'].to_s return if name.empty? value = case field['type'] when 'radio', 'checkbox' return unless field['checked'] Capybara::RackTest::Node.new(driver, field).value.to_s when 'file' return if value.empty? && params.keys.include?(name) && Rack::Test::VERSION.to_f >= 2.0 # rubocop:disable Performance/InefficientHashSearch if multipart? file_to_upload(value) else File.basename(value) end else value end # merge_param!(params, name, value) params[name] = value end def file_to_upload(filename) if filename.empty? NilUploadedFile.new else mime_info = MiniMime.lookup_by_filename(filename) Rack::Test::UploadedFile.new(filename, mime_info&.content_type&.to_s) end end def add_select_param(field, params) name = field['name'] if field.has_attribute?('multiple') value = field.xpath('.//option[@selected]').map do |option| # merge_param!(params, field['name'], (option['value'] || option.text).to_s) (option['value'] || option.text).to_s end params[name] = value unless value.empty? else option = field.xpath('.//option[@selected]').first || field.xpath('.//option').first # merge_param!(params, field['name'], (option['value'] || option.text).to_s) if option params[name] = (option['value'] || option.text).to_s if option end end def add_textarea_param(field, params) # merge_param!(params, field['name'], field['_capybara_raw_value'].to_s.gsub(/\r?\n/, "\r\n")) params[field['name']] = field['_capybara_raw_value'].to_s.gsub(/\r?\n/, "\r\n") end def submitter?(el) (%w[submit image].include? el['type']) || (el.name == 'button') end end
Ruby
{ "end_line": 139, "name": "add_select_param", "signature": "def add_select_param(field, params)", "start_line": 126 }
{ "class_name": "Capybara::RackTest::Form", "class_signature": "class Capybara::RackTest::Form < < Capybara::RackTest::Node", "module": "" }
set
capybara/lib/capybara/rack_test/node.rb
def set(value, **options) return if disabled? || readonly? warn "Options passed to Node#set but the RackTest driver doesn't support any - ignoring" unless options.empty? if value.is_a?(Array) && !multiple? raise TypeError, "Value cannot be an Array when 'multiple' attribute is not present. Not a #{value.class}" end if radio? then set_radio(value) elsif checkbox? then set_checkbox(value) elsif range? then set_range(value) elsif input_field? then set_input(value) elsif textarea? then native['_capybara_raw_value'] = value.to_s end end
# frozen_string_literal: true require 'capybara/rack_test/errors' require 'capybara/node/whitespace_normalizer' class Capybara::RackTest::Node < Capybara::Driver::Node include Capybara::Node::WhitespaceNormalizer BLOCK_ELEMENTS = %w[p h1 h2 h3 h4 h5 h6 ol ul pre address blockquote dl div fieldset form hr noscript table].freeze def all_text normalize_spacing(native.text) end def visible_text normalize_visible_spacing(displayed_text) end def [](name) string_node[name] end def style(_styles) raise NotImplementedError, 'The rack_test driver does not process CSS' end def value string_node.value end def set(value, **options) return if disabled? || readonly? warn "Options passed to Node#set but the RackTest driver doesn't support any - ignoring" unless options.empty? if value.is_a?(Array) && !multiple? raise TypeError, "Value cannot be an Array when 'multiple' attribute is not present. Not a #{value.class}" end if radio? then set_radio(value) elsif checkbox? then set_checkbox(value) elsif range? then set_range(value) elsif input_field? then set_input(value) elsif textarea? then native['_capybara_raw_value'] = value.to_s end end def select_option return if disabled? deselect_options unless select_node.multiple? native['selected'] = 'selected' end def unselect_option raise Capybara::UnselectNotAllowed, 'Cannot unselect option from single select box.' unless select_node.multiple? native.remove_attribute('selected') end def click(keys = [], **options) options.delete(:offset) raise ArgumentError, 'The RackTest driver does not support click options' unless keys.empty? && options.empty? if link? follow_link elsif submits? associated_form = form Capybara::RackTest::Form.new(driver, associated_form).submit(self) if associated_form elsif checkable? set(!checked?) elsif tag_name == 'label' click_label elsif (details = native.xpath('.//ancestor-or-self::details').last) toggle_details(details) end end def tag_name native.node_name end def visible? string_node.visible? end def checked? string_node.checked? end def selected? string_node.selected? end def disabled? return true if string_node.disabled? if %w[option optgroup].include? tag_name find_xpath(OPTION_OWNER_XPATH)[0].disabled? else !find_xpath(DISABLED_BY_FIELDSET_XPATH).empty? end end def readonly? # readonly attribute not valid on these input types return false if input_field? && %w[hidden range color checkbox radio file submit image reset button].include?(type) super end def path native.path end def find_xpath(locator, **_hints) native.xpath(locator).map { |el| self.class.new(driver, el) } end def find_css(locator, **_hints) native.css(locator, Capybara::RackTest::CSSHandlers.new).map { |el| self.class.new(driver, el) } end public_instance_methods(false).each do |meth_name| alias_method "unchecked_#{meth_name}", meth_name private "unchecked_#{meth_name}" # rubocop:disable Style/AccessModifierDeclarations class_eval <<~METHOD, __FILE__, __LINE__ + 1 def #{meth_name}(...) stale_check method(:"unchecked_#{meth_name}").call(...) end METHOD end protected # @api private def displayed_text(check_ancestor: true) if !string_node.visible?(check_ancestor) '' elsif native.text? native .text .delete(REMOVED_CHARACTERS) .tr(SQUEEZED_SPACES, ' ') .squeeze(' ') elsif native.element? text = native.children.map do |child| Capybara::RackTest::Node.new(driver, child).displayed_text(check_ancestor: false) end.join || '' text = "\n#{text}\n" if BLOCK_ELEMENTS.include?(tag_name) text else # rubocop:disable Lint/DuplicateBranch '' end end private def stale_check raise Capybara::RackTest::Errors::StaleElementReferenceError unless native.document == driver.dom end def deselect_options select_node.find_xpath('.//option[@selected]').each { |node| node.native.remove_attribute('selected') } end def string_node @string_node ||= Capybara::Node::Simple.new(native) end # a reference to the select node if this is an option node def select_node find_xpath('./ancestor::select[1]').first end def type native[:type] end def form if native[:form] native.xpath("//form[@id='#{native[:form]}']") else native.ancestors('form') end.first end def set_radio(_value) # rubocop:disable Naming/AccessorMethodName other_radios_xpath = XPath.generate { |xp| xp.anywhere(:input)[xp.attr(:name) == self[:name]] }.to_s driver.dom.xpath(other_radios_xpath).each { |node| node.remove_attribute('checked') } native['checked'] = 'checked' end def set_checkbox(value) # rubocop:disable Naming/AccessorMethodName if value && !native['checked'] native['checked'] = 'checked' elsif !value && native['checked'] native.remove_attribute('checked') end end def set_range(value) # rubocop:disable Naming/AccessorMethodName min, max, step = (native['min'] || 0).to_f, (native['max'] || 100).to_f, (native['step'] || 1).to_f value = value.to_f value = value.clamp(min, max) value = (((value - min) / step).round * step) + min native['value'] = value.clamp(min, max) end def set_input(value) # rubocop:disable Naming/AccessorMethodName if text_or_password? && attribute_is_not_blank?(:maxlength) # Browser behavior for maxlength="0" is inconsistent, so we stick with # Firefox, allowing no input value = value.to_s[0...self[:maxlength].to_i] end if value.is_a?(Array) # Assert multiple attribute is present value.each do |val| new_native = native.clone new_native.remove_attribute('value') native.add_next_sibling(new_native) new_native['value'] = val.to_s end native.remove else value.to_s.tap do |set_value| if set_value.end_with?("\n") && (form&.css('input, textarea')&.count == 1) # rubocop:disable Style/CollectionQuerying native['value'] = set_value.to_s.chop Capybara::RackTest::Form.new(driver, form).submit(self) else native['value'] = set_value end end end end def attribute_is_not_blank?(attribute) self[attribute] && !self[attribute].empty? end def follow_link method = self['data-method'] || self['data-turbo-method'] if driver.options[:respect_data_method] method ||= :get driver.follow(method, self[:href].to_s) end def click_label labelled_control = if native[:for] find_xpath("//input[@id='#{native[:for]}']") else find_xpath('.//input') end.first labelled_control.set(!labelled_control.checked?) if checkbox_or_radio?(labelled_control) end def toggle_details(details = nil) details ||= native.xpath('.//ancestor-or-self::details').last return unless details if details.has_attribute?('open') details.remove_attribute('open') else details.set_attribute('open', 'open') end end def link? tag_name == 'a' && !self[:href].nil? end def submits? (tag_name == 'input' && %w[submit image].include?(type)) || (tag_name == 'button' && [nil, 'submit'].include?(type)) end def checkable? tag_name == 'input' && %w[checkbox radio].include?(type) end protected def checkbox_or_radio?(field = self) field&.checkbox? || field&.radio? end def checkbox? input_field? && type == 'checkbox' end def radio? input_field? && type == 'radio' end def text_or_password? input_field? && %w[text password].include?(type) end def input_field? tag_name == 'input' end def textarea? tag_name == 'textarea' end def range? input_field? && type == 'range' end OPTION_OWNER_XPATH = XPath.parent(:optgroup, :select, :datalist).to_s.freeze DISABLED_BY_FIELDSET_XPATH = XPath.generate do |x| x.parent(:fieldset)[ XPath.attr(:disabled) ] + x.ancestor[ ~x.self(:legend) | x.preceding_sibling(:legend) ][ x.parent(:fieldset)[ x.attr(:disabled) ] ] end.to_s.freeze end
Ruby
{ "end_line": 46, "name": "set", "signature": "def set(value, **options)", "start_line": 31 }
{ "class_name": "Capybara::RackTest::Node", "class_signature": "class Capybara::RackTest::Node < < Capybara::Driver::Node", "module": "" }
click
capybara/lib/capybara/rack_test/node.rb
def click(keys = [], **options) options.delete(:offset) raise ArgumentError, 'The RackTest driver does not support click options' unless keys.empty? && options.empty? if link? follow_link elsif submits? associated_form = form Capybara::RackTest::Form.new(driver, associated_form).submit(self) if associated_form elsif checkable? set(!checked?) elsif tag_name == 'label' click_label elsif (details = native.xpath('.//ancestor-or-self::details').last) toggle_details(details) end end
# frozen_string_literal: true require 'capybara/rack_test/errors' require 'capybara/node/whitespace_normalizer' class Capybara::RackTest::Node < Capybara::Driver::Node include Capybara::Node::WhitespaceNormalizer BLOCK_ELEMENTS = %w[p h1 h2 h3 h4 h5 h6 ol ul pre address blockquote dl div fieldset form hr noscript table].freeze def all_text normalize_spacing(native.text) end def visible_text normalize_visible_spacing(displayed_text) end def [](name) string_node[name] end def style(_styles) raise NotImplementedError, 'The rack_test driver does not process CSS' end def value string_node.value end def set(value, **options) return if disabled? || readonly? warn "Options passed to Node#set but the RackTest driver doesn't support any - ignoring" unless options.empty? if value.is_a?(Array) && !multiple? raise TypeError, "Value cannot be an Array when 'multiple' attribute is not present. Not a #{value.class}" end if radio? then set_radio(value) elsif checkbox? then set_checkbox(value) elsif range? then set_range(value) elsif input_field? then set_input(value) elsif textarea? then native['_capybara_raw_value'] = value.to_s end end def select_option return if disabled? deselect_options unless select_node.multiple? native['selected'] = 'selected' end def unselect_option raise Capybara::UnselectNotAllowed, 'Cannot unselect option from single select box.' unless select_node.multiple? native.remove_attribute('selected') end def click(keys = [], **options) options.delete(:offset) raise ArgumentError, 'The RackTest driver does not support click options' unless keys.empty? && options.empty? if link? follow_link elsif submits? associated_form = form Capybara::RackTest::Form.new(driver, associated_form).submit(self) if associated_form elsif checkable? set(!checked?) elsif tag_name == 'label' click_label elsif (details = native.xpath('.//ancestor-or-self::details').last) toggle_details(details) end end def tag_name native.node_name end def visible? string_node.visible? end def checked? string_node.checked? end def selected? string_node.selected? end def disabled? return true if string_node.disabled? if %w[option optgroup].include? tag_name find_xpath(OPTION_OWNER_XPATH)[0].disabled? else !find_xpath(DISABLED_BY_FIELDSET_XPATH).empty? end end def readonly? # readonly attribute not valid on these input types return false if input_field? && %w[hidden range color checkbox radio file submit image reset button].include?(type) super end def path native.path end def find_xpath(locator, **_hints) native.xpath(locator).map { |el| self.class.new(driver, el) } end def find_css(locator, **_hints) native.css(locator, Capybara::RackTest::CSSHandlers.new).map { |el| self.class.new(driver, el) } end public_instance_methods(false).each do |meth_name| alias_method "unchecked_#{meth_name}", meth_name private "unchecked_#{meth_name}" # rubocop:disable Style/AccessModifierDeclarations class_eval <<~METHOD, __FILE__, __LINE__ + 1 def #{meth_name}(...) stale_check method(:"unchecked_#{meth_name}").call(...) end METHOD end protected # @api private def displayed_text(check_ancestor: true) if !string_node.visible?(check_ancestor) '' elsif native.text? native .text .delete(REMOVED_CHARACTERS) .tr(SQUEEZED_SPACES, ' ') .squeeze(' ') elsif native.element? text = native.children.map do |child| Capybara::RackTest::Node.new(driver, child).displayed_text(check_ancestor: false) end.join || '' text = "\n#{text}\n" if BLOCK_ELEMENTS.include?(tag_name) text else # rubocop:disable Lint/DuplicateBranch '' end end private def stale_check raise Capybara::RackTest::Errors::StaleElementReferenceError unless native.document == driver.dom end def deselect_options select_node.find_xpath('.//option[@selected]').each { |node| node.native.remove_attribute('selected') } end def string_node @string_node ||= Capybara::Node::Simple.new(native) end # a reference to the select node if this is an option node def select_node find_xpath('./ancestor::select[1]').first end def type native[:type] end def form if native[:form] native.xpath("//form[@id='#{native[:form]}']") else native.ancestors('form') end.first end def set_radio(_value) # rubocop:disable Naming/AccessorMethodName other_radios_xpath = XPath.generate { |xp| xp.anywhere(:input)[xp.attr(:name) == self[:name]] }.to_s driver.dom.xpath(other_radios_xpath).each { |node| node.remove_attribute('checked') } native['checked'] = 'checked' end def set_checkbox(value) # rubocop:disable Naming/AccessorMethodName if value && !native['checked'] native['checked'] = 'checked' elsif !value && native['checked'] native.remove_attribute('checked') end end def set_range(value) # rubocop:disable Naming/AccessorMethodName min, max, step = (native['min'] || 0).to_f, (native['max'] || 100).to_f, (native['step'] || 1).to_f value = value.to_f value = value.clamp(min, max) value = (((value - min) / step).round * step) + min native['value'] = value.clamp(min, max) end def set_input(value) # rubocop:disable Naming/AccessorMethodName if text_or_password? && attribute_is_not_blank?(:maxlength) # Browser behavior for maxlength="0" is inconsistent, so we stick with # Firefox, allowing no input value = value.to_s[0...self[:maxlength].to_i] end if value.is_a?(Array) # Assert multiple attribute is present value.each do |val| new_native = native.clone new_native.remove_attribute('value') native.add_next_sibling(new_native) new_native['value'] = val.to_s end native.remove else value.to_s.tap do |set_value| if set_value.end_with?("\n") && (form&.css('input, textarea')&.count == 1) # rubocop:disable Style/CollectionQuerying native['value'] = set_value.to_s.chop Capybara::RackTest::Form.new(driver, form).submit(self) else native['value'] = set_value end end end end def attribute_is_not_blank?(attribute) self[attribute] && !self[attribute].empty? end def follow_link method = self['data-method'] || self['data-turbo-method'] if driver.options[:respect_data_method] method ||= :get driver.follow(method, self[:href].to_s) end def click_label labelled_control = if native[:for] find_xpath("//input[@id='#{native[:for]}']") else find_xpath('.//input') end.first labelled_control.set(!labelled_control.checked?) if checkbox_or_radio?(labelled_control) end def toggle_details(details = nil) details ||= native.xpath('.//ancestor-or-self::details').last return unless details if details.has_attribute?('open') details.remove_attribute('open') else details.set_attribute('open', 'open') end end def link? tag_name == 'a' && !self[:href].nil? end def submits? (tag_name == 'input' && %w[submit image].include?(type)) || (tag_name == 'button' && [nil, 'submit'].include?(type)) end def checkable? tag_name == 'input' && %w[checkbox radio].include?(type) end protected def checkbox_or_radio?(field = self) field&.checkbox? || field&.radio? end def checkbox? input_field? && type == 'checkbox' end def radio? input_field? && type == 'radio' end def text_or_password? input_field? && %w[text password].include?(type) end def input_field? tag_name == 'input' end def textarea? tag_name == 'textarea' end def range? input_field? && type == 'range' end OPTION_OWNER_XPATH = XPath.parent(:optgroup, :select, :datalist).to_s.freeze DISABLED_BY_FIELDSET_XPATH = XPath.generate do |x| x.parent(:fieldset)[ XPath.attr(:disabled) ] + x.ancestor[ ~x.self(:legend) | x.preceding_sibling(:legend) ][ x.parent(:fieldset)[ x.attr(:disabled) ] ] end.to_s.freeze end
Ruby
{ "end_line": 77, "name": "click", "signature": "def click(keys = [], **options)", "start_line": 61 }
{ "class_name": "Capybara::RackTest::Node", "class_signature": "class Capybara::RackTest::Node < < Capybara::Driver::Node", "module": "" }
displayed_text
capybara/lib/capybara/rack_test/node.rb
def displayed_text(check_ancestor: true) if !string_node.visible?(check_ancestor) '' elsif native.text? native .text .delete(REMOVED_CHARACTERS) .tr(SQUEEZED_SPACES, ' ') .squeeze(' ') elsif native.element? text = native.children.map do |child| Capybara::RackTest::Node.new(driver, child).displayed_text(check_ancestor: false) end.join || '' text = "\n#{text}\n" if BLOCK_ELEMENTS.include?(tag_name) text else # rubocop:disable Lint/DuplicateBranch '' end end
# frozen_string_literal: true require 'capybara/rack_test/errors' require 'capybara/node/whitespace_normalizer' class Capybara::RackTest::Node < Capybara::Driver::Node include Capybara::Node::WhitespaceNormalizer BLOCK_ELEMENTS = %w[p h1 h2 h3 h4 h5 h6 ol ul pre address blockquote dl div fieldset form hr noscript table].freeze def all_text normalize_spacing(native.text) end def visible_text normalize_visible_spacing(displayed_text) end def [](name) string_node[name] end def style(_styles) raise NotImplementedError, 'The rack_test driver does not process CSS' end def value string_node.value end def set(value, **options) return if disabled? || readonly? warn "Options passed to Node#set but the RackTest driver doesn't support any - ignoring" unless options.empty? if value.is_a?(Array) && !multiple? raise TypeError, "Value cannot be an Array when 'multiple' attribute is not present. Not a #{value.class}" end if radio? then set_radio(value) elsif checkbox? then set_checkbox(value) elsif range? then set_range(value) elsif input_field? then set_input(value) elsif textarea? then native['_capybara_raw_value'] = value.to_s end end def select_option return if disabled? deselect_options unless select_node.multiple? native['selected'] = 'selected' end def unselect_option raise Capybara::UnselectNotAllowed, 'Cannot unselect option from single select box.' unless select_node.multiple? native.remove_attribute('selected') end def click(keys = [], **options) options.delete(:offset) raise ArgumentError, 'The RackTest driver does not support click options' unless keys.empty? && options.empty? if link? follow_link elsif submits? associated_form = form Capybara::RackTest::Form.new(driver, associated_form).submit(self) if associated_form elsif checkable? set(!checked?) elsif tag_name == 'label' click_label elsif (details = native.xpath('.//ancestor-or-self::details').last) toggle_details(details) end end def tag_name native.node_name end def visible? string_node.visible? end def checked? string_node.checked? end def selected? string_node.selected? end def disabled? return true if string_node.disabled? if %w[option optgroup].include? tag_name find_xpath(OPTION_OWNER_XPATH)[0].disabled? else !find_xpath(DISABLED_BY_FIELDSET_XPATH).empty? end end def readonly? # readonly attribute not valid on these input types return false if input_field? && %w[hidden range color checkbox radio file submit image reset button].include?(type) super end def path native.path end def find_xpath(locator, **_hints) native.xpath(locator).map { |el| self.class.new(driver, el) } end def find_css(locator, **_hints) native.css(locator, Capybara::RackTest::CSSHandlers.new).map { |el| self.class.new(driver, el) } end public_instance_methods(false).each do |meth_name| alias_method "unchecked_#{meth_name}", meth_name private "unchecked_#{meth_name}" # rubocop:disable Style/AccessModifierDeclarations class_eval <<~METHOD, __FILE__, __LINE__ + 1 def #{meth_name}(...) stale_check method(:"unchecked_#{meth_name}").call(...) end METHOD end protected # @api private def displayed_text(check_ancestor: true) if !string_node.visible?(check_ancestor) '' elsif native.text? native .text .delete(REMOVED_CHARACTERS) .tr(SQUEEZED_SPACES, ' ') .squeeze(' ') elsif native.element? text = native.children.map do |child| Capybara::RackTest::Node.new(driver, child).displayed_text(check_ancestor: false) end.join || '' text = "\n#{text}\n" if BLOCK_ELEMENTS.include?(tag_name) text else # rubocop:disable Lint/DuplicateBranch '' end end private def stale_check raise Capybara::RackTest::Errors::StaleElementReferenceError unless native.document == driver.dom end def deselect_options select_node.find_xpath('.//option[@selected]').each { |node| node.native.remove_attribute('selected') } end def string_node @string_node ||= Capybara::Node::Simple.new(native) end # a reference to the select node if this is an option node def select_node find_xpath('./ancestor::select[1]').first end def type native[:type] end def form if native[:form] native.xpath("//form[@id='#{native[:form]}']") else native.ancestors('form') end.first end def set_radio(_value) # rubocop:disable Naming/AccessorMethodName other_radios_xpath = XPath.generate { |xp| xp.anywhere(:input)[xp.attr(:name) == self[:name]] }.to_s driver.dom.xpath(other_radios_xpath).each { |node| node.remove_attribute('checked') } native['checked'] = 'checked' end def set_checkbox(value) # rubocop:disable Naming/AccessorMethodName if value && !native['checked'] native['checked'] = 'checked' elsif !value && native['checked'] native.remove_attribute('checked') end end def set_range(value) # rubocop:disable Naming/AccessorMethodName min, max, step = (native['min'] || 0).to_f, (native['max'] || 100).to_f, (native['step'] || 1).to_f value = value.to_f value = value.clamp(min, max) value = (((value - min) / step).round * step) + min native['value'] = value.clamp(min, max) end def set_input(value) # rubocop:disable Naming/AccessorMethodName if text_or_password? && attribute_is_not_blank?(:maxlength) # Browser behavior for maxlength="0" is inconsistent, so we stick with # Firefox, allowing no input value = value.to_s[0...self[:maxlength].to_i] end if value.is_a?(Array) # Assert multiple attribute is present value.each do |val| new_native = native.clone new_native.remove_attribute('value') native.add_next_sibling(new_native) new_native['value'] = val.to_s end native.remove else value.to_s.tap do |set_value| if set_value.end_with?("\n") && (form&.css('input, textarea')&.count == 1) # rubocop:disable Style/CollectionQuerying native['value'] = set_value.to_s.chop Capybara::RackTest::Form.new(driver, form).submit(self) else native['value'] = set_value end end end end def attribute_is_not_blank?(attribute) self[attribute] && !self[attribute].empty? end def follow_link method = self['data-method'] || self['data-turbo-method'] if driver.options[:respect_data_method] method ||= :get driver.follow(method, self[:href].to_s) end def click_label labelled_control = if native[:for] find_xpath("//input[@id='#{native[:for]}']") else find_xpath('.//input') end.first labelled_control.set(!labelled_control.checked?) if checkbox_or_radio?(labelled_control) end def toggle_details(details = nil) details ||= native.xpath('.//ancestor-or-self::details').last return unless details if details.has_attribute?('open') details.remove_attribute('open') else details.set_attribute('open', 'open') end end def link? tag_name == 'a' && !self[:href].nil? end def submits? (tag_name == 'input' && %w[submit image].include?(type)) || (tag_name == 'button' && [nil, 'submit'].include?(type)) end def checkable? tag_name == 'input' && %w[checkbox radio].include?(type) end protected def checkbox_or_radio?(field = self) field&.checkbox? || field&.radio? end def checkbox? input_field? && type == 'checkbox' end def radio? input_field? && type == 'radio' end def text_or_password? input_field? && %w[text password].include?(type) end def input_field? tag_name == 'input' end def textarea? tag_name == 'textarea' end def range? input_field? && type == 'range' end OPTION_OWNER_XPATH = XPath.parent(:optgroup, :select, :datalist).to_s.freeze DISABLED_BY_FIELDSET_XPATH = XPath.generate do |x| x.parent(:fieldset)[ XPath.attr(:disabled) ] + x.ancestor[ ~x.self(:legend) | x.preceding_sibling(:legend) ][ x.parent(:fieldset)[ x.attr(:disabled) ] ] end.to_s.freeze end
Ruby
{ "end_line": 157, "name": "displayed_text", "signature": "def displayed_text(check_ancestor: true)", "start_line": 139 }
{ "class_name": "Capybara::RackTest::Node", "class_signature": "class Capybara::RackTest::Node < < Capybara::Driver::Node", "module": "" }
set_input
capybara/lib/capybara/rack_test/node.rb
def set_input(value) # rubocop:disable Naming/AccessorMethodName if text_or_password? && attribute_is_not_blank?(:maxlength) # Browser behavior for maxlength="0" is inconsistent, so we stick with # Firefox, allowing no input value = value.to_s[0...self[:maxlength].to_i] end if value.is_a?(Array) # Assert multiple attribute is present value.each do |val| new_native = native.clone new_native.remove_attribute('value') native.add_next_sibling(new_native) new_native['value'] = val.to_s end native.remove else value.to_s.tap do |set_value| if set_value.end_with?("\n") && (form&.css('input, textarea')&.count == 1) # rubocop:disable Style/CollectionQuerying native['value'] = set_value.to_s.chop Capybara::RackTest::Form.new(driver, form).submit(self) else native['value'] = set_value end end end end
# frozen_string_literal: true require 'capybara/rack_test/errors' require 'capybara/node/whitespace_normalizer' class Capybara::RackTest::Node < Capybara::Driver::Node include Capybara::Node::WhitespaceNormalizer BLOCK_ELEMENTS = %w[p h1 h2 h3 h4 h5 h6 ol ul pre address blockquote dl div fieldset form hr noscript table].freeze def all_text normalize_spacing(native.text) end def visible_text normalize_visible_spacing(displayed_text) end def [](name) string_node[name] end def style(_styles) raise NotImplementedError, 'The rack_test driver does not process CSS' end def value string_node.value end def set(value, **options) return if disabled? || readonly? warn "Options passed to Node#set but the RackTest driver doesn't support any - ignoring" unless options.empty? if value.is_a?(Array) && !multiple? raise TypeError, "Value cannot be an Array when 'multiple' attribute is not present. Not a #{value.class}" end if radio? then set_radio(value) elsif checkbox? then set_checkbox(value) elsif range? then set_range(value) elsif input_field? then set_input(value) elsif textarea? then native['_capybara_raw_value'] = value.to_s end end def select_option return if disabled? deselect_options unless select_node.multiple? native['selected'] = 'selected' end def unselect_option raise Capybara::UnselectNotAllowed, 'Cannot unselect option from single select box.' unless select_node.multiple? native.remove_attribute('selected') end def click(keys = [], **options) options.delete(:offset) raise ArgumentError, 'The RackTest driver does not support click options' unless keys.empty? && options.empty? if link? follow_link elsif submits? associated_form = form Capybara::RackTest::Form.new(driver, associated_form).submit(self) if associated_form elsif checkable? set(!checked?) elsif tag_name == 'label' click_label elsif (details = native.xpath('.//ancestor-or-self::details').last) toggle_details(details) end end def tag_name native.node_name end def visible? string_node.visible? end def checked? string_node.checked? end def selected? string_node.selected? end def disabled? return true if string_node.disabled? if %w[option optgroup].include? tag_name find_xpath(OPTION_OWNER_XPATH)[0].disabled? else !find_xpath(DISABLED_BY_FIELDSET_XPATH).empty? end end def readonly? # readonly attribute not valid on these input types return false if input_field? && %w[hidden range color checkbox radio file submit image reset button].include?(type) super end def path native.path end def find_xpath(locator, **_hints) native.xpath(locator).map { |el| self.class.new(driver, el) } end def find_css(locator, **_hints) native.css(locator, Capybara::RackTest::CSSHandlers.new).map { |el| self.class.new(driver, el) } end public_instance_methods(false).each do |meth_name| alias_method "unchecked_#{meth_name}", meth_name private "unchecked_#{meth_name}" # rubocop:disable Style/AccessModifierDeclarations class_eval <<~METHOD, __FILE__, __LINE__ + 1 def #{meth_name}(...) stale_check method(:"unchecked_#{meth_name}").call(...) end METHOD end protected # @api private def displayed_text(check_ancestor: true) if !string_node.visible?(check_ancestor) '' elsif native.text? native .text .delete(REMOVED_CHARACTERS) .tr(SQUEEZED_SPACES, ' ') .squeeze(' ') elsif native.element? text = native.children.map do |child| Capybara::RackTest::Node.new(driver, child).displayed_text(check_ancestor: false) end.join || '' text = "\n#{text}\n" if BLOCK_ELEMENTS.include?(tag_name) text else # rubocop:disable Lint/DuplicateBranch '' end end private def stale_check raise Capybara::RackTest::Errors::StaleElementReferenceError unless native.document == driver.dom end def deselect_options select_node.find_xpath('.//option[@selected]').each { |node| node.native.remove_attribute('selected') } end def string_node @string_node ||= Capybara::Node::Simple.new(native) end # a reference to the select node if this is an option node def select_node find_xpath('./ancestor::select[1]').first end def type native[:type] end def form if native[:form] native.xpath("//form[@id='#{native[:form]}']") else native.ancestors('form') end.first end def set_radio(_value) # rubocop:disable Naming/AccessorMethodName other_radios_xpath = XPath.generate { |xp| xp.anywhere(:input)[xp.attr(:name) == self[:name]] }.to_s driver.dom.xpath(other_radios_xpath).each { |node| node.remove_attribute('checked') } native['checked'] = 'checked' end def set_checkbox(value) # rubocop:disable Naming/AccessorMethodName if value && !native['checked'] native['checked'] = 'checked' elsif !value && native['checked'] native.remove_attribute('checked') end end def set_range(value) # rubocop:disable Naming/AccessorMethodName min, max, step = (native['min'] || 0).to_f, (native['max'] || 100).to_f, (native['step'] || 1).to_f value = value.to_f value = value.clamp(min, max) value = (((value - min) / step).round * step) + min native['value'] = value.clamp(min, max) end def set_input(value) # rubocop:disable Naming/AccessorMethodName if text_or_password? && attribute_is_not_blank?(:maxlength) # Browser behavior for maxlength="0" is inconsistent, so we stick with # Firefox, allowing no input value = value.to_s[0...self[:maxlength].to_i] end if value.is_a?(Array) # Assert multiple attribute is present value.each do |val| new_native = native.clone new_native.remove_attribute('value') native.add_next_sibling(new_native) new_native['value'] = val.to_s end native.remove else value.to_s.tap do |set_value| if set_value.end_with?("\n") && (form&.css('input, textarea')&.count == 1) # rubocop:disable Style/CollectionQuerying native['value'] = set_value.to_s.chop Capybara::RackTest::Form.new(driver, form).submit(self) else native['value'] = set_value end end end end def attribute_is_not_blank?(attribute) self[attribute] && !self[attribute].empty? end def follow_link method = self['data-method'] || self['data-turbo-method'] if driver.options[:respect_data_method] method ||= :get driver.follow(method, self[:href].to_s) end def click_label labelled_control = if native[:for] find_xpath("//input[@id='#{native[:for]}']") else find_xpath('.//input') end.first labelled_control.set(!labelled_control.checked?) if checkbox_or_radio?(labelled_control) end def toggle_details(details = nil) details ||= native.xpath('.//ancestor-or-self::details').last return unless details if details.has_attribute?('open') details.remove_attribute('open') else details.set_attribute('open', 'open') end end def link? tag_name == 'a' && !self[:href].nil? end def submits? (tag_name == 'input' && %w[submit image].include?(type)) || (tag_name == 'button' && [nil, 'submit'].include?(type)) end def checkable? tag_name == 'input' && %w[checkbox radio].include?(type) end protected def checkbox_or_radio?(field = self) field&.checkbox? || field&.radio? end def checkbox? input_field? && type == 'checkbox' end def radio? input_field? && type == 'radio' end def text_or_password? input_field? && %w[text password].include?(type) end def input_field? tag_name == 'input' end def textarea? tag_name == 'textarea' end def range? input_field? && type == 'range' end OPTION_OWNER_XPATH = XPath.parent(:optgroup, :select, :datalist).to_s.freeze DISABLED_BY_FIELDSET_XPATH = XPath.generate do |x| x.parent(:fieldset)[ XPath.attr(:disabled) ] + x.ancestor[ ~x.self(:legend) | x.preceding_sibling(:legend) ][ x.parent(:fieldset)[ x.attr(:disabled) ] ] end.to_s.freeze end
Ruby
{ "end_line": 236, "name": "set_input", "signature": "def set_input(value) # rubocop:disable Naming/AccessorMethodName", "start_line": 212 }
{ "class_name": "Capybara::RackTest::Node", "class_signature": "class Capybara::RackTest::Node < < Capybara::Driver::Node", "module": "" }
split
capybara/lib/capybara/selector/css.rb
def split(css) selectors = [] StringIO.open(css.to_s) do |str| selector = +'' while (char = str.getc) case char when '[' selector << parse_square(str) when '(' selector << parse_paren(str) when '"', "'" selector << parse_string(char, str) when '\\' selector << (char + str.getc) when ',' selectors << selector.strip selector.clear else selector << char end end selectors << selector.strip end selectors end
# frozen_string_literal: true require 'capybara/selector/selector' module Capybara class Selector class CSS def self.escape(str) value = str.dup out = +'' out << value.slice!(0...1) if value.match?(/^[-_]/) out << (value[0].match?(NMSTART) ? value.slice!(0...1) : escape_char(value.slice!(0...1))) out << value.gsub(/[^a-zA-Z0-9_-]/) { |char| escape_char char } out end def self.escape_char(char) char.match?(%r{[ -/:-~]}) ? "\\#{char}" : format('\\%06<hex>x', hex: char.ord) end def self.split(css) Splitter.new.split(css) end S = '\u{80}-\u{D7FF}\u{E000}-\u{FFFD}\u{10000}-\u{10FFFF}' H = /[0-9a-fA-F]/ UNICODE = /\\#{H}{1,6}[ \t\r\n\f]?/ NONASCII = /[#{S}]/ ESCAPE = /#{UNICODE}|\\[ -~#{S}]/ NMSTART = /[_a-zA-Z]|#{NONASCII}|#{ESCAPE}/ class Splitter def split(css) selectors = [] StringIO.open(css.to_s) do |str| selector = +'' while (char = str.getc) case char when '[' selector << parse_square(str) when '(' selector << parse_paren(str) when '"', "'" selector << parse_string(char, str) when '\\' selector << (char + str.getc) when ',' selectors << selector.strip selector.clear else selector << char end end selectors << selector.strip end selectors end private def parse_square(strio) parse_block('[', ']', strio) end def parse_paren(strio) parse_block('(', ')', strio) end def parse_block(start, final, strio) block = start while (char = strio.getc) case char when final return block + char when '\\' block += char + strio.getc when '"', "'" block += parse_string(char, strio) else block += char end end raise ArgumentError, "Invalid CSS Selector - Block end '#{final}' not found" end def parse_string(quote, strio) string = quote while (char = strio.getc) string += char case char when quote return string when '\\' string += strio.getc end end raise ArgumentError, 'Invalid CSS Selector - string end not found' end end end end end
Ruby
{ "end_line": 57, "name": "split", "signature": "def split(css)", "start_line": 33 }
{ "class_name": "Selector", "class_signature": "class Selector", "module": "Capybara" }
parse_block
capybara/lib/capybara/selector/css.rb
def parse_block(start, final, strio) block = start while (char = strio.getc) case char when final return block + char when '\\' block += char + strio.getc when '"', "'" block += parse_string(char, strio) else block += char end end raise ArgumentError, "Invalid CSS Selector - Block end '#{final}' not found" end
# frozen_string_literal: true require 'capybara/selector/selector' module Capybara class Selector class CSS def self.escape(str) value = str.dup out = +'' out << value.slice!(0...1) if value.match?(/^[-_]/) out << (value[0].match?(NMSTART) ? value.slice!(0...1) : escape_char(value.slice!(0...1))) out << value.gsub(/[^a-zA-Z0-9_-]/) { |char| escape_char char } out end def self.escape_char(char) char.match?(%r{[ -/:-~]}) ? "\\#{char}" : format('\\%06<hex>x', hex: char.ord) end def self.split(css) Splitter.new.split(css) end S = '\u{80}-\u{D7FF}\u{E000}-\u{FFFD}\u{10000}-\u{10FFFF}' H = /[0-9a-fA-F]/ UNICODE = /\\#{H}{1,6}[ \t\r\n\f]?/ NONASCII = /[#{S}]/ ESCAPE = /#{UNICODE}|\\[ -~#{S}]/ NMSTART = /[_a-zA-Z]|#{NONASCII}|#{ESCAPE}/ class Splitter def split(css) selectors = [] StringIO.open(css.to_s) do |str| selector = +'' while (char = str.getc) case char when '[' selector << parse_square(str) when '(' selector << parse_paren(str) when '"', "'" selector << parse_string(char, str) when '\\' selector << (char + str.getc) when ',' selectors << selector.strip selector.clear else selector << char end end selectors << selector.strip end selectors end private def parse_square(strio) parse_block('[', ']', strio) end def parse_paren(strio) parse_block('(', ')', strio) end def parse_block(start, final, strio) block = start while (char = strio.getc) case char when final return block + char when '\\' block += char + strio.getc when '"', "'" block += parse_string(char, strio) else block += char end end raise ArgumentError, "Invalid CSS Selector - Block end '#{final}' not found" end def parse_string(quote, strio) string = quote while (char = strio.getc) string += char case char when quote return string when '\\' string += strio.getc end end raise ArgumentError, 'Invalid CSS Selector - string end not found' end end end end end
Ruby
{ "end_line": 84, "name": "parse_block", "signature": "def parse_block(start, final, strio)", "start_line": 69 }
{ "class_name": "Selector", "class_signature": "class Selector", "module": "Capybara" }
parse_string
capybara/lib/capybara/selector/css.rb
def parse_string(quote, strio) string = quote while (char = strio.getc) string += char case char when quote return string when '\\' string += strio.getc end end raise ArgumentError, 'Invalid CSS Selector - string end not found' end
# frozen_string_literal: true require 'capybara/selector/selector' module Capybara class Selector class CSS def self.escape(str) value = str.dup out = +'' out << value.slice!(0...1) if value.match?(/^[-_]/) out << (value[0].match?(NMSTART) ? value.slice!(0...1) : escape_char(value.slice!(0...1))) out << value.gsub(/[^a-zA-Z0-9_-]/) { |char| escape_char char } out end def self.escape_char(char) char.match?(%r{[ -/:-~]}) ? "\\#{char}" : format('\\%06<hex>x', hex: char.ord) end def self.split(css) Splitter.new.split(css) end S = '\u{80}-\u{D7FF}\u{E000}-\u{FFFD}\u{10000}-\u{10FFFF}' H = /[0-9a-fA-F]/ UNICODE = /\\#{H}{1,6}[ \t\r\n\f]?/ NONASCII = /[#{S}]/ ESCAPE = /#{UNICODE}|\\[ -~#{S}]/ NMSTART = /[_a-zA-Z]|#{NONASCII}|#{ESCAPE}/ class Splitter def split(css) selectors = [] StringIO.open(css.to_s) do |str| selector = +'' while (char = str.getc) case char when '[' selector << parse_square(str) when '(' selector << parse_paren(str) when '"', "'" selector << parse_string(char, str) when '\\' selector << (char + str.getc) when ',' selectors << selector.strip selector.clear else selector << char end end selectors << selector.strip end selectors end private def parse_square(strio) parse_block('[', ']', strio) end def parse_paren(strio) parse_block('(', ')', strio) end def parse_block(start, final, strio) block = start while (char = strio.getc) case char when final return block + char when '\\' block += char + strio.getc when '"', "'" block += parse_string(char, strio) else block += char end end raise ArgumentError, "Invalid CSS Selector - Block end '#{final}' not found" end def parse_string(quote, strio) string = quote while (char = strio.getc) string += char case char when quote return string when '\\' string += strio.getc end end raise ArgumentError, 'Invalid CSS Selector - string end not found' end end end end end
Ruby
{ "end_line": 98, "name": "parse_string", "signature": "def parse_string(quote, strio)", "start_line": 86 }
{ "class_name": "Selector", "class_signature": "class Selector", "module": "Capybara" }
initialize
capybara/lib/capybara/selector/definition.rb
def initialize(name, locator_type: nil, raw_locator: false, supports_exact: nil, &block) @name = name @filter_set = Capybara::Selector::FilterSet.add(name) @match = nil @label = nil @failure_message = nil @expressions = {} @expression_filters = {} @locator_filter = nil @default_visibility = nil @locator_type = locator_type @raw_locator = raw_locator @supports_exact = supports_exact instance_eval(&block) end
# frozen_string_literal: true require 'capybara/selector/filter_set' require 'capybara/selector/css' require 'capybara/selector/regexp_disassembler' require 'capybara/selector/builders/xpath_builder' require 'capybara/selector/builders/css_builder' module Capybara class Selector class Definition attr_reader :name, :expressions extend Forwardable def initialize(name, locator_type: nil, raw_locator: false, supports_exact: nil, &block) @name = name @filter_set = Capybara::Selector::FilterSet.add(name) @match = nil @label = nil @failure_message = nil @expressions = {} @expression_filters = {} @locator_filter = nil @default_visibility = nil @locator_type = locator_type @raw_locator = raw_locator @supports_exact = supports_exact instance_eval(&block) end def custom_filters warn "Deprecated: Selector#custom_filters is not valid when same named expression and node filter exist - don't use" node_filters.merge(expression_filters).freeze end def node_filters @filter_set.node_filters end def expression_filters @filter_set.expression_filters end ## # # Define a selector by an xpath expression # # @overload xpath(*expression_filters, &block) # @param [Array<Symbol>] expression_filters ([]) Names of filters that are implemented via this expression, if not specified the names of any keyword parameters in the block will be used # @yield [locator, options] The block to use to generate the XPath expression # @yieldparam [String] locator The locator string passed to the query # @yieldparam [Hash] options The options hash passed to the query # @yieldreturn [#to_xpath, #to_s] An object that can produce an xpath expression # # @overload xpath() # @return [#call] The block that will be called to generate the XPath expression # def xpath(*allowed_filters, &block) expression(:xpath, allowed_filters, &block) end ## # # Define a selector by a CSS selector # # @overload css(*expression_filters, &block) # @param [Array<Symbol>] expression_filters ([]) Names of filters that can be implemented via this CSS selector # @yield [locator, options] The block to use to generate the CSS selector # @yieldparam [String] locator The locator string passed to the query # @yieldparam [Hash] options The options hash passed to the query # @yieldreturn [#to_s] An object that can produce a CSS selector # # @overload css() # @return [#call] The block that will be called to generate the CSS selector # def css(*allowed_filters, &block) expression(:css, allowed_filters, &block) end ## # # Automatic selector detection # # @yield [locator] This block takes the passed in locator string and returns whether or not it matches the selector # @yieldparam [String], locator The locator string used to determine if it matches the selector # @yieldreturn [Boolean] Whether this selector matches the locator string # @return [#call] The block that will be used to detect selector match # def match(&block) @match = block if block @match end ## # # Set/get a descriptive label for the selector # # @overload label(label) # @param [String] label A descriptive label for this selector - used in error messages # @overload label() # @return [String] The currently set label # def label(label = nil) @label = label if label @label end ## # # Description of the selector # # @!method description(options) # @param [Hash] options The options of the query used to generate the description # @return [String] Description of the selector when used with the options passed def_delegator :@filter_set, :description ## # # Should this selector be used for the passed in locator # # This is used by the automatic selector selection mechanism when no selector type is passed to a selector query # # @param [String] locator The locator passed to the query # @return [Boolean] Whether or not to use this selector # def match?(locator) @match&.call(locator) end ## # # Define a node filter for use with this selector # # @!method node_filter(name, *types, options={}, &block) # @param [Symbol, Regexp] name The filter name # @param [Array<Symbol>] types The types of the filter - currently valid types are [:boolean] # @param [Hash] options ({}) Options of the filter # @option options [Array<>] :valid_values Valid values for this filter # @option options :default The default value of the filter (if any) # @option options :skip_if Value of the filter that will cause it to be skipped # @option options [Regexp] :matcher (nil) A Regexp used to check whether a specific option is handled by this filter. If not provided the filter will be used for options matching the filter name. # # If a Symbol is passed for the name the block should accept | node, option_value |, while if a Regexp # is passed for the name the block should accept | node, option_name, option_value |. In either case # the block should return `true` if the node passes the filer or `false` if it doesn't ## # # Define an expression filter for use with this selector # # @!method expression_filter(name, *types, matcher: nil, **options, &block) # @param [Symbol, Regexp] name The filter name # @param [Regexp] matcher (nil) A Regexp used to check whether a specific option is handled by this filter # @param [Array<Symbol>] types The types of the filter - currently valid types are [:boolean] # @param [Hash] options ({}) Options of the filter # @option options [Array<>] :valid_values Valid values for this filter # @option options :default The default value of the filter (if any) # @option options :skip_if Value of the filter that will cause it to be skipped # @option options [Regexp] :matcher (nil) A Regexp used to check whether a specific option is handled by this filter. If not provided the filter will be used for options matching the filter name. # # If a Symbol is passed for the name the block should accept | current_expression, option_value |, while if a Regexp # is passed for the name the block should accept | current_expression, option_name, option_value |. In either case # the block should return the modified expression def_delegators :@filter_set, :node_filter, :expression_filter, :filter def locator_filter(*types, **options, &block) types.each { |type| options[type] = true } @locator_filter = Capybara::Selector::Filters::LocatorFilter.new(block, **options) if block @locator_filter end def filter_set(name, filters_to_use = nil) @filter_set.import(name, filters_to_use) end def_delegator :@filter_set, :describe def describe_expression_filters(&block) if block describe(:expression_filters, &block) else describe(:expression_filters) do |**options| describe_all_expression_filters(**options) end end end def describe_all_expression_filters(**opts) expression_filters.map do |ef_name, ef| if ef.matcher? handled_custom_options(ef, opts).map { |option, value| " with #{ef_name}[#{option} => #{value}]" }.join elsif opts.key?(ef_name) " with #{ef_name} #{opts[ef_name]}" end end.join end def describe_node_filters(&block) describe(:node_filters, &block) end ## # # Set the default visibility mode that should be used if no visible option is passed when using the selector. # If not specified will default to the behavior indicated by Capybara.ignore_hidden_elements # # @param [Symbol] default_visibility Only find elements with the specified visibility: # * :all - finds visible and invisible elements. # * :hidden - only finds invisible elements. # * :visible - only finds visible elements. def visible(default_visibility = nil, &block) @default_visibility = block || default_visibility end def default_visibility(fallback = Capybara.ignore_hidden_elements, options = {}) vis = if @default_visibility.respond_to?(:call) @default_visibility.call(options) else @default_visibility end vis.nil? ? fallback : vis end # @api private def raw_locator? !!@raw_locator end # @api private def supports_exact? @supports_exact end def default_format return nil if @expressions.keys.empty? if @expressions.size == 1 @expressions.keys.first else :xpath end end # @api private def locator_types return nil unless @locator_type Array(@locator_type) end private def handled_custom_options(filter, options) options.select do |option, _| filter.handles_option?(option) && !::Capybara::Queries::SelectorQuery::VALID_KEYS.include?(option) end end def parameter_names(block) key_types = %i[key keyreq] # user filter_map when we drop dupport for 2.6 # block.parameters.select { |(type, _name)| key_types.include? type }.map { |(_, name)| name } block.parameters.filter_map { |(type, name)| name if key_types.include? type } end def expression(type, allowed_filters, &block) if block @expressions[type] = block allowed_filters = parameter_names(block) if allowed_filters.empty? allowed_filters.flatten.each do |ef| expression_filters[ef] = Capybara::Selector::Filters::IdentityExpressionFilter.new(ef) end end @expressions[type] end end end end
Ruby
{ "end_line": 30, "name": "initialize", "signature": "def initialize(name, locator_type: nil, raw_locator: false, supports_exact: nil, &block)", "start_line": 16 }
{ "class_name": "Selector", "class_signature": "class Selector", "module": "Capybara" }
expression
capybara/lib/capybara/selector/definition.rb
def expression(type, allowed_filters, &block) if block @expressions[type] = block allowed_filters = parameter_names(block) if allowed_filters.empty? allowed_filters.flatten.each do |ef| expression_filters[ef] = Capybara::Selector::Filters::IdentityExpressionFilter.new(ef) end end @expressions[type] end
# frozen_string_literal: true require 'capybara/selector/filter_set' require 'capybara/selector/css' require 'capybara/selector/regexp_disassembler' require 'capybara/selector/builders/xpath_builder' require 'capybara/selector/builders/css_builder' module Capybara class Selector class Definition attr_reader :name, :expressions extend Forwardable def initialize(name, locator_type: nil, raw_locator: false, supports_exact: nil, &block) @name = name @filter_set = Capybara::Selector::FilterSet.add(name) @match = nil @label = nil @failure_message = nil @expressions = {} @expression_filters = {} @locator_filter = nil @default_visibility = nil @locator_type = locator_type @raw_locator = raw_locator @supports_exact = supports_exact instance_eval(&block) end def custom_filters warn "Deprecated: Selector#custom_filters is not valid when same named expression and node filter exist - don't use" node_filters.merge(expression_filters).freeze end def node_filters @filter_set.node_filters end def expression_filters @filter_set.expression_filters end ## # # Define a selector by an xpath expression # # @overload xpath(*expression_filters, &block) # @param [Array<Symbol>] expression_filters ([]) Names of filters that are implemented via this expression, if not specified the names of any keyword parameters in the block will be used # @yield [locator, options] The block to use to generate the XPath expression # @yieldparam [String] locator The locator string passed to the query # @yieldparam [Hash] options The options hash passed to the query # @yieldreturn [#to_xpath, #to_s] An object that can produce an xpath expression # # @overload xpath() # @return [#call] The block that will be called to generate the XPath expression # def xpath(*allowed_filters, &block) expression(:xpath, allowed_filters, &block) end ## # # Define a selector by a CSS selector # # @overload css(*expression_filters, &block) # @param [Array<Symbol>] expression_filters ([]) Names of filters that can be implemented via this CSS selector # @yield [locator, options] The block to use to generate the CSS selector # @yieldparam [String] locator The locator string passed to the query # @yieldparam [Hash] options The options hash passed to the query # @yieldreturn [#to_s] An object that can produce a CSS selector # # @overload css() # @return [#call] The block that will be called to generate the CSS selector # def css(*allowed_filters, &block) expression(:css, allowed_filters, &block) end ## # # Automatic selector detection # # @yield [locator] This block takes the passed in locator string and returns whether or not it matches the selector # @yieldparam [String], locator The locator string used to determine if it matches the selector # @yieldreturn [Boolean] Whether this selector matches the locator string # @return [#call] The block that will be used to detect selector match # def match(&block) @match = block if block @match end ## # # Set/get a descriptive label for the selector # # @overload label(label) # @param [String] label A descriptive label for this selector - used in error messages # @overload label() # @return [String] The currently set label # def label(label = nil) @label = label if label @label end ## # # Description of the selector # # @!method description(options) # @param [Hash] options The options of the query used to generate the description # @return [String] Description of the selector when used with the options passed def_delegator :@filter_set, :description ## # # Should this selector be used for the passed in locator # # This is used by the automatic selector selection mechanism when no selector type is passed to a selector query # # @param [String] locator The locator passed to the query # @return [Boolean] Whether or not to use this selector # def match?(locator) @match&.call(locator) end ## # # Define a node filter for use with this selector # # @!method node_filter(name, *types, options={}, &block) # @param [Symbol, Regexp] name The filter name # @param [Array<Symbol>] types The types of the filter - currently valid types are [:boolean] # @param [Hash] options ({}) Options of the filter # @option options [Array<>] :valid_values Valid values for this filter # @option options :default The default value of the filter (if any) # @option options :skip_if Value of the filter that will cause it to be skipped # @option options [Regexp] :matcher (nil) A Regexp used to check whether a specific option is handled by this filter. If not provided the filter will be used for options matching the filter name. # # If a Symbol is passed for the name the block should accept | node, option_value |, while if a Regexp # is passed for the name the block should accept | node, option_name, option_value |. In either case # the block should return `true` if the node passes the filer or `false` if it doesn't ## # # Define an expression filter for use with this selector # # @!method expression_filter(name, *types, matcher: nil, **options, &block) # @param [Symbol, Regexp] name The filter name # @param [Regexp] matcher (nil) A Regexp used to check whether a specific option is handled by this filter # @param [Array<Symbol>] types The types of the filter - currently valid types are [:boolean] # @param [Hash] options ({}) Options of the filter # @option options [Array<>] :valid_values Valid values for this filter # @option options :default The default value of the filter (if any) # @option options :skip_if Value of the filter that will cause it to be skipped # @option options [Regexp] :matcher (nil) A Regexp used to check whether a specific option is handled by this filter. If not provided the filter will be used for options matching the filter name. # # If a Symbol is passed for the name the block should accept | current_expression, option_value |, while if a Regexp # is passed for the name the block should accept | current_expression, option_name, option_value |. In either case # the block should return the modified expression def_delegators :@filter_set, :node_filter, :expression_filter, :filter def locator_filter(*types, **options, &block) types.each { |type| options[type] = true } @locator_filter = Capybara::Selector::Filters::LocatorFilter.new(block, **options) if block @locator_filter end def filter_set(name, filters_to_use = nil) @filter_set.import(name, filters_to_use) end def_delegator :@filter_set, :describe def describe_expression_filters(&block) if block describe(:expression_filters, &block) else describe(:expression_filters) do |**options| describe_all_expression_filters(**options) end end end def describe_all_expression_filters(**opts) expression_filters.map do |ef_name, ef| if ef.matcher? handled_custom_options(ef, opts).map { |option, value| " with #{ef_name}[#{option} => #{value}]" }.join elsif opts.key?(ef_name) " with #{ef_name} #{opts[ef_name]}" end end.join end def describe_node_filters(&block) describe(:node_filters, &block) end ## # # Set the default visibility mode that should be used if no visible option is passed when using the selector. # If not specified will default to the behavior indicated by Capybara.ignore_hidden_elements # # @param [Symbol] default_visibility Only find elements with the specified visibility: # * :all - finds visible and invisible elements. # * :hidden - only finds invisible elements. # * :visible - only finds visible elements. def visible(default_visibility = nil, &block) @default_visibility = block || default_visibility end def default_visibility(fallback = Capybara.ignore_hidden_elements, options = {}) vis = if @default_visibility.respond_to?(:call) @default_visibility.call(options) else @default_visibility end vis.nil? ? fallback : vis end # @api private def raw_locator? !!@raw_locator end # @api private def supports_exact? @supports_exact end def default_format return nil if @expressions.keys.empty? if @expressions.size == 1 @expressions.keys.first else :xpath end end # @api private def locator_types return nil unless @locator_type Array(@locator_type) end private def handled_custom_options(filter, options) options.select do |option, _| filter.handles_option?(option) && !::Capybara::Queries::SelectorQuery::VALID_KEYS.include?(option) end end def parameter_names(block) key_types = %i[key keyreq] # user filter_map when we drop dupport for 2.6 # block.parameters.select { |(type, _name)| key_types.include? type }.map { |(_, name)| name } block.parameters.filter_map { |(type, name)| name if key_types.include? type } end def expression(type, allowed_filters, &block) if block @expressions[type] = block allowed_filters = parameter_names(block) if allowed_filters.empty? allowed_filters.flatten.each do |ef| expression_filters[ef] = Capybara::Selector::Filters::IdentityExpressionFilter.new(ef) end end @expressions[type] end end end end
Ruby
{ "end_line": 277, "name": "expression", "signature": "def expression(type, allowed_filters, &block)", "start_line": 268 }
{ "class_name": "Selector", "class_signature": "class Selector", "module": "Capybara" }
describe
capybara/lib/capybara/selector/filter_set.rb
def describe(what = nil, &block) case what when nil undeclared_descriptions.push block when :node_filters node_filter_descriptions.push block when :expression_filters expression_filter_descriptions.push block else raise ArgumentError, 'Unknown description type' end end
# frozen_string_literal: true require 'capybara/selector/filter' module Capybara class Selector class FilterSet attr_reader :node_filters, :expression_filters def initialize(name, &block) @name = name @node_filters = {} @expression_filters = {} @descriptions = Hash.new { |hsh, key| hsh[key] = [] } instance_eval(&block) if block end def node_filter(names, *types, **options, &block) Array(names).each do |name| add_filter(name, Filters::NodeFilter, *types, **options, &block) end end alias_method :filter, :node_filter def expression_filter(name, *types, **options, &block) add_filter(name, Filters::ExpressionFilter, *types, **options, &block) end def describe(what = nil, &block) case what when nil undeclared_descriptions.push block when :node_filters node_filter_descriptions.push block when :expression_filters expression_filter_descriptions.push block else raise ArgumentError, 'Unknown description type' end end def description(node_filters: true, expression_filters: true, **options) opts = options_with_defaults(options) description = +'' description << undeclared_descriptions.map { |desc| desc.call(**opts).to_s }.join description << expression_filter_descriptions.map { |desc| desc.call(**opts).to_s }.join if expression_filters description << node_filter_descriptions.map { |desc| desc.call(**opts).to_s }.join if node_filters description end def descriptions Capybara::Helpers.warn 'DEPRECATED: FilterSet#descriptions is deprecated without replacement' [undeclared_descriptions, node_filter_descriptions, expression_filter_descriptions].flatten end def import(name, filters = nil) filter_selector = filters.nil? ? ->(*) { true } : ->(filter_name, _) { filters.include? filter_name } self.class[name].tap do |f_set| expression_filters.merge!(f_set.expression_filters.select(&filter_selector)) node_filters.merge!(f_set.node_filters.select(&filter_selector)) f_set.undeclared_descriptions.each { |desc| describe(&desc) } f_set.expression_filter_descriptions.each { |desc| describe(:expression_filters, &desc) } f_set.node_filter_descriptions.each { |desc| describe(:node_filters, &desc) } end self end class << self def all @filter_sets ||= {} # rubocop:disable Naming/MemoizedInstanceVariableName end def [](name) all.fetch(name.to_sym) { |set_name| raise ArgumentError, "Unknown filter set (:#{set_name})" } end def add(name, &block) all[name.to_sym] = FilterSet.new(name.to_sym, &block) end def remove(name) all.delete(name.to_sym) end end protected def undeclared_descriptions @descriptions[:undeclared] end def node_filter_descriptions @descriptions[:node_filters] end def expression_filter_descriptions @descriptions[:expression_filters] end private def options_with_defaults(options) expression_filters .chain(node_filters) .filter_map { |name, filter| [name, filter.default] if filter.default? } .to_h.merge!(options) end def add_filter(name, filter_class, *types, matcher: nil, **options, &block) types.each { |type| options[type] = true } if matcher && options[:default] raise 'ArgumentError', ':default option is not supported for filters with a :matcher option' end filter = filter_class.new(name, matcher, block, **options) (filter_class <= Filters::ExpressionFilter ? @expression_filters : @node_filters)[name] = filter end end end end
Ruby
{ "end_line": 40, "name": "describe", "signature": "def describe(what = nil, &block)", "start_line": 29 }
{ "class_name": "Selector", "class_signature": "class Selector", "module": "Capybara" }
import
capybara/lib/capybara/selector/filter_set.rb
def import(name, filters = nil) filter_selector = filters.nil? ? ->(*) { true } : ->(filter_name, _) { filters.include? filter_name } self.class[name].tap do |f_set| expression_filters.merge!(f_set.expression_filters.select(&filter_selector)) node_filters.merge!(f_set.node_filters.select(&filter_selector)) f_set.undeclared_descriptions.each { |desc| describe(&desc) } f_set.expression_filter_descriptions.each { |desc| describe(:expression_filters, &desc) } f_set.node_filter_descriptions.each { |desc| describe(:node_filters, &desc) } end self end
# frozen_string_literal: true require 'capybara/selector/filter' module Capybara class Selector class FilterSet attr_reader :node_filters, :expression_filters def initialize(name, &block) @name = name @node_filters = {} @expression_filters = {} @descriptions = Hash.new { |hsh, key| hsh[key] = [] } instance_eval(&block) if block end def node_filter(names, *types, **options, &block) Array(names).each do |name| add_filter(name, Filters::NodeFilter, *types, **options, &block) end end alias_method :filter, :node_filter def expression_filter(name, *types, **options, &block) add_filter(name, Filters::ExpressionFilter, *types, **options, &block) end def describe(what = nil, &block) case what when nil undeclared_descriptions.push block when :node_filters node_filter_descriptions.push block when :expression_filters expression_filter_descriptions.push block else raise ArgumentError, 'Unknown description type' end end def description(node_filters: true, expression_filters: true, **options) opts = options_with_defaults(options) description = +'' description << undeclared_descriptions.map { |desc| desc.call(**opts).to_s }.join description << expression_filter_descriptions.map { |desc| desc.call(**opts).to_s }.join if expression_filters description << node_filter_descriptions.map { |desc| desc.call(**opts).to_s }.join if node_filters description end def descriptions Capybara::Helpers.warn 'DEPRECATED: FilterSet#descriptions is deprecated without replacement' [undeclared_descriptions, node_filter_descriptions, expression_filter_descriptions].flatten end def import(name, filters = nil) filter_selector = filters.nil? ? ->(*) { true } : ->(filter_name, _) { filters.include? filter_name } self.class[name].tap do |f_set| expression_filters.merge!(f_set.expression_filters.select(&filter_selector)) node_filters.merge!(f_set.node_filters.select(&filter_selector)) f_set.undeclared_descriptions.each { |desc| describe(&desc) } f_set.expression_filter_descriptions.each { |desc| describe(:expression_filters, &desc) } f_set.node_filter_descriptions.each { |desc| describe(:node_filters, &desc) } end self end class << self def all @filter_sets ||= {} # rubocop:disable Naming/MemoizedInstanceVariableName end def [](name) all.fetch(name.to_sym) { |set_name| raise ArgumentError, "Unknown filter set (:#{set_name})" } end def add(name, &block) all[name.to_sym] = FilterSet.new(name.to_sym, &block) end def remove(name) all.delete(name.to_sym) end end protected def undeclared_descriptions @descriptions[:undeclared] end def node_filter_descriptions @descriptions[:node_filters] end def expression_filter_descriptions @descriptions[:expression_filters] end private def options_with_defaults(options) expression_filters .chain(node_filters) .filter_map { |name, filter| [name, filter.default] if filter.default? } .to_h.merge!(options) end def add_filter(name, filter_class, *types, matcher: nil, **options, &block) types.each { |type| options[type] = true } if matcher && options[:default] raise 'ArgumentError', ':default option is not supported for filters with a :matcher option' end filter = filter_class.new(name, matcher, block, **options) (filter_class <= Filters::ExpressionFilter ? @expression_filters : @node_filters)[name] = filter end end end end
Ruby
{ "end_line": 67, "name": "import", "signature": "def import(name, filters = nil)", "start_line": 56 }
{ "class_name": "Selector", "class_signature": "class Selector", "module": "Capybara" }
combine
capybara/lib/capybara/selector/regexp_disassembler.rb
def combine(strs) suffixes = [[]] strs.reverse_each do |str| if str.is_a? Set prefixes = str.flat_map { |s| combine(s) } suffixes = prefixes.product(suffixes).map { |pair| pair.flatten(1) } else suffixes.each { |arr| arr.unshift str } end end suffixes end
# frozen_string_literal: true require 'regexp_parser' module Capybara class Selector # @api private class RegexpDisassembler def initialize(regexp) @regexp = regexp end def alternated_substrings @alternated_substrings ||= begin or_strings = process(alternation: true) remove_or_covered(or_strings) or_strings.any?(&:empty?) ? [] : or_strings end end def substrings @substrings ||= begin strs = process(alternation: false).first remove_and_covered(strs) end end private def remove_and_covered(strings) # delete_if is documented to modify the array after every block iteration - this doesn't appear to be true # uniq the strings to prevent identical strings from removing each other strings.uniq! # If we have "ab" and "abcd" required - only need to check for "abcd" strings.delete_if do |sub_string| strings.any? do |cover_string| next if sub_string.equal? cover_string cover_string.include?(sub_string) end end end def remove_or_covered(or_series) # If we are going to match `("a" and "b") or ("ade" and "bce")` it only makes sense to match ("a" and "b") # Ensure minimum sets of strings are being or'd or_series.each { |strs| remove_and_covered(strs) } # Remove any of the alternated string series that fully contain any other string series or_series.delete_if do |and_strs| or_series.any? do |and_strs2| next if and_strs.equal? and_strs2 remove_and_covered(and_strs + and_strs2) == and_strs end end end def process(alternation:) strs = extract_strings(Regexp::Parser.parse(@regexp), alternation: alternation) strs = collapse(combine(strs).map(&:flatten)) strs.each { |str| str.map!(&:upcase) } if @regexp.casefold? strs end def combine(strs) suffixes = [[]] strs.reverse_each do |str| if str.is_a? Set prefixes = str.flat_map { |s| combine(s) } suffixes = prefixes.product(suffixes).map { |pair| pair.flatten(1) } else suffixes.each { |arr| arr.unshift str } end end suffixes end def collapse(strs) strs.map do |substrings| substrings.slice_before(&:nil?).map(&:join).reject(&:empty?).uniq end end def extract_strings(expression, alternation: false) Expression.new(expression).extract_strings(alternation) end # @api private class Expression def initialize(exp) @exp = exp end def extract_strings(process_alternatives) strings = [] each do |exp| next if exp.ignore? next strings.push(nil) if exp.optional? && !process_alternatives next strings.push(exp.alternative_strings) if exp.alternation? && process_alternatives strings.concat(exp.strings(process_alternatives)) end strings end protected def alternation? (type == :meta) && !terminal? end def optional? min_repeat.zero? end def terminal? @exp.terminal? end def strings(process_alternatives) if indeterminate? [nil] elsif terminal? terminal_strings elsif optional? optional_strings else repeated_strings(process_alternatives) end end def terminal_strings text = case @exp.type when :literal then @exp.text when :escape then @exp.char else return [nil] end optional? ? options_set(text) : repeat_set(text) end def optional_strings options_set(extract_strings(true)) end def repeated_strings(process_alternatives) repeat_set extract_strings(process_alternatives) end def alternative_strings alts = alternatives.map { |sub_exp| sub_exp.extract_strings(alternation: true) } alts.all?(&:any?) ? Set.new(alts) : nil end def ignore? [Regexp::Expression::Assertion::NegativeLookahead, Regexp::Expression::Assertion::NegativeLookbehind].any? { |klass| @exp.is_a? klass } end private def indeterminate? %i[meta set].include?(type) end def min_repeat @exp.repetitions.begin end def max_repeat @exp.repetitions.end end def fixed_repeat? min_repeat == max_repeat end def type @exp.type end def repeat_set(str) strs = Array(str * min_repeat) strs.push(nil) unless fixed_repeat? strs end def options_set(strs) strs = [Set.new([[''], Array(strs)])] strs.push(nil) unless max_repeat == 1 strs end def alternatives @exp.alternatives.map { |exp| Expression.new(exp) } end def each @exp.each { |exp| yield Expression.new(exp) } end end private_constant :Expression end end end
Ruby
{ "end_line": 79, "name": "combine", "signature": "def combine(strs)", "start_line": 68 }
{ "class_name": "Selector", "class_signature": "class Selector", "module": "Capybara" }
extract_strings
capybara/lib/capybara/selector/regexp_disassembler.rb
def extract_strings(process_alternatives) strings = [] each do |exp| next if exp.ignore? next strings.push(nil) if exp.optional? && !process_alternatives next strings.push(exp.alternative_strings) if exp.alternation? && process_alternatives strings.concat(exp.strings(process_alternatives)) end strings end
# frozen_string_literal: true require 'regexp_parser' module Capybara class Selector # @api private class RegexpDisassembler def initialize(regexp) @regexp = regexp end def alternated_substrings @alternated_substrings ||= begin or_strings = process(alternation: true) remove_or_covered(or_strings) or_strings.any?(&:empty?) ? [] : or_strings end end def substrings @substrings ||= begin strs = process(alternation: false).first remove_and_covered(strs) end end private def remove_and_covered(strings) # delete_if is documented to modify the array after every block iteration - this doesn't appear to be true # uniq the strings to prevent identical strings from removing each other strings.uniq! # If we have "ab" and "abcd" required - only need to check for "abcd" strings.delete_if do |sub_string| strings.any? do |cover_string| next if sub_string.equal? cover_string cover_string.include?(sub_string) end end end def remove_or_covered(or_series) # If we are going to match `("a" and "b") or ("ade" and "bce")` it only makes sense to match ("a" and "b") # Ensure minimum sets of strings are being or'd or_series.each { |strs| remove_and_covered(strs) } # Remove any of the alternated string series that fully contain any other string series or_series.delete_if do |and_strs| or_series.any? do |and_strs2| next if and_strs.equal? and_strs2 remove_and_covered(and_strs + and_strs2) == and_strs end end end def process(alternation:) strs = extract_strings(Regexp::Parser.parse(@regexp), alternation: alternation) strs = collapse(combine(strs).map(&:flatten)) strs.each { |str| str.map!(&:upcase) } if @regexp.casefold? strs end def combine(strs) suffixes = [[]] strs.reverse_each do |str| if str.is_a? Set prefixes = str.flat_map { |s| combine(s) } suffixes = prefixes.product(suffixes).map { |pair| pair.flatten(1) } else suffixes.each { |arr| arr.unshift str } end end suffixes end def collapse(strs) strs.map do |substrings| substrings.slice_before(&:nil?).map(&:join).reject(&:empty?).uniq end end def extract_strings(expression, alternation: false) Expression.new(expression).extract_strings(alternation) end # @api private class Expression def initialize(exp) @exp = exp end def extract_strings(process_alternatives) strings = [] each do |exp| next if exp.ignore? next strings.push(nil) if exp.optional? && !process_alternatives next strings.push(exp.alternative_strings) if exp.alternation? && process_alternatives strings.concat(exp.strings(process_alternatives)) end strings end protected def alternation? (type == :meta) && !terminal? end def optional? min_repeat.zero? end def terminal? @exp.terminal? end def strings(process_alternatives) if indeterminate? [nil] elsif terminal? terminal_strings elsif optional? optional_strings else repeated_strings(process_alternatives) end end def terminal_strings text = case @exp.type when :literal then @exp.text when :escape then @exp.char else return [nil] end optional? ? options_set(text) : repeat_set(text) end def optional_strings options_set(extract_strings(true)) end def repeated_strings(process_alternatives) repeat_set extract_strings(process_alternatives) end def alternative_strings alts = alternatives.map { |sub_exp| sub_exp.extract_strings(alternation: true) } alts.all?(&:any?) ? Set.new(alts) : nil end def ignore? [Regexp::Expression::Assertion::NegativeLookahead, Regexp::Expression::Assertion::NegativeLookbehind].any? { |klass| @exp.is_a? klass } end private def indeterminate? %i[meta set].include?(type) end def min_repeat @exp.repetitions.begin end def max_repeat @exp.repetitions.end end def fixed_repeat? min_repeat == max_repeat end def type @exp.type end def repeat_set(str) strs = Array(str * min_repeat) strs.push(nil) unless fixed_repeat? strs end def options_set(strs) strs = [Set.new([[''], Array(strs)])] strs.push(nil) unless max_repeat == 1 strs end def alternatives @exp.alternatives.map { |exp| Expression.new(exp) } end def each @exp.each { |exp| yield Expression.new(exp) } end end private_constant :Expression end end end
Ruby
{ "end_line": 109, "name": "extract_strings", "signature": "def extract_strings(process_alternatives)", "start_line": 97 }
{ "class_name": "Selector", "class_signature": "class Selector", "module": "Capybara" }
strings
capybara/lib/capybara/selector/regexp_disassembler.rb
def strings(process_alternatives) if indeterminate? [nil] elsif terminal? terminal_strings elsif optional? optional_strings else repeated_strings(process_alternatives) end end
# frozen_string_literal: true require 'regexp_parser' module Capybara class Selector # @api private class RegexpDisassembler def initialize(regexp) @regexp = regexp end def alternated_substrings @alternated_substrings ||= begin or_strings = process(alternation: true) remove_or_covered(or_strings) or_strings.any?(&:empty?) ? [] : or_strings end end def substrings @substrings ||= begin strs = process(alternation: false).first remove_and_covered(strs) end end private def remove_and_covered(strings) # delete_if is documented to modify the array after every block iteration - this doesn't appear to be true # uniq the strings to prevent identical strings from removing each other strings.uniq! # If we have "ab" and "abcd" required - only need to check for "abcd" strings.delete_if do |sub_string| strings.any? do |cover_string| next if sub_string.equal? cover_string cover_string.include?(sub_string) end end end def remove_or_covered(or_series) # If we are going to match `("a" and "b") or ("ade" and "bce")` it only makes sense to match ("a" and "b") # Ensure minimum sets of strings are being or'd or_series.each { |strs| remove_and_covered(strs) } # Remove any of the alternated string series that fully contain any other string series or_series.delete_if do |and_strs| or_series.any? do |and_strs2| next if and_strs.equal? and_strs2 remove_and_covered(and_strs + and_strs2) == and_strs end end end def process(alternation:) strs = extract_strings(Regexp::Parser.parse(@regexp), alternation: alternation) strs = collapse(combine(strs).map(&:flatten)) strs.each { |str| str.map!(&:upcase) } if @regexp.casefold? strs end def combine(strs) suffixes = [[]] strs.reverse_each do |str| if str.is_a? Set prefixes = str.flat_map { |s| combine(s) } suffixes = prefixes.product(suffixes).map { |pair| pair.flatten(1) } else suffixes.each { |arr| arr.unshift str } end end suffixes end def collapse(strs) strs.map do |substrings| substrings.slice_before(&:nil?).map(&:join).reject(&:empty?).uniq end end def extract_strings(expression, alternation: false) Expression.new(expression).extract_strings(alternation) end # @api private class Expression def initialize(exp) @exp = exp end def extract_strings(process_alternatives) strings = [] each do |exp| next if exp.ignore? next strings.push(nil) if exp.optional? && !process_alternatives next strings.push(exp.alternative_strings) if exp.alternation? && process_alternatives strings.concat(exp.strings(process_alternatives)) end strings end protected def alternation? (type == :meta) && !terminal? end def optional? min_repeat.zero? end def terminal? @exp.terminal? end def strings(process_alternatives) if indeterminate? [nil] elsif terminal? terminal_strings elsif optional? optional_strings else repeated_strings(process_alternatives) end end def terminal_strings text = case @exp.type when :literal then @exp.text when :escape then @exp.char else return [nil] end optional? ? options_set(text) : repeat_set(text) end def optional_strings options_set(extract_strings(true)) end def repeated_strings(process_alternatives) repeat_set extract_strings(process_alternatives) end def alternative_strings alts = alternatives.map { |sub_exp| sub_exp.extract_strings(alternation: true) } alts.all?(&:any?) ? Set.new(alts) : nil end def ignore? [Regexp::Expression::Assertion::NegativeLookahead, Regexp::Expression::Assertion::NegativeLookbehind].any? { |klass| @exp.is_a? klass } end private def indeterminate? %i[meta set].include?(type) end def min_repeat @exp.repetitions.begin end def max_repeat @exp.repetitions.end end def fixed_repeat? min_repeat == max_repeat end def type @exp.type end def repeat_set(str) strs = Array(str * min_repeat) strs.push(nil) unless fixed_repeat? strs end def options_set(strs) strs = [Set.new([[''], Array(strs)])] strs.push(nil) unless max_repeat == 1 strs end def alternatives @exp.alternatives.map { |exp| Expression.new(exp) } end def each @exp.each { |exp| yield Expression.new(exp) } end end private_constant :Expression end end end
Ruby
{ "end_line": 135, "name": "strings", "signature": "def strings(process_alternatives)", "start_line": 125 }
{ "class_name": "Selector", "class_signature": "class Selector", "module": "Capybara" }
call
capybara/lib/capybara/selector/selector.rb
def call(locator, **options) if format raise ArgumentError, "Selector #{@name} does not support #{format}" unless expressions.key?(format) instance_exec(locator, **options, &expressions[format]) else warn 'Selector has no format' end ensure unless locator_valid?(locator) Capybara::Helpers.warn( "Locator #{locator.class}:#{locator.inspect} for selector #{name.inspect} must #{locator_description}. " \ 'This will raise an error in a future version of Capybara. ' \ "Called from: #{Capybara::Helpers.filter_backtrace(caller)}" ) end end
# frozen_string_literal: true module Capybara class Selector < SimpleDelegator class << self def all @definitions ||= {} # rubocop:disable Naming/MemoizedInstanceVariableName end def [](name) all.fetch(name.to_sym) { |sel_type| raise ArgumentError, "Unknown selector type (:#{sel_type})" } end def add(name, **options, &block) all[name.to_sym] = Definition.new(name.to_sym, **options, &block) end def update(name, &block) self[name].instance_eval(&block) end def remove(name) all.delete(name.to_sym) end def for(locator) all.values.find { |sel| sel.match?(locator) } end end attr_reader :errors def initialize(definition, config:, format:) definition = self.class[definition] unless definition.is_a? Definition super(definition) @definition = definition @config = config @format = format @errors = [] end def format @format || @definition.default_format end alias_method :current_format, :format def enable_aria_label @config[:enable_aria_label] end def enable_aria_role @config[:enable_aria_role] end def test_id @config[:test_id] end def call(locator, **options) if format raise ArgumentError, "Selector #{@name} does not support #{format}" unless expressions.key?(format) instance_exec(locator, **options, &expressions[format]) else warn 'Selector has no format' end ensure unless locator_valid?(locator) Capybara::Helpers.warn( "Locator #{locator.class}:#{locator.inspect} for selector #{name.inspect} must #{locator_description}. " \ 'This will raise an error in a future version of Capybara. ' \ "Called from: #{Capybara::Helpers.filter_backtrace(caller)}" ) end end def add_error(error_msg) errors << error_msg end def expression_for(name, locator, config: @config, format: current_format, **options) Selector.new(name, config: config, format: format).call(locator, **options) end # @api private def with_filter_errors(errors) old_errors = @errors @errors = errors yield ensure @errors = old_errors end # @api private def builder(expr = nil) case format when :css Capybara::Selector::CSSBuilder when :xpath Capybara::Selector::XPathBuilder else raise NotImplementedError, "No builder exists for selector of type #{default_format}" end.new(expr) end private def locator_description locator_types.group_by { |lt| lt.is_a? Symbol }.map do |symbol, types_or_methods| if symbol "respond to #{types_or_methods.join(' or ')}" else "be an instance of #{types_or_methods.join(' or ')}" end end.join(' or ') end def locator_valid?(locator) return true unless locator && locator_types locator_types&.any? do |type_or_method| type_or_method.is_a?(Symbol) ? locator.respond_to?(type_or_method) : type_or_method === locator # rubocop:disable Style/CaseEquality end end def locate_field(xpath, locator, **_options) return xpath if locator.nil? locate_xpath = xpath # Need to save original xpath for the label wrap locator = locator.to_s attr_matchers = [XPath.attr(:id) == locator, XPath.attr(:name) == locator, XPath.attr(:placeholder) == locator, XPath.attr(:id) == XPath.anywhere(:label)[XPath.string.n.is(locator)].attr(:for)].reduce(:|) attr_matchers |= XPath.attr(:'aria-label').is(locator) if enable_aria_label attr_matchers |= XPath.attr(test_id) == locator if test_id locate_xpath = locate_xpath[attr_matchers] locate_xpath + locate_label(locator).descendant(xpath) end def locate_label(locator) XPath.descendant(:label)[XPath.string.n.is(locator)] end def find_by_attr(attribute, value) finder_name = "find_by_#{attribute}_attr" if respond_to?(finder_name, true) send(finder_name, value) else value ? XPath.attr(attribute) == value : nil end end def find_by_class_attr(classes) Array(classes).map { |klass| XPath.attr(:class).contains_word(klass) }.reduce(:&) end end end
Ruby
{ "end_line": 75, "name": "call", "signature": "def call(locator, **options)", "start_line": 59 }
{ "class_name": "Selector", "class_signature": "class Selector < < SimpleDelegator", "module": "Capybara" }
builder
capybara/lib/capybara/selector/selector.rb
def builder(expr = nil) case format when :css Capybara::Selector::CSSBuilder when :xpath Capybara::Selector::XPathBuilder else raise NotImplementedError, "No builder exists for selector of type #{default_format}" end.new(expr) end
# frozen_string_literal: true module Capybara class Selector < SimpleDelegator class << self def all @definitions ||= {} # rubocop:disable Naming/MemoizedInstanceVariableName end def [](name) all.fetch(name.to_sym) { |sel_type| raise ArgumentError, "Unknown selector type (:#{sel_type})" } end def add(name, **options, &block) all[name.to_sym] = Definition.new(name.to_sym, **options, &block) end def update(name, &block) self[name].instance_eval(&block) end def remove(name) all.delete(name.to_sym) end def for(locator) all.values.find { |sel| sel.match?(locator) } end end attr_reader :errors def initialize(definition, config:, format:) definition = self.class[definition] unless definition.is_a? Definition super(definition) @definition = definition @config = config @format = format @errors = [] end def format @format || @definition.default_format end alias_method :current_format, :format def enable_aria_label @config[:enable_aria_label] end def enable_aria_role @config[:enable_aria_role] end def test_id @config[:test_id] end def call(locator, **options) if format raise ArgumentError, "Selector #{@name} does not support #{format}" unless expressions.key?(format) instance_exec(locator, **options, &expressions[format]) else warn 'Selector has no format' end ensure unless locator_valid?(locator) Capybara::Helpers.warn( "Locator #{locator.class}:#{locator.inspect} for selector #{name.inspect} must #{locator_description}. " \ 'This will raise an error in a future version of Capybara. ' \ "Called from: #{Capybara::Helpers.filter_backtrace(caller)}" ) end end def add_error(error_msg) errors << error_msg end def expression_for(name, locator, config: @config, format: current_format, **options) Selector.new(name, config: config, format: format).call(locator, **options) end # @api private def with_filter_errors(errors) old_errors = @errors @errors = errors yield ensure @errors = old_errors end # @api private def builder(expr = nil) case format when :css Capybara::Selector::CSSBuilder when :xpath Capybara::Selector::XPathBuilder else raise NotImplementedError, "No builder exists for selector of type #{default_format}" end.new(expr) end private def locator_description locator_types.group_by { |lt| lt.is_a? Symbol }.map do |symbol, types_or_methods| if symbol "respond to #{types_or_methods.join(' or ')}" else "be an instance of #{types_or_methods.join(' or ')}" end end.join(' or ') end def locator_valid?(locator) return true unless locator && locator_types locator_types&.any? do |type_or_method| type_or_method.is_a?(Symbol) ? locator.respond_to?(type_or_method) : type_or_method === locator # rubocop:disable Style/CaseEquality end end def locate_field(xpath, locator, **_options) return xpath if locator.nil? locate_xpath = xpath # Need to save original xpath for the label wrap locator = locator.to_s attr_matchers = [XPath.attr(:id) == locator, XPath.attr(:name) == locator, XPath.attr(:placeholder) == locator, XPath.attr(:id) == XPath.anywhere(:label)[XPath.string.n.is(locator)].attr(:for)].reduce(:|) attr_matchers |= XPath.attr(:'aria-label').is(locator) if enable_aria_label attr_matchers |= XPath.attr(test_id) == locator if test_id locate_xpath = locate_xpath[attr_matchers] locate_xpath + locate_label(locator).descendant(xpath) end def locate_label(locator) XPath.descendant(:label)[XPath.string.n.is(locator)] end def find_by_attr(attribute, value) finder_name = "find_by_#{attribute}_attr" if respond_to?(finder_name, true) send(finder_name, value) else value ? XPath.attr(attribute) == value : nil end end def find_by_class_attr(classes) Array(classes).map { |klass| XPath.attr(:class).contains_word(klass) }.reduce(:&) end end end
Ruby
{ "end_line": 104, "name": "builder", "signature": "def builder(expr = nil)", "start_line": 95 }
{ "class_name": "Selector", "class_signature": "class Selector < < SimpleDelegator", "module": "Capybara" }
locate_field
capybara/lib/capybara/selector/selector.rb
def locate_field(xpath, locator, **_options) return xpath if locator.nil? locate_xpath = xpath # Need to save original xpath for the label wrap locator = locator.to_s attr_matchers = [XPath.attr(:id) == locator, XPath.attr(:name) == locator, XPath.attr(:placeholder) == locator, XPath.attr(:id) == XPath.anywhere(:label)[XPath.string.n.is(locator)].attr(:for)].reduce(:|) attr_matchers |= XPath.attr(:'aria-label').is(locator) if enable_aria_label attr_matchers |= XPath.attr(test_id) == locator if test_id locate_xpath = locate_xpath[attr_matchers] locate_xpath + locate_label(locator).descendant(xpath) end
# frozen_string_literal: true module Capybara class Selector < SimpleDelegator class << self def all @definitions ||= {} # rubocop:disable Naming/MemoizedInstanceVariableName end def [](name) all.fetch(name.to_sym) { |sel_type| raise ArgumentError, "Unknown selector type (:#{sel_type})" } end def add(name, **options, &block) all[name.to_sym] = Definition.new(name.to_sym, **options, &block) end def update(name, &block) self[name].instance_eval(&block) end def remove(name) all.delete(name.to_sym) end def for(locator) all.values.find { |sel| sel.match?(locator) } end end attr_reader :errors def initialize(definition, config:, format:) definition = self.class[definition] unless definition.is_a? Definition super(definition) @definition = definition @config = config @format = format @errors = [] end def format @format || @definition.default_format end alias_method :current_format, :format def enable_aria_label @config[:enable_aria_label] end def enable_aria_role @config[:enable_aria_role] end def test_id @config[:test_id] end def call(locator, **options) if format raise ArgumentError, "Selector #{@name} does not support #{format}" unless expressions.key?(format) instance_exec(locator, **options, &expressions[format]) else warn 'Selector has no format' end ensure unless locator_valid?(locator) Capybara::Helpers.warn( "Locator #{locator.class}:#{locator.inspect} for selector #{name.inspect} must #{locator_description}. " \ 'This will raise an error in a future version of Capybara. ' \ "Called from: #{Capybara::Helpers.filter_backtrace(caller)}" ) end end def add_error(error_msg) errors << error_msg end def expression_for(name, locator, config: @config, format: current_format, **options) Selector.new(name, config: config, format: format).call(locator, **options) end # @api private def with_filter_errors(errors) old_errors = @errors @errors = errors yield ensure @errors = old_errors end # @api private def builder(expr = nil) case format when :css Capybara::Selector::CSSBuilder when :xpath Capybara::Selector::XPathBuilder else raise NotImplementedError, "No builder exists for selector of type #{default_format}" end.new(expr) end private def locator_description locator_types.group_by { |lt| lt.is_a? Symbol }.map do |symbol, types_or_methods| if symbol "respond to #{types_or_methods.join(' or ')}" else "be an instance of #{types_or_methods.join(' or ')}" end end.join(' or ') end def locator_valid?(locator) return true unless locator && locator_types locator_types&.any? do |type_or_method| type_or_method.is_a?(Symbol) ? locator.respond_to?(type_or_method) : type_or_method === locator # rubocop:disable Style/CaseEquality end end def locate_field(xpath, locator, **_options) return xpath if locator.nil? locate_xpath = xpath # Need to save original xpath for the label wrap locator = locator.to_s attr_matchers = [XPath.attr(:id) == locator, XPath.attr(:name) == locator, XPath.attr(:placeholder) == locator, XPath.attr(:id) == XPath.anywhere(:label)[XPath.string.n.is(locator)].attr(:for)].reduce(:|) attr_matchers |= XPath.attr(:'aria-label').is(locator) if enable_aria_label attr_matchers |= XPath.attr(test_id) == locator if test_id locate_xpath = locate_xpath[attr_matchers] locate_xpath + locate_label(locator).descendant(xpath) end def locate_label(locator) XPath.descendant(:label)[XPath.string.n.is(locator)] end def find_by_attr(attribute, value) finder_name = "find_by_#{attribute}_attr" if respond_to?(finder_name, true) send(finder_name, value) else value ? XPath.attr(attribute) == value : nil end end def find_by_class_attr(classes) Array(classes).map { |klass| XPath.attr(:class).contains_word(klass) }.reduce(:&) end end end
Ruby
{ "end_line": 140, "name": "locate_field", "signature": "def locate_field(xpath, locator, **_options)", "start_line": 126 }
{ "class_name": "Selector", "class_signature": "class Selector < < SimpleDelegator", "module": "Capybara" }
load_selenium
capybara/lib/capybara/selenium/driver.rb
def load_selenium require 'selenium-webdriver' require 'capybara/selenium/patches/atoms' require 'capybara/selenium/patches/is_displayed' # Look up the version of `selenium-webdriver` to # see if it's a version we support. # # By default, we use Gem.loaded_specs to determine # the version number. However, in some cases, such # as when loading `selenium-webdriver` outside of # Rubygems, we fall back to referencing # Selenium::WebDriver::VERSION. Ideally we'd # use the constant in all cases, but earlier versions # of `selenium-webdriver` didn't provide the constant. @selenium_webdriver_version = if Gem.loaded_specs['selenium-webdriver'] Gem.loaded_specs['selenium-webdriver'].version else Gem::Version.new(Selenium::WebDriver::VERSION) end unless Gem::Requirement.new('>= 4.8').satisfied_by? @selenium_webdriver_version warn "Warning: You're using an unsupported version of selenium-webdriver, please upgrade to 4.8+." end @selenium_webdriver_version rescue LoadError => e raise e unless e.message.include?('selenium-webdriver') raise LoadError, "Capybara's selenium driver is unable to load `selenium-webdriver`, please install the gem and add `gem 'selenium-webdriver'` to your Gemfile if you are using bundler." end
# frozen_string_literal: true require 'uri' require 'English' class Capybara::Selenium::Driver < Capybara::Driver::Base include Capybara::Selenium::Find DEFAULT_OPTIONS = { browser: :firefox, clear_local_storage: nil, clear_session_storage: nil }.freeze SPECIAL_OPTIONS = %i[browser clear_local_storage clear_session_storage timeout native_displayed].freeze CAPS_VERSION = Gem::Requirement.new('< 4.8.0') attr_reader :app, :options class << self attr_reader :selenium_webdriver_version def load_selenium require 'selenium-webdriver' require 'capybara/selenium/patches/atoms' require 'capybara/selenium/patches/is_displayed' # Look up the version of `selenium-webdriver` to # see if it's a version we support. # # By default, we use Gem.loaded_specs to determine # the version number. However, in some cases, such # as when loading `selenium-webdriver` outside of # Rubygems, we fall back to referencing # Selenium::WebDriver::VERSION. Ideally we'd # use the constant in all cases, but earlier versions # of `selenium-webdriver` didn't provide the constant. @selenium_webdriver_version = if Gem.loaded_specs['selenium-webdriver'] Gem.loaded_specs['selenium-webdriver'].version else Gem::Version.new(Selenium::WebDriver::VERSION) end unless Gem::Requirement.new('>= 4.8').satisfied_by? @selenium_webdriver_version warn "Warning: You're using an unsupported version of selenium-webdriver, please upgrade to 4.8+." end @selenium_webdriver_version rescue LoadError => e raise e unless e.message.include?('selenium-webdriver') raise LoadError, "Capybara's selenium driver is unable to load `selenium-webdriver`, please install the gem and add `gem 'selenium-webdriver'` to your Gemfile if you are using bundler." end attr_reader :specializations def register_specialization(browser_name, specialization) @specializations ||= {} @specializations[browser_name] = specialization end end def browser unless @browser options[:http_client] ||= begin require 'capybara/selenium/patches/persistent_client' if options[:timeout] ::Capybara::Selenium::PersistentClient.new(read_timeout: options[:timeout]) else ::Capybara::Selenium::PersistentClient.new end end processed_options = options.except(*SPECIAL_OPTIONS) @browser = Selenium::WebDriver.for(options[:browser], processed_options) specialize_driver setup_exit_handler end @browser end def initialize(app, **options) super() self.class.load_selenium @app = app @browser = nil @exit_status = nil @frame_handles = Hash.new { |hash, handle| hash[handle] = [] } @options = DEFAULT_OPTIONS.merge(options) @node_class = ::Capybara::Selenium::Node end def visit(path) browser.navigate.to(path) end def refresh browser.navigate.refresh end def go_back browser.navigate.back end def go_forward browser.navigate.forward end def html browser.page_source rescue Selenium::WebDriver::Error::JavascriptError => e raise unless e.message.include?('documentElement is null') end def title browser.title end def current_url browser.current_url end def wait?; true; end def needs_server?; true; end def execute_script(script, *args) browser.execute_script(script, *native_args(args)) end def evaluate_script(script, *args) result = execute_script("return #{script}", *args) unwrap_script_result(result) end def evaluate_async_script(script, *args) browser.manage.timeouts.script_timeout = Capybara.default_max_wait_time result = browser.execute_async_script(script, *native_args(args)) unwrap_script_result(result) end def active_element build_node(native_active_element) end def send_keys(*args) # Should this call the specialized nodes rather than native??? native_active_element.send_keys(*args) end def save_screenshot(path, **options) browser.save_screenshot(path, **options) end def reset! # Use instance variable directly so we avoid starting the browser just to reset the session return unless @browser navigated = false timer = Capybara::Helpers.timer(expire_in: 10) begin # Only trigger a navigation if we haven't done it already, otherwise it # can trigger an endless series of unload modals reset_browser_state unless navigated navigated = true # Ensure the page is empty and trigger an UnhandledAlertError for any modals that appear during unload wait_for_empty_page(timer) rescue *unhandled_alert_errors # This error is thrown if an unhandled alert is on the page # Firefox appears to automatically dismiss this alert, chrome does not # We'll try to accept it accept_unhandled_reset_alert # try cleaning up the browser again retry end end def frame_obscured_at?(x:, y:) frame = @frame_handles[current_window_handle].last return false unless frame switch_to_frame(:parent) begin frame.base.obscured?(x: x, y: y) ensure switch_to_frame(frame) end end def switch_to_frame(frame) handles = @frame_handles[current_window_handle] case frame when :top handles.clear browser.switch_to.default_content when :parent handles.pop browser.switch_to.parent_frame else handles << frame browser.switch_to.frame(frame.native) end end def current_window_handle browser.window_handle end def window_size(handle) within_given_window(handle) do size = browser.manage.window.size [size.width, size.height] end end def resize_window_to(handle, width, height) within_given_window(handle) do browser.manage.window.resize_to(width, height) end end def maximize_window(handle) within_given_window(handle) do browser.manage.window.maximize end sleep 0.1 # work around for https://code.google.com/p/selenium/issues/detail?id=7405 end def fullscreen_window(handle) within_given_window(handle) do browser.manage.window.full_screen end end def close_window(handle) raise ArgumentError, 'Not allowed to close the primary window' if handle == window_handles.first within_given_window(handle) do browser.close end end def window_handles browser.window_handles end def open_new_window(kind = :tab) if browser.switch_to.respond_to?(:new_window) handle = current_window_handle browser.switch_to.new_window(kind) switch_to_window(handle) else browser.manage.new_window(kind) end rescue NoMethodError, Selenium::WebDriver::Error::WebDriverError # If not supported by the driver or browser default to using JS browser.execute_script('window.open();') end def switch_to_window(handle) browser.switch_to.window handle end def accept_modal(_type, **options) yield if block_given? modal = find_modal(**options) modal.send_keys options[:with] if options[:with] message = modal.text modal.accept message end def dismiss_modal(_type, **options) yield if block_given? modal = find_modal(**options) message = modal.text modal.dismiss message end def quit @browser&.quit rescue Selenium::WebDriver::Error::SessionNotCreatedError, Errno::ECONNREFUSED, Selenium::WebDriver::Error::InvalidSessionIdError # Browser must have already gone rescue Selenium::WebDriver::Error::UnknownError => e unless silenced_unknown_error_message?(e.message) # Most likely already gone # probably already gone but not sure - so warn warn "Ignoring Selenium UnknownError during driver quit: #{e.message}" end ensure @browser = nil end def invalid_element_errors @invalid_element_errors ||= [ ::Selenium::WebDriver::Error::StaleElementReferenceError, ::Selenium::WebDriver::Error::ElementNotInteractableError, ::Selenium::WebDriver::Error::InvalidSelectorError, # Work around chromedriver go_back/go_forward race condition ::Selenium::WebDriver::Error::ElementClickInterceptedError, ::Selenium::WebDriver::Error::NoSuchElementError, # IE ::Selenium::WebDriver::Error::InvalidArgumentError # IE ].tap do |errors| if defined?(::Selenium::WebDriver::Error::DetachedShadowRootError) errors.push(::Selenium::WebDriver::Error::DetachedShadowRootError) end end end def no_such_window_error Selenium::WebDriver::Error::NoSuchWindowError end private def native_args(args) args.map { |arg| arg.is_a?(Capybara::Selenium::Node) ? arg.native : arg } end def native_active_element browser.switch_to.active_element end def clear_browser_state delete_all_cookies clear_storage rescue *clear_browser_state_errors # delete_all_cookies fails when we've previously gone # to about:blank, so we rescue this error and do nothing # instead. end def clear_browser_state_errors @clear_browser_state_errors ||= [Selenium::WebDriver::Error::UnknownError] end def unhandled_alert_errors @unhandled_alert_errors ||= [Selenium::WebDriver::Error::UnexpectedAlertOpenError] end def delete_all_cookies @browser.manage.delete_all_cookies end def clear_storage clear_session_storage unless options[:clear_session_storage] == false clear_local_storage unless options[:clear_local_storage] == false rescue Selenium::WebDriver::Error::JavascriptError, Selenium::WebDriver::Error::WebDriverError # session/local storage may not be available if on non-http pages (e.g. about:blank) end def clear_session_storage if @browser.respond_to? :session_storage @browser.session_storage.clear else begin @browser&.execute_script('window.sessionStorage.clear()') rescue # rubocop:disable Style/RescueStandardError unless options[:clear_session_storage].nil? warn 'sessionStorage clear requested but is not supported by this driver' end end end end def clear_local_storage # selenium-webdriver 4.30.0 removed HTML5 storage accessors -- not really sure why # can we replicate this robustly via CDP? if @browser.respond_to? :local_storage @browser.local_storage.clear else begin @browser&.execute_script('window.localStorage.clear()') rescue # rubocop:disable Style/RescueStandardError unless options[:clear_local_storage].nil? warn 'localStorage clear requested but is not supported by this driver' end end end end def navigate_with_accept(url) @browser.navigate.to(url) sleep 0.1 # slight wait for alert @browser.switch_to.alert.accept rescue modal_error # alert now gone, should mean navigation happened end def modal_error Selenium::WebDriver::Error::NoSuchAlertError end def within_given_window(handle) original_handle = current_window_handle if handle == original_handle yield else switch_to_window(handle) result = yield switch_to_window(original_handle) result end end def find_modal(text: nil, **options) # Selenium has its own built in wait (2 seconds)for a modal to show up, so this wait is really the minimum time # Actual wait time may be longer than specified wait = Selenium::WebDriver::Wait.new( timeout: options.fetch(:wait, session_options.default_max_wait_time) || 0, ignore: modal_error ) begin wait.until do alert = @browser.switch_to.alert regexp = text.is_a?(Regexp) ? text : Regexp.new(Regexp.escape(text.to_s)) matched = alert.text.match?(regexp) unless matched raise Capybara::ModalNotFound, "Unable to find modal dialog with #{text} - found '#{alert.text}' instead." end alert end rescue *find_modal_errors raise Capybara::ModalNotFound, "Unable to find modal dialog#{" with #{text}" if text}" end end def find_modal_errors @find_modal_errors ||= [Selenium::WebDriver::Error::TimeoutError] end def silenced_unknown_error_message?(msg) silenced_unknown_error_messages.any? { |regex| msg.match? regex } end def silenced_unknown_error_messages [/Error communicating with the remote browser/] end def unwrap_script_result(arg) case arg when Array arg.map { |arr| unwrap_script_result(arr) } when Hash arg.transform_values! { |value| unwrap_script_result(value) } when Selenium::WebDriver::Element, Selenium::WebDriver::ShadowRoot build_node(arg) else arg end end def find_context browser end def build_node(native_node, initial_cache = {}) ::Capybara::Selenium::Node.new(self, native_node, initial_cache) end def bridge browser.send(:bridge) end def specialize_driver browser_type = browser.browser Capybara::Selenium::Driver.specializations.select { |k, _v| k === browser_type }.each_value do |specialization| # rubocop:disable Style/CaseEquality extend specialization end end def setup_exit_handler main = Process.pid at_exit do # Store the exit status of the test run since it goes away after calling the at_exit proc... @exit_status = $ERROR_INFO.status if $ERROR_INFO.is_a?(SystemExit) quit if Process.pid == main exit @exit_status if @exit_status # Force exit with stored status end end def reset_browser_state clear_browser_state @browser.navigate.to('about:blank') end def wait_for_empty_page(timer) until find_xpath('/html/body/*').empty? raise Capybara::ExpectationNotMet, 'Timed out waiting for Selenium session reset' if timer.expired? sleep 0.01 # It has been observed that it is possible that asynchronous JS code in # the application under test can navigate the browser away from about:blank # if the timing is just right. Ensure we are still at about:blank... @browser.navigate.to('about:blank') unless current_url == 'about:blank' end end def accept_unhandled_reset_alert @browser.switch_to.alert.accept sleep 0.25 # allow time for the modal to be handled rescue modal_error # The alert is now gone. # If navigation has not occurred attempt again and accept alert # since FF may have dismissed the alert at first attempt. navigate_with_accept('about:blank') if current_url != 'about:blank' end end require 'capybara/selenium/driver_specializations/chrome_driver' require 'capybara/selenium/driver_specializations/firefox_driver' require 'capybara/selenium/driver_specializations/internet_explorer_driver' require 'capybara/selenium/driver_specializations/safari_driver' require 'capybara/selenium/driver_specializations/edge_driver'
Ruby
{ "end_line": 53, "name": "load_selenium", "signature": "def load_selenium", "start_line": 22 }
{ "class_name": "Capybara::Selenium::Driver", "class_signature": "class Capybara::Selenium::Driver < < Capybara::Driver::Base", "module": "" }
browser
capybara/lib/capybara/selenium/driver.rb
def browser unless @browser options[:http_client] ||= begin require 'capybara/selenium/patches/persistent_client' if options[:timeout] ::Capybara::Selenium::PersistentClient.new(read_timeout: options[:timeout]) else ::Capybara::Selenium::PersistentClient.new end end processed_options = options.except(*SPECIAL_OPTIONS) @browser = Selenium::WebDriver.for(options[:browser], processed_options) specialize_driver setup_exit_handler end @browser end
# frozen_string_literal: true require 'uri' require 'English' class Capybara::Selenium::Driver < Capybara::Driver::Base include Capybara::Selenium::Find DEFAULT_OPTIONS = { browser: :firefox, clear_local_storage: nil, clear_session_storage: nil }.freeze SPECIAL_OPTIONS = %i[browser clear_local_storage clear_session_storage timeout native_displayed].freeze CAPS_VERSION = Gem::Requirement.new('< 4.8.0') attr_reader :app, :options class << self attr_reader :selenium_webdriver_version def load_selenium require 'selenium-webdriver' require 'capybara/selenium/patches/atoms' require 'capybara/selenium/patches/is_displayed' # Look up the version of `selenium-webdriver` to # see if it's a version we support. # # By default, we use Gem.loaded_specs to determine # the version number. However, in some cases, such # as when loading `selenium-webdriver` outside of # Rubygems, we fall back to referencing # Selenium::WebDriver::VERSION. Ideally we'd # use the constant in all cases, but earlier versions # of `selenium-webdriver` didn't provide the constant. @selenium_webdriver_version = if Gem.loaded_specs['selenium-webdriver'] Gem.loaded_specs['selenium-webdriver'].version else Gem::Version.new(Selenium::WebDriver::VERSION) end unless Gem::Requirement.new('>= 4.8').satisfied_by? @selenium_webdriver_version warn "Warning: You're using an unsupported version of selenium-webdriver, please upgrade to 4.8+." end @selenium_webdriver_version rescue LoadError => e raise e unless e.message.include?('selenium-webdriver') raise LoadError, "Capybara's selenium driver is unable to load `selenium-webdriver`, please install the gem and add `gem 'selenium-webdriver'` to your Gemfile if you are using bundler." end attr_reader :specializations def register_specialization(browser_name, specialization) @specializations ||= {} @specializations[browser_name] = specialization end end def browser unless @browser options[:http_client] ||= begin require 'capybara/selenium/patches/persistent_client' if options[:timeout] ::Capybara::Selenium::PersistentClient.new(read_timeout: options[:timeout]) else ::Capybara::Selenium::PersistentClient.new end end processed_options = options.except(*SPECIAL_OPTIONS) @browser = Selenium::WebDriver.for(options[:browser], processed_options) specialize_driver setup_exit_handler end @browser end def initialize(app, **options) super() self.class.load_selenium @app = app @browser = nil @exit_status = nil @frame_handles = Hash.new { |hash, handle| hash[handle] = [] } @options = DEFAULT_OPTIONS.merge(options) @node_class = ::Capybara::Selenium::Node end def visit(path) browser.navigate.to(path) end def refresh browser.navigate.refresh end def go_back browser.navigate.back end def go_forward browser.navigate.forward end def html browser.page_source rescue Selenium::WebDriver::Error::JavascriptError => e raise unless e.message.include?('documentElement is null') end def title browser.title end def current_url browser.current_url end def wait?; true; end def needs_server?; true; end def execute_script(script, *args) browser.execute_script(script, *native_args(args)) end def evaluate_script(script, *args) result = execute_script("return #{script}", *args) unwrap_script_result(result) end def evaluate_async_script(script, *args) browser.manage.timeouts.script_timeout = Capybara.default_max_wait_time result = browser.execute_async_script(script, *native_args(args)) unwrap_script_result(result) end def active_element build_node(native_active_element) end def send_keys(*args) # Should this call the specialized nodes rather than native??? native_active_element.send_keys(*args) end def save_screenshot(path, **options) browser.save_screenshot(path, **options) end def reset! # Use instance variable directly so we avoid starting the browser just to reset the session return unless @browser navigated = false timer = Capybara::Helpers.timer(expire_in: 10) begin # Only trigger a navigation if we haven't done it already, otherwise it # can trigger an endless series of unload modals reset_browser_state unless navigated navigated = true # Ensure the page is empty and trigger an UnhandledAlertError for any modals that appear during unload wait_for_empty_page(timer) rescue *unhandled_alert_errors # This error is thrown if an unhandled alert is on the page # Firefox appears to automatically dismiss this alert, chrome does not # We'll try to accept it accept_unhandled_reset_alert # try cleaning up the browser again retry end end def frame_obscured_at?(x:, y:) frame = @frame_handles[current_window_handle].last return false unless frame switch_to_frame(:parent) begin frame.base.obscured?(x: x, y: y) ensure switch_to_frame(frame) end end def switch_to_frame(frame) handles = @frame_handles[current_window_handle] case frame when :top handles.clear browser.switch_to.default_content when :parent handles.pop browser.switch_to.parent_frame else handles << frame browser.switch_to.frame(frame.native) end end def current_window_handle browser.window_handle end def window_size(handle) within_given_window(handle) do size = browser.manage.window.size [size.width, size.height] end end def resize_window_to(handle, width, height) within_given_window(handle) do browser.manage.window.resize_to(width, height) end end def maximize_window(handle) within_given_window(handle) do browser.manage.window.maximize end sleep 0.1 # work around for https://code.google.com/p/selenium/issues/detail?id=7405 end def fullscreen_window(handle) within_given_window(handle) do browser.manage.window.full_screen end end def close_window(handle) raise ArgumentError, 'Not allowed to close the primary window' if handle == window_handles.first within_given_window(handle) do browser.close end end def window_handles browser.window_handles end def open_new_window(kind = :tab) if browser.switch_to.respond_to?(:new_window) handle = current_window_handle browser.switch_to.new_window(kind) switch_to_window(handle) else browser.manage.new_window(kind) end rescue NoMethodError, Selenium::WebDriver::Error::WebDriverError # If not supported by the driver or browser default to using JS browser.execute_script('window.open();') end def switch_to_window(handle) browser.switch_to.window handle end def accept_modal(_type, **options) yield if block_given? modal = find_modal(**options) modal.send_keys options[:with] if options[:with] message = modal.text modal.accept message end def dismiss_modal(_type, **options) yield if block_given? modal = find_modal(**options) message = modal.text modal.dismiss message end def quit @browser&.quit rescue Selenium::WebDriver::Error::SessionNotCreatedError, Errno::ECONNREFUSED, Selenium::WebDriver::Error::InvalidSessionIdError # Browser must have already gone rescue Selenium::WebDriver::Error::UnknownError => e unless silenced_unknown_error_message?(e.message) # Most likely already gone # probably already gone but not sure - so warn warn "Ignoring Selenium UnknownError during driver quit: #{e.message}" end ensure @browser = nil end def invalid_element_errors @invalid_element_errors ||= [ ::Selenium::WebDriver::Error::StaleElementReferenceError, ::Selenium::WebDriver::Error::ElementNotInteractableError, ::Selenium::WebDriver::Error::InvalidSelectorError, # Work around chromedriver go_back/go_forward race condition ::Selenium::WebDriver::Error::ElementClickInterceptedError, ::Selenium::WebDriver::Error::NoSuchElementError, # IE ::Selenium::WebDriver::Error::InvalidArgumentError # IE ].tap do |errors| if defined?(::Selenium::WebDriver::Error::DetachedShadowRootError) errors.push(::Selenium::WebDriver::Error::DetachedShadowRootError) end end end def no_such_window_error Selenium::WebDriver::Error::NoSuchWindowError end private def native_args(args) args.map { |arg| arg.is_a?(Capybara::Selenium::Node) ? arg.native : arg } end def native_active_element browser.switch_to.active_element end def clear_browser_state delete_all_cookies clear_storage rescue *clear_browser_state_errors # delete_all_cookies fails when we've previously gone # to about:blank, so we rescue this error and do nothing # instead. end def clear_browser_state_errors @clear_browser_state_errors ||= [Selenium::WebDriver::Error::UnknownError] end def unhandled_alert_errors @unhandled_alert_errors ||= [Selenium::WebDriver::Error::UnexpectedAlertOpenError] end def delete_all_cookies @browser.manage.delete_all_cookies end def clear_storage clear_session_storage unless options[:clear_session_storage] == false clear_local_storage unless options[:clear_local_storage] == false rescue Selenium::WebDriver::Error::JavascriptError, Selenium::WebDriver::Error::WebDriverError # session/local storage may not be available if on non-http pages (e.g. about:blank) end def clear_session_storage if @browser.respond_to? :session_storage @browser.session_storage.clear else begin @browser&.execute_script('window.sessionStorage.clear()') rescue # rubocop:disable Style/RescueStandardError unless options[:clear_session_storage].nil? warn 'sessionStorage clear requested but is not supported by this driver' end end end end def clear_local_storage # selenium-webdriver 4.30.0 removed HTML5 storage accessors -- not really sure why # can we replicate this robustly via CDP? if @browser.respond_to? :local_storage @browser.local_storage.clear else begin @browser&.execute_script('window.localStorage.clear()') rescue # rubocop:disable Style/RescueStandardError unless options[:clear_local_storage].nil? warn 'localStorage clear requested but is not supported by this driver' end end end end def navigate_with_accept(url) @browser.navigate.to(url) sleep 0.1 # slight wait for alert @browser.switch_to.alert.accept rescue modal_error # alert now gone, should mean navigation happened end def modal_error Selenium::WebDriver::Error::NoSuchAlertError end def within_given_window(handle) original_handle = current_window_handle if handle == original_handle yield else switch_to_window(handle) result = yield switch_to_window(original_handle) result end end def find_modal(text: nil, **options) # Selenium has its own built in wait (2 seconds)for a modal to show up, so this wait is really the minimum time # Actual wait time may be longer than specified wait = Selenium::WebDriver::Wait.new( timeout: options.fetch(:wait, session_options.default_max_wait_time) || 0, ignore: modal_error ) begin wait.until do alert = @browser.switch_to.alert regexp = text.is_a?(Regexp) ? text : Regexp.new(Regexp.escape(text.to_s)) matched = alert.text.match?(regexp) unless matched raise Capybara::ModalNotFound, "Unable to find modal dialog with #{text} - found '#{alert.text}' instead." end alert end rescue *find_modal_errors raise Capybara::ModalNotFound, "Unable to find modal dialog#{" with #{text}" if text}" end end def find_modal_errors @find_modal_errors ||= [Selenium::WebDriver::Error::TimeoutError] end def silenced_unknown_error_message?(msg) silenced_unknown_error_messages.any? { |regex| msg.match? regex } end def silenced_unknown_error_messages [/Error communicating with the remote browser/] end def unwrap_script_result(arg) case arg when Array arg.map { |arr| unwrap_script_result(arr) } when Hash arg.transform_values! { |value| unwrap_script_result(value) } when Selenium::WebDriver::Element, Selenium::WebDriver::ShadowRoot build_node(arg) else arg end end def find_context browser end def build_node(native_node, initial_cache = {}) ::Capybara::Selenium::Node.new(self, native_node, initial_cache) end def bridge browser.send(:bridge) end def specialize_driver browser_type = browser.browser Capybara::Selenium::Driver.specializations.select { |k, _v| k === browser_type }.each_value do |specialization| # rubocop:disable Style/CaseEquality extend specialization end end def setup_exit_handler main = Process.pid at_exit do # Store the exit status of the test run since it goes away after calling the at_exit proc... @exit_status = $ERROR_INFO.status if $ERROR_INFO.is_a?(SystemExit) quit if Process.pid == main exit @exit_status if @exit_status # Force exit with stored status end end def reset_browser_state clear_browser_state @browser.navigate.to('about:blank') end def wait_for_empty_page(timer) until find_xpath('/html/body/*').empty? raise Capybara::ExpectationNotMet, 'Timed out waiting for Selenium session reset' if timer.expired? sleep 0.01 # It has been observed that it is possible that asynchronous JS code in # the application under test can navigate the browser away from about:blank # if the timing is just right. Ensure we are still at about:blank... @browser.navigate.to('about:blank') unless current_url == 'about:blank' end end def accept_unhandled_reset_alert @browser.switch_to.alert.accept sleep 0.25 # allow time for the modal to be handled rescue modal_error # The alert is now gone. # If navigation has not occurred attempt again and accept alert # since FF may have dismissed the alert at first attempt. navigate_with_accept('about:blank') if current_url != 'about:blank' end end require 'capybara/selenium/driver_specializations/chrome_driver' require 'capybara/selenium/driver_specializations/firefox_driver' require 'capybara/selenium/driver_specializations/internet_explorer_driver' require 'capybara/selenium/driver_specializations/safari_driver' require 'capybara/selenium/driver_specializations/edge_driver'
Ruby
{ "end_line": 81, "name": "browser", "signature": "def browser", "start_line": 63 }
{ "class_name": "Capybara::Selenium::Driver", "class_signature": "class Capybara::Selenium::Driver < < Capybara::Driver::Base", "module": "" }
initialize
capybara/lib/capybara/selenium/driver.rb
def initialize(app, **options) super() self.class.load_selenium @app = app @browser = nil @exit_status = nil @frame_handles = Hash.new { |hash, handle| hash[handle] = [] } @options = DEFAULT_OPTIONS.merge(options) @node_class = ::Capybara::Selenium::Node end
# frozen_string_literal: true require 'uri' require 'English' class Capybara::Selenium::Driver < Capybara::Driver::Base include Capybara::Selenium::Find DEFAULT_OPTIONS = { browser: :firefox, clear_local_storage: nil, clear_session_storage: nil }.freeze SPECIAL_OPTIONS = %i[browser clear_local_storage clear_session_storage timeout native_displayed].freeze CAPS_VERSION = Gem::Requirement.new('< 4.8.0') attr_reader :app, :options class << self attr_reader :selenium_webdriver_version def load_selenium require 'selenium-webdriver' require 'capybara/selenium/patches/atoms' require 'capybara/selenium/patches/is_displayed' # Look up the version of `selenium-webdriver` to # see if it's a version we support. # # By default, we use Gem.loaded_specs to determine # the version number. However, in some cases, such # as when loading `selenium-webdriver` outside of # Rubygems, we fall back to referencing # Selenium::WebDriver::VERSION. Ideally we'd # use the constant in all cases, but earlier versions # of `selenium-webdriver` didn't provide the constant. @selenium_webdriver_version = if Gem.loaded_specs['selenium-webdriver'] Gem.loaded_specs['selenium-webdriver'].version else Gem::Version.new(Selenium::WebDriver::VERSION) end unless Gem::Requirement.new('>= 4.8').satisfied_by? @selenium_webdriver_version warn "Warning: You're using an unsupported version of selenium-webdriver, please upgrade to 4.8+." end @selenium_webdriver_version rescue LoadError => e raise e unless e.message.include?('selenium-webdriver') raise LoadError, "Capybara's selenium driver is unable to load `selenium-webdriver`, please install the gem and add `gem 'selenium-webdriver'` to your Gemfile if you are using bundler." end attr_reader :specializations def register_specialization(browser_name, specialization) @specializations ||= {} @specializations[browser_name] = specialization end end def browser unless @browser options[:http_client] ||= begin require 'capybara/selenium/patches/persistent_client' if options[:timeout] ::Capybara::Selenium::PersistentClient.new(read_timeout: options[:timeout]) else ::Capybara::Selenium::PersistentClient.new end end processed_options = options.except(*SPECIAL_OPTIONS) @browser = Selenium::WebDriver.for(options[:browser], processed_options) specialize_driver setup_exit_handler end @browser end def initialize(app, **options) super() self.class.load_selenium @app = app @browser = nil @exit_status = nil @frame_handles = Hash.new { |hash, handle| hash[handle] = [] } @options = DEFAULT_OPTIONS.merge(options) @node_class = ::Capybara::Selenium::Node end def visit(path) browser.navigate.to(path) end def refresh browser.navigate.refresh end def go_back browser.navigate.back end def go_forward browser.navigate.forward end def html browser.page_source rescue Selenium::WebDriver::Error::JavascriptError => e raise unless e.message.include?('documentElement is null') end def title browser.title end def current_url browser.current_url end def wait?; true; end def needs_server?; true; end def execute_script(script, *args) browser.execute_script(script, *native_args(args)) end def evaluate_script(script, *args) result = execute_script("return #{script}", *args) unwrap_script_result(result) end def evaluate_async_script(script, *args) browser.manage.timeouts.script_timeout = Capybara.default_max_wait_time result = browser.execute_async_script(script, *native_args(args)) unwrap_script_result(result) end def active_element build_node(native_active_element) end def send_keys(*args) # Should this call the specialized nodes rather than native??? native_active_element.send_keys(*args) end def save_screenshot(path, **options) browser.save_screenshot(path, **options) end def reset! # Use instance variable directly so we avoid starting the browser just to reset the session return unless @browser navigated = false timer = Capybara::Helpers.timer(expire_in: 10) begin # Only trigger a navigation if we haven't done it already, otherwise it # can trigger an endless series of unload modals reset_browser_state unless navigated navigated = true # Ensure the page is empty and trigger an UnhandledAlertError for any modals that appear during unload wait_for_empty_page(timer) rescue *unhandled_alert_errors # This error is thrown if an unhandled alert is on the page # Firefox appears to automatically dismiss this alert, chrome does not # We'll try to accept it accept_unhandled_reset_alert # try cleaning up the browser again retry end end def frame_obscured_at?(x:, y:) frame = @frame_handles[current_window_handle].last return false unless frame switch_to_frame(:parent) begin frame.base.obscured?(x: x, y: y) ensure switch_to_frame(frame) end end def switch_to_frame(frame) handles = @frame_handles[current_window_handle] case frame when :top handles.clear browser.switch_to.default_content when :parent handles.pop browser.switch_to.parent_frame else handles << frame browser.switch_to.frame(frame.native) end end def current_window_handle browser.window_handle end def window_size(handle) within_given_window(handle) do size = browser.manage.window.size [size.width, size.height] end end def resize_window_to(handle, width, height) within_given_window(handle) do browser.manage.window.resize_to(width, height) end end def maximize_window(handle) within_given_window(handle) do browser.manage.window.maximize end sleep 0.1 # work around for https://code.google.com/p/selenium/issues/detail?id=7405 end def fullscreen_window(handle) within_given_window(handle) do browser.manage.window.full_screen end end def close_window(handle) raise ArgumentError, 'Not allowed to close the primary window' if handle == window_handles.first within_given_window(handle) do browser.close end end def window_handles browser.window_handles end def open_new_window(kind = :tab) if browser.switch_to.respond_to?(:new_window) handle = current_window_handle browser.switch_to.new_window(kind) switch_to_window(handle) else browser.manage.new_window(kind) end rescue NoMethodError, Selenium::WebDriver::Error::WebDriverError # If not supported by the driver or browser default to using JS browser.execute_script('window.open();') end def switch_to_window(handle) browser.switch_to.window handle end def accept_modal(_type, **options) yield if block_given? modal = find_modal(**options) modal.send_keys options[:with] if options[:with] message = modal.text modal.accept message end def dismiss_modal(_type, **options) yield if block_given? modal = find_modal(**options) message = modal.text modal.dismiss message end def quit @browser&.quit rescue Selenium::WebDriver::Error::SessionNotCreatedError, Errno::ECONNREFUSED, Selenium::WebDriver::Error::InvalidSessionIdError # Browser must have already gone rescue Selenium::WebDriver::Error::UnknownError => e unless silenced_unknown_error_message?(e.message) # Most likely already gone # probably already gone but not sure - so warn warn "Ignoring Selenium UnknownError during driver quit: #{e.message}" end ensure @browser = nil end def invalid_element_errors @invalid_element_errors ||= [ ::Selenium::WebDriver::Error::StaleElementReferenceError, ::Selenium::WebDriver::Error::ElementNotInteractableError, ::Selenium::WebDriver::Error::InvalidSelectorError, # Work around chromedriver go_back/go_forward race condition ::Selenium::WebDriver::Error::ElementClickInterceptedError, ::Selenium::WebDriver::Error::NoSuchElementError, # IE ::Selenium::WebDriver::Error::InvalidArgumentError # IE ].tap do |errors| if defined?(::Selenium::WebDriver::Error::DetachedShadowRootError) errors.push(::Selenium::WebDriver::Error::DetachedShadowRootError) end end end def no_such_window_error Selenium::WebDriver::Error::NoSuchWindowError end private def native_args(args) args.map { |arg| arg.is_a?(Capybara::Selenium::Node) ? arg.native : arg } end def native_active_element browser.switch_to.active_element end def clear_browser_state delete_all_cookies clear_storage rescue *clear_browser_state_errors # delete_all_cookies fails when we've previously gone # to about:blank, so we rescue this error and do nothing # instead. end def clear_browser_state_errors @clear_browser_state_errors ||= [Selenium::WebDriver::Error::UnknownError] end def unhandled_alert_errors @unhandled_alert_errors ||= [Selenium::WebDriver::Error::UnexpectedAlertOpenError] end def delete_all_cookies @browser.manage.delete_all_cookies end def clear_storage clear_session_storage unless options[:clear_session_storage] == false clear_local_storage unless options[:clear_local_storage] == false rescue Selenium::WebDriver::Error::JavascriptError, Selenium::WebDriver::Error::WebDriverError # session/local storage may not be available if on non-http pages (e.g. about:blank) end def clear_session_storage if @browser.respond_to? :session_storage @browser.session_storage.clear else begin @browser&.execute_script('window.sessionStorage.clear()') rescue # rubocop:disable Style/RescueStandardError unless options[:clear_session_storage].nil? warn 'sessionStorage clear requested but is not supported by this driver' end end end end def clear_local_storage # selenium-webdriver 4.30.0 removed HTML5 storage accessors -- not really sure why # can we replicate this robustly via CDP? if @browser.respond_to? :local_storage @browser.local_storage.clear else begin @browser&.execute_script('window.localStorage.clear()') rescue # rubocop:disable Style/RescueStandardError unless options[:clear_local_storage].nil? warn 'localStorage clear requested but is not supported by this driver' end end end end def navigate_with_accept(url) @browser.navigate.to(url) sleep 0.1 # slight wait for alert @browser.switch_to.alert.accept rescue modal_error # alert now gone, should mean navigation happened end def modal_error Selenium::WebDriver::Error::NoSuchAlertError end def within_given_window(handle) original_handle = current_window_handle if handle == original_handle yield else switch_to_window(handle) result = yield switch_to_window(original_handle) result end end def find_modal(text: nil, **options) # Selenium has its own built in wait (2 seconds)for a modal to show up, so this wait is really the minimum time # Actual wait time may be longer than specified wait = Selenium::WebDriver::Wait.new( timeout: options.fetch(:wait, session_options.default_max_wait_time) || 0, ignore: modal_error ) begin wait.until do alert = @browser.switch_to.alert regexp = text.is_a?(Regexp) ? text : Regexp.new(Regexp.escape(text.to_s)) matched = alert.text.match?(regexp) unless matched raise Capybara::ModalNotFound, "Unable to find modal dialog with #{text} - found '#{alert.text}' instead." end alert end rescue *find_modal_errors raise Capybara::ModalNotFound, "Unable to find modal dialog#{" with #{text}" if text}" end end def find_modal_errors @find_modal_errors ||= [Selenium::WebDriver::Error::TimeoutError] end def silenced_unknown_error_message?(msg) silenced_unknown_error_messages.any? { |regex| msg.match? regex } end def silenced_unknown_error_messages [/Error communicating with the remote browser/] end def unwrap_script_result(arg) case arg when Array arg.map { |arr| unwrap_script_result(arr) } when Hash arg.transform_values! { |value| unwrap_script_result(value) } when Selenium::WebDriver::Element, Selenium::WebDriver::ShadowRoot build_node(arg) else arg end end def find_context browser end def build_node(native_node, initial_cache = {}) ::Capybara::Selenium::Node.new(self, native_node, initial_cache) end def bridge browser.send(:bridge) end def specialize_driver browser_type = browser.browser Capybara::Selenium::Driver.specializations.select { |k, _v| k === browser_type }.each_value do |specialization| # rubocop:disable Style/CaseEquality extend specialization end end def setup_exit_handler main = Process.pid at_exit do # Store the exit status of the test run since it goes away after calling the at_exit proc... @exit_status = $ERROR_INFO.status if $ERROR_INFO.is_a?(SystemExit) quit if Process.pid == main exit @exit_status if @exit_status # Force exit with stored status end end def reset_browser_state clear_browser_state @browser.navigate.to('about:blank') end def wait_for_empty_page(timer) until find_xpath('/html/body/*').empty? raise Capybara::ExpectationNotMet, 'Timed out waiting for Selenium session reset' if timer.expired? sleep 0.01 # It has been observed that it is possible that asynchronous JS code in # the application under test can navigate the browser away from about:blank # if the timing is just right. Ensure we are still at about:blank... @browser.navigate.to('about:blank') unless current_url == 'about:blank' end end def accept_unhandled_reset_alert @browser.switch_to.alert.accept sleep 0.25 # allow time for the modal to be handled rescue modal_error # The alert is now gone. # If navigation has not occurred attempt again and accept alert # since FF may have dismissed the alert at first attempt. navigate_with_accept('about:blank') if current_url != 'about:blank' end end require 'capybara/selenium/driver_specializations/chrome_driver' require 'capybara/selenium/driver_specializations/firefox_driver' require 'capybara/selenium/driver_specializations/internet_explorer_driver' require 'capybara/selenium/driver_specializations/safari_driver' require 'capybara/selenium/driver_specializations/edge_driver'
Ruby
{ "end_line": 92, "name": "initialize", "signature": "def initialize(app, **options)", "start_line": 83 }
{ "class_name": "Capybara::Selenium::Driver", "class_signature": "class Capybara::Selenium::Driver < < Capybara::Driver::Base", "module": "" }
reset!
capybara/lib/capybara/selenium/driver.rb
def reset! # Use instance variable directly so we avoid starting the browser just to reset the session return unless @browser navigated = false timer = Capybara::Helpers.timer(expire_in: 10) begin # Only trigger a navigation if we haven't done it already, otherwise it # can trigger an endless series of unload modals reset_browser_state unless navigated navigated = true # Ensure the page is empty and trigger an UnhandledAlertError for any modals that appear during unload wait_for_empty_page(timer) rescue *unhandled_alert_errors # This error is thrown if an unhandled alert is on the page # Firefox appears to automatically dismiss this alert, chrome does not # We'll try to accept it accept_unhandled_reset_alert # try cleaning up the browser again retry end end
# frozen_string_literal: true require 'uri' require 'English' class Capybara::Selenium::Driver < Capybara::Driver::Base include Capybara::Selenium::Find DEFAULT_OPTIONS = { browser: :firefox, clear_local_storage: nil, clear_session_storage: nil }.freeze SPECIAL_OPTIONS = %i[browser clear_local_storage clear_session_storage timeout native_displayed].freeze CAPS_VERSION = Gem::Requirement.new('< 4.8.0') attr_reader :app, :options class << self attr_reader :selenium_webdriver_version def load_selenium require 'selenium-webdriver' require 'capybara/selenium/patches/atoms' require 'capybara/selenium/patches/is_displayed' # Look up the version of `selenium-webdriver` to # see if it's a version we support. # # By default, we use Gem.loaded_specs to determine # the version number. However, in some cases, such # as when loading `selenium-webdriver` outside of # Rubygems, we fall back to referencing # Selenium::WebDriver::VERSION. Ideally we'd # use the constant in all cases, but earlier versions # of `selenium-webdriver` didn't provide the constant. @selenium_webdriver_version = if Gem.loaded_specs['selenium-webdriver'] Gem.loaded_specs['selenium-webdriver'].version else Gem::Version.new(Selenium::WebDriver::VERSION) end unless Gem::Requirement.new('>= 4.8').satisfied_by? @selenium_webdriver_version warn "Warning: You're using an unsupported version of selenium-webdriver, please upgrade to 4.8+." end @selenium_webdriver_version rescue LoadError => e raise e unless e.message.include?('selenium-webdriver') raise LoadError, "Capybara's selenium driver is unable to load `selenium-webdriver`, please install the gem and add `gem 'selenium-webdriver'` to your Gemfile if you are using bundler." end attr_reader :specializations def register_specialization(browser_name, specialization) @specializations ||= {} @specializations[browser_name] = specialization end end def browser unless @browser options[:http_client] ||= begin require 'capybara/selenium/patches/persistent_client' if options[:timeout] ::Capybara::Selenium::PersistentClient.new(read_timeout: options[:timeout]) else ::Capybara::Selenium::PersistentClient.new end end processed_options = options.except(*SPECIAL_OPTIONS) @browser = Selenium::WebDriver.for(options[:browser], processed_options) specialize_driver setup_exit_handler end @browser end def initialize(app, **options) super() self.class.load_selenium @app = app @browser = nil @exit_status = nil @frame_handles = Hash.new { |hash, handle| hash[handle] = [] } @options = DEFAULT_OPTIONS.merge(options) @node_class = ::Capybara::Selenium::Node end def visit(path) browser.navigate.to(path) end def refresh browser.navigate.refresh end def go_back browser.navigate.back end def go_forward browser.navigate.forward end def html browser.page_source rescue Selenium::WebDriver::Error::JavascriptError => e raise unless e.message.include?('documentElement is null') end def title browser.title end def current_url browser.current_url end def wait?; true; end def needs_server?; true; end def execute_script(script, *args) browser.execute_script(script, *native_args(args)) end def evaluate_script(script, *args) result = execute_script("return #{script}", *args) unwrap_script_result(result) end def evaluate_async_script(script, *args) browser.manage.timeouts.script_timeout = Capybara.default_max_wait_time result = browser.execute_async_script(script, *native_args(args)) unwrap_script_result(result) end def active_element build_node(native_active_element) end def send_keys(*args) # Should this call the specialized nodes rather than native??? native_active_element.send_keys(*args) end def save_screenshot(path, **options) browser.save_screenshot(path, **options) end def reset! # Use instance variable directly so we avoid starting the browser just to reset the session return unless @browser navigated = false timer = Capybara::Helpers.timer(expire_in: 10) begin # Only trigger a navigation if we haven't done it already, otherwise it # can trigger an endless series of unload modals reset_browser_state unless navigated navigated = true # Ensure the page is empty and trigger an UnhandledAlertError for any modals that appear during unload wait_for_empty_page(timer) rescue *unhandled_alert_errors # This error is thrown if an unhandled alert is on the page # Firefox appears to automatically dismiss this alert, chrome does not # We'll try to accept it accept_unhandled_reset_alert # try cleaning up the browser again retry end end def frame_obscured_at?(x:, y:) frame = @frame_handles[current_window_handle].last return false unless frame switch_to_frame(:parent) begin frame.base.obscured?(x: x, y: y) ensure switch_to_frame(frame) end end def switch_to_frame(frame) handles = @frame_handles[current_window_handle] case frame when :top handles.clear browser.switch_to.default_content when :parent handles.pop browser.switch_to.parent_frame else handles << frame browser.switch_to.frame(frame.native) end end def current_window_handle browser.window_handle end def window_size(handle) within_given_window(handle) do size = browser.manage.window.size [size.width, size.height] end end def resize_window_to(handle, width, height) within_given_window(handle) do browser.manage.window.resize_to(width, height) end end def maximize_window(handle) within_given_window(handle) do browser.manage.window.maximize end sleep 0.1 # work around for https://code.google.com/p/selenium/issues/detail?id=7405 end def fullscreen_window(handle) within_given_window(handle) do browser.manage.window.full_screen end end def close_window(handle) raise ArgumentError, 'Not allowed to close the primary window' if handle == window_handles.first within_given_window(handle) do browser.close end end def window_handles browser.window_handles end def open_new_window(kind = :tab) if browser.switch_to.respond_to?(:new_window) handle = current_window_handle browser.switch_to.new_window(kind) switch_to_window(handle) else browser.manage.new_window(kind) end rescue NoMethodError, Selenium::WebDriver::Error::WebDriverError # If not supported by the driver or browser default to using JS browser.execute_script('window.open();') end def switch_to_window(handle) browser.switch_to.window handle end def accept_modal(_type, **options) yield if block_given? modal = find_modal(**options) modal.send_keys options[:with] if options[:with] message = modal.text modal.accept message end def dismiss_modal(_type, **options) yield if block_given? modal = find_modal(**options) message = modal.text modal.dismiss message end def quit @browser&.quit rescue Selenium::WebDriver::Error::SessionNotCreatedError, Errno::ECONNREFUSED, Selenium::WebDriver::Error::InvalidSessionIdError # Browser must have already gone rescue Selenium::WebDriver::Error::UnknownError => e unless silenced_unknown_error_message?(e.message) # Most likely already gone # probably already gone but not sure - so warn warn "Ignoring Selenium UnknownError during driver quit: #{e.message}" end ensure @browser = nil end def invalid_element_errors @invalid_element_errors ||= [ ::Selenium::WebDriver::Error::StaleElementReferenceError, ::Selenium::WebDriver::Error::ElementNotInteractableError, ::Selenium::WebDriver::Error::InvalidSelectorError, # Work around chromedriver go_back/go_forward race condition ::Selenium::WebDriver::Error::ElementClickInterceptedError, ::Selenium::WebDriver::Error::NoSuchElementError, # IE ::Selenium::WebDriver::Error::InvalidArgumentError # IE ].tap do |errors| if defined?(::Selenium::WebDriver::Error::DetachedShadowRootError) errors.push(::Selenium::WebDriver::Error::DetachedShadowRootError) end end end def no_such_window_error Selenium::WebDriver::Error::NoSuchWindowError end private def native_args(args) args.map { |arg| arg.is_a?(Capybara::Selenium::Node) ? arg.native : arg } end def native_active_element browser.switch_to.active_element end def clear_browser_state delete_all_cookies clear_storage rescue *clear_browser_state_errors # delete_all_cookies fails when we've previously gone # to about:blank, so we rescue this error and do nothing # instead. end def clear_browser_state_errors @clear_browser_state_errors ||= [Selenium::WebDriver::Error::UnknownError] end def unhandled_alert_errors @unhandled_alert_errors ||= [Selenium::WebDriver::Error::UnexpectedAlertOpenError] end def delete_all_cookies @browser.manage.delete_all_cookies end def clear_storage clear_session_storage unless options[:clear_session_storage] == false clear_local_storage unless options[:clear_local_storage] == false rescue Selenium::WebDriver::Error::JavascriptError, Selenium::WebDriver::Error::WebDriverError # session/local storage may not be available if on non-http pages (e.g. about:blank) end def clear_session_storage if @browser.respond_to? :session_storage @browser.session_storage.clear else begin @browser&.execute_script('window.sessionStorage.clear()') rescue # rubocop:disable Style/RescueStandardError unless options[:clear_session_storage].nil? warn 'sessionStorage clear requested but is not supported by this driver' end end end end def clear_local_storage # selenium-webdriver 4.30.0 removed HTML5 storage accessors -- not really sure why # can we replicate this robustly via CDP? if @browser.respond_to? :local_storage @browser.local_storage.clear else begin @browser&.execute_script('window.localStorage.clear()') rescue # rubocop:disable Style/RescueStandardError unless options[:clear_local_storage].nil? warn 'localStorage clear requested but is not supported by this driver' end end end end def navigate_with_accept(url) @browser.navigate.to(url) sleep 0.1 # slight wait for alert @browser.switch_to.alert.accept rescue modal_error # alert now gone, should mean navigation happened end def modal_error Selenium::WebDriver::Error::NoSuchAlertError end def within_given_window(handle) original_handle = current_window_handle if handle == original_handle yield else switch_to_window(handle) result = yield switch_to_window(original_handle) result end end def find_modal(text: nil, **options) # Selenium has its own built in wait (2 seconds)for a modal to show up, so this wait is really the minimum time # Actual wait time may be longer than specified wait = Selenium::WebDriver::Wait.new( timeout: options.fetch(:wait, session_options.default_max_wait_time) || 0, ignore: modal_error ) begin wait.until do alert = @browser.switch_to.alert regexp = text.is_a?(Regexp) ? text : Regexp.new(Regexp.escape(text.to_s)) matched = alert.text.match?(regexp) unless matched raise Capybara::ModalNotFound, "Unable to find modal dialog with #{text} - found '#{alert.text}' instead." end alert end rescue *find_modal_errors raise Capybara::ModalNotFound, "Unable to find modal dialog#{" with #{text}" if text}" end end def find_modal_errors @find_modal_errors ||= [Selenium::WebDriver::Error::TimeoutError] end def silenced_unknown_error_message?(msg) silenced_unknown_error_messages.any? { |regex| msg.match? regex } end def silenced_unknown_error_messages [/Error communicating with the remote browser/] end def unwrap_script_result(arg) case arg when Array arg.map { |arr| unwrap_script_result(arr) } when Hash arg.transform_values! { |value| unwrap_script_result(value) } when Selenium::WebDriver::Element, Selenium::WebDriver::ShadowRoot build_node(arg) else arg end end def find_context browser end def build_node(native_node, initial_cache = {}) ::Capybara::Selenium::Node.new(self, native_node, initial_cache) end def bridge browser.send(:bridge) end def specialize_driver browser_type = browser.browser Capybara::Selenium::Driver.specializations.select { |k, _v| k === browser_type }.each_value do |specialization| # rubocop:disable Style/CaseEquality extend specialization end end def setup_exit_handler main = Process.pid at_exit do # Store the exit status of the test run since it goes away after calling the at_exit proc... @exit_status = $ERROR_INFO.status if $ERROR_INFO.is_a?(SystemExit) quit if Process.pid == main exit @exit_status if @exit_status # Force exit with stored status end end def reset_browser_state clear_browser_state @browser.navigate.to('about:blank') end def wait_for_empty_page(timer) until find_xpath('/html/body/*').empty? raise Capybara::ExpectationNotMet, 'Timed out waiting for Selenium session reset' if timer.expired? sleep 0.01 # It has been observed that it is possible that asynchronous JS code in # the application under test can navigate the browser away from about:blank # if the timing is just right. Ensure we are still at about:blank... @browser.navigate.to('about:blank') unless current_url == 'about:blank' end end def accept_unhandled_reset_alert @browser.switch_to.alert.accept sleep 0.25 # allow time for the modal to be handled rescue modal_error # The alert is now gone. # If navigation has not occurred attempt again and accept alert # since FF may have dismissed the alert at first attempt. navigate_with_accept('about:blank') if current_url != 'about:blank' end end require 'capybara/selenium/driver_specializations/chrome_driver' require 'capybara/selenium/driver_specializations/firefox_driver' require 'capybara/selenium/driver_specializations/internet_explorer_driver' require 'capybara/selenium/driver_specializations/safari_driver' require 'capybara/selenium/driver_specializations/edge_driver'
Ruby
{ "end_line": 176, "name": "reset!", "signature": "def reset!", "start_line": 155 }
{ "class_name": "Capybara::Selenium::Driver", "class_signature": "class Capybara::Selenium::Driver < < Capybara::Driver::Base", "module": "" }
frame_obscured_at?
capybara/lib/capybara/selenium/driver.rb
def frame_obscured_at?(x:, y:) frame = @frame_handles[current_window_handle].last return false unless frame switch_to_frame(:parent) begin frame.base.obscured?(x: x, y: y) ensure switch_to_frame(frame) end end
# frozen_string_literal: true require 'uri' require 'English' class Capybara::Selenium::Driver < Capybara::Driver::Base include Capybara::Selenium::Find DEFAULT_OPTIONS = { browser: :firefox, clear_local_storage: nil, clear_session_storage: nil }.freeze SPECIAL_OPTIONS = %i[browser clear_local_storage clear_session_storage timeout native_displayed].freeze CAPS_VERSION = Gem::Requirement.new('< 4.8.0') attr_reader :app, :options class << self attr_reader :selenium_webdriver_version def load_selenium require 'selenium-webdriver' require 'capybara/selenium/patches/atoms' require 'capybara/selenium/patches/is_displayed' # Look up the version of `selenium-webdriver` to # see if it's a version we support. # # By default, we use Gem.loaded_specs to determine # the version number. However, in some cases, such # as when loading `selenium-webdriver` outside of # Rubygems, we fall back to referencing # Selenium::WebDriver::VERSION. Ideally we'd # use the constant in all cases, but earlier versions # of `selenium-webdriver` didn't provide the constant. @selenium_webdriver_version = if Gem.loaded_specs['selenium-webdriver'] Gem.loaded_specs['selenium-webdriver'].version else Gem::Version.new(Selenium::WebDriver::VERSION) end unless Gem::Requirement.new('>= 4.8').satisfied_by? @selenium_webdriver_version warn "Warning: You're using an unsupported version of selenium-webdriver, please upgrade to 4.8+." end @selenium_webdriver_version rescue LoadError => e raise e unless e.message.include?('selenium-webdriver') raise LoadError, "Capybara's selenium driver is unable to load `selenium-webdriver`, please install the gem and add `gem 'selenium-webdriver'` to your Gemfile if you are using bundler." end attr_reader :specializations def register_specialization(browser_name, specialization) @specializations ||= {} @specializations[browser_name] = specialization end end def browser unless @browser options[:http_client] ||= begin require 'capybara/selenium/patches/persistent_client' if options[:timeout] ::Capybara::Selenium::PersistentClient.new(read_timeout: options[:timeout]) else ::Capybara::Selenium::PersistentClient.new end end processed_options = options.except(*SPECIAL_OPTIONS) @browser = Selenium::WebDriver.for(options[:browser], processed_options) specialize_driver setup_exit_handler end @browser end def initialize(app, **options) super() self.class.load_selenium @app = app @browser = nil @exit_status = nil @frame_handles = Hash.new { |hash, handle| hash[handle] = [] } @options = DEFAULT_OPTIONS.merge(options) @node_class = ::Capybara::Selenium::Node end def visit(path) browser.navigate.to(path) end def refresh browser.navigate.refresh end def go_back browser.navigate.back end def go_forward browser.navigate.forward end def html browser.page_source rescue Selenium::WebDriver::Error::JavascriptError => e raise unless e.message.include?('documentElement is null') end def title browser.title end def current_url browser.current_url end def wait?; true; end def needs_server?; true; end def execute_script(script, *args) browser.execute_script(script, *native_args(args)) end def evaluate_script(script, *args) result = execute_script("return #{script}", *args) unwrap_script_result(result) end def evaluate_async_script(script, *args) browser.manage.timeouts.script_timeout = Capybara.default_max_wait_time result = browser.execute_async_script(script, *native_args(args)) unwrap_script_result(result) end def active_element build_node(native_active_element) end def send_keys(*args) # Should this call the specialized nodes rather than native??? native_active_element.send_keys(*args) end def save_screenshot(path, **options) browser.save_screenshot(path, **options) end def reset! # Use instance variable directly so we avoid starting the browser just to reset the session return unless @browser navigated = false timer = Capybara::Helpers.timer(expire_in: 10) begin # Only trigger a navigation if we haven't done it already, otherwise it # can trigger an endless series of unload modals reset_browser_state unless navigated navigated = true # Ensure the page is empty and trigger an UnhandledAlertError for any modals that appear during unload wait_for_empty_page(timer) rescue *unhandled_alert_errors # This error is thrown if an unhandled alert is on the page # Firefox appears to automatically dismiss this alert, chrome does not # We'll try to accept it accept_unhandled_reset_alert # try cleaning up the browser again retry end end def frame_obscured_at?(x:, y:) frame = @frame_handles[current_window_handle].last return false unless frame switch_to_frame(:parent) begin frame.base.obscured?(x: x, y: y) ensure switch_to_frame(frame) end end def switch_to_frame(frame) handles = @frame_handles[current_window_handle] case frame when :top handles.clear browser.switch_to.default_content when :parent handles.pop browser.switch_to.parent_frame else handles << frame browser.switch_to.frame(frame.native) end end def current_window_handle browser.window_handle end def window_size(handle) within_given_window(handle) do size = browser.manage.window.size [size.width, size.height] end end def resize_window_to(handle, width, height) within_given_window(handle) do browser.manage.window.resize_to(width, height) end end def maximize_window(handle) within_given_window(handle) do browser.manage.window.maximize end sleep 0.1 # work around for https://code.google.com/p/selenium/issues/detail?id=7405 end def fullscreen_window(handle) within_given_window(handle) do browser.manage.window.full_screen end end def close_window(handle) raise ArgumentError, 'Not allowed to close the primary window' if handle == window_handles.first within_given_window(handle) do browser.close end end def window_handles browser.window_handles end def open_new_window(kind = :tab) if browser.switch_to.respond_to?(:new_window) handle = current_window_handle browser.switch_to.new_window(kind) switch_to_window(handle) else browser.manage.new_window(kind) end rescue NoMethodError, Selenium::WebDriver::Error::WebDriverError # If not supported by the driver or browser default to using JS browser.execute_script('window.open();') end def switch_to_window(handle) browser.switch_to.window handle end def accept_modal(_type, **options) yield if block_given? modal = find_modal(**options) modal.send_keys options[:with] if options[:with] message = modal.text modal.accept message end def dismiss_modal(_type, **options) yield if block_given? modal = find_modal(**options) message = modal.text modal.dismiss message end def quit @browser&.quit rescue Selenium::WebDriver::Error::SessionNotCreatedError, Errno::ECONNREFUSED, Selenium::WebDriver::Error::InvalidSessionIdError # Browser must have already gone rescue Selenium::WebDriver::Error::UnknownError => e unless silenced_unknown_error_message?(e.message) # Most likely already gone # probably already gone but not sure - so warn warn "Ignoring Selenium UnknownError during driver quit: #{e.message}" end ensure @browser = nil end def invalid_element_errors @invalid_element_errors ||= [ ::Selenium::WebDriver::Error::StaleElementReferenceError, ::Selenium::WebDriver::Error::ElementNotInteractableError, ::Selenium::WebDriver::Error::InvalidSelectorError, # Work around chromedriver go_back/go_forward race condition ::Selenium::WebDriver::Error::ElementClickInterceptedError, ::Selenium::WebDriver::Error::NoSuchElementError, # IE ::Selenium::WebDriver::Error::InvalidArgumentError # IE ].tap do |errors| if defined?(::Selenium::WebDriver::Error::DetachedShadowRootError) errors.push(::Selenium::WebDriver::Error::DetachedShadowRootError) end end end def no_such_window_error Selenium::WebDriver::Error::NoSuchWindowError end private def native_args(args) args.map { |arg| arg.is_a?(Capybara::Selenium::Node) ? arg.native : arg } end def native_active_element browser.switch_to.active_element end def clear_browser_state delete_all_cookies clear_storage rescue *clear_browser_state_errors # delete_all_cookies fails when we've previously gone # to about:blank, so we rescue this error and do nothing # instead. end def clear_browser_state_errors @clear_browser_state_errors ||= [Selenium::WebDriver::Error::UnknownError] end def unhandled_alert_errors @unhandled_alert_errors ||= [Selenium::WebDriver::Error::UnexpectedAlertOpenError] end def delete_all_cookies @browser.manage.delete_all_cookies end def clear_storage clear_session_storage unless options[:clear_session_storage] == false clear_local_storage unless options[:clear_local_storage] == false rescue Selenium::WebDriver::Error::JavascriptError, Selenium::WebDriver::Error::WebDriverError # session/local storage may not be available if on non-http pages (e.g. about:blank) end def clear_session_storage if @browser.respond_to? :session_storage @browser.session_storage.clear else begin @browser&.execute_script('window.sessionStorage.clear()') rescue # rubocop:disable Style/RescueStandardError unless options[:clear_session_storage].nil? warn 'sessionStorage clear requested but is not supported by this driver' end end end end def clear_local_storage # selenium-webdriver 4.30.0 removed HTML5 storage accessors -- not really sure why # can we replicate this robustly via CDP? if @browser.respond_to? :local_storage @browser.local_storage.clear else begin @browser&.execute_script('window.localStorage.clear()') rescue # rubocop:disable Style/RescueStandardError unless options[:clear_local_storage].nil? warn 'localStorage clear requested but is not supported by this driver' end end end end def navigate_with_accept(url) @browser.navigate.to(url) sleep 0.1 # slight wait for alert @browser.switch_to.alert.accept rescue modal_error # alert now gone, should mean navigation happened end def modal_error Selenium::WebDriver::Error::NoSuchAlertError end def within_given_window(handle) original_handle = current_window_handle if handle == original_handle yield else switch_to_window(handle) result = yield switch_to_window(original_handle) result end end def find_modal(text: nil, **options) # Selenium has its own built in wait (2 seconds)for a modal to show up, so this wait is really the minimum time # Actual wait time may be longer than specified wait = Selenium::WebDriver::Wait.new( timeout: options.fetch(:wait, session_options.default_max_wait_time) || 0, ignore: modal_error ) begin wait.until do alert = @browser.switch_to.alert regexp = text.is_a?(Regexp) ? text : Regexp.new(Regexp.escape(text.to_s)) matched = alert.text.match?(regexp) unless matched raise Capybara::ModalNotFound, "Unable to find modal dialog with #{text} - found '#{alert.text}' instead." end alert end rescue *find_modal_errors raise Capybara::ModalNotFound, "Unable to find modal dialog#{" with #{text}" if text}" end end def find_modal_errors @find_modal_errors ||= [Selenium::WebDriver::Error::TimeoutError] end def silenced_unknown_error_message?(msg) silenced_unknown_error_messages.any? { |regex| msg.match? regex } end def silenced_unknown_error_messages [/Error communicating with the remote browser/] end def unwrap_script_result(arg) case arg when Array arg.map { |arr| unwrap_script_result(arr) } when Hash arg.transform_values! { |value| unwrap_script_result(value) } when Selenium::WebDriver::Element, Selenium::WebDriver::ShadowRoot build_node(arg) else arg end end def find_context browser end def build_node(native_node, initial_cache = {}) ::Capybara::Selenium::Node.new(self, native_node, initial_cache) end def bridge browser.send(:bridge) end def specialize_driver browser_type = browser.browser Capybara::Selenium::Driver.specializations.select { |k, _v| k === browser_type }.each_value do |specialization| # rubocop:disable Style/CaseEquality extend specialization end end def setup_exit_handler main = Process.pid at_exit do # Store the exit status of the test run since it goes away after calling the at_exit proc... @exit_status = $ERROR_INFO.status if $ERROR_INFO.is_a?(SystemExit) quit if Process.pid == main exit @exit_status if @exit_status # Force exit with stored status end end def reset_browser_state clear_browser_state @browser.navigate.to('about:blank') end def wait_for_empty_page(timer) until find_xpath('/html/body/*').empty? raise Capybara::ExpectationNotMet, 'Timed out waiting for Selenium session reset' if timer.expired? sleep 0.01 # It has been observed that it is possible that asynchronous JS code in # the application under test can navigate the browser away from about:blank # if the timing is just right. Ensure we are still at about:blank... @browser.navigate.to('about:blank') unless current_url == 'about:blank' end end def accept_unhandled_reset_alert @browser.switch_to.alert.accept sleep 0.25 # allow time for the modal to be handled rescue modal_error # The alert is now gone. # If navigation has not occurred attempt again and accept alert # since FF may have dismissed the alert at first attempt. navigate_with_accept('about:blank') if current_url != 'about:blank' end end require 'capybara/selenium/driver_specializations/chrome_driver' require 'capybara/selenium/driver_specializations/firefox_driver' require 'capybara/selenium/driver_specializations/internet_explorer_driver' require 'capybara/selenium/driver_specializations/safari_driver' require 'capybara/selenium/driver_specializations/edge_driver'
Ruby
{ "end_line": 188, "name": "frame_obscured_at?", "signature": "def frame_obscured_at?(x:, y:)", "start_line": 178 }
{ "class_name": "Capybara::Selenium::Driver", "class_signature": "class Capybara::Selenium::Driver < < Capybara::Driver::Base", "module": "" }
switch_to_frame
capybara/lib/capybara/selenium/driver.rb
def switch_to_frame(frame) handles = @frame_handles[current_window_handle] case frame when :top handles.clear browser.switch_to.default_content when :parent handles.pop browser.switch_to.parent_frame else handles << frame browser.switch_to.frame(frame.native) end end
# frozen_string_literal: true require 'uri' require 'English' class Capybara::Selenium::Driver < Capybara::Driver::Base include Capybara::Selenium::Find DEFAULT_OPTIONS = { browser: :firefox, clear_local_storage: nil, clear_session_storage: nil }.freeze SPECIAL_OPTIONS = %i[browser clear_local_storage clear_session_storage timeout native_displayed].freeze CAPS_VERSION = Gem::Requirement.new('< 4.8.0') attr_reader :app, :options class << self attr_reader :selenium_webdriver_version def load_selenium require 'selenium-webdriver' require 'capybara/selenium/patches/atoms' require 'capybara/selenium/patches/is_displayed' # Look up the version of `selenium-webdriver` to # see if it's a version we support. # # By default, we use Gem.loaded_specs to determine # the version number. However, in some cases, such # as when loading `selenium-webdriver` outside of # Rubygems, we fall back to referencing # Selenium::WebDriver::VERSION. Ideally we'd # use the constant in all cases, but earlier versions # of `selenium-webdriver` didn't provide the constant. @selenium_webdriver_version = if Gem.loaded_specs['selenium-webdriver'] Gem.loaded_specs['selenium-webdriver'].version else Gem::Version.new(Selenium::WebDriver::VERSION) end unless Gem::Requirement.new('>= 4.8').satisfied_by? @selenium_webdriver_version warn "Warning: You're using an unsupported version of selenium-webdriver, please upgrade to 4.8+." end @selenium_webdriver_version rescue LoadError => e raise e unless e.message.include?('selenium-webdriver') raise LoadError, "Capybara's selenium driver is unable to load `selenium-webdriver`, please install the gem and add `gem 'selenium-webdriver'` to your Gemfile if you are using bundler." end attr_reader :specializations def register_specialization(browser_name, specialization) @specializations ||= {} @specializations[browser_name] = specialization end end def browser unless @browser options[:http_client] ||= begin require 'capybara/selenium/patches/persistent_client' if options[:timeout] ::Capybara::Selenium::PersistentClient.new(read_timeout: options[:timeout]) else ::Capybara::Selenium::PersistentClient.new end end processed_options = options.except(*SPECIAL_OPTIONS) @browser = Selenium::WebDriver.for(options[:browser], processed_options) specialize_driver setup_exit_handler end @browser end def initialize(app, **options) super() self.class.load_selenium @app = app @browser = nil @exit_status = nil @frame_handles = Hash.new { |hash, handle| hash[handle] = [] } @options = DEFAULT_OPTIONS.merge(options) @node_class = ::Capybara::Selenium::Node end def visit(path) browser.navigate.to(path) end def refresh browser.navigate.refresh end def go_back browser.navigate.back end def go_forward browser.navigate.forward end def html browser.page_source rescue Selenium::WebDriver::Error::JavascriptError => e raise unless e.message.include?('documentElement is null') end def title browser.title end def current_url browser.current_url end def wait?; true; end def needs_server?; true; end def execute_script(script, *args) browser.execute_script(script, *native_args(args)) end def evaluate_script(script, *args) result = execute_script("return #{script}", *args) unwrap_script_result(result) end def evaluate_async_script(script, *args) browser.manage.timeouts.script_timeout = Capybara.default_max_wait_time result = browser.execute_async_script(script, *native_args(args)) unwrap_script_result(result) end def active_element build_node(native_active_element) end def send_keys(*args) # Should this call the specialized nodes rather than native??? native_active_element.send_keys(*args) end def save_screenshot(path, **options) browser.save_screenshot(path, **options) end def reset! # Use instance variable directly so we avoid starting the browser just to reset the session return unless @browser navigated = false timer = Capybara::Helpers.timer(expire_in: 10) begin # Only trigger a navigation if we haven't done it already, otherwise it # can trigger an endless series of unload modals reset_browser_state unless navigated navigated = true # Ensure the page is empty and trigger an UnhandledAlertError for any modals that appear during unload wait_for_empty_page(timer) rescue *unhandled_alert_errors # This error is thrown if an unhandled alert is on the page # Firefox appears to automatically dismiss this alert, chrome does not # We'll try to accept it accept_unhandled_reset_alert # try cleaning up the browser again retry end end def frame_obscured_at?(x:, y:) frame = @frame_handles[current_window_handle].last return false unless frame switch_to_frame(:parent) begin frame.base.obscured?(x: x, y: y) ensure switch_to_frame(frame) end end def switch_to_frame(frame) handles = @frame_handles[current_window_handle] case frame when :top handles.clear browser.switch_to.default_content when :parent handles.pop browser.switch_to.parent_frame else handles << frame browser.switch_to.frame(frame.native) end end def current_window_handle browser.window_handle end def window_size(handle) within_given_window(handle) do size = browser.manage.window.size [size.width, size.height] end end def resize_window_to(handle, width, height) within_given_window(handle) do browser.manage.window.resize_to(width, height) end end def maximize_window(handle) within_given_window(handle) do browser.manage.window.maximize end sleep 0.1 # work around for https://code.google.com/p/selenium/issues/detail?id=7405 end def fullscreen_window(handle) within_given_window(handle) do browser.manage.window.full_screen end end def close_window(handle) raise ArgumentError, 'Not allowed to close the primary window' if handle == window_handles.first within_given_window(handle) do browser.close end end def window_handles browser.window_handles end def open_new_window(kind = :tab) if browser.switch_to.respond_to?(:new_window) handle = current_window_handle browser.switch_to.new_window(kind) switch_to_window(handle) else browser.manage.new_window(kind) end rescue NoMethodError, Selenium::WebDriver::Error::WebDriverError # If not supported by the driver or browser default to using JS browser.execute_script('window.open();') end def switch_to_window(handle) browser.switch_to.window handle end def accept_modal(_type, **options) yield if block_given? modal = find_modal(**options) modal.send_keys options[:with] if options[:with] message = modal.text modal.accept message end def dismiss_modal(_type, **options) yield if block_given? modal = find_modal(**options) message = modal.text modal.dismiss message end def quit @browser&.quit rescue Selenium::WebDriver::Error::SessionNotCreatedError, Errno::ECONNREFUSED, Selenium::WebDriver::Error::InvalidSessionIdError # Browser must have already gone rescue Selenium::WebDriver::Error::UnknownError => e unless silenced_unknown_error_message?(e.message) # Most likely already gone # probably already gone but not sure - so warn warn "Ignoring Selenium UnknownError during driver quit: #{e.message}" end ensure @browser = nil end def invalid_element_errors @invalid_element_errors ||= [ ::Selenium::WebDriver::Error::StaleElementReferenceError, ::Selenium::WebDriver::Error::ElementNotInteractableError, ::Selenium::WebDriver::Error::InvalidSelectorError, # Work around chromedriver go_back/go_forward race condition ::Selenium::WebDriver::Error::ElementClickInterceptedError, ::Selenium::WebDriver::Error::NoSuchElementError, # IE ::Selenium::WebDriver::Error::InvalidArgumentError # IE ].tap do |errors| if defined?(::Selenium::WebDriver::Error::DetachedShadowRootError) errors.push(::Selenium::WebDriver::Error::DetachedShadowRootError) end end end def no_such_window_error Selenium::WebDriver::Error::NoSuchWindowError end private def native_args(args) args.map { |arg| arg.is_a?(Capybara::Selenium::Node) ? arg.native : arg } end def native_active_element browser.switch_to.active_element end def clear_browser_state delete_all_cookies clear_storage rescue *clear_browser_state_errors # delete_all_cookies fails when we've previously gone # to about:blank, so we rescue this error and do nothing # instead. end def clear_browser_state_errors @clear_browser_state_errors ||= [Selenium::WebDriver::Error::UnknownError] end def unhandled_alert_errors @unhandled_alert_errors ||= [Selenium::WebDriver::Error::UnexpectedAlertOpenError] end def delete_all_cookies @browser.manage.delete_all_cookies end def clear_storage clear_session_storage unless options[:clear_session_storage] == false clear_local_storage unless options[:clear_local_storage] == false rescue Selenium::WebDriver::Error::JavascriptError, Selenium::WebDriver::Error::WebDriverError # session/local storage may not be available if on non-http pages (e.g. about:blank) end def clear_session_storage if @browser.respond_to? :session_storage @browser.session_storage.clear else begin @browser&.execute_script('window.sessionStorage.clear()') rescue # rubocop:disable Style/RescueStandardError unless options[:clear_session_storage].nil? warn 'sessionStorage clear requested but is not supported by this driver' end end end end def clear_local_storage # selenium-webdriver 4.30.0 removed HTML5 storage accessors -- not really sure why # can we replicate this robustly via CDP? if @browser.respond_to? :local_storage @browser.local_storage.clear else begin @browser&.execute_script('window.localStorage.clear()') rescue # rubocop:disable Style/RescueStandardError unless options[:clear_local_storage].nil? warn 'localStorage clear requested but is not supported by this driver' end end end end def navigate_with_accept(url) @browser.navigate.to(url) sleep 0.1 # slight wait for alert @browser.switch_to.alert.accept rescue modal_error # alert now gone, should mean navigation happened end def modal_error Selenium::WebDriver::Error::NoSuchAlertError end def within_given_window(handle) original_handle = current_window_handle if handle == original_handle yield else switch_to_window(handle) result = yield switch_to_window(original_handle) result end end def find_modal(text: nil, **options) # Selenium has its own built in wait (2 seconds)for a modal to show up, so this wait is really the minimum time # Actual wait time may be longer than specified wait = Selenium::WebDriver::Wait.new( timeout: options.fetch(:wait, session_options.default_max_wait_time) || 0, ignore: modal_error ) begin wait.until do alert = @browser.switch_to.alert regexp = text.is_a?(Regexp) ? text : Regexp.new(Regexp.escape(text.to_s)) matched = alert.text.match?(regexp) unless matched raise Capybara::ModalNotFound, "Unable to find modal dialog with #{text} - found '#{alert.text}' instead." end alert end rescue *find_modal_errors raise Capybara::ModalNotFound, "Unable to find modal dialog#{" with #{text}" if text}" end end def find_modal_errors @find_modal_errors ||= [Selenium::WebDriver::Error::TimeoutError] end def silenced_unknown_error_message?(msg) silenced_unknown_error_messages.any? { |regex| msg.match? regex } end def silenced_unknown_error_messages [/Error communicating with the remote browser/] end def unwrap_script_result(arg) case arg when Array arg.map { |arr| unwrap_script_result(arr) } when Hash arg.transform_values! { |value| unwrap_script_result(value) } when Selenium::WebDriver::Element, Selenium::WebDriver::ShadowRoot build_node(arg) else arg end end def find_context browser end def build_node(native_node, initial_cache = {}) ::Capybara::Selenium::Node.new(self, native_node, initial_cache) end def bridge browser.send(:bridge) end def specialize_driver browser_type = browser.browser Capybara::Selenium::Driver.specializations.select { |k, _v| k === browser_type }.each_value do |specialization| # rubocop:disable Style/CaseEquality extend specialization end end def setup_exit_handler main = Process.pid at_exit do # Store the exit status of the test run since it goes away after calling the at_exit proc... @exit_status = $ERROR_INFO.status if $ERROR_INFO.is_a?(SystemExit) quit if Process.pid == main exit @exit_status if @exit_status # Force exit with stored status end end def reset_browser_state clear_browser_state @browser.navigate.to('about:blank') end def wait_for_empty_page(timer) until find_xpath('/html/body/*').empty? raise Capybara::ExpectationNotMet, 'Timed out waiting for Selenium session reset' if timer.expired? sleep 0.01 # It has been observed that it is possible that asynchronous JS code in # the application under test can navigate the browser away from about:blank # if the timing is just right. Ensure we are still at about:blank... @browser.navigate.to('about:blank') unless current_url == 'about:blank' end end def accept_unhandled_reset_alert @browser.switch_to.alert.accept sleep 0.25 # allow time for the modal to be handled rescue modal_error # The alert is now gone. # If navigation has not occurred attempt again and accept alert # since FF may have dismissed the alert at first attempt. navigate_with_accept('about:blank') if current_url != 'about:blank' end end require 'capybara/selenium/driver_specializations/chrome_driver' require 'capybara/selenium/driver_specializations/firefox_driver' require 'capybara/selenium/driver_specializations/internet_explorer_driver' require 'capybara/selenium/driver_specializations/safari_driver' require 'capybara/selenium/driver_specializations/edge_driver'
Ruby
{ "end_line": 203, "name": "switch_to_frame", "signature": "def switch_to_frame(frame)", "start_line": 190 }
{ "class_name": "Capybara::Selenium::Driver", "class_signature": "class Capybara::Selenium::Driver < < Capybara::Driver::Base", "module": "" }
open_new_window
capybara/lib/capybara/selenium/driver.rb
def open_new_window(kind = :tab) if browser.switch_to.respond_to?(:new_window) handle = current_window_handle browser.switch_to.new_window(kind) switch_to_window(handle) else browser.manage.new_window(kind) end rescue NoMethodError, Selenium::WebDriver::Error::WebDriverError # If not supported by the driver or browser default to using JS browser.execute_script('window.open();') end
# frozen_string_literal: true require 'uri' require 'English' class Capybara::Selenium::Driver < Capybara::Driver::Base include Capybara::Selenium::Find DEFAULT_OPTIONS = { browser: :firefox, clear_local_storage: nil, clear_session_storage: nil }.freeze SPECIAL_OPTIONS = %i[browser clear_local_storage clear_session_storage timeout native_displayed].freeze CAPS_VERSION = Gem::Requirement.new('< 4.8.0') attr_reader :app, :options class << self attr_reader :selenium_webdriver_version def load_selenium require 'selenium-webdriver' require 'capybara/selenium/patches/atoms' require 'capybara/selenium/patches/is_displayed' # Look up the version of `selenium-webdriver` to # see if it's a version we support. # # By default, we use Gem.loaded_specs to determine # the version number. However, in some cases, such # as when loading `selenium-webdriver` outside of # Rubygems, we fall back to referencing # Selenium::WebDriver::VERSION. Ideally we'd # use the constant in all cases, but earlier versions # of `selenium-webdriver` didn't provide the constant. @selenium_webdriver_version = if Gem.loaded_specs['selenium-webdriver'] Gem.loaded_specs['selenium-webdriver'].version else Gem::Version.new(Selenium::WebDriver::VERSION) end unless Gem::Requirement.new('>= 4.8').satisfied_by? @selenium_webdriver_version warn "Warning: You're using an unsupported version of selenium-webdriver, please upgrade to 4.8+." end @selenium_webdriver_version rescue LoadError => e raise e unless e.message.include?('selenium-webdriver') raise LoadError, "Capybara's selenium driver is unable to load `selenium-webdriver`, please install the gem and add `gem 'selenium-webdriver'` to your Gemfile if you are using bundler." end attr_reader :specializations def register_specialization(browser_name, specialization) @specializations ||= {} @specializations[browser_name] = specialization end end def browser unless @browser options[:http_client] ||= begin require 'capybara/selenium/patches/persistent_client' if options[:timeout] ::Capybara::Selenium::PersistentClient.new(read_timeout: options[:timeout]) else ::Capybara::Selenium::PersistentClient.new end end processed_options = options.except(*SPECIAL_OPTIONS) @browser = Selenium::WebDriver.for(options[:browser], processed_options) specialize_driver setup_exit_handler end @browser end def initialize(app, **options) super() self.class.load_selenium @app = app @browser = nil @exit_status = nil @frame_handles = Hash.new { |hash, handle| hash[handle] = [] } @options = DEFAULT_OPTIONS.merge(options) @node_class = ::Capybara::Selenium::Node end def visit(path) browser.navigate.to(path) end def refresh browser.navigate.refresh end def go_back browser.navigate.back end def go_forward browser.navigate.forward end def html browser.page_source rescue Selenium::WebDriver::Error::JavascriptError => e raise unless e.message.include?('documentElement is null') end def title browser.title end def current_url browser.current_url end def wait?; true; end def needs_server?; true; end def execute_script(script, *args) browser.execute_script(script, *native_args(args)) end def evaluate_script(script, *args) result = execute_script("return #{script}", *args) unwrap_script_result(result) end def evaluate_async_script(script, *args) browser.manage.timeouts.script_timeout = Capybara.default_max_wait_time result = browser.execute_async_script(script, *native_args(args)) unwrap_script_result(result) end def active_element build_node(native_active_element) end def send_keys(*args) # Should this call the specialized nodes rather than native??? native_active_element.send_keys(*args) end def save_screenshot(path, **options) browser.save_screenshot(path, **options) end def reset! # Use instance variable directly so we avoid starting the browser just to reset the session return unless @browser navigated = false timer = Capybara::Helpers.timer(expire_in: 10) begin # Only trigger a navigation if we haven't done it already, otherwise it # can trigger an endless series of unload modals reset_browser_state unless navigated navigated = true # Ensure the page is empty and trigger an UnhandledAlertError for any modals that appear during unload wait_for_empty_page(timer) rescue *unhandled_alert_errors # This error is thrown if an unhandled alert is on the page # Firefox appears to automatically dismiss this alert, chrome does not # We'll try to accept it accept_unhandled_reset_alert # try cleaning up the browser again retry end end def frame_obscured_at?(x:, y:) frame = @frame_handles[current_window_handle].last return false unless frame switch_to_frame(:parent) begin frame.base.obscured?(x: x, y: y) ensure switch_to_frame(frame) end end def switch_to_frame(frame) handles = @frame_handles[current_window_handle] case frame when :top handles.clear browser.switch_to.default_content when :parent handles.pop browser.switch_to.parent_frame else handles << frame browser.switch_to.frame(frame.native) end end def current_window_handle browser.window_handle end def window_size(handle) within_given_window(handle) do size = browser.manage.window.size [size.width, size.height] end end def resize_window_to(handle, width, height) within_given_window(handle) do browser.manage.window.resize_to(width, height) end end def maximize_window(handle) within_given_window(handle) do browser.manage.window.maximize end sleep 0.1 # work around for https://code.google.com/p/selenium/issues/detail?id=7405 end def fullscreen_window(handle) within_given_window(handle) do browser.manage.window.full_screen end end def close_window(handle) raise ArgumentError, 'Not allowed to close the primary window' if handle == window_handles.first within_given_window(handle) do browser.close end end def window_handles browser.window_handles end def open_new_window(kind = :tab) if browser.switch_to.respond_to?(:new_window) handle = current_window_handle browser.switch_to.new_window(kind) switch_to_window(handle) else browser.manage.new_window(kind) end rescue NoMethodError, Selenium::WebDriver::Error::WebDriverError # If not supported by the driver or browser default to using JS browser.execute_script('window.open();') end def switch_to_window(handle) browser.switch_to.window handle end def accept_modal(_type, **options) yield if block_given? modal = find_modal(**options) modal.send_keys options[:with] if options[:with] message = modal.text modal.accept message end def dismiss_modal(_type, **options) yield if block_given? modal = find_modal(**options) message = modal.text modal.dismiss message end def quit @browser&.quit rescue Selenium::WebDriver::Error::SessionNotCreatedError, Errno::ECONNREFUSED, Selenium::WebDriver::Error::InvalidSessionIdError # Browser must have already gone rescue Selenium::WebDriver::Error::UnknownError => e unless silenced_unknown_error_message?(e.message) # Most likely already gone # probably already gone but not sure - so warn warn "Ignoring Selenium UnknownError during driver quit: #{e.message}" end ensure @browser = nil end def invalid_element_errors @invalid_element_errors ||= [ ::Selenium::WebDriver::Error::StaleElementReferenceError, ::Selenium::WebDriver::Error::ElementNotInteractableError, ::Selenium::WebDriver::Error::InvalidSelectorError, # Work around chromedriver go_back/go_forward race condition ::Selenium::WebDriver::Error::ElementClickInterceptedError, ::Selenium::WebDriver::Error::NoSuchElementError, # IE ::Selenium::WebDriver::Error::InvalidArgumentError # IE ].tap do |errors| if defined?(::Selenium::WebDriver::Error::DetachedShadowRootError) errors.push(::Selenium::WebDriver::Error::DetachedShadowRootError) end end end def no_such_window_error Selenium::WebDriver::Error::NoSuchWindowError end private def native_args(args) args.map { |arg| arg.is_a?(Capybara::Selenium::Node) ? arg.native : arg } end def native_active_element browser.switch_to.active_element end def clear_browser_state delete_all_cookies clear_storage rescue *clear_browser_state_errors # delete_all_cookies fails when we've previously gone # to about:blank, so we rescue this error and do nothing # instead. end def clear_browser_state_errors @clear_browser_state_errors ||= [Selenium::WebDriver::Error::UnknownError] end def unhandled_alert_errors @unhandled_alert_errors ||= [Selenium::WebDriver::Error::UnexpectedAlertOpenError] end def delete_all_cookies @browser.manage.delete_all_cookies end def clear_storage clear_session_storage unless options[:clear_session_storage] == false clear_local_storage unless options[:clear_local_storage] == false rescue Selenium::WebDriver::Error::JavascriptError, Selenium::WebDriver::Error::WebDriverError # session/local storage may not be available if on non-http pages (e.g. about:blank) end def clear_session_storage if @browser.respond_to? :session_storage @browser.session_storage.clear else begin @browser&.execute_script('window.sessionStorage.clear()') rescue # rubocop:disable Style/RescueStandardError unless options[:clear_session_storage].nil? warn 'sessionStorage clear requested but is not supported by this driver' end end end end def clear_local_storage # selenium-webdriver 4.30.0 removed HTML5 storage accessors -- not really sure why # can we replicate this robustly via CDP? if @browser.respond_to? :local_storage @browser.local_storage.clear else begin @browser&.execute_script('window.localStorage.clear()') rescue # rubocop:disable Style/RescueStandardError unless options[:clear_local_storage].nil? warn 'localStorage clear requested but is not supported by this driver' end end end end def navigate_with_accept(url) @browser.navigate.to(url) sleep 0.1 # slight wait for alert @browser.switch_to.alert.accept rescue modal_error # alert now gone, should mean navigation happened end def modal_error Selenium::WebDriver::Error::NoSuchAlertError end def within_given_window(handle) original_handle = current_window_handle if handle == original_handle yield else switch_to_window(handle) result = yield switch_to_window(original_handle) result end end def find_modal(text: nil, **options) # Selenium has its own built in wait (2 seconds)for a modal to show up, so this wait is really the minimum time # Actual wait time may be longer than specified wait = Selenium::WebDriver::Wait.new( timeout: options.fetch(:wait, session_options.default_max_wait_time) || 0, ignore: modal_error ) begin wait.until do alert = @browser.switch_to.alert regexp = text.is_a?(Regexp) ? text : Regexp.new(Regexp.escape(text.to_s)) matched = alert.text.match?(regexp) unless matched raise Capybara::ModalNotFound, "Unable to find modal dialog with #{text} - found '#{alert.text}' instead." end alert end rescue *find_modal_errors raise Capybara::ModalNotFound, "Unable to find modal dialog#{" with #{text}" if text}" end end def find_modal_errors @find_modal_errors ||= [Selenium::WebDriver::Error::TimeoutError] end def silenced_unknown_error_message?(msg) silenced_unknown_error_messages.any? { |regex| msg.match? regex } end def silenced_unknown_error_messages [/Error communicating with the remote browser/] end def unwrap_script_result(arg) case arg when Array arg.map { |arr| unwrap_script_result(arr) } when Hash arg.transform_values! { |value| unwrap_script_result(value) } when Selenium::WebDriver::Element, Selenium::WebDriver::ShadowRoot build_node(arg) else arg end end def find_context browser end def build_node(native_node, initial_cache = {}) ::Capybara::Selenium::Node.new(self, native_node, initial_cache) end def bridge browser.send(:bridge) end def specialize_driver browser_type = browser.browser Capybara::Selenium::Driver.specializations.select { |k, _v| k === browser_type }.each_value do |specialization| # rubocop:disable Style/CaseEquality extend specialization end end def setup_exit_handler main = Process.pid at_exit do # Store the exit status of the test run since it goes away after calling the at_exit proc... @exit_status = $ERROR_INFO.status if $ERROR_INFO.is_a?(SystemExit) quit if Process.pid == main exit @exit_status if @exit_status # Force exit with stored status end end def reset_browser_state clear_browser_state @browser.navigate.to('about:blank') end def wait_for_empty_page(timer) until find_xpath('/html/body/*').empty? raise Capybara::ExpectationNotMet, 'Timed out waiting for Selenium session reset' if timer.expired? sleep 0.01 # It has been observed that it is possible that asynchronous JS code in # the application under test can navigate the browser away from about:blank # if the timing is just right. Ensure we are still at about:blank... @browser.navigate.to('about:blank') unless current_url == 'about:blank' end end def accept_unhandled_reset_alert @browser.switch_to.alert.accept sleep 0.25 # allow time for the modal to be handled rescue modal_error # The alert is now gone. # If navigation has not occurred attempt again and accept alert # since FF may have dismissed the alert at first attempt. navigate_with_accept('about:blank') if current_url != 'about:blank' end end require 'capybara/selenium/driver_specializations/chrome_driver' require 'capybara/selenium/driver_specializations/firefox_driver' require 'capybara/selenium/driver_specializations/internet_explorer_driver' require 'capybara/selenium/driver_specializations/safari_driver' require 'capybara/selenium/driver_specializations/edge_driver'
Ruby
{ "end_line": 258, "name": "open_new_window", "signature": "def open_new_window(kind = :tab)", "start_line": 247 }
{ "class_name": "Capybara::Selenium::Driver", "class_signature": "class Capybara::Selenium::Driver < < Capybara::Driver::Base", "module": "" }
quit
capybara/lib/capybara/selenium/driver.rb
def quit @browser&.quit rescue Selenium::WebDriver::Error::SessionNotCreatedError, Errno::ECONNREFUSED, Selenium::WebDriver::Error::InvalidSessionIdError # Browser must have already gone rescue Selenium::WebDriver::Error::UnknownError => e unless silenced_unknown_error_message?(e.message) # Most likely already gone # probably already gone but not sure - so warn warn "Ignoring Selenium UnknownError during driver quit: #{e.message}" end ensure @browser = nil end
# frozen_string_literal: true require 'uri' require 'English' class Capybara::Selenium::Driver < Capybara::Driver::Base include Capybara::Selenium::Find DEFAULT_OPTIONS = { browser: :firefox, clear_local_storage: nil, clear_session_storage: nil }.freeze SPECIAL_OPTIONS = %i[browser clear_local_storage clear_session_storage timeout native_displayed].freeze CAPS_VERSION = Gem::Requirement.new('< 4.8.0') attr_reader :app, :options class << self attr_reader :selenium_webdriver_version def load_selenium require 'selenium-webdriver' require 'capybara/selenium/patches/atoms' require 'capybara/selenium/patches/is_displayed' # Look up the version of `selenium-webdriver` to # see if it's a version we support. # # By default, we use Gem.loaded_specs to determine # the version number. However, in some cases, such # as when loading `selenium-webdriver` outside of # Rubygems, we fall back to referencing # Selenium::WebDriver::VERSION. Ideally we'd # use the constant in all cases, but earlier versions # of `selenium-webdriver` didn't provide the constant. @selenium_webdriver_version = if Gem.loaded_specs['selenium-webdriver'] Gem.loaded_specs['selenium-webdriver'].version else Gem::Version.new(Selenium::WebDriver::VERSION) end unless Gem::Requirement.new('>= 4.8').satisfied_by? @selenium_webdriver_version warn "Warning: You're using an unsupported version of selenium-webdriver, please upgrade to 4.8+." end @selenium_webdriver_version rescue LoadError => e raise e unless e.message.include?('selenium-webdriver') raise LoadError, "Capybara's selenium driver is unable to load `selenium-webdriver`, please install the gem and add `gem 'selenium-webdriver'` to your Gemfile if you are using bundler." end attr_reader :specializations def register_specialization(browser_name, specialization) @specializations ||= {} @specializations[browser_name] = specialization end end def browser unless @browser options[:http_client] ||= begin require 'capybara/selenium/patches/persistent_client' if options[:timeout] ::Capybara::Selenium::PersistentClient.new(read_timeout: options[:timeout]) else ::Capybara::Selenium::PersistentClient.new end end processed_options = options.except(*SPECIAL_OPTIONS) @browser = Selenium::WebDriver.for(options[:browser], processed_options) specialize_driver setup_exit_handler end @browser end def initialize(app, **options) super() self.class.load_selenium @app = app @browser = nil @exit_status = nil @frame_handles = Hash.new { |hash, handle| hash[handle] = [] } @options = DEFAULT_OPTIONS.merge(options) @node_class = ::Capybara::Selenium::Node end def visit(path) browser.navigate.to(path) end def refresh browser.navigate.refresh end def go_back browser.navigate.back end def go_forward browser.navigate.forward end def html browser.page_source rescue Selenium::WebDriver::Error::JavascriptError => e raise unless e.message.include?('documentElement is null') end def title browser.title end def current_url browser.current_url end def wait?; true; end def needs_server?; true; end def execute_script(script, *args) browser.execute_script(script, *native_args(args)) end def evaluate_script(script, *args) result = execute_script("return #{script}", *args) unwrap_script_result(result) end def evaluate_async_script(script, *args) browser.manage.timeouts.script_timeout = Capybara.default_max_wait_time result = browser.execute_async_script(script, *native_args(args)) unwrap_script_result(result) end def active_element build_node(native_active_element) end def send_keys(*args) # Should this call the specialized nodes rather than native??? native_active_element.send_keys(*args) end def save_screenshot(path, **options) browser.save_screenshot(path, **options) end def reset! # Use instance variable directly so we avoid starting the browser just to reset the session return unless @browser navigated = false timer = Capybara::Helpers.timer(expire_in: 10) begin # Only trigger a navigation if we haven't done it already, otherwise it # can trigger an endless series of unload modals reset_browser_state unless navigated navigated = true # Ensure the page is empty and trigger an UnhandledAlertError for any modals that appear during unload wait_for_empty_page(timer) rescue *unhandled_alert_errors # This error is thrown if an unhandled alert is on the page # Firefox appears to automatically dismiss this alert, chrome does not # We'll try to accept it accept_unhandled_reset_alert # try cleaning up the browser again retry end end def frame_obscured_at?(x:, y:) frame = @frame_handles[current_window_handle].last return false unless frame switch_to_frame(:parent) begin frame.base.obscured?(x: x, y: y) ensure switch_to_frame(frame) end end def switch_to_frame(frame) handles = @frame_handles[current_window_handle] case frame when :top handles.clear browser.switch_to.default_content when :parent handles.pop browser.switch_to.parent_frame else handles << frame browser.switch_to.frame(frame.native) end end def current_window_handle browser.window_handle end def window_size(handle) within_given_window(handle) do size = browser.manage.window.size [size.width, size.height] end end def resize_window_to(handle, width, height) within_given_window(handle) do browser.manage.window.resize_to(width, height) end end def maximize_window(handle) within_given_window(handle) do browser.manage.window.maximize end sleep 0.1 # work around for https://code.google.com/p/selenium/issues/detail?id=7405 end def fullscreen_window(handle) within_given_window(handle) do browser.manage.window.full_screen end end def close_window(handle) raise ArgumentError, 'Not allowed to close the primary window' if handle == window_handles.first within_given_window(handle) do browser.close end end def window_handles browser.window_handles end def open_new_window(kind = :tab) if browser.switch_to.respond_to?(:new_window) handle = current_window_handle browser.switch_to.new_window(kind) switch_to_window(handle) else browser.manage.new_window(kind) end rescue NoMethodError, Selenium::WebDriver::Error::WebDriverError # If not supported by the driver or browser default to using JS browser.execute_script('window.open();') end def switch_to_window(handle) browser.switch_to.window handle end def accept_modal(_type, **options) yield if block_given? modal = find_modal(**options) modal.send_keys options[:with] if options[:with] message = modal.text modal.accept message end def dismiss_modal(_type, **options) yield if block_given? modal = find_modal(**options) message = modal.text modal.dismiss message end def quit @browser&.quit rescue Selenium::WebDriver::Error::SessionNotCreatedError, Errno::ECONNREFUSED, Selenium::WebDriver::Error::InvalidSessionIdError # Browser must have already gone rescue Selenium::WebDriver::Error::UnknownError => e unless silenced_unknown_error_message?(e.message) # Most likely already gone # probably already gone but not sure - so warn warn "Ignoring Selenium UnknownError during driver quit: #{e.message}" end ensure @browser = nil end def invalid_element_errors @invalid_element_errors ||= [ ::Selenium::WebDriver::Error::StaleElementReferenceError, ::Selenium::WebDriver::Error::ElementNotInteractableError, ::Selenium::WebDriver::Error::InvalidSelectorError, # Work around chromedriver go_back/go_forward race condition ::Selenium::WebDriver::Error::ElementClickInterceptedError, ::Selenium::WebDriver::Error::NoSuchElementError, # IE ::Selenium::WebDriver::Error::InvalidArgumentError # IE ].tap do |errors| if defined?(::Selenium::WebDriver::Error::DetachedShadowRootError) errors.push(::Selenium::WebDriver::Error::DetachedShadowRootError) end end end def no_such_window_error Selenium::WebDriver::Error::NoSuchWindowError end private def native_args(args) args.map { |arg| arg.is_a?(Capybara::Selenium::Node) ? arg.native : arg } end def native_active_element browser.switch_to.active_element end def clear_browser_state delete_all_cookies clear_storage rescue *clear_browser_state_errors # delete_all_cookies fails when we've previously gone # to about:blank, so we rescue this error and do nothing # instead. end def clear_browser_state_errors @clear_browser_state_errors ||= [Selenium::WebDriver::Error::UnknownError] end def unhandled_alert_errors @unhandled_alert_errors ||= [Selenium::WebDriver::Error::UnexpectedAlertOpenError] end def delete_all_cookies @browser.manage.delete_all_cookies end def clear_storage clear_session_storage unless options[:clear_session_storage] == false clear_local_storage unless options[:clear_local_storage] == false rescue Selenium::WebDriver::Error::JavascriptError, Selenium::WebDriver::Error::WebDriverError # session/local storage may not be available if on non-http pages (e.g. about:blank) end def clear_session_storage if @browser.respond_to? :session_storage @browser.session_storage.clear else begin @browser&.execute_script('window.sessionStorage.clear()') rescue # rubocop:disable Style/RescueStandardError unless options[:clear_session_storage].nil? warn 'sessionStorage clear requested but is not supported by this driver' end end end end def clear_local_storage # selenium-webdriver 4.30.0 removed HTML5 storage accessors -- not really sure why # can we replicate this robustly via CDP? if @browser.respond_to? :local_storage @browser.local_storage.clear else begin @browser&.execute_script('window.localStorage.clear()') rescue # rubocop:disable Style/RescueStandardError unless options[:clear_local_storage].nil? warn 'localStorage clear requested but is not supported by this driver' end end end end def navigate_with_accept(url) @browser.navigate.to(url) sleep 0.1 # slight wait for alert @browser.switch_to.alert.accept rescue modal_error # alert now gone, should mean navigation happened end def modal_error Selenium::WebDriver::Error::NoSuchAlertError end def within_given_window(handle) original_handle = current_window_handle if handle == original_handle yield else switch_to_window(handle) result = yield switch_to_window(original_handle) result end end def find_modal(text: nil, **options) # Selenium has its own built in wait (2 seconds)for a modal to show up, so this wait is really the minimum time # Actual wait time may be longer than specified wait = Selenium::WebDriver::Wait.new( timeout: options.fetch(:wait, session_options.default_max_wait_time) || 0, ignore: modal_error ) begin wait.until do alert = @browser.switch_to.alert regexp = text.is_a?(Regexp) ? text : Regexp.new(Regexp.escape(text.to_s)) matched = alert.text.match?(regexp) unless matched raise Capybara::ModalNotFound, "Unable to find modal dialog with #{text} - found '#{alert.text}' instead." end alert end rescue *find_modal_errors raise Capybara::ModalNotFound, "Unable to find modal dialog#{" with #{text}" if text}" end end def find_modal_errors @find_modal_errors ||= [Selenium::WebDriver::Error::TimeoutError] end def silenced_unknown_error_message?(msg) silenced_unknown_error_messages.any? { |regex| msg.match? regex } end def silenced_unknown_error_messages [/Error communicating with the remote browser/] end def unwrap_script_result(arg) case arg when Array arg.map { |arr| unwrap_script_result(arr) } when Hash arg.transform_values! { |value| unwrap_script_result(value) } when Selenium::WebDriver::Element, Selenium::WebDriver::ShadowRoot build_node(arg) else arg end end def find_context browser end def build_node(native_node, initial_cache = {}) ::Capybara::Selenium::Node.new(self, native_node, initial_cache) end def bridge browser.send(:bridge) end def specialize_driver browser_type = browser.browser Capybara::Selenium::Driver.specializations.select { |k, _v| k === browser_type }.each_value do |specialization| # rubocop:disable Style/CaseEquality extend specialization end end def setup_exit_handler main = Process.pid at_exit do # Store the exit status of the test run since it goes away after calling the at_exit proc... @exit_status = $ERROR_INFO.status if $ERROR_INFO.is_a?(SystemExit) quit if Process.pid == main exit @exit_status if @exit_status # Force exit with stored status end end def reset_browser_state clear_browser_state @browser.navigate.to('about:blank') end def wait_for_empty_page(timer) until find_xpath('/html/body/*').empty? raise Capybara::ExpectationNotMet, 'Timed out waiting for Selenium session reset' if timer.expired? sleep 0.01 # It has been observed that it is possible that asynchronous JS code in # the application under test can navigate the browser away from about:blank # if the timing is just right. Ensure we are still at about:blank... @browser.navigate.to('about:blank') unless current_url == 'about:blank' end end def accept_unhandled_reset_alert @browser.switch_to.alert.accept sleep 0.25 # allow time for the modal to be handled rescue modal_error # The alert is now gone. # If navigation has not occurred attempt again and accept alert # since FF may have dismissed the alert at first attempt. navigate_with_accept('about:blank') if current_url != 'about:blank' end end require 'capybara/selenium/driver_specializations/chrome_driver' require 'capybara/selenium/driver_specializations/firefox_driver' require 'capybara/selenium/driver_specializations/internet_explorer_driver' require 'capybara/selenium/driver_specializations/safari_driver' require 'capybara/selenium/driver_specializations/edge_driver'
Ruby
{ "end_line": 295, "name": "quit", "signature": "def quit", "start_line": 283 }
{ "class_name": "Capybara::Selenium::Driver", "class_signature": "class Capybara::Selenium::Driver < < Capybara::Driver::Base", "module": "" }
invalid_element_errors
capybara/lib/capybara/selenium/driver.rb
def invalid_element_errors @invalid_element_errors ||= [ ::Selenium::WebDriver::Error::StaleElementReferenceError, ::Selenium::WebDriver::Error::ElementNotInteractableError, ::Selenium::WebDriver::Error::InvalidSelectorError, # Work around chromedriver go_back/go_forward race condition ::Selenium::WebDriver::Error::ElementClickInterceptedError, ::Selenium::WebDriver::Error::NoSuchElementError, # IE ::Selenium::WebDriver::Error::InvalidArgumentError # IE ].tap do |errors| if defined?(::Selenium::WebDriver::Error::DetachedShadowRootError) errors.push(::Selenium::WebDriver::Error::DetachedShadowRootError) end end end
# frozen_string_literal: true require 'uri' require 'English' class Capybara::Selenium::Driver < Capybara::Driver::Base include Capybara::Selenium::Find DEFAULT_OPTIONS = { browser: :firefox, clear_local_storage: nil, clear_session_storage: nil }.freeze SPECIAL_OPTIONS = %i[browser clear_local_storage clear_session_storage timeout native_displayed].freeze CAPS_VERSION = Gem::Requirement.new('< 4.8.0') attr_reader :app, :options class << self attr_reader :selenium_webdriver_version def load_selenium require 'selenium-webdriver' require 'capybara/selenium/patches/atoms' require 'capybara/selenium/patches/is_displayed' # Look up the version of `selenium-webdriver` to # see if it's a version we support. # # By default, we use Gem.loaded_specs to determine # the version number. However, in some cases, such # as when loading `selenium-webdriver` outside of # Rubygems, we fall back to referencing # Selenium::WebDriver::VERSION. Ideally we'd # use the constant in all cases, but earlier versions # of `selenium-webdriver` didn't provide the constant. @selenium_webdriver_version = if Gem.loaded_specs['selenium-webdriver'] Gem.loaded_specs['selenium-webdriver'].version else Gem::Version.new(Selenium::WebDriver::VERSION) end unless Gem::Requirement.new('>= 4.8').satisfied_by? @selenium_webdriver_version warn "Warning: You're using an unsupported version of selenium-webdriver, please upgrade to 4.8+." end @selenium_webdriver_version rescue LoadError => e raise e unless e.message.include?('selenium-webdriver') raise LoadError, "Capybara's selenium driver is unable to load `selenium-webdriver`, please install the gem and add `gem 'selenium-webdriver'` to your Gemfile if you are using bundler." end attr_reader :specializations def register_specialization(browser_name, specialization) @specializations ||= {} @specializations[browser_name] = specialization end end def browser unless @browser options[:http_client] ||= begin require 'capybara/selenium/patches/persistent_client' if options[:timeout] ::Capybara::Selenium::PersistentClient.new(read_timeout: options[:timeout]) else ::Capybara::Selenium::PersistentClient.new end end processed_options = options.except(*SPECIAL_OPTIONS) @browser = Selenium::WebDriver.for(options[:browser], processed_options) specialize_driver setup_exit_handler end @browser end def initialize(app, **options) super() self.class.load_selenium @app = app @browser = nil @exit_status = nil @frame_handles = Hash.new { |hash, handle| hash[handle] = [] } @options = DEFAULT_OPTIONS.merge(options) @node_class = ::Capybara::Selenium::Node end def visit(path) browser.navigate.to(path) end def refresh browser.navigate.refresh end def go_back browser.navigate.back end def go_forward browser.navigate.forward end def html browser.page_source rescue Selenium::WebDriver::Error::JavascriptError => e raise unless e.message.include?('documentElement is null') end def title browser.title end def current_url browser.current_url end def wait?; true; end def needs_server?; true; end def execute_script(script, *args) browser.execute_script(script, *native_args(args)) end def evaluate_script(script, *args) result = execute_script("return #{script}", *args) unwrap_script_result(result) end def evaluate_async_script(script, *args) browser.manage.timeouts.script_timeout = Capybara.default_max_wait_time result = browser.execute_async_script(script, *native_args(args)) unwrap_script_result(result) end def active_element build_node(native_active_element) end def send_keys(*args) # Should this call the specialized nodes rather than native??? native_active_element.send_keys(*args) end def save_screenshot(path, **options) browser.save_screenshot(path, **options) end def reset! # Use instance variable directly so we avoid starting the browser just to reset the session return unless @browser navigated = false timer = Capybara::Helpers.timer(expire_in: 10) begin # Only trigger a navigation if we haven't done it already, otherwise it # can trigger an endless series of unload modals reset_browser_state unless navigated navigated = true # Ensure the page is empty and trigger an UnhandledAlertError for any modals that appear during unload wait_for_empty_page(timer) rescue *unhandled_alert_errors # This error is thrown if an unhandled alert is on the page # Firefox appears to automatically dismiss this alert, chrome does not # We'll try to accept it accept_unhandled_reset_alert # try cleaning up the browser again retry end end def frame_obscured_at?(x:, y:) frame = @frame_handles[current_window_handle].last return false unless frame switch_to_frame(:parent) begin frame.base.obscured?(x: x, y: y) ensure switch_to_frame(frame) end end def switch_to_frame(frame) handles = @frame_handles[current_window_handle] case frame when :top handles.clear browser.switch_to.default_content when :parent handles.pop browser.switch_to.parent_frame else handles << frame browser.switch_to.frame(frame.native) end end def current_window_handle browser.window_handle end def window_size(handle) within_given_window(handle) do size = browser.manage.window.size [size.width, size.height] end end def resize_window_to(handle, width, height) within_given_window(handle) do browser.manage.window.resize_to(width, height) end end def maximize_window(handle) within_given_window(handle) do browser.manage.window.maximize end sleep 0.1 # work around for https://code.google.com/p/selenium/issues/detail?id=7405 end def fullscreen_window(handle) within_given_window(handle) do browser.manage.window.full_screen end end def close_window(handle) raise ArgumentError, 'Not allowed to close the primary window' if handle == window_handles.first within_given_window(handle) do browser.close end end def window_handles browser.window_handles end def open_new_window(kind = :tab) if browser.switch_to.respond_to?(:new_window) handle = current_window_handle browser.switch_to.new_window(kind) switch_to_window(handle) else browser.manage.new_window(kind) end rescue NoMethodError, Selenium::WebDriver::Error::WebDriverError # If not supported by the driver or browser default to using JS browser.execute_script('window.open();') end def switch_to_window(handle) browser.switch_to.window handle end def accept_modal(_type, **options) yield if block_given? modal = find_modal(**options) modal.send_keys options[:with] if options[:with] message = modal.text modal.accept message end def dismiss_modal(_type, **options) yield if block_given? modal = find_modal(**options) message = modal.text modal.dismiss message end def quit @browser&.quit rescue Selenium::WebDriver::Error::SessionNotCreatedError, Errno::ECONNREFUSED, Selenium::WebDriver::Error::InvalidSessionIdError # Browser must have already gone rescue Selenium::WebDriver::Error::UnknownError => e unless silenced_unknown_error_message?(e.message) # Most likely already gone # probably already gone but not sure - so warn warn "Ignoring Selenium UnknownError during driver quit: #{e.message}" end ensure @browser = nil end def invalid_element_errors @invalid_element_errors ||= [ ::Selenium::WebDriver::Error::StaleElementReferenceError, ::Selenium::WebDriver::Error::ElementNotInteractableError, ::Selenium::WebDriver::Error::InvalidSelectorError, # Work around chromedriver go_back/go_forward race condition ::Selenium::WebDriver::Error::ElementClickInterceptedError, ::Selenium::WebDriver::Error::NoSuchElementError, # IE ::Selenium::WebDriver::Error::InvalidArgumentError # IE ].tap do |errors| if defined?(::Selenium::WebDriver::Error::DetachedShadowRootError) errors.push(::Selenium::WebDriver::Error::DetachedShadowRootError) end end end def no_such_window_error Selenium::WebDriver::Error::NoSuchWindowError end private def native_args(args) args.map { |arg| arg.is_a?(Capybara::Selenium::Node) ? arg.native : arg } end def native_active_element browser.switch_to.active_element end def clear_browser_state delete_all_cookies clear_storage rescue *clear_browser_state_errors # delete_all_cookies fails when we've previously gone # to about:blank, so we rescue this error and do nothing # instead. end def clear_browser_state_errors @clear_browser_state_errors ||= [Selenium::WebDriver::Error::UnknownError] end def unhandled_alert_errors @unhandled_alert_errors ||= [Selenium::WebDriver::Error::UnexpectedAlertOpenError] end def delete_all_cookies @browser.manage.delete_all_cookies end def clear_storage clear_session_storage unless options[:clear_session_storage] == false clear_local_storage unless options[:clear_local_storage] == false rescue Selenium::WebDriver::Error::JavascriptError, Selenium::WebDriver::Error::WebDriverError # session/local storage may not be available if on non-http pages (e.g. about:blank) end def clear_session_storage if @browser.respond_to? :session_storage @browser.session_storage.clear else begin @browser&.execute_script('window.sessionStorage.clear()') rescue # rubocop:disable Style/RescueStandardError unless options[:clear_session_storage].nil? warn 'sessionStorage clear requested but is not supported by this driver' end end end end def clear_local_storage # selenium-webdriver 4.30.0 removed HTML5 storage accessors -- not really sure why # can we replicate this robustly via CDP? if @browser.respond_to? :local_storage @browser.local_storage.clear else begin @browser&.execute_script('window.localStorage.clear()') rescue # rubocop:disable Style/RescueStandardError unless options[:clear_local_storage].nil? warn 'localStorage clear requested but is not supported by this driver' end end end end def navigate_with_accept(url) @browser.navigate.to(url) sleep 0.1 # slight wait for alert @browser.switch_to.alert.accept rescue modal_error # alert now gone, should mean navigation happened end def modal_error Selenium::WebDriver::Error::NoSuchAlertError end def within_given_window(handle) original_handle = current_window_handle if handle == original_handle yield else switch_to_window(handle) result = yield switch_to_window(original_handle) result end end def find_modal(text: nil, **options) # Selenium has its own built in wait (2 seconds)for a modal to show up, so this wait is really the minimum time # Actual wait time may be longer than specified wait = Selenium::WebDriver::Wait.new( timeout: options.fetch(:wait, session_options.default_max_wait_time) || 0, ignore: modal_error ) begin wait.until do alert = @browser.switch_to.alert regexp = text.is_a?(Regexp) ? text : Regexp.new(Regexp.escape(text.to_s)) matched = alert.text.match?(regexp) unless matched raise Capybara::ModalNotFound, "Unable to find modal dialog with #{text} - found '#{alert.text}' instead." end alert end rescue *find_modal_errors raise Capybara::ModalNotFound, "Unable to find modal dialog#{" with #{text}" if text}" end end def find_modal_errors @find_modal_errors ||= [Selenium::WebDriver::Error::TimeoutError] end def silenced_unknown_error_message?(msg) silenced_unknown_error_messages.any? { |regex| msg.match? regex } end def silenced_unknown_error_messages [/Error communicating with the remote browser/] end def unwrap_script_result(arg) case arg when Array arg.map { |arr| unwrap_script_result(arr) } when Hash arg.transform_values! { |value| unwrap_script_result(value) } when Selenium::WebDriver::Element, Selenium::WebDriver::ShadowRoot build_node(arg) else arg end end def find_context browser end def build_node(native_node, initial_cache = {}) ::Capybara::Selenium::Node.new(self, native_node, initial_cache) end def bridge browser.send(:bridge) end def specialize_driver browser_type = browser.browser Capybara::Selenium::Driver.specializations.select { |k, _v| k === browser_type }.each_value do |specialization| # rubocop:disable Style/CaseEquality extend specialization end end def setup_exit_handler main = Process.pid at_exit do # Store the exit status of the test run since it goes away after calling the at_exit proc... @exit_status = $ERROR_INFO.status if $ERROR_INFO.is_a?(SystemExit) quit if Process.pid == main exit @exit_status if @exit_status # Force exit with stored status end end def reset_browser_state clear_browser_state @browser.navigate.to('about:blank') end def wait_for_empty_page(timer) until find_xpath('/html/body/*').empty? raise Capybara::ExpectationNotMet, 'Timed out waiting for Selenium session reset' if timer.expired? sleep 0.01 # It has been observed that it is possible that asynchronous JS code in # the application under test can navigate the browser away from about:blank # if the timing is just right. Ensure we are still at about:blank... @browser.navigate.to('about:blank') unless current_url == 'about:blank' end end def accept_unhandled_reset_alert @browser.switch_to.alert.accept sleep 0.25 # allow time for the modal to be handled rescue modal_error # The alert is now gone. # If navigation has not occurred attempt again and accept alert # since FF may have dismissed the alert at first attempt. navigate_with_accept('about:blank') if current_url != 'about:blank' end end require 'capybara/selenium/driver_specializations/chrome_driver' require 'capybara/selenium/driver_specializations/firefox_driver' require 'capybara/selenium/driver_specializations/internet_explorer_driver' require 'capybara/selenium/driver_specializations/safari_driver' require 'capybara/selenium/driver_specializations/edge_driver'
Ruby
{ "end_line": 311, "name": "invalid_element_errors", "signature": "def invalid_element_errors", "start_line": 297 }
{ "class_name": "Capybara::Selenium::Driver", "class_signature": "class Capybara::Selenium::Driver < < Capybara::Driver::Base", "module": "" }
clear_session_storage
capybara/lib/capybara/selenium/driver.rb
def clear_session_storage if @browser.respond_to? :session_storage @browser.session_storage.clear else begin @browser&.execute_script('window.sessionStorage.clear()') rescue # rubocop:disable Style/RescueStandardError unless options[:clear_session_storage].nil? warn 'sessionStorage clear requested but is not supported by this driver' end end end end
# frozen_string_literal: true require 'uri' require 'English' class Capybara::Selenium::Driver < Capybara::Driver::Base include Capybara::Selenium::Find DEFAULT_OPTIONS = { browser: :firefox, clear_local_storage: nil, clear_session_storage: nil }.freeze SPECIAL_OPTIONS = %i[browser clear_local_storage clear_session_storage timeout native_displayed].freeze CAPS_VERSION = Gem::Requirement.new('< 4.8.0') attr_reader :app, :options class << self attr_reader :selenium_webdriver_version def load_selenium require 'selenium-webdriver' require 'capybara/selenium/patches/atoms' require 'capybara/selenium/patches/is_displayed' # Look up the version of `selenium-webdriver` to # see if it's a version we support. # # By default, we use Gem.loaded_specs to determine # the version number. However, in some cases, such # as when loading `selenium-webdriver` outside of # Rubygems, we fall back to referencing # Selenium::WebDriver::VERSION. Ideally we'd # use the constant in all cases, but earlier versions # of `selenium-webdriver` didn't provide the constant. @selenium_webdriver_version = if Gem.loaded_specs['selenium-webdriver'] Gem.loaded_specs['selenium-webdriver'].version else Gem::Version.new(Selenium::WebDriver::VERSION) end unless Gem::Requirement.new('>= 4.8').satisfied_by? @selenium_webdriver_version warn "Warning: You're using an unsupported version of selenium-webdriver, please upgrade to 4.8+." end @selenium_webdriver_version rescue LoadError => e raise e unless e.message.include?('selenium-webdriver') raise LoadError, "Capybara's selenium driver is unable to load `selenium-webdriver`, please install the gem and add `gem 'selenium-webdriver'` to your Gemfile if you are using bundler." end attr_reader :specializations def register_specialization(browser_name, specialization) @specializations ||= {} @specializations[browser_name] = specialization end end def browser unless @browser options[:http_client] ||= begin require 'capybara/selenium/patches/persistent_client' if options[:timeout] ::Capybara::Selenium::PersistentClient.new(read_timeout: options[:timeout]) else ::Capybara::Selenium::PersistentClient.new end end processed_options = options.except(*SPECIAL_OPTIONS) @browser = Selenium::WebDriver.for(options[:browser], processed_options) specialize_driver setup_exit_handler end @browser end def initialize(app, **options) super() self.class.load_selenium @app = app @browser = nil @exit_status = nil @frame_handles = Hash.new { |hash, handle| hash[handle] = [] } @options = DEFAULT_OPTIONS.merge(options) @node_class = ::Capybara::Selenium::Node end def visit(path) browser.navigate.to(path) end def refresh browser.navigate.refresh end def go_back browser.navigate.back end def go_forward browser.navigate.forward end def html browser.page_source rescue Selenium::WebDriver::Error::JavascriptError => e raise unless e.message.include?('documentElement is null') end def title browser.title end def current_url browser.current_url end def wait?; true; end def needs_server?; true; end def execute_script(script, *args) browser.execute_script(script, *native_args(args)) end def evaluate_script(script, *args) result = execute_script("return #{script}", *args) unwrap_script_result(result) end def evaluate_async_script(script, *args) browser.manage.timeouts.script_timeout = Capybara.default_max_wait_time result = browser.execute_async_script(script, *native_args(args)) unwrap_script_result(result) end def active_element build_node(native_active_element) end def send_keys(*args) # Should this call the specialized nodes rather than native??? native_active_element.send_keys(*args) end def save_screenshot(path, **options) browser.save_screenshot(path, **options) end def reset! # Use instance variable directly so we avoid starting the browser just to reset the session return unless @browser navigated = false timer = Capybara::Helpers.timer(expire_in: 10) begin # Only trigger a navigation if we haven't done it already, otherwise it # can trigger an endless series of unload modals reset_browser_state unless navigated navigated = true # Ensure the page is empty and trigger an UnhandledAlertError for any modals that appear during unload wait_for_empty_page(timer) rescue *unhandled_alert_errors # This error is thrown if an unhandled alert is on the page # Firefox appears to automatically dismiss this alert, chrome does not # We'll try to accept it accept_unhandled_reset_alert # try cleaning up the browser again retry end end def frame_obscured_at?(x:, y:) frame = @frame_handles[current_window_handle].last return false unless frame switch_to_frame(:parent) begin frame.base.obscured?(x: x, y: y) ensure switch_to_frame(frame) end end def switch_to_frame(frame) handles = @frame_handles[current_window_handle] case frame when :top handles.clear browser.switch_to.default_content when :parent handles.pop browser.switch_to.parent_frame else handles << frame browser.switch_to.frame(frame.native) end end def current_window_handle browser.window_handle end def window_size(handle) within_given_window(handle) do size = browser.manage.window.size [size.width, size.height] end end def resize_window_to(handle, width, height) within_given_window(handle) do browser.manage.window.resize_to(width, height) end end def maximize_window(handle) within_given_window(handle) do browser.manage.window.maximize end sleep 0.1 # work around for https://code.google.com/p/selenium/issues/detail?id=7405 end def fullscreen_window(handle) within_given_window(handle) do browser.manage.window.full_screen end end def close_window(handle) raise ArgumentError, 'Not allowed to close the primary window' if handle == window_handles.first within_given_window(handle) do browser.close end end def window_handles browser.window_handles end def open_new_window(kind = :tab) if browser.switch_to.respond_to?(:new_window) handle = current_window_handle browser.switch_to.new_window(kind) switch_to_window(handle) else browser.manage.new_window(kind) end rescue NoMethodError, Selenium::WebDriver::Error::WebDriverError # If not supported by the driver or browser default to using JS browser.execute_script('window.open();') end def switch_to_window(handle) browser.switch_to.window handle end def accept_modal(_type, **options) yield if block_given? modal = find_modal(**options) modal.send_keys options[:with] if options[:with] message = modal.text modal.accept message end def dismiss_modal(_type, **options) yield if block_given? modal = find_modal(**options) message = modal.text modal.dismiss message end def quit @browser&.quit rescue Selenium::WebDriver::Error::SessionNotCreatedError, Errno::ECONNREFUSED, Selenium::WebDriver::Error::InvalidSessionIdError # Browser must have already gone rescue Selenium::WebDriver::Error::UnknownError => e unless silenced_unknown_error_message?(e.message) # Most likely already gone # probably already gone but not sure - so warn warn "Ignoring Selenium UnknownError during driver quit: #{e.message}" end ensure @browser = nil end def invalid_element_errors @invalid_element_errors ||= [ ::Selenium::WebDriver::Error::StaleElementReferenceError, ::Selenium::WebDriver::Error::ElementNotInteractableError, ::Selenium::WebDriver::Error::InvalidSelectorError, # Work around chromedriver go_back/go_forward race condition ::Selenium::WebDriver::Error::ElementClickInterceptedError, ::Selenium::WebDriver::Error::NoSuchElementError, # IE ::Selenium::WebDriver::Error::InvalidArgumentError # IE ].tap do |errors| if defined?(::Selenium::WebDriver::Error::DetachedShadowRootError) errors.push(::Selenium::WebDriver::Error::DetachedShadowRootError) end end end def no_such_window_error Selenium::WebDriver::Error::NoSuchWindowError end private def native_args(args) args.map { |arg| arg.is_a?(Capybara::Selenium::Node) ? arg.native : arg } end def native_active_element browser.switch_to.active_element end def clear_browser_state delete_all_cookies clear_storage rescue *clear_browser_state_errors # delete_all_cookies fails when we've previously gone # to about:blank, so we rescue this error and do nothing # instead. end def clear_browser_state_errors @clear_browser_state_errors ||= [Selenium::WebDriver::Error::UnknownError] end def unhandled_alert_errors @unhandled_alert_errors ||= [Selenium::WebDriver::Error::UnexpectedAlertOpenError] end def delete_all_cookies @browser.manage.delete_all_cookies end def clear_storage clear_session_storage unless options[:clear_session_storage] == false clear_local_storage unless options[:clear_local_storage] == false rescue Selenium::WebDriver::Error::JavascriptError, Selenium::WebDriver::Error::WebDriverError # session/local storage may not be available if on non-http pages (e.g. about:blank) end def clear_session_storage if @browser.respond_to? :session_storage @browser.session_storage.clear else begin @browser&.execute_script('window.sessionStorage.clear()') rescue # rubocop:disable Style/RescueStandardError unless options[:clear_session_storage].nil? warn 'sessionStorage clear requested but is not supported by this driver' end end end end def clear_local_storage # selenium-webdriver 4.30.0 removed HTML5 storage accessors -- not really sure why # can we replicate this robustly via CDP? if @browser.respond_to? :local_storage @browser.local_storage.clear else begin @browser&.execute_script('window.localStorage.clear()') rescue # rubocop:disable Style/RescueStandardError unless options[:clear_local_storage].nil? warn 'localStorage clear requested but is not supported by this driver' end end end end def navigate_with_accept(url) @browser.navigate.to(url) sleep 0.1 # slight wait for alert @browser.switch_to.alert.accept rescue modal_error # alert now gone, should mean navigation happened end def modal_error Selenium::WebDriver::Error::NoSuchAlertError end def within_given_window(handle) original_handle = current_window_handle if handle == original_handle yield else switch_to_window(handle) result = yield switch_to_window(original_handle) result end end def find_modal(text: nil, **options) # Selenium has its own built in wait (2 seconds)for a modal to show up, so this wait is really the minimum time # Actual wait time may be longer than specified wait = Selenium::WebDriver::Wait.new( timeout: options.fetch(:wait, session_options.default_max_wait_time) || 0, ignore: modal_error ) begin wait.until do alert = @browser.switch_to.alert regexp = text.is_a?(Regexp) ? text : Regexp.new(Regexp.escape(text.to_s)) matched = alert.text.match?(regexp) unless matched raise Capybara::ModalNotFound, "Unable to find modal dialog with #{text} - found '#{alert.text}' instead." end alert end rescue *find_modal_errors raise Capybara::ModalNotFound, "Unable to find modal dialog#{" with #{text}" if text}" end end def find_modal_errors @find_modal_errors ||= [Selenium::WebDriver::Error::TimeoutError] end def silenced_unknown_error_message?(msg) silenced_unknown_error_messages.any? { |regex| msg.match? regex } end def silenced_unknown_error_messages [/Error communicating with the remote browser/] end def unwrap_script_result(arg) case arg when Array arg.map { |arr| unwrap_script_result(arr) } when Hash arg.transform_values! { |value| unwrap_script_result(value) } when Selenium::WebDriver::Element, Selenium::WebDriver::ShadowRoot build_node(arg) else arg end end def find_context browser end def build_node(native_node, initial_cache = {}) ::Capybara::Selenium::Node.new(self, native_node, initial_cache) end def bridge browser.send(:bridge) end def specialize_driver browser_type = browser.browser Capybara::Selenium::Driver.specializations.select { |k, _v| k === browser_type }.each_value do |specialization| # rubocop:disable Style/CaseEquality extend specialization end end def setup_exit_handler main = Process.pid at_exit do # Store the exit status of the test run since it goes away after calling the at_exit proc... @exit_status = $ERROR_INFO.status if $ERROR_INFO.is_a?(SystemExit) quit if Process.pid == main exit @exit_status if @exit_status # Force exit with stored status end end def reset_browser_state clear_browser_state @browser.navigate.to('about:blank') end def wait_for_empty_page(timer) until find_xpath('/html/body/*').empty? raise Capybara::ExpectationNotMet, 'Timed out waiting for Selenium session reset' if timer.expired? sleep 0.01 # It has been observed that it is possible that asynchronous JS code in # the application under test can navigate the browser away from about:blank # if the timing is just right. Ensure we are still at about:blank... @browser.navigate.to('about:blank') unless current_url == 'about:blank' end end def accept_unhandled_reset_alert @browser.switch_to.alert.accept sleep 0.25 # allow time for the modal to be handled rescue modal_error # The alert is now gone. # If navigation has not occurred attempt again and accept alert # since FF may have dismissed the alert at first attempt. navigate_with_accept('about:blank') if current_url != 'about:blank' end end require 'capybara/selenium/driver_specializations/chrome_driver' require 'capybara/selenium/driver_specializations/firefox_driver' require 'capybara/selenium/driver_specializations/internet_explorer_driver' require 'capybara/selenium/driver_specializations/safari_driver' require 'capybara/selenium/driver_specializations/edge_driver'
Ruby
{ "end_line": 367, "name": "clear_session_storage", "signature": "def clear_session_storage", "start_line": 355 }
{ "class_name": "Capybara::Selenium::Driver", "class_signature": "class Capybara::Selenium::Driver < < Capybara::Driver::Base", "module": "" }
clear_local_storage
capybara/lib/capybara/selenium/driver.rb
def clear_local_storage # selenium-webdriver 4.30.0 removed HTML5 storage accessors -- not really sure why # can we replicate this robustly via CDP? if @browser.respond_to? :local_storage @browser.local_storage.clear else begin @browser&.execute_script('window.localStorage.clear()') rescue # rubocop:disable Style/RescueStandardError unless options[:clear_local_storage].nil? warn 'localStorage clear requested but is not supported by this driver' end end end end
# frozen_string_literal: true require 'uri' require 'English' class Capybara::Selenium::Driver < Capybara::Driver::Base include Capybara::Selenium::Find DEFAULT_OPTIONS = { browser: :firefox, clear_local_storage: nil, clear_session_storage: nil }.freeze SPECIAL_OPTIONS = %i[browser clear_local_storage clear_session_storage timeout native_displayed].freeze CAPS_VERSION = Gem::Requirement.new('< 4.8.0') attr_reader :app, :options class << self attr_reader :selenium_webdriver_version def load_selenium require 'selenium-webdriver' require 'capybara/selenium/patches/atoms' require 'capybara/selenium/patches/is_displayed' # Look up the version of `selenium-webdriver` to # see if it's a version we support. # # By default, we use Gem.loaded_specs to determine # the version number. However, in some cases, such # as when loading `selenium-webdriver` outside of # Rubygems, we fall back to referencing # Selenium::WebDriver::VERSION. Ideally we'd # use the constant in all cases, but earlier versions # of `selenium-webdriver` didn't provide the constant. @selenium_webdriver_version = if Gem.loaded_specs['selenium-webdriver'] Gem.loaded_specs['selenium-webdriver'].version else Gem::Version.new(Selenium::WebDriver::VERSION) end unless Gem::Requirement.new('>= 4.8').satisfied_by? @selenium_webdriver_version warn "Warning: You're using an unsupported version of selenium-webdriver, please upgrade to 4.8+." end @selenium_webdriver_version rescue LoadError => e raise e unless e.message.include?('selenium-webdriver') raise LoadError, "Capybara's selenium driver is unable to load `selenium-webdriver`, please install the gem and add `gem 'selenium-webdriver'` to your Gemfile if you are using bundler." end attr_reader :specializations def register_specialization(browser_name, specialization) @specializations ||= {} @specializations[browser_name] = specialization end end def browser unless @browser options[:http_client] ||= begin require 'capybara/selenium/patches/persistent_client' if options[:timeout] ::Capybara::Selenium::PersistentClient.new(read_timeout: options[:timeout]) else ::Capybara::Selenium::PersistentClient.new end end processed_options = options.except(*SPECIAL_OPTIONS) @browser = Selenium::WebDriver.for(options[:browser], processed_options) specialize_driver setup_exit_handler end @browser end def initialize(app, **options) super() self.class.load_selenium @app = app @browser = nil @exit_status = nil @frame_handles = Hash.new { |hash, handle| hash[handle] = [] } @options = DEFAULT_OPTIONS.merge(options) @node_class = ::Capybara::Selenium::Node end def visit(path) browser.navigate.to(path) end def refresh browser.navigate.refresh end def go_back browser.navigate.back end def go_forward browser.navigate.forward end def html browser.page_source rescue Selenium::WebDriver::Error::JavascriptError => e raise unless e.message.include?('documentElement is null') end def title browser.title end def current_url browser.current_url end def wait?; true; end def needs_server?; true; end def execute_script(script, *args) browser.execute_script(script, *native_args(args)) end def evaluate_script(script, *args) result = execute_script("return #{script}", *args) unwrap_script_result(result) end def evaluate_async_script(script, *args) browser.manage.timeouts.script_timeout = Capybara.default_max_wait_time result = browser.execute_async_script(script, *native_args(args)) unwrap_script_result(result) end def active_element build_node(native_active_element) end def send_keys(*args) # Should this call the specialized nodes rather than native??? native_active_element.send_keys(*args) end def save_screenshot(path, **options) browser.save_screenshot(path, **options) end def reset! # Use instance variable directly so we avoid starting the browser just to reset the session return unless @browser navigated = false timer = Capybara::Helpers.timer(expire_in: 10) begin # Only trigger a navigation if we haven't done it already, otherwise it # can trigger an endless series of unload modals reset_browser_state unless navigated navigated = true # Ensure the page is empty and trigger an UnhandledAlertError for any modals that appear during unload wait_for_empty_page(timer) rescue *unhandled_alert_errors # This error is thrown if an unhandled alert is on the page # Firefox appears to automatically dismiss this alert, chrome does not # We'll try to accept it accept_unhandled_reset_alert # try cleaning up the browser again retry end end def frame_obscured_at?(x:, y:) frame = @frame_handles[current_window_handle].last return false unless frame switch_to_frame(:parent) begin frame.base.obscured?(x: x, y: y) ensure switch_to_frame(frame) end end def switch_to_frame(frame) handles = @frame_handles[current_window_handle] case frame when :top handles.clear browser.switch_to.default_content when :parent handles.pop browser.switch_to.parent_frame else handles << frame browser.switch_to.frame(frame.native) end end def current_window_handle browser.window_handle end def window_size(handle) within_given_window(handle) do size = browser.manage.window.size [size.width, size.height] end end def resize_window_to(handle, width, height) within_given_window(handle) do browser.manage.window.resize_to(width, height) end end def maximize_window(handle) within_given_window(handle) do browser.manage.window.maximize end sleep 0.1 # work around for https://code.google.com/p/selenium/issues/detail?id=7405 end def fullscreen_window(handle) within_given_window(handle) do browser.manage.window.full_screen end end def close_window(handle) raise ArgumentError, 'Not allowed to close the primary window' if handle == window_handles.first within_given_window(handle) do browser.close end end def window_handles browser.window_handles end def open_new_window(kind = :tab) if browser.switch_to.respond_to?(:new_window) handle = current_window_handle browser.switch_to.new_window(kind) switch_to_window(handle) else browser.manage.new_window(kind) end rescue NoMethodError, Selenium::WebDriver::Error::WebDriverError # If not supported by the driver or browser default to using JS browser.execute_script('window.open();') end def switch_to_window(handle) browser.switch_to.window handle end def accept_modal(_type, **options) yield if block_given? modal = find_modal(**options) modal.send_keys options[:with] if options[:with] message = modal.text modal.accept message end def dismiss_modal(_type, **options) yield if block_given? modal = find_modal(**options) message = modal.text modal.dismiss message end def quit @browser&.quit rescue Selenium::WebDriver::Error::SessionNotCreatedError, Errno::ECONNREFUSED, Selenium::WebDriver::Error::InvalidSessionIdError # Browser must have already gone rescue Selenium::WebDriver::Error::UnknownError => e unless silenced_unknown_error_message?(e.message) # Most likely already gone # probably already gone but not sure - so warn warn "Ignoring Selenium UnknownError during driver quit: #{e.message}" end ensure @browser = nil end def invalid_element_errors @invalid_element_errors ||= [ ::Selenium::WebDriver::Error::StaleElementReferenceError, ::Selenium::WebDriver::Error::ElementNotInteractableError, ::Selenium::WebDriver::Error::InvalidSelectorError, # Work around chromedriver go_back/go_forward race condition ::Selenium::WebDriver::Error::ElementClickInterceptedError, ::Selenium::WebDriver::Error::NoSuchElementError, # IE ::Selenium::WebDriver::Error::InvalidArgumentError # IE ].tap do |errors| if defined?(::Selenium::WebDriver::Error::DetachedShadowRootError) errors.push(::Selenium::WebDriver::Error::DetachedShadowRootError) end end end def no_such_window_error Selenium::WebDriver::Error::NoSuchWindowError end private def native_args(args) args.map { |arg| arg.is_a?(Capybara::Selenium::Node) ? arg.native : arg } end def native_active_element browser.switch_to.active_element end def clear_browser_state delete_all_cookies clear_storage rescue *clear_browser_state_errors # delete_all_cookies fails when we've previously gone # to about:blank, so we rescue this error and do nothing # instead. end def clear_browser_state_errors @clear_browser_state_errors ||= [Selenium::WebDriver::Error::UnknownError] end def unhandled_alert_errors @unhandled_alert_errors ||= [Selenium::WebDriver::Error::UnexpectedAlertOpenError] end def delete_all_cookies @browser.manage.delete_all_cookies end def clear_storage clear_session_storage unless options[:clear_session_storage] == false clear_local_storage unless options[:clear_local_storage] == false rescue Selenium::WebDriver::Error::JavascriptError, Selenium::WebDriver::Error::WebDriverError # session/local storage may not be available if on non-http pages (e.g. about:blank) end def clear_session_storage if @browser.respond_to? :session_storage @browser.session_storage.clear else begin @browser&.execute_script('window.sessionStorage.clear()') rescue # rubocop:disable Style/RescueStandardError unless options[:clear_session_storage].nil? warn 'sessionStorage clear requested but is not supported by this driver' end end end end def clear_local_storage # selenium-webdriver 4.30.0 removed HTML5 storage accessors -- not really sure why # can we replicate this robustly via CDP? if @browser.respond_to? :local_storage @browser.local_storage.clear else begin @browser&.execute_script('window.localStorage.clear()') rescue # rubocop:disable Style/RescueStandardError unless options[:clear_local_storage].nil? warn 'localStorage clear requested but is not supported by this driver' end end end end def navigate_with_accept(url) @browser.navigate.to(url) sleep 0.1 # slight wait for alert @browser.switch_to.alert.accept rescue modal_error # alert now gone, should mean navigation happened end def modal_error Selenium::WebDriver::Error::NoSuchAlertError end def within_given_window(handle) original_handle = current_window_handle if handle == original_handle yield else switch_to_window(handle) result = yield switch_to_window(original_handle) result end end def find_modal(text: nil, **options) # Selenium has its own built in wait (2 seconds)for a modal to show up, so this wait is really the minimum time # Actual wait time may be longer than specified wait = Selenium::WebDriver::Wait.new( timeout: options.fetch(:wait, session_options.default_max_wait_time) || 0, ignore: modal_error ) begin wait.until do alert = @browser.switch_to.alert regexp = text.is_a?(Regexp) ? text : Regexp.new(Regexp.escape(text.to_s)) matched = alert.text.match?(regexp) unless matched raise Capybara::ModalNotFound, "Unable to find modal dialog with #{text} - found '#{alert.text}' instead." end alert end rescue *find_modal_errors raise Capybara::ModalNotFound, "Unable to find modal dialog#{" with #{text}" if text}" end end def find_modal_errors @find_modal_errors ||= [Selenium::WebDriver::Error::TimeoutError] end def silenced_unknown_error_message?(msg) silenced_unknown_error_messages.any? { |regex| msg.match? regex } end def silenced_unknown_error_messages [/Error communicating with the remote browser/] end def unwrap_script_result(arg) case arg when Array arg.map { |arr| unwrap_script_result(arr) } when Hash arg.transform_values! { |value| unwrap_script_result(value) } when Selenium::WebDriver::Element, Selenium::WebDriver::ShadowRoot build_node(arg) else arg end end def find_context browser end def build_node(native_node, initial_cache = {}) ::Capybara::Selenium::Node.new(self, native_node, initial_cache) end def bridge browser.send(:bridge) end def specialize_driver browser_type = browser.browser Capybara::Selenium::Driver.specializations.select { |k, _v| k === browser_type }.each_value do |specialization| # rubocop:disable Style/CaseEquality extend specialization end end def setup_exit_handler main = Process.pid at_exit do # Store the exit status of the test run since it goes away after calling the at_exit proc... @exit_status = $ERROR_INFO.status if $ERROR_INFO.is_a?(SystemExit) quit if Process.pid == main exit @exit_status if @exit_status # Force exit with stored status end end def reset_browser_state clear_browser_state @browser.navigate.to('about:blank') end def wait_for_empty_page(timer) until find_xpath('/html/body/*').empty? raise Capybara::ExpectationNotMet, 'Timed out waiting for Selenium session reset' if timer.expired? sleep 0.01 # It has been observed that it is possible that asynchronous JS code in # the application under test can navigate the browser away from about:blank # if the timing is just right. Ensure we are still at about:blank... @browser.navigate.to('about:blank') unless current_url == 'about:blank' end end def accept_unhandled_reset_alert @browser.switch_to.alert.accept sleep 0.25 # allow time for the modal to be handled rescue modal_error # The alert is now gone. # If navigation has not occurred attempt again and accept alert # since FF may have dismissed the alert at first attempt. navigate_with_accept('about:blank') if current_url != 'about:blank' end end require 'capybara/selenium/driver_specializations/chrome_driver' require 'capybara/selenium/driver_specializations/firefox_driver' require 'capybara/selenium/driver_specializations/internet_explorer_driver' require 'capybara/selenium/driver_specializations/safari_driver' require 'capybara/selenium/driver_specializations/edge_driver'
Ruby
{ "end_line": 383, "name": "clear_local_storage", "signature": "def clear_local_storage", "start_line": 369 }
{ "class_name": "Capybara::Selenium::Driver", "class_signature": "class Capybara::Selenium::Driver < < Capybara::Driver::Base", "module": "" }
within_given_window
capybara/lib/capybara/selenium/driver.rb
def within_given_window(handle) original_handle = current_window_handle if handle == original_handle yield else switch_to_window(handle) result = yield switch_to_window(original_handle) result end end
# frozen_string_literal: true require 'uri' require 'English' class Capybara::Selenium::Driver < Capybara::Driver::Base include Capybara::Selenium::Find DEFAULT_OPTIONS = { browser: :firefox, clear_local_storage: nil, clear_session_storage: nil }.freeze SPECIAL_OPTIONS = %i[browser clear_local_storage clear_session_storage timeout native_displayed].freeze CAPS_VERSION = Gem::Requirement.new('< 4.8.0') attr_reader :app, :options class << self attr_reader :selenium_webdriver_version def load_selenium require 'selenium-webdriver' require 'capybara/selenium/patches/atoms' require 'capybara/selenium/patches/is_displayed' # Look up the version of `selenium-webdriver` to # see if it's a version we support. # # By default, we use Gem.loaded_specs to determine # the version number. However, in some cases, such # as when loading `selenium-webdriver` outside of # Rubygems, we fall back to referencing # Selenium::WebDriver::VERSION. Ideally we'd # use the constant in all cases, but earlier versions # of `selenium-webdriver` didn't provide the constant. @selenium_webdriver_version = if Gem.loaded_specs['selenium-webdriver'] Gem.loaded_specs['selenium-webdriver'].version else Gem::Version.new(Selenium::WebDriver::VERSION) end unless Gem::Requirement.new('>= 4.8').satisfied_by? @selenium_webdriver_version warn "Warning: You're using an unsupported version of selenium-webdriver, please upgrade to 4.8+." end @selenium_webdriver_version rescue LoadError => e raise e unless e.message.include?('selenium-webdriver') raise LoadError, "Capybara's selenium driver is unable to load `selenium-webdriver`, please install the gem and add `gem 'selenium-webdriver'` to your Gemfile if you are using bundler." end attr_reader :specializations def register_specialization(browser_name, specialization) @specializations ||= {} @specializations[browser_name] = specialization end end def browser unless @browser options[:http_client] ||= begin require 'capybara/selenium/patches/persistent_client' if options[:timeout] ::Capybara::Selenium::PersistentClient.new(read_timeout: options[:timeout]) else ::Capybara::Selenium::PersistentClient.new end end processed_options = options.except(*SPECIAL_OPTIONS) @browser = Selenium::WebDriver.for(options[:browser], processed_options) specialize_driver setup_exit_handler end @browser end def initialize(app, **options) super() self.class.load_selenium @app = app @browser = nil @exit_status = nil @frame_handles = Hash.new { |hash, handle| hash[handle] = [] } @options = DEFAULT_OPTIONS.merge(options) @node_class = ::Capybara::Selenium::Node end def visit(path) browser.navigate.to(path) end def refresh browser.navigate.refresh end def go_back browser.navigate.back end def go_forward browser.navigate.forward end def html browser.page_source rescue Selenium::WebDriver::Error::JavascriptError => e raise unless e.message.include?('documentElement is null') end def title browser.title end def current_url browser.current_url end def wait?; true; end def needs_server?; true; end def execute_script(script, *args) browser.execute_script(script, *native_args(args)) end def evaluate_script(script, *args) result = execute_script("return #{script}", *args) unwrap_script_result(result) end def evaluate_async_script(script, *args) browser.manage.timeouts.script_timeout = Capybara.default_max_wait_time result = browser.execute_async_script(script, *native_args(args)) unwrap_script_result(result) end def active_element build_node(native_active_element) end def send_keys(*args) # Should this call the specialized nodes rather than native??? native_active_element.send_keys(*args) end def save_screenshot(path, **options) browser.save_screenshot(path, **options) end def reset! # Use instance variable directly so we avoid starting the browser just to reset the session return unless @browser navigated = false timer = Capybara::Helpers.timer(expire_in: 10) begin # Only trigger a navigation if we haven't done it already, otherwise it # can trigger an endless series of unload modals reset_browser_state unless navigated navigated = true # Ensure the page is empty and trigger an UnhandledAlertError for any modals that appear during unload wait_for_empty_page(timer) rescue *unhandled_alert_errors # This error is thrown if an unhandled alert is on the page # Firefox appears to automatically dismiss this alert, chrome does not # We'll try to accept it accept_unhandled_reset_alert # try cleaning up the browser again retry end end def frame_obscured_at?(x:, y:) frame = @frame_handles[current_window_handle].last return false unless frame switch_to_frame(:parent) begin frame.base.obscured?(x: x, y: y) ensure switch_to_frame(frame) end end def switch_to_frame(frame) handles = @frame_handles[current_window_handle] case frame when :top handles.clear browser.switch_to.default_content when :parent handles.pop browser.switch_to.parent_frame else handles << frame browser.switch_to.frame(frame.native) end end def current_window_handle browser.window_handle end def window_size(handle) within_given_window(handle) do size = browser.manage.window.size [size.width, size.height] end end def resize_window_to(handle, width, height) within_given_window(handle) do browser.manage.window.resize_to(width, height) end end def maximize_window(handle) within_given_window(handle) do browser.manage.window.maximize end sleep 0.1 # work around for https://code.google.com/p/selenium/issues/detail?id=7405 end def fullscreen_window(handle) within_given_window(handle) do browser.manage.window.full_screen end end def close_window(handle) raise ArgumentError, 'Not allowed to close the primary window' if handle == window_handles.first within_given_window(handle) do browser.close end end def window_handles browser.window_handles end def open_new_window(kind = :tab) if browser.switch_to.respond_to?(:new_window) handle = current_window_handle browser.switch_to.new_window(kind) switch_to_window(handle) else browser.manage.new_window(kind) end rescue NoMethodError, Selenium::WebDriver::Error::WebDriverError # If not supported by the driver or browser default to using JS browser.execute_script('window.open();') end def switch_to_window(handle) browser.switch_to.window handle end def accept_modal(_type, **options) yield if block_given? modal = find_modal(**options) modal.send_keys options[:with] if options[:with] message = modal.text modal.accept message end def dismiss_modal(_type, **options) yield if block_given? modal = find_modal(**options) message = modal.text modal.dismiss message end def quit @browser&.quit rescue Selenium::WebDriver::Error::SessionNotCreatedError, Errno::ECONNREFUSED, Selenium::WebDriver::Error::InvalidSessionIdError # Browser must have already gone rescue Selenium::WebDriver::Error::UnknownError => e unless silenced_unknown_error_message?(e.message) # Most likely already gone # probably already gone but not sure - so warn warn "Ignoring Selenium UnknownError during driver quit: #{e.message}" end ensure @browser = nil end def invalid_element_errors @invalid_element_errors ||= [ ::Selenium::WebDriver::Error::StaleElementReferenceError, ::Selenium::WebDriver::Error::ElementNotInteractableError, ::Selenium::WebDriver::Error::InvalidSelectorError, # Work around chromedriver go_back/go_forward race condition ::Selenium::WebDriver::Error::ElementClickInterceptedError, ::Selenium::WebDriver::Error::NoSuchElementError, # IE ::Selenium::WebDriver::Error::InvalidArgumentError # IE ].tap do |errors| if defined?(::Selenium::WebDriver::Error::DetachedShadowRootError) errors.push(::Selenium::WebDriver::Error::DetachedShadowRootError) end end end def no_such_window_error Selenium::WebDriver::Error::NoSuchWindowError end private def native_args(args) args.map { |arg| arg.is_a?(Capybara::Selenium::Node) ? arg.native : arg } end def native_active_element browser.switch_to.active_element end def clear_browser_state delete_all_cookies clear_storage rescue *clear_browser_state_errors # delete_all_cookies fails when we've previously gone # to about:blank, so we rescue this error and do nothing # instead. end def clear_browser_state_errors @clear_browser_state_errors ||= [Selenium::WebDriver::Error::UnknownError] end def unhandled_alert_errors @unhandled_alert_errors ||= [Selenium::WebDriver::Error::UnexpectedAlertOpenError] end def delete_all_cookies @browser.manage.delete_all_cookies end def clear_storage clear_session_storage unless options[:clear_session_storage] == false clear_local_storage unless options[:clear_local_storage] == false rescue Selenium::WebDriver::Error::JavascriptError, Selenium::WebDriver::Error::WebDriverError # session/local storage may not be available if on non-http pages (e.g. about:blank) end def clear_session_storage if @browser.respond_to? :session_storage @browser.session_storage.clear else begin @browser&.execute_script('window.sessionStorage.clear()') rescue # rubocop:disable Style/RescueStandardError unless options[:clear_session_storage].nil? warn 'sessionStorage clear requested but is not supported by this driver' end end end end def clear_local_storage # selenium-webdriver 4.30.0 removed HTML5 storage accessors -- not really sure why # can we replicate this robustly via CDP? if @browser.respond_to? :local_storage @browser.local_storage.clear else begin @browser&.execute_script('window.localStorage.clear()') rescue # rubocop:disable Style/RescueStandardError unless options[:clear_local_storage].nil? warn 'localStorage clear requested but is not supported by this driver' end end end end def navigate_with_accept(url) @browser.navigate.to(url) sleep 0.1 # slight wait for alert @browser.switch_to.alert.accept rescue modal_error # alert now gone, should mean navigation happened end def modal_error Selenium::WebDriver::Error::NoSuchAlertError end def within_given_window(handle) original_handle = current_window_handle if handle == original_handle yield else switch_to_window(handle) result = yield switch_to_window(original_handle) result end end def find_modal(text: nil, **options) # Selenium has its own built in wait (2 seconds)for a modal to show up, so this wait is really the minimum time # Actual wait time may be longer than specified wait = Selenium::WebDriver::Wait.new( timeout: options.fetch(:wait, session_options.default_max_wait_time) || 0, ignore: modal_error ) begin wait.until do alert = @browser.switch_to.alert regexp = text.is_a?(Regexp) ? text : Regexp.new(Regexp.escape(text.to_s)) matched = alert.text.match?(regexp) unless matched raise Capybara::ModalNotFound, "Unable to find modal dialog with #{text} - found '#{alert.text}' instead." end alert end rescue *find_modal_errors raise Capybara::ModalNotFound, "Unable to find modal dialog#{" with #{text}" if text}" end end def find_modal_errors @find_modal_errors ||= [Selenium::WebDriver::Error::TimeoutError] end def silenced_unknown_error_message?(msg) silenced_unknown_error_messages.any? { |regex| msg.match? regex } end def silenced_unknown_error_messages [/Error communicating with the remote browser/] end def unwrap_script_result(arg) case arg when Array arg.map { |arr| unwrap_script_result(arr) } when Hash arg.transform_values! { |value| unwrap_script_result(value) } when Selenium::WebDriver::Element, Selenium::WebDriver::ShadowRoot build_node(arg) else arg end end def find_context browser end def build_node(native_node, initial_cache = {}) ::Capybara::Selenium::Node.new(self, native_node, initial_cache) end def bridge browser.send(:bridge) end def specialize_driver browser_type = browser.browser Capybara::Selenium::Driver.specializations.select { |k, _v| k === browser_type }.each_value do |specialization| # rubocop:disable Style/CaseEquality extend specialization end end def setup_exit_handler main = Process.pid at_exit do # Store the exit status of the test run since it goes away after calling the at_exit proc... @exit_status = $ERROR_INFO.status if $ERROR_INFO.is_a?(SystemExit) quit if Process.pid == main exit @exit_status if @exit_status # Force exit with stored status end end def reset_browser_state clear_browser_state @browser.navigate.to('about:blank') end def wait_for_empty_page(timer) until find_xpath('/html/body/*').empty? raise Capybara::ExpectationNotMet, 'Timed out waiting for Selenium session reset' if timer.expired? sleep 0.01 # It has been observed that it is possible that asynchronous JS code in # the application under test can navigate the browser away from about:blank # if the timing is just right. Ensure we are still at about:blank... @browser.navigate.to('about:blank') unless current_url == 'about:blank' end end def accept_unhandled_reset_alert @browser.switch_to.alert.accept sleep 0.25 # allow time for the modal to be handled rescue modal_error # The alert is now gone. # If navigation has not occurred attempt again and accept alert # since FF may have dismissed the alert at first attempt. navigate_with_accept('about:blank') if current_url != 'about:blank' end end require 'capybara/selenium/driver_specializations/chrome_driver' require 'capybara/selenium/driver_specializations/firefox_driver' require 'capybara/selenium/driver_specializations/internet_explorer_driver' require 'capybara/selenium/driver_specializations/safari_driver' require 'capybara/selenium/driver_specializations/edge_driver'
Ruby
{ "end_line": 407, "name": "within_given_window", "signature": "def within_given_window(handle)", "start_line": 397 }
{ "class_name": "Capybara::Selenium::Driver", "class_signature": "class Capybara::Selenium::Driver < < Capybara::Driver::Base", "module": "" }
find_modal
capybara/lib/capybara/selenium/driver.rb
def find_modal(text: nil, **options) # Selenium has its own built in wait (2 seconds)for a modal to show up, so this wait is really the minimum time # Actual wait time may be longer than specified wait = Selenium::WebDriver::Wait.new( timeout: options.fetch(:wait, session_options.default_max_wait_time) || 0, ignore: modal_error ) begin wait.until do alert = @browser.switch_to.alert regexp = text.is_a?(Regexp) ? text : Regexp.new(Regexp.escape(text.to_s)) matched = alert.text.match?(regexp) unless matched raise Capybara::ModalNotFound, "Unable to find modal dialog with #{text} - found '#{alert.text}' instead." end alert end rescue *find_modal_errors raise Capybara::ModalNotFound, "Unable to find modal dialog#{" with #{text}" if text}" end end
# frozen_string_literal: true require 'uri' require 'English' class Capybara::Selenium::Driver < Capybara::Driver::Base include Capybara::Selenium::Find DEFAULT_OPTIONS = { browser: :firefox, clear_local_storage: nil, clear_session_storage: nil }.freeze SPECIAL_OPTIONS = %i[browser clear_local_storage clear_session_storage timeout native_displayed].freeze CAPS_VERSION = Gem::Requirement.new('< 4.8.0') attr_reader :app, :options class << self attr_reader :selenium_webdriver_version def load_selenium require 'selenium-webdriver' require 'capybara/selenium/patches/atoms' require 'capybara/selenium/patches/is_displayed' # Look up the version of `selenium-webdriver` to # see if it's a version we support. # # By default, we use Gem.loaded_specs to determine # the version number. However, in some cases, such # as when loading `selenium-webdriver` outside of # Rubygems, we fall back to referencing # Selenium::WebDriver::VERSION. Ideally we'd # use the constant in all cases, but earlier versions # of `selenium-webdriver` didn't provide the constant. @selenium_webdriver_version = if Gem.loaded_specs['selenium-webdriver'] Gem.loaded_specs['selenium-webdriver'].version else Gem::Version.new(Selenium::WebDriver::VERSION) end unless Gem::Requirement.new('>= 4.8').satisfied_by? @selenium_webdriver_version warn "Warning: You're using an unsupported version of selenium-webdriver, please upgrade to 4.8+." end @selenium_webdriver_version rescue LoadError => e raise e unless e.message.include?('selenium-webdriver') raise LoadError, "Capybara's selenium driver is unable to load `selenium-webdriver`, please install the gem and add `gem 'selenium-webdriver'` to your Gemfile if you are using bundler." end attr_reader :specializations def register_specialization(browser_name, specialization) @specializations ||= {} @specializations[browser_name] = specialization end end def browser unless @browser options[:http_client] ||= begin require 'capybara/selenium/patches/persistent_client' if options[:timeout] ::Capybara::Selenium::PersistentClient.new(read_timeout: options[:timeout]) else ::Capybara::Selenium::PersistentClient.new end end processed_options = options.except(*SPECIAL_OPTIONS) @browser = Selenium::WebDriver.for(options[:browser], processed_options) specialize_driver setup_exit_handler end @browser end def initialize(app, **options) super() self.class.load_selenium @app = app @browser = nil @exit_status = nil @frame_handles = Hash.new { |hash, handle| hash[handle] = [] } @options = DEFAULT_OPTIONS.merge(options) @node_class = ::Capybara::Selenium::Node end def visit(path) browser.navigate.to(path) end def refresh browser.navigate.refresh end def go_back browser.navigate.back end def go_forward browser.navigate.forward end def html browser.page_source rescue Selenium::WebDriver::Error::JavascriptError => e raise unless e.message.include?('documentElement is null') end def title browser.title end def current_url browser.current_url end def wait?; true; end def needs_server?; true; end def execute_script(script, *args) browser.execute_script(script, *native_args(args)) end def evaluate_script(script, *args) result = execute_script("return #{script}", *args) unwrap_script_result(result) end def evaluate_async_script(script, *args) browser.manage.timeouts.script_timeout = Capybara.default_max_wait_time result = browser.execute_async_script(script, *native_args(args)) unwrap_script_result(result) end def active_element build_node(native_active_element) end def send_keys(*args) # Should this call the specialized nodes rather than native??? native_active_element.send_keys(*args) end def save_screenshot(path, **options) browser.save_screenshot(path, **options) end def reset! # Use instance variable directly so we avoid starting the browser just to reset the session return unless @browser navigated = false timer = Capybara::Helpers.timer(expire_in: 10) begin # Only trigger a navigation if we haven't done it already, otherwise it # can trigger an endless series of unload modals reset_browser_state unless navigated navigated = true # Ensure the page is empty and trigger an UnhandledAlertError for any modals that appear during unload wait_for_empty_page(timer) rescue *unhandled_alert_errors # This error is thrown if an unhandled alert is on the page # Firefox appears to automatically dismiss this alert, chrome does not # We'll try to accept it accept_unhandled_reset_alert # try cleaning up the browser again retry end end def frame_obscured_at?(x:, y:) frame = @frame_handles[current_window_handle].last return false unless frame switch_to_frame(:parent) begin frame.base.obscured?(x: x, y: y) ensure switch_to_frame(frame) end end def switch_to_frame(frame) handles = @frame_handles[current_window_handle] case frame when :top handles.clear browser.switch_to.default_content when :parent handles.pop browser.switch_to.parent_frame else handles << frame browser.switch_to.frame(frame.native) end end def current_window_handle browser.window_handle end def window_size(handle) within_given_window(handle) do size = browser.manage.window.size [size.width, size.height] end end def resize_window_to(handle, width, height) within_given_window(handle) do browser.manage.window.resize_to(width, height) end end def maximize_window(handle) within_given_window(handle) do browser.manage.window.maximize end sleep 0.1 # work around for https://code.google.com/p/selenium/issues/detail?id=7405 end def fullscreen_window(handle) within_given_window(handle) do browser.manage.window.full_screen end end def close_window(handle) raise ArgumentError, 'Not allowed to close the primary window' if handle == window_handles.first within_given_window(handle) do browser.close end end def window_handles browser.window_handles end def open_new_window(kind = :tab) if browser.switch_to.respond_to?(:new_window) handle = current_window_handle browser.switch_to.new_window(kind) switch_to_window(handle) else browser.manage.new_window(kind) end rescue NoMethodError, Selenium::WebDriver::Error::WebDriverError # If not supported by the driver or browser default to using JS browser.execute_script('window.open();') end def switch_to_window(handle) browser.switch_to.window handle end def accept_modal(_type, **options) yield if block_given? modal = find_modal(**options) modal.send_keys options[:with] if options[:with] message = modal.text modal.accept message end def dismiss_modal(_type, **options) yield if block_given? modal = find_modal(**options) message = modal.text modal.dismiss message end def quit @browser&.quit rescue Selenium::WebDriver::Error::SessionNotCreatedError, Errno::ECONNREFUSED, Selenium::WebDriver::Error::InvalidSessionIdError # Browser must have already gone rescue Selenium::WebDriver::Error::UnknownError => e unless silenced_unknown_error_message?(e.message) # Most likely already gone # probably already gone but not sure - so warn warn "Ignoring Selenium UnknownError during driver quit: #{e.message}" end ensure @browser = nil end def invalid_element_errors @invalid_element_errors ||= [ ::Selenium::WebDriver::Error::StaleElementReferenceError, ::Selenium::WebDriver::Error::ElementNotInteractableError, ::Selenium::WebDriver::Error::InvalidSelectorError, # Work around chromedriver go_back/go_forward race condition ::Selenium::WebDriver::Error::ElementClickInterceptedError, ::Selenium::WebDriver::Error::NoSuchElementError, # IE ::Selenium::WebDriver::Error::InvalidArgumentError # IE ].tap do |errors| if defined?(::Selenium::WebDriver::Error::DetachedShadowRootError) errors.push(::Selenium::WebDriver::Error::DetachedShadowRootError) end end end def no_such_window_error Selenium::WebDriver::Error::NoSuchWindowError end private def native_args(args) args.map { |arg| arg.is_a?(Capybara::Selenium::Node) ? arg.native : arg } end def native_active_element browser.switch_to.active_element end def clear_browser_state delete_all_cookies clear_storage rescue *clear_browser_state_errors # delete_all_cookies fails when we've previously gone # to about:blank, so we rescue this error and do nothing # instead. end def clear_browser_state_errors @clear_browser_state_errors ||= [Selenium::WebDriver::Error::UnknownError] end def unhandled_alert_errors @unhandled_alert_errors ||= [Selenium::WebDriver::Error::UnexpectedAlertOpenError] end def delete_all_cookies @browser.manage.delete_all_cookies end def clear_storage clear_session_storage unless options[:clear_session_storage] == false clear_local_storage unless options[:clear_local_storage] == false rescue Selenium::WebDriver::Error::JavascriptError, Selenium::WebDriver::Error::WebDriverError # session/local storage may not be available if on non-http pages (e.g. about:blank) end def clear_session_storage if @browser.respond_to? :session_storage @browser.session_storage.clear else begin @browser&.execute_script('window.sessionStorage.clear()') rescue # rubocop:disable Style/RescueStandardError unless options[:clear_session_storage].nil? warn 'sessionStorage clear requested but is not supported by this driver' end end end end def clear_local_storage # selenium-webdriver 4.30.0 removed HTML5 storage accessors -- not really sure why # can we replicate this robustly via CDP? if @browser.respond_to? :local_storage @browser.local_storage.clear else begin @browser&.execute_script('window.localStorage.clear()') rescue # rubocop:disable Style/RescueStandardError unless options[:clear_local_storage].nil? warn 'localStorage clear requested but is not supported by this driver' end end end end def navigate_with_accept(url) @browser.navigate.to(url) sleep 0.1 # slight wait for alert @browser.switch_to.alert.accept rescue modal_error # alert now gone, should mean navigation happened end def modal_error Selenium::WebDriver::Error::NoSuchAlertError end def within_given_window(handle) original_handle = current_window_handle if handle == original_handle yield else switch_to_window(handle) result = yield switch_to_window(original_handle) result end end def find_modal(text: nil, **options) # Selenium has its own built in wait (2 seconds)for a modal to show up, so this wait is really the minimum time # Actual wait time may be longer than specified wait = Selenium::WebDriver::Wait.new( timeout: options.fetch(:wait, session_options.default_max_wait_time) || 0, ignore: modal_error ) begin wait.until do alert = @browser.switch_to.alert regexp = text.is_a?(Regexp) ? text : Regexp.new(Regexp.escape(text.to_s)) matched = alert.text.match?(regexp) unless matched raise Capybara::ModalNotFound, "Unable to find modal dialog with #{text} - found '#{alert.text}' instead." end alert end rescue *find_modal_errors raise Capybara::ModalNotFound, "Unable to find modal dialog#{" with #{text}" if text}" end end def find_modal_errors @find_modal_errors ||= [Selenium::WebDriver::Error::TimeoutError] end def silenced_unknown_error_message?(msg) silenced_unknown_error_messages.any? { |regex| msg.match? regex } end def silenced_unknown_error_messages [/Error communicating with the remote browser/] end def unwrap_script_result(arg) case arg when Array arg.map { |arr| unwrap_script_result(arr) } when Hash arg.transform_values! { |value| unwrap_script_result(value) } when Selenium::WebDriver::Element, Selenium::WebDriver::ShadowRoot build_node(arg) else arg end end def find_context browser end def build_node(native_node, initial_cache = {}) ::Capybara::Selenium::Node.new(self, native_node, initial_cache) end def bridge browser.send(:bridge) end def specialize_driver browser_type = browser.browser Capybara::Selenium::Driver.specializations.select { |k, _v| k === browser_type }.each_value do |specialization| # rubocop:disable Style/CaseEquality extend specialization end end def setup_exit_handler main = Process.pid at_exit do # Store the exit status of the test run since it goes away after calling the at_exit proc... @exit_status = $ERROR_INFO.status if $ERROR_INFO.is_a?(SystemExit) quit if Process.pid == main exit @exit_status if @exit_status # Force exit with stored status end end def reset_browser_state clear_browser_state @browser.navigate.to('about:blank') end def wait_for_empty_page(timer) until find_xpath('/html/body/*').empty? raise Capybara::ExpectationNotMet, 'Timed out waiting for Selenium session reset' if timer.expired? sleep 0.01 # It has been observed that it is possible that asynchronous JS code in # the application under test can navigate the browser away from about:blank # if the timing is just right. Ensure we are still at about:blank... @browser.navigate.to('about:blank') unless current_url == 'about:blank' end end def accept_unhandled_reset_alert @browser.switch_to.alert.accept sleep 0.25 # allow time for the modal to be handled rescue modal_error # The alert is now gone. # If navigation has not occurred attempt again and accept alert # since FF may have dismissed the alert at first attempt. navigate_with_accept('about:blank') if current_url != 'about:blank' end end require 'capybara/selenium/driver_specializations/chrome_driver' require 'capybara/selenium/driver_specializations/firefox_driver' require 'capybara/selenium/driver_specializations/internet_explorer_driver' require 'capybara/selenium/driver_specializations/safari_driver' require 'capybara/selenium/driver_specializations/edge_driver'
Ruby
{ "end_line": 430, "name": "find_modal", "signature": "def find_modal(text: nil, **options)", "start_line": 409 }
{ "class_name": "Capybara::Selenium::Driver", "class_signature": "class Capybara::Selenium::Driver < < Capybara::Driver::Base", "module": "" }
unwrap_script_result
capybara/lib/capybara/selenium/driver.rb
def unwrap_script_result(arg) case arg when Array arg.map { |arr| unwrap_script_result(arr) } when Hash arg.transform_values! { |value| unwrap_script_result(value) } when Selenium::WebDriver::Element, Selenium::WebDriver::ShadowRoot build_node(arg) else arg end end
# frozen_string_literal: true require 'uri' require 'English' class Capybara::Selenium::Driver < Capybara::Driver::Base include Capybara::Selenium::Find DEFAULT_OPTIONS = { browser: :firefox, clear_local_storage: nil, clear_session_storage: nil }.freeze SPECIAL_OPTIONS = %i[browser clear_local_storage clear_session_storage timeout native_displayed].freeze CAPS_VERSION = Gem::Requirement.new('< 4.8.0') attr_reader :app, :options class << self attr_reader :selenium_webdriver_version def load_selenium require 'selenium-webdriver' require 'capybara/selenium/patches/atoms' require 'capybara/selenium/patches/is_displayed' # Look up the version of `selenium-webdriver` to # see if it's a version we support. # # By default, we use Gem.loaded_specs to determine # the version number. However, in some cases, such # as when loading `selenium-webdriver` outside of # Rubygems, we fall back to referencing # Selenium::WebDriver::VERSION. Ideally we'd # use the constant in all cases, but earlier versions # of `selenium-webdriver` didn't provide the constant. @selenium_webdriver_version = if Gem.loaded_specs['selenium-webdriver'] Gem.loaded_specs['selenium-webdriver'].version else Gem::Version.new(Selenium::WebDriver::VERSION) end unless Gem::Requirement.new('>= 4.8').satisfied_by? @selenium_webdriver_version warn "Warning: You're using an unsupported version of selenium-webdriver, please upgrade to 4.8+." end @selenium_webdriver_version rescue LoadError => e raise e unless e.message.include?('selenium-webdriver') raise LoadError, "Capybara's selenium driver is unable to load `selenium-webdriver`, please install the gem and add `gem 'selenium-webdriver'` to your Gemfile if you are using bundler." end attr_reader :specializations def register_specialization(browser_name, specialization) @specializations ||= {} @specializations[browser_name] = specialization end end def browser unless @browser options[:http_client] ||= begin require 'capybara/selenium/patches/persistent_client' if options[:timeout] ::Capybara::Selenium::PersistentClient.new(read_timeout: options[:timeout]) else ::Capybara::Selenium::PersistentClient.new end end processed_options = options.except(*SPECIAL_OPTIONS) @browser = Selenium::WebDriver.for(options[:browser], processed_options) specialize_driver setup_exit_handler end @browser end def initialize(app, **options) super() self.class.load_selenium @app = app @browser = nil @exit_status = nil @frame_handles = Hash.new { |hash, handle| hash[handle] = [] } @options = DEFAULT_OPTIONS.merge(options) @node_class = ::Capybara::Selenium::Node end def visit(path) browser.navigate.to(path) end def refresh browser.navigate.refresh end def go_back browser.navigate.back end def go_forward browser.navigate.forward end def html browser.page_source rescue Selenium::WebDriver::Error::JavascriptError => e raise unless e.message.include?('documentElement is null') end def title browser.title end def current_url browser.current_url end def wait?; true; end def needs_server?; true; end def execute_script(script, *args) browser.execute_script(script, *native_args(args)) end def evaluate_script(script, *args) result = execute_script("return #{script}", *args) unwrap_script_result(result) end def evaluate_async_script(script, *args) browser.manage.timeouts.script_timeout = Capybara.default_max_wait_time result = browser.execute_async_script(script, *native_args(args)) unwrap_script_result(result) end def active_element build_node(native_active_element) end def send_keys(*args) # Should this call the specialized nodes rather than native??? native_active_element.send_keys(*args) end def save_screenshot(path, **options) browser.save_screenshot(path, **options) end def reset! # Use instance variable directly so we avoid starting the browser just to reset the session return unless @browser navigated = false timer = Capybara::Helpers.timer(expire_in: 10) begin # Only trigger a navigation if we haven't done it already, otherwise it # can trigger an endless series of unload modals reset_browser_state unless navigated navigated = true # Ensure the page is empty and trigger an UnhandledAlertError for any modals that appear during unload wait_for_empty_page(timer) rescue *unhandled_alert_errors # This error is thrown if an unhandled alert is on the page # Firefox appears to automatically dismiss this alert, chrome does not # We'll try to accept it accept_unhandled_reset_alert # try cleaning up the browser again retry end end def frame_obscured_at?(x:, y:) frame = @frame_handles[current_window_handle].last return false unless frame switch_to_frame(:parent) begin frame.base.obscured?(x: x, y: y) ensure switch_to_frame(frame) end end def switch_to_frame(frame) handles = @frame_handles[current_window_handle] case frame when :top handles.clear browser.switch_to.default_content when :parent handles.pop browser.switch_to.parent_frame else handles << frame browser.switch_to.frame(frame.native) end end def current_window_handle browser.window_handle end def window_size(handle) within_given_window(handle) do size = browser.manage.window.size [size.width, size.height] end end def resize_window_to(handle, width, height) within_given_window(handle) do browser.manage.window.resize_to(width, height) end end def maximize_window(handle) within_given_window(handle) do browser.manage.window.maximize end sleep 0.1 # work around for https://code.google.com/p/selenium/issues/detail?id=7405 end def fullscreen_window(handle) within_given_window(handle) do browser.manage.window.full_screen end end def close_window(handle) raise ArgumentError, 'Not allowed to close the primary window' if handle == window_handles.first within_given_window(handle) do browser.close end end def window_handles browser.window_handles end def open_new_window(kind = :tab) if browser.switch_to.respond_to?(:new_window) handle = current_window_handle browser.switch_to.new_window(kind) switch_to_window(handle) else browser.manage.new_window(kind) end rescue NoMethodError, Selenium::WebDriver::Error::WebDriverError # If not supported by the driver or browser default to using JS browser.execute_script('window.open();') end def switch_to_window(handle) browser.switch_to.window handle end def accept_modal(_type, **options) yield if block_given? modal = find_modal(**options) modal.send_keys options[:with] if options[:with] message = modal.text modal.accept message end def dismiss_modal(_type, **options) yield if block_given? modal = find_modal(**options) message = modal.text modal.dismiss message end def quit @browser&.quit rescue Selenium::WebDriver::Error::SessionNotCreatedError, Errno::ECONNREFUSED, Selenium::WebDriver::Error::InvalidSessionIdError # Browser must have already gone rescue Selenium::WebDriver::Error::UnknownError => e unless silenced_unknown_error_message?(e.message) # Most likely already gone # probably already gone but not sure - so warn warn "Ignoring Selenium UnknownError during driver quit: #{e.message}" end ensure @browser = nil end def invalid_element_errors @invalid_element_errors ||= [ ::Selenium::WebDriver::Error::StaleElementReferenceError, ::Selenium::WebDriver::Error::ElementNotInteractableError, ::Selenium::WebDriver::Error::InvalidSelectorError, # Work around chromedriver go_back/go_forward race condition ::Selenium::WebDriver::Error::ElementClickInterceptedError, ::Selenium::WebDriver::Error::NoSuchElementError, # IE ::Selenium::WebDriver::Error::InvalidArgumentError # IE ].tap do |errors| if defined?(::Selenium::WebDriver::Error::DetachedShadowRootError) errors.push(::Selenium::WebDriver::Error::DetachedShadowRootError) end end end def no_such_window_error Selenium::WebDriver::Error::NoSuchWindowError end private def native_args(args) args.map { |arg| arg.is_a?(Capybara::Selenium::Node) ? arg.native : arg } end def native_active_element browser.switch_to.active_element end def clear_browser_state delete_all_cookies clear_storage rescue *clear_browser_state_errors # delete_all_cookies fails when we've previously gone # to about:blank, so we rescue this error and do nothing # instead. end def clear_browser_state_errors @clear_browser_state_errors ||= [Selenium::WebDriver::Error::UnknownError] end def unhandled_alert_errors @unhandled_alert_errors ||= [Selenium::WebDriver::Error::UnexpectedAlertOpenError] end def delete_all_cookies @browser.manage.delete_all_cookies end def clear_storage clear_session_storage unless options[:clear_session_storage] == false clear_local_storage unless options[:clear_local_storage] == false rescue Selenium::WebDriver::Error::JavascriptError, Selenium::WebDriver::Error::WebDriverError # session/local storage may not be available if on non-http pages (e.g. about:blank) end def clear_session_storage if @browser.respond_to? :session_storage @browser.session_storage.clear else begin @browser&.execute_script('window.sessionStorage.clear()') rescue # rubocop:disable Style/RescueStandardError unless options[:clear_session_storage].nil? warn 'sessionStorage clear requested but is not supported by this driver' end end end end def clear_local_storage # selenium-webdriver 4.30.0 removed HTML5 storage accessors -- not really sure why # can we replicate this robustly via CDP? if @browser.respond_to? :local_storage @browser.local_storage.clear else begin @browser&.execute_script('window.localStorage.clear()') rescue # rubocop:disable Style/RescueStandardError unless options[:clear_local_storage].nil? warn 'localStorage clear requested but is not supported by this driver' end end end end def navigate_with_accept(url) @browser.navigate.to(url) sleep 0.1 # slight wait for alert @browser.switch_to.alert.accept rescue modal_error # alert now gone, should mean navigation happened end def modal_error Selenium::WebDriver::Error::NoSuchAlertError end def within_given_window(handle) original_handle = current_window_handle if handle == original_handle yield else switch_to_window(handle) result = yield switch_to_window(original_handle) result end end def find_modal(text: nil, **options) # Selenium has its own built in wait (2 seconds)for a modal to show up, so this wait is really the minimum time # Actual wait time may be longer than specified wait = Selenium::WebDriver::Wait.new( timeout: options.fetch(:wait, session_options.default_max_wait_time) || 0, ignore: modal_error ) begin wait.until do alert = @browser.switch_to.alert regexp = text.is_a?(Regexp) ? text : Regexp.new(Regexp.escape(text.to_s)) matched = alert.text.match?(regexp) unless matched raise Capybara::ModalNotFound, "Unable to find modal dialog with #{text} - found '#{alert.text}' instead." end alert end rescue *find_modal_errors raise Capybara::ModalNotFound, "Unable to find modal dialog#{" with #{text}" if text}" end end def find_modal_errors @find_modal_errors ||= [Selenium::WebDriver::Error::TimeoutError] end def silenced_unknown_error_message?(msg) silenced_unknown_error_messages.any? { |regex| msg.match? regex } end def silenced_unknown_error_messages [/Error communicating with the remote browser/] end def unwrap_script_result(arg) case arg when Array arg.map { |arr| unwrap_script_result(arr) } when Hash arg.transform_values! { |value| unwrap_script_result(value) } when Selenium::WebDriver::Element, Selenium::WebDriver::ShadowRoot build_node(arg) else arg end end def find_context browser end def build_node(native_node, initial_cache = {}) ::Capybara::Selenium::Node.new(self, native_node, initial_cache) end def bridge browser.send(:bridge) end def specialize_driver browser_type = browser.browser Capybara::Selenium::Driver.specializations.select { |k, _v| k === browser_type }.each_value do |specialization| # rubocop:disable Style/CaseEquality extend specialization end end def setup_exit_handler main = Process.pid at_exit do # Store the exit status of the test run since it goes away after calling the at_exit proc... @exit_status = $ERROR_INFO.status if $ERROR_INFO.is_a?(SystemExit) quit if Process.pid == main exit @exit_status if @exit_status # Force exit with stored status end end def reset_browser_state clear_browser_state @browser.navigate.to('about:blank') end def wait_for_empty_page(timer) until find_xpath('/html/body/*').empty? raise Capybara::ExpectationNotMet, 'Timed out waiting for Selenium session reset' if timer.expired? sleep 0.01 # It has been observed that it is possible that asynchronous JS code in # the application under test can navigate the browser away from about:blank # if the timing is just right. Ensure we are still at about:blank... @browser.navigate.to('about:blank') unless current_url == 'about:blank' end end def accept_unhandled_reset_alert @browser.switch_to.alert.accept sleep 0.25 # allow time for the modal to be handled rescue modal_error # The alert is now gone. # If navigation has not occurred attempt again and accept alert # since FF may have dismissed the alert at first attempt. navigate_with_accept('about:blank') if current_url != 'about:blank' end end require 'capybara/selenium/driver_specializations/chrome_driver' require 'capybara/selenium/driver_specializations/firefox_driver' require 'capybara/selenium/driver_specializations/internet_explorer_driver' require 'capybara/selenium/driver_specializations/safari_driver' require 'capybara/selenium/driver_specializations/edge_driver'
Ruby
{ "end_line": 455, "name": "unwrap_script_result", "signature": "def unwrap_script_result(arg)", "start_line": 444 }
{ "class_name": "Capybara::Selenium::Driver", "class_signature": "class Capybara::Selenium::Driver < < Capybara::Driver::Base", "module": "" }