rails-jsdom 0.1.0 → 0.2.1

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,47 @@
1
+ module RailsJsdom
2
+ class Cable # :nodoc:
3
+ def initialize(clock)
4
+ @clock = clock
5
+ @sockets = {}
6
+ @frames = []
7
+ end
8
+
9
+ def answer(request, cookie)
10
+ case request.fetch("action")
11
+ when "open" then open(request.fetch("socket"), request.fetch("url"), request.fetch("protocols"), cookie)
12
+ when "send" then send_data(request.fetch("socket"), request.fetch("data"))
13
+ when "close" then close_socket(request.fetch("socket"))
14
+ end
15
+ end
16
+
17
+ def drain
18
+ @frames.slice!(0..)
19
+ end
20
+
21
+ def active?
22
+ @frames.any? || @sockets.each_value.any?(&:open?)
23
+ end
24
+
25
+ def close
26
+ @sockets.each_value(&:close_by_page)
27
+ @sockets.clear
28
+ end
29
+
30
+ private
31
+
32
+ def open(id, url, protocols, cookie)
33
+ socket = CableSocket.new(id, @frames, @clock)
34
+ socket.open(url, protocols, cookie).tap { |reply| @sockets[id] = socket if reply.key?(:protocol) }
35
+ end
36
+
37
+ def send_data(id, data)
38
+ @sockets.fetch(id).receive(data)
39
+ nil
40
+ end
41
+
42
+ def close_socket(id)
43
+ @sockets.delete(id)&.close_by_page
44
+ nil
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,37 @@
1
+ module RailsJsdom
2
+ class CableAdapter < ActionCable::SubscriptionAdapter::Test # :nodoc:
3
+ def initialize(server)
4
+ super
5
+ @thread = Thread.current
6
+ @failures = Thread::Queue.new
7
+ end
8
+
9
+ def broadcast(channel, payload)
10
+ Thread.current == @thread ? super : refuse(channel)
11
+ end
12
+
13
+ def report(failure)
14
+ @failures << failure
15
+ end
16
+
17
+ def failed?
18
+ !@failures.empty?
19
+ end
20
+
21
+ def raise_failure
22
+ raise Error, @failures.pop if failed?
23
+ end
24
+
25
+ private
26
+
27
+ def new_subscriber_map
28
+ ActionCable::SubscriptionAdapter::SubscriberMap.new
29
+ end
30
+
31
+ def refuse(channel)
32
+ report "#{channel.inspect} was broadcast from a thread other than the test's, so RailsJsdom did not deliver it. " \
33
+ "Interaction tests deliver each broadcast as it is made, so broadcasts must come from the test, from a request the page makes, " \
34
+ "or from jobs the test runs with perform_enqueued_jobs; a broadcast from another thread could reach the page at any moment."
35
+ end
36
+ end
37
+ end
@@ -0,0 +1,28 @@
1
+ module RailsJsdom
2
+ class CableFailure # :nodoc:
3
+ COMMANDS = %i[dispatch dispatch_websocket_message].freeze
4
+
5
+ def initialize(error, receiver, method, args)
6
+ @error = error
7
+ @receiver = receiver
8
+ @method = method
9
+ @args = args
10
+ end
11
+
12
+ def message
13
+ "#{@error.class}: #{@error.message} was raised in Action Cable code while #{doing}, and no rescue_from handled it. " \
14
+ "Action Cable would log it and carry on; RailsJsdom fails the test so the error is not missed. " \
15
+ "If the error is expected, handle it with rescue_from in the channel or the connection.\n#{backtrace}"
16
+ end
17
+
18
+ private
19
+
20
+ def doing
21
+ COMMANDS.include?(@method) ? "handling the page's command #{@args.first}" : "running #{@receiver.class.name}##{@method}"
22
+ end
23
+
24
+ def backtrace
25
+ Array(@error.backtrace).first(10).join("\n")
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,97 @@
1
+ module RailsJsdom
2
+ class CableServer # :nodoc:
3
+ module Takeover
4
+ def call(env)
5
+ socket = env[CableSocket::ENV_KEY]
6
+ socket ? socket.attach(self, env) : super
7
+ end
8
+ end
9
+
10
+ delegate :config, :pubsub, :broadcast, to: :@server
11
+
12
+ def initialize(server, clock)
13
+ @server = server
14
+ @clock = clock
15
+ end
16
+
17
+ def executor
18
+ self
19
+ end
20
+
21
+ def post
22
+ yield
23
+ end
24
+
25
+ def timer(interval, &block)
26
+ @clock.every(interval, &block)
27
+ end
28
+ end
29
+
30
+ class LegacyCableServer < CableServer # :nodoc:
31
+ delegate :logger, to: :@server
32
+
33
+ def initialize(server, clock, socket)
34
+ super(server, clock)
35
+ @socket = socket
36
+ end
37
+
38
+ def worker_pool
39
+ self
40
+ end
41
+
42
+ def event_loop
43
+ self
44
+ end
45
+
46
+ def add_connection(_connection); end
47
+
48
+ def remove_connection(_connection); end
49
+
50
+ def async_invoke(receiver, method, *args, connection: receiver, &block)
51
+ @socket.work(receiver, method, *args, connection: connection, &block)
52
+ end
53
+
54
+ def async_exec(receiver, *args, connection:, &block)
55
+ async_invoke(receiver, :instance_exec, *args, connection: connection, &block)
56
+ end
57
+ end
58
+
59
+ class LegacyWebSocket # :nodoc:
60
+ module Takeover
61
+ def new(env, *arguments, **options)
62
+ socket = env[CableSocket::ENV_KEY]
63
+ socket ? LegacyWebSocket.new(socket) : super
64
+ end
65
+ end
66
+
67
+ delegate :protocol, :close, to: :@socket
68
+
69
+ def initialize(socket)
70
+ @socket = socket
71
+ end
72
+
73
+ def possible?
74
+ true
75
+ end
76
+
77
+ def alive?
78
+ @socket.open?
79
+ end
80
+
81
+ def transmit(text)
82
+ @socket.deliver(text)
83
+ end
84
+
85
+ def rack_response
86
+ @socket.accept
87
+ end
88
+ end
89
+ end
90
+
91
+ module RailsJsdom
92
+ module LegacyRescue # :nodoc:
93
+ def rescue_with_handler(exception)
94
+ super || raise(exception)
95
+ end
96
+ end
97
+ end
@@ -0,0 +1,194 @@
1
+ require "rack/mock_request"
2
+
3
+ module RailsJsdom
4
+ class CableSocket # :nodoc:
5
+ ENV_KEY = "rails_jsdom.cable_socket".freeze
6
+
7
+ module Modern
8
+ def connect
9
+ @logger = @server.new_tagged_logger { request }
10
+ @connection = @server.config.connection_class.call.new(CableServer.new(@server, @clock), self)
11
+ @server.allow_request_origin?(env) ? opened : [ 404, {}, [] ]
12
+ end
13
+
14
+ def receive(text)
15
+ work(self, :dispatch, text)
16
+ end
17
+
18
+ private
19
+
20
+ def opened
21
+ start
22
+ work(@connection, :handle_open)
23
+ work(self, :keep_alive)
24
+ [ -1, {}, [] ]
25
+ end
26
+
27
+ def keep_alive
28
+ @clock.keep_alive(self) if open?
29
+ end
30
+
31
+ def dispatch(text)
32
+ @connection.handle_incoming(ActiveSupport::JSON.decode(text)) if open?
33
+ rescue StandardError => error
34
+ raise unless routing_error?(error)
35
+
36
+ logger.error "Could not handle incoming message: #{text} [#{error.class} - #{error.message}]"
37
+ end
38
+
39
+ def routing_error?(error)
40
+ error.class.module_parent == ActionCable::Connection::Subscriptions
41
+ end
42
+
43
+ def disconnect
44
+ work(@connection, :handle_close)
45
+ end
46
+ end
47
+
48
+ module Legacy
49
+ def self.included(_socket_class)
50
+ ActionCable::Connection::WebSocket.singleton_class.prepend(LegacyWebSocket::Takeover)
51
+ end
52
+
53
+ def connect
54
+ @logger = @server.logger
55
+ @connection = @server.config.connection_class.call.new(LegacyCableServer.new(@server, @clock, self), env)
56
+ @connection.singleton_class.prepend(LegacyRescue)
57
+ @connection.process
58
+ end
59
+
60
+ def receive(text)
61
+ @connection.on_message(text)
62
+ end
63
+
64
+ def accept
65
+ start
66
+ @connection.on_open
67
+ @clock.keep_alive(self) if open?
68
+ [ -1, {}, [] ]
69
+ end
70
+
71
+ private
72
+
73
+ def disconnect
74
+ @connection.on_close(nil, 1000)
75
+ end
76
+ end
77
+
78
+ attr_reader :env, :protocol, :logger
79
+
80
+ def self.env(url, protocols, cookie)
81
+ uri = URI(url)
82
+ origin = origin(uri)
83
+ Rack::MockRequest.env_for("#{origin}#{uri.request_uri}", headers(origin, protocols, cookie))
84
+ end
85
+
86
+ def self.origin(uri)
87
+ port = uri.port == uri.default_port ? "" : ":#{uri.port}"
88
+ "http://#{uri.host}#{port}"
89
+ end
90
+
91
+ def self.headers(origin, protocols, cookie)
92
+ {
93
+ "HTTP_HOST" => origin.delete_prefix("http://"),
94
+ "HTTP_ORIGIN" => origin,
95
+ "HTTP_COOKIE" => cookie,
96
+ "HTTP_CONNECTION" => "Upgrade",
97
+ "HTTP_UPGRADE" => "websocket",
98
+ "HTTP_SEC_WEBSOCKET_VERSION" => "13",
99
+ "HTTP_SEC_WEBSOCKET_KEY" => SecureRandom.base64(16),
100
+ "HTTP_SEC_WEBSOCKET_PROTOCOL" => protocols.join(", "),
101
+ "REMOTE_ADDR" => "127.0.0.1"
102
+ }
103
+ end
104
+
105
+ def initialize(id, outbox, clock)
106
+ @id = id
107
+ @outbox = outbox
108
+ @clock = clock
109
+ @state = :connecting
110
+ @jobs = []
111
+ end
112
+
113
+ def open(url, protocols, cookie)
114
+ @protocol = (protocols & ActionCable::INTERNAL[:protocols]).first.to_s
115
+ status, = Rails.application.call(self.class.env(url, protocols, cookie).merge(ENV_KEY => self))
116
+ status == -1 ? { protocol: @protocol } : { error: "the cable endpoint answered #{status}" }
117
+ end
118
+
119
+ def attach(server, env)
120
+ @server = server
121
+ @env = env
122
+ connect
123
+ end
124
+
125
+ def request
126
+ @request ||= ActionDispatch::Request.new(Rails.application.env_config.merge(env))
127
+ end
128
+
129
+ def open?
130
+ @state == :open
131
+ end
132
+
133
+ def start
134
+ @state = :open
135
+ end
136
+
137
+ def transmit(cable_message)
138
+ deliver(ActiveSupport::JSON.encode(cable_message))
139
+ end
140
+
141
+ def deliver(text)
142
+ @outbox << { socket: @id, data: text } if open?
143
+ end
144
+
145
+ def close(*)
146
+ shut(1000) if open?
147
+ end
148
+
149
+ def close_by_page
150
+ shut(nil) if open?
151
+ end
152
+
153
+ def beat
154
+ @connection.beat
155
+ end
156
+
157
+ def perform_work(receiver, method, *args)
158
+ work(receiver, method, *args)
159
+ end
160
+
161
+ def work(receiver, method, *args, connection: self, &block)
162
+ @jobs << [ receiver, method, args, connection, block ]
163
+ run_jobs unless working?
164
+ end
165
+
166
+ private
167
+
168
+ def working?
169
+ @working
170
+ end
171
+
172
+ def shut(code)
173
+ @state = :closed
174
+ @clock.let_go(self)
175
+ @outbox << { socket: @id, closed: true, code: code } if code
176
+ disconnect
177
+ end
178
+
179
+ def run_jobs
180
+ @working = true
181
+ run_job(*@jobs.shift) until @jobs.empty?
182
+ ensure
183
+ @working = false
184
+ end
185
+
186
+ def run_job(receiver, method, args, connection, block)
187
+ @server.worker_pool.work(connection) { receiver.send(method, *args, &block) }
188
+ rescue StandardError => error
189
+ @server.pubsub.report(CableFailure.new(error, receiver, method, args).message)
190
+ end
191
+
192
+ include({ socket: Modern, env: Legacy }.fetch(ActionCable::Connection::Base.instance_method(:initialize).parameters.dig(1, 1)))
193
+ end
194
+ end
@@ -0,0 +1,113 @@
1
+ module RailsJsdom
2
+ class Clock # :nodoc:
3
+ Timer = Struct.new(:at, :every, :order, :action, :clock) do
4
+ def shutdown
5
+ clock.cancel(self)
6
+ end
7
+ end
8
+
9
+ BEAT = ActionCable::Server::Connections::BEAT_INTERVAL * 1000
10
+
11
+ attr_reader :now
12
+
13
+ def initialize(epoch, &travel)
14
+ @epoch = epoch
15
+ @now = 0r
16
+ @travel = travel
17
+ @timers = []
18
+ @order = 0
19
+ @beating = []
20
+ travel.call(epoch)
21
+ end
22
+
23
+ def every(interval, &action)
24
+ milliseconds = interval.to_r * 1000
25
+ schedule(@now + milliseconds, milliseconds, action)
26
+ end
27
+
28
+ def keep_alive(socket)
29
+ @beating << socket
30
+ @heartbeat ||= schedule(((@now / BEAT).floor + 1) * BEAT, BEAT, -> { @beating.dup.each(&:beat) })
31
+ end
32
+
33
+ def let_go(socket)
34
+ @beating.delete(socket)
35
+ end
36
+
37
+ def cancel(timer)
38
+ @timers.delete(timer)
39
+ end
40
+
41
+ def page_time(now)
42
+ @now = now.to_r
43
+ run_due
44
+ @travel.call(current)
45
+ end
46
+
47
+ def moved?
48
+ keep_fraction
49
+ Time.now.to_r != current.to_r
50
+ end
51
+
52
+ def view
53
+ keep_fraction
54
+ follow_travel_back
55
+ { epoch: (@epoch.to_r * 1000).to_f, now: (@now + ahead).to_f, deadline: deadline }
56
+ end
57
+
58
+ private
59
+
60
+ def keep_fraction
61
+ @travel.call(current) if fraction_dropped?
62
+ end
63
+
64
+ def fraction_dropped?
65
+ exact = current.to_r
66
+ exact != exact.floor && Time.now.to_r == exact.floor
67
+ end
68
+
69
+ def follow_travel_back
70
+ @epoch = Time.now - (@now / 1000) if ahead.negative?
71
+ end
72
+
73
+ def deadline
74
+ next_timer&.at&.to_f
75
+ end
76
+
77
+ def ahead
78
+ (Time.now.to_r - current.to_r) * 1000
79
+ end
80
+
81
+ def run_due
82
+ while (timer = next_due)
83
+ @travel.call(@epoch + (timer.at / 1000))
84
+ repeat(timer)
85
+ timer.action.call
86
+ end
87
+ end
88
+
89
+ def current
90
+ @epoch + (@now / 1000)
91
+ end
92
+
93
+ def schedule(at, every, action)
94
+ @order += 1
95
+ Timer.new(at, every, @order, action, self).tap { |timer| @timers << timer }
96
+ end
97
+
98
+ def repeat(timer)
99
+ @order += 1
100
+ timer.at += timer.every
101
+ timer.order = @order
102
+ end
103
+
104
+ def next_timer
105
+ @timers.min_by { |timer| [ timer.at, timer.order ] }
106
+ end
107
+
108
+ def next_due
109
+ timer = next_timer
110
+ timer if timer && timer.at <= @now
111
+ end
112
+ end
113
+ end
@@ -34,6 +34,18 @@ module RailsJsdom
34
34
  @handle = handle
