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,453 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "base64"
4
+ require "fileutils"
5
+ require "json"
6
+ require "tmpdir"
7
+
8
+ module Testsurfer
9
+ # Accessibility snapshots, rendered and matched by the daemon (`vs_aria`).
10
+ module Aria
11
+ module_function
12
+
13
+ # One `vs_aria` call: the page, or the element `scope` finds (strict).
14
+ # Returns { found:, matched:, text: }.
15
+ def call(page, scope: nil, template: nil, timeout: 0)
16
+ id = page.ensure_open
17
+ req = Wire::Request.new("vs_aria").arg(id).flag_value("session", page.session_id).flag_value("timeout", timeout.to_i)
18
+ if scope
19
+ r = scope.request("refs", {})
20
+ req.flag_value("locate", JSON.generate({ "steps" => r[:steps], "op" => "refs", "args" => {} }))
21
+ end
22
+ req.flag_value("expect", Base64.strict_encode64(template)) if template
23
+ body = page.wire.call(req).body
24
+ field = ->(k) { (l = body.find { |x| x.start_with?("#{k} ") }) && l[(k.length + 1)..] }
25
+ text = field.("text")
26
+ text = text ? Base64.decode64(text.strip).force_encoding(Encoding::UTF_8) : ""
27
+ m = field.("match")
28
+ { found: field.("found") == "1", matched: m.nil? ? nil : m == "1", text: text }
29
+ end
30
+ end
31
+
32
+ class Page
33
+ # The whole page's accessibility tree as template text (see `to_match_aria_snapshot`).
34
+ def aria_snapshot(**)
35
+ Aria.call(self)[:text]
36
+ end
37
+ end
38
+
39
+ class Locator
40
+ # The element's accessibility subtree as template text, ready to
41
+ # paste into `to_match_aria_snapshot` and trim.
42
+ def aria_snapshot(**)
43
+ got = Aria.call(page, scope: self)
44
+ raise TimeoutError, "locator.ariaSnapshot: #{inspect} not found" unless got[:found]
45
+
46
+ got[:text]
47
+ end
48
+
49
+ # The most readable locator that finds the same single element: by
50
+ # test id, then by role and name, then by text; this one otherwise.
51
+ def normalize
52
+ attr = page.test_id_attribute
53
+ id = begin
54
+ get_attribute(attr)
55
+ rescue Error
56
+ nil
57
+ end
58
+ if id
59
+ l = page.get_by_test_id(id)
60
+ return l if unique?(l)
61
+ end
62
+ role, name = begin
63
+ [wait_one("locator.normalize", "role", {}, nil), wait_one("locator.normalize", "name", {}, nil)]
64
+ rescue Error
65
+ ["", ""]
66
+ end
67
+ if !role.to_s.empty? && !name.to_s.empty? && role != "text"
68
+ l = page.get_by_role(role, name: name, exact: true)
69
+ return l if unique?(l)
70
+ end
71
+ text = begin
72
+ text_content.to_s.strip
73
+ rescue Error
74
+ ""
75
+ end
76
+ unless text.empty?
77
+ l = page.get_by_text(text, exact: true)
78
+ return l if unique?(l)
79
+ end
80
+ self
81
+ end
82
+
83
+ # Drop files and strings on the element as a native drag from another
84
+ # application: files: (paths or { name:, mime_type:, buffer: }), data:
85
+ # (MIME type => string).
86
+ def drop(files: [], data: {})
87
+ b = bounding_box || raise(TimeoutError, "locator.drop: #{inspect} is not rendered")
88
+ x = b["x"] + b["width"] / 2.0
89
+ y = b["y"] + b["height"] / 2.0
90
+ dir = nil
91
+ paths = InputFiles.list(files).map do |f|
92
+ next f.to_s unless InputFiles.buffer?(f)
93
+
94
+ h = f.transform_keys(&:to_sym)
95
+ dir ||= Dir.mktmpdir("testsurfer-drop-")
96
+ p = File.join(dir, h[:name].to_s)
97
+ File.binwrite(p, h[:buffer].to_s)
98
+ p
99
+ end
100
+ payload = { "files" => paths, "data" => data.map { |k, v| [k.to_s, v.to_s] } }
101
+ id = page.ensure_open
102
+ req = Wire::Request.new("vs_drop").arg(id).arg(Testsurfer.fmt_num(x)).arg(Testsurfer.fmt_num(y))
103
+ .arg(Base64.strict_encode64(JSON.generate(payload))).flag_value("session", page.session_id)
104
+ begin
105
+ got = page.wire.call(req)
106
+ ensure
107
+ FileUtils.rm_rf(dir) if dir
108
+ end
109
+ raise UsageError, "locator.drop: the page did not accept the drop" unless got.body.first == "accepted"
110
+
111
+ nil
112
+ end
113
+
114
+ # A PNG of the element, scrolled into view first. With `path`, also written there.
115
+ def screenshot(path: nil, timeout: nil)
116
+ scroll_into_view_if_needed(timeout: timeout)
117
+ b = bounding_box(timeout: timeout) || raise(TimeoutError, "locator.screenshot: #{inspect} is not rendered")
118
+ page.screenshot(path: path, clip: b)
119
+ end
120
+
121
+ private
122
+
123
+ def unique?(l)
124
+ l.count == 1
125
+ rescue Error
126
+ false
127
+ end
128
+ end
129
+
130
+ # A file the page saved (Playwright's Download). A headless web view
131
+ # has nowhere to put it, so the daemon captures each one and reports it
132
+ # on the stream; `path` fetches the bytes to disk on first use.
133
+ class Download
134
+ attr_reader :page, :url, :suggested_filename, :mime, :size, :failure
135
+
136
+ def initialize(page:, id:, filename:, size:, mime:, url:, error:)
137
+ @page = page
138
+ @id = id
139
+ @suggested_filename = filename
140
+ @size = size
141
+ @mime = mime
142
+ @url = url
143
+ @failure = error
144
+ @saved = nil
145
+ @lock = Mutex.new
146
+ end
147
+
148
+ def inspect
149
+ "#<Testsurfer::Download #{suggested_filename.inspect}>"
150
+ end
151
+
152
+ # Where the file is on disk, fetching it on first call.
153
+ def path
154
+ @lock.synchronize do
155
+ return @saved if @saved
156
+ raise UsageError, "download.path: #{@failure}" if @failure
157
+
158
+ dir = File.join(Dir.tmpdir, "testsurfer-dl-#{Process.pid}-#{@id}")
159
+ FileUtils.mkdir_p(dir)
160
+ name = @suggested_filename.to_s.empty? ? "download-#{@id}" : @suggested_filename
161
+ dest = File.join(dir, name)
162
+ id = page.ensure_open
163
+ req = Wire::Request.new("vs_download").arg(id).flag_value("session", page.session_id)
164
+ .flag_value("id", @id).flag_value("dest", dest)
165
+ body = page.wire.call(req).body
166
+ l = body.find { |x| x.start_with?("path\t") }
167
+ @saved = l ? l.delete_prefix("path\t") : dest
168
+ end
169
+ end
170
+
171
+ # Copy the file to `to`.
172
+ def save_as(to)
173
+ from = path
174
+ FileUtils.mkdir_p(File.dirname(to.to_s))
175
+ FileUtils.cp(from, to.to_s)
176
+ nil
177
+ end
178
+
179
+ # Remove the fetched file.
180
+ def delete
181
+ p = @lock.synchronize { @saved }
182
+ FileUtils.rm_f(p) if p
183
+ nil
184
+ end
185
+ end
186
+
187
+ # A page's recorded video; its file is there once the page closes.
188
+ class Video
189
+ def initialize
190
+ @slot = Slot.new
191
+ end
192
+
193
+ def finish(path)
194
+ @slot.set(path)
195
+ end
196
+
197
+ # The video's path, once the page has closed and the file is written.
198
+ def path(timeout: nil)
199
+ ok, v = @slot.wait(timeout && timeout / 1000.0)
200
+ raise TimeoutError, "video.path: the recording has not ended" unless ok
201
+ raise UsageError, "video: the recording ended without a file" if v.nil?
202
+
203
+ v
204
+ end
205
+
206
+ # Copy the video to `to`.
207
+ def save_as(to)
208
+ from = path
209
+ FileUtils.mkdir_p(File.dirname(to.to_s))
210
+ FileUtils.cp(from, to.to_s)
211
+ nil
212
+ end
213
+ end
214
+
215
+ # Ends what started it when disposed.
216
+ class Disposable
217
+ def initialize(&finish)
218
+ @finish = finish
219
+ end
220
+
221
+ def dispose
222
+ @finish.call
223
+ end
224
+ end
225
+
226
+ class Page
227
+ RECORD_FPS = "25"
228
+ @video_seq = 0
229
+ @video_lock = Mutex.new
230
+
231
+ def self.next_video
232
+ @video_lock.synchronize { @video_seq += 1 }
233
+ end
234
+
235
+ def record_start_on(id, width)
236
+ req = Wire::Request.new("vs_record").arg("start").arg(id).flag_value("session", session_id)
237
+ .flag_value("fps", RECORD_FPS).flag_value("format", "webm")
238
+ req.flag_value("width", width) if width
239
+ wire.call(req)
240
+ end
241
+
242
+ # Start recording a page that just opened into the context's video directory.
243
+ def begin_video(id, opts)
244
+ start = @state_lock.synchronize do
245
+ next false if @recorder
246
+
247
+ @recorder = [opts[:dir], Video.new]
248
+ true
249
+ end
250
+ record_start_on(id, opts[:width]) if start
251
+ end
252
+
253
+ # Stop recording; the file the daemon wrote.
254
+ def record_stop(id)
255
+ body = wire.call(Wire::Request.new("vs_record").arg("stop").arg(id).flag_value("session", session_id)).body
256
+ l = body.find { |x| x.start_with?("path\t") }
257
+ l&.delete_prefix("path\t")
258
+ rescue Error
259
+ nil
260
+ end
261
+
262
+ # Finish the video before the page's web view goes.
263
+ def finish_video(id)
264
+ rec = @state_lock.synchronize { @recorder }
265
+ return if rec.nil?
266
+
267
+ dir, video = rec
268
+ recorded = record_stop(id)
269
+ return video.finish(nil) if recorded.nil?
270
+
271
+ FileUtils.mkdir_p(dir)
272
+ ext = File.extname(recorded).delete_prefix(".")
273
+ ext = "webm" if ext.empty?
274
+ to = File.join(dir, "#{Process.pid}-#{Page.next_video}.#{ext}")
275
+ begin
276
+ File.rename(recorded, to)
277
+ rescue SystemCallError
278
+ FileUtils.cp(recorded, to)
279
+ end
280
+ video.finish(to)
281
+ end
282
+
283
+ # The page's video, when its context records them.
284
+ def video
285
+ @state_lock.synchronize { @recorder&.last }
286
+ end
287
+
288
+ # Screencast frames, video and annotations for this page.
289
+ def screencast
290
+ @screencast ||= Screencast.new(self)
291
+ end
292
+ end
293
+
294
+ # A page's screencast (Playwright's `page.screencast`).
295
+ class Screencast
296
+ LAYER = <<~JS
297
+ (() => {
298
+ let l = document.getElementById('__ts_overlays');
299
+ if (!l) {
300
+ l = document.createElement('div');
301
+ l.id = '__ts_overlays';
302
+ l.style.cssText = 'position:fixed;inset:0;pointer-events:none;z-index:2147483647;';
303
+ (document.body || document.documentElement).appendChild(l);
304
+ }
305
+ return l;
306
+ })()
307
+ JS
308
+
309
+ def initialize(page)
310
+ @page = page
311
+ @running = false
312
+ @path = nil
313
+ @seq = 0
314
+ @lock = Mutex.new
315
+ @thread = nil
316
+ end
317
+
318
+ # Start sending frames to the block (each a { data:, timestamp: }
319
+ # hash, about every 100 ms) and/or recording a video to `path`.
320
+ # Returns a Disposable that stops it.
321
+ def start(path: nil, width: nil, &on_frame)
322
+ @lock.synchronize { @running = true }
323
+ if path
324
+ @lock.synchronize { @path = path.to_s }
325
+ id = @page.ensure_open
326
+ @page.record_start_on(id, width)
327
+ end
328
+ if on_frame
329
+ # The first frame before start returns: on a busy machine a short
330
+ # screencast could otherwise end before the loop's first capture.
331
+ frame(on_frame)
332
+ @thread = Thread.new do
333
+ while @lock.synchronize { @running }
334
+ frame(on_frame)
335
+ sleep 0.1
336
+ end
337
+ end
338
+ end
339
+ Disposable.new { stop }
340
+ end
341
+
342
+ # Stop frames and the recording, copying the video to its path.
343
+ def stop
344
+ @lock.synchronize { @running = false }
345
+ @thread&.join(2)
346
+ to = @lock.synchronize { p = @path; @path = nil; p }
347
+ if to
348
+ id = @page.ensure_open
349
+ recorded = @page.record_stop(id)
350
+ if recorded
351
+ FileUtils.mkdir_p(File.dirname(to))
352
+ FileUtils.cp(recorded, to)
353
+ end
354
+ end
355
+ nil
356
+ end
357
+
358
+ # A full-page title card for `duration` ms (2000 by default).
359
+ def show_chapter(title, description: nil, duration: 2000)
360
+ desc = description ? "<div style=\"font:400 18px system-ui;margin-top:8px\">#{Screencast.escape_html(description)}</div>" : ""
361
+ html = "<div style=\"position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;" \
362
+ "justify-content:center;background:rgba(0,0,0,.6);color:#fff;font:600 32px system-ui\">" \
363
+ "#{Screencast.escape_html(title)}#{desc}</div>"
364
+ overlay(html, duration, "inset:0;")
365
+ sleep(duration / 1000.0)
366
+ nil
367
+ end
368
+
369
+ # Show `html` over the page until disposed.
370
+ def show_overlay(html)
371
+ id = overlay(html, 0, "top:0;left:0;")
372
+ Disposable.new do
373
+ @page.evaluate("(id) => { const n = document.getElementById(id); if (n) n.remove(); return null; }", arg: id)
374
+ nil
375
+ end
376
+ end
377
+
378
+ def self.escape_html(s)
379
+ s.to_s.gsub("&", "&amp;").gsub("<", "&lt;").gsub(">", "&gt;").gsub('"', "&quot;")
380
+ end
381
+
382
+ private
383
+
384
+ def frame(on_frame)
385
+ data = @page.screenshot
386
+ on_frame.call({ data: data, timestamp: (Time.now.to_f * 1000).to_i })
387
+ rescue Error
388
+ nil
389
+ end
390
+
391
+ def overlay(html, duration, place)
392
+ id = "__ts_overlay_#{@lock.synchronize { @seq += 1 }}"
393
+ script = <<~JS
394
+ ([id, html, duration, where]) => {
395
+ const l = #{LAYER.strip};
396
+ const d = document.createElement('div');
397
+ d.id = id;
398
+ d.style.cssText = 'position:absolute;' + where;
399
+ d.innerHTML = html;
400
+ l.appendChild(d);
401
+ if (duration > 0) setTimeout(() => d.remove(), duration);
402
+ return null;
403
+ }
404
+ JS
405
+ @page.evaluate(script, arg: [id, html, duration.to_i, place])
406
+ id
407
+ end
408
+ end
409
+
410
+ # A context's tracing (Playwright's `context.tracing`), recorded by the
411
+ # daemon (`vs_trace`): actions, screenshots after them, and the network.
412
+ class Tracing
413
+ def initialize(ctx)
414
+ @ctx = ctx
415
+ end
416
+
417
+ # screenshots: a screenshot after each action; snapshots: the DOM
418
+ # before and after each action, for the viewer to replay.
419
+ def start(screenshots: false, snapshots: false, title: nil, name: nil, sources: nil) # rubocop:disable Lint/UnusedMethodArgument
420
+ req = Wire::Request.new("vs_trace").arg("start")
421
+ req.flag("screenshots") if screenshots
422
+ req.flag("snapshots") if snapshots
423
+ req.flag_value("title", title) if title
424
+ call(req)
425
+ end
426
+
427
+ # Write the trace zip (open it with `npx playwright show-trace`) and stop.
428
+ def stop(path: nil)
429
+ call(Wire::Request.new("vs_trace").arg("stop").arg(path.to_s))
430
+ end
431
+
432
+ # Write the trace so far to `path` and go on with a new chunk.
433
+ def stop_chunk(path: nil)
434
+ call(Wire::Request.new("vs_trace").arg("chunk").arg(path.to_s))
435
+ end
436
+
437
+ # Nest the calls until `group_end` under `name`.
438
+ def group(name, **)
439
+ call(Wire::Request.new("vs_trace").arg("group").arg(name))
440
+ end
441
+
442
+ def group_end
443
+ call(Wire::Request.new("vs_trace").arg("group-end"))
444
+ end
445
+
446
+ private
447
+
448
+ def call(req)
449
+ @ctx.wire.call(req.flag_value("session", @ctx.session_id))
450
+ nil
451
+ end
452
+ end
453
+ end