e2e_rb 0.1.0.beta

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.
data/lib/e2e_rb/dsl.rb ADDED
@@ -0,0 +1,56 @@
1
+ # frozen_string_literal: true
2
+
3
+ module E2eRb
4
+ # Methods both adapters mix into a test: app, screen, agent, e2e_expect, ...
5
+ module DSL
6
+ def e2e_session
7
+ @e2e_session || raise(Error, "no e2e session is open for this test")
8
+ end
9
+
10
+ def app = e2e_session.app
11
+ def screen = e2e_session.screen
12
+ def agent = e2e_session.agent
13
+ def platform = e2e_session.platform
14
+ def e2e_fixture(name) = e2e_session.fixture(name)
15
+
16
+ # e2e_expect(screen.get_by_role("status")).to_have_text("hello")
17
+ def e2e_expect(subject, soft: false) = e2e_session.expect(subject, soft: soft)
18
+
19
+ def secret(name) = E2eRb.secret(name)
20
+ def credential(name, field) = E2eRb.credential(name, field)
21
+
22
+ private
23
+
24
+ def e2e_open(name, failure_class:)
25
+ @e2e_trace_path = nil
26
+ @e2e_session = E2eRb.open_session(name: name, failure_class: failure_class)
27
+ @e2e_trace_path = @e2e_session.trace_path
28
+ end
29
+
30
+ # Closes the attempt; returns the failure message e2e reported, or nil.
31
+ def e2e_close
32
+ session = @e2e_session
33
+ return nil unless session
34
+
35
+ @e2e_session = nil
36
+ failures = session.close
37
+ return nil if failures.empty?
38
+
39
+ "e2e reported #{failures.size} failure(s) at close:\n" +
40
+ failures.map { |f| " - #{f["message"]}#{" [#{f["code"]}]" if f["code"]}" }.join("\n") +
41
+ "\n e2e trace: #{session.trace_path}"
42
+ end
43
+
44
+ # Adds the test's trace.md path to a failure that does not name it yet (a plain
45
+ # assert_equal, an exception from the test's own code), so every failed e2e test
46
+ # points at its trace.
47
+ def e2e_annotate(exception)
48
+ trace = @e2e_trace_path
49
+ return exception if trace.nil? || exception.message.include?(trace)
50
+
51
+ line = "\n e2e trace: #{trace}"
52
+ exception.singleton_class.define_method(:message) { "#{super()}#{line}" }
53
+ exception
54
+ end
55
+ end
56
+ end
@@ -0,0 +1,65 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The exceptions e2e_rb raises, and how an error the bridge reports becomes one.
4
+ module E2eRb
5
+ # Anything e2e_rb raises.
6
+ class Error < StandardError; end
7
+
8
+ # The bridge process could not start, died, or broke the protocol.
9
+ class BridgeError < Error; end
10
+
11
+ # e2e refused the config, the target, a secret, etc. (category: configuration).
12
+ class ConfigurationError < Error; end
13
+
14
+ # e2e failed to drive the app (category: infrastructure / internal).
15
+ class InfrastructureError < Error; end
16
+
17
+ # Marks a test failure: a failed expect, a failed agent.assert, a timeout.
18
+ # The exception itself is the framework's own failure class (Minitest::Assertion,
19
+ # RSpec::Expectations::ExpectationNotMetError), extended with this module, so the
20
+ # framework counts it as a failure and `rescue E2eRb::Failure` still matches.
21
+ module Failure
22
+ attr_accessor :e2e_code
23
+ end
24
+
25
+ # Failure class used when no adapter opened the session (plain E2eRb.open_session).
26
+ class TestFailure < Error; end
27
+
28
+ # A member the e2e object does not have (`screen.no_such_thing`): a NoMethodError,
29
+ # as for any Ruby object, not a bridge error.
30
+ class NoMemberError < ::NoMethodError; end
31
+
32
+ # The bridge's error categories other than test failures; any other is infrastructure.
33
+ WIRE_CATEGORIES = { "configuration" => ConfigurationError, "bridge" => BridgeError }.freeze
34
+
35
+ class << self
36
+ # failure_class: the framework's own failure class (the exact class: Minitest
37
+ # counts failures by exact class, not subclasses), given per session by the adapter.
38
+ def failure(message, code: nil, failure_class: TestFailure)
39
+ exception = failure_class.new(message).extend(Failure)
40
+ exception.e2e_code = code
41
+ exception
42
+ end
43
+
44
+ # Builds the exception for one error the bridge reported.
45
+ def error_from_wire(error, trace_path: nil, failure_class: TestFailure)
46
+ data = error["data"] || {}
47
+ category = data["category"]
48
+ return NoMemberError.new(error["message"].to_s, data["member"]&.to_sym) if category == "no_member"
49
+
50
+ message = wire_message(error["message"], data["e2eCode"], trace_path)
51
+ return failure(message, code: data["e2eCode"], failure_class: failure_class) if category == "test"
52
+
53
+ WIRE_CATEGORIES.fetch(category, InfrastructureError).new(message)
54
+ end
55
+
56
+ private
57
+
58
+ def wire_message(message, code, trace_path)
59
+ text = message.to_s
60
+ text += " [#{code}]" if code
61
+ text += "\n e2e trace: #{trace_path}" if trace_path
62
+ text
63
+ end
64
+ end
65
+ end
@@ -0,0 +1,105 @@
1
+ # frozen_string_literal: true
2
+
3
+ module E2eRb
4
+ # A Ruby Regexp as the JavaScript regexp that matches the same strings, read by the
5
+ # bridge as `new RegExp(source, flags)` (no `u` flag). What JavaScript cannot express
6
+ # raises ArgumentError instead of silently matching something else.
7
+ class JsRegexp
8
+ # Ruby escapes with a JS equivalent (outside a character class).
9
+ ESCAPES = {
10
+ "A" => "(?<![\\s\\S])", # start of string
11
+ "z" => "(?![\\s\\S])", # end of string
12
+ "Z" => "(?=\\n?(?![\\s\\S]))", # end of string, before a final newline
13
+ "h" => "[0-9a-fA-F]",
14
+ "H" => "[^0-9a-fA-F]"
15
+ }.freeze
16
+ # Ruby escapes JS reads differently or not at all: \p{..} \g<..> \e \a \C- \M- ...
17
+ RUBY_ONLY_ESCAPES = %w[G K R X p P g e a C M].freeze
18
+ # Ruby groups JS lacks: atomic, absent, comment, quoted name, conditional, inline options.
19
+ RUBY_ONLY_GROUP = /\A\(\?(?:>|~|#|'|\(|[imx-]+[:)])/
20
+
21
+ attr_reader :source, :flags
22
+
23
+ def initialize(regexp)
24
+ @regexp = regexp
25
+ @flags = translate_flags
26
+ @source = translate_source
27
+ end
28
+
29
+ def to_wire = { "source" => source, "flags" => flags }
30
+
31
+ private
32
+
33
+ # `m` always: Ruby's ^ and $ are line anchors. Ruby's /m (dot matches newline) is JS's `s`.
34
+ def translate_flags
35
+ refuse("JavaScript regexps have no extended (x) mode") if option?(Regexp::EXTENDED)
36
+ flags = +"m"
37
+ flags << "i" if option?(Regexp::IGNORECASE)
38
+ flags << "s" if option?(Regexp::MULTILINE)
39
+ flags
40
+ end
41
+
42
+ def option?(flag) = @regexp.options.anybits?(flag)
43
+
44
+ def translate_source
45
+ @in = @regexp.source
46
+ @out = +""
47
+ @at = 0
48
+ @in_class = false
49
+ step while @at < @in.length
50
+ @out
51
+ end
52
+
53
+ def step
54
+ char = @in[@at]
55
+ if char == "\\" then escape
56
+ elsif @in_class then class_char(char)
57
+ elsif char == "[" then open_class
58
+ else
59
+ refuse_group if char == "("
60
+ emit(char, 1)
61
+ end
62
+ end
63
+
64
+ def emit(text, width)
65
+ @out << text
66
+ @at += width
67
+ end
68
+
69
+ # `[` / `[^`, then a `]` right after it: in Ruby a literal `]`, in JS an empty class.
70
+ def open_class
71
+ @in_class = true
72
+ emit("[", 1)
73
+ emit("^", 1) if @in[@at] == "^"
74
+ emit("\\]", 1) if @in[@at] == "]"
75
+ end
76
+
77
+ def class_char(char)
78
+ refuse("JavaScript regexps have no class intersection (&&)") if @in[@at, 2] == "&&"
79
+ refuse("JavaScript regexps have no nested or POSIX ([:alpha:]) classes") if char == "["
80
+ @in_class = false if char == "]"
81
+ emit(char, 1)
82
+ end
83
+
84
+ def refuse_group
85
+ refuse("JavaScript regexps have no #{Regexp.last_match(0)} group") if @in[@at..] =~ RUBY_ONLY_GROUP
86
+ end
87
+
88
+ def escape
89
+ escaped = @in[@at + 1]
90
+ refuse("regexp ends in a backslash") if escaped.nil?
91
+ refuse("JavaScript regexps have no \\#{escaped}") if RUBY_ONLY_ESCAPES.include?(escaped)
92
+ refuse("JavaScript regexps have no \\u{...}") if escaped == "u" && @in[@at + 2] == "{"
93
+ emit(@in_class ? class_escape(escaped) : ESCAPES.fetch(escaped, "\\#{escaped}"), 2)
94
+ end
95
+
96
+ def class_escape(escaped)
97
+ refuse("\\H inside a character class has no JavaScript form") if escaped == "H"
98
+ escaped == "h" ? "0-9a-fA-F" : "\\#{escaped}"
99
+ end
100
+
101
+ def refuse(reason)
102
+ raise ArgumentError, "#{reason}: #{@regexp.inspect}"
103
+ end
104
+ end
105
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ module E2eRb
4
+ # e2e's locator / screen matchers (AsyncExpectation + ScreenExpectation in e2e's
5
+ # types.d.ts), one row each, with the names the adapters give them:
6
+ # rspec: expect(locator).to be_visible
7
+ # minitest: assert_visible(locator) / refute_visible(locator)
8
+ # Both adapters are generated from this table; example/spec/matchers_drift_spec.rb
9
+ # fails when e2e adds or drops a matcher.
10
+ MATCHERS = [
11
+ { e2e: "toBeVisible", rspec: :be_visible, minitest: :visible },
12
+ { e2e: "toBeHidden", rspec: :be_hidden, minitest: :hidden },
13
+ { e2e: "toBeAttached", rspec: :be_attached, minitest: :attached },
14
+ { e2e: "toBeEnabled", rspec: :be_enabled, minitest: :enabled },
15
+ { e2e: "toBeDisabled", rspec: :be_disabled, minitest: :disabled },
16
+ { e2e: "toBeChecked", rspec: :be_checked, minitest: :checked },
17
+ { e2e: "toBeSelected", rspec: :be_selected, minitest: :selected },
18
+ { e2e: "toBeExpanded", rspec: :be_expanded, minitest: :expanded },
19
+ { e2e: "toBeFocused", rspec: :be_focused, minitest: :focused },
20
+ { e2e: "toHaveText", rspec: :have_text, minitest: :text },
21
+ { e2e: "toContainText", rspec: :contain_text, minitest: :contains_text },
22
+ { e2e: "toHaveValue", rspec: :have_value, minitest: :value },
23
+ { e2e: "toHaveAttribute", rspec: :have_attribute, minitest: :attribute },
24
+ { e2e: "toHaveCount", rspec: :have_count, minitest: :count },
25
+ { e2e: "toHaveAccessibleName", rspec: :have_accessible_name, minitest: :accessible_name },
26
+ { e2e: "toHaveScreenshot", rspec: :have_screenshot, minitest: :screenshot }
27
+ ].each(&:freeze).freeze
28
+ end
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Minitest's plugin hook: Minitest calls plugin_<name>_init for every name in
4
+ # Minitest.extensions. e2e_rb's adds the reporter that closes the e2e host at the end
5
+ # of the run. Registered when the adapter is required, never by auto-discovery, so a
6
+ # suite that does not use e2e_rb is untouched.
7
+ module Minitest
8
+ def self.plugin_e2e_rb_init(options)
9
+ reporter << E2eRb::Minitest::HostReporter.new(options.fetch(:io, $stdout))
10
+ end
11
+ end
12
+ Minitest.extensions << "e2e_rb" unless Minitest.extensions.include?("e2e_rb")
@@ -0,0 +1,98 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "minitest"
4
+ require_relative "../e2e_rb"
5
+ require_relative "dsl"
6
+
7
+ module E2eRb
8
+ # Include into any Minitest::Test subclass, e.g. a suite's existing base class:
9
+ #
10
+ # class BrowserTest < MyApp::Test
11
+ # include E2eRb::Minitest
12
+ # def test_upgrade = (app.open("/"); assert_text(screen.get_by_role("status"), "Pro"))
13
+ # end
14
+ #
15
+ # Every test opens one e2e session before setup and closes it after teardown.
16
+ # e2e allows one session per process: parallelize with processes, never threads.
17
+ module Minitest
18
+ include E2eRb::DSL
19
+
20
+ THREADS_REFUSED = "e2e allows one session per process; parallelize with processes (one Ruby process per " \
21
+ "test file, parallel_tests, ...), not Minitest's threads (parallelize_me!)"
22
+
23
+ # Refuses parallelize_me! on the including class and its subclasses.
24
+ module ClassMethods
25
+ def parallelize_me!
26
+ raise E2eRb::Error, THREADS_REFUSED
27
+ end
28
+ end
29
+
30
+ # The class runs its tests in Minitest's threads (Minitest 6: run_order, Minitest 5: test_order).
31
+ def self.parallel?(klass)
32
+ %i[run_order test_order].any? { |order| klass.respond_to?(order) && klass.public_send(order) == :parallel }
33
+ end
34
+
35
+ def self.included(base)
36
+ super
37
+ base.extend(ClassMethods)
38
+ end
39
+
40
+ # Closes the e2e host when the run ends; a close failure fails the run
41
+ # (Minitest's exit status follows the reporters' passed?).
42
+ class HostReporter < ::Minitest::AbstractReporter
43
+ def initialize(io)
44
+ super()
45
+ @io = io
46
+ @error = nil
47
+ end
48
+
49
+ def report
50
+ E2eRb.close!
51
+ rescue E2eRb::Error => e
52
+ @error = e
53
+ @io.puts("\n#{e.class}: #{e.message}")
54
+ end
55
+
56
+ def passed? = @error.nil?
57
+ end
58
+
59
+ def before_setup
60
+ # A class made parallel some other way still runs in threads.
61
+ raise E2eRb::Error, THREADS_REFUSED if E2eRb::Minitest.parallel?(self.class)
62
+
63
+ super
64
+ e2e_open("#{self.class.name}##{name}", failure_class: ::Minitest::Assertion)
65
+ end
66
+
67
+ def after_teardown
68
+ message = e2e_close
69
+ raise E2eRb.failure(message, failure_class: ::Minitest::Assertion) if message
70
+ ensure
71
+ super
72
+ failures.each { |failure| e2e_annotate(failure.respond_to?(:error) ? failure.error : failure) }
73
+ end
74
+
75
+ # e2e_expect(...) counted as one Minitest assertion.
76
+ def e2e_expect(subject, soft: false)
77
+ self.assertions += 1
78
+ super
79
+ end
80
+
81
+ E2eRb::MATCHERS.each do |row|
82
+ e2e = row[:e2e]
83
+ define_method(:"assert_#{row[:minitest]}") do |subject, *args, **options|
84
+ e2e_expect(subject).matcher(e2e, *args, **options)
85
+ end
86
+ define_method(:"refute_#{row[:minitest]}") do |subject, *args, **options|
87
+ e2e_expect(subject).not.matcher(e2e, *args, **options)
88
+ end
89
+ end
90
+
91
+ # `class FooTest < E2eRb::Minitest::Test`: the same, as a base class.
92
+ class Test < ::Minitest::Test
93
+ include E2eRb::Minitest
94
+ end
95
+ end
96
+ end
97
+
98
+ require_relative "minitest/plugin"
@@ -0,0 +1,65 @@
1
+ # frozen_string_literal: true
2
+
3
+ module E2eRb
4
+ # A remote e2e object: a fixture root (app, screen, agent, ...) plus a call chain.
5
+ # Every method call goes to the bridge, which re-applies the chain in Node.
6
+ # Builders (get_by_role, first, filter, ...) come back as new proxies;
7
+ # actions (click, fill, act, ...) come back as values.
8
+ #
9
+ # A BasicObject, so Locator#tap, #select_option etc. never hit Object's methods.
10
+ class Proxy < BasicObject
11
+ def initialize(session, root, chain = [])
12
+ @session = session
13
+ @root = root
14
+ @chain = chain
15
+ end
16
+
17
+ def method_missing(name, *positional, **options, &block)
18
+ # Ruby's implicit conversions (to_ary, to_str, ...) are never e2e calls.
19
+ ::Kernel.raise ::NoMethodError.new("undefined method '#{name}' for #{inspect}", name) if name.start_with?("to_")
20
+ ::Kernel.raise ::ArgumentError, "e2e calls take no block (#{name})" if block
21
+
22
+ chain = @chain + [{ "m" => Codec.js_name(name), "a" => Codec.args(positional, options) }]
23
+ __e2e_result__(@session.invoke(@root, chain), chain)
24
+ end
25
+
26
+ # Ruby duck-typing probes (respond_to?(:to_ary), :call, ...) must not reach e2e:
27
+ # a proxy claims only its own __e2e_* methods.
28
+ def respond_to_missing?(name, _include_all) = name.to_s.start_with?("__e2e_")
29
+ def respond_to?(name, *) = respond_to_missing?(name, false)
30
+
31
+ def __e2e_wire__ = { "$locator" => { "root" => @root, "chain" => @chain } }
32
+ def __e2e_session__ = @session
33
+ def __e2e_subject__ = { "root" => @root, "chain" => @chain }
34
+
35
+ # Two proxies are equal when they name the same expression in the same session,
36
+ # so they work as Hash keys and in Array#include? without a round trip.
37
+ def ==(other)
38
+ other.is_a?(Proxy) && other.__e2e_session__.equal?(@session) && other.__e2e_subject__ == __e2e_subject__
39
+ end
40
+ alias eql? ==
41
+ def hash = [Proxy, @session.__id__, @root, @chain].hash
42
+
43
+ def is_a?(klass) = klass == Proxy
44
+ alias kind_of? is_a?
45
+ def class = Proxy
46
+ def nil? = false
47
+
48
+ # A builder's result is a new proxy; all() a list of nth() proxies; an action's, its value.
49
+ def __e2e_result__(result, chain)
50
+ case result["kind"]
51
+ when "locator" then Proxy.new(@session, @root, chain)
52
+ when "locators" then ::Array.new(result.fetch("count")) { |index| __e2e_nth__(chain, index) }
53
+ else result["value"]
54
+ end
55
+ end
56
+
57
+ def inspect
58
+ calls = @chain.map { |step| "#{step["m"]}(#{step["a"].map { |a| ::JSON.generate(a) }.join(", ")})" }
59
+ "#<e2e #{[@root, *calls].join(".")}>"
60
+ end
61
+ alias to_s inspect
62
+
63
+ def __e2e_nth__(chain, index) = Proxy.new(@session, @root, chain[0...-1] + [{ "m" => "nth", "a" => [index] }])
64
+ end
65
+ end
@@ -0,0 +1,83 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rspec/core"
4
+ require "rspec/expectations"
5
+ require_relative "../e2e_rb"
6
+ require_relative "dsl"
7
+
8
+ module E2eRb
9
+ module RSpec
10
+ # Ruby matcher name -> e2e matcher (from E2eRb::MATCHERS).
11
+ MATCHERS = E2eRb::MATCHERS.to_h { |row| [row[:rspec], row[:e2e]] }.freeze
12
+
13
+ # expect(locator).to have_text("x") runs e2e's own auto-waiting matcher in Node.
14
+ class Matcher
15
+ def initialize(ruby_name, e2e_name, positional, options)
16
+ @ruby_name = ruby_name
17
+ @e2e_name = e2e_name
18
+ @positional = positional
19
+ @options = options
20
+ end
21
+
22
+ def matches?(actual) = run(actual, negate: false)
23
+ def does_not_match?(actual) = run(actual, negate: true)
24
+
25
+ attr_reader :failure_message
26
+ alias failure_message_when_negated failure_message
27
+
28
+ def description
29
+ args = @positional.map(&:inspect)
30
+ args << @options.inspect unless @options.empty?
31
+ "#{@ruby_name.to_s.tr("_", " ")}#{" #{args.join(", ")}" unless args.empty?}"
32
+ end
33
+
34
+ def supports_block_expectations? = false
35
+
36
+ private
37
+
38
+ def run(actual, negate:)
39
+ unless actual.respond_to?(:__e2e_subject__)
40
+ raise ArgumentError, "#{@ruby_name} is e2e's matcher and takes a locator or screen, got #{actual.inspect}"
41
+ end
42
+
43
+ args = E2eRb::Codec.args(@positional, @options)
44
+ actual.__e2e_session__.run_expectation(actual, @e2e_name, args, negate: negate, soft: false)
45
+ true
46
+ rescue E2eRb::Failure => e
47
+ @failure_message = e.message
48
+ false
49
+ end
50
+ end
51
+
52
+ # be_visible, have_text, ...: one RSpec matcher per row of E2eRb::MATCHERS.
53
+ module Matchers
54
+ MATCHERS.each do |ruby_name, e2e_name|
55
+ define_method(ruby_name) { |*positional, **options| Matcher.new(ruby_name, e2e_name, positional, options) }
56
+ end
57
+ end
58
+
59
+ module DSL
60
+ include E2eRb::DSL
61
+ include Matchers
62
+ end
63
+ end
64
+ end
65
+
66
+ RSpec.configure do |config|
67
+ config.include E2eRb::RSpec::DSL, type: :e2e
68
+
69
+ config.before(:each, type: :e2e) do |example|
70
+ # e2e test failures are RSpec expectation failures, not errors.
71
+ e2e_open(example.metadata[:full_description], failure_class: RSpec::Expectations::ExpectationNotMetError)
72
+ end
73
+
74
+ config.after(:each, type: :e2e) do |example|
75
+ message = e2e_close
76
+ raise E2eRb.failure(message, failure_class: RSpec::Expectations::ExpectationNotMetError) if message
77
+ ensure
78
+ e2e_annotate(example.exception) if example.exception
79
+ end
80
+
81
+ # The host (app, engine) closes with the suite; a close failure fails the run.
82
+ config.after(:suite) { E2eRb.close! }
83
+ end
@@ -0,0 +1,108 @@
1
+ # frozen_string_literal: true
2
+
3
+ module E2eRb
4
+ # Per-process state: one bridge, one host, at most one open session.
5
+ # A forked worker starts its own bridge; a separately spawned worker process
6
+ # (one Ruby process per test file) has its own runtime anyway.
7
+ class Runtime
8
+ ONE_SESSION = "e2e allows one per process (use process parallelism, not threads)"
9
+
10
+ attr_reader :bridge
11
+
12
+ def initialize(configuration)
13
+ @configuration = configuration
14
+ @pid = Process.pid
15
+ @session = nil
16
+ end
17
+
18
+ def open_session(name:, failure_class: TestFailure, timeout: @configuration.timeout, agent: nil)
19
+ ensure_host
20
+ raise Error, "session #{@session.name.inspect} is still open; #{ONE_SESSION}" if @session
21
+
22
+ info = @bridge.request("session/open", "name" => name, "timeout" => timeout, "agent" => agent)
23
+ @session = Session.new(self, name: name, info: info, failure_class: failure_class)
24
+ end
25
+
26
+ def close_session(session)
27
+ return close_open_session if @session.equal?(session)
28
+
29
+ raise Error, "closing #{session.name.inspect}, but #{@session&.name.inspect} is open"
30
+ end
31
+
32
+ # Closes the host (stops the app, the engine) and the bridge. Called by the
33
+ # adapters at the end of the suite; raises InfrastructureError with the reason
34
+ # when e2e reports a close failure or the bridge died, so the run fails.
35
+ def close!
36
+ return unless @bridge && @pid == Process.pid
37
+
38
+ bridge = @bridge
39
+ host_open = @host_open
40
+ forget_bridge
41
+ failures = host_open ? close_host(bridge) : []
42
+ bridge.shutdown
43
+ return if failures.empty?
44
+
45
+ raise InfrastructureError, "e2e host close failed: #{failures.map { |f| f["message"] }.join("; ")}"
46
+ end
47
+
48
+ # Last resort at process exit: ends the bridge without raising (the bridge
49
+ # closes its host when its input ends). The adapters' close! reports failures.
50
+ def reap
51
+ return unless @bridge && @pid == Process.pid
52
+
53
+ @bridge.reap
54
+ forget_bridge
55
+ end
56
+
57
+ private
58
+
59
+ def close_open_session
60
+ @session = nil
61
+ @bridge.request("session/close")
62
+ end
63
+
64
+ # e2e's close failures. A dead bridge, or an error e2e raises, is a failure too.
65
+ def close_host(bridge)
66
+ bridge.request("host/close").fetch("failures")
67
+ rescue BridgeError, IOError, SystemCallError => e
68
+ bridge.reap
69
+ raise InfrastructureError, "e2e host close failed: the bridge is gone (#{e.message})"
70
+ rescue Error => e
71
+ bridge.shutdown
72
+ raise InfrastructureError, "e2e host close failed: #{e.message}"
73
+ end
74
+
75
+ def forget_bridge
76
+ @bridge = nil
77
+ @host_open = false
78
+ end
79
+
80
+ def ensure_host
81
+ reset_after_fork if @pid != Process.pid
82
+ return if @host_open
83
+
84
+ @bridge ||= Bridge.new(node: @configuration.node, cwd: @configuration.project_root,
85
+ on_notification: method(:notification))
86
+ @bridge.request("host/open", "config" => @configuration.config, "target" => @configuration.target,
87
+ "headed" => @configuration.headed)
88
+ @host_open = true
89
+ end
90
+
91
+ # The parent's bridge belongs to the parent: the child drops its copies of the
92
+ # pipe ends (so the parent's bridge still sees end of input when the parent
93
+ # exits) and starts its own.
94
+ def reset_after_fork
95
+ @bridge&.close_inherited
96
+ @pid = Process.pid
97
+ forget_bridge
98
+ @session = nil
99
+ end
100
+
101
+ def notification(method, params)
102
+ case method
103
+ when "step" then @configuration.on_step&.call(params)
104
+ when "notice" then @configuration.on_notice&.call(params["target"], params["message"])
105
+ end
106
+ end
107
+ end
108
+ end