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,300 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "fileutils"
|
|
4
|
+
require "zlib"
|
|
5
|
+
|
|
6
|
+
module Testsurfer
|
|
7
|
+
# Enough PNG to compare screenshots: 8- and 16-bit gray, gray+alpha,
|
|
8
|
+
# RGB, RGBA and palette images, non-interlaced, read as RGBA; written as RGBA.
|
|
9
|
+
module PNG
|
|
10
|
+
MAGIC = "\x89PNG\r\n\x1a\n".b
|
|
11
|
+
Image = Struct.new(:width, :height, :rgba)
|
|
12
|
+
|
|
13
|
+
module_function
|
|
14
|
+
|
|
15
|
+
def decode(bytes)
|
|
16
|
+
bytes = bytes.b
|
|
17
|
+
raise UsageError, "snapshot: not a PNG" unless bytes.start_with?(MAGIC)
|
|
18
|
+
|
|
19
|
+
pos = 8
|
|
20
|
+
ihdr = nil
|
|
21
|
+
palette = nil
|
|
22
|
+
trns = nil
|
|
23
|
+
idat = +"".b
|
|
24
|
+
while pos + 8 <= bytes.bytesize
|
|
25
|
+
len = bytes[pos, 4].unpack1("N")
|
|
26
|
+
type = bytes[pos + 4, 4]
|
|
27
|
+
data = bytes[pos + 8, len]
|
|
28
|
+
pos += 12 + len
|
|
29
|
+
case type
|
|
30
|
+
when "IHDR" then ihdr = data.unpack("NNCCCCC")
|
|
31
|
+
when "PLTE" then palette = data.bytes.each_slice(3).to_a
|
|
32
|
+
when "tRNS" then trns = data.bytes
|
|
33
|
+
when "IDAT" then idat << data
|
|
34
|
+
when "IEND" then break
|
|
35
|
+
end
|
|
36
|
+
end
|
|
37
|
+
raise UsageError, "snapshot: not a PNG: no header" if ihdr.nil?
|
|
38
|
+
|
|
39
|
+
w, h, depth, color, _comp, _filter, interlace = ihdr
|
|
40
|
+
raise UsageError, "snapshot: interlaced PNGs are not supported" unless interlace.zero?
|
|
41
|
+
|
|
42
|
+
channels = { 0 => 1, 2 => 3, 3 => 1, 4 => 2, 6 => 4 }.fetch(color) { raise UsageError, "snapshot: PNG color type #{color}" }
|
|
43
|
+
bits = depth * channels
|
|
44
|
+
bpp = [(bits + 7) / 8, 1].max
|
|
45
|
+
stride = (w * bits + 7) / 8
|
|
46
|
+
raw = Zlib::Inflate.inflate(idat)
|
|
47
|
+
prev = Array.new(stride, 0)
|
|
48
|
+
rgba = String.new(capacity: w * h * 4, encoding: Encoding::BINARY)
|
|
49
|
+
h.times do |y|
|
|
50
|
+
off = y * (stride + 1)
|
|
51
|
+
ftype = raw.getbyte(off)
|
|
52
|
+
line = raw.byteslice(off + 1, stride).bytes
|
|
53
|
+
unfilter(ftype, line, prev, bpp)
|
|
54
|
+
prev = line
|
|
55
|
+
rgba << row_rgba(line, w, depth, color, palette, trns)
|
|
56
|
+
end
|
|
57
|
+
Image.new(w, h, rgba)
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
def unfilter(ftype, line, prev, bpp)
|
|
61
|
+
n = line.length
|
|
62
|
+
case ftype
|
|
63
|
+
when 0 then nil
|
|
64
|
+
when 1 then (bpp...n).each { |i| line[i] = (line[i] + line[i - bpp]) & 0xff }
|
|
65
|
+
when 2 then n.times { |i| line[i] = (line[i] + prev[i]) & 0xff }
|
|
66
|
+
when 3
|
|
67
|
+
n.times { |i| line[i] = (line[i] + (((i >= bpp ? line[i - bpp] : 0) + prev[i]) >> 1)) & 0xff }
|
|
68
|
+
when 4
|
|
69
|
+
n.times do |i|
|
|
70
|
+
a = i >= bpp ? line[i - bpp] : 0
|
|
71
|
+
b = prev[i]
|
|
72
|
+
c = i >= bpp ? prev[i - bpp] : 0
|
|
73
|
+
p = a + b - c
|
|
74
|
+
pa = (p - a).abs
|
|
75
|
+
pb = (p - b).abs
|
|
76
|
+
pc = (p - c).abs
|
|
77
|
+
pred = pa <= pb && pa <= pc ? a : (pb <= pc ? b : c)
|
|
78
|
+
line[i] = (line[i] + pred) & 0xff
|
|
79
|
+
end
|
|
80
|
+
else raise UsageError, "snapshot: bad PNG filter #{ftype}"
|
|
81
|
+
end
|
|
82
|
+
end
|
|
83
|
+
|
|
84
|
+
def row_rgba(line, w, depth, color, palette, trns)
|
|
85
|
+
if depth == 8
|
|
86
|
+
case color
|
|
87
|
+
when 6 then return line.pack("C*")
|
|
88
|
+
when 2 then return line.each_slice(3).flat_map { |r, g, b| [r, g, b, 255] }.pack("C*")
|
|
89
|
+
when 0 then return line.flat_map { |g| [g, g, g, 255] }.pack("C*")
|
|
90
|
+
when 4 then return line.each_slice(2).flat_map { |g, a| [g, g, g, a] }.pack("C*")
|
|
91
|
+
end
|
|
92
|
+
end
|
|
93
|
+
if depth == 16
|
|
94
|
+
hi = line.each_slice(2).map(&:first)
|
|
95
|
+
return row_rgba(hi, w, 8, color, palette, trns)
|
|
96
|
+
end
|
|
97
|
+
# Sub-byte depths and palettes: one sample per pixel.
|
|
98
|
+
samples = []
|
|
99
|
+
line.each { |byte| (8 / depth).times { |k| samples << ((byte >> (8 - depth * (k + 1))) & ((1 << depth) - 1)) } }
|
|
100
|
+
samples = samples.first(w)
|
|
101
|
+
if color == 3
|
|
102
|
+
samples.flat_map { |i| r, g, b = palette[i] || [0, 0, 0]; [r, g, b, trns && i < trns.length ? trns[i] : 255] }.pack("C*")
|
|
103
|
+
else
|
|
104
|
+
scale = 255 / ((1 << depth) - 1)
|
|
105
|
+
samples.flat_map { |g| v = g * scale; [v, v, v, 255] }.pack("C*")
|
|
106
|
+
end
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
def chunk(type, data)
|
|
110
|
+
[data.bytesize].pack("N") + type + data + [Zlib.crc32(type + data)].pack("N")
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
def encode(img)
|
|
114
|
+
raw = String.new(capacity: (img.width * 4 + 1) * img.height, encoding: Encoding::BINARY)
|
|
115
|
+
img.height.times { |y| raw << "\x00".b << img.rgba.byteslice(y * img.width * 4, img.width * 4) }
|
|
116
|
+
MAGIC + chunk("IHDR", [img.width, img.height, 8, 6, 0, 0, 0].pack("NNCCCCC")) +
|
|
117
|
+
chunk("IDAT", Zlib::Deflate.deflate(raw)) + chunk("IEND", "".b)
|
|
118
|
+
end
|
|
119
|
+
end
|
|
120
|
+
|
|
121
|
+
# Screenshot and snapshot assertions (Playwright's toHaveScreenshot
|
|
122
|
+
# and toMatchSnapshot), compared as testsurfer for Node compares them:
|
|
123
|
+
# a pixel counts as changed when one of its channels differs by more
|
|
124
|
+
# than `threshold` (0 to 1, default 0.2), and the test fails when more
|
|
125
|
+
# pixels changed than `max_diff_pixels` (or the `max_diff_pixel_ratio`
|
|
126
|
+
# share) allows.
|
|
127
|
+
#
|
|
128
|
+
# Baselines live in `spec/snapshots/` (or TESTSURFER_SNAPSHOT_DIR),
|
|
129
|
+
# named `<name>-<platform>.png`. A missing baseline is written and the
|
|
130
|
+
# test fails, as in Playwright; TESTSURFER_UPDATE_SNAPSHOTS=1 rewrites
|
|
131
|
+
# them all. A failed comparison leaves `<name>-actual.png` and
|
|
132
|
+
# `<name>-diff.png` in TESTSURFER_OUTPUT_DIR (default `tmp/testsurfer-results`).
|
|
133
|
+
module Snapshot
|
|
134
|
+
SETTLE = 0.1
|
|
135
|
+
|
|
136
|
+
module_function
|
|
137
|
+
|
|
138
|
+
def platform
|
|
139
|
+
case RbConfig::CONFIG["host_os"]
|
|
140
|
+
when /darwin/ then "darwin"
|
|
141
|
+
when /mswin|mingw|cygwin/ then "win32"
|
|
142
|
+
when /linux/ then "linux"
|
|
143
|
+
else RbConfig::CONFIG["host_os"]
|
|
144
|
+
end
|
|
145
|
+
end
|
|
146
|
+
|
|
147
|
+
def safe(name)
|
|
148
|
+
s = name.to_s.gsub(/[^A-Za-z0-9._-]/, "-").gsub(/\A-+|-+\z/, "")
|
|
149
|
+
s.empty? ? "screenshot" : s[0, 100]
|
|
150
|
+
end
|
|
151
|
+
|
|
152
|
+
def snapshot_dir
|
|
153
|
+
ENV["TESTSURFER_SNAPSHOT_DIR"] || File.join(Dir.pwd, "spec", "snapshots")
|
|
154
|
+
end
|
|
155
|
+
|
|
156
|
+
def output_dir
|
|
157
|
+
ENV["TESTSURFER_OUTPUT_DIR"] || File.join(Dir.pwd, "tmp", "testsurfer-results")
|
|
158
|
+
end
|
|
159
|
+
|
|
160
|
+
# Where the baseline for `name` lives.
|
|
161
|
+
def snapshot_path(name)
|
|
162
|
+
ext = File.extname(name.to_s)
|
|
163
|
+
stem = File.basename(name.to_s, ext)
|
|
164
|
+
ext = ".png" if ext.empty?
|
|
165
|
+
File.join(snapshot_dir, "#{safe(stem)}-#{platform}#{ext}")
|
|
166
|
+
end
|
|
167
|
+
|
|
168
|
+
def update_all?
|
|
169
|
+
%w[1 all].include?(ENV["TESTSURFER_UPDATE_SNAPSHOTS"])
|
|
170
|
+
end
|
|
171
|
+
|
|
172
|
+
def write(path, bytes)
|
|
173
|
+
FileUtils.mkdir_p(File.dirname(path))
|
|
174
|
+
File.binwrite(path, bytes)
|
|
175
|
+
end
|
|
176
|
+
|
|
177
|
+
# Changed pixels between two same-size images, and the diff image:
|
|
178
|
+
# red where pixels differ, the expected image faded elsewhere.
|
|
179
|
+
def diff(expected, actual, threshold)
|
|
180
|
+
limit = threshold * 255.0
|
|
181
|
+
changed = 0
|
|
182
|
+
a = expected.rgba.bytes
|
|
183
|
+
b = actual.rgba.bytes
|
|
184
|
+
out = String.new(capacity: a.length, encoding: Encoding::BINARY)
|
|
185
|
+
(a.length / 4).times do |i|
|
|
186
|
+
o = i * 4
|
|
187
|
+
max = [(a[o] - b[o]).abs, (a[o + 1] - b[o + 1]).abs, (a[o + 2] - b[o + 2]).abs, (a[o + 3] - b[o + 3]).abs].max
|
|
188
|
+
if max > limit
|
|
189
|
+
changed += 1
|
|
190
|
+
out << [255, 0, 0, 255].pack("C4")
|
|
191
|
+
else
|
|
192
|
+
gray = (a[o] + a[o + 1] + a[o + 2]) / 3.0
|
|
193
|
+
f = (255.0 - (255.0 - gray) * 0.3).to_i
|
|
194
|
+
out << [f, f, f, 255].pack("C4")
|
|
195
|
+
end
|
|
196
|
+
end
|
|
197
|
+
[changed, PNG::Image.new(expected.width, expected.height, out)]
|
|
198
|
+
end
|
|
199
|
+
|
|
200
|
+
# [:match] | [:differs, changed, allowed, diff_image] | [:size, [ew, eh], [aw, ah]]
|
|
201
|
+
def compare(expected, actual_png, o)
|
|
202
|
+
actual = PNG.decode(actual_png)
|
|
203
|
+
if [actual.width, actual.height] != [expected.width, expected.height]
|
|
204
|
+
return [:size, [expected.width, expected.height], [actual.width, actual.height]]
|
|
205
|
+
end
|
|
206
|
+
|
|
207
|
+
total = expected.width * expected.height
|
|
208
|
+
by_ratio = ((o[:max_diff_pixel_ratio] || 0.0) * total).floor
|
|
209
|
+
allowed = [o[:max_diff_pixels] || 0, by_ratio].max
|
|
210
|
+
changed, image = diff(expected, actual, o[:threshold] || 0.2)
|
|
211
|
+
changed <= allowed ? [:match] : [:differs, changed, allowed, image]
|
|
212
|
+
end
|
|
213
|
+
|
|
214
|
+
def mismatch(what, baseline, name, actual_png, found)
|
|
215
|
+
out = output_dir
|
|
216
|
+
stem = File.basename(name.to_s, File.extname(name.to_s))
|
|
217
|
+
actual_file = File.join(out, "#{safe(stem)}-actual.png")
|
|
218
|
+
begin
|
|
219
|
+
write(actual_file, actual_png)
|
|
220
|
+
rescue SystemCallError
|
|
221
|
+
nil
|
|
222
|
+
end
|
|
223
|
+
detail = case found[0]
|
|
224
|
+
when :differs
|
|
225
|
+
diff_file = File.join(out, "#{safe(stem)}-diff.png")
|
|
226
|
+
begin
|
|
227
|
+
write(diff_file, PNG.encode(found[3]))
|
|
228
|
+
rescue SystemCallError
|
|
229
|
+
nil
|
|
230
|
+
end
|
|
231
|
+
"#{found[1]} pixels differ (allowed #{found[2]}); diff: #{diff_file}"
|
|
232
|
+
when :size
|
|
233
|
+
"expected an image #{found[1][0]}px by #{found[1][1]}px, received #{found[2][0]}px by #{found[2][1]}px"
|
|
234
|
+
else ""
|
|
235
|
+
end
|
|
236
|
+
AssertionError.new("#{what}: #{stem} does not match #{baseline}: #{detail}; actual: #{actual_file}")
|
|
237
|
+
end
|
|
238
|
+
|
|
239
|
+
# A missing baseline (or one being updated): write `bytes`. Raises
|
|
240
|
+
# the error that fails the test, unless updating.
|
|
241
|
+
def record_baseline(what, path, bytes)
|
|
242
|
+
write(path, bytes)
|
|
243
|
+
return nil if update_all?
|
|
244
|
+
|
|
245
|
+
raise AssertionError, "#{what}: no baseline; wrote #{path}. Check it in and run again."
|
|
246
|
+
end
|
|
247
|
+
|
|
248
|
+
# `toMatchSnapshot` for bytes: a PNG compares as an image, anything
|
|
249
|
+
# else byte for byte. A missing baseline is written and fails.
|
|
250
|
+
def match_snapshot(value, name, **options)
|
|
251
|
+
value = value.b
|
|
252
|
+
path = snapshot_path(name)
|
|
253
|
+
return record_baseline("toMatchSnapshot", path, value) if update_all? || !File.exist?(path)
|
|
254
|
+
|
|
255
|
+
want = File.binread(path)
|
|
256
|
+
if value.start_with?(PNG::MAGIC[0, 4]) && want.start_with?(PNG::MAGIC[0, 4])
|
|
257
|
+
found = compare(PNG.decode(want), value, options)
|
|
258
|
+
raise mismatch("toMatchSnapshot", path, name, value, found) unless found[0] == :match
|
|
259
|
+
|
|
260
|
+
return nil
|
|
261
|
+
end
|
|
262
|
+
raise AssertionError, "toMatchSnapshot: #{path} differs from the received value." unless value == want
|
|
263
|
+
|
|
264
|
+
nil
|
|
265
|
+
end
|
|
266
|
+
|
|
267
|
+
# `toHaveScreenshot`: capture until it matches the baseline or `budget`
|
|
268
|
+
# (ms) runs out. A missing baseline is taken once two captures in a
|
|
269
|
+
# row are identical (animations settled), written, and fails the test.
|
|
270
|
+
def assert_screenshot(target, name, options, budget, &capture)
|
|
271
|
+
path = snapshot_path(name)
|
|
272
|
+
deadline = Testsurfer.now + budget / 1000.0
|
|
273
|
+
if update_all? || !File.exist?(path)
|
|
274
|
+
prev = capture.call
|
|
275
|
+
while Testsurfer.now < deadline
|
|
276
|
+
sleep SETTLE
|
|
277
|
+
nxt = capture.call
|
|
278
|
+
break if nxt == prev
|
|
279
|
+
|
|
280
|
+
prev = nxt
|
|
281
|
+
end
|
|
282
|
+
return record_baseline("#{target} toHaveScreenshot", path, prev)
|
|
283
|
+
end
|
|
284
|
+
expected = PNG.decode(File.binread(path))
|
|
285
|
+
loop do
|
|
286
|
+
shot = capture.call
|
|
287
|
+
found = compare(expected, shot, options)
|
|
288
|
+
return nil if found[0] == :match
|
|
289
|
+
raise mismatch("#{target} toHaveScreenshot", path, name, shot, found) if Testsurfer.now >= deadline
|
|
290
|
+
|
|
291
|
+
sleep SETTLE
|
|
292
|
+
end
|
|
293
|
+
end
|
|
294
|
+
end
|
|
295
|
+
|
|
296
|
+
# `toMatchSnapshot` for bytes; see Snapshot.
|
|
297
|
+
def self.match_snapshot(value, name, **options)
|
|
298
|
+
Snapshot.match_snapshot(value, name, **options)
|
|
299
|
+
end
|
|
300
|
+
end
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
require "fileutils"
|
|
5
|
+
|
|
6
|
+
module Testsurfer
|
|
7
|
+
# A storage state, as Playwright saves it: a hash with "cookies" (see
|
|
8
|
+
# Cookies) and "origins" ([{ "origin", "localStorage" => [{ "name", "value" }] }]).
|
|
9
|
+
module StorageState
|
|
10
|
+
module_function
|
|
11
|
+
|
|
12
|
+
# Read a state saved with `storage_state(path: ...)`.
|
|
13
|
+
def load(path)
|
|
14
|
+
coerce(JSON.parse(File.read(path)))
|
|
15
|
+
rescue SystemCallError, JSON::ParserError => e
|
|
16
|
+
raise UsageError, "storageState #{path}: #{e.message}"
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
# A state from a hash (string or symbol keys) or a path to its JSON.
|
|
20
|
+
def coerce(s)
|
|
21
|
+
return load(s.to_s) if s.is_a?(String) || (defined?(Pathname) && s.is_a?(Pathname))
|
|
22
|
+
|
|
23
|
+
h = JSON.parse(JSON.generate(s))
|
|
24
|
+
{ "cookies" => h["cookies"] || [], "origins" => h["origins"] || [] }
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
def save(state, path)
|
|
28
|
+
FileUtils.mkdir_p(File.dirname(path))
|
|
29
|
+
File.write(path, JSON.pretty_generate(state))
|
|
30
|
+
rescue SystemCallError => e
|
|
31
|
+
raise UsageError, "storageState #{path}: #{e.message}"
|
|
32
|
+
end
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
class BrowserContext
|
|
36
|
+
READ_ORIGIN = <<~JS
|
|
37
|
+
() => {
|
|
38
|
+
const o = location.origin;
|
|
39
|
+
if (!o || o === 'null') return null;
|
|
40
|
+
const items = [];
|
|
41
|
+
for (let i = 0; i < localStorage.length; i++) {
|
|
42
|
+
const k = localStorage.key(i);
|
|
43
|
+
if (k !== null) items.push({ name: k, value: localStorage.getItem(k) ?? '' });
|
|
44
|
+
}
|
|
45
|
+
return { origin: o, localStorage: items };
|
|
46
|
+
}
|
|
47
|
+
JS
|
|
48
|
+
|
|
49
|
+
# The context's cookies and the localStorage of its pages' origins;
|
|
50
|
+
# with `path`, also written there as JSON.
|
|
51
|
+
def storage_state(path: nil)
|
|
52
|
+
origins = []
|
|
53
|
+
pages.each do |p|
|
|
54
|
+
next if p.page_id.nil?
|
|
55
|
+
|
|
56
|
+
o = begin
|
|
57
|
+
p.evaluate(READ_ORIGIN)
|
|
58
|
+
rescue Error
|
|
59
|
+
nil
|
|
60
|
+
end
|
|
61
|
+
next unless o.is_a?(Hash) && !o["localStorage"].to_a.empty?
|
|
62
|
+
|
|
63
|
+
origins << o unless origins.any? { |x| x["origin"] == o["origin"] }
|
|
64
|
+
end
|
|
65
|
+
state = { "cookies" => cookies, "origins" => origins }
|
|
66
|
+
StorageState.save(state, path) if path
|
|
67
|
+
state
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
# Put a state's cookies in the jar and its localStorage in each origin.
|
|
71
|
+
def apply_storage_state(state)
|
|
72
|
+
add_cookies(state["cookies"]) unless state["cookies"].empty?
|
|
73
|
+
origins = state["origins"].reject { |o| o["localStorage"].to_a.empty? }
|
|
74
|
+
return if origins.empty?
|
|
75
|
+
|
|
76
|
+
# A page at each origin, its document made up by a route, sets the items.
|
|
77
|
+
page = new_page
|
|
78
|
+
origins.each do |o|
|
|
79
|
+
url = "#{o['origin']}/__testsurfer_storage_state__"
|
|
80
|
+
page.route(url) { |r| r.fulfill(body: "<!doctype html><title>storage</title>", content_type: "text/html") }
|
|
81
|
+
page.goto(url)
|
|
82
|
+
page.evaluate("(items) => { for (const i of items) localStorage.setItem(i.name, i.value); }", arg: o["localStorage"])
|
|
83
|
+
page.unroute_all
|
|
84
|
+
end
|
|
85
|
+
page.close
|
|
86
|
+
end
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
# A context whose cookies and localStorage live in a directory: loaded
|
|
90
|
+
# on launch, written back on `close`, so a later launch with the same
|
|
91
|
+
# directory starts where this one ended. Session cookies end with it.
|
|
92
|
+
class PersistentContext
|
|
93
|
+
attr_reader :browser, :context
|
|
94
|
+
|
|
95
|
+
def initialize(browser, context, file)
|
|
96
|
+
@browser = browser
|
|
97
|
+
@context = context
|
|
98
|
+
@file = file
|
|
99
|
+
end
|
|
100
|
+
|
|
101
|
+
# Save the state to the directory, then close the context and the browser.
|
|
102
|
+
def close
|
|
103
|
+
begin
|
|
104
|
+
state = @context.storage_state
|
|
105
|
+
state["cookies"] = state["cookies"].select { |c| c["expires"].positive? }
|
|
106
|
+
StorageState.save(state, @file)
|
|
107
|
+
rescue Error
|
|
108
|
+
nil
|
|
109
|
+
end
|
|
110
|
+
@context.close
|
|
111
|
+
@browser.close
|
|
112
|
+
end
|
|
113
|
+
|
|
114
|
+
def method_missing(name, *args, **kw, &blk)
|
|
115
|
+
return super unless @context.respond_to?(name)
|
|
116
|
+
|
|
117
|
+
@context.public_send(name, *args, **kw, &blk)
|
|
118
|
+
end
|
|
119
|
+
|
|
120
|
+
def respond_to_missing?(name, include_private = false)
|
|
121
|
+
@context.respond_to?(name) || super
|
|
122
|
+
end
|
|
123
|
+
end
|
|
124
|
+
|
|
125
|
+
# A page's localStorage or sessionStorage, for its current origin.
|
|
126
|
+
class WebStorage
|
|
127
|
+
def initialize(page, area)
|
|
128
|
+
@page = page
|
|
129
|
+
@area = area
|
|
130
|
+
end
|
|
131
|
+
|
|
132
|
+
def get_item(name)
|
|
133
|
+
call("return s.getItem(a);", name)
|
|
134
|
+
end
|
|
135
|
+
alias [] get_item
|
|
136
|
+
|
|
137
|
+
def set_item(name, value)
|
|
138
|
+
call("s.setItem(a[0], a[1]); return null;", [name.to_s, value.to_s])
|
|
139
|
+
nil
|
|
140
|
+
end
|
|
141
|
+
alias []= set_item
|
|
142
|
+
|
|
143
|
+
def remove_item(name)
|
|
144
|
+
call("s.removeItem(a); return null;", name)
|
|
145
|
+
nil
|
|
146
|
+
end
|
|
147
|
+
|
|
148
|
+
def clear
|
|
149
|
+
call("s.clear(); return null;", nil)
|
|
150
|
+
nil
|
|
151
|
+
end
|
|
152
|
+
|
|
153
|
+
# Every item, in key order: [{ "name", "value" }].
|
|
154
|
+
def items
|
|
155
|
+
call("const out = []; for (let i = 0; i < s.length; i++) { const k = s.key(i); out.push({ name: k, value: s.getItem(k) ?? '' }); } return out;", nil)
|
|
156
|
+
end
|
|
157
|
+
|
|
158
|
+
private
|
|
159
|
+
|
|
160
|
+
def call(body, arg)
|
|
161
|
+
@page.evaluate("(a) => { const s = window.#{@area}; #{body} }", arg: arg)
|
|
162
|
+
end
|
|
163
|
+
end
|
|
164
|
+
|
|
165
|
+
class Page
|
|
166
|
+
# The page's localStorage, for its current origin.
|
|
167
|
+
def local_storage
|
|
168
|
+
WebStorage.new(self, "localStorage")
|
|
169
|
+
end
|
|
170
|
+
|
|
171
|
+
# The page's sessionStorage, for its current origin.
|
|
172
|
+
def session_storage
|
|
173
|
+
WebStorage.new(self, "sessionStorage")
|
|
174
|
+
end
|
|
175
|
+
end
|
|
176
|
+
end
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Testsurfer
|
|
4
|
+
# A value one thread sets once and others wait for, with a timeout.
|
|
5
|
+
class Slot
|
|
6
|
+
def initialize
|
|
7
|
+
@lock = Mutex.new
|
|
8
|
+
@cond = ConditionVariable.new
|
|
9
|
+
@set = false
|
|
10
|
+
@value = nil
|
|
11
|
+
@error = nil
|
|
12
|
+
end
|
|
13
|
+
|
|
14
|
+
def set(value)
|
|
15
|
+
@lock.synchronize do
|
|
16
|
+
return false if @set
|
|
17
|
+
|
|
18
|
+
@set = true
|
|
19
|
+
@value = value
|
|
20
|
+
@cond.broadcast
|
|
21
|
+
end
|
|
22
|
+
true
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
def fail(error)
|
|
26
|
+
@lock.synchronize do
|
|
27
|
+
return false if @set
|
|
28
|
+
|
|
29
|
+
@set = true
|
|
30
|
+
@error = error
|
|
31
|
+
@cond.broadcast
|
|
32
|
+
end
|
|
33
|
+
true
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
def set?
|
|
37
|
+
@lock.synchronize { @set }
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
# The value, waiting at most `timeout` seconds (nil: no limit).
|
|
41
|
+
# Returns [true, value] or [false, nil] on timeout.
|
|
42
|
+
def wait(timeout = nil)
|
|
43
|
+
deadline = timeout && (Testsurfer.now + timeout)
|
|
44
|
+
@lock.synchronize do
|
|
45
|
+
until @set
|
|
46
|
+
left = deadline && (deadline - Testsurfer.now)
|
|
47
|
+
return [false, nil] if left && left <= 0
|
|
48
|
+
|
|
49
|
+
@cond.wait(@lock, left)
|
|
50
|
+
end
|
|
51
|
+
raise @error if @error
|
|
52
|
+
|
|
53
|
+
[true, @value]
|
|
54
|
+
end
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
def value
|
|
58
|
+
@lock.synchronize { @value }
|
|
59
|
+
end
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
# Monotonic seconds.
|
|
63
|
+
def self.now
|
|
64
|
+
Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
# Run the block in a thread that reports, not raises, what fails in it.
|
|
68
|
+
def self.spawn(&blk)
|
|
69
|
+
Thread.new do
|
|
70
|
+
blk.call
|
|
71
|
+
rescue StandardError => e
|
|
72
|
+
warn "testsurfer: #{e.class}: #{e.message}" if ENV["TESTSURFER_DEBUG"]
|
|
73
|
+
end
|
|
74
|
+
end
|
|
75
|
+
end
|