ruby_raider 3.12.1 → 4.0.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 +4 -4
- data/.github/workflows/runtime.yml +38 -0
- data/.github/workflows/system_tests.yml +1 -23
- data/.reek.yml +1 -0
- data/.rspec +1 -0
- data/Gemfile +2 -0
- data/README.md +17 -48
- data/RELEASE.md +22 -0
- data/bin/raider +5 -0
- data/lib/commands/scaffolding_commands.rb +2 -25
- data/lib/commands/utility_commands.rb +39 -3
- data/lib/generators/automation/automation_generator.rb +0 -5
- data/lib/generators/automation/templates/component.tt +1 -0
- data/lib/generators/automation/templates/home.tt +2 -2
- data/lib/generators/automation/templates/login.tt +6 -26
- data/lib/generators/automation/templates/page.tt +23 -18
- data/lib/generators/automation/templates/partials/home_page_selector.tt +1 -2
- data/lib/generators/automation/templates/partials/initialize_selector.tt +0 -8
- data/lib/generators/automation/templates/partials/pdp_page_selector.tt +1 -2
- data/lib/generators/automation/templates/partials/url_methods.tt +8 -2
- data/lib/generators/automation/templates/partials/visit_method.tt +0 -5
- data/lib/generators/automation/templates/pdp.tt +1 -9
- data/lib/generators/common_generator.rb +0 -2
- data/lib/generators/generator.rb +19 -17
- data/lib/generators/helper_generator.rb +25 -16
- data/lib/generators/infrastructure/templates/azure_pipelines.tt +1 -1
- data/lib/generators/infrastructure/templates/github.tt +2 -3
- data/lib/generators/infrastructure/templates/github_appium.tt +0 -8
- data/lib/generators/invoke_generators.rb +4 -23
- data/lib/generators/menu_generator.rb +1 -9
- data/lib/generators/rspec/templates/accessibility_spec.tt +1 -9
- data/lib/generators/rspec/templates/spec.tt +8 -24
- data/lib/generators/template_renderer/partial_cache.rb +3 -1
- data/lib/generators/template_renderer.rb +1 -1
- data/lib/generators/templates/common/gemfile.tt +3 -10
- data/lib/generators/templates/common/git_ignore.tt +0 -5
- data/lib/generators/templates/common/partials/mobile_config.tt +3 -1
- data/lib/generators/templates/common/partials/web_config.tt +17 -1
- data/lib/generators/templates/common/rakefile.tt +0 -15
- data/lib/generators/templates/common/read_me.tt +394 -242
- data/lib/generators/templates/common/rubocop.tt +0 -2
- data/lib/generators/templates/helpers/driver_helper.tt +30 -0
- data/lib/generators/templates/helpers/gesture_helper.tt +78 -0
- data/lib/generators/templates/helpers/network_helper.tt +521 -0
- data/lib/generators/templates/helpers/partials/quit_driver.tt +0 -2
- data/lib/generators/templates/helpers/partials/screenshot.tt +0 -2
- data/lib/generators/templates/helpers/partials/selenium_driver.tt +14 -1
- data/lib/generators/templates/helpers/screenshot_helper.tt +490 -0
- data/lib/generators/templates/helpers/spec_helper.tt +56 -27
- data/lib/generators/templates/helpers/trace_helper.tt +1242 -0
- data/lib/generators/templates/helpers/video_helper.tt +3 -8
- data/lib/ruby_raider/runtime/actionability.rb +129 -0
- data/lib/ruby_raider/runtime/actionable.rb +49 -0
- data/lib/ruby_raider/runtime/by_role.rb +55 -0
- data/lib/ruby_raider/runtime/config.rb +79 -0
- data/lib/ruby_raider/runtime/context.rb +38 -0
- data/lib/ruby_raider/runtime/errors.rb +69 -0
- data/lib/ruby_raider/runtime/finders.rb +73 -0
- data/lib/ruby_raider/runtime/js/actionability.js +134 -0
- data/lib/ruby_raider/runtime/js/role_engine.js +315 -0
- data/lib/ruby_raider/runtime/locator_converter.rb +72 -0
- data/lib/ruby_raider/runtime/matchers/base.rb +222 -0
- data/lib/ruby_raider/runtime/matchers/element.rb +183 -0
- data/lib/ruby_raider/runtime/matchers/page.rb +71 -0
- data/lib/ruby_raider/runtime/matchers/presence.rb +41 -0
- data/lib/ruby_raider/runtime/matchers/retrying_block.rb +104 -0
- data/lib/ruby_raider/runtime/observer.rb +170 -0
- data/lib/ruby_raider/runtime/role_finder.rb +83 -0
- data/lib/ruby_raider/runtime/rspec.rb +78 -0
- data/lib/ruby_raider/runtime/selectors.rb +60 -0
- data/lib/ruby_raider/runtime/strict.rb +142 -0
- data/lib/ruby_raider/runtime/wait.rb +84 -0
- data/lib/ruby_raider/runtime.rb +20 -0
- data/lib/scaffolding/name_normalizer.rb +1 -1
- data/lib/scaffolding/project_detector.rb +2 -28
- data/lib/scaffolding/scaffolding.rb +0 -20
- data/lib/scaffolding/templates/component.tt +0 -14
- data/lib/scaffolding/templates/page_object.tt +2 -14
- data/lib/scaffolding/templates/spec.tt +1 -9
- data/lib/utilities/utilities.rb +17 -8
- data/lib/version +1 -1
- data/ruby_raider.gemspec +3 -1
- data/sig/commands/scaffolding_commands.rbs +0 -2
- data/sig/commands/utility_commands.rbs +8 -0
- data/sig/generators/generator.rbs +4 -4
- data/sig/generators/helper_generator.rbs +1 -1
- data/sig/generators/menu_generator.rbs +0 -1
- data/sig/ruby_raider/runtime/actionability.rbs +25 -0
- data/sig/ruby_raider/runtime/actionable.rbs +13 -0
- data/sig/ruby_raider/runtime/by_role.rbs +15 -0
- data/sig/ruby_raider/runtime/config.rbs +26 -0
- data/sig/ruby_raider/runtime/context.rbs +12 -0
- data/sig/ruby_raider/runtime/errors.rbs +36 -0
- data/sig/ruby_raider/runtime/finders.rbs +26 -0
- data/sig/ruby_raider/runtime/locator_converter.rbs +21 -0
- data/sig/ruby_raider/runtime/matchers/base.rbs +64 -0
- data/sig/ruby_raider/runtime/matchers/element.rbs +78 -0
- data/sig/ruby_raider/runtime/matchers/page.rbs +38 -0
- data/sig/ruby_raider/runtime/matchers/presence.rbs +21 -0
- data/sig/ruby_raider/runtime/matchers/retrying_block.rbs +27 -0
- data/sig/ruby_raider/runtime/observer.rbs +46 -0
- data/sig/ruby_raider/runtime/role_finder.rbs +18 -0
- data/sig/ruby_raider/runtime/selectors.rbs +21 -0
- data/sig/ruby_raider/runtime/strict.rbs +35 -0
- data/sig/ruby_raider/runtime/wait.rbs +17 -0
- data/sig/ruby_raider/runtime.rbs +2 -0
- data/sig/scaffolding/project_detector.rbs +0 -4
- data/sig/scaffolding/scaffolding.rbs +0 -5
- data/sig/utilities/utilities.rbs +3 -1
- data/sig/vendor/selenium_webdriver.rbs +71 -0
- data/spec/commands/raider_commands_spec.rb +38 -3
- data/spec/commands/scaffolding_commands_spec.rb +27 -0
- data/spec/commands/utility_commands_spec.rb +53 -0
- data/spec/generators/fixtures/video_helper_stubs/selenium-webdriver.rb +11 -2
- data/spec/generators/gesture_helper_spec.rb +123 -0
- data/spec/generators/network_helper_spec.rb +634 -0
- data/spec/generators/screenshot_helper_spec.rb +776 -0
- data/spec/generators/template_renderer_spec.rb +0 -4
- data/spec/generators/trace_helper_spec.rb +1337 -0
- data/spec/generators/video_helper_spec.rb +0 -9
- data/spec/integration/commands/browser_update_after_creation_spec.rb +0 -8
- data/spec/integration/commands/scaffolding_commands_spec.rb +12 -70
- data/spec/integration/commands/utility_commands_spec.rb +19 -41
- data/spec/integration/content/azure_content_spec.rb +2 -6
- data/spec/integration/content/ci_content_spec.rb +1 -55
- data/spec/integration/content/common_content_spec.rb +1 -118
- data/spec/integration/content/config_content_spec.rb +52 -29
- data/spec/integration/content/gemfile_content_spec.rb +7 -72
- data/spec/integration/content/helper_content_spec.rb +158 -93
- data/spec/integration/content/page_content_spec.rb +85 -87
- data/spec/integration/content/readme_content_spec.rb +176 -71
- data/spec/integration/content/rspec_reporter_content_spec.rb +2 -2
- data/spec/integration/content/rubocop_content_spec.rb +1 -1
- data/spec/integration/content/syntax_validation_spec.rb +2 -2
- data/spec/integration/content/test_content_spec.rb +23 -147
- data/spec/integration/end_to_end_features_spec.rb +1 -43
- data/spec/integration/end_to_end_spec.rb +648 -292
- data/spec/integration/generators/automation_generator_spec.rb +3 -37
- data/spec/integration/generators/axe_addon_spec.rb +2 -35
- data/spec/integration/generators/azure_generator_spec.rb +1 -1
- data/spec/integration/generators/common_generator_spec.rb +1 -40
- data/spec/integration/generators/config_features_spec.rb +1 -24
- data/spec/integration/generators/github_generator_spec.rb +0 -12
- data/spec/integration/generators/helpers_generator_spec.rb +91 -71
- data/spec/integration/generators/invoke_generators_spec.rb +54 -45
- data/spec/integration/generators/rspec_generator_spec.rb +0 -6
- data/spec/integration/scaffolding_e2e_spec.rb +17 -179
- data/spec/integration/spec_helper.rb +4 -6
- data/spec/integration/trace_format_checker.rb +150 -0
- data/spec/integration/trace_page_server.rb +147 -0
- data/spec/menus/menu_generator_spec.rb +14 -39
- data/spec/runtime/actionability_spec.rb +207 -0
- data/spec/runtime/actionable_spec.rb +125 -0
- data/spec/runtime/browser/actionability_script_browser_spec.rb +150 -0
- data/spec/runtime/browser/actionable_browser_spec.rb +98 -0
- data/spec/runtime/browser/finders_browser_spec.rb +148 -0
- data/spec/runtime/browser/matchers_browser_spec.rb +67 -0
- data/spec/runtime/browser/retrying_block_browser_spec.rb +37 -0
- data/spec/runtime/browser/role_engine_browser_spec.rb +184 -0
- data/spec/runtime/browser/strict_browser_spec.rb +38 -0
- data/spec/runtime/by_role_spec.rb +52 -0
- data/spec/runtime/config_spec.rb +79 -0
- data/spec/runtime/context_spec.rb +73 -0
- data/spec/runtime/errors_spec.rb +89 -0
- data/spec/runtime/finders_spec.rb +165 -0
- data/spec/runtime/fixtures/actionability.html +70 -0
- data/spec/runtime/fixtures/locators.html +46 -0
- data/spec/runtime/fixtures/matchers.html +33 -0
- data/spec/runtime/fixtures/roles.html +162 -0
- data/spec/runtime/matchers/base_spec.rb +165 -0
- data/spec/runtime/matchers/element_spec.rb +277 -0
- data/spec/runtime/matchers/page_spec.rb +102 -0
- data/spec/runtime/matchers/presence_spec.rb +59 -0
- data/spec/runtime/matchers/retrying_block_spec.rb +165 -0
- data/spec/runtime/observer_spec.rb +341 -0
- data/spec/runtime/role_finder_spec.rb +156 -0
- data/spec/runtime/role_query_spec.rb +75 -0
- data/spec/runtime/selectors_spec.rb +135 -0
- data/spec/runtime/strict_spec.rb +257 -0
- data/spec/runtime/support/browser.rb +48 -0
- data/spec/runtime/support/fake_bridge.rb +117 -0
- data/spec/runtime/wait_spec.rb +71 -0
- data/spec/scaffolding/name_normalizer_spec.rb +3 -2
- data/spec/scaffolding/scaffold_project_detector_spec.rb +4 -43
- data/spec/system/selenium_spec.rb +1 -5
- data/spec/system/support/system_test_helper.rb +2 -5
- data/spec/utilities/headless_config_spec.rb +0 -7
- data/spec/utilities/trace_command_spec.rb +66 -0
- data/spec/utilities/utilities_spec.rb +24 -0
- metadata +134 -44
- data/lib/generators/automation/templates/header.tt +0 -9
- data/lib/generators/cucumber/cucumber_generator.rb +0 -58
- data/lib/generators/cucumber/templates/accessibility_feature.tt +0 -5
- data/lib/generators/cucumber/templates/accessibility_steps.tt +0 -17
- data/lib/generators/cucumber/templates/cucumber.tt +0 -1
- data/lib/generators/cucumber/templates/env.tt +0 -7
- data/lib/generators/cucumber/templates/feature.tt +0 -21
- data/lib/generators/cucumber/templates/partials/appium_env.tt +0 -26
- data/lib/generators/cucumber/templates/partials/driver_world.tt +0 -18
- data/lib/generators/cucumber/templates/partials/mobile_steps.tt +0 -20
- data/lib/generators/cucumber/templates/partials/selenium_env.tt +0 -56
- data/lib/generators/cucumber/templates/partials/watir_env.tt +0 -48
- data/lib/generators/cucumber/templates/partials/watir_world.tt +0 -4
- data/lib/generators/cucumber/templates/partials/web_steps.tt +0 -28
- data/lib/generators/cucumber/templates/steps.tt +0 -5
- data/lib/generators/cucumber/templates/user_factory.tt +0 -15
- data/lib/generators/cucumber/templates/world.tt +0 -7
- data/lib/generators/templates/helpers/browser_helper.tt +0 -31
- data/lib/generators/templates/helpers/raider_element.tt +0 -159
- data/lib/generators/templates/helpers/wait_helper.tt +0 -470
- data/lib/scaffolding/templates/feature.tt +0 -6
- data/lib/scaffolding/templates/steps.tt +0 -19
- data/sig/generators/cucumber/cucumber_generator.rbs +0 -12
- data/spec/fixtures/watir_master/cucumber_watir/Readme.md.snapshot +0 -175
- data/spec/fixtures/watir_master/cucumber_watir/features/step_definitions/login_steps.rb.snapshot +0 -24
- data/spec/fixtures/watir_master/cucumber_watir/page_objects/abstract/page.rb.snapshot +0 -37
- data/spec/fixtures/watir_master/cucumber_watir/page_objects/pages/login.rb.snapshot +0 -33
- data/spec/fixtures/watir_master/rspec_watir/Readme.md.snapshot +0 -174
- data/spec/fixtures/watir_master/rspec_watir/page_objects/abstract/page.rb.snapshot +0 -37
- data/spec/fixtures/watir_master/rspec_watir/page_objects/pages/login.rb.snapshot +0 -33
- data/spec/fixtures/watir_master/rspec_watir/spec/login_page_spec.rb.snapshot +0 -49
- data/spec/integration/content/cucumber_reporter_content_spec.rb +0 -110
- data/spec/integration/generators/cucumber_generator_spec.rb +0 -100
- data/spec/integration/helpers/wait_helper_mobile_spec.rb +0 -281
- data/spec/integration/helpers/wait_helper_spec.rb +0 -496
- data/spec/integration/helpers/wait_helper_support.rb +0 -183
- data/spec/system/watir_spec.rb +0 -38
|
@@ -0,0 +1,1242 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'cgi/escape'
|
|
4
|
+
require 'fileutils'
|
|
5
|
+
require 'json'
|
|
6
|
+
require 'ruby_raider/runtime'
|
|
7
|
+
require 'selenium-webdriver'
|
|
8
|
+
require 'tmpdir'
|
|
9
|
+
require 'yaml'
|
|
10
|
+
require 'zlib'
|
|
11
|
+
|
|
12
|
+
# Records a trace of each test: one step per element action and navigation, with
|
|
13
|
+
# a screenshot and the page HTML after each state-changing step. stop(keep: true)
|
|
14
|
+
# writes it as trace.zip in the raider-trace v1 format, which Raider Desktop and
|
|
15
|
+
# Hideout open. Any capture error prints one [trace] line and turns tracing off for
|
|
16
|
+
# the rest of the run; it never raises into a test. Something only left out (a
|
|
17
|
+
# screenshot, or network on a browser without BiDi) prints at most one notice. TRACE=off skips tracing and
|
|
18
|
+
# TRACE=on keeps the trace of passing tests too.
|
|
19
|
+
# The Recorder follows Raider.observer. Navigation comes from TraceHelper.listener,
|
|
20
|
+
# and network and console from passive WebDriver BiDi events (chrome, edge and firefox).
|
|
21
|
+
module TraceHelper
|
|
22
|
+
DEFAULTS = { 'enabled' => true, 'max_steps' => 200, 'max_mb' => 20 }.freeze
|
|
23
|
+
PRODUCER = { name: 'ruby_raider', version: '<%= ruby_raider_version %>' }.freeze
|
|
24
|
+
# Only these get a screenshot and a snapshot; query actions cost almost nothing.
|
|
25
|
+
MEDIA_ACTIONS = %w[navigate click send_keys clear submit].freeze
|
|
26
|
+
# Only these record what was typed, as value (null when secret).
|
|
27
|
+
TYPED_ACTIONS = %w[send_keys].freeze
|
|
28
|
+
SECRET_ENV_PREFIX = 'RAIDER_SECRET_'
|
|
29
|
+
# The driver helper sets web_socket_url for these while tracing is on.
|
|
30
|
+
BIDI_BROWSERS = %w[chrome edge firefox].freeze
|
|
31
|
+
# Step entries are named steps/NNNN.*, so a trace keeps at most 9999 steps.
|
|
32
|
+
MAX_STEPS_LIMIT = 9999
|
|
33
|
+
|
|
34
|
+
@disabled = false
|
|
35
|
+
@warned = false
|
|
36
|
+
@disable_warned = false
|
|
37
|
+
@active_recorder = nil
|
|
38
|
+
@flags = Mutex.new
|
|
39
|
+
|
|
40
|
+
class << self
|
|
41
|
+
attr_accessor :active_recorder
|
|
42
|
+
|
|
43
|
+
def config
|
|
44
|
+
@config ||= DEFAULTS.merge(trace_config)
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
def enabled?
|
|
48
|
+
config['enabled'] != false && ENV['TRACE'] != 'off' && !@disabled
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
def keep_all?
|
|
52
|
+
ENV['TRACE'] == 'on'
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
# True while tracing is on for a browser that speaks WebDriver BiDi (Edge reports MicrosoftEdge).
|
|
56
|
+
def bidi?(browser)
|
|
57
|
+
name = browser.to_s.downcase.delete_prefix('microsoft')
|
|
58
|
+
enabled? && ENV['BIDI'].to_s.downcase != 'off' && BIDI_BROWSERS.any? { |bidi_browser| name.start_with?(bidi_browser) }
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
# Passed to Selenium through the driver helper's fan-out listener when the driver is created.
|
|
62
|
+
def listener
|
|
63
|
+
return nil unless enabled?
|
|
64
|
+
|
|
65
|
+
@listener ||= Listener.new
|
|
66
|
+
end
|
|
67
|
+
|
|
68
|
+
# screenshot: ->(driver) { [bytes, ext] }, snapshot: ->(driver) { html }; nil takes the default.
|
|
69
|
+
def recorder_for(driver, screenshot: nil, snapshot: nil)
|
|
70
|
+
return null_recorder unless enabled?
|
|
71
|
+
|
|
72
|
+
recorder = Recorder.new(driver, screenshot: screenshot, snapshot: snapshot)
|
|
73
|
+
Raider.observer = recorder
|
|
74
|
+
# Lazy: the project may have removed network_helper.
|
|
75
|
+
NetworkHelper.observer = MockMarks if defined?(NetworkHelper)
|
|
76
|
+
recorder
|
|
77
|
+
rescue StandardError => e
|
|
78
|
+
disable!("could not create a recorder: #{e.message}")
|
|
79
|
+
null_recorder
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
# Unhooks the recorder from Raider.observer and the navigation listener.
|
|
83
|
+
def release(recorder)
|
|
84
|
+
@active_recorder = nil if @active_recorder.equal?(recorder)
|
|
85
|
+
Raider.observer = nil if Raider.observer.equal?(recorder)
|
|
86
|
+
end
|
|
87
|
+
|
|
88
|
+
# The first reason tracing stopped always gets its own [trace] line, even after a notice.
|
|
89
|
+
def disable!(reason)
|
|
90
|
+
@disabled = true
|
|
91
|
+
release(@active_recorder)
|
|
92
|
+
detach_observer
|
|
93
|
+
return nil unless claim(:@disable_warned)
|
|
94
|
+
|
|
95
|
+
say("#{reason}; tracing disabled for this run")
|
|
96
|
+
nil
|
|
97
|
+
end
|
|
98
|
+
|
|
99
|
+
# At most one notice per run, for something left out of a trace while tracing goes on.
|
|
100
|
+
def warn_once(message)
|
|
101
|
+
return nil unless claim(:@warned)
|
|
102
|
+
|
|
103
|
+
say(message)
|
|
104
|
+
nil
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
# One notice per run for events dropped as malformed, apart from warn_once so neither hides the other.
|
|
108
|
+
def warn_dropped_event(message)
|
|
109
|
+
return nil unless claim(:@dropped_warned)
|
|
110
|
+
|
|
111
|
+
say(message)
|
|
112
|
+
nil
|
|
113
|
+
end
|
|
114
|
+
|
|
115
|
+
# A real number that is neither NaN nor infinite; a duration or a timestamp is built only from these.
|
|
116
|
+
def finite_number?(value)
|
|
117
|
+
value.is_a?(Numeric) && value.real? && value.finite?
|
|
118
|
+
end
|
|
119
|
+
|
|
120
|
+
# Above 9999 is taken as 9999, silently; zero or less (or not a number) as the default.
|
|
121
|
+
def max_steps
|
|
122
|
+
value = config['max_steps'].to_i
|
|
123
|
+
value.positive? ? [value, MAX_STEPS_LIMIT].min : DEFAULTS['max_steps']
|
|
124
|
+
end
|
|
125
|
+
|
|
126
|
+
def max_bytes
|
|
127
|
+
value = config['max_mb'].to_f
|
|
128
|
+
((value.positive? ? value : DEFAULTS['max_mb']) * 1024 * 1024).floor
|
|
129
|
+
end
|
|
130
|
+
|
|
131
|
+
# UTC ISO-8601 with milliseconds.
|
|
132
|
+
def timestamp(time = Time.now)
|
|
133
|
+
time.getutc.strftime('%Y-%m-%dT%H:%M:%S.%LZ')
|
|
134
|
+
end
|
|
135
|
+
|
|
136
|
+
def monotonic_now
|
|
137
|
+
Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
138
|
+
end
|
|
139
|
+
|
|
140
|
+
# The format's error shape, on steps and on test: { class:, message: } or nil.
|
|
141
|
+
def error_json(error)
|
|
142
|
+
error && { class: error.class.name || error.class.to_s, message: error.message }
|
|
143
|
+
end
|
|
144
|
+
|
|
145
|
+
# True when a typed value equals a RAIDER_SECRET_* environment value.
|
|
146
|
+
def secret_value?(value)
|
|
147
|
+
ENV.any? { |name, secret| name.start_with?(SECRET_ENV_PREFIX) && !secret.to_s.empty? && secret == value }
|
|
148
|
+
end
|
|
149
|
+
|
|
150
|
+
private
|
|
151
|
+
|
|
152
|
+
def null_recorder
|
|
153
|
+
detach_observer
|
|
154
|
+
NullRecorder.new
|
|
155
|
+
end
|
|
156
|
+
|
|
157
|
+
def detach_observer
|
|
158
|
+
Raider.observer = nil if Raider.observer.is_a?(Recorder)
|
|
159
|
+
end
|
|
160
|
+
|
|
161
|
+
def trace_config
|
|
162
|
+
trace = YAML.load_file('config/config.yml')['trace']
|
|
163
|
+
trace.is_a?(Hash) ? trace : {}
|
|
164
|
+
rescue StandardError
|
|
165
|
+
{}
|
|
166
|
+
end
|
|
167
|
+
|
|
168
|
+
# Atomically takes a once-only flag; true for the first caller only. Events arrive on websocket threads.
|
|
169
|
+
def claim(flag)
|
|
170
|
+
@flags.synchronize do
|
|
171
|
+
next false if instance_variable_get(flag)
|
|
172
|
+
|
|
173
|
+
instance_variable_set(flag, true)
|
|
174
|
+
end
|
|
175
|
+
end
|
|
176
|
+
|
|
177
|
+
# $stderr.puts, not Kernel#warn: warn is silenced under -W0.
|
|
178
|
+
# rubocop:disable Style/StderrPuts
|
|
179
|
+
def say(message)
|
|
180
|
+
$stderr.puts("[trace] #{message}")
|
|
181
|
+
end
|
|
182
|
+
# rubocop:enable Style/StderrPuts
|
|
183
|
+
end
|
|
184
|
+
|
|
185
|
+
# Where an action was called from, for the observer.
|
|
186
|
+
module Observation
|
|
187
|
+
# helpers/ by its given and its real path (__dir__ is the real one), and the runtime's own directory:
|
|
188
|
+
# the trace, driver and runtime files are never the line that called an action or a navigation.
|
|
189
|
+
HELPER_DIRS = [File.dirname(__FILE__), __dir__, Raider::Observer::LIB_DIR].uniq.map { |dir| File.join(dir, '') }.freeze
|
|
190
|
+
|
|
191
|
+
# The first frame outside helpers/, Ruby and gems, as { file:, line: } (file relative
|
|
192
|
+
# to the working directory when inside it), or nil.
|
|
193
|
+
def self.source
|
|
194
|
+
frame = caller_locations.find { |location| project?(location.absolute_path || location.path) }
|
|
195
|
+
return unless frame
|
|
196
|
+
|
|
197
|
+
{ file: relative(frame.absolute_path || frame.path), line: frame.lineno }
|
|
198
|
+
end
|
|
199
|
+
|
|
200
|
+
def self.project?(path)
|
|
201
|
+
return false if path.start_with?('<internal:') || HELPER_DIRS.any? { |dir| path.start_with?(dir) }
|
|
202
|
+
|
|
203
|
+
library_paths.none? { |root| path.start_with?(root) }
|
|
204
|
+
end
|
|
205
|
+
|
|
206
|
+
def self.library_paths
|
|
207
|
+
@library_paths ||= [*RbConfig::CONFIG.values_at('rubylibdir', 'rubyarchdir'), *Gem.path]
|
|
208
|
+
.compact.map { |dir| File.join(dir, '') }
|
|
209
|
+
end
|
|
210
|
+
|
|
211
|
+
def self.relative(path)
|
|
212
|
+
root = File.join(Dir.pwd, '')
|
|
213
|
+
path.start_with?(root) ? path.delete_prefix(root) : path
|
|
214
|
+
end
|
|
215
|
+
end
|
|
216
|
+
|
|
217
|
+
# One step of the timeline. parent is always nil (the v1 group kind stays readable but is no longer
|
|
218
|
+
# produced); the index is given when the trace is written, after max_steps has dropped steps.
|
|
219
|
+
# element is the format's { tag, label, role }; secret is true, false, or nil while the field is unknown.
|
|
220
|
+
Step = Struct.new(:seq, :parent, :kind, :action, :locator, :url, :page_title, :started_at, :clock, :duration_ms,
|
|
221
|
+
:waited_ms, :retries, :status, :error, :source, :rect, :screenshot, :snapshot, :element,
|
|
222
|
+
:value, :secret, :typed_strings, :name, keyword_init: true) do
|
|
223
|
+
def finish(status, error)
|
|
224
|
+
self.status = status.to_s
|
|
225
|
+
self.error = error
|
|
226
|
+
self.duration_ms = ((TraceHelper.monotonic_now - clock) * 1000).round
|
|
227
|
+
end
|
|
228
|
+
|
|
229
|
+
def as_json(index, parent_index, media)
|
|
230
|
+
json = { index: index, parent_index: parent_index, kind: kind, action: action, locator: locator }
|
|
231
|
+
json[:element] = element if element
|
|
232
|
+
json[:name] = name if name
|
|
233
|
+
json.update(typed) if TYPED_ACTIONS.include?(action)
|
|
234
|
+
json.update(url: url, page_title: page_title, started_at: started_at, duration_ms: duration_ms.to_i,
|
|
235
|
+
waited_ms: waited_ms.to_i, retries: retries.to_i, status: status, error: TraceHelper.error_json(error),
|
|
236
|
+
source: source, rect: rect, screenshot: media[:screenshots], snapshot: media[:snapshots])
|
|
237
|
+
end
|
|
238
|
+
|
|
239
|
+
# A field whose secrecy could not be read (it was never ready, or its script failed) is masked too.
|
|
240
|
+
def typed
|
|
241
|
+
masked = secret != false
|
|
242
|
+
{ value: masked ? nil : value, secret: masked }
|
|
243
|
+
end
|
|
244
|
+
end
|
|
245
|
+
|
|
246
|
+
# Follows a test: the runtime reports element actions to Raider.observer and the
|
|
247
|
+
# navigation listener calls navigated. Media goes to its own tmpdir until stop.
|
|
248
|
+
# BiDi events arrive on Selenium's websocket threads, so the event lists are locked.
|
|
249
|
+
class Recorder
|
|
250
|
+
SNAPSHOT = :page_source.to_proc
|
|
251
|
+
# Requests awaiting their response, and responses awaiting their request: a page cannot grow either past this.
|
|
252
|
+
MAX_PENDING = 1_000
|
|
253
|
+
|
|
254
|
+
attr_reader :dir, :capabilities
|
|
255
|
+
|
|
256
|
+
# The default screenshot is a viewport JPEG through BiDi when it is attached, else a PNG.
|
|
257
|
+
def initialize(driver, screenshot: nil, snapshot: nil)
|
|
258
|
+
@driver = driver
|
|
259
|
+
@screenshot = screenshot || ->(page_driver) { Screenshot.take(page_driver, bidi: @bidi) }
|
|
260
|
+
@snapshot = snapshot || SNAPSHOT
|
|
261
|
+
@recording = false
|
|
262
|
+
@bidi = false
|
|
263
|
+
@lock = Mutex.new
|
|
264
|
+
end
|
|
265
|
+
|
|
266
|
+
def start
|
|
267
|
+
@dir = Dir.mktmpdir('raider-trace')
|
|
268
|
+
reset
|
|
269
|
+
@recording = true
|
|
270
|
+
TraceHelper.active_recorder = self
|
|
271
|
+
connect_bidi
|
|
272
|
+
nil
|
|
273
|
+
rescue StandardError => e
|
|
274
|
+
TraceHelper.disable!("tracing failed to start: #{e.message}")
|
|
275
|
+
discard
|
|
276
|
+
end
|
|
277
|
+
|
|
278
|
+
# Returns the step as the token the runtime hands back (nil when not recording, so no ready or finished
|
|
279
|
+
# follows). args: send_keys' keys. The locator has no label: a page object's element method has returned
|
|
280
|
+
# before the action runs.
|
|
281
|
+
def action_started(action:, locator:, within:, args: nil)
|
|
282
|
+
record('action') do
|
|
283
|
+
step = add(kind: 'action', action: action.to_s, locator: trace_locator(locator, within),
|
|
284
|
+
source: TraceHelper::Observation.source)
|
|
285
|
+
typed(step, Array(args)) if TYPED_ACTIONS.include?(step.action)
|
|
286
|
+
step
|
|
287
|
+
end
|
|
288
|
+
end
|
|
289
|
+
|
|
290
|
+
# match_screenshot compared the page with a baseline. The PNG it took is the step's screenshot,
|
|
291
|
+
# so no second screenshot is taken.
|
|
292
|
+
def screenshot_compared(name:, status:, png:, error: nil)
|
|
293
|
+
record('action') do
|
|
294
|
+
step = add(kind: 'action', action: 'match_screenshot', locator: nil, source: navigation_source)
|
|
295
|
+
step.name = name
|
|
296
|
+
step.finish(status, error)
|
|
297
|
+
step.screenshot = media(step, 'screenshot') { [png, 'png'] }
|
|
298
|
+
nil
|
|
299
|
+
end
|
|
300
|
+
end
|
|
301
|
+
|
|
302
|
+
# The element is ready and the action is about to run: its rect, what it is, and whether it is secret.
|
|
303
|
+
# Query actions skip it, to stay cheap.
|
|
304
|
+
def action_ready(step, element:)
|
|
305
|
+
record('action') do
|
|
306
|
+
element_info(step, element) if element && MEDIA_ACTIONS.include?(step.action)
|
|
307
|
+
nil
|
|
308
|
+
end
|
|
309
|
+
end
|
|
310
|
+
|
|
311
|
+
def action_finished(step, status:, waited_ms:, retries:, error:, **)
|
|
312
|
+
record('action') do
|
|
313
|
+
step.finish(status, error)
|
|
314
|
+
step.waited_ms = waited_ms
|
|
315
|
+
step.retries = retries
|
|
316
|
+
remember_secret(step)
|
|
317
|
+
capture_step_media(step) if MEDIA_ACTIONS.include?(step.action)
|
|
318
|
+
nil
|
|
319
|
+
end
|
|
320
|
+
end
|
|
321
|
+
|
|
322
|
+
# A navigation has begun. Its step stays pending until navigated, so the requests the page makes
|
|
323
|
+
# while loading are credited to it. A driver.get that fails never reaches navigated.
|
|
324
|
+
def navigating(url)
|
|
325
|
+
record('navigation') do
|
|
326
|
+
finish_navigation(:failed)
|
|
327
|
+
@navigation = add(kind: 'navigate', action: 'navigate', locator: nil, source: navigation_source)
|
|
328
|
+
@navigation.url = url if url
|
|
329
|
+
nil
|
|
330
|
+
end
|
|
331
|
+
end
|
|
332
|
+
|
|
333
|
+
def navigated(url)
|
|
334
|
+
record('navigation') do
|
|
335
|
+
step = @navigation || add(kind: 'navigate', action: 'navigate', locator: nil, source: navigation_source)
|
|
336
|
+
@navigation = nil
|
|
337
|
+
step.url = url if url
|
|
338
|
+
step.finish(:passed, nil)
|
|
339
|
+
capture_step_media(step)
|
|
340
|
+
nil
|
|
341
|
+
end
|
|
342
|
+
end
|
|
343
|
+
|
|
344
|
+
# hash: a network[] entry of the format; step_index is filled in when written.
|
|
345
|
+
def network_event(hash)
|
|
346
|
+
record('network') do
|
|
347
|
+
event(:network, hash)
|
|
348
|
+
nil
|
|
349
|
+
end
|
|
350
|
+
end
|
|
351
|
+
|
|
352
|
+
# A request whose response is still to come: network_completed finishes it by its BiDi
|
|
353
|
+
# request id. at: the event's epoch milliseconds, for duration_ms.
|
|
354
|
+
# Each BiDi event runs on its own thread, so a completion can come first; it is then kept
|
|
355
|
+
# until its start arrives.
|
|
356
|
+
def network_started(request, hash, at: nil)
|
|
357
|
+
record('network') do
|
|
358
|
+
entry = event(:network, hash)
|
|
359
|
+
early = @lock.synchronize do
|
|
360
|
+
@requests[request] = [entry, at]
|
|
361
|
+
@requests.shift while @requests.size > MAX_PENDING
|
|
362
|
+
entry.update(@early_marks.delete(request) || {})
|
|
363
|
+
@early.delete(request)
|
|
364
|
+
end
|
|
365
|
+
network_completed(request, *early) if early
|
|
366
|
+
nil
|
|
367
|
+
end
|
|
368
|
+
end
|
|
369
|
+
|
|
370
|
+
# Merges fields into the entry started for request; a redirect's next hop starts a new one.
|
|
371
|
+
def network_completed(request, fields, at = nil)
|
|
372
|
+
record('network') do
|
|
373
|
+
entry, started = @lock.synchronize do
|
|
374
|
+
@requests.delete(request).tap { |found| remember_early(request, fields, at) unless found }
|
|
375
|
+
end
|
|
376
|
+
complete(entry, fields, at, started) if entry
|
|
377
|
+
nil
|
|
378
|
+
end
|
|
379
|
+
end
|
|
380
|
+
|
|
381
|
+
# A mocked request, marked by NetworkHelper before it answers. The entry stays pending: its
|
|
382
|
+
# completion still arrives, and its status wins when it has one. A mark that comes before
|
|
383
|
+
# network_started is kept until the entry exists.
|
|
384
|
+
def network_marked(request, fields)
|
|
385
|
+
record('network') do
|
|
386
|
+
fields = fields.transform_keys(&:to_s)
|
|
387
|
+
@lock.synchronize do
|
|
388
|
+
entry = @requests[request]&.first
|
|
389
|
+
if entry
|
|
390
|
+
entry.update(fields)
|
|
391
|
+
else
|
|
392
|
+
@early_marks[request] = fields
|
|
393
|
+
@early_marks.shift while @early_marks.size > MAX_PENDING
|
|
394
|
+
end
|
|
395
|
+
end
|
|
396
|
+
nil
|
|
397
|
+
end
|
|
398
|
+
end
|
|
399
|
+
|
|
400
|
+
# hash: a console[] entry of the format; step_index is filled in when written.
|
|
401
|
+
def console_event(hash)
|
|
402
|
+
record('console') do
|
|
403
|
+
event(:console, hash)
|
|
404
|
+
nil
|
|
405
|
+
end
|
|
406
|
+
end
|
|
407
|
+
|
|
408
|
+
# The screenshot and the sanitised page HTML after a step, and the page it ended on.
|
|
409
|
+
# One that fails is left out (null in the trace); the step is still kept. While an
|
|
410
|
+
# alert is open nothing is read: any page command would dismiss it.
|
|
411
|
+
def capture_step_media(step)
|
|
412
|
+
return nil if alert_open?
|
|
413
|
+
|
|
414
|
+
page = Page.capture(@driver, @snapshot)
|
|
415
|
+
read_page(step, page)
|
|
416
|
+
step.screenshot = media(step, 'screenshot') { @screenshot.call(@driver) }
|
|
417
|
+
step.snapshot = media(step, 'snapshot') do
|
|
418
|
+
raise page[:error] unless page[:html]
|
|
419
|
+
|
|
420
|
+
[Snapshot.sanitize(page[:html], css: page[:css], skipped: page[:skipped_sheets], secrets: @secrets), 'html']
|
|
421
|
+
end
|
|
422
|
+
nil
|
|
423
|
+
end
|
|
424
|
+
|
|
425
|
+
# test: { identifier:, full_name:, status:, attempt:, error: }. Returns the trace.zip path, or nil.
|
|
426
|
+
def stop(keep:, test:)
|
|
427
|
+
return nil unless @recording
|
|
428
|
+
|
|
429
|
+
@recording = false
|
|
430
|
+
TraceHelper.release(self)
|
|
431
|
+
return discard unless keep && TraceHelper.enabled?
|
|
432
|
+
|
|
433
|
+
finish_navigation(:failed, test[:error])
|
|
434
|
+
failure(test[:error])
|
|
435
|
+
write(test)
|
|
436
|
+
rescue StandardError => e
|
|
437
|
+
TraceHelper.disable!("could not write the trace: #{e.message}")
|
|
438
|
+
discard
|
|
439
|
+
end
|
|
440
|
+
|
|
441
|
+
def cleanup
|
|
442
|
+
TraceHelper.release(self)
|
|
443
|
+
FileUtils.rm_rf(@dir) if @dir
|
|
444
|
+
nil
|
|
445
|
+
rescue StandardError => e
|
|
446
|
+
TraceHelper.disable!("could not remove the trace files: #{e.message}")
|
|
447
|
+
end
|
|
448
|
+
|
|
449
|
+
private
|
|
450
|
+
|
|
451
|
+
def reset
|
|
452
|
+
@steps = []
|
|
453
|
+
@navigation = nil
|
|
454
|
+
@lock.synchronize do
|
|
455
|
+
@events = []
|
|
456
|
+
@requests = {}
|
|
457
|
+
@early = {}
|
|
458
|
+
@early_marks = {}
|
|
459
|
+
end
|
|
460
|
+
@bidi = false
|
|
461
|
+
@seq = 0
|
|
462
|
+
@secrets = []
|
|
463
|
+
@page = { url: nil, page_title: nil }
|
|
464
|
+
@truncated = { steps: 0, screenshots: 0, snapshots: 0, network: 0, console: 0 }
|
|
465
|
+
@capabilities = { network: false, console: false, screenshots: true, snapshots: true }
|
|
466
|
+
@meta = { browser: browser, viewport: viewport, device_pixel_ratio: pixel_ratio }
|
|
467
|
+
@started_at = TraceHelper.timestamp
|
|
468
|
+
end
|
|
469
|
+
|
|
470
|
+
# Network and console come over BiDi; without it the trace still has its steps and media.
|
|
471
|
+
def connect_bidi
|
|
472
|
+
name = @meta[:browser][:name].to_s
|
|
473
|
+
if TraceHelper.bidi?(name)
|
|
474
|
+
@bidi = Bidi.attach(@driver, self)
|
|
475
|
+
else
|
|
476
|
+
TraceHelper.warn_once("network and console not captured: #{name.empty? ? 'this browser' : name} has no WebDriver BiDi")
|
|
477
|
+
end
|
|
478
|
+
@capabilities[:network] = @capabilities[:console] = @bidi
|
|
479
|
+
end
|
|
480
|
+
|
|
481
|
+
# Runs a hook while recording. A hook that fails turns tracing off instead of
|
|
482
|
+
# raising into the runtime (which would warn a second time).
|
|
483
|
+
def record(what)
|
|
484
|
+
return nil unless @recording && TraceHelper.enabled?
|
|
485
|
+
|
|
486
|
+
yield
|
|
487
|
+
rescue StandardError => e
|
|
488
|
+
TraceHelper.disable!("#{what} capture failed: #{e.message}")
|
|
489
|
+
end
|
|
490
|
+
|
|
491
|
+
def add(kind:, action:, locator:, source:)
|
|
492
|
+
finish_navigation(:failed) unless kind == 'navigate'
|
|
493
|
+
@seq += 1
|
|
494
|
+
step = Step.new(seq: @seq, parent: nil, kind: kind, action: action, locator: locator, source: source,
|
|
495
|
+
url: @page[:url], page_title: @page[:page_title], started_at: TraceHelper.timestamp,
|
|
496
|
+
clock: TraceHelper.monotonic_now, waited_ms: 0, retries: 0)
|
|
497
|
+
@steps << step
|
|
498
|
+
drop_oldest_step while @steps.size > TraceHelper.max_steps
|
|
499
|
+
step
|
|
500
|
+
end
|
|
501
|
+
|
|
502
|
+
# A navigation still pending when the next step starts, or at stop, never completed. At stop the test's
|
|
503
|
+
# error goes to it, so failure does not add a second step for the same exception.
|
|
504
|
+
def finish_navigation(status, error = nil)
|
|
505
|
+
return unless @navigation
|
|
506
|
+
|
|
507
|
+
@navigation.finish(status, error)
|
|
508
|
+
@navigation = nil
|
|
509
|
+
end
|
|
510
|
+
|
|
511
|
+
def drop_oldest_step
|
|
512
|
+
step = @steps.shift
|
|
513
|
+
@navigation = nil if step.equal?(@navigation)
|
|
514
|
+
delete_media(step)
|
|
515
|
+
@truncated[:steps] += 1
|
|
516
|
+
end
|
|
517
|
+
|
|
518
|
+
# Called inside the lock.
|
|
519
|
+
def remember_early(request, fields, at)
|
|
520
|
+
@early[request] = [fields, at]
|
|
521
|
+
@early.shift while @early.size > MAX_PENDING
|
|
522
|
+
end
|
|
523
|
+
|
|
524
|
+
def complete(entry, fields, finished, started)
|
|
525
|
+
duration = finished - started if TraceHelper.finite_number?(finished) && TraceHelper.finite_number?(started)
|
|
526
|
+
fields = fields.merge(duration_ms: duration.round) if TraceHelper.finite_number?(duration)
|
|
527
|
+
@lock.synchronize do
|
|
528
|
+
fields = fields.reject { |key, value| key == :status && value.nil? && entry['status'] }
|
|
529
|
+
entry.update(fields.transform_keys(&:to_s))
|
|
530
|
+
end
|
|
531
|
+
end
|
|
532
|
+
|
|
533
|
+
# Returns the stored entry, which network_completed may still fill in.
|
|
534
|
+
def event(list, hash)
|
|
535
|
+
entry = hash.transform_keys(&:to_s)
|
|
536
|
+
@lock.synchronize { @events << [list, @seq, entry] }
|
|
537
|
+
entry
|
|
538
|
+
end
|
|
539
|
+
|
|
540
|
+
def trace_locator(locator, within)
|
|
541
|
+
return nil unless locator
|
|
542
|
+
|
|
543
|
+
traced = { strategy: locator[:strategy], selector: locator[:selector] }
|
|
544
|
+
traced[:within] = within unless within.nil? || within.empty?
|
|
545
|
+
traced
|
|
546
|
+
end
|
|
547
|
+
|
|
548
|
+
def navigation_source
|
|
549
|
+
TraceHelper::Observation.source
|
|
550
|
+
end
|
|
551
|
+
|
|
552
|
+
# The value as typed: strings as they are, keys such as :enter as {enter}.
|
|
553
|
+
def typed(step, args)
|
|
554
|
+
shown = args.flatten.map { |key| key_name(key) }.join
|
|
555
|
+
step.value = shown
|
|
556
|
+
step.typed_strings = [shown, *args.flatten.grep(String)].reject(&:empty?).uniq
|
|
557
|
+
step.secret = true if step.typed_strings.any? { |each_value| TraceHelper.secret_value?(each_value) }
|
|
558
|
+
end
|
|
559
|
+
|
|
560
|
+
# What a masked step typed, so this test's later snapshots blank it too (a show-password
|
|
561
|
+
# toggle makes the field type=text, but its value is still the secret).
|
|
562
|
+
def remember_secret(step)
|
|
563
|
+
return unless TYPED_ACTIONS.include?(step.action) && step.typed[:secret]
|
|
564
|
+
|
|
565
|
+
@secrets |= step.typed_strings.to_a
|
|
566
|
+
end
|
|
567
|
+
|
|
568
|
+
def key_name(key)
|
|
569
|
+
key.is_a?(Symbol) ? "{#{key}}" : key.to_s
|
|
570
|
+
end
|
|
571
|
+
|
|
572
|
+
def element_info(step, element)
|
|
573
|
+
info = Page.element_info(@driver, element)
|
|
574
|
+
return unless info
|
|
575
|
+
|
|
576
|
+
step.rect = info[:rect]
|
|
577
|
+
step.element = info[:element]
|
|
578
|
+
step.secret = info[:secret] || step.secret || false unless info[:secret].nil?
|
|
579
|
+
end
|
|
580
|
+
|
|
581
|
+
# VideoHelper's check, called rather than copied; without the video helper there is no check.
|
|
582
|
+
def alert_open?
|
|
583
|
+
return false unless defined?(VideoHelper) && VideoHelper.respond_to?(:alert_open?)
|
|
584
|
+
|
|
585
|
+
VideoHelper.alert_open?(@driver) == true
|
|
586
|
+
rescue StandardError
|
|
587
|
+
false
|
|
588
|
+
end
|
|
589
|
+
|
|
590
|
+
# A step whose page cannot be read keeps the URL and title it started with.
|
|
591
|
+
def read_page(step, page)
|
|
592
|
+
@page = { url: page[:url] || @page[:url], page_title: page[:page_title] || @page[:page_title] }
|
|
593
|
+
step.url = @page[:url]
|
|
594
|
+
step.page_title = @page[:page_title]
|
|
595
|
+
end
|
|
596
|
+
|
|
597
|
+
def media(step, kind)
|
|
598
|
+
bytes, ext = yield
|
|
599
|
+
path = File.join(@dir, format('%<seq>06d-%<kind>s.%<ext>s', seq: step.seq, kind: kind, ext: ext))
|
|
600
|
+
File.binwrite(path, bytes)
|
|
601
|
+
path
|
|
602
|
+
rescue StandardError => e
|
|
603
|
+
TraceHelper.warn_once("#{kind} not captured: #{e.message}")
|
|
604
|
+
nil
|
|
605
|
+
end
|
|
606
|
+
|
|
607
|
+
def delete_media(step)
|
|
608
|
+
[step.screenshot, step.snapshot].compact.each { |path| FileUtils.rm_f(path) }
|
|
609
|
+
end
|
|
610
|
+
|
|
611
|
+
# A test that raised outside every kept step gets a last failure step. Steps dropped by
|
|
612
|
+
# max_steps own nothing, so their error still gets a step.
|
|
613
|
+
def failure(error)
|
|
614
|
+
return if error.nil? || @steps.any? { |step| step.error.equal?(error) }
|
|
615
|
+
|
|
616
|
+
step = add(kind: 'failure', action: 'failure', locator: nil, source: nil)
|
|
617
|
+
step.finish(:failed, error)
|
|
618
|
+
capture_step_media(step)
|
|
619
|
+
end
|
|
620
|
+
|
|
621
|
+
def write(test)
|
|
622
|
+
@steps.each { |step| step.finish(:failed, nil) unless step.status }
|
|
623
|
+
positions = {}.compare_by_identity
|
|
624
|
+
@steps.each_with_index { |step, position| positions[step] = position }
|
|
625
|
+
caps = Caps.new(TraceHelper.max_bytes)
|
|
626
|
+
media, events = caps.fit(media_entries, event_entries, @steps.size) { |kept, listed| index(test, positions, kept, listed) }
|
|
627
|
+
caps.drops.each { |kind, count| @truncated[kind] += count }
|
|
628
|
+
path = File.join(@dir, 'trace.zip')
|
|
629
|
+
ZipWriter.write(path, [['trace.json', index(test, positions, media, events), true], *media.map(&:entry)])
|
|
630
|
+
end
|
|
631
|
+
|
|
632
|
+
# [Caps::Media] for every captured file, oldest step first.
|
|
633
|
+
def media_entries
|
|
634
|
+
@steps.each_with_index.flat_map do |step, position|
|
|
635
|
+
{ screenshots: step.screenshot, snapshots: step.snapshot }.filter_map do |kind, file|
|
|
636
|
+
next unless file
|
|
637
|
+
|
|
638
|
+
name = format('steps/%<index>04d%<ext>s', index: position + 1, ext: File.extname(file))
|
|
639
|
+
Caps::Media.new(position, kind, ZipWriter.entry(name, File.binread(file), kind == :snapshots))
|
|
640
|
+
end
|
|
641
|
+
end
|
|
642
|
+
end
|
|
643
|
+
|
|
644
|
+
# [Caps::Event] in arrival order, each with the step that was running or had just run.
|
|
645
|
+
def event_entries
|
|
646
|
+
seqs = @steps.map(&:seq)
|
|
647
|
+
events = @lock.synchronize { @events.map { |list, seq, hash| [list, seq, hash.dup] } }
|
|
648
|
+
events.map do |list, seq, hash|
|
|
649
|
+
step_index = [seqs.bsearch_index { |each_seq| each_seq > seq } || seqs.size, 1].max
|
|
650
|
+
entry = { 'step_index' => step_index }.merge(hash.reject { |key, _| key == 'step_index' })
|
|
651
|
+
Caps::Event.new(list, entry, JSON.generate(entry).bytesize + 1)
|
|
652
|
+
end
|
|
653
|
+
end
|
|
654
|
+
|
|
655
|
+
def index(test, positions, media, events)
|
|
656
|
+
names = media.each_with_object(Hash.new { |hash, key| hash[key] = {} }) do |item, by_position|
|
|
657
|
+
by_position[item.position][item.kind] = item.entry.name
|
|
658
|
+
end
|
|
659
|
+
JSON.generate(document(test, steps_json(positions, names), events))
|
|
660
|
+
end
|
|
661
|
+
|
|
662
|
+
def steps_json(positions, names)
|
|
663
|
+
@steps.each_with_index.map do |step, position|
|
|
664
|
+
parent = step.parent && positions[step.parent]
|
|
665
|
+
step.as_json(position + 1, parent && (parent + 1), names.fetch(position, {}))
|
|
666
|
+
end
|
|
667
|
+
end
|
|
668
|
+
|
|
669
|
+
def document(test, steps, events)
|
|
670
|
+
{ format: 'raider-trace', version: 1, producer: PRODUCER,
|
|
671
|
+
test: { identifier: test[:identifier], full_name: test[:full_name], status: test[:status].to_s, attempt: test[:attempt],
|
|
672
|
+
error: TraceHelper.error_json(test[:error]) },
|
|
673
|
+
browser: @meta[:browser], viewport: @meta[:viewport], device_pixel_ratio: @meta[:device_pixel_ratio],
|
|
674
|
+
started_at: @started_at, finished_at: TraceHelper.timestamp, capabilities: @capabilities, truncated: @truncated,
|
|
675
|
+
steps: steps, network: events.select { |item| item.list == :network }.map(&:entry),
|
|
676
|
+
console: events.select { |item| item.list == :console }.map(&:entry) }
|
|
677
|
+
end
|
|
678
|
+
|
|
679
|
+
# Selenium reports Edge as MicrosoftEdge; the trace names it edge, like config.yml.
|
|
680
|
+
def browser
|
|
681
|
+
caps = @driver.capabilities
|
|
682
|
+
name = caps.browser_name.to_s
|
|
683
|
+
{ name: name.casecmp?('MicrosoftEdge') ? 'edge' : name, version: caps.browser_version.to_s }
|
|
684
|
+
rescue StandardError
|
|
685
|
+
{ name: nil, version: nil }
|
|
686
|
+
end
|
|
687
|
+
|
|
688
|
+
# The inner size: the outer window size includes the browser chrome, so it would not match
|
|
689
|
+
# the rects or the viewport screenshot.
|
|
690
|
+
def viewport
|
|
691
|
+
width, height = @driver.execute_script('return [window.innerWidth, window.innerHeight]')
|
|
692
|
+
return { width: nil, height: nil } unless width.is_a?(Numeric) && height.is_a?(Numeric)
|
|
693
|
+
|
|
694
|
+
{ width: width, height: height }
|
|
695
|
+
rescue StandardError
|
|
696
|
+
{ width: nil, height: nil }
|
|
697
|
+
end
|
|
698
|
+
|
|
699
|
+
def pixel_ratio
|
|
700
|
+
ratio = @driver.execute_script('return window.devicePixelRatio')
|
|
701
|
+
ratio.is_a?(Numeric) && ratio.positive? ? ratio : 1
|
|
702
|
+
rescue StandardError
|
|
703
|
+
1
|
|
704
|
+
end
|
|
705
|
+
|
|
706
|
+
def discard
|
|
707
|
+
cleanup
|
|
708
|
+
nil
|
|
709
|
+
end
|
|
710
|
+
end
|
|
711
|
+
|
|
712
|
+
# Keeps the zip under max_mb. Drops, in order: the HTML of the oldest steps, then
|
|
713
|
+
# their screenshots, then the oldest network and console entries. The index and
|
|
714
|
+
# the last 10 steps' media are never dropped. drops counts what went, by kind.
|
|
715
|
+
class Caps
|
|
716
|
+
KEEP_LAST = 10
|
|
717
|
+
MEDIA_ORDER = %i[snapshots screenshots].freeze
|
|
718
|
+
Media = Struct.new(:position, :kind, :entry)
|
|
719
|
+
Event = Struct.new(:list, :entry, :bytes)
|
|
720
|
+
|
|
721
|
+
attr_reader :drops
|
|
722
|
+
|
|
723
|
+
def initialize(limit)
|
|
724
|
+
@limit = limit
|
|
725
|
+
@drops = Hash.new(0)
|
|
726
|
+
end
|
|
727
|
+
|
|
728
|
+
# Yields (media, events) for the trace.json they give; returns the [media, events] to keep.
|
|
729
|
+
def fit(media, events, step_count)
|
|
730
|
+
queue = drop_order(media, events, step_count)
|
|
731
|
+
loop do
|
|
732
|
+
index = yield(media, events)
|
|
733
|
+
excess = size(media, index) - @limit
|
|
734
|
+
return [media, events] if excess <= 0 || queue.empty?
|
|
735
|
+
|
|
736
|
+
ratio = deflated(index).bytesize.fdiv([index.bytesize, 1].max)
|
|
737
|
+
media, events = drop(queue, media, events, excess, ratio)
|
|
738
|
+
end
|
|
739
|
+
end
|
|
740
|
+
|
|
741
|
+
private
|
|
742
|
+
|
|
743
|
+
def drop_order(media, events, step_count)
|
|
744
|
+
droppable = media.select { |item| item.position < step_count - KEEP_LAST }
|
|
745
|
+
MEDIA_ORDER.flat_map { |kind| droppable.select { |item| item.kind == kind } } + events
|
|
746
|
+
end
|
|
747
|
+
|
|
748
|
+
# Drops from the front of the queue until the estimate says excess bytes went.
|
|
749
|
+
def drop(queue, media, events, excess, ratio)
|
|
750
|
+
gone = {}.compare_by_identity
|
|
751
|
+
while excess.positive? && !queue.empty?
|
|
752
|
+
item = queue.shift
|
|
753
|
+
gone[item] = true
|
|
754
|
+
@drops[item.is_a?(Media) ? item.kind : item.list] += 1
|
|
755
|
+
excess -= item.is_a?(Media) ? ZipWriter.footprint(item.entry) : item.bytes * ratio
|
|
756
|
+
end
|
|
757
|
+
[media.reject { |item| gone.key?(item) }, events.reject { |item| gone.key?(item) }]
|
|
758
|
+
end
|
|
759
|
+
|
|
760
|
+
def size(media, index)
|
|
761
|
+
ZipWriter::END_RECORD_BYTES + ZipWriter.footprint(ZipWriter::Entry.new('trace.json', deflated(index))) +
|
|
762
|
+
media.sum { |item| ZipWriter.footprint(item.entry) }
|
|
763
|
+
end
|
|
764
|
+
|
|
765
|
+
def deflated(bytes)
|
|
766
|
+
ZipWriter.entry('trace.json', bytes, true).data
|
|
767
|
+
end
|
|
768
|
+
end
|
|
769
|
+
|
|
770
|
+
# A minimal zip writer (no rubyzip in generated projects): stored or raw-deflated
|
|
771
|
+
# entries, a central directory and the end record. No directories, no zip64.
|
|
772
|
+
module ZipWriter
|
|
773
|
+
Entry = Struct.new(:name, :data, :crc, :raw_size, :compression)
|
|
774
|
+
STORED = 0
|
|
775
|
+
DEFLATED = 8
|
|
776
|
+
VERSION = 20
|
|
777
|
+
LOCAL_HEADER_BYTES = 30
|
|
778
|
+
CENTRAL_RECORD_BYTES = 46
|
|
779
|
+
END_RECORD_BYTES = 22
|
|
780
|
+
|
|
781
|
+
def self.entry(name, bytes, deflate)
|
|
782
|
+
bytes = bytes.to_s.b
|
|
783
|
+
data = deflate ? raw_deflate(bytes) : bytes
|
|
784
|
+
Entry.new(name, data, Zlib.crc32(bytes), bytes.bytesize, deflate ? DEFLATED : STORED)
|
|
785
|
+
end
|
|
786
|
+
|
|
787
|
+
# The bytes an entry takes in the zip: its local header, its data and its central record.
|
|
788
|
+
def self.footprint(entry)
|
|
789
|
+
LOCAL_HEADER_BYTES + CENTRAL_RECORD_BYTES + (2 * entry.name.bytesize) + entry.data.bytesize
|
|
790
|
+
end
|
|
791
|
+
|
|
792
|
+
# entries: [[name, bytes, deflate]] or Entry. Returns path.
|
|
793
|
+
def self.write(path, entries)
|
|
794
|
+
entries = entries.map { |each_entry| each_entry.is_a?(Entry) ? each_entry : entry(*each_entry) }
|
|
795
|
+
stamp = dos_time(Time.now)
|
|
796
|
+
File.open(path, 'wb') do |file|
|
|
797
|
+
central = entries.map do |each_entry|
|
|
798
|
+
offset = file.pos
|
|
799
|
+
file.write(header(each_entry, stamp), each_entry.data)
|
|
800
|
+
central_record(each_entry, stamp, offset)
|
|
801
|
+
end
|
|
802
|
+
start = file.pos
|
|
803
|
+
file.write(central.join)
|
|
804
|
+
file.write([0x06054b50, 0, 0, entries.size, entries.size, file.pos - start, start, 0].pack('VvvvvVVv'))
|
|
805
|
+
end
|
|
806
|
+
path
|
|
807
|
+
end
|
|
808
|
+
|
|
809
|
+
def self.raw_deflate(bytes)
|
|
810
|
+
deflater = Zlib::Deflate.new(Zlib::DEFAULT_COMPRESSION, -Zlib::MAX_WBITS)
|
|
811
|
+
deflater.deflate(bytes, Zlib::FINISH)
|
|
812
|
+
ensure
|
|
813
|
+
deflater&.close
|
|
814
|
+
end
|
|
815
|
+
|
|
816
|
+
def self.header(entry, stamp)
|
|
817
|
+
[0x04034b50, VERSION, 0, entry.compression, *stamp, entry.crc, entry.data.bytesize, entry.raw_size,
|
|
818
|
+
entry.name.bytesize, 0].pack('VvvvvvVVVvv') + entry.name
|
|
819
|
+
end
|
|
820
|
+
|
|
821
|
+
def self.central_record(entry, stamp, offset)
|
|
822
|
+
[0x02014b50, VERSION, VERSION, 0, entry.compression, *stamp, entry.crc, entry.data.bytesize, entry.raw_size,
|
|
823
|
+
entry.name.bytesize, 0, 0, 0, 0, 0, offset].pack('VvvvvvvVVVvvvvvVV') + entry.name
|
|
824
|
+
end
|
|
825
|
+
|
|
826
|
+
# [time, date] in MS-DOS format.
|
|
827
|
+
def self.dos_time(time)
|
|
828
|
+
[(time.hour << 11) | (time.min << 5) | (time.sec / 2), ((time.year - 1980) << 9) | (time.month << 5) | time.day]
|
|
829
|
+
end
|
|
830
|
+
end
|
|
831
|
+
|
|
832
|
+
# Used when tracing is off.
|
|
833
|
+
class NullRecorder
|
|
834
|
+
def start
|
|
835
|
+
nil
|
|
836
|
+
end
|
|
837
|
+
|
|
838
|
+
def navigating(_url)
|
|
839
|
+
nil
|
|
840
|
+
end
|
|
841
|
+
|
|
842
|
+
def navigated(_url)
|
|
843
|
+
nil
|
|
844
|
+
end
|
|
845
|
+
|
|
846
|
+
def network_event(_hash)
|
|
847
|
+
nil
|
|
848
|
+
end
|
|
849
|
+
|
|
850
|
+
def network_started(_request, _hash, **)
|
|
851
|
+
nil
|
|
852
|
+
end
|
|
853
|
+
|
|
854
|
+
def network_completed(_request, _fields, _at = nil)
|
|
855
|
+
nil
|
|
856
|
+
end
|
|
857
|
+
|
|
858
|
+
def network_marked(_request, _fields)
|
|
859
|
+
nil
|
|
860
|
+
end
|
|
861
|
+
|
|
862
|
+
def console_event(_hash)
|
|
863
|
+
nil
|
|
864
|
+
end
|
|
865
|
+
|
|
866
|
+
def stop(**)
|
|
867
|
+
nil
|
|
868
|
+
end
|
|
869
|
+
|
|
870
|
+
def cleanup
|
|
871
|
+
nil
|
|
872
|
+
end
|
|
873
|
+
end
|
|
874
|
+
end
|
|
875
|
+
|
|
876
|
+
# What a step reads from the page, and the snapshot made of its HTML. Kept apart from the
|
|
877
|
+
# recorder above. Every script is guarded: one that fails leaves its fields nil.
|
|
878
|
+
module TraceHelper
|
|
879
|
+
# Reads the page through the driver, one execute_script per call.
|
|
880
|
+
module Page
|
|
881
|
+
# The cssText of every enabled sheet in document order, @import and media kept; a
|
|
882
|
+
# sheet whose rules cannot be read (cross-origin) is skipped and counted. ES5 only.
|
|
883
|
+
STYLES = <<~'JS'
|
|
884
|
+
var skipped = 0;
|
|
885
|
+
function read(sheet) {
|
|
886
|
+
var rules = null, parts = [], media = sheet.media && sheet.media.mediaText;
|
|
887
|
+
try { rules = sheet.cssRules; } catch (e) { rules = null; }
|
|
888
|
+
if (!rules) { skipped += 1; return ''; }
|
|
889
|
+
for (var i = 0; i < rules.length; i += 1) {
|
|
890
|
+
parts.push(rules[i].styleSheet ? read(rules[i].styleSheet) : rules[i].cssText);
|
|
891
|
+
}
|
|
892
|
+
var text = parts.join('\n');
|
|
893
|
+
return media && media !== 'all' ? '@media ' + media + ' {\n' + text + '\n}' : text;
|
|
894
|
+
}
|
|
895
|
+
var css = [];
|
|
896
|
+
for (var i = 0; i < document.styleSheets.length; i += 1) {
|
|
897
|
+
if (!document.styleSheets[i].disabled) { css.push(read(document.styleSheets[i])); }
|
|
898
|
+
}
|
|
899
|
+
return { css: css.join('\n'), skipped: skipped, title: document.title };
|
|
900
|
+
JS
|
|
901
|
+
# The element's viewport rect and what a person would call it. ES5 only.
|
|
902
|
+
ELEMENT = <<~'JS'
|
|
903
|
+
var el = arguments[0], box = el.getBoundingClientRect(), tag = el.tagName.toLowerCase();
|
|
904
|
+
var type = (el.getAttribute('type') || '').toLowerCase();
|
|
905
|
+
var text = (el.innerText || '').replace(/\s+/g, ' ').trim().slice(0, 40);
|
|
906
|
+
var roles = { button: 'button', textarea: 'textbox', select: 'combobox' };
|
|
907
|
+
var role = el.getAttribute('role') || roles[tag] || null;
|
|
908
|
+
if (!role && tag === 'a' && el.hasAttribute('href')) { role = 'link'; }
|
|
909
|
+
if (!role && tag === 'input') {
|
|
910
|
+
if (type === 'checkbox') { role = 'checkbox'; }
|
|
911
|
+
else if (['button', 'submit', 'reset', 'image'].indexOf(type) >= 0) { role = 'button'; }
|
|
912
|
+
else if (['', 'text', 'email', 'password', 'search', 'tel', 'url'].indexOf(type) >= 0) { role = 'textbox'; }
|
|
913
|
+
}
|
|
914
|
+
var autocomplete = (el.getAttribute('autocomplete') || '').toLowerCase();
|
|
915
|
+
return { rect: { x: box.left, y: box.top, width: box.width, height: box.height }, tag: tag,
|
|
916
|
+
label: text || el.getAttribute('aria-label') || el.getAttribute('placeholder') || null, role: role,
|
|
917
|
+
secret: type === 'password' || autocomplete.indexOf('password') >= 0 };
|
|
918
|
+
JS
|
|
919
|
+
|
|
920
|
+
# { html:, css:, skipped_sheets:, page_title:, url: }, plus error: when the HTML could not be read.
|
|
921
|
+
# source reads the HTML (the recorder's snapshot lambda, page_source by default).
|
|
922
|
+
def self.capture(driver, source = :page_source.to_proc)
|
|
923
|
+
styles = script(driver, STYLES) || {}
|
|
924
|
+
page = { css: styles['css'], skipped_sheets: styles['skipped'].to_i,
|
|
925
|
+
page_title: styles['title'] || read { driver.title }, url: read { driver.current_url } }
|
|
926
|
+
page.merge(html: source.call(driver))
|
|
927
|
+
rescue StandardError => e
|
|
928
|
+
(page || {}).merge(html: nil, error: e)
|
|
929
|
+
end
|
|
930
|
+
|
|
931
|
+
# { rect:, element: { tag:, label:, role: }, secret: }, or nil when the script fails.
|
|
932
|
+
def self.element_info(driver, element)
|
|
933
|
+
info = script(driver, ELEMENT, element)
|
|
934
|
+
return unless info
|
|
935
|
+
|
|
936
|
+
{ rect: info['rect'], element: { tag: info['tag'], label: info['label'], role: info['role'] }.compact,
|
|
937
|
+
secret: info['secret'] }
|
|
938
|
+
end
|
|
939
|
+
|
|
940
|
+
# The script's Hash, or nil when it raised or answered something else.
|
|
941
|
+
def self.script(driver, source, *args)
|
|
942
|
+
result = driver.execute_script(source, *args)
|
|
943
|
+
result.is_a?(Hash) ? result : nil
|
|
944
|
+
rescue StandardError
|
|
945
|
+
nil
|
|
946
|
+
end
|
|
947
|
+
|
|
948
|
+
def self.read
|
|
949
|
+
yield
|
|
950
|
+
rescue StandardError
|
|
951
|
+
nil
|
|
952
|
+
end
|
|
953
|
+
end
|
|
954
|
+
|
|
955
|
+
# Makes page HTML safe to keep and to open offline. Scans the HTML string (no parser in a
|
|
956
|
+
# generated project); viewers sanitise again, so the aim is that real pages come out right.
|
|
957
|
+
module Snapshot
|
|
958
|
+
SCRIPT = %r{<script\b[^>]*>.*?</script\s*>|</?script\b[^>]*>}mi.freeze
|
|
959
|
+
STYLE = %r{<style\b[^>]*>.*?</style\s*>}mi.freeze
|
|
960
|
+
# A start tag, its attributes allowed to hold a quoted '>'.
|
|
961
|
+
TAG = /<([a-zA-Z][\w:.-]*)((?:[^>"']|"[^"]*"|'[^']*')*)>/.freeze
|
|
962
|
+
ATTRIBUTE = %r{([^\s"'>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+)))?}.freeze
|
|
963
|
+
URL_ATTRIBUTES = %w[href src action formaction xlink:href].freeze
|
|
964
|
+
SKIPPED_ATTRIBUTE = 'data-raider-skipped-sheets'
|
|
965
|
+
|
|
966
|
+
# Removes scripts, on* handlers, javascript: URLs, <base> and meta refresh; blanks the value of
|
|
967
|
+
# secret inputs. With css (Page.capture's), one <style> holding it replaces every stylesheet
|
|
968
|
+
# link and <style>. <html> gets data-raider-skipped-sheets: the sheets that could not be read.
|
|
969
|
+
# Never adds a <base>: a viewer must not fetch from the site under test.
|
|
970
|
+
# secrets: values the recorder masked in this test; a value attribute equal to one, or to a
|
|
971
|
+
# RAIDER_SECRET_* value, is blanked whatever the field's type is now.
|
|
972
|
+
def self.sanitize(html, css:, skipped: 0, secrets: [])
|
|
973
|
+
html = html.to_s.gsub(SCRIPT, '')
|
|
974
|
+
html = html.gsub(STYLE, '') if css
|
|
975
|
+
links = 0
|
|
976
|
+
html = html.gsub(TAG) do
|
|
977
|
+
tag = Regexp.last_match
|
|
978
|
+
attributes = tag[2].to_enum(:scan, ATTRIBUTE).map { Regexp.last_match }
|
|
979
|
+
next '' if removed?(tag[1].downcase, attributes) { links += 1 }
|
|
980
|
+
|
|
981
|
+
clean(tag[0], tag[1], attributes, secrets)
|
|
982
|
+
end
|
|
983
|
+
html = counted(html, css ? skipped : links)
|
|
984
|
+
css ? with_style(html, css) : html
|
|
985
|
+
end
|
|
986
|
+
|
|
987
|
+
# A <base>, a meta refresh or a stylesheet link (which yields, to be counted).
|
|
988
|
+
def self.removed?(tag, attributes)
|
|
989
|
+
return true if tag == 'base'
|
|
990
|
+
return value(attributes, 'http-equiv').casecmp?('refresh') if tag == 'meta'
|
|
991
|
+
return false unless tag == 'link' && value(attributes, 'rel').downcase.split.include?('stylesheet')
|
|
992
|
+
|
|
993
|
+
yield
|
|
994
|
+
true
|
|
995
|
+
end
|
|
996
|
+
|
|
997
|
+
def self.clean(original, name, attributes, secrets)
|
|
998
|
+
field = name.casecmp?('input') && secret?(attributes)
|
|
999
|
+
kept = attributes.reject { |attribute| unsafe?(attribute) }
|
|
1000
|
+
parts = kept.map { |attribute| blank?(attribute, field, secrets) ? 'value=""' : attribute[0] }
|
|
1001
|
+
return original if parts == attributes.map { |attribute| attribute[0] }
|
|
1002
|
+
|
|
1003
|
+
rebuilt(original, name, parts)
|
|
1004
|
+
end
|
|
1005
|
+
|
|
1006
|
+
# A value attribute of a secret field, or one holding a secret value. The HTML has it
|
|
1007
|
+
# entity-encoded (& as &), so it is decoded before it is compared.
|
|
1008
|
+
def self.blank?(attribute, field, secrets)
|
|
1009
|
+
return false unless attribute[1].casecmp?('value')
|
|
1010
|
+
|
|
1011
|
+
value = attribute_value(attribute)
|
|
1012
|
+
return false if value.empty?
|
|
1013
|
+
|
|
1014
|
+
value = CGI.unescapeHTML(value)
|
|
1015
|
+
field || secrets.include?(value) || TraceHelper.secret_value?(value)
|
|
1016
|
+
end
|
|
1017
|
+
|
|
1018
|
+
def self.rebuilt(original, name, parts)
|
|
1019
|
+
slash = original.match?(%r{/\s*>\z}) ? ' /' : ''
|
|
1020
|
+
"<#{[name, *parts].join(' ')}#{slash}>"
|
|
1021
|
+
end
|
|
1022
|
+
|
|
1023
|
+
# Sets data-raider-skipped-sheets on <html>, once every stylesheet link has been counted.
|
|
1024
|
+
def self.counted(html, skipped)
|
|
1025
|
+
html.sub(/<(html)\b((?:[^>"']|"[^"]*"|'[^']*')*)>/i) do
|
|
1026
|
+
tag = Regexp.last_match
|
|
1027
|
+
parts = tag[2].to_enum(:scan, ATTRIBUTE).map { Regexp.last_match }
|
|
1028
|
+
.reject { |attribute| attribute[1].casecmp?(SKIPPED_ATTRIBUTE) }.map { |attribute| attribute[0] }
|
|
1029
|
+
rebuilt(tag[0], tag[1], parts << %(#{SKIPPED_ATTRIBUTE}="#{skipped.to_i}"))
|
|
1030
|
+
end
|
|
1031
|
+
end
|
|
1032
|
+
|
|
1033
|
+
def self.unsafe?(attribute)
|
|
1034
|
+
name = attribute[1].downcase
|
|
1035
|
+
return true if name.start_with?('on')
|
|
1036
|
+
|
|
1037
|
+
URL_ATTRIBUTES.include?(name) && attribute_value(attribute).gsub(/[\x00-\x20]/, '').match?(/\Ajavascript:/i)
|
|
1038
|
+
end
|
|
1039
|
+
|
|
1040
|
+
def self.secret?(attributes)
|
|
1041
|
+
value(attributes, 'type').casecmp?('password') || value(attributes, 'autocomplete').downcase.include?('password')
|
|
1042
|
+
end
|
|
1043
|
+
|
|
1044
|
+
def self.value(attributes, name)
|
|
1045
|
+
attribute = attributes.find { |each_attribute| each_attribute[1].casecmp?(name) }
|
|
1046
|
+
attribute ? attribute_value(attribute) : ''
|
|
1047
|
+
end
|
|
1048
|
+
|
|
1049
|
+
def self.attribute_value(attribute)
|
|
1050
|
+
attribute[2] || attribute[3] || attribute[4] || ''
|
|
1051
|
+
end
|
|
1052
|
+
|
|
1053
|
+
# One <style> at the end of <head>, or after <html> when there is no head.
|
|
1054
|
+
def self.with_style(html, css)
|
|
1055
|
+
style = "<style>#{css.gsub(%r{</(style)}i) { "<\\/#{Regexp.last_match(1)}" }}</style>"
|
|
1056
|
+
return html.sub(%r{</head\s*>}i) { "#{style}#{Regexp.last_match(0)}" } if html.match?(%r{</head\s*>}i)
|
|
1057
|
+
return html.sub(/<html\b(?:[^>"']|"[^"]*"|'[^']*')*>/i) { "#{Regexp.last_match(0)}#{style}" } if html.match?(/<html\b/i)
|
|
1058
|
+
|
|
1059
|
+
style + html
|
|
1060
|
+
end
|
|
1061
|
+
end
|
|
1062
|
+
end
|
|
1063
|
+
|
|
1064
|
+
# What comes from the browser beside the element actions: navigation from Selenium's event listener,
|
|
1065
|
+
# network and console from WebDriver BiDi, and the screenshot.
|
|
1066
|
+
module TraceHelper
|
|
1067
|
+
# Selenium calls these after each navigation (through the driver helper's fan-out listener).
|
|
1068
|
+
class Listener < Selenium::WebDriver::Support::AbstractEventListener
|
|
1069
|
+
# Before, so the requests of the load belong to the navigate step. If the navigation fails, after is never called.
|
|
1070
|
+
def before_navigate_to(url, _driver)
|
|
1071
|
+
navigating(url)
|
|
1072
|
+
end
|
|
1073
|
+
|
|
1074
|
+
def before_navigate_back(_driver)
|
|
1075
|
+
navigating(nil)
|
|
1076
|
+
end
|
|
1077
|
+
|
|
1078
|
+
def before_navigate_forward(_driver)
|
|
1079
|
+
navigating(nil)
|
|
1080
|
+
end
|
|
1081
|
+
|
|
1082
|
+
def after_navigate_to(url, _driver)
|
|
1083
|
+
navigated(url)
|
|
1084
|
+
end
|
|
1085
|
+
|
|
1086
|
+
# The URL is read from the page with the step's media.
|
|
1087
|
+
def after_navigate_back(_driver)
|
|
1088
|
+
navigated(nil)
|
|
1089
|
+
end
|
|
1090
|
+
|
|
1091
|
+
def after_navigate_forward(_driver)
|
|
1092
|
+
navigated(nil)
|
|
1093
|
+
end
|
|
1094
|
+
|
|
1095
|
+
private
|
|
1096
|
+
|
|
1097
|
+
def navigating(url)
|
|
1098
|
+
TraceHelper.active_recorder&.navigating(url)
|
|
1099
|
+
nil
|
|
1100
|
+
end
|
|
1101
|
+
|
|
1102
|
+
def navigated(url)
|
|
1103
|
+
TraceHelper.active_recorder&.navigated(url)
|
|
1104
|
+
nil
|
|
1105
|
+
end
|
|
1106
|
+
end
|
|
1107
|
+
|
|
1108
|
+
# NetworkHelper's observer: marks the trace entry of a request it answers without the network.
|
|
1109
|
+
module MockMarks
|
|
1110
|
+
def self.request_mocked(request_id:, redirect_count:, outcome:, status: nil)
|
|
1111
|
+
fields = { mocked: outcome }
|
|
1112
|
+
fields[:status] = status if status
|
|
1113
|
+
TraceHelper.active_recorder&.network_marked([request_id, redirect_count], fields)
|
|
1114
|
+
rescue StandardError => e
|
|
1115
|
+
TraceHelper.warn_dropped_event("dropped a mocked-request mark: #{e.class}")
|
|
1116
|
+
end
|
|
1117
|
+
end
|
|
1118
|
+
|
|
1119
|
+
# Passive BiDi: one session.subscribe per driver, never network.addIntercept, which would
|
|
1120
|
+
# pause every request. Events go to the recorder last attached to that driver. Only the
|
|
1121
|
+
# method, URL, status, MIME type, timing, size and error text are kept: no headers, no bodies.
|
|
1122
|
+
module Bidi
|
|
1123
|
+
HANDLERS = { 'network.beforeRequestSent' => :request_sent, 'network.responseCompleted' => :response_completed,
|
|
1124
|
+
'network.fetchError' => :fetch_error, 'log.entryAdded' => :log_entry }.freeze
|
|
1125
|
+
Link = Struct.new(:recorder)
|
|
1126
|
+
@links = ObjectSpace::WeakMap.new
|
|
1127
|
+
|
|
1128
|
+
# True when the driver's network and console events now reach recorder. False, with one
|
|
1129
|
+
# [trace] warning, when the driver has no BiDi or the subscription fails.
|
|
1130
|
+
def self.attach(driver, recorder)
|
|
1131
|
+
link = @links[driver] ||= subscribe(driver.bidi)
|
|
1132
|
+
link.recorder = recorder
|
|
1133
|
+
true
|
|
1134
|
+
rescue StandardError => e
|
|
1135
|
+
TraceHelper.warn_once("network and console not captured: BiDi subscribe failed: #{e.message}")
|
|
1136
|
+
false
|
|
1137
|
+
end
|
|
1138
|
+
|
|
1139
|
+
def self.subscribe(bidi)
|
|
1140
|
+
bidi.session.subscribe(HANDLERS.keys)
|
|
1141
|
+
link = Link.new
|
|
1142
|
+
HANDLERS.each { |event, handler| bidi.add_callback(event) { |params| deliver(link, event, handler, params) } }
|
|
1143
|
+
link
|
|
1144
|
+
end
|
|
1145
|
+
|
|
1146
|
+
# On a websocket thread, which swallows errors. One event we cannot read is dropped with a notice;
|
|
1147
|
+
# tracing carries on, since the next one is usually fine.
|
|
1148
|
+
def self.deliver(link, event, handler, params)
|
|
1149
|
+
recorder = link.recorder
|
|
1150
|
+
send(handler, recorder, params) if recorder
|
|
1151
|
+
rescue StandardError => e
|
|
1152
|
+
TraceHelper.warn_dropped_event("dropped a malformed BiDi #{event} event: #{e.class}")
|
|
1153
|
+
end
|
|
1154
|
+
|
|
1155
|
+
def self.request_sent(recorder, params)
|
|
1156
|
+
key = key(params)
|
|
1157
|
+
request = params['request']
|
|
1158
|
+
recorder.network_started(key,
|
|
1159
|
+
{ method: scalar(request['method']), url: scalar(request['url']), status: nil, mime_type: nil,
|
|
1160
|
+
started_at: time(params['timestamp']), duration_ms: nil, bytes: nil, error: nil },
|
|
1161
|
+
at: params['timestamp'])
|
|
1162
|
+
end
|
|
1163
|
+
|
|
1164
|
+
def self.response_completed(recorder, params)
|
|
1165
|
+
key = key(params)
|
|
1166
|
+
response = params['response'].is_a?(Hash) ? params['response'] : {}
|
|
1167
|
+
recorder.network_completed(key,
|
|
1168
|
+
{ status: scalar(response['status']), mime_type: scalar(response['mimeType']),
|
|
1169
|
+
bytes: scalar(response['bytesReceived'] || response['encodedDataLength']) },
|
|
1170
|
+
finished_at(params))
|
|
1171
|
+
end
|
|
1172
|
+
|
|
1173
|
+
# Epoch ms the response ended. Chrome stamps every event of a request with its start, so the end comes
|
|
1174
|
+
# from request.timings: ms after timeOrigin in Chrome, absolute (timeOrigin 0) in Firefox.
|
|
1175
|
+
def self.finished_at(params)
|
|
1176
|
+
stamp = params['timestamp']
|
|
1177
|
+
origin, response_end = params.dig('request', 'timings')&.values_at('timeOrigin', 'responseEnd')
|
|
1178
|
+
return stamp unless TraceHelper.finite_number?(origin) && TraceHelper.finite_number?(response_end) && response_end.positive?
|
|
1179
|
+
|
|
1180
|
+
[stamp, origin + response_end].select { |ms| TraceHelper.finite_number?(ms) }.max
|
|
1181
|
+
end
|
|
1182
|
+
|
|
1183
|
+
def self.fetch_error(recorder, params)
|
|
1184
|
+
recorder.network_completed(key(params), { error: scalar(params['errorText']) }, params['timestamp'])
|
|
1185
|
+
end
|
|
1186
|
+
|
|
1187
|
+
# A redirect keeps the request id and counts its hops, so the id alone would merge the hops.
|
|
1188
|
+
# An event without an object request that has a string id is malformed: it raises, so deliver drops it.
|
|
1189
|
+
def self.key(params)
|
|
1190
|
+
request = params['request']
|
|
1191
|
+
raise ArgumentError, 'request is not an object with a string id' unless request.is_a?(Hash) && request['request'].is_a?(String)
|
|
1192
|
+
|
|
1193
|
+
hop = params['redirectCount']
|
|
1194
|
+
[request['request'], hop.is_a?(Integer) ? hop : 0]
|
|
1195
|
+
end
|
|
1196
|
+
|
|
1197
|
+
# Only text, finite numbers, booleans and nil are kept from an event; a list or object becomes nil.
|
|
1198
|
+
def self.scalar(value)
|
|
1199
|
+
case value
|
|
1200
|
+
when String, true, false, nil then value
|
|
1201
|
+
when Numeric then value if TraceHelper.finite_number?(value)
|
|
1202
|
+
end
|
|
1203
|
+
end
|
|
1204
|
+
|
|
1205
|
+
def self.log_entry(recorder, params)
|
|
1206
|
+
recorder.console_event(level: scalar(params['level']), text: scalar(params['text']), source: location(params),
|
|
1207
|
+
at: time(params['timestamp']))
|
|
1208
|
+
end
|
|
1209
|
+
|
|
1210
|
+
# "url:line:column" of the innermost frame, 1-based; nil without a stack trace.
|
|
1211
|
+
def self.location(params)
|
|
1212
|
+
frame = Array(params.dig('stackTrace', 'callFrames')).first
|
|
1213
|
+
frame && "#{frame['url']}:#{frame['lineNumber'].to_i + 1}:#{frame['columnNumber'].to_i + 1}"
|
|
1214
|
+
end
|
|
1215
|
+
|
|
1216
|
+
# BiDi timestamps are epoch milliseconds.
|
|
1217
|
+
def self.time(milliseconds)
|
|
1218
|
+
return TraceHelper.timestamp unless TraceHelper.finite_number?(milliseconds)
|
|
1219
|
+
|
|
1220
|
+
TraceHelper.timestamp(Time.at(Rational(milliseconds.to_i, 1000)))
|
|
1221
|
+
end
|
|
1222
|
+
end
|
|
1223
|
+
|
|
1224
|
+
# The viewport after a step: a JPEG through BiDi, else (or when BiDi fails for that shot) a PNG.
|
|
1225
|
+
module Screenshot
|
|
1226
|
+
JPEG = { type: 'image/jpeg', quality: 0.7 }.freeze
|
|
1227
|
+
|
|
1228
|
+
# [bytes, ext]
|
|
1229
|
+
def self.take(driver, bidi:)
|
|
1230
|
+
(bidi && jpeg(driver)) || [driver.screenshot_as(:png), 'png']
|
|
1231
|
+
end
|
|
1232
|
+
|
|
1233
|
+
# In Chrome and Firefox BiDi the window handle is the browsing context id.
|
|
1234
|
+
def self.jpeg(driver)
|
|
1235
|
+
params = { context: driver.window_handle, origin: 'viewport', format: JPEG }
|
|
1236
|
+
result = driver.bidi.send_cmd('browsingContext.captureScreenshot', **params)
|
|
1237
|
+
[result.fetch('data').unpack1('m'), 'jpg']
|
|
1238
|
+
rescue StandardError
|
|
1239
|
+
nil
|
|
1240
|
+
end
|
|
1241
|
+
end
|
|
1242
|
+
end
|