cuprite 0.20.1 → 0.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +35 -31
  3. data/lib/capybara/cuprite/deprecation.rb +8 -1
  4. data/lib/capybara/cuprite/devices.rb +8 -0
  5. data/lib/capybara/cuprite/driver/deprecations.rb +22 -184
  6. data/lib/capybara/cuprite/driver/extensions.rb +50 -0
  7. data/lib/capybara/cuprite/driver/settings.rb +102 -0
  8. data/lib/capybara/cuprite/driver/window/frames.rb +35 -0
  9. data/lib/capybara/cuprite/driver/window/modals.rb +113 -0
  10. data/lib/capybara/cuprite/driver/window.rb +34 -0
  11. data/lib/capybara/cuprite/driver/windows.rb +90 -0
  12. data/lib/capybara/cuprite/driver.rb +331 -66
  13. data/lib/capybara/cuprite/errors.rb +48 -1
  14. data/lib/capybara/cuprite/finder/hints.rb +51 -0
  15. data/lib/capybara/cuprite/finder.rb +18 -3
  16. data/lib/capybara/cuprite/javascripts/index.js +123 -58
  17. data/lib/capybara/cuprite/node/extensions.rb +14 -4
  18. data/lib/capybara/cuprite/node/typing.rb +75 -0
  19. data/lib/capybara/cuprite/node.rb +208 -63
  20. data/lib/capybara/cuprite/version.rb +3 -1
  21. data/lib/capybara/cuprite.rb +1 -4
  22. data/sig/capybara/cuprite/deprecation.rbs +7 -0
  23. data/sig/capybara/cuprite/devices.rbs +19 -0
  24. data/sig/capybara/cuprite/driver/deprecations.rbs +11 -0
  25. data/sig/capybara/cuprite/driver/extensions.rbs +29 -0
  26. data/sig/capybara/cuprite/driver/settings.rbs +42 -0
  27. data/sig/capybara/cuprite/driver/window/frames.rbs +13 -0
  28. data/sig/capybara/cuprite/driver/window/modals.rbs +29 -0
  29. data/sig/capybara/cuprite/driver/window.rbs +22 -0
  30. data/sig/capybara/cuprite/driver/windows.rbs +27 -0
  31. data/sig/capybara/cuprite/driver.rbs +140 -0
  32. data/sig/capybara/cuprite/errors.rbs +56 -0
  33. data/sig/capybara/cuprite/finder/hints.rbs +28 -0
  34. data/sig/capybara/cuprite/finder.rbs +7 -0
  35. data/sig/capybara/cuprite/node/extensions.rbs +9 -0
  36. data/sig/capybara/cuprite/node/typing.rbs +30 -0
  37. data/sig/capybara/cuprite/node.rbs +112 -0
  38. data/sig/capybara/cuprite/version.rbs +5 -0
  39. metadata +27 -11
  40. data/lib/capybara/cuprite/browser/deprecations.rb +0 -26
  41. data/lib/capybara/cuprite/browser/extensions.rb +0 -59
  42. data/lib/capybara/cuprite/browser.rb +0 -108
  43. data/lib/capybara/cuprite/node/deprecations.rb +0 -43
  44. data/lib/capybara/cuprite/options.rb +0 -33
  45. data/lib/capybara/cuprite/page/frames.rb +0 -47
  46. data/lib/capybara/cuprite/page/modals.rb +0 -118
  47. data/lib/capybara/cuprite/page.rb +0 -36
@@ -1,15 +1,54 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "forwardable"
4
+ require "rack"
4
5
  require "capybara/cuprite/finder"
5
6
  require "capybara/cuprite/driver/deprecations"
6
7
  require "capybara/cuprite/driver/extensions"
8
+ require "capybara/cuprite/driver/settings"
9
+ require "capybara/cuprite/driver/window"
10
+ require "capybara/cuprite/driver/windows"
7
11
 
8
12
  module Capybara
9
13
  module Cuprite
