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.
- checksums.yaml +7 -0
- data/LICENSE +202 -0
- data/README.md +38 -0
- data/lib/testsurfer/api.rb +195 -0
- data/lib/testsurfer/browser.rb +167 -0
- data/lib/testsurfer/capybara/driver.rb +537 -0
- data/lib/testsurfer/capybara/node.rb +574 -0
- data/lib/testsurfer/capybara.rb +12 -0
- data/lib/testsurfer/clock.rb +114 -0
- data/lib/testsurfer/context.rb +299 -0
- data/lib/testsurfer/cookies.rb +136 -0
- data/lib/testsurfer/daemon.rb +176 -0
- data/lib/testsurfer/emulation.rb +87 -0
- data/lib/testsurfer/errors.rb +70 -0
- data/lib/testsurfer/events.rb +581 -0
- data/lib/testsurfer/expect.rb +684 -0
- data/lib/testsurfer/frame.rb +350 -0
- data/lib/testsurfer/hooks.rb +367 -0
- data/lib/testsurfer/input.rb +160 -0
- data/lib/testsurfer/locator.rb +503 -0
- data/lib/testsurfer/media.rb +453 -0
- data/lib/testsurfer/net.rb +376 -0
- data/lib/testsurfer/page.rb +655 -0
- data/lib/testsurfer/page_events.rb +217 -0
- data/lib/testsurfer/query.rb +342 -0
- data/lib/testsurfer/rspec.rb +98 -0
- data/lib/testsurfer/selector.rb +357 -0
- data/lib/testsurfer/serialize.rb +122 -0
- data/lib/testsurfer/snapshot.rb +300 -0
- data/lib/testsurfer/storage.rb +176 -0
- data/lib/testsurfer/sync.rb +75 -0
- data/lib/testsurfer/version.rb +8 -0
- data/lib/testsurfer/wire.rb +295 -0
- data/lib/testsurfer.rb +50 -0
- data/testsurfer.gemspec +25 -0
- metadata +97 -0
|
@@ -0,0 +1,574 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "capybara"
|
|
4
|
+
require "date"
|
|
5
|
+
require "json"
|
|
6
|
+
|
|
7
|
+
module Testsurfer
|
|
8
|
+
module Capybara
|
|
9
|
+
# Capybara's key names as the page's key names.
|
|
10
|
+
module Keys
|
|
11
|
+
NAMES = {
|
|
12
|
+
cancel: "Cancel", help: "Help", backspace: "Backspace", tab: "Tab", clear: "Clear", return: "Enter",
|
|
13
|
+
enter: "Enter", shift: "Shift", control: "Control", ctrl: "Control", alt: "Alt", pause: "Pause",
|
|
14
|
+
escape: "Escape", space: " ", page_up: "PageUp", page_down: "PageDown", end: "End", home: "Home",
|
|
15
|
+
left: "ArrowLeft", up: "ArrowUp", right: "ArrowRight", down: "ArrowDown", insert: "Insert",
|
|
16
|
+
delete: "Delete", semicolon: ";", equals: "=", numpad0: "0", numpad1: "1", numpad2: "2", numpad3: "3",
|
|
17
|
+
numpad4: "4", numpad5: "5", numpad6: "6", numpad7: "7", numpad8: "8", numpad9: "9", multiply: "*",
|
|
18
|
+
add: "+", separator: ",", subtract: "-", decimal: ".", divide: "/", f1: "F1", f2: "F2", f3: "F3",
|
|
19
|
+
f4: "F4", f5: "F5", f6: "F6", f7: "F7", f8: "F8", f9: "F9", f10: "F10", f11: "F11", f12: "F12",
|
|
20
|
+
meta: "Meta", command: "Meta", left_shift: "Shift", left_control: "Control", left_alt: "Alt"
|
|
21
|
+
}.freeze
|
|
22
|
+
MODIFIERS = %w[Shift Control Alt Meta].freeze
|
|
23
|
+
|
|
24
|
+
module_function
|
|
25
|
+
|
|
26
|
+
def name(k)
|
|
27
|
+
NAMES.fetch(k.to_sym) { raise ArgumentError, "unknown key #{k.inspect}" }
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
# Press `keys` on the focused element: strings are typed, symbols
|
|
31
|
+
# pressed, and an array holds its leading modifiers for the rest.
|
|
32
|
+
def send_keys(page, keys, held = [])
|
|
33
|
+
keys.each do |k|
|
|
34
|
+
case k
|
|
35
|
+
when String
|
|
36
|
+
if held.empty?
|
|
37
|
+
page.type_trusted(k)
|
|
38
|
+
else
|
|
39
|
+
k.each_char { |c| page.keyboard.press((held + [c]).join("+")) }
|
|
40
|
+
end
|
|
41
|
+
when Symbol
|
|
42
|
+
n = name(k)
|
|
43
|
+
if MODIFIERS.include?(n) && held.empty?
|
|
44
|
+
# A lone modifier stays down for the keys after it, as WebDriver does.
|
|
45
|
+
held = held + [n]
|
|
46
|
+
else
|
|
47
|
+
page.keyboard.press((held + [n]).join("+"))
|
|
48
|
+
end
|
|
49
|
+
when Array
|
|
50
|
+
mods = k.take_while { |x| x.is_a?(Symbol) && MODIFIERS.include?(name(x)) }.map { |x| name(x) }
|
|
51
|
+
send_keys(page, k.drop(mods.length), held + mods)
|
|
52
|
+
else raise ArgumentError, "unknown key #{k.inspect}"
|
|
53
|
+
end
|
|
54
|
+
end
|
|
55
|
+
nil
|
|
56
|
+
end
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
# One element Capybara found: a handle the page holds, valid while its document lives.
|
|
60
|
+
class Node < ::Capybara::Driver::Node
|
|
61
|
+
CAPYBARA_DIR = File.dirname($LOADED_FEATURES.find { |f| f.end_with?("/capybara.rb") } || "")
|
|
62
|
+
IS_DISPLAYED = File.read(File.join(CAPYBARA_DIR, "capybara", "selenium", "atoms", "isDisplayed.min.js")).strip
|
|
63
|
+
GET_ATTRIBUTE = File.read(File.join(CAPYBARA_DIR, "capybara", "selenium", "atoms", "getAttribute.min.js")).strip
|
|
64
|
+
|
|
65
|
+
def doc
|
|
66
|
+
native[0]
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
def handle
|
|
70
|
+
native[1]
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
def page
|
|
74
|
+
driver.page
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
# Raise StaleElementError when the element is gone.
|
|
78
|
+
def check!
|
|
79
|
+
call("() => true")
|
|
80
|
+
nil
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
# `fn(el, ...args)` in the page; its value, with elements as nodes.
|
|
84
|
+
def call(fn, *args)
|
|
85
|
+
enc = JSON.generate(Serialize.encode(driver.script_args(args)))
|
|
86
|
+
r = page.engine_call("(function(){if(E.doc!==#{JSON.generate(doc)})return {stale:1};var el=E.h(#{handle});" \
|
|
87
|
+
"if(!el||!el.isConnected)return {stale:1};var v=(#{fn}).apply(null,[el].concat(E.des(#{enc})));" \
|
|
88
|
+
"return (v&&typeof v.then==='function')?v.then(function(x){return {v:#{Driver::WRAP}(x,0)};}):{v:#{Driver::WRAP}(v,0)};})()")
|
|
89
|
+
raise StaleElementError, "The element is no longer attached to the DOM" if r.nil? || r["stale"]
|
|
90
|
+
|
|
91
|
+
driver.wrap_result(r["v"])
|
|
92
|
+
rescue Testsurfer::ContextDestroyedError
|
|
93
|
+
raise StaleElementError, "The element's document is gone"
|
|
94
|
+
end
|
|
95
|
+
|
|
96
|
+
# The element as a locator, for actions with actionability waits.
|
|
97
|
+
def locator
|
|
98
|
+
check!
|
|
99
|
+
Locator.new(page, Chain.new([Step.new(Query.new(:handle, id: handle))]))
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
def all_text
|
|
103
|
+
t = call("(el) => el.textContent") || ""
|
|
104
|
+
t.gsub(/[]/, "").gsub(/[ \n\f\t\v
]+/, " ")
|
|
105
|
+
.gsub(/\A[[:space:]&&[^ ]]+/, "").gsub(/[[:space:]&&[^ ]]+\z/, "").tr(" ", " ")
|
|
106
|
+
end
|
|
107
|
+
|
|
108
|
+
VISIBLE_TEXT = <<~JS
|
|
109
|
+
(el) => {
|
|
110
|
+
const shown = (#{IS_DISPLAYED});
|
|
111
|
+
if (el.nodeType === 11) {
|
|
112
|
+
// A shadow root has no innerText: the text of its shown children, on one line.
|
|
113
|
+
return Array.from(el.childNodes).map((c) => c.nodeType === 3 ? c.data : (c.nodeType === 1 && shown(c) ? c.textContent : ''))
|
|
114
|
+
.join('').replace(/[ \\t\\n\\r\\f]+/g, ' ').trim();
|
|
115
|
+
}
|
|
116
|
+
if (!shown(el)) return '';
|
|
117
|
+
const t = el.innerText;
|
|
118
|
+
return t == null ? '' : String(t);
|
|
119
|
+
}
|
|
120
|
+
JS
|
|
121
|
+
|
|
122
|
+
# Whitespace WebDriver's visible text drops: all of it but the no-break space.
|
|
123
|
+
SPACE = /[[:space:]&&[^ \n]]+/
|
|
124
|
+
|
|
125
|
+
# The element's text as WebDriver shows it: lines trimmed, spaces
|
|
126
|
+
# collapsed, no-break spaces kept as spaces.
|
|
127
|
+
def visible_text
|
|
128
|
+
t = call(VISIBLE_TEXT).to_s
|
|
129
|
+
lines = t.split("\n").map { |l| l.gsub(SPACE, " ").gsub(/\A[[:space:]&&[^ ]]+|[[:space:]&&[^ ]]+\z/, "") }
|
|
130
|
+
lines.reject(&:empty?).join("\n").tr(" ", " ")
|
|
131
|
+
end
|
|
132
|
+
|
|
133
|
+
def [](name)
|
|
134
|
+
call("(el, n) => (#{GET_ATTRIBUTE})(el, n)", name.to_s)
|
|
135
|
+
end
|
|
136
|
+
|
|
137
|
+
def value
|
|
138
|
+
call(<<~JS)
|
|
139
|
+
(el) => {
|
|
140
|
+
if (el.tagName === 'SELECT' && el.multiple)
|
|
141
|
+
return Array.from(el.querySelectorAll('option')).filter((o) => o.selected).map((o) => o.value || o.text);
|
|
142
|
+
return el.value === undefined ? null : el.value;
|
|
143
|
+
}
|
|
144
|
+
JS
|
|
145
|
+
end
|
|
146
|
+
|
|
147
|
+
def style(styles)
|
|
148
|
+
call("(el, s) => { const c = getComputedStyle(el); const o = {}; for (const k of s) o[k] = c.getPropertyValue(k) || c[k]; return o; }",
|
|
149
|
+
styles.map(&:to_s))
|
|
150
|
+
end
|
|
151
|
+
|
|
152
|
+
def set(value, **options)
|
|
153
|
+
if value.is_a?(Array) && !multiple?
|
|
154
|
+
raise ArgumentError, "Value cannot be an Array when 'multiple' attribute is not present. Not a #{value.class}"
|
|
155
|
+
end
|
|
156
|
+
|
|
157
|
+
tag, type = call("(el) => [el.tagName.toLowerCase(), (el.type || '').toLowerCase()]")
|
|
158
|
+
case tag
|
|
159
|
+
when "input"
|
|
160
|
+
case type
|
|
161
|
+
when "radio" then click
|
|
162
|
+
when "checkbox" then click if value ^ checked?
|
|
163
|
+
when "file" then set_files(value)
|
|
164
|
+
when "date" then set_date(value, options)
|
|
165
|
+
when "time" then set_time(value, options)
|
|
166
|
+
when "datetime-local" then set_datetime_local(value, options)
|
|
167
|
+
when "color", "range" then update_value_js(value)
|
|
168
|
+
else set_text(value, **options)
|
|
169
|
+
end
|
|
170
|
+
when "textarea" then set_text(value, **options)
|
|
171
|
+
else set_content_editable(value)
|
|
172
|
+
end
|
|
173
|
+
end
|
|
174
|
+
|
|
175
|
+
# Choose an option, as a user picking it from the list does: input and change on its select.
|
|
176
|
+
def select_option
|
|
177
|
+
return if disabled?
|
|
178
|
+
|
|
179
|
+
call(<<~JS)
|
|
180
|
+
(el) => {
|
|
181
|
+
if (el.selected) return;
|
|
182
|
+
const s = el.closest('select');
|
|
183
|
+
el.selected = true;
|
|
184
|
+
if (s) {
|
|
185
|
+
s.dispatchEvent(new Event('input', { bubbles: true, composed: true }));
|
|
186
|
+
s.dispatchEvent(new Event('change', { bubbles: true }));
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
JS
|
|
190
|
+
end
|
|
191
|
+
|
|
192
|
+
def unselect_option
|
|
193
|
+
unless call("(el) => { const s = el.closest('select'); return !!(s && s.multiple); }")
|
|
194
|
+
raise ::Capybara::UnselectNotAllowed, "Cannot unselect option from single select box."
|
|
195
|
+
end
|
|
196
|
+
|
|
197
|
+
call(<<~JS)
|
|
198
|
+
(el) => {
|
|
199
|
+
if (!el.selected) return;
|
|
200
|
+
const s = el.closest('select');
|
|
201
|
+
el.selected = false;
|
|
202
|
+
s.dispatchEvent(new Event('input', { bubbles: true, composed: true }));
|
|
203
|
+
s.dispatchEvent(new Event('change', { bubbles: true }));
|
|
204
|
+
}
|
|
205
|
+
JS
|
|
206
|
+
end
|
|
207
|
+
|
|
208
|
+
def click(keys = [], **options)
|
|
209
|
+
act { locator.click(**click_options(keys, options)) }
|
|
210
|
+
nil
|
|
211
|
+
end
|
|
212
|
+
|
|
213
|
+
def right_click(keys = [], **options)
|
|
214
|
+
act { locator.click(**click_options(keys, options), button: "right") }
|
|
215
|
+
nil
|
|
216
|
+
end
|
|
217
|
+
|
|
218
|
+
def double_click(keys = [], **options)
|
|
219
|
+
act { locator.click(**click_options(keys, options), click_count: 2) }
|
|
220
|
+
nil
|
|
221
|
+
end
|
|
222
|
+
|
|
223
|
+
def send_keys(*args)
|
|
224
|
+
focused = call("(el) => { const r = el.getRootNode(); return (r.activeElement || document.activeElement) === el; }")
|
|
225
|
+
act { locator.focus(timeout: driver.node_timeout) } unless focused
|
|
226
|
+
Keys.send_keys(page, args)
|
|
227
|
+
end
|
|
228
|
+
|
|
229
|
+
def hover
|
|
230
|
+
act { locator.hover(timeout: driver.node_timeout) }
|
|
231
|
+
nil
|
|
232
|
+
end
|
|
233
|
+
|
|
234
|
+
def drag_to(element, **_options)
|
|
235
|
+
target = element.is_a?(::Capybara::Node::Element) ? element.base : element
|
|
236
|
+
# A native drag is one gesture, so both ends must be in view at
|
|
237
|
+
# once: scroll to show them both, and when they lie further apart
|
|
238
|
+
# than the viewport is tall, make it taller for the drag.
|
|
239
|
+
span = call(<<~JS, target)
|
|
240
|
+
(el, other) => {
|
|
241
|
+
const w = el.ownerDocument.defaultView;
|
|
242
|
+
const a = el.getBoundingClientRect(), b = other.getBoundingClientRect();
|
|
243
|
+
const top = Math.min(a.top, b.top) + w.scrollY, bottom = Math.max(a.bottom, b.bottom) + w.scrollY;
|
|
244
|
+
const left = Math.min(a.left, b.left) + w.scrollX;
|
|
245
|
+
const need = bottom - top + 40;
|
|
246
|
+
w.scrollTo(Math.max(0, left - 20), Math.max(0, top - Math.max(20, (w.innerHeight - need) / 2)));
|
|
247
|
+
return [need, w.innerHeight, w === window.top];
|
|
248
|
+
}
|
|
249
|
+
JS
|
|
250
|
+
old = page.viewport_size
|
|
251
|
+
grow = span[2] && old && span[0] > span[1]
|
|
252
|
+
page.set_viewport_size(width: old[:width], height: [span[0].ceil, 4000].min) if grow
|
|
253
|
+
begin
|
|
254
|
+
call("(el, other) => { const r = el.getBoundingClientRect(); const w = el.ownerDocument.defaultView; " \
|
|
255
|
+
"const t = Math.min(r.top, other.getBoundingClientRect().top); if (t < 0 || t > w.innerHeight) w.scrollBy(0, t - 20); }", target)
|
|
256
|
+
act { locator.drag_to(target.locator) }
|
|
257
|
+
ensure
|
|
258
|
+
page.set_viewport_size(width: old[:width], height: old[:height]) if grow
|
|
259
|
+
end
|
|
260
|
+
nil
|
|
261
|
+
end
|
|
262
|
+
|
|
263
|
+
# Drop files (paths) or strings (or { mime => string } hashes) on the element.
|
|
264
|
+
def drop(*args)
|
|
265
|
+
files = []
|
|
266
|
+
data = {}
|
|
267
|
+
args.each do |a|
|
|
268
|
+
case a
|
|
269
|
+
when String, Pathname then File.exist?(a.to_s) ? files << a.to_s : data["text/plain"] = a
|
|
270
|
+
when Hash then a.each { |k, v| data[k.to_s] = v.to_s }
|
|
271
|
+
end
|
|
272
|
+
end
|
|
273
|
+
locator.drop(files: files, data: data)
|
|
274
|
+
end
|
|
275
|
+
|
|
276
|
+
def scroll_by(x, y)
|
|
277
|
+
call("(el, x, y) => { el.scrollBy(x, y); }", x, y)
|
|
278
|
+
self
|
|
279
|
+
end
|
|
280
|
+
|
|
281
|
+
def scroll_to(element, alignment, position = nil)
|
|
282
|
+
if element.is_a?(::Capybara::Node::Element) || element.is_a?(Node)
|
|
283
|
+
other = element.is_a?(Node) ? element : element.base
|
|
284
|
+
call(SCROLL_ELEMENT, other, alignment.to_s)
|
|
285
|
+
elsif position
|
|
286
|
+
call("(el, x, y) => { el.scrollTo(x, y); }", position[0], position[1])
|
|
287
|
+
else
|
|
288
|
+
call("(el, a) => { el.scrollTo(0, a === 'top' ? 0 : a === 'bottom' ? el.scrollHeight : (el.scrollHeight - el.clientHeight) / 2); }",
|
|
289
|
+
alignment.to_s)
|
|
290
|
+
end
|
|
291
|
+
self
|
|
292
|
+
end
|
|
293
|
+
|
|
294
|
+
SCROLL_ELEMENT = <<~JS
|
|
295
|
+
(el, target, align) => {
|
|
296
|
+
const block = { top: 'start', bottom: 'end', center: 'center' }[align] || 'start';
|
|
297
|
+
target.scrollIntoView({ behavior: 'instant', block, inline: 'nearest' });
|
|
298
|
+
}
|
|
299
|
+
JS
|
|
300
|
+
|
|
301
|
+
def tag_name
|
|
302
|
+
@tag_name ||= call("(el) => el.nodeType === 11 ? 'ShadowRoot' : el.tagName.toLowerCase()")
|
|
303
|
+
end
|
|
304
|
+
|
|
305
|
+
def visible?
|
|
306
|
+
call("(el) => (#{IS_DISPLAYED})(el)") ? true : false
|
|
307
|
+
end
|
|
308
|
+
|
|
309
|
+
def obscured?(x: nil, y: nil)
|
|
310
|
+
call(<<~JS, x, y)
|
|
311
|
+
(el, x, y) => {
|
|
312
|
+
let r = el.getBoundingClientRect();
|
|
313
|
+
if (x == null) x = r.width / 2;
|
|
314
|
+
if (y == null) y = r.height / 2;
|
|
315
|
+
let px = r.left + x, py = r.top + y;
|
|
316
|
+
let doc = el.ownerDocument, win = doc.defaultView;
|
|
317
|
+
for (;;) {
|
|
318
|
+
if (px < 0 || py < 0 || px >= win.innerWidth || py >= win.innerHeight) return true;
|
|
319
|
+
const hit = doc.elementFromPoint(px, py);
|
|
320
|
+
if (!hit || !(el === hit || el.contains(hit))) return true;
|
|
321
|
+
const fe = win.frameElement;
|
|
322
|
+
if (!fe) return false;
|
|
323
|
+
const fr = fe.getBoundingClientRect();
|
|
324
|
+
px += fr.left + fe.clientLeft;
|
|
325
|
+
py += fr.top + fe.clientTop;
|
|
326
|
+
el = fe;
|
|
327
|
+
doc = fe.ownerDocument;
|
|
328
|
+
win = doc.defaultView;
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
JS
|
|
332
|
+
end
|
|
333
|
+
|
|
334
|
+
def checked?
|
|
335
|
+
call("(el) => !!el.checked")
|
|
336
|
+
end
|
|
337
|
+
|
|
338
|
+
def selected?
|
|
339
|
+
call("(el) => !!(el.selected || el.checked)")
|
|
340
|
+
end
|
|
341
|
+
|
|
342
|
+
def disabled?
|
|
343
|
+
call(<<~JS)
|
|
344
|
+
(el) => {
|
|
345
|
+
const fieldset = (n) => {
|
|
346
|
+
for (let f = n.closest('fieldset'); f; f = f.parentElement && f.parentElement.closest('fieldset')) {
|
|
347
|
+
if (f.disabled) {
|
|
348
|
+
const legend = f.querySelector(':scope > legend');
|
|
349
|
+
if (!(legend && legend.contains(n))) return true;
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
return false;
|
|
353
|
+
};
|
|
354
|
+
if (el.tagName === 'OPTION') {
|
|
355
|
+
const s = el.closest('select');
|
|
356
|
+
return el.disabled || !!(el.closest('optgroup') && el.closest('optgroup').disabled) || !!(s && (s.disabled || fieldset(s)));
|
|
357
|
+
}
|
|
358
|
+
if (el.tagName === 'OPTGROUP') return el.disabled || !!(el.closest('select') && el.closest('select').disabled);
|
|
359
|
+
if (/^(BUTTON|INPUT|SELECT|TEXTAREA|FIELDSET)$/.test(el.tagName)) return !!el.disabled || fieldset(el);
|
|
360
|
+
return false;
|
|
361
|
+
}
|
|
362
|
+
JS
|
|
363
|
+
end
|
|
364
|
+
|
|
365
|
+
def readonly?
|
|
366
|
+
call("(el) => !!el.readOnly")
|
|
367
|
+
end
|
|
368
|
+
|
|
369
|
+
def multiple?
|
|
370
|
+
call("(el) => !!el.multiple")
|
|
371
|
+
end
|
|
372
|
+
|
|
373
|
+
def content_editable?
|
|
374
|
+
call("(el) => !!el.isContentEditable")
|
|
375
|
+
end
|
|
376
|
+
|
|
377
|
+
Rect = Struct.new(:x, :y, :width, :height)
|
|
378
|
+
|
|
379
|
+
def rect
|
|
380
|
+
r = call("(el) => { const b = el.getBoundingClientRect(); return [b.x, b.y, b.width, b.height]; }")
|
|
381
|
+
Rect.new(*r)
|
|
382
|
+
end
|
|
383
|
+
|
|
384
|
+
def path
|
|
385
|
+
call(<<~JS)
|
|
386
|
+
(el) => {
|
|
387
|
+
if (el.getRootNode && el.getRootNode() instanceof ShadowRoot) return "(: Shadow DOM element - no XPath :)";
|
|
388
|
+
const xml = el.ownerDocument;
|
|
389
|
+
let xpath = '';
|
|
390
|
+
while (el !== xml.documentElement) {
|
|
391
|
+
let pos = 0;
|
|
392
|
+
for (let s = el; s; s = s.previousSibling) if (s.nodeType === 1 && s.nodeName === el.nodeName) pos += 1;
|
|
393
|
+
if (el.namespaceURI != xml.documentElement.namespaceURI) {
|
|
394
|
+
xpath = "*[local-name()='" + el.nodeName + "' and namespace-uri()='" + (el.namespaceURI === null ? '' : el.namespaceURI) + "'][" + pos + ']' + '/' + xpath;
|
|
395
|
+
} else {
|
|
396
|
+
xpath = el.nodeName.toUpperCase() + '[' + pos + ']/' + xpath;
|
|
397
|
+
}
|
|
398
|
+
el = el.parentNode;
|
|
399
|
+
}
|
|
400
|
+
xpath = '/' + xml.documentElement.nodeName.toUpperCase() + '/' + xpath;
|
|
401
|
+
return xpath.replace(/\\/$/, '');
|
|
402
|
+
}
|
|
403
|
+
JS
|
|
404
|
+
end
|
|
405
|
+
|
|
406
|
+
def trigger(event)
|
|
407
|
+
call("(el, t) => { el.dispatchEvent(new Event(t, { bubbles: true, cancelable: true })); }", event.to_s)
|
|
408
|
+
end
|
|
409
|
+
|
|
410
|
+
def shadow_root
|
|
411
|
+
root = call("(el) => el.shadowRoot")
|
|
412
|
+
root.is_a?(Node) ? root : nil
|
|
413
|
+
end
|
|
414
|
+
|
|
415
|
+
def shadow_root?
|
|
416
|
+
call("(el) => el.nodeType === 11")
|
|
417
|
+
end
|
|
418
|
+
|
|
419
|
+
def find_xpath(query, **_options)
|
|
420
|
+
driver.find_in(self, Query.new(:xpath, xpath: Driver.drop_empty_predicates(query)))
|
|
421
|
+
end
|
|
422
|
+
|
|
423
|
+
def find_css(query, **_options)
|
|
424
|
+
driver.find_in(self, Query.new(:css, selector: query, light: true))
|
|
425
|
+
end
|
|
426
|
+
|
|
427
|
+
def ==(other)
|
|
428
|
+
return false unless other.is_a?(Node)
|
|
429
|
+
return true if other.native == native
|
|
430
|
+
|
|
431
|
+
other.doc == doc && call("(el, o) => el === o", other)
|
|
432
|
+
rescue StaleElementError
|
|
433
|
+
false
|
|
434
|
+
end
|
|
435
|
+
|
|
436
|
+
def inspect
|
|
437
|
+
%(#<#{self.class} tag="#{tag_name}" path="#{path}">)
|
|
438
|
+
rescue StandardError
|
|
439
|
+
%(#<#{self.class} handle=#{handle}>)
|
|
440
|
+
end
|
|
441
|
+
|
|
442
|
+
private
|
|
443
|
+
|
|
444
|
+
# An action: a timeout while waiting for actionability is a retryable error to Capybara.
|
|
445
|
+
def act
|
|
446
|
+
yield
|
|
447
|
+
rescue Testsurfer::TimeoutError => e
|
|
448
|
+
raise NotInteractableError, e.message
|
|
449
|
+
end
|
|
450
|
+
|
|
451
|
+
MODIFIER_NAMES = { shift: "Shift", control: "Control", ctrl: "Control", alt: "Alt", meta: "Meta", command: "Meta" }.freeze
|
|
452
|
+
|
|
453
|
+
def click_options(keys, options)
|
|
454
|
+
o = { timeout: driver.node_timeout }
|
|
455
|
+
o[:modifiers] = keys.map { |k| MODIFIER_NAMES.fetch(k.to_sym) { raise ArgumentError, "unknown modifier #{k}" } } unless keys.empty?
|
|
456
|
+
x = options[:x]
|
|
457
|
+
y = options[:y]
|
|
458
|
+
if x && y
|
|
459
|
+
if (options[:offset] || (session_w3c? ? :center : :top_left)) == :center
|
|
460
|
+
r = rect
|
|
461
|
+
x += r.width / 2.0
|
|
462
|
+
y += r.height / 2.0
|
|
463
|
+
end
|
|
464
|
+
o[:position] = { x: x, y: y }
|
|
465
|
+
# A point may lie outside the element, on whatever is there, as WebDriver's actions allow.
|
|
466
|
+
o[:force] = true
|
|
467
|
+
end
|
|
468
|
+
o
|
|
469
|
+
end
|
|
470
|
+
|
|
471
|
+
def session_w3c?
|
|
472
|
+
driver.session_options.w3c_click_offset
|
|
473
|
+
end
|
|
474
|
+
|
|
475
|
+
def set_files(value)
|
|
476
|
+
paths = value.to_s.empty? ? [] : Array(value).map { |p| File.expand_path(p.to_s) }
|
|
477
|
+
act { locator.set_input_files(paths, timeout: driver.node_timeout) }
|
|
478
|
+
end
|
|
479
|
+
|
|
480
|
+
def set_text(value, clear: nil, rapid: nil, **_unused) # rubocop:disable Lint/UnusedMethodArgument
|
|
481
|
+
value = value.to_s
|
|
482
|
+
return if readonly?
|
|
483
|
+
|
|
484
|
+
if value.empty? && clear.nil?
|
|
485
|
+
act { locator.fill("", timeout: driver.node_timeout) }
|
|
486
|
+
elsif clear == :backspace
|
|
487
|
+
backspaces = [:backspace] * self.value.to_s.length
|
|
488
|
+
send_keys(:end, *backspaces, value)
|
|
489
|
+
elsif clear.is_a?(Array)
|
|
490
|
+
send_keys(*clear, value)
|
|
491
|
+
else
|
|
492
|
+
act { locator.focus(timeout: driver.node_timeout) }
|
|
493
|
+
unless clear == :none
|
|
494
|
+
call("(el) => { try { el.select(); } catch (e) {} if (el.selectionStart !== el.selectionEnd || !el.value) return; " \
|
|
495
|
+
"el.value = ''; }")
|
|
496
|
+
end
|
|
497
|
+
type_text(value.gsub("\r\n", "\n"), rapid)
|
|
498
|
+
end
|
|
499
|
+
end
|
|
500
|
+
|
|
501
|
+
# Type `value`; a long one (or with `rapid: true`) is inserted but
|
|
502
|
+
# for its last character, which is typed, as Capybara's Selenium
|
|
503
|
+
# driver inserts the middle of a long text.
|
|
504
|
+
def type_text(value, rapid)
|
|
505
|
+
unless value.length >= 2 && (rapid == true || (value.length > 30 && rapid != false))
|
|
506
|
+
page.type_trusted(value)
|
|
507
|
+
return
|
|
508
|
+
end
|
|
509
|
+
# One native typing call costs about as much for one key as for
|
|
510
|
+
# many, so the text goes in first and the last key is typed.
|
|
511
|
+
call(<<~JS, value[0...-1])
|
|
512
|
+
(el, t) => {
|
|
513
|
+
if (typeof el.setRangeText === 'function') {
|
|
514
|
+
el.setRangeText(t, el.selectionStart, el.selectionEnd, 'end');
|
|
515
|
+
} else {
|
|
516
|
+
el.value += t;
|
|
517
|
+
}
|
|
518
|
+
el.dispatchEvent(new InputEvent('input', { bubbles: true, inputType: 'insertText', data: t }));
|
|
519
|
+
}
|
|
520
|
+
JS
|
|
521
|
+
page.type_trusted(value[-1])
|
|
522
|
+
end
|
|
523
|
+
|
|
524
|
+
def update_value_js(value)
|
|
525
|
+
call(<<~JS, value.to_s)
|
|
526
|
+
(el, v) => {
|
|
527
|
+
if (el.readOnly) return;
|
|
528
|
+
if (document.activeElement !== el) el.focus();
|
|
529
|
+
if (el.value != v) {
|
|
530
|
+
el.value = v;
|
|
531
|
+
el.dispatchEvent(new InputEvent('input'));
|
|
532
|
+
el.dispatchEvent(new Event('change', { bubbles: true }));
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
JS
|
|
536
|
+
end
|
|
537
|
+
|
|
538
|
+
def set_date(value, options)
|
|
539
|
+
return set_text(value, **options) unless value.respond_to?(:to_date) && !value.is_a?(String)
|
|
540
|
+
|
|
541
|
+
update_value_js(value.to_date.iso8601)
|
|
542
|
+
end
|
|
543
|
+
|
|
544
|
+
def set_time(value, options)
|
|
545
|
+
return set_text(value, **options) unless value.respond_to?(:to_time) && !value.is_a?(String)
|
|
546
|
+
|
|
547
|
+
update_value_js(value.to_time.strftime("%H:%M"))
|
|
548
|
+
end
|
|
549
|
+
|
|
550
|
+
def set_datetime_local(value, options)
|
|
551
|
+
return set_text(value, **options) unless value.respond_to?(:to_time) && !value.is_a?(String)
|
|
552
|
+
|
|
553
|
+
update_value_js(value.to_time.strftime("%Y-%m-%dT%H:%M"))
|
|
554
|
+
end
|
|
555
|
+
|
|
556
|
+
def set_content_editable(value)
|
|
557
|
+
click
|
|
558
|
+
editable = call(<<~JS)
|
|
559
|
+
(el) => {
|
|
560
|
+
if (!el.isContentEditable) return false;
|
|
561
|
+
const range = document.createRange();
|
|
562
|
+
const sel = window.getSelection();
|
|
563
|
+
el.focus();
|
|
564
|
+
range.selectNodeContents(el);
|
|
565
|
+
sel.removeAllRanges();
|
|
566
|
+
sel.addRange(range);
|
|
567
|
+
return true;
|
|
568
|
+
}
|
|
569
|
+
JS
|
|
570
|
+
page.type_trusted(value.to_s) if editable
|
|
571
|
+
end
|
|
572
|
+
end
|
|
573
|
+
end
|
|
574
|
+
end
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "capybara"
|
|
4
|
+
require "testsurfer"
|
|
5
|
+
require_relative "capybara/driver"
|
|
6
|
+
require_relative "capybara/node"
|
|
7
|
+
|
|
8
|
+
# `:testsurfer`: the OS web view through vibesurfer. Options for your own
|
|
9
|
+
# registration are those of Testsurfer::Capybara::Driver.new.
|
|
10
|
+
Capybara.register_driver(:testsurfer) do |app|
|
|
11
|
+
Testsurfer::Capybara::Driver.new(app)
|
|
12
|
+
end
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "base64"
|
|
4
|
+
require "json"
|
|
5
|
+
|
|
6
|
+
module Testsurfer
|
|
7
|
+
# Playwright's Clock: fake time in the page, done by the daemon (`vs_clock`).
|
|
8
|
+
# A time is Unix milliseconds (Integer), a Time, or an ISO 8601 string;
|
|
9
|
+
# a span is milliseconds, or a string such as "01:00" or "02:34:10".
|
|
10
|
+
class Clock
|
|
11
|
+
def initialize(page: nil, context: nil)
|
|
12
|
+
@page = page
|
|
13
|
+
@context = context
|
|
14
|
+
end
|
|
15
|
+
|
|
16
|
+
# `2024-02-02T08:00:00Z` (or with an offset or fraction) as Unix milliseconds.
|
|
17
|
+
def self.iso_millis(s)
|
|
18
|
+
date, rest = s.split("T", 2)
|
|
19
|
+
rest ||= "00:00:00Z"
|
|
20
|
+
y, mo, d = date.split("-").map { |p| Integer(p, 10) }
|
|
21
|
+
return nil if d.nil?
|
|
22
|
+
|
|
23
|
+
if rest.end_with?("Z")
|
|
24
|
+
time = rest[0...-1]
|
|
25
|
+
offset = 0
|
|
26
|
+
elsif (i = rest.rindex(/[+-]/))
|
|
27
|
+
time = rest[0...i]
|
|
28
|
+
sign = rest[i] == "-" ? -1 : 1
|
|
29
|
+
hm = rest[(i + 1)..].split(":")
|
|
30
|
+
offset = sign * (Integer(hm[0], 10) * 60 + (hm[1] ? Integer(hm[1], 10) : 0))
|
|
31
|
+
else
|
|
32
|
+
time = rest
|
|
33
|
+
offset = 0
|
|
34
|
+
end
|
|
35
|
+
h, mi, sec = time.split(":")
|
|
36
|
+
days = Time.utc(y, mo, d).to_i / 86_400
|
|
37
|
+
ms = (Float(sec || "0") * 1000).round
|
|
38
|
+
(((days * 24 + Integer(h, 10)) * 60 + Integer(mi || "0", 10) - offset) * 60_000) + ms
|
|
39
|
+
rescue ArgumentError, TypeError
|
|
40
|
+
nil
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
def self.millis(t)
|
|
44
|
+
case t
|
|
45
|
+
when Integer then t
|
|
46
|
+
when Time then (t.to_r * 1000).to_i
|
|
47
|
+
when String then iso_millis(t) || raise(UsageError, "clock: not a time: #{t.inspect}")
|
|
48
|
+
else raise UsageError, "clock: not a time: #{t.inspect}"
|
|
49
|
+
end
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
def self.span_ms(s)
|
|
53
|
+
return s.to_i if s.is_a?(Numeric)
|
|
54
|
+
|
|
55
|
+
ms = 0
|
|
56
|
+
s.to_s.split(":").each do |p|
|
|
57
|
+
ms = ms * 60 + Integer(p.strip, 10)
|
|
58
|
+
rescue ArgumentError
|
|
59
|
+
raise UsageError, "clock: not a duration: #{s.inspect}"
|
|
60
|
+
end
|
|
61
|
+
ms * 1000
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
# Fake Date, timers, animation frames and performance.now, from `time` (now by default).
|
|
65
|
+
def install(time: nil)
|
|
66
|
+
op = { "kind" => "install" }
|
|
67
|
+
op["time"] = Clock.millis(time) unless time.nil?
|
|
68
|
+
run(op)
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
# Jump ahead, firing each due timer at most once.
|
|
72
|
+
def fast_forward(ticks)
|
|
73
|
+
run({ "kind" => "fastForward", "ms" => Clock.span_ms(ticks) })
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
# Advance, firing every timer that comes due on the way.
|
|
77
|
+
def run_for(ticks)
|
|
78
|
+
run({ "kind" => "runFor", "ms" => Clock.span_ms(ticks) })
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
# Advance to `time`, firing timers on the way, and stop the clock there.
|
|
82
|
+
def pause_at(time)
|
|
83
|
+
run({ "kind" => "pauseAt", "time" => Clock.millis(time) })
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
# Let a paused clock run again.
|
|
87
|
+
def resume
|
|
88
|
+
run({ "kind" => "resume" })
|
|
89
|
+
end
|
|
90
|
+
|
|
91
|
+
# `Date.now()` and `new Date()` always answer `time`; timers run as usual.
|
|
92
|
+
def set_fixed_time(time)
|
|
93
|
+
run({ "kind" => "fixed", "time" => Clock.millis(time) })
|
|
94
|
+
end
|
|
95
|
+
|
|
96
|
+
# Change the wall-clock time without firing timers.
|
|
97
|
+
def set_system_time(time)
|
|
98
|
+
run({ "kind" => "system", "time" => Clock.millis(time) })
|
|
99
|
+
end
|
|
100
|
+
|
|
101
|
+
private
|
|
102
|
+
|
|
103
|
+
def run(op)
|
|
104
|
+
arg = Base64.strict_encode64(JSON.generate(op))
|
|
105
|
+
if @page
|
|
106
|
+
id = @page.ensure_open
|
|
107
|
+
@page.wire.call(Wire::Request.new("vs_clock").arg(arg).flag_value("session", @page.session_id).flag_value("page", id))
|
|
108
|
+
else
|
|
109
|
+
@context.wire.call(Wire::Request.new("vs_clock").arg(arg).flag_value("session", @context.session_id))
|
|
110
|
+
end
|
|
111
|
+
nil
|
|
112
|
+
end
|
|
113
|
+
end
|
|
114
|
+
end
|