35
35
  end
36
36
 
37
+ # Runs `script` in the page with `this` set to the element, as in system
38
+ # tests. Extra arguments are available as `arguments`.
39
+ def execute_script(script, *arguments)
40
+ @test.rails_jsdom_script(script, arguments, "statements", handle)
41
+ nil
42
+ end
43
+
44
+ # Evaluates `script` with `this` set to the element and returns its value.
45
+ def evaluate_script(script, *arguments)
46
+ @test.rails_jsdom_script(script, arguments, "expression", handle)
47
+ end
48
+
37
49
  ##
38
50
  # Clicks the element.
39
51
  action :click
@@ -8,16 +8,30 @@ module RailsJsdom
8
8
  expected.is_a?(Regexp) ? actual.match?(expected) : actual.include?(expected.to_s)
9
9
  end
10
10
 
11
+ def self.flag?(actual, expected)
12
+ expected == :all || actual == expected
13
+ end
14
+
15
+ def self.classes?(actual, expected)
16
+ expected.all? { |name| class_matches?(actual, name) }
17
+ end
18
+
19
+ def self.class_matches?(actual, name)
20
+ name.start_with?("!") ? actual.exclude?(name.delete_prefix("!")) : actual.include?(name)
21
+ end
22
+
11
23
  def self.same?(actual, expected)