14
+ # Capybara driver for Chrome, built on Ferrum.
15
+ #
16
+ # The driver keeps what Capybara needs and Ferrum doesn't have, and leaves the rest to a plain Ferrum browser:
17
+ #
18
+ # Driver
19
+ # ├─ browser Ferrum::Browser
20
+ # │ └─ on_page sets up every new page: Cuprite's JS, viewport, user agent, URL lists, JS errors
21
+ # ├─ current_page Ferrum::Page of Capybara's current window
22
+ # ├─ window Window, that window's frames and dialogs
23
+ # │ ├─ Frames the frame switched to, current_frame
24
+ # │ └─ Modals the dialogs to answer, the unhandled dialog error
25
+ # ├─ Windows window handles, opening, switching, closing
26
+ # ├─ Settings the options only Cuprite handles
27
+ # └─ Extensions debug, URL lists, raise_on_unhandled_modal
28
+ #
29
+ # Node wraps a Ferrum::Node and works in current_frame and current_page, Finder finds nodes in a frame.
30
+ #
31
+ # @example Register the driver
32
+ # Capybara.register_driver(:cuprite) do |app|
33
+ # Capybara::Cuprite::Driver.new(app, window_size: [1200, 800])
34
+ # end
10
35
  class Driver < Capybara::Driver::Base
36
+ # The window size `maximize_window` resizes to unless `screen_size:` is given.
11
37
  DEFAULT_MAXIMIZE_SCREEN_SIZE = [1366, 768].freeze
38
+ # The path of the JavaScript Cuprite adds to every page.
39
+ # @api private
12
40
  EXTENSION = File.expand_path("javascripts/index.js", __dir__)
41
+ # The JavaScript Cuprite adds to every page.
42
+ # @api private
43
+ EXTENSION_JS = File.read(EXTENSION).freeze
44
+ # The options Cuprite handles itself and doesn't pass to Ferrum.
45
+ # @api private
46
+ CUPRITE_OPTIONS = %i[js_errors pending_connection_errors].freeze
47
+ # The case-insensitive Hash class `response_headers` returns.
48
+ # @api private
49
+ RESPONSE_HEADERS = defined?(Rack::Headers) ? Rack::Headers : Rack::Utils::HeaderHash
50
+ # The wrapper that turns an async script's callback into a Promise.
51
+ # @api private
13
52
  CALLBACK_JS = <<~JS
