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,684 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Testsurfer
6
+ # Web-first assertions. Each matcher sends vibesurfer a read and a test
7
+ # (engine/src/expect.ts); the daemon polls until the assertion holds or
8
+ # the expect timeout passes, and a failure prints Playwright's message.
9
+ #
10
+ # Testsurfer.expect(page.locator("#status")).to_have_text("Saved")
11
+ # Testsurfer.expect(page.locator("li")).not_to_have_count(0)
12
+ # Testsurfer.expect(page).to_have_url(/dashboard/)
13
+ #
14
+ # Every `to_*` has a `not_to_*` twin. `timeout:` (ms) overrides the
15
+ # expect timeout; `message:` prints above the failure.
16
+ module Expect
17
+ # What a matcher's header and lines print.
18
+ Spec = Struct.new(:name, :arg, :expected, :expected_label, :received_label) do
19
+ def labels(e, r)
20
+ self.expected_label = e
21
+ self.received_label = r
22
+ self
23
+ end
24
+ end
25
+
26
+ # One reading of the page, as a failure prints it.
27
+ Sample = Struct.new(:found, :received, :diff, :log, keyword_init: true)
28
+
29
+ module_function
30
+
31
+ def show(v)
32
+ v.nil? ? "null" : JSON.generate(v)
33
+ end
34
+
35
+ # Playwright's text normalization: zero-width characters out, whitespace collapsed.
36
+ def normalize(s)
37
+ s.to_s.delete("​­").split.join(" ")
38
+ end
39
+
40
+ # jest-style diff of two string lists, as Playwright prints array mismatches.
41
+ def array_diff(expected, received, matched)
42
+ lines = []
43
+ minus = 0
44
+ plus = 0
45
+ [expected.length, received.length].max.times do |i|
46
+ e = i < expected.length ? TextMatch.show(expected[i]) : nil
47
+ r = i < received.length ? JSON.generate(received[i]) : nil
48
+ if e && r && matched[i]
49
+ lines << " #{r},"
50
+ next
51
+ end
52
+ if e
53
+ lines << "- #{e},"
54
+ minus += 1
55
+ end
56
+ if r
57
+ lines << "+ #{r},"
58
+ plus += 1
59
+ end
60
+ end
61
+ (["- Expected - #{minus}", "+ Received + #{plus}", "", " Array ["] + lines + [" ]"]).join("\n")
62
+ end
63
+
64
+ # An array matcher's printed result: a diff, or plain lines when negated.
65
+ def array_out(expected, received, matched, negated)
66
+ return Sample.new(found: true, received: JSON.generate(received)) if negated
67
+
68
+ Sample.new(found: true, diff: array_diff(expected, received, matched))
69
+ end
70
+
71
+ def resolved_log(n)
72
+ ["locator resolved to #{n} element#{n == 1 ? '' : 's'}"]
73
+ end
74
+
75
+ def list_json(items)
76
+ JSON.generate(items.map { |t| TextMatch.regex?(t) ? TextMatch.literal(t) : t })
77
+ end
78
+
79
+ # The failure message, in Playwright's layout.
80
+ def render(subject, locator, spec, negated, timeout, last, error, custom)
81
+ ms = timeout
82
+ out = []
83
+ if custom
84
+ out << custom
85
+ out << ""
86
+ end
87
+ out << "expect(#{subject}).#{negated ? 'not.' : ''}#{spec.name}(#{spec.arg}) failed"
88
+ out << ""
89
+ expected = "#{negated && !spec.expected.start_with?('predicate to') ? 'not ' : ''}#{spec.expected}"
90
+ loc = locator ? [["Locator", locator]] : []
91
+ if error
92
+ loc.each { |k, v| out << "#{k}: #{v}" }
93
+ out << "Expected: #{expected}"
94
+ out << error
95
+ elsif last.nil? || !last.found
96
+ loc.each { |k, v| out << "#{k}: #{v}" }
97
+ out << "Expected: #{expected}"
98
+ out << "Timeout: #{ms}ms"
99
+ out << "Error: element(s) not found"
100
+ elsif last.diff
101
+ loc.each { |k, v| out << "#{k}: #{v}" }
102
+ out << "Timeout: #{ms}ms"
103
+ out << last.diff
104
+ else
105
+ received = last.received.to_s
106
+ el = spec.expected_label || "Expected"
107
+ rl = spec.received_label || "Received"
108
+ if el == "Expected" && rl == "Received"
109
+ loc.each { |k, v| out << "#{k}: #{v}" }
110
+ out << "Expected: #{expected}"
111
+ out << "Received: #{received}"
112
+ out << "Timeout: #{ms}ms"
113
+ else
114
+ # Playwright aligns the two values, except in a negated message.
115
+ w = negated ? 0 : [el.length, rl.length].max + 2
116
+ loc.each { |k, v| out << "#{k}: #{v}" }
117
+ label = ->(l) { w.positive? ? "#{l}:".ljust(w) : "#{l}: " }
118
+ out << "#{label.(el)}#{expected}"
119
+ out << "#{label.(rl)}#{received}"
120
+ out << "Timeout: #{ms}ms"
121
+ end
122
+ end
123
+ log = ["Expect \"#{negated ? 'not ' : ''}#{spec.name}\" with timeout #{ms}ms"]
124
+ log << "waiting for #{locator}" if locator
125
+ log.concat(last.log) if last&.log
126
+ if last && error.nil? && last.found && last.diff.nil? && last.received
127
+ r = last.received
128
+ v = r.start_with?('"', "[", "{") ? r : JSON.generate(r)
129
+ log << " - unexpected value #{v}"
130
+ end
131
+ out << ""
132
+ out << "Call log:"
133
+ log.each { |l| out << (l.start_with?(" ") ? " #{l}" : " - #{l}") }
134
+ out << ""
135
+ out.join("\n")
136
+ end
137
+
138
+ # An error during an assertion as one "Error: ..." line, and whether it is fatal.
139
+ def error_line(e)
140
+ fatal = e.is_a?(StrictModeError) || e.message.start_with?("Error: ")
141
+ msg = e.message.sub(/\n+\z/, "")
142
+ # "locator.x: Error: ..." and "Error: ..." both print as one "Error: ..." line.
143
+ i = msg.index(": Error: ")
144
+ bare = i && !msg[0...i].include?(" ") ? msg[(i + 2)..] : msg
145
+ return [bare, fatal] if bare.start_with?("Error: ")
146
+
147
+ j = bare.index(": ")
148
+ stripped = j && !bare[0...j].include?(" ") ? bare[(j + 2)..] : bare
149
+ ["Error: #{stripped}", fatal]
150
+ end
151
+
152
+ # A page expression yielding `[value, matches]` for `value_expr`
153
+ # against `want`: whitespace-normalized when `normalized`, a pattern
154
+ # tested as a JavaScript regular expression.
155
+ def page_test(value_expr, want, normalized)
156
+ norm = "(function(s){return String(s).replace(/[\\u200b\\u00ad]/g,'').trim().replace(/\\s+/g,' ');})"
157
+ test = if TextMatch.regex?(want)
158
+ s, f = TextMatch.parts(want)
159
+ "new RegExp(#{JSON.generate(s)}, #{JSON.generate(f)}).test(v)"
160
+ elsif normalized
161
+ "#{norm}(v) === #{norm}(#{JSON.generate(want)})"
162
+ else
163
+ "v === #{JSON.generate(want)}"
164
+ end
165
+ "(function(){var v=#{value_expr};return [v, #{test}];})()"
166
+ end
167
+ end
168
+
169
+ # Adds a `not_to_x` for every `to_x`.
170
+ module Negatable
171
+ def self.included(base)
172
+ base.extend(ClassMethods)
173
+ end
174
+
175
+ module ClassMethods
176
+ def method_added(name)
177
+ super
178
+ s = name.to_s
179
+ return unless s.start_with?("to_") && !method_defined?("not_#{s}")
180
+
181
+ define_method("not_#{s}") { |*a, **k, &b| self.not.public_send(name, *a, **k, &b) }
182
+ end
183
+ end
184
+ end
185
+
186
+ # Assertions on a locator; see `Testsurfer.expect`.
187
+ class LocatorAssertions
188
+ include Negatable
189
+
190
+ attr_reader :locator, :negated
191
+
192
+ def initialize(locator, negated: false, timeout: nil, message: nil)
193
+ @locator = locator
194
+ @negated = negated
195
+ @timeout = timeout
196
+ @message = message
197
+ end
198
+
199
+ # The opposite assertion.
200
+ def not
201
+ LocatorAssertions.new(locator, negated: !negated, timeout: @timeout, message: @message)
202
+ end
203
+
204
+ # Poll this long (ms) instead of the expect timeout.
205
+ def with_timeout(ms)
206
+ LocatorAssertions.new(locator, negated: negated, timeout: ms, message: @message)
207
+ end
208
+
209
+ # A message printed above the failure.
210
+ def with_message(message)
211
+ LocatorAssertions.new(locator, negated: negated, timeout: @timeout, message: message)
212
+ end
213
+
214
+ def budget
215
+ @timeout || locator.page.timeouts.expect
216
+ end
217
+
218
+ def to_be_visible(visible: true, timeout: nil)
219
+ return opts(timeout).not.to_be_visible if visible == false
220
+
221
+ spec = Expect::Spec.new("toBeVisible", "", "visible")
222
+ c = { read: { "op" => "visible" }, test: { "t" => "eq", "v" => true }, missing_ok: negated }
223
+ check(spec, c, timeout) { |s| Expect::Sample.new(found: s["found"], received: s["r"] == true ? "visible" : "hidden") }
224
+ end
225
+
226
+ def to_be_hidden(timeout: nil)
227
+ spec = Expect::Spec.new("toBeHidden", "", "hidden")
228
+ c = { read: { "op" => "visible" }, test: { "t" => "eq", "v" => false }, missing_ok: !negated }
229
+ check(spec, c, timeout) { |s| Expect::Sample.new(found: s["found"], received: s["r"] == true ? "visible" : "hidden") }
230
+ end
231
+
232
+ def to_be_attached(attached: true, timeout: nil)
233
+ return opts(timeout).not.to_be_attached if attached == false
234
+
235
+ spec = Expect::Spec.new("toBeAttached", "", "attached")
236
+ c = { read: { "op" => "count", "many" => true }, test: { "t" => "attached", "v" => true }, missing_ok: false }
237
+ check(spec, c, timeout) { |s| Expect::Sample.new(found: true, received: (s["n"] || 0).positive? ? "attached" : "detached") }
238
+ end
239
+
240
+ def to_be_checked(checked: true, timeout: nil)
241
+ word = ->(v) { v ? "checked" : "unchecked" }
242
+ spec = Expect::Spec.new("toBeChecked", checked ? "" : "{ checked: false }", word.(checked))
243
+ c = { read: { "op" => "checkedMixed" }, test: { "t" => "checked", "want" => checked }, missing_ok: false }
244
+ check(spec, c, timeout) do |s|
245
+ r = s["r"]
246
+ v = r.is_a?(Hash) ? r["c"] : nil
247
+ [true, false].include?(v) ? Expect::Sample.new(found: true, received: word.(v)) : Expect::Sample.new(found: false)
248
+ end
249
+ end
250
+
251
+ def to_be_unchecked(timeout: nil)
252
+ to_be_checked(checked: false, timeout: timeout)
253
+ end
254
+
255
+ def to_be_disabled(timeout: nil)
256
+ state("toBeDisabled", "disabled", "enabled", "disabled", true, timeout)
257
+ end
258
+
259
+ def to_be_enabled(enabled: true, timeout: nil)
260
+ return opts(timeout).not.to_be_enabled if enabled == false
261
+
262
+ state("toBeEnabled", "disabled", "enabled", "disabled", false, timeout)
263
+ end
264
+
265
+ def to_be_editable(editable: true, timeout: nil)
266
+ return opts(timeout).not.to_be_editable if editable == false
267
+
268
+ state("toBeEditable", "editable", "readOnly", "editable", true, timeout)
269
+ end
270
+
271
+ def to_be_focused(timeout: nil)
272
+ state("toBeFocused", "focused", "inactive", "focused", true, timeout)
273
+ end
274
+
275
+ def to_be_empty(timeout: nil)
276
+ state("toBeEmpty", "empty", "notEmpty", "empty", true, timeout)
277
+ end
278
+
279
+ # The element intersects the viewport (by at least `ratio` when given).
280
+ def to_be_in_viewport(ratio: nil, timeout: nil)
281
+ spec = Expect::Spec.new("toBeInViewport", ratio ? "{ ratio: #{ratio} }" : "", "in viewport")
282
+ c = { read: { "op" => "inViewport" }, test: { "t" => "ratio", "min" => ratio }, missing_ok: false }
283
+ check(spec, c, timeout) { |s| Expect::Sample.new(found: true, received: "viewport ratio #{s['r'].is_a?(Numeric) ? s['r'] : 0.0}") }
284
+ end
285
+
286
+ # The element's text equals `expected` (whitespace-normalized) or
287
+ # matches the pattern. An Array checks the matches' texts in order.
288
+ def to_have_text(expected, ignore_case: nil, use_inner_text: false, timeout: nil)
289
+ return texts("toHaveText", expected, false, ignore_case, use_inner_text, timeout) if expected.is_a?(Array)
290
+
291
+ text("toHaveText", TextMatch.check!(expected), false, ignore_case, use_inner_text, timeout)
292
+ end
293
+
294
+ # The element's text contains `expected` or matches the pattern. An
295
+ # Array finds each in order among the matches' texts.
296
+ def to_contain_text(expected, ignore_case: nil, use_inner_text: false, timeout: nil)
297
+ return texts("toContainText", expected, true, ignore_case, use_inner_text, timeout) if expected.is_a?(Array)
298
+
299
+ text("toContainText", TextMatch.check!(expected), true, ignore_case, use_inner_text, timeout)
300
+ end
301
+
302
+ # The field's value equals `expected` exactly, or matches the pattern.
303
+ def to_have_value(expected, timeout: nil)
304
+ expected = TextMatch.check!(expected)
305
+ spec = Expect::Spec.new("toHaveValue", "expected", TextMatch.show(expected))
306
+ c = { read: { "op" => "value" }, test: { "t" => "text", "e" => TextMatch.wire_plain(expected), "normalize" => false }, missing_ok: false }
307
+ check(spec, c, timeout) { |s| Expect::Sample.new(found: true, received: Expect.show(s["r"])) }
308
+ end
309
+
310
+ # A multi-select's selected values.
311
+ def to_have_values(expected, timeout: nil)
312
+ expected = expected.map { |e| TextMatch.check!(e) }
313
+ spec = Expect::Spec.new("toHaveValues", "expected", Expect.list_json(expected))
314
+ c = { read: { "op" => "values" }, test: { "t" => "texts", "e" => expected.map { |e| TextMatch.wire_plain(e) }, "normalize" => false },
315
+ missing_ok: false }
316
+ neg = negated
317
+ check(spec, c, timeout) do |s|
318
+ v = s["r"].is_a?(Array) ? s["r"].map(&:to_s) : []
319
+ # A one-element read carries no per-item matches; compare as shown.
320
+ m = v.each_with_index.map { |x, i| i < expected.length && !TextMatch.regex?(expected[i]) && expected[i] == x }
321
+ Expect.array_out(expected, v, m, neg)
322
+ end
323
+ end
324
+
325
+ # The attribute is present, and with `value`, equals it or matches the pattern.
326
+ def to_have_attribute(name, value = nil, timeout: nil)
327
+ value = TextMatch.check!(value) unless value.nil?
328
+ spec = if value.nil?
329
+ Expect::Spec.new("toHaveAttribute", "expected", "have attribute")
330
+ elsif TextMatch.regex?(value)
331
+ Expect::Spec.new("toHaveAttribute", "expected", TextMatch.show(value)).labels("Expected pattern", "Received string")
332
+ else
333
+ Expect::Spec.new("toHaveAttribute", "expected", TextMatch.show(value))
334
+ end
335
+ test = { "t" => "attr", "normalize" => false }
336
+ test["e"] = TextMatch.wire_plain(value) unless value.nil?
337
+ c = { read: { "op" => "attr", "args" => { "name" => name } }, test: test, missing_ok: false }
338
+ check(spec, c, timeout) do |s|
339
+ r = s["r"]
340
+ received = if value.nil? then r.is_a?(String) ? "have attribute" : "not have attribute"
341
+ elsif !r.is_a?(String)
342
+ # null and "" print alike, so say that instead of a confusing "null".
343
+ if TextMatch.regex?(value) then '""'
344
+ elsif value.empty? then "serializes to the same string"
345
+ else "null"
346
+ end
347
+ else JSON.generate(r)
348
+ end
349
+ Expect::Sample.new(found: true, received: received)
350
+ end
351
+ end
352
+
353
+ # The class attribute equals `expected` (whitespace-normalized) or
354
+ # matches the pattern. An Array checks each match's class in order.
355
+ def to_have_class(expected, timeout: nil)
356
+ expected = TextMatch.check!(expected)
357
+ spec = Expect::Spec.new("toHaveClass", "expected", TextMatch.show(expected))
358
+ spec.labels("Expected pattern", "Received string") if TextMatch.regex?(expected)
359
+ c = { read: { "op" => "attr", "args" => { "name" => "class" } }, test: { "t" => "text", "e" => TextMatch.wire_plain(expected) }, missing_ok: false }
360
+ check(spec, c, timeout) { |s| Expect::Sample.new(found: true, received: JSON.generate(s["r"].is_a?(String) ? s["r"] : "")) }
361
+ end
362
+
363
+ # Every class in `expected` (space-separated) is present.
364
+ def to_contain_class(expected, timeout: nil)
365
+ spec = Expect::Spec.new("toContainClass", "expected", JSON.generate(expected)).labels("Expected", "Received")
366
+ c = { read: { "op" => "attr", "args" => { "name" => "class" } }, test: { "t" => "classes", "e" => expected }, missing_ok: false }
367
+ check(spec, c, timeout) { |s| Expect::Sample.new(found: true, received: JSON.generate(s["r"].is_a?(String) ? s["r"] : "")) }
368
+ end
369
+
370
+ def to_have_id(expected, timeout: nil)
371
+ expected = TextMatch.check!(expected)
372
+ spec = Expect::Spec.new("toHaveId", "expected", TextMatch.show(expected))
373
+ c = { read: { "op" => "attr", "args" => { "name" => "id" } },
374
+ test: { "t" => "text", "e" => TextMatch.wire_plain(expected), "normalize" => false }, missing_ok: false }
375
+ check(spec, c, timeout) { |s| Expect::Sample.new(found: true, received: JSON.generate(s["r"].is_a?(String) ? s["r"] : "")) }
376
+ end
377
+
378
+ # A computed style property equals `value` or matches the pattern.
379
+ def to_have_css(name, value, timeout: nil)
380
+ value = TextMatch.check!(value)
381
+ spec = Expect::Spec.new("toHaveCSS", "expected", TextMatch.show(value))
382
+ c = { read: { "op" => "css", "args" => { "name" => name } },
383
+ test: { "t" => "text", "e" => TextMatch.wire_plain(value), "normalize" => false }, missing_ok: false }
384
+ check(spec, c, timeout) { |s| Expect::Sample.new(found: true, received: Expect.show(s["r"])) }
385
+ end
386
+
387
+ # A JavaScript property of the element equals `value` (deeply).
388
+ def to_have_js_property(name, value, timeout: nil)
389
+ spec = Expect::Spec.new("toHaveJSProperty", "expected", Expect.show(value))
390
+ c = { read: { "op" => "prop", "args" => { "name" => name } }, test: { "t" => "eq", "v" => Serialize.encode(value), "ser" => true },
391
+ missing_ok: false }
392
+ check(spec, c, timeout) { |s| Expect::Sample.new(found: true, received: Expect.show(s["r"])) }
393
+ end
394
+
395
+ def to_have_role(role, timeout: nil)
396
+ spec = Expect::Spec.new("toHaveRole", "expected", JSON.generate(role.to_s))
397
+ c = { read: { "op" => "role" }, test: { "t" => "eq", "v" => role.to_s }, missing_ok: false }
398
+ check(spec, c, timeout) { |s| Expect::Sample.new(found: true, received: Expect.show(s["r"])) }
399
+ end
400
+
401
+ def to_have_accessible_name(name, timeout: nil)
402
+ name = TextMatch.check!(name)
403
+ spec = Expect::Spec.new("toHaveAccessibleName", "expected", TextMatch.show(name))
404
+ c = { read: { "op" => "name" }, test: { "t" => "text", "e" => TextMatch.wire_plain(name) }, missing_ok: false }
405
+ check(spec, c, timeout) { |s| Expect::Sample.new(found: true, received: Expect.show(s["r"])) }
406
+ end
407
+
408
+ def to_have_accessible_description(description, timeout: nil)
409
+ description = TextMatch.check!(description)
410
+ spec = Expect::Spec.new("toHaveAccessibleDescription", "expected", TextMatch.show(description))
411
+ c = { read: { "op" => "description" }, test: { "t" => "text", "e" => TextMatch.wire_plain(description) }, missing_ok: false }
412
+ check(spec, c, timeout) { |s| Expect::Sample.new(found: true, received: Expect.show(s["r"])) }
413
+ end
414
+
415
+ # The locator matches `count` elements.
416
+ def to_have_count(count, timeout: nil)
417
+ spec = Expect::Spec.new("toHaveCount", "expected", count.to_s)
418
+ c = { read: { "op" => "count", "many" => true }, test: { "t" => "count", "v" => count }, missing_ok: false }
419
+ check(spec, c, timeout) do |s|
420
+ n = s["r"].is_a?(Integer) ? s["r"] : 0
421
+ Expect::Sample.new(found: true, received: n.to_s, log: Expect.resolved_log(n))
422
+ end
423
+ end
424
+
425
+ # The element's accessibility subtree matches `template` (one
426
+ # `- role "name"` line per node, children indented under a colon).
427
+ def to_match_aria_snapshot(template, timeout: nil)
428
+ b = timeout || budget
429
+ got = Aria.call(locator.page, scope: locator, template: template, timeout: negated ? 0 : b)
430
+ pass = got[:matched] == true
431
+ return nil if pass != negated
432
+
433
+ received = got[:found] ? "\n#{got[:text]}" : "<element(s) not found>"
434
+ raise AssertionError,
435
+ "expect(locator).#{negated ? 'not.' : ''}toMatchAriaSnapshot(expected) failed\n\nLocator: #{locator}\n" \
436
+ "Expected: \n#{template.strip}\nReceived: #{received}\nTimeout: #{b}ms\n"
437
+ end
438
+
439
+ # The element looks like its baseline `name` (see Snapshot).
440
+ def to_have_screenshot(name, timeout: nil, **options)
441
+ raise UsageError, "toHaveScreenshot cannot be negated" if negated
442
+
443
+ Snapshot.assert_screenshot(locator.to_s, name, options, timeout || budget) { locator.screenshot }
444
+ end
445
+
446
+ private
447
+
448
+ def opts(timeout)
449
+ timeout ? with_timeout(timeout) : self
450
+ end
451
+
452
+ def fail_with(spec, last, error, timeout)
453
+ msg = Expect.render("locator", locator.to_s, spec, negated, timeout || budget, last, error, @message)
454
+ AssertionError.new(msg)
455
+ end
456
+
457
+ # Send the check, let the daemon poll it, and render a failure.
458
+ def check(spec, c, timeout)
459
+ b = timeout || budget
460
+ deadline = Testsurfer.now + b / 1000.0
461
+ args = { "read" => c[:read], "test" => c[:test], "missingOk" => c[:missing_ok], "not" => negated }
462
+ begin
463
+ req = locator.request("expect", args)
464
+ req[:many] = true
465
+ rescue Error => e
466
+ raise fail_with(spec, nil, Expect.error_line(e)[0], b)
467
+ end
468
+ loop do
469
+ left = [((deadline - Testsurfer.now) * 1000).round, 1].max
470
+ begin
471
+ r = locator.page.locate_waiting(req, left)
472
+ rescue Error => e
473
+ line, fatal = Expect.error_line(e)
474
+ raise fail_with(spec, nil, line, b) if fatal || Testsurfer.now >= deadline
475
+
476
+ # Not fatal (a navigation under the call): wait on.
477
+ sleep 0.05
478
+ next
479
+ end
480
+ return nil if r["k"] == "ok"
481
+
482
+ if r["k"] == "strict"
483
+ line, = Expect.error_line(locator.strict_error("expect.#{spec.name}", r))
484
+ raise fail_with(spec, nil, line, b)
485
+ end
486
+ s = r["sample"].is_a?(Hash) ? r["sample"] : {}
487
+ raise fail_with(spec, Expect::Sample.new(found: false), nil, b) if !s["found"] && !s["missingOk"]
488
+
489
+ out = yield(s)
490
+ out.log = ["locator resolved to #{s['p']}"] if out.log.nil? && s["p"]
491
+ raise fail_with(spec, out, nil, b)
492
+ end
493
+ end
494
+
495
+ # A boolean element state: passes when `op` reads `want`.
496
+ def state(name, yes, no, op, want, timeout)
497
+ spec = Expect::Spec.new(name, "", want ? yes : no)
498
+ c = { read: { "op" => op }, test: { "t" => "eq", "v" => want }, missing_ok: false }
499
+ check(spec, c, timeout) { |s| Expect::Sample.new(found: true, received: s["r"] == true ? yes : no) }
500
+ end
501
+
502
+ def text(name, expected, substring, ignore_case, inner, timeout)
503
+ spec = Expect::Spec.new(name, "expected", TextMatch.show(expected))
504
+ if TextMatch.regex?(expected)
505
+ spec.labels("Expected pattern", "Received string")
506
+ elsif substring
507
+ spec.labels("Expected substring", "Received string")
508
+ end
509
+ is_re = TextMatch.regex?(expected)
510
+ c = { read: { "op" => inner ? "innerText" : "elText" },
511
+ test: { "t" => "text", "e" => TextMatch.wire_plain(expected), "substring" => substring, "ignoreCase" => ignore_case },
512
+ missing_ok: false }
513
+ check(spec, c, timeout) do |s|
514
+ t = s["r"].is_a?(String) ? s["r"] : ""
515
+ Expect::Sample.new(found: true, received: JSON.generate(is_re ? t : Expect.normalize(t)))
516
+ end
517
+ end
518
+
519
+ def texts(name, expected, substring, ignore_case, inner, timeout)
520
+ expected = expected.map { |e| TextMatch.check!(e) }
521
+ spec = Expect::Spec.new(name, "expected", Expect.list_json(expected))
522
+ c = { read: { "op" => inner ? "innerTexts" : "elTexts", "many" => true },
523
+ test: { "t" => "texts", "e" => expected.map { |e| TextMatch.wire_plain(e) }, "substring" => substring, "ignoreCase" => ignore_case },
524
+ missing_ok: false }
525
+ neg = negated
526
+ check(spec, c, timeout) do |s|
527
+ t = s["r"].is_a?(Array) ? s["r"].map(&:to_s) : []
528
+ out = Expect.array_out(expected, t, s["m"].is_a?(Array) ? s["m"] : [], neg)
529
+ out.log = Expect.resolved_log(t.length)
530
+ out
531
+ end
532
+ end
533
+ end
534
+
535
+ # Assertions on a page; see `Testsurfer.expect`.
536
+ class PageAssertions
537
+ include Negatable
538
+
539
+ BACKOFF = [0, 20, 50, 100, 100, 250].freeze
540
+
541
+ attr_reader :page, :negated
542
+
543
+ def initialize(page, negated: false, timeout: nil)
544
+ @page = page
545
+ @negated = negated
546
+ @timeout = timeout
547
+ end
548
+
549
+ def not
550
+ PageAssertions.new(page, negated: !negated, timeout: @timeout)
551
+ end
552
+
553
+ def with_timeout(ms)
554
+ PageAssertions.new(page, negated: negated, timeout: ms)
555
+ end
556
+
557
+ def budget
558
+ @timeout || page.timeouts.expect
559
+ end
560
+
561
+ # The page URL equals `expected` (resolved against the base URL) or matches the pattern.
562
+ def to_have_url(expected, timeout: nil, ignore_case: nil) # rubocop:disable Lint/UnusedMethodArgument
563
+ expected = TextMatch.check!(expected)
564
+ expected = page.resolve_url(expected) unless TextMatch.regex?(expected)
565
+ poll(Expect::Spec.new("toHaveURL", "expected", TextMatch.show(expected)), Expect.page_test("location.href", expected, false), timeout)
566
+ end
567
+
568
+ # The document title equals `expected` (whitespace-normalized) or matches the pattern.
569
+ def to_have_title(expected, timeout: nil)
570
+ expected = TextMatch.check!(expected)
571
+ poll(Expect::Spec.new("toHaveTitle", "expected", TextMatch.show(expected)), Expect.page_test("document.title", expected, true), timeout)
572
+ end
573
+
574
+ # The page looks like its baseline `name` (see Snapshot).
575
+ def to_have_screenshot(name, timeout: nil, full_page: false, **options)
576
+ raise UsageError, "toHaveScreenshot cannot be negated" if negated
577
+
578
+ Snapshot.assert_screenshot("page", name, options, timeout || budget) { page.screenshot(full_page: full_page) }
579
+ end
580
+
581
+ private
582
+
583
+ # Poll `expr` (a page expression yielding `[value, pass]`) until it
584
+ # passes, or fails when negated. The test runs in the page, so a
585
+ # pattern is a JavaScript regular expression, as everywhere else.
586
+ def poll(spec, expr, timeout)
587
+ b = timeout || budget
588
+ deadline = Testsurfer.now + b / 1000.0
589
+ last = nil
590
+ attempt = 0
591
+ loop do
592
+ begin
593
+ v, pass = page.evaluate(expr)
594
+ return nil if pass != negated
595
+
596
+ last = v
597
+ rescue Error
598
+ nil
599
+ end
600
+ break if Testsurfer.now >= deadline
601
+
602
+ sleep BACKOFF[[attempt, BACKOFF.length - 1].min] / 1000.0
603
+ attempt += 1
604
+ end
605
+ sample = last.nil? ? nil : Expect::Sample.new(found: true, received: JSON.generate(last.to_s))
606
+ raise AssertionError, Expect.render("page", nil, spec, negated, b, sample, nil, nil)
607
+ end
608
+ end
609
+
610
+ # A value assertion that polls, as Playwright's `expect.poll`:
611
+ # `Testsurfer.expect_poll { page.title }.to_equal("Done")`.
612
+ class Poll
613
+ include Negatable
614
+
615
+ def initialize(timeout: 5000, intervals: [100, 250, 500, 1000], negated: false, &read)
616
+ @read = read
617
+ @timeout = timeout
618
+ @intervals = intervals.empty? ? [100, 250, 500, 1000] : intervals
619
+ @negated = negated
620
+ end
621
+
622
+ def not
623
+ Poll.new(timeout: @timeout, intervals: @intervals, negated: !@negated, &@read)
624
+ end
625
+
626
+ # Wait until the value equals `want`.
627
+ def to_equal(want)
628
+ wait("toEqual", want) { |v| v == want }
629
+ end
630
+ alias to_eq to_equal
631
+ alias to_be to_equal
632
+
633
+ # Wait until the block accepts the value.
634
+ def to_satisfy(&test)
635
+ wait("toSatisfy", "a value the block accepts") { |v| test.call(v) }
636
+ end
637
+
638
+ private
639
+
640
+ def wait(_name, want)
641
+ deadline = Testsurfer.now + @timeout / 1000.0
642
+ last = nil
643
+ attempt = 0
644
+ loop do
645
+ begin
646
+ v = @read.call
647
+ return nil if (yield v) != @negated
648
+
649
+ last = [:ok, v]
650
+ rescue StandardError => e
651
+ raise if e.is_a?(NoMethodError) || e.is_a?(NameError)
652
+
653
+ last = [:err, e]
654
+ end
655
+ break if Testsurfer.now >= deadline
656
+
657
+ sleep @intervals[[attempt, @intervals.length - 1].min] / 1000.0
658
+ attempt += 1
659
+ end
660
+ received = if last.nil? then "nothing"
661
+ elsif last[0] == :ok then last[1].inspect
662
+ else "error: #{last[1].message}"
663
+ end
664
+ raise AssertionError,
665
+ "expect.poll: Timeout #{@timeout}ms exceeded.\n\nExpected: #{@negated ? 'not ' : ''}#{want.inspect}\nReceived: #{received}\n"
666
+ end
667
+ end
668
+
669
+ module_function
670
+
671
+ # Assertions on a Locator or a Page.
672
+ def expect(target, timeout: nil, message: nil)
673
+ case target
674
+ when Locator then LocatorAssertions.new(target, timeout: timeout, message: message)
675
+ when Page then PageAssertions.new(target, timeout: timeout)
676
+ else raise UsageError, "expect: needs a Locator or a Page, got #{target.class}"
677
+ end
678
+ end
679
+
680
+ # Poll the block until its value passes; see Poll.
681
+ def expect_poll(timeout: 5000, intervals: [100, 250, 500, 1000], &read)
682
+ Poll.new(timeout: timeout, intervals: intervals, &read)
683
+ end
684
+ end