testsurfer 0.5.0

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.
@@ -0,0 +1,537 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "capybara"
4
+ require "testsurfer"
5
+
6
+ module Testsurfer
7
+ # A Capybara driver on testsurfer: Rails system tests and Capybara
8
+ # specs drive the OS web view through vibesurfer.
9
+ #
10
+ # require "testsurfer/capybara"
11
+ # Capybara.default_driver = :testsurfer # or, in Rails:
12
+ # driven_by :testsurfer # ApplicationSystemTestCase
13
+ module Capybara
14
+ # A node whose element is gone (its document changed or it was removed).
15
+ class StaleElementError < Testsurfer::Error
16
+ def kind = :stale
17
+ end
18
+
19
+ # An action whose element did not become actionable in time; Capybara retries it.
20
+ class NotInteractableError < Testsurfer::Error
21
+ def kind = :not_interactable
22
+ end
23
+
24
+ # The window a call names is closed.
25
+ class NoSuchWindowError < Testsurfer::Error
26
+ def kind = :no_such_window
27
+ end
28
+
29
+ class Driver < ::Capybara::Driver::Base
30
+ # A pending accept_modal or dismiss_modal.
31
+ Expectation = Struct.new(:accept, :text, :with, :slot)
32
+
33
+ attr_reader :app, :options
34
+
35
+ # Options: launch options for the browser (base_url:, timeout:,
36
+ # viewport: { width:, height: }, input_mode:, ...) and context:
37
+ # (BrowserContext options, such as locale: or color_scheme:).
38
+ def initialize(app, context: {}, **launch)
39
+ super()
40
+ @app = app
41
+ @launch = { viewport: { width: 1280, height: 720 } }.merge(launch)
42
+ @context_options = context
43
+ @options = launch
44
+ @browser = nil
45
+ @context = nil
46
+ @page = nil
47
+ @frames = [] # handle ids of the iframes switched into, outermost first
48
+ @handles = {}
49
+ @handle_seq = 0
50
+ @expectations = []
51
+ @modal_lock = Monitor.new
52
+ end
53
+
54
+ def needs_server?
55
+ true
56
+ end
57
+
58
+ def wait?
59
+ true
60
+ end
61
+
62
+ def browser
63
+ @browser ||= Testsurfer::Browser.launch(**@launch)
64
+ end
65
+
66
+ # The page Capybara is on.
67
+ def page
68
+ start unless @page
69
+ raise NoSuchWindowError, "the current window is closed" if @page.closed?
70
+
71
+ @page
72
+ end
73
+
74
+ def visit(url)
75
+ @frames.clear
76
+ page.goto(url)
77
+ nil
78
+ end
79
+
80
+ # Reload (a POST is sent again) and wait for the new document.
81
+ def refresh
82
+ @frames.clear
83
+ before = page.engine_call("E.doc")
84
+ # WebKit reloads a POST result with a GET; send the POST again, as other browsers do.
85
+ last = last_response&.request
86
+ repost = last && last.method == "POST" && last.post_data_buffer
87
+ if repost
88
+ headers = last.headers.select { |k, _| k == "content-type" }
89
+ page.route(last.url, times: 1) { |r| r.continue(method: "POST", post_data: repost, headers: r.request.headers.merge(headers)) }
90
+ end
91
+ page.evaluate("(setTimeout(function(){location.reload();},0), null)")
92
+ deadline = Testsurfer.now + page.timeouts.navigation / 1000.0
93
+ loop do
94
+ begin
95
+ break if page.engine_call("E.doc") != before && page.evaluate("document.readyState") == "complete"
96
+ rescue Testsurfer::ContextDestroyedError
97
+ nil
98
+ end
99
+ raise Testsurfer::TimeoutError, "refresh: the page did not load again" if Testsurfer.now >= deadline
100
+
101
+ sleep 0.02
102
+ end
103
+ nil
104
+ ensure
105
+ page.unroute(last.url) if repost
106
+ end
107
+
108
+ def current_url
109
+ page.evaluate("location.href")
110
+ end
111
+
112
+ # The top-level document's title.
113
+ def title
114
+ page.evaluate("document.title")
115
+ end
116
+
117
+ def frame_title
118
+ frame_eval("document.title")
119
+ end
120
+
121
+ def frame_url
122
+ frame_eval("location.href")
123
+ end
124
+
125
+ def html
126
+ frame_eval("(function(){var d=document.doctype;return (d?'<!DOCTYPE '+d.name+'>':'')+document.documentElement.outerHTML;})()")
127
+ end
128
+
129
+ def go_back
130
+ page.go_back
131
+ end
132
+
133
+ def go_forward
134
+ page.go_forward
135
+ end
136
+
137
+ def find_xpath(query, **_options)
138
+ find_in(nil, Query.new(:xpath, xpath: Driver.drop_empty_predicates(query)))
139
+ end
140
+
141
+ # Capybara writes `[]` for a Symbol text filter; Chrome's XPath takes
142
+ # an empty predicate as true, WebKit's refuses it. Drop them outside strings.
143
+ def self.drop_empty_predicates(xpath)
144
+ out = +""
145
+ quote = nil
146
+ i = 0
147
+ while i < xpath.length
148
+ c = xpath[i]
149
+ if quote
150
+ quote = nil if c == quote
151
+ elsif c == "'" || c == '"'
152
+ quote = c
153
+ elsif c == "[" && xpath[i + 1] == "]"
154
+ i += 2
155
+ next
156
+ end
157
+ out << c
158
+ i += 1
159
+ end
160
+ out
161
+ end
162
+
163
+ def find_css(query, **_options)
164
+ find_in(nil, Query.new(:css, selector: query, light: true))
165
+ end
166
+
167
+ # Run `script` as a function body with `args` as `arguments`.
168
+ def execute_script(script, *args)
169
+ run_script(script, args, returns: false)
170
+ nil
171
+ end
172
+
173
+ # The value of the expression `script`, with `args` as `arguments`.
174
+ def evaluate_script(script, *args)
175
+ run_script("return #{script.strip.sub(/;+\z/, '')}", args, returns: true)
176
+ end
177
+
178
+ # Run `script` with a callback as its last argument; its value is what the callback gets.
179
+ def evaluate_async_script(script, *args)
180
+ wait_ms = (session_options.default_max_wait_time * 1000).to_i
181
+ run_script(script, args, returns: true, async: wait_ms)
182
+ end
183
+
184
+ def save_screenshot(path, **options)
185
+ page.screenshot(path: path.to_s, full_page: options[:full] || options[:full_page] || false)
186
+ end
187
+
188
+ # The headers of the last main-document response, when the context reports one.
189
+ def response_headers
190
+ Headers.new(last_response&.headers || {})
191
+ end
192
+
193
+ # Response headers by any case of their name.
194
+ class Headers < Hash
195
+ def initialize(h)
196
+ super()
197
+ h.each { |k, v| self[k.downcase] = v }
198
+ end
199
+
200
+ def [](k)
201
+ super(k.to_s.downcase)
202
+ end
203
+
204
+ def fetch(k, *rest, &blk)
205
+ super(k.to_s.downcase, *rest, &blk)
206
+ end
207
+
208
+ def key?(k)
209
+ super(k.to_s.downcase)
210
+ end
211
+ end
212
+
213
+ def status_code
214
+ last_response&.status
215
+ end
216
+
217
+ # Keys to the focused element (see Node#send_keys for the key names).
218
+ def send_keys(*keys)
219
+ Keys.send_keys(page, keys)
220
+ end
221
+
222
+ def active_element
223
+ nodes = wrap_result(frame_eval_raw("(function(){var a=document.activeElement;return a?#{WRAP}(a):null;})()"))
224
+ nodes
225
+ end
226
+
227
+ def switch_to_frame(frame)
228
+ case frame
229
+ when :top then @frames.clear
230
+ when :parent then @frames.pop
231
+ else
232
+ node = frame.is_a?(::Capybara::Node::Element) ? frame.base : frame
233
+ node.check!
234
+ @frames.push(node.handle)
235
+ end
236
+ nil
237
+ end
238
+
239
+ # --- windows ------------------------------------------------------
240
+
241
+ def current_window_handle
242
+ handle_of(page)
243
+ end
244
+
245
+ def window_handles
246
+ start unless @page
247
+ @context.pages.reject(&:closed?).map { |p| handle_of(p) }
248
+ end
249
+
250
+ def open_new_window(_kind = :tab)
251
+ p = @context.new_page
252
+ p.ensure_open
253
+ watch_dialogs(p)
254
+ handle_of(p)
255
+ end
256
+
257
+ def switch_to_window(handle)
258
+ p = page_for(handle)
259
+ raise NoSuchWindowError, "no window with handle #{handle}" unless p
260
+
261
+ @page = p
262
+ @frames.clear
263
+ settle(p)
264
+ nil
265
+ end
266
+
267
+ # A popup is reported as it opens, on its first blank document: wait
268
+ # for the document it was opened with, so scripts run in that one.
269
+ def settle(p)
270
+ want_blank = p.url.start_with?("about:")
271
+ deadline = Testsurfer.now + p.timeouts.navigation / 1000.0
272
+ while Testsurfer.now < deadline
273
+ begin
274
+ href, state = p.evaluate("[location.href, document.readyState]")
275
+ return if state == "complete" && (want_blank || !href.start_with?("about:"))
276
+ rescue Testsurfer::Error
277
+ return if p.closed?
278
+ end
279
+ sleep 0.02
280
+ end
281
+ end
282
+
283
+ def close_window(handle)
284
+ p = page_for(handle)
285
+ raise NoSuchWindowError, "no window with handle #{handle}" unless p
286
+
287
+ p.close
288
+ nil
289
+ end
290
+
291
+ def window_size(handle)
292
+ within_window(handle) { |p| p.evaluate("[window.outerWidth || window.innerWidth, window.outerHeight || window.innerHeight]") }
293
+ end
294
+
295
+ def resize_window_to(handle, width, height)
296
+ within_window(handle) { |p| p.set_viewport_size(width: width, height: height) }
297
+ nil
298
+ end
299
+
300
+ def maximize_window(handle)
301
+ within_window(handle) do |p|
302
+ w, h = p.evaluate("[screen.availWidth, screen.availHeight]")
303
+ p.set_viewport_size(width: w, height: h)
304
+ end
305
+ nil
306
+ end
307
+
308
+ def fullscreen_window(handle)
309
+ within_window(handle) do |p|
310
+ w, h = p.evaluate("[screen.width, screen.height]")
311
+ p.set_viewport_size(width: w, height: h)
312
+ end
313
+ nil
314
+ end
315
+
316
+ def no_such_window_error
317
+ NoSuchWindowError
318
+ end
319
+
320
+ # --- modals -------------------------------------------------------
321
+
322
+ def accept_modal(_type, **options, &blk)
323
+ expect_modal(true, options, &blk)
324
+ end
325
+
326
+ def dismiss_modal(_type, **options, &blk)
327
+ expect_modal(false, options, &blk)
328
+ end
329
+
330
+ def invalid_element_errors
331
+ [StaleElementError, NotInteractableError, Testsurfer::ContextDestroyedError]
332
+ end
333
+
334
+ # A fresh context: no cookies, storage or windows from the test before.
335
+ def reset!
336
+ @frames.clear
337
+ @handles.clear
338
+ @modal_lock.synchronize { @expectations.clear }
339
+ old = @context
340
+ @context = nil
341
+ @page = nil
342
+ begin
343
+ old&.close
344
+ rescue Testsurfer::Error
345
+ nil
346
+ end
347
+ nil
348
+ end
349
+
350
+ # Close the browser (Capybara calls this at exit).
351
+ def quit
352
+ reset!
353
+ @browser&.close
354
+ @browser = nil
355
+ end
356
+
357
+ # --- internals the nodes use --------------------------------------
358
+
359
+ WRAP = "(function w(v,d){if(v&&typeof v==='object'){if(v.nodeType===1||v.nodeType===11)" \
360
+ "return {__ts_el:E.adoptValue(v).id,doc:E.doc};if(d>32)return null;if(Array.isArray(v))" \
361
+ "return v.map(function(x){return w(x,d+1);});if(Object.getPrototypeOf(v)===Object.prototype){var o={};" \
362
+ "for(var k in v)o[k]=w(v[k],d+1);return o;}}return v;})"
363
+
364
+ ADOPT_ALL = "(els) => { const E = window.__tse; return { doc: E.doc, ids: els.map((e) => E.adoptValue(e).id) }; }"
365
+
366
+ # Nodes for the elements `query` finds in the current frame, or inside `node`.
367
+ def find_in(node, query)
368
+ steps = if node
369
+ node.check!
370
+ [Step.new(Query.new(:handle, id: node.handle))]
371
+ else
372
+ frame_steps
373
+ end
374
+ chain = Chain.new(steps + [Step.new(query)])
375
+ req = { steps: chain.wire_checked, op: "evalAll", args: { "arg" => nil }, many: true, first: false }
376
+ r = page.locate(req, func: ADOPT_ALL)["v"] || {}
377
+ (r["ids"] || []).map { |id| Node.new(self, [r["doc"], id]) }
378
+ rescue Testsurfer::JavaScriptError => e
379
+ raise ::Capybara::ElementNotFound, e.message if e.message.include?("is not a valid")
380
+
381
+ raise
382
+ end
383
+
384
+ # The steps into the current frame.
385
+ def frame_steps
386
+ return [] if @frames.empty?
387
+
388
+ [Step.new(Query.new(:handle, id: @frames.last)), Step.new(Query.new(:frame))]
389
+ end
390
+
391
+ # Turn `{__ts_el:, doc:}` in a script's result into nodes.
392
+ def wrap_result(v)
393
+ case v
394
+ when Array then v.map { |x| wrap_result(x) }
395
+ when Hash
396
+ return Node.new(self, [v["doc"], v["__ts_el"]]) if v.key?("__ts_el")
397
+
398
+ v.transform_values { |x| wrap_result(x) }
399
+ else v
400
+ end
401
+ end
402
+
403
+ # `args` for the page: nodes as their elements.
404
+ def script_args(args)
405
+ args.map do |a|
406
+ case a
407
+ when ::Capybara::Node::Element then script_args([a.base]).first
408
+ when Node then { Serialize::RAW_KEY => { "$t" => "h", "v" => a.handle } }
409
+ when Array then script_args(a)
410
+ when Hash then a.transform_values { |x| script_args([x]).first }
411
+ else a
412
+ end
413
+ end
414
+ end
415
+
416
+ # A value from the page in the current frame (`expr` is an expression).
417
+ def frame_eval(expr)
418
+ wrap_result(frame_eval_raw("#{WRAP}(#{expr},0)"))
419
+ end
420
+
421
+ def frame_eval_raw(expr)
422
+ return page.engine_call(expr) if @frames.empty?
423
+
424
+ page.engine_call("(function(){var w=E.h(#{@frames.last}).contentWindow;return w.eval(#{Serialize.js_string("(#{expr})")});})()")
425
+ rescue Testsurfer::JavaScriptError => e
426
+ raise unless e.message.include?("contentWindow")
427
+
428
+ raise StaleElementError, "the frame is gone"
429
+ end
430
+
431
+ # The current frame's window, as a JavaScript expression.
432
+ def frame_window
433
+ @frames.empty? ? "window" : "E.h(#{@frames.last}).contentWindow"
434
+ end
435
+
436
+ def node_timeout
437
+ [(session_options.default_max_wait_time * 1000).to_i, 1000].max
438
+ end
439
+
440
+ private
441
+
442
+ def start
443
+ @context = browser.new_context(**@context_options)
444
+ # A headless view has no window frame: its outer size is its viewport.
445
+ @context.add_init_script("for (const [o, i] of [['outerWidth', 'innerWidth'], ['outerHeight', 'innerHeight']]) " \
446
+ "Object.defineProperty(window, o, { get() { return window[i]; }, configurable: true });")
447
+ @page = @context.new_page
448
+ @page.ensure_open
449
+ watch_dialogs(@page)
450
+ @context.on("page") { |p| watch_dialogs(p) }
451
+ end
452
+
453
+ def last_response
454
+ id = page.page_id
455
+ id && @context.hub.get_last_nav(id)
456
+ end
457
+
458
+ def handle_of(p)
459
+ @handles[p] ||= "ts-window-#{@handle_seq += 1}"
460
+ end
461
+
462
+ def page_for(handle)
463
+ start unless @page
464
+ @context.pages.find { |p| handle_of(p) == handle && !p.closed? }
465
+ end
466
+
467
+ def within_window(handle)
468
+ p = page_for(handle)
469
+ raise NoSuchWindowError, "no window with handle #{handle}" unless p
470
+
471
+ yield p
472
+ end
473
+
474
+ def run_script(script, args, returns:, async: nil)
475
+ enc = JSON.generate(Serialize.encode(script_args(args)))
476
+ fn = "new (#{frame_window}).Function(#{Serialize.js_string(script)})"
477
+ body = if async
478
+ "new Promise(function(ok,fail){var a=E.des(#{enc});a.push(ok);" \
479
+ "setTimeout(function(){fail(new Error('timeout: the async script did not call back within #{async}ms'))},#{async});" \
480
+ "#{fn}.apply(null,a);}).then(function(v){return #{WRAP}(v,0);})"
481
+ else
482
+ "(function(){var v=#{fn}.apply(null,E.des(#{enc}));" \
483
+ "return (v&&typeof v.then==='function')?v.then(function(x){return #{WRAP}(x,0);}):#{WRAP}(v,0);})()"
484
+ end
485
+ v = page.engine_call(body)
486
+ returns ? wrap_result(v) : nil
487
+ end
488
+
489
+ # Answer the page's dialogs as the modal calls say, and keep its downloads in the save path.
490
+ def watch_dialogs(p)
491
+ p.on("dialog") { |d| on_dialog(d) }
492
+ p.on("download") do |d|
493
+ dir = session_options.save_path || Dir.pwd
494
+ Testsurfer.spawn { d.save_as(File.join(dir, d.suggested_filename.to_s.empty? ? "download" : d.suggested_filename)) }
495
+ end
496
+ end
497
+
498
+ # A dialog: answered by the innermost pending expectation whose text
499
+ # it matches; with none pending, dismissed.
500
+ def on_dialog(dialog)
501
+ pick = nil
502
+ failed = nil
503
+ @modal_lock.synchronize do
504
+ open = @expectations.reverse.reject { |e| e.slot.set? }
505
+ pick = open.find { |e| e.text.nil? || dialog.message.match?(e.text) }
506
+ failed = open.first if pick.nil?
507
+ end
508
+ if pick
509
+ pick.accept ? dialog.accept(pick.with) : dialog.dismiss
510
+ pick.slot.set(dialog.message)
511
+ else
512
+ dialog.dismiss
513
+ failed&.slot&.fail(::Capybara::ModalNotFound.new(
514
+ "Unable to find modal dialog with #{failed.text.source} - found '#{dialog.message}' instead."
515
+ ))
516
+ end
517
+ end
518
+
519
+ def expect_modal(accept, options)
520
+ text = options[:text]
521
+ text = Regexp.new(Regexp.escape(text.to_s)) unless text.nil? || text.is_a?(Regexp)
522
+ e = Expectation.new(accept, text, options[:with], Slot.new)
523
+ @modal_lock.synchronize { @expectations << e }
524
+ begin
525
+ yield if block_given?
526
+ wait = options.fetch(:wait, session_options.default_max_wait_time) || 0
527
+ ok, message = e.slot.wait(wait)
528
+ raise ::Capybara::ModalNotFound, "Unable to find modal dialog#{" with #{options[:text]}" if options[:text]}" unless ok
529
+
530
+ message
531
+ ensure
532
+ @modal_lock.synchronize { @expectations.delete(e) }
533
+ end
534
+ end
535
+ end
536
+ end
537
+ end