14
53
  function(...args) {
15
54
  return new Promise((resolve, reject) => {
@@ -25,32 +64,73 @@ module Capybara
25
64
  JS
26
65
 
27
66
  extend Forwardable
28
- include Deprecations
29
67
  include Extensions
30
-
31
- delegate %i[quit current_url title
32
- window_handles current_window_handle close_window switch_to_window
33
- refresh] => :browser
68
+ include Windows
69
+
70
+ # @!method title
71
+ # @return [String] the title of the current page
72
+ # @!method refresh
73
+ # Reloads the current page.
74
+ # @return [void]
75
+ delegate %i[title refresh] => :current_page
76
+ # @!method send_keys(*keys)
77
+ # Types keys into the focused element, see {Node#send_keys}.
78
+ # @param keys [Array<String, Symbol, Array>]
79
+ # @return [void]
34
80
  delegate %i[send_keys] => :active_element
35
- def_delegator :browser, :body, :html
36
- def_delegator :browser, :back, :go_back
37
- def_delegator :browser, :forward, :go_forward
38
-
39
- attr_reader :app, :options
40
-
81
+ # @!method current_url
82
+ # @return [String] the URL of the current page
83
+ def_delegator :current_page, :url, :current_url
84
+ # @!method html
85
+ # @return [String] the HTML of the current page or frame
86
+ delegate %i[html] => :current_frame
87
+ # @!method go_back
88
+ # Navigates back in history.
89
+ # @return [void]
90
+ def_delegator :current_page, :back, :go_back
91
+ # @!method go_forward
92
+ # Navigates forward in history.
93
+ # @return [void]
94
+ def_delegator :current_page, :forward, :go_forward
95
+
96
+ # @return [#call] the Rack application under test
97
+ attr_reader :app
98
+ # @return [Hash] the options the browser is started with
99
+ attr_reader :options
100
+
101
+ # Every Ferrum option is accepted as well, see Ferrum's docs.
102
+ #
103
+ # @param app [#call] the Rack application under test
104
+ # @param options [Hash]
105
+ # @option options [Boolean] :js_errors re-raise JavaScript errors from the page as `Ferrum::JavaScriptError`,
106
+ # `false` by default
107
+ # @option options [Boolean] :pending_connection_errors raise {PendingConnectionsError} from `visit` when the
108
+ # page doesn't load in time, `true` by default
109
+ # @option options [Array(Integer, Integer)] :screen_size the size `maximize_window` resizes to,
110
+ # {DEFAULT_MAXIMIZE_SCREEN_SIZE} by default
111
+ # @option options [Boolean] :raise_on_unhandled_modal raise {UnhandledModalError} instead of warning when a
112
+ # dialog isn't handled, `false` by default
113
+ # @option options [Array<Regexp>] :url_blocklist requests to block, alias `:url_blacklist`
114
+ # @option options [Array<Regexp>] :url_allowlist requests to allow, alias `:url_whitelist`
115
+ # @option options [Symbol] :emulate a device from {Devices::LIST} to emulate
116
+ # @option options [Boolean] :mobile emulate a mobile device, `false` by default
117
+ # @option options [Numeric] :scale_factor the device scale factor to emulate, `0` (browser default) by default
41
118
  def initialize(app, options = {})
42
119
  @app = app
43
120
  @options = options.dup
44
121
  @started = false
122
+ @current_page = nil
123
+ @page_closed = false
124
+ @windows = {}
45
125
 
46
- @options[:extensions] ||= []
47
- @options[:extensions] << EXTENSION
126
+ @options[:init_scripts] = [*@options[:init_scripts], EXTENSION]
48
127
 
49
128
  @screen_size = @options.delete(:screen_size)
50
129
  @screen_size ||= DEFAULT_MAXIMIZE_SCREEN_SIZE
51
130
  @options[:save_path] ||= File.expand_path(Capybara.save_path) if Capybara.save_path
52
131
 
53
- @options[:pending_connection_errors] = true unless @options.key?(:pending_connection_errors)
132
+ @options[:url_blacklist] = @options.delete(:url_blocklist) if @options.key?(:url_blocklist)
133
+ @options[:url_whitelist] = @options.delete(:url_allowlist) if @options.key?(:url_allowlist)
54
134
 
55
135
  # It's set for debug() to make devtools tab open correctly.
56
136
  @options[:browser_options] ||= {}
@@ -62,187 +142,372 @@ module Capybara
62
142
  super()
63
143
  end
64
144
 
145
+ # @return [true] Cuprite runs the app in a server
65
146
  def needs_server?
66
147
  true
67
148
  end
68
149
 
150
+ # The Ferrum browser, started on first use. Reach for it for browser-wide settings such as `timeout`, and for
151
+ # pages through {#current_page}.
152
+ #
153
+ # @return [Ferrum::Browser]
154
+ # @raise [ArgumentError] for a URL pattern that isn't a Regexp, both URL lists, or an unknown device
69
155
  def browser
70
- @browser ||= Browser.new({ base_url: capybara_base_url }.compact.merge(@options))
156
+ @browser ||= start_browser
157
+ end
158
+
159
+ # The Ferrum page of Capybara's current window, the one it's switched to at the moment. The driver runs Capybara's
160
+ # calls on it, and it's the way to use Ferrum in that window, because `browser.page` is always the first window,
161
+ # even inside `within_window`.
162
+ #
163
+ # @example
164
+ # within_window(new_window) { page.driver.current_page.network.traffic }
165
+ #
166
+ # @return [Ferrum::Page] the first window's page until Capybara switches to another one
167
+ # @raise [Ferrum::NoSuchPageError] when the current window was closed
168
+ def current_page
169
+ raise Ferrum::NoSuchPageError if @page_closed
170
+
171
+ @current_page ||= browser.page
172
+ end
173
+
174
+ # @api private
175
+ # @return [Window] the frames and dialogs Cuprite keeps for the current window
176
+ def window
177
+ @windows.fetch(current_page.target_id)
178
+ end
179
+
180
+ # @api private
181
+ # @return [Ferrum::Frame] the frame switched to in the current page
182
+ def current_frame
183
+ window.current_frame
71
184
  end
72
185
 
186
+ # Navigates to a URL, relative ones against Capybara's `app_host` or server.
187
+ #
188
+ # @param url [String]
189
+ # @return [void]
190
+ # @raise [PendingConnectionsError] with `pending_connection_errors` when the page doesn't load in time
73
191
  def visit(url)
74
192
  @started = true
75
193
  browser.base_url = url if url.match?(%r{\Ahttps?://})
76
- browser.goto(url)
194
+ check_modals { navigate(url) }
77
195
  end
78
196
 
197
+ # @return [Integer, nil] the HTTP status of the last response
79
198
  def status_code
80
- browser.network.status
199
+ current_page.network.status
81
200
  end
82
201
 
202
+ # @return [String] the URL of the current frame
83
203
  def frame_url
84
204
  evaluate_script("window.location.href")
85
205
  end
86
206
 
207
+ # @return [String] the title of the current frame
87
208
  def frame_title
88
209
  evaluate_script("document.title")
89
210
  end
90
211
 
212
+ # @return [Node] the focused element
91
213
  def active_element
92
- Node.new(self, browser.evaluate("document.activeElement"))
214
+ Node.new(self, current_frame.evaluate("document.activeElement"))
93
215
  end
94
216
 
95
- def find_xpath(selector)
96
- find(:xpath, selector)
217
+ # @param selector [String]
218
+ # @param hints [Hash] Capybara's finder hints
219
+ # @return [Array<Node>] the elements matching the XPath
220
+ # @raise [InvalidSelector]
221
+ def find_xpath(selector, **hints)
222
+ find(:xpath, selector, **hints)
97
223
  end
98
224
 
99
- def find_css(selector)
100
- find(:css, selector)
225
+ # @param selector [String]
226
+ # @param hints [Hash] Capybara's finder hints
227
+ # @return [Array<Node>] the elements matching the CSS selector
228
+ # @raise [InvalidSelector]
229
+ def find_css(selector, **hints)
230
+ find(:css, selector, **hints)
101
231
  end
102
232
 
233
+ # Evaluates a JavaScript expression, with `arguments` set to `args`.
234
+ #
235
+ # @param script [String]
236
+ # @param args [Array] values passed to the script, nodes as elements
237
+ # @return [Object] the result, elements as {Node}
103
238
  def evaluate_script(script, *args)
104
- result = browser.evaluate(script, *native_args(args))
239
+ result = check_modals { current_frame.evaluate(script, *native_args(args)) }
105
240
  unwrap_script_result(result)
106
241
  end
107
242
 
243
+ # Evaluates JavaScript that calls the callback passed as its last argument, waiting up to Capybara's
244
+ # `default_max_wait_time`.
245
+ #
246
+ # @param script [String]
247
+ # @param args [Array] values passed to the script, nodes as elements
248
+ # @return [Object] the value passed to the callback, elements as {Node}
108
249
  def evaluate_async_script(script, *args)
109
- result = browser.evaluate(CALLBACK_JS.sub("SCRIPT") { script }, *native_args(args), timeout: session_wait_time)
250
+ result = check_modals do
251
+ current_frame.evaluate(CALLBACK_JS.sub("SCRIPT") { script }, *native_args(args), timeout: session_wait_time)
252
+ end
110
253
  unwrap_script_result(result)
111
254
  end
112
255
 
256
+ # Executes JavaScript, with `arguments` set to `args`.
257
+ #
258
+ # @param script [String]
259
+ # @param args [Array] values passed to the script, nodes as elements
260
+ # @return [nil]
113
261
  def execute_script(script, *args)
114
- browser.execute(script, *native_args(args))
262
+ check_modals { current_frame.execute(script, *native_args(args)) }
115
263
  nil
116
264
  end
117
265
 
266
+ # @param locator [Capybara::Node::Element, Node, :parent, :top] the frame element, or the parent or top frame
267
+ # @return [void]
268
+ # @raise [ArgumentError] for any other locator
118
269
  def switch_to_frame(locator)
119
270
  handle = case locator
120
271
  when Capybara::Node::Element
121
- locator.native.node.description["frameId"]
272
+ locator.native.node.frame_id
122
273
  when Capybara::Cuprite::Node
123
- locator.node.description["frameId"]
274
+ locator.node.frame_id
124
275
  when :parent, :top
125
276
  locator
126
277
  end
127
278
 
128
279
  raise ArgumentError, "Unable to switch to frame from #{locator.class}" unless handle
129
280
 
130
- browser.page.switch_to_frame(handle)
131
- end
132
-
133
- def open_new_window
134
- browser.open_new_window
281
+ window.switch_to_frame(handle)
135
282
  end
136
283
 
137
- def no_such_window_error
138
- Ferrum::NoSuchPageError
284
+ # Closes the browser.
285
+ #
286
+ # @return [void]
287
+ def quit
288
+ @browser&.quit
289
+ ensure
290
+ @windows.clear
291
+ forget_page
139
292
  end
140
293
 
294
+ # Resets the browser between tests: starts a fresh browser context and restores the options.
295
+ #
296
+ # @return [void]
141
297
  def reset!
142
- @zoom_factor = nil
143
- @paper_size = nil
144
- browser.url_blacklist = @options[:url_blacklist]
145
- browser.url_whitelist = @options[:url_whitelist]
146
- browser.raise_on_unhandled_modal = @options.fetch(:raise_on_unhandled_modal, false)
147
- browser.reset
298
+ return unless @browser
299
+
300
+ reset_browser
148
301
  base_url = @options[:base_url] || capybara_base_url
149
302
  browser.base_url = base_url if base_url
150
303
  ensure
151
304
  @started = false
152
305
  end
153
306
 
307
+ # Saves a screenshot, or a PDF when the path ends in `.pdf`.
308
+ #
309
+ # @param path [String]
310
+ # @param options [Hash] the options of Ferrum's `screenshot` or `pdf`, like `full:` or `selector:`
311
+ # @return [void]
154
312
  def save_screenshot(path, options = {})
155
- options[:scale] = @zoom_factor if @zoom_factor
156
-
157
313
  if File.extname(path) == ".pdf"
158
- options[:paperWidth] = @paper_size[:width].to_f if @paper_size
159
- options[:paperHeight] = @paper_size[:height].to_f if @paper_size
160
- browser.pdf(path: path, **options)
314
+ current_page.pdf(path: path, **options)
161
315
  else
162
- browser.screenshot(path: path, **options)
316
+ current_page.screenshot(path: path, **options)
163
317
  end
164
318
  end
165
319
 
320
+ # @param handle [String]
321
+ # @param width [Integer]
322
+ # @param height [Integer]
323
+ # @return [void]
324
+ # @raise [Ferrum::NoSuchPageError] when there's no such window
166
325
  def resize_window_to(handle, width, height)
167
326
  within_window(handle) do
168
- browser.resize(width: width, height: height)
327
+ settings.window_size = [width, height]
328
+ current_page.resize(width: width, height: height)
329
+ emulate_viewport(current_page, width, height)
169
330
  end
170
331
  end
171
332
 
333
+ # Resizes a window to `screen_size:`.
334
+ #
335
+ # @param handle [String]
336
+ # @return [void]
337
+ # @raise [Ferrum::NoSuchPageError] when there's no such window
172
338
  def maximize_window(handle)
173
339
  resize_window_to(handle, *screen_size)
174
340
  end
175
341
 
342
+ # @param handle [String]
343
+ # @return [Array(Integer, Integer)] the inner width and height of the window
344
+ # @raise [Ferrum::NoSuchPageError] when there's no such window
176
345
  def window_size(handle)
177
346
  within_window(handle) do
178
347
  evaluate_script("[window.innerWidth, window.innerHeight]")
179
348
  end
180
349
  end
181
350
 
351
+ # @param handle [String]
352
+ # @return [void]
353
+ # @raise [Ferrum::NoSuchPageError] when there's no such window
182
354
  def fullscreen_window(handle)
183
355
  within_window(handle) do
184
- browser.resize(fullscreen: true)
356
+ settings.window_size = [nil, nil]
357
+ current_page.resize(fullscreen: true)
358
+ emulate_viewport(current_page, *current_page.document_size)
185
359
  end
186
360
  end
187
361
 
362
+ # The headers of the last response, looked up case-insensitively as with rack_test.
363
+ #
364
+ # @return [Hash{String => String}, nil] `Rack::Headers`, or `Rack::Utils::HeaderHash` on Rack 2
188
365
  def response_headers
189
- browser.network.response&.headers
366
+ headers = current_page.network.response&.headers
367
+ RESPONSE_HEADERS[headers] if headers
190
368
  end
191
369
 
370
+ # @return [true] Capybara waits for elements with Cuprite
192
371
  def wait?
193
372
  true
194
373
  end
195
374
 
375
+ # @return [Array<Class>] the errors after which Capybara looks the element up again
196
376
  def invalid_element_errors
197
377
  [Capybara::Cuprite::ObsoleteNode,
198
378
  Capybara::Cuprite::MouseEventFailed,
199
379
  Ferrum::CoordinatesNotFoundError,
200
380
  Ferrum::NoExecutionContextError,
201
- Ferrum::NodeNotFoundError]
202
- end
203
-
381
+ Ferrum::ExecutionContextDestroyedError,
382
+ Ferrum::NodeNotFoundError,
383
+ Ferrum::ForeignObjectError]
384
+ end
385
+
386
+ # Accepts the dialog the block opens.
387
+ #
388
+ # @param type [:alert, :confirm, :prompt]
389
+ # @param options [Hash]
390
+ # @option options [String, Regexp] :text the text the dialog has to match
391
+ # @option options [String] :with the response to a prompt
392
+ # @option options [Numeric] :wait how long to wait for the dialog
393
+ # @yield the action that opens the dialog
394
+ # @return [String] the dialog's message
395
+ # @raise [Capybara::ModalNotFound] when no matching dialog opens in time
204
396
  def accept_modal(type, options = {})
205
397
  case type
206
398
  when :alert, :confirm
207
- browser.page.accept_confirm
399
+ window.accept_confirm
208
400
  when :prompt
209
- browser.page.accept_prompt(options[:with])
401
+ window.accept_prompt(options[:with])
210
402
  end
211
403
 
212
404
  yield if block_given?
213
405
 
214
- browser.page.find_modal(options)
406
+ window.find_modal(options)
215
407
  end
216
408
 
409
+ # Dismisses the dialog the block opens.
410
+ #
411
+ # @param type [:confirm, :prompt]
412
+ # @param options [Hash]
413
+ # @option options [String, Regexp] :text the text the dialog has to match
414
+ # @option options [Numeric] :wait how long to wait for the dialog
415
+ # @yield the action that opens the dialog
416
+ # @return [String] the dialog's message
417
+ # @raise [Capybara::ModalNotFound] when no matching dialog opens in time
217
418
  def dismiss_modal(type, options = {})
218
419
  case type
219
420
  when :confirm
220
- browser.page.dismiss_confirm
421
+ window.dismiss_confirm
221
422
  when :prompt
222
- browser.page.dismiss_prompt
423
+ window.dismiss_prompt
223
424
  end
224
425
 
225
426
  yield if block_given?
226
427
 
227
- browser.page.find_modal(options)
428
+ window.find_modal(options)
228
429
  end
229
430
 
230
431
  private
231
432
 
232
433
  attr_reader :screen_size
233
434
 
234
- def find(method, selector)
235
- Finder.find(browser, method, selector).map { |native| Node.new(self, native) }
435
+ def find(method, selector, **hints)
436
+ nodes = check_modals { Finder.find(current_frame, method, selector, **hints) }
437
+ nodes.map { |native, cache| Node.new(self, native, cache) }
438
+ end
439
+
440
+ def check_modals(&)
441
+ window.check_modals(&)
236
442
  end
237
443
 
238
- def within_window(handle)
239
- original = browser.current_window_handle
240
- raise Ferrum::NoSuchPageError unless browser.window_handles.include?(handle)
444
+ def start_browser
445
+ options = { base_url: capybara_base_url }.compact.merge(@options)
446
+ device = options[:emulate]
447
+ options = Devices.fetch(device).except(:user_agent).merge(options) if device
241
448
 
242
- browser.switch_to_window(handle)
243
- yield
449
+ browser = Ferrum::Browser.new(options.except(*CUPRITE_OPTIONS))
450
+ @settings = Settings.new(options, browser.options.window_size)
451
+ browser.on_page { |page| prepare_page(page) }
452
+ Deprecations.extend_browser(browser, self)
453
+ browser
454
+ rescue StandardError
455
+ browser&.quit
456
+ raise
457
+ end
458
+
459
+ def reset_browser
460
+ @windows.clear
461
+ browser.contexts.reset
462
+ rescue Ferrum::DeadBrowserError
463
+ browser.restart
244
464
  ensure
245
- browser.switch_to_window(original)
465
+ @settings.reset
466
+ forget_page
467
+ end
468
+
469
+ def settings
470
+ browser
471
+ @settings
472
+ end
473
+
474
+ def navigate(url)
475
+ return current_page.go_to(url) unless settings.pending_connection_errors?
476
+
477
+ current_page.go_to!(url)
478
+ rescue Ferrum::NavigationTimeoutError => e
479
+ raise if Ferrum::Deadline.current&.expired?
480
+
481
+ raise PendingConnectionsError.new(e.url, e.pendings)
482
+ end
483
+
484
+ def prepare_page(page)
485
+ @windows[page.target_id] = Window.new(page, @settings)
486
+ subscribe_to_js_errors(page) if @settings.js_errors?
487
+ page.execute(EXTENSION_JS)
488
+
489
+ width, height = @settings.window_size
490
+ page.resize(width: width, height: height) if width && height
491
+ emulate_viewport(page, width, height)
492
+ emulate_device_user_agent(page) if @settings.device_user_agent?
493
+
494
+ page.network.blacklist = @settings.url_blacklist if @settings.url_blacklist.any?
495
+ page.network.whitelist = @settings.url_whitelist if @settings.url_whitelist.any?
496
+ end
497
+
498
+ def subscribe_to_js_errors(page)
499
+ page.on("Runtime.exceptionThrown") do |params|
500
+ Thread.main.raise Ferrum::JavaScriptError, params["exceptionDetails"]
501
+ end
502
+ end
503
+
504
+ def emulate_viewport(page, width, height)
505
+ page.set_viewport(width: width || 0, height: height || 0, scale_factor: @settings.scale_factor,
506
+ mobile: @settings.mobile)
507
+ end
508
+
509
+ def emulate_device_user_agent(page)
510
+ page.network.emulate(user_agent: @settings.user_agent(browser.default_user_agent))
246
511
  end
247
512
 
248
513
  def capybara_base_url
@@ -2,32 +2,48 @@
2
2
 
3
3
  module Capybara
4
4
  module Cuprite
5
+ # The base of Cuprite's errors.
5
6
  class Error < StandardError; end
6
7
 
8
+ # An error the browser reported.
7
9
  class ClientError < Error
10
+ # @return [Object] what the browser responded with
8
11
  attr_reader :response
9
12
 
13
+ # @param response [Object] what the browser responded with
10
14
  def initialize(response)
11
15
  @response = response
12
16
  super()
13
17
  end
14
18
  end
15
19
 
20
+ # Raised by the finders for a selector the browser can't parse.
16
21
  class InvalidSelector < ClientError
22
+ # @param response [Object] what the browser responded with
23
+ # @param method [:css, :xpath]
24
+ # @param selector [String]
17
25
  def initialize(response, method, selector)
18
26
  super(response)
19
27
  @method = method
20
28
  @selector = selector
21
29
  end
22
30
 
31
+ # @return [String]
23
32
  def message
24
33
  "Browser raised error trying to find #{@method}: #{@selector.inspect}"
25
34
  end
26
35
  end
27
36
 
37
+ # Raised by a click when another element, overlapping this one, would receive it.
28
38
  class MouseEventFailed < ClientError
29
- attr_reader :name, :selector, :position
39
+ # @return [String] the mouse event, like `"click"`
40
+ attr_reader :name
41
+ # @return [String] the CSS selector of the overlapping element
42
+ attr_reader :selector
43
+ # @return [Array(Float, Float)] the coordinates of the event
44
+ attr_reader :position
30
45
 
46
+ # Parses the browser's `"MouseEventFailed: <name>, <selector>, <x>, <y>"` response.
31
47
  def initialize(*)
32
48
  super
33
49
  data = /\A\w+: (\w+), (.+?), ([\d.-]+), ([\d.-]+)/.match(@response)
@@ -35,6 +51,7 @@ module Capybara
35
51
  @position = data.values_at(3, 4).map(&:to_f)
36
52
  end
37
53
 
54
+ # @return [String]
38
55
  def message
39
56
  "Firing a #{name} at coordinates [#{position.join(', ')}] failed. Cuprite detected " \
40
57
  "another element with CSS selector \"#{selector}\" at this position. " \
@@ -43,23 +60,53 @@ module Capybara
43
60
  end
44
61
  end
45
62
 
63
+ # Raised with `raise_on_unhandled_modal: true` when a dialog opens outside `accept_*` or `dismiss_*`.
46
64
  class UnhandledModalError < Error
65
+ # @return [String]
47
66
  attr_reader :message
48
67
 
68
+ # @param message [String]
49
69
  def initialize(message)
50
70
  @message = message
51
71
  super()
52
72
  end
53
73
  end
54
74
 
75
+ # Raised by `visit` with `pending_connection_errors: true` when the page doesn't load in time.
76
+ class PendingConnectionsError < Ferrum::StatusError
77
+ # @return [String] the URL being loaded
78
+ attr_reader :url
79
+ # @return [Array<String>] the URLs of the requests still pending
80
+ attr_reader :pendings
81
+
82
+ # @param url [String] the URL being loaded
83
+ # @param pendings [Array<String>] the URLs of the requests still pending
84
+ def initialize(url, pendings = [])
85
+ super(url)
86
+ @url = url
87
+ @pendings = pendings
88
+ end
89
+
90
+ # @return [String]
91
+ def message
92
+ message = "Request to #{@url} reached server, but there are still pending connections"
93
+ @pendings.empty? ? message : "#{message}: #{@pendings.join(', ')}"
94
+ end
95
+ end
96
+
97
+ # Raised when an element is no longer in the DOM. Capybara finds it again and retries.
55
98
  class ObsoleteNode < ClientError
99
+ # @return [Node] the element
56
100
  attr_reader :node
57
101
 
102
+ # @param node [Node] the element
103
+ # @param response [Object, nil] what the browser responded with
58
104
  def initialize(node, response)
59
105
  @node = node
60
106
  super(response)
61
107
  end
62
108
 
109
+ # @return [String]
63
110
  def message
64
111
  "The element you are trying to interact with is either not part of the DOM, or is " \
65
112
  "not currently visible on the page (perhaps display: none is set). " \