delta-qa-vision 0.0.1.beta2

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,34 @@
1
+ module DeltaQa
2
+ module Vision
3
+ # The wait for the page's resize event, the same in every adapter: a listener named on the window, so that the page
4
+ # is left without it on every path, whose promise settles at the first resize event — or at false once forgotten,
5
+ # so that no evaluation stays waiting in the page.
6
+ module ResizeWait
7
+ TIMEOUT_MS = 10_000
8
+ # Statements: listen to the next resize event.
9
+ LISTEN = "window.__deltaQaResized = new Promise((resolve) => { " \
10
+ "window.__deltaQaSettleResize = resolve; " \
11
+ "window.__deltaQaOnResize = () => { window.__deltaQaResizeFired = true; resolve(true); }; " \
12
+ "window.addEventListener('resize', window.__deltaQaOnResize, { once: true }); });".freeze
13
+ # An expression: the promise of the listener, true at the resize event.
14
+ RESIZED = "window.__deltaQaResized".freeze
15
+ # An expression: whether the resize event came.
16
+ FIRED = "window.__deltaQaResizeFired === true".freeze
17
+ # An expression: the promise of the listener, false at the end of the timeout — for a framework that cannot bound
18
+ # an evaluation itself.
19
+ RESIZED_OR_TIMEOUT = "Promise.race([window.__deltaQaResized, " \
20
+ "new Promise((resolve) => setTimeout(() => resolve(false), #{TIMEOUT_MS}))])".freeze
21
+ # Statements: take the listener off and settle its promise.
22
+ FORGET = "if (window.__deltaQaOnResize) window.removeEventListener('resize', window.__deltaQaOnResize); " \
23
+ "if (window.__deltaQaSettleResize) window.__deltaQaSettleResize(false); " \
24
+ "delete window.__deltaQaOnResize; delete window.__deltaQaSettleResize; " \
25
+ "delete window.__deltaQaResized; delete window.__deltaQaResizeFired;".freeze
26
+
27
+ module_function
28
+
29
+ def timed_out(size)
30
+ RuntimeError.new("The page never applied the size #{size}: no resize event came within #{TIMEOUT_MS} ms")
31
+ end
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,237 @@
1
+ require_relative "relay"
2
+ require_relative "resize_wait"
3
+
4
+ module DeltaQa
5
+ module Vision
6
+ # The page of a Selenium test as the relay takes it — the steps of the selenium-webdriver adapter of the JavaScript
7
+ # SDK, the same in every Selenium SDK. WebDriver evaluates in one document at a time: the adapter switches to a frame
8
+ # by its tag, a frame of another origin included, comes back to the top document after each call — where the test
9
+ # must be when it checks — and takes off the mark ChromeDriver leaves on each frame tag it switched into. Chromium's
10
+ # protocol is ChromeDriver's (execute_cdp).
11
+ class SeleniumPageDriver
12
+ FRAME_TAGS = <<~JS.chomp.freeze
13
+ const tags = [];
14
+ const walk = (root) => {
15
+ for (const element of root.querySelectorAll("*")) {
16
+ if (element.localName === "iframe" || element.localName === "frame") tags.push(element);
17
+ if (element.shadowRoot) walk(element.shadowRoot);
18
+ }
19
+ };
20
+ walk(document);
21
+ return tags;
22
+ JS
23
+ DRIVER_MARK = "cd_frame_id_".freeze
24
+ CHROMIUM = /\A(chrome|chromium|msedge|microsoftedge|chrome-headless-shell)\z/i
25
+ CHANGING = ["stale element", "no such frame", "execution context was destroyed"].freeze
26
+ LISTEN_RESIZE = ResizeWait::LISTEN
27
+ WAIT_RESIZE = "return #{ResizeWait::RESIZED_OR_TIMEOUT};".freeze
28
+ FORGET_RESIZE = ResizeWait::FORGET
29
+
30
+ # A session of Chromium's protocol on the page: ChromeDriver's.
31
+ class Session
32
+ def initialize(driver)
33
+ @driver = driver
34
+ end
35
+
36
+ def send(method, params)
37
+ @driver.execute_cdp(method, **params.transform_keys(&:to_sym))
38
+ end
39
+
40
+ # ChromeDriver's own session stays: the driver needs it.
41
+ def close; end
42
+ end
43
+
44
+ # A frame tag held: its parent document's way, and its element there.
45
+ Host = Struct.new(:parent, :element)
46
+
47
+ def initialize(driver)
48
+ @driver = driver
49
+ @natural = nil
50
+ end
51
+
52
+ def framework
53
+ "Selenium"
54
+ end
55
+
56
+ def browser
57
+ capabilities = @driver.capabilities
58
+ name = capabilities.browser_name.to_s
59
+ [CHROMIUM.match?(name), "#{name} #{capabilities.browser_version}".strip]
60
+ end
61
+
62
+ def url
63
+ @driver.current_url
64
+ end
65
+
66
+ def title
67
+ @driver.title
68
+ end
69
+
70
+ def documents
71
+ require_top
72
+ documents = [Relay::PageDocument.new(@driver.execute_script("return document.URL").to_s, 0, [])]
73
+ walk([], documents)
74
+ documents
75
+ end
76
+
77
+ def evaluate(document, function, args)
78
+ within(document.handle) { @driver.execute_script(script(function, 1), args) }
79
+ end
80
+
81
+ def host_of(document)
82
+ path = document.handle
83
+ parent = path[0...-1]
84
+ tags = within(parent) { @driver.execute_script(FRAME_TAGS) }
85
+ if path[-1] >= tags.size
86
+ raise ::Selenium::WebDriver::Error::NoSuchFrameError, "Frame was detached: the frame #{document.url} has no tag in its parent any more"
87
+ end
88
+ Host.new(parent, tags[path[-1]])
89
+ end
90
+
91
+ def evaluate_on(element, function, args)
92
+ within(element.parent) { @driver.execute_script(script(function, 2), element.element, args) }
93
+ end
94
+
95
+ # A reference of WebDriver holds nothing in the page: there is nothing to let go.
96
+ def release(_element); end
97
+
98
+ def document_received(document)
99
+ timeout_s = @driver.manage.timeouts.page_load
100
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout_s
101
+ loop do
102
+ state = within(document.handle) { @driver.execute_script("return document.readyState") }
103
+ return unless state == "loading"
104
+ if Process.clock_gettime(Process::CLOCK_MONOTONIC) > deadline
105
+ raise DocumentStillReceivingError.new(document.url, "still loading after the page load timeout of #{(timeout_s * 1000).to_i} ms")
106
+ end
107
+ sleep 0.05
108
+ end
109
+ end
110
+
111
+ def open_cdp
112
+ unless @driver.respond_to?(:execute_cdp)
113
+ raise TypeError, "This WebDriver gives no access to Chromium's protocol (execute_cdp): Delta-QA Vision takes the page through it" \
114
+ " — drive Chrome, Chromium or Edge with Selenium::WebDriver.for(:chrome) or (:edge)"
115
+ end
116
+ Session.new(@driver)
117
+ end
118
+
119
+ def viewport
120
+ width, height = @driver.execute_script("return [window.innerWidth, window.innerHeight]")
121
+ Relay::Size.new(width.to_i, height.to_i)
122
+ end
123
+
124
+ def resize(size)
125
+ current = viewport
126
+ return if current == size
127
+ @natural ||= current
128
+ session = open_cdp
129
+ @driver.execute_script(LISTEN_RESIZE)
130
+ begin
131
+ if @natural == size
132
+ # Back to the size the page had: the emulation is taken off, the window shows the page again.
133
+ session.send("Emulation.clearDeviceMetricsOverride", {})
134
+ @natural = nil
135
+ else
136
+ # The size of the page itself, not of the window: what Playwright and Puppeteer set too.
137
+ session.send("Emulation.setDeviceMetricsOverride", { "width" => size.width, "height" => size.height, "deviceScaleFactor" => 1, "mobile" => false })
138
+ end
139
+ raise ResizeWait.timed_out(size) unless @driver.execute_script(WAIT_RESIZE) == true
140
+ ensure
141
+ @driver.execute_script(FORGET_RESIZE)
142
+ end
143
+ end
144
+
145
+ def zone_selector_sets(zone, _kind, function)
146
+ require_top
147
+ case zone
148
+ when String
149
+ described = "css selector \"#{zone}\""
150
+ elements = @driver.find_elements(:css, zone)
151
+ when Hash
152
+ raise ArgumentError, "A locator zone is one pair, as find_elements takes it ({css: \"#cart\"}), got #{zone.inspect}" unless zone.size == 1
153
+ described = zone.inspect
154
+ elements = @driver.find_elements(**zone)
155
+ when ::Selenium::WebDriver::Element
156
+ described = "element #{zone.inspect}"
157
+ begin
158
+ connected = @driver.execute_script(script(Relay.capture("connected"), 1), [[zone]])
159
+ rescue ::Selenium::WebDriver::Error::StaleElementReferenceError
160
+ return [described, []]
161
+ end
162
+ elements = connected[0] == true ? [zone] : []
163
+ else
164
+ raise TypeError, "A zone of a Selenium test is a CSS selector, a locator ({css: \"#cart\"}) or an element, got #{zone.inspect}"
165
+ end
166
+ return [described, []] if elements.empty?
167
+ [described, @driver.execute_script(script(function, 1), [elements])]
168
+ end
169
+
170
+ def page_changing?(error)
171
+ return true if error.is_a?(::Selenium::WebDriver::Error::StaleElementReferenceError) || error.is_a?(::Selenium::WebDriver::Error::NoSuchFrameError)
172
+ message = error.message.to_s.downcase
173
+ CHANGING.any? { |marker| message.include?(marker) }
174
+ end
175
+
176
+ private
177
+
178
+ def walk(path, documents)
179
+ tags = within(path) { @driver.execute_script(FRAME_TAGS) }
180
+ tags.each_index do |rank|
181
+ child = path + [rank]
182
+ begin
183
+ url = within(child) { @driver.execute_script("return document.URL") }.to_s
184
+ rescue StandardError => e # a frame the page is changing is left
185
+ next if page_changing?(e)
186
+ raise
187
+ end
188
+ documents << Relay::PageDocument.new(url, child.size, child)
189
+ walk(child, documents)
190
+ end
191
+ end
192
+
193
+ # Runs the block in the document at path, then comes back to the top document, taking ChromeDriver's marks off.
194
+ def within(path)
195
+ reached = 0
196
+ begin
197
+ reached = switch_to(path)
198
+ yield
199
+ ensure
200
+ unless path.empty?
201
+ @driver.switch_to.default_content
202
+ # The deepest mark first: reaching a parent marks again the tags above it, taken off after.
203
+ (reached - 1).downto(0) do |level|
204
+ switch_to(path[0...level])
205
+ @driver.execute_script("#{FRAME_TAGS.sub("return tags;", "")}\ntags[arguments[0]]?.removeAttribute('#{DRIVER_MARK}');", path[level])
206
+ @driver.switch_to.default_content
207
+ end
208
+ end
209
+ end
210
+ end
211
+
212
+ def switch_to(path)
213
+ reached = 0
214
+ path.each do |rank|
215
+ tags = @driver.execute_script(FRAME_TAGS)
216
+ raise ::Selenium::WebDriver::Error::NoSuchFrameError, "no such frame: the frame tag left the page" if rank >= tags.size
217
+ @driver.switch_to.frame(tags[rank])
218
+ reached += 1
219
+ end
220
+ reached
221
+ end
222
+
223
+ # The test checks from the top document: the adapter could not give a frame back, which WebDriver does not name.
224
+ def require_top
225
+ return if @driver.execute_script("return window === window.top") == true
226
+ raise "The test is in a frame (driver.switch_to.frame): check from the top document, " \
227
+ "after driver.switch_to.default_content"
228
+ end
229
+
230
+ # A function of the page called by WebDriver: its source, then the arguments of execute_script.
231
+ def script(function, arity)
232
+ args = (0...arity).map { |index| "arguments[#{index}]" }.join(", ")
233
+ "return (function (#{function.params.join(", ")}) {\n#{function.body}\n}).call(null, #{args});"
234
+ end
235
+ end
236
+ end
237
+ end
@@ -0,0 +1,109 @@
1
+ require_relative "vision/errors"
2
+ require_relative "vision/gate"
3
+ require_relative "vision/relay"
4
+ require_relative "vision/selenium"
5
+ require_relative "vision/playwright"
6
+ require_relative "vision/ferrum"
7
+ require_relative "vision/frameworks"
8
+
9
+ module DeltaQa
10
+ # Delta-QA Vision for Ruby: a test (Selenium, Playwright, Ferrum, Capybara, Watir — under Chrome, Chromium or Edge)
11
+ # sends its pages to Delta-QA and reads the verdict.
12
+ #
13
+ # DeltaQa::Vision.open(driver, id: "checkout", name: "Checkout", commit: sha) do |vision|
14
+ # vision.check("Cart", ignore: ["#now"])
15
+ # end
16
+ module Vision
17
+ Size = Relay::Size
18
+ PASSING = %w[NEW PASSED].freeze
19
+
20
+ Check = Struct.new(:name, :sizes)
21
+ Results = Struct.new(:test_name, :commit, :commit_url, :launches)
22
+
23
+ # Opens a Vision test on the page the test holds — a Selenium driver, a Playwright page, a Ferrum browser or page, a
24
+ # Capybara session, a Watir browser: one launch per size, the page at its own size when none is declared. With a
25
+ # block, the test is closed when the block returns, and its results are returned.
26
+ def self.open(driver, id:, name:, commit:, tag: nil, branch: nil, base_branch: nil, app: nil, sizes: nil, save_new_tests: true, env: ENV)
27
+ { "id" => id, "name" => name, "commit" => commit }.each { |setting, value| require_text(value, setting) }
28
+ { "tag" => tag, "branch" => branch, "base_branch" => base_branch, "app" => app }.each { |setting, value| require_text(value, setting) unless value.nil? }
29
+ gate = Gate.from_environment(env)
30
+ page = page_driver(driver)
31
+ request = {}
32
+ request["appName"] = app unless app.nil?
33
+ request.merge!("testKey" => id, "testName" => name, "commit" => commit)
34
+ { "tag" => tag, "branch" => branch, "baseBranch" => base_branch }.each { |key, value| request[key] = value unless value.nil? }
35
+ request["saveNewTests"] = save_new_tests
36
+ test = Test.new(page, Relay::Launches.open(gate, page, request, sizes&.to_a), name, commit)
37
+ return test unless block_given?
38
+ yield test
39
+ # A block that raised keeps its own error: the launches stay open, closed by Delta-QA after its delay.
40
+ test.close
41
+ end
42
+
43
+ # The adapter of the object the test holds, recognised by its class: a framework the test did not load is not one.
44
+ def self.page_driver(held)
45
+ return SeleniumPageDriver.new(held) if instance_of_framework?(held, "Selenium::WebDriver::Driver")
46
+ return PlaywrightPageDriver.new(held) if instance_of_framework?(held, "Playwright::Page")
47
+ return FerrumPageDriver.new(held) if instance_of_framework?(held, "Ferrum::Browser") || instance_of_framework?(held, "Ferrum::Page")
48
+ return OnTopPageDriver.capybara(held) if instance_of_framework?(held, "Capybara::Session")
49
+ return OnTopPageDriver.watir(held) if instance_of_framework?(held, "Watir::Browser")
50
+ raise TypeError, "Delta-QA Vision opens a test on a Selenium driver, a Playwright page, a Ferrum browser or page, " \
51
+ "a Capybara session or a Watir browser, got #{held.class}"
52
+ end
53
+
54
+ def self.instance_of_framework?(held, name)
55
+ Object.const_defined?(name) && held.is_a?(Object.const_get(name))
56
+ end
57
+ private_class_method :page_driver, :instance_of_framework?
58
+
59
+ def self.require_text(value, setting)
60
+ raise ArgumentError, "The setting #{setting} of a Vision test is a text that is not empty" unless value.is_a?(String) && !value.empty?
61
+ end
62
+ private_class_method :require_text
63
+
64
+ # An open Vision test: its checks, then its close, which waits for the verdict and raises when a launch is not passed.
65
+ class Test
66
+ def initialize(driver, launches, name, commit)
67
+ @driver = driver
68
+ @launches = launches
69
+ @name = name
70
+ @commit = commit
71
+ @names = {}
72
+ @closed = nil
73
+ @failure = nil
74
+ end
75
+
76
+ # A check of the page: ignore leaves zones out, region looks at one zone alone. A zone is a CSS selector, a locator
77
+ # or an element of the test's framework.
78
+ def check(name, ignore: [], region: nil)
79
+ raise ArgumentError, "A check of the Vision API needs its name, a text that is not empty" unless name.is_a?(String) && !name.empty?
80
+ raise "check after close: this Vision test is closed — open another one" if closed?
81
+ raise DuplicateCheckNameError, name if @names.key?(name)
82
+ @names[name] = true
83
+ Check.new(name, @launches.check(@driver, name, ignore.to_a, region.nil? ? [] : [region]))
84
+ end
85
+
86
+ def closed?
87
+ !@closed.nil? || !@failure.nil?
88
+ end
89
+
90
+ # Closes the launches and waits for their verdict; a second call gives the same results, or raises the same failure.
91
+ def close
92
+ raise @failure unless @failure.nil?
93
+ return @closed unless @closed.nil?
94
+ begin
95
+ read = @launches.close
96
+ rescue StandardError => e # the failure of the close is kept for a second call, then raised again
97
+ @failure = e
98
+ raise
99
+ end
100
+ results = Results.new(@name, @commit, Relay.commit_url(read[0], @commit), read)
101
+ if read.any? { |launch| !PASSING.include?(launch.result) }
102
+ @failure = TestFailedError.new(results)
103
+ raise @failure
104
+ end
105
+ @closed = results
106
+ end
107
+ end
108
+ end
109
+ end
metadata ADDED
@@ -0,0 +1,59 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: delta-qa-vision
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1.beta2
5
+ platform: ruby
6
+ authors:
7
+ - Delta-QA
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2026-11-29 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description:
14
+ email:
15
+ - support@delta-qa.com
16
+ executables: []
17
+ extensions: []
18
+ extra_rdoc_files: []
19
+ files:
20
+ - LICENSE
21
+ - NOTICE
22
+ - README.md
23
+ - lib/delta_qa/vision.rb
24
+ - lib/delta_qa/vision/delta-qa-capture.js
25
+ - lib/delta_qa/vision/errors.rb
26
+ - lib/delta_qa/vision/ferrum.rb
27
+ - lib/delta_qa/vision/frameworks.rb
28
+ - lib/delta_qa/vision/gate.rb
29
+ - lib/delta_qa/vision/playwright.rb
30
+ - lib/delta_qa/vision/relay.rb
31
+ - lib/delta_qa/vision/resize_wait.rb
32
+ - lib/delta_qa/vision/selenium.rb
33
+ homepage: https://delta-qa.com
34
+ licenses:
35
+ - Apache-2.0
36
+ metadata:
37
+ homepage_uri: https://delta-qa.com
38
+ source_code_uri: https://github.com/delta-qa-com/delta-qa-vision
39
+ post_install_message:
40
+ rdoc_options: []
41
+ require_paths:
42
+ - lib
43
+ required_ruby_version: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '3.3'
48
+ required_rubygems_version: !ruby/object:Gem::Requirement
49
+ requirements:
50
+ - - ">="
51
+ - !ruby/object:Gem::Version
52
+ version: '0'
53
+ requirements: []
54
+ rubygems_version: 3.5.22
55
+ signing_key:
56
+ specification_version: 4
57
+ summary: 'Delta-QA Vision SDK: a Selenium, Playwright, Ferrum, Capybara or Watir test
58
+ sends its pages to Delta-QA and reads the verdict'
59
+ test_files: []