From afc7d2426f4b5c15beea3e32b475c123f4100ec5 Mon Sep 17 00:00:00 2001 From: Dmitry Vorotilin Date: Tue, 24 Nov 2026 21:21:04 +0300 Subject: [PATCH] ref(errors)!: raise ArgumentError for bad arguments and fix misleading error messages Bare RuntimeError raises (unknown mouse button, cookies.remove without :domain or :url, relative go_to without :base_url) become ArgumentError, a relative :save_path raises ArgumentError instead of Ferrum::Error, and screencast and debug_url failures raise Ferrum::Error. NoSuchPageError, NoSuchTargetError, EmptyPathError, CoordinatesNotFoundError and ArgumentErrors without text now name what's missing or list the valid values. DeadBrowserError no longer talks about windows, NodeMovingError no longer assumes a click, TimeoutError is one line, raw array inspects become a | b lists, and links point to docs.rubycdp.com. Refs #557 --- CHANGELOG.md | 4 ++++ lib/ferrum/browser.rb | 4 ++-- lib/ferrum/browser/options.rb | 6 +++--- lib/ferrum/client.rb | 15 +++++++++++---- lib/ferrum/context.rb | 2 +- lib/ferrum/cookies.rb | 4 +++- lib/ferrum/downloads.rb | 9 +++++---- lib/ferrum/errors.rb | 29 +++++++++++++++-------------- lib/ferrum/frame.rb | 4 +++- lib/ferrum/keyboard.rb | 10 +++++----- lib/ferrum/mouse.rb | 8 +++++++- lib/ferrum/network.rb | 4 ++-- lib/ferrum/node.rb | 4 ++-- lib/ferrum/page.rb | 2 +- lib/ferrum/page/cookies.rb | 4 +++- lib/ferrum/page/navigation.rb | 7 ++++++- lib/ferrum/page/screencast.rb | 2 +- lib/ferrum/page/screenshot.rb | 6 ++++-- lib/ferrum/rgba.rb | 4 ++-- sig/ferrum/browser/options.rbs | 2 +- sig/ferrum/client.rbs | 4 +++- sig/ferrum/errors.rbs | 1 + spec/browser_spec.rb | 5 +++-- spec/client_spec.rb | 2 +- spec/context_spec.rb | 5 +++++ spec/cookies_spec.rb | 9 +++++++++ spec/downloads_spec.rb | 2 +- spec/keyboard_spec.rb | 16 ++++++++-------- spec/mouse_spec.rb | 4 ++-- spec/network_spec.rb | 2 +- spec/node_spec.rb | 4 ++-- spec/page/navigation_spec.rb | 9 +++++++++ spec/page/screenshot_spec.rb | 2 +- spec/rgba_spec.rb | 10 +++++----- 34 files changed, 132 insertions(+), 73 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7e8d9ccf..e6be5fc0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,12 +5,16 @@ ### Changed - `User-Agent` and `Accept-Language` set through `headers` are only sent with requests, they no longer change what `navigator` reports. Use `network.emulate(user_agent:, accept_language:)` to override both +- An unknown mouse button, `cookies.remove` without `:domain` or `:url`, a relative `go_to` without `:base_url` and a + relative `:save_path` raise `ArgumentError` instead of `RuntimeError` or `Ferrum::Error`. A failed screencast and + `debug_url` raise `Ferrum::Error`. Errors that had no message or a misleading one say what's missing now [#557] ### Deprecated ### Fixed ### Removed +- `Browser::Options::BASE_URL_SCHEMA`, use `BASE_URL_SCHEMES` - `target.window?` and `windows` of a context and of the browser, use `target.opener_id`, `await_page { ... }` or `pages(&:opener_id)` - `:js_errors`, uncaught exceptions are in `page.console` with `source: :exception`, and `page.on(:console)` yields them diff --git a/lib/ferrum/browser.rb b/lib/ferrum/browser.rb index eace4322..1c6bdd73 100644 --- a/lib/ferrum/browser.rb +++ b/lib/ferrum/browser.rb @@ -125,7 +125,7 @@ class Browser # {Ferrum::DeadBrowserError}. # # @option options [Hash] :proxy - # Specify proxy settings, [read more](https://github.com/rubycdp/ferrum#proxy). + # Specify proxy settings, [read more](https://docs.rubycdp.com/docs/ferrum/proxy). # # @option options [String] :save_path # Path to save attachments with [Content-Disposition](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) @@ -331,7 +331,7 @@ def debug_url response = JSON.parse(Net::HTTP.get(URI(build_remote_debug_url(path: "/json")))) devtools_frontend_path = response[0]&.[]("devtoolsFrontendUrl") - raise "Could not generate debug url for remote debugging session" unless devtools_frontend_path + raise Error, "Could not generate debug url for remote debugging session" unless devtools_frontend_path build_remote_debug_url(path: devtools_frontend_path) end diff --git a/lib/ferrum/browser/options.rb b/lib/ferrum/browser/options.rb index 9f5123d5..77d430ae 100644 --- a/lib/ferrum/browser/options.rb +++ b/lib/ferrum/browser/options.rb @@ -14,7 +14,7 @@ class Options BROWSER_PORT = "0" BROWSER_HOST = "127.0.0.1" WINDOW_SIZE = [1024, 768].freeze - BASE_URL_SCHEMA = %w[http https].freeze + BASE_URL_SCHEMES = %w[http https].freeze DEFAULT_TIMEOUT = ENV.fetch("FERRUM_DEFAULT_TIMEOUT", 5).to_f PROCESS_TIMEOUT = ENV.fetch("FERRUM_PROCESS_TIMEOUT", 10).to_i @@ -140,8 +140,8 @@ def parse_logger(logger) def parse_base_url(value) parsed = Addressable::URI.parse(value) - unless BASE_URL_SCHEMA.include?(parsed&.normalized_scheme) - raise ArgumentError, "`base_url` should be absolute and include schema: #{BASE_URL_SCHEMA.join(' | ')}" + unless BASE_URL_SCHEMES.include?(parsed&.normalized_scheme) + raise ArgumentError, "`base_url` should be absolute and include scheme: #{BASE_URL_SCHEMES.join(' | ')}" end parsed diff --git a/lib/ferrum/client.rb b/lib/ferrum/client.rb index 410f94e0..2e27a9c6 100644 --- a/lib/ferrum/client.rb +++ b/lib/ferrum/client.rb @@ -249,7 +249,7 @@ def send_message(message, timeout:) raise TimeoutError.new(message[:method], session_id: message[:sessionId]) unless data error, response = data.values_at("error", "result") - raise_browser_error(error) if error + raise_browser_error(error, message) if error response end @@ -413,7 +413,7 @@ def next_command_id @command_id_mutex.synchronize { @command_id += 1 } end - def raise_browser_error(error) + def raise_browser_error(error, message) case error["message"] # Node has disappeared while we were trying to get it when "No node with given id found", @@ -425,12 +425,19 @@ def raise_browser_error(error) when "Cannot find context with specified id" raise NoExecutionContextError, error when "No target with given id found" - raise NoSuchPageError + raise NoSuchPageError, no_target_message(message) when /Could not compute content quads/ - raise CoordinatesNotFoundError + raise CoordinatesNotFoundError, error["message"] else raise BrowserError, error end end + + def no_target_message(message) + target_id = message.dig(:params, :targetId) + return "#{message[:method]} found no target, it's closed or never existed" unless target_id + + "#{message[:method]} found no target #{target_id}, it's closed or never existed" + end end end diff --git a/lib/ferrum/context.rb b/lib/ferrum/context.rb index 027aca79..246c62c8 100644 --- a/lib/ferrum/context.rb +++ b/lib/ferrum/context.rb @@ -257,7 +257,7 @@ def delete_target(target_id) # @raise [TimeoutError] def attach_target(target_id) target = @targets[target_id] - raise NoSuchTargetError unless target + raise NoSuchTargetError, "No target #{target_id} in context #{id}" unless target return target if target.session_id @contexts.manually_attached(target_id) diff --git a/lib/ferrum/cookies.rb b/lib/ferrum/cookies.rb index 7e69df6b..4673ada3 100644 --- a/lib/ferrum/cookies.rb +++ b/lib/ferrum/cookies.rb @@ -118,6 +118,8 @@ def set(options) # # @return [nil] # + # @raise [ArgumentError] if neither `:domain`, `:url` nor `:base_url` is set. + # # @raise [TimeoutError] # # @example @@ -125,7 +127,7 @@ def set(options) # def remove(name:, **options) domain = options[:domain] || (default_domain unless options[:url]) - raise "Specify :domain or :url option" if !domain && !options[:url] + raise ArgumentError, "Specify :domain or :url option" if !domain && !options[:url] uri = URI.parse(options[:url]) if options[:url] cookies = select do |cookie| diff --git a/lib/ferrum/downloads.rb b/lib/ferrum/downloads.rb index 022949d9..396705ee 100644 --- a/lib/ferrum/downloads.rb +++ b/lib/ferrum/downloads.rb @@ -89,14 +89,15 @@ def await_download!(timeout: WAIT_TIMEOUT, &) # # @return [nil] # - # @raise [ArgumentError] - # @raise [Ferrum::Error] + # @raise [ArgumentError] if the behavior is unknown or the path isn't absolute. # # @raise [TimeoutError] # def set_behavior(save_path:, behavior: :allow) - raise ArgumentError unless VALID_BEHAVIOR.include?(behavior.to_sym) - raise Error, "supply absolute path for `:save_path` option" unless Pathname.new(save_path.to_s).absolute? + unless VALID_BEHAVIOR.include?(behavior.to_sym) + raise ArgumentError, "Unknown behavior #{behavior.inspect}, use #{VALID_BEHAVIOR.map(&:inspect).join(' | ')}" + end + raise ArgumentError, "Supply absolute path for `:save_path` option" unless Pathname.new(save_path.to_s).absolute? options = { browserContextId: @page.context_id } if @page.context_id @page.command("Browser.setDownloadBehavior", diff --git a/lib/ferrum/errors.rb b/lib/ferrum/errors.rb index e188314a..57997212 100644 --- a/lib/ferrum/errors.rb +++ b/lib/ferrum/errors.rb @@ -9,8 +9,13 @@ class NoSuchTargetError < Error; end class NoSuchPageError < NoSuchTargetError; end # Raised when no browser binary can be found at the configured path. class BinaryNotFoundError < Error; end + # Raised when a required file path option is empty. - class EmptyPathError < Error; end + class EmptyPathError < Error + def initialize(message = "PATH is empty, there's nowhere to look for the executable") + super + end + end # Raised when a request fails to reach the server, e.g. due to DNS or # connectivity issues. @@ -52,10 +57,7 @@ def initialize(command = nil, session_id: nil) # @return [String] # def message - "Timed out waiting for #{awaited}. It's possible that this happened " \ - "because something took a very long time (for example a page load " \ - "was slow). If so, setting the :timeout option to a higher value might " \ - "help." + "Timed out waiting for #{awaited}, set the :timeout option higher if it's expected to be slow" end private @@ -167,7 +169,8 @@ class ProcessTimeoutError < Error def initialize(timeout, output) @output = output - super("Browser did not produce websocket url within #{timeout} seconds, try to increase `:process_timeout`. See https://github.com/rubycdp/ferrum#customization") + super("Browser did not produce websocket url within #{timeout} seconds, try to increase `:process_timeout`. " \ + "See https://docs.rubycdp.com/docs/ferrum/customization") end end @@ -185,16 +188,16 @@ def initialize(url, status = nil) end end - # Raised when trying to interact with a browser process that has died or - # a window that has already been closed. + # Raised when the connection to the browser is lost, because the browser + # crashed, was closed, or the websocket dropped. class DeadBrowserError < Error - def initialize(message = "Browser is dead or given window is closed") + def initialize(message = "Lost the connection to the browser, it crashed or was closed") super end end # Raised when a node keeps moving between attempts to interact with it, - # e.g. while trying to click it. + # e.g. while trying to click or hover it. class NodeMovingError < Error def initialize(node, prev, current) @node = node @@ -209,9 +212,7 @@ def initialize(node, prev, current) # @return [String] # def message - "#{@node.inspect} that you're trying to click is moving, hence " \ - "we cannot. Previously it was at #{@prev.inspect} but now at " \ - "#{@current.inspect}." + "#{@node.inspect} keeps moving, it was at #{@prev.inspect} and then at #{@current.inspect}" end end @@ -276,7 +277,7 @@ class NodeNotFoundError < BrowserError; end # command against, e.g. because the frame isn't attached. class NoExecutionContextError < BrowserError def initialize(response = nil) - super(response || { "message" => "There's no context available" }) + super(response || { "message" => "There's no JavaScript context to run in, the frame is detached or navigating" }) end end diff --git a/lib/ferrum/frame.rb b/lib/ferrum/frame.rb index a8e86cb3..fda622e8 100644 --- a/lib/ferrum/frame.rb +++ b/lib/ferrum/frame.rb @@ -97,7 +97,9 @@ def initialize(id, page, parent_id = nil) # # @api private def state=(value) - raise ArgumentError unless STATE_VALUES.include?(value) + unless STATE_VALUES.include?(value) + raise ArgumentError, "Unknown frame state #{value.inspect}, use #{STATE_VALUES.map(&:inspect).join(' | ')}" + end @state = value end diff --git a/lib/ferrum/keyboard.rb b/lib/ferrum/keyboard.rb index ac06cd60..f5a2e709 100644 --- a/lib/ferrum/keyboard.rb +++ b/lib/ferrum/keyboard.rb @@ -137,9 +137,9 @@ def type(*keys, timeout: nil) # end # def hold(*keys) - raise ArgumentError, "block is required" unless block_given? + raise ArgumentError, "Block is required" unless block_given? - keys = keys.map { |key| modifier_name(key) || raise(ArgumentError, "not a modifier key: #{key.inspect}") } + keys = keys.map { |key| modifier_name(key) || raise(ArgumentError, "Not a modifier key: #{key.inspect}") } previous = @held_modifiers pressed = [] @@ -212,7 +212,7 @@ def dispatch_modifier(type, name) def normalize_keys(keys, pressed_keys = [], memo = []) case keys when Array - raise ArgumentError, "empty keys passed" if keys.empty? + raise ArgumentError, "Empty keys passed" if keys.empty? pressed_keys.push([]) memo += combine_strings(keys).map do |key| @@ -232,7 +232,7 @@ def normalize_keys(keys, pressed_keys = [], memo = []) to_options(key) end when String - raise ArgumentError, "empty keys passed" if keys.empty? + raise ArgumentError, "Empty keys passed" if keys.empty? pressed = pressed_keys.flatten mask = pressed.map { |k| MODIFIERS[k] }.reduce(@held_modifiers, :|) @@ -263,7 +263,7 @@ def normalize_keys(keys, pressed_keys = [], memo = []) end.flatten end else - raise ArgumentError, "unexpected argument" + raise ArgumentError, "Keys should be a String, Symbol or Array, got #{keys.inspect}" end end # rubocop:enable Metrics/PerceivedComplexity diff --git a/lib/ferrum/mouse.rb b/lib/ferrum/mouse.rb index b3624553..7ef00d75 100644 --- a/lib/ferrum/mouse.rb +++ b/lib/ferrum/mouse.rb @@ -104,6 +104,8 @@ def scroll_to(x: nil, y: nil) # # @return [self] # + # @raise [ArgumentError] if the button is unknown. + # # @raise [TimeoutError] # def click(x:, y:, delay: 0, navigation_wait: Page::NAVIGATION_WAIT, timeout: nil, **options) @@ -137,6 +139,8 @@ def click(x:, y:, delay: 0, navigation_wait: Page::NAVIGATION_WAIT, timeout: nil # # @return [self] # + # @raise [ArgumentError] if the button is unknown. + # # @raise [TimeoutError] # def down(**options) @@ -167,6 +171,8 @@ def down(**options) # # @return [self] # + # @raise [ArgumentError] if the button is unknown. + # # @raise [TimeoutError] # def up(**options) @@ -251,7 +257,7 @@ def modifiers_mask(modifiers) def validate_button(button) button = button.to_s - raise "Invalid button: #{button}" unless BUTTON_MASKS.key?(button) + raise ArgumentError, "Invalid button: #{button}" unless BUTTON_MASKS.key?(button) button end diff --git a/lib/ferrum/network.rb b/lib/ferrum/network.rb index 22e827e8..36f2ee96 100644 --- a/lib/ferrum/network.rb +++ b/lib/ferrum/network.rb @@ -29,7 +29,7 @@ class Network SignedExchange Ping CSPViolationReport Preflight Other].freeze AUTHORIZE_BLOCK_MISSING = "Block is missing, call `authorize(...) { |r| r.continue } " \ "or subscribe to `on(:request)` events before calling it" - AUTHORIZE_TYPE_WRONG = ":type should be in #{AUTHORIZE_TYPE}".freeze + AUTHORIZE_TYPE_WRONG = ":type should be #{AUTHORIZE_TYPE.map(&:inspect).join(' | ')}".freeze ALLOWED_CONNECTION_TYPE = %w[none cellular2g cellular3g cellular4g bluetooth ethernet wifi wimax other].freeze # Network traffic. @@ -194,7 +194,7 @@ def status # traffic.size # => 0 # def clear(type) - raise ArgumentError, ":type should be in #{CLEAR_TYPE}" unless CLEAR_TYPE.include?(type) + raise ArgumentError, ":type should be #{CLEAR_TYPE.map(&:inspect).join(' | ')}" unless CLEAR_TYPE.include?(type) if type == :traffic @traffic.clear diff --git a/lib/ferrum/node.rb b/lib/ferrum/node.rb index f6274f40..18be9797 100644 --- a/lib/ferrum/node.rb +++ b/lib/ferrum/node.rb @@ -88,13 +88,13 @@ def node_id @node_id = begin id = page.command("DOM.pushNodesByBackendIdsToFrontend", backendNodeIds: [backend_node_id])["nodeIds"].first - raise NodeNotFoundError, { "message" => "node is not trackable" } if id.zero? + raise NodeNotFoundError, { "message" => "Node is not trackable" } if id.zero? id rescue BrowserError => e raise unless e.message == "Document needs to be requested first" - raise NodeNotFoundError, { "message" => "node is not trackable, the page is still loading a new document" } + raise NodeNotFoundError, { "message" => "Node is not trackable, the page is still loading a new document" } end @document_version = document_version @node_id diff --git a/lib/ferrum/page.rb b/lib/ferrum/page.rb index 8d2ee025..373514b4 100644 --- a/lib/ferrum/page.rb +++ b/lib/ferrum/page.rb @@ -587,7 +587,7 @@ def build_chain(name) def accept_dialog(dialog) warn "Dialog was shown but no `on(:dialog)` callback handled it, accepting it by default. " \ - "Please take a look at https://github.com/rubycdp/ferrum#dialogs" + "Please take a look at https://docs.rubycdp.com/docs/ferrum/dialogs" dialog.accept end diff --git a/lib/ferrum/page/cookies.rb b/lib/ferrum/page/cookies.rb index 3bc1b886..4a4e1885 100644 --- a/lib/ferrum/page/cookies.rb +++ b/lib/ferrum/page/cookies.rb @@ -87,13 +87,15 @@ def set(options) # # @return [nil] # + # @raise [ArgumentError] if neither `:domain`, `:url` nor `:base_url` is set. + # # @raise [TimeoutError] # # @example # page.cookies.remove(name: "stealth") # => true # def remove(name:, **options) - raise "Specify :domain or :url option" if !options[:domain] && !options[:url] && !default_domain + raise ArgumentError, "Specify :domain or :url option" if !options[:domain] && !options[:url] && !default_domain options = options.merge(name: name) options[:domain] ||= default_domain unless options[:url] diff --git a/lib/ferrum/page/navigation.rb b/lib/ferrum/page/navigation.rb index e2e5c5f8..3edc64a2 100644 --- a/lib/ferrum/page/navigation.rb +++ b/lib/ferrum/page/navigation.rb @@ -27,6 +27,8 @@ module Navigation # @return [String, nil] # The navigated frame's id, or `nil` when the page doesn't load in time. # + # @raise [ArgumentError] if the URL is relative and there's no `:base_url`. + # # @raise [StatusError] # If the request fails. # @@ -58,6 +60,8 @@ def go_to(url = nil, timeout: nil, referrer: nil) # @return [String] # The navigated frame's id. # + # @raise [ArgumentError] if the URL is relative and there's no `:base_url`. + # # @raise [StatusError] # If the request fails. # @@ -299,7 +303,8 @@ def combine_url!(url_or_path) nil_or_relative = url.nil? || url.relative? if nil_or_relative && !@options.base_url - raise "Set :base_url browser's option or use absolute url in `go_to`, you passed: #{url_or_path}" + raise ArgumentError, + "Set :base_url browser's option or use absolute url in `go_to`, you passed: #{url_or_path}" end (nil_or_relative ? @options.base_url.join(url.to_s) : url).to_s diff --git a/lib/ferrum/page/screencast.rb b/lib/ferrum/page/screencast.rb index 26ff8eff..86edafa1 100644 --- a/lib/ferrum/page/screencast.rb +++ b/lib/ferrum/page/screencast.rb @@ -82,7 +82,7 @@ def start_screencast(**opts) response = command("Page.startScreencast", **options) if (error_text = response["errorText"]) # https://cs.chromium.org/chromium/src/net/base/net_error_list.h - raise "Starting screencast failed (#{error_text})" + raise Error, "Starting screencast failed (#{error_text})" end on("Page.screencastFrame") do |params| diff --git a/lib/ferrum/page/screenshot.rb b/lib/ferrum/page/screenshot.rb index b4b52337..32c1f422 100644 --- a/lib/ferrum/page/screenshot.rb +++ b/lib/ferrum/page/screenshot.rb @@ -247,7 +247,7 @@ def pdf_options(**opts) if format if opts[:paper_width] || opts[:paper_height] - raise ArgumentError, "Specify :format or :paper_width, :paper_height" + raise ArgumentError, "Pass either :format or :paper_width and :paper_height, not both" end dimension = PAPER_FORMATS.fetch(format) @@ -347,7 +347,9 @@ def capture_screenshot(options, full, background_color, timeout) def with_background_color(color) if color - raise ArgumentError, "Accept Ferrum::RGBA class only" unless color.is_a?(RGBA) + unless color.is_a?(RGBA) + raise ArgumentError, ":background_color should be a Ferrum::RGBA, got #{color.inspect}" + end command("Emulation.setDefaultBackgroundColorOverride", color: color.to_h) end diff --git a/lib/ferrum/rgba.rb b/lib/ferrum/rgba.rb index 7c2da3bc..989f0bc9 100644 --- a/lib/ferrum/rgba.rb +++ b/lib/ferrum/rgba.rb @@ -37,14 +37,14 @@ def validate def validate_color(value) return if value.is_a?(Integer) && Range.new(0, 255).include?(value) - raise ArgumentError, "Wrong value of #{value} should be Integer from 0 to 255" + raise ArgumentError, "Color should be an Integer from 0 to 255, got #{value.inspect}" end def validate_alpha return if alpha.is_a?(Float) && Range.new(0.0, 1.0).include?(alpha) raise ArgumentError, - "Wrong alpha value #{alpha} should be Float between 0.0 (fully transparent) and 1.0 (fully opaque)" + "Alpha should be a Float from 0.0 (fully transparent) to 1.0 (fully opaque), got #{alpha.inspect}" end end end diff --git a/sig/ferrum/browser/options.rbs b/sig/ferrum/browser/options.rbs index 02b8dddc..1f4d8383 100644 --- a/sig/ferrum/browser/options.rbs +++ b/sig/ferrum/browser/options.rbs @@ -7,7 +7,7 @@ module Ferrum WINDOW_SIZE: ::Array[::Integer] - BASE_URL_SCHEMA: ::Array[String] + BASE_URL_SCHEMES: ::Array[String] DEFAULT_TIMEOUT: ::Float diff --git a/sig/ferrum/client.rbs b/sig/ferrum/client.rbs index c0277b53..68407bdb 100644 --- a/sig/ferrum/client.rbs +++ b/sig/ferrum/client.rbs @@ -90,6 +90,8 @@ module Ferrum def next_command_id: () -> ::Integer - def raise_browser_error: (Hash[String, untyped] error) -> void + def raise_browser_error: (Hash[String, untyped] error, Hash[Symbol, untyped] message) -> void + + def no_target_message: (Hash[Symbol, untyped] message) -> String end end diff --git a/sig/ferrum/errors.rbs b/sig/ferrum/errors.rbs index 9c8adf8c..deedc027 100644 --- a/sig/ferrum/errors.rbs +++ b/sig/ferrum/errors.rbs @@ -12,6 +12,7 @@ module Ferrum end class EmptyPathError < Error + def initialize: (?::String message) -> void end class StatusError < Error diff --git a/spec/browser_spec.rb b/spec/browser_spec.rb index 99839cb9..464bf02b 100644 --- a/spec/browser_spec.rb +++ b/spec/browser_spec.rb @@ -282,7 +282,8 @@ def broken.puts(*) = raise(IOError, "closed stream") Ferrum::Browser.new(browser_path: path, process_timeout: 2) end.to raise_error( Ferrum::ProcessTimeoutError, - "Browser did not produce websocket url within 2 seconds, try to increase `:process_timeout`. See https://github.com/rubycdp/ferrum#customization" + "Browser did not produce websocket url within 2 seconds, try to increase `:process_timeout`. " \ + "See https://docs.rubycdp.com/docs/ferrum/customization" ) end @@ -772,7 +773,7 @@ def closed_by_peer?(socket) it "raises an error", :launch do expect do browser.go_to("/#{filename}") - end.to raise_error(Ferrum::Error, "supply absolute path for `:save_path` option") + end.to raise_error(ArgumentError, "Supply absolute path for `:save_path` option") end end diff --git a/spec/client_spec.rb b/spec/client_spec.rb index bd37790a..118d1207 100644 --- a/spec/client_spec.rb +++ b/spec/client_spec.rb @@ -29,7 +29,7 @@ def evaluate_in_background(page, expression, timeout:) it "raises NoSuchTargetError for an unknown target" do expect { page.command("Target.activateTarget", targetId: "missing") } - .to raise_error(Ferrum::NoSuchTargetError) + .to raise_error(Ferrum::NoSuchPageError, "Target.activateTarget found no target missing, it's closed or never existed") end end diff --git a/spec/context_spec.rb b/spec/context_spec.rb index 68db15ad..05f63a94 100644 --- a/spec/context_spec.rb +++ b/spec/context_spec.rb @@ -314,6 +314,11 @@ expect(target.worker.evaluate("1 + 1")).to eq(2) end + + it "raises NoSuchTargetError naming a target the context doesn't have" do + expect { browser.attach_target("missing") } + .to raise_error(Ferrum::NoSuchTargetError, /\ANo target missing in context /) + end end describe "#find_target" do diff --git a/spec/cookies_spec.rb b/spec/cookies_spec.rb index 3b934e0a..509deec4 100644 --- a/spec/cookies_spec.rb +++ b/spec/cookies_spec.rb @@ -278,6 +278,15 @@ expect(browser.cookies.map(&:domain)).to eq(["localhost"]) end + + it "raises ArgumentError without :domain or :url when base_url isn't set", :launch do + browser = Ferrum::Browser.new + + expect { browser.cookies.remove(name: "stealth") } + .to raise_error(ArgumentError, "Specify :domain or :url option") + ensure + browser&.quit + end end describe "#clear" do diff --git a/spec/downloads_spec.rb b/spec/downloads_spec.rb index 966bda64..ae09cbf1 100644 --- a/spec/downloads_spec.rb +++ b/spec/downloads_spec.rb @@ -115,7 +115,7 @@ it "raises an error" do expect do page.downloads.set_behavior(save_path: save_path) - end.to raise_error(Ferrum::Error, "supply absolute path for `:save_path` option") + end.to raise_error(ArgumentError, "Supply absolute path for `:save_path` option") page.go_to("/#{filename}") expect(File.exist?("#{save_path}/#{filename}")).to be false diff --git a/spec/keyboard_spec.rb b/spec/keyboard_spec.rb index 505339ff..1880d652 100644 --- a/spec/keyboard_spec.rb +++ b/spec/keyboard_spec.rb @@ -5,11 +5,11 @@ before { browser.go_to("/set") } it "sends down events from keyboard" do - expect { browser.keyboard.down("") }.to raise_error(ArgumentError, "empty keys passed") - expect { browser.keyboard.down([]) }.to raise_error(ArgumentError, "empty keys passed") + expect { browser.keyboard.down("") }.to raise_error(ArgumentError, "Empty keys passed") + expect { browser.keyboard.down([]) }.to raise_error(ArgumentError, "Empty keys passed") expect { browser.keyboard.down("arghhh") }.not_to raise_error expect { browser.keyboard.down(:page_down) }.not_to raise_error - expect { browser.keyboard.down(1) }.to raise_error(ArgumentError, "unexpected argument") + expect { browser.keyboard.down(1) }.to raise_error(ArgumentError, "Keys should be a String, Symbol or Array, got 1") end it "rejects a modifier key" do @@ -21,11 +21,11 @@ before { browser.go_to("/set") } it "sends up events from keyboard" do - expect { browser.keyboard.up("") }.to raise_error(ArgumentError, "empty keys passed") - expect { browser.keyboard.up([]) }.to raise_error(ArgumentError, "empty keys passed") + expect { browser.keyboard.up("") }.to raise_error(ArgumentError, "Empty keys passed") + expect { browser.keyboard.up([]) }.to raise_error(ArgumentError, "Empty keys passed") expect { browser.keyboard.up("arghhh") }.not_to raise_error expect { browser.keyboard.up(:page_down) }.not_to raise_error - expect { browser.keyboard.up(1) }.to raise_error(ArgumentError, "unexpected argument") + expect { browser.keyboard.up(1) }.to raise_error(ArgumentError, "Keys should be a String, Symbol or Array, got 1") end it "rejects a modifier key" do @@ -162,8 +162,8 @@ end it "rejects keys that are not modifiers" do - expect { browser.keyboard.hold(:enter) { nil } }.to raise_error(ArgumentError, "not a modifier key: :enter") - expect { browser.keyboard.hold(:shift) }.to raise_error(ArgumentError, "block is required") + expect { browser.keyboard.hold(:enter) { nil } }.to raise_error(ArgumentError, "Not a modifier key: :enter") + expect { browser.keyboard.hold(:shift) }.to raise_error(ArgumentError, "Block is required") end end diff --git a/spec/mouse_spec.rb b/spec/mouse_spec.rb index 73a7dd32..c5ebd6ea 100644 --- a/spec/mouse_spec.rb +++ b/spec/mouse_spec.rb @@ -181,7 +181,7 @@ def record_mouse_buttons end it "raises for an unknown button" do - expect { browser.mouse.down(button: :wheel) }.to raise_error(RuntimeError, "Invalid button: wheel") + expect { browser.mouse.down(button: :wheel) }.to raise_error(ArgumentError, "Invalid button: wheel") end it "returns itself" do @@ -207,7 +207,7 @@ def record_mouse_buttons end it "raises for an unknown button" do - expect { browser.mouse.up(button: :wheel) }.to raise_error(RuntimeError, "Invalid button: wheel") + expect { browser.mouse.up(button: :wheel) }.to raise_error(ArgumentError, "Invalid button: wheel") end it "returns itself" do diff --git a/spec/network_spec.rb b/spec/network_spec.rb index 5771a613..a32429a4 100644 --- a/spec/network_spec.rb +++ b/spec/network_spec.rb @@ -207,7 +207,7 @@ page.go_to("/with_js") expect(traffic.length).to eq(4) - expect { network.clear(:something) }.to raise_error(ArgumentError, ":type should be in [:traffic, :cache]") + expect { network.clear(:something) }.to raise_error(ArgumentError, ":type should be :traffic | :cache") expect(traffic.length).to eq(4) end diff --git a/spec/node_spec.rb b/spec/node_spec.rb index dc16823f..5ac7208f 100644 --- a/spec/node_spec.rb +++ b/spec/node_spec.rb @@ -307,8 +307,8 @@ def record_mousedowns browser.at_css("#customer_email").focus browser.at_css("#customer_email").blur - expect { node.focus }.to raise_error(Ferrum::NodeNotFoundError, "node is not trackable") - expect { node.focus }.to raise_error(Ferrum::NodeNotFoundError, "node is not trackable") + expect { node.focus }.to raise_error(Ferrum::NodeNotFoundError, "Node is not trackable") + expect { node.focus }.to raise_error(Ferrum::NodeNotFoundError, "Node is not trackable") expect(browser.evaluate("document.activeElement.id")).not_to eq("customer_email") end diff --git a/spec/page/navigation_spec.rb b/spec/page/navigation_spec.rb index 134a4eb4..a084906a 100644 --- a/spec/page/navigation_spec.rb +++ b/spec/page/navigation_spec.rb @@ -54,6 +54,15 @@ ) end + it "raises ArgumentError for a relative URL when base_url isn't set", :launch do + browser = Ferrum::Browser.new + + expect { browser.go_to("/simple") } + .to raise_error(ArgumentError, "Set :base_url browser's option or use absolute url in `go_to`, you passed: /simple") + ensure + browser&.quit + end + it "returns nil when the page doesn't load in time" do expect(page.go_to("/really_slow", timeout: 0.5)).to be_nil end diff --git a/spec/page/screenshot_spec.rb b/spec/page/screenshot_spec.rb index 3e66a04a..a59d6b02 100644 --- a/spec/page/screenshot_spec.rb +++ b/spec/page/screenshot_spec.rb @@ -362,7 +362,7 @@ def expect_scaled_screenshot(scale) browser.go_to expect do browser.screenshot(path: file, background_color: "#FFF") - end.to raise_exception(ArgumentError, "Accept Ferrum::RGBA class only") + end.to raise_exception(ArgumentError, /:background_color should be a Ferrum::RGBA, got/) end it "defaults to base64 when path isn't set" do diff --git a/spec/rgba_spec.rb b/spec/rgba_spec.rb index 30fdf09d..530e629a 100644 --- a/spec/rgba_spec.rb +++ b/spec/rgba_spec.rb @@ -7,7 +7,7 @@ Ferrum::RGBA.new(0, 0, 0, 0) end.to raise_exception( ArgumentError, - "Wrong alpha value 0 should be Float between 0.0 (fully transparent) and 1.0 (fully opaque)" + "Alpha should be a Float from 0.0 (fully transparent) to 1.0 (fully opaque), got 0" ) end @@ -16,26 +16,26 @@ Ferrum::RGBA.new(0, 0, 0, 2.0) end.to raise_exception( ArgumentError, - "Wrong alpha value 2.0 should be Float between 0.0 (fully transparent) and 1.0 (fully opaque)" + "Alpha should be a Float from 0.0 (fully transparent) to 1.0 (fully opaque), got 2.0" ) end it "raises ArgumentError for wrong value of red" do expect do Ferrum::RGBA.new(-1, 0, 0, 0.0) - end.to raise_exception(ArgumentError, "Wrong value of -1 should be Integer from 0 to 255") + end.to raise_exception(ArgumentError, "Color should be an Integer from 0 to 255, got -1") end it "raises ArgumentError for wrong value of green" do expect do Ferrum::RGBA.new(0, 256, 0, 0.0) - end.to raise_exception(ArgumentError, "Wrong value of 256 should be Integer from 0 to 255") + end.to raise_exception(ArgumentError, "Color should be an Integer from 0 to 255, got 256") end it "raises ArgumentError for wrong value of blue" do expect do Ferrum::RGBA.new(0, 0, 0.0, 0.0) - end.to raise_exception(ArgumentError, "Wrong value of 0.0 should be Integer from 0 to 255") + end.to raise_exception(ArgumentError, "Color should be an Integer from 0 to 255, got 0.0") end end