12
24
  expected.is_a?(Regexp) ? actual.match?(expected) : actual == expected.to_s
13
25
  end
14
26
 
15
- def initialize(strategy, locator, text: nil, exact_text: nil, visible: true, with: nil, checked: nil, unchecked: nil, disabled: nil, href: nil, type: nil)
27
+ def initialize(strategy, locator, text: nil, exact_text: nil, visible: true, with: nil, checked: nil, unchecked: nil, disabled: nil, href: nil, type: nil, id: nil, **others)
28
+ classes = others.delete(:class)
29
+ RailsJsdom.reject_options(others.keys)
16
30
  @strategy = strategy
17
31
  @locator = locator
18
32
  @visible = visible
19
33
  disabled = false if disabled.nil? && DISABLED_BY_DEFAULT.include?(strategy)
20
- @filters = { text: text, exact_text: exact_text, with: with, checked: checked, unchecked: unchecked, disabled: disabled, href: href, type: type }.compact
34
+ @filters = { text: text, exact_text: exact_text, with: with, checked: checked, unchecked: unchecked, disabled: disabled, href: href, type: type, id: id, class: classes && Array(classes) }.compact
21
35
  end
22
36
 
23
37
  def message
@@ -54,7 +68,9 @@ module RailsJsdom
54
68
  when :text
55
69
  Query.like?(actual, expected)
56
70
  when :checked, :unchecked, :disabled
57
- expected == :all || actual == expected
71
+ Query.flag?(actual, expected)
72
+ when :class
73
+ Query.classes?(actual, expected)
58
74
  else
59
75
  Query.same?(actual, expected)
60
76
  end
@@ -68,9 +84,12 @@ module RailsJsdom
68
84
  checked: descriptor.fetch("checked"),
69
85
  unchecked: !descriptor.fetch("checked"),
70
86
  disabled: descriptor.fetch("disabled"),
71
- href: descriptor.fetch("attributes")["href"].to_s,
72
87
  type: descriptor.fetch("type")
73
- }
88
+ }.merge(attribute_values(descriptor.fetch("attributes")))
89
+ end
90
+
91
+ def attribute_values(attributes)
92
+ { href: attributes["href"].to_s, id: attributes["id"].to_s, class: attributes["class"].to_s.split }
74
93
  end
75
94
  end
76
95
  end