closes #10005
[arvados.git] / apps / workbench / test / integration_helper.rb
1 require 'test_helper'
2 require 'capybara/rails'
3 require 'capybara/poltergeist'
4 require 'uri'
5 require 'yaml'
6
7 def available_port for_what
8   begin
9     Addrinfo.tcp("0.0.0.0", 0).listen do |srv|
10       port = srv.connect_address.ip_port
11       # Selenium needs an additional locking port, check if it's available
12       # and retry if necessary.
13       if for_what == 'selenium'
14         locking_port = port - 1
15         Addrinfo.tcp("0.0.0.0", locking_port).listen.close
16       end
17       STDERR.puts "Using port #{port} for #{for_what}"
18       return port
19     end
20   rescue Errno::EADDRINUSE, Errno::EACCES
21     retry
22   end
23 end
24
25 def selenium_opts
26   {
27     port: available_port('selenium'),
28   }
29 end
30
31 def poltergeist_opts
32   {
33     phantomjs_options: ['--ignore-ssl-errors=true'],
34     port: available_port('poltergeist'),
35     window_size: [1200, 800],
36   }
37 end
38
39 Capybara.register_driver :poltergeist do |app|
40   Capybara::Poltergeist::Driver.new app, poltergeist_opts
41 end
42
43 Capybara.register_driver :poltergeist_debug do |app|
44   Capybara::Poltergeist::Driver.new app, poltergeist_opts.merge(inspector: true)
45 end
46
47 Capybara.register_driver :poltergeist_with_fake_websocket do |app|
48   js = File.expand_path '../support/fake_websocket.js', __FILE__
49   Capybara::Poltergeist::Driver.new app, poltergeist_opts.merge(extensions: [js])
50 end
51
52 Capybara.register_driver :poltergeist_without_file_api do |app|
53   js = File.expand_path '../support/remove_file_api.js', __FILE__
54   Capybara::Poltergeist::Driver.new app, poltergeist_opts.merge(extensions: [js])
55 end
56
57 Capybara.register_driver :selenium do |app|
58   Capybara::Selenium::Driver.new app, selenium_opts
59 end
60
61 Capybara.register_driver :selenium_with_download do |app|
62   profile = Selenium::WebDriver::Firefox::Profile.new
63   profile['browser.download.dir'] = DownloadHelper.path.to_s
64   profile['browser.download.downloadDir'] = DownloadHelper.path.to_s
65   profile['browser.download.defaultFolder'] = DownloadHelper.path.to_s
66   profile['browser.download.folderList'] = 2 # "save to user-defined location"
67   profile['browser.download.manager.showWhenStarting'] = false
68   profile['browser.helperApps.alwaysAsk.force'] = false
69   profile['browser.helperApps.neverAsk.saveToDisk'] = 'text/plain,application/octet-stream'
70   Capybara::Selenium::Driver.new app, selenium_opts.merge(profile: profile)
71 end
72
73 module WaitForAjax
74   Capybara.default_max_wait_time = 10
75   def wait_for_ajax
76     Timeout.timeout(Capybara.default_max_wait_time) do
77       loop until finished_all_ajax_requests?
78     end
79   end
80
81   def finished_all_ajax_requests?
82     page.evaluate_script('jQuery.active').zero?
83   end
84 end
85
86 module AssertDomEvent
87   # Yield the supplied block, then wait for an event to arrive at a
88   # DOM element.
89   def assert_triggers_dom_event events, target='body'
90     magic = 'received-dom-event-' + rand(2**30).to_s(36)
91     page.evaluate_script <<eos
92       $('#{target}').one('#{events}', function() {
93         $('body').addClass('#{magic}');
94       });
95 eos
96     yield
97     assert_selector "body.#{magic}"
98     page.evaluate_script "$('body').removeClass('#{magic}');";
99   end
100 end
101
102 module HeadlessHelper
103   class HeadlessSingleton
104     @display = ENV['ARVADOS_TEST_HEADLESS_DISPLAY'] || rand(400)+100
105     STDERR.puts "Using display :#{@display} for headless tests"
106     def self.get
107       @headless ||= Headless.new reuse: false, display: @display
108     end
109   end
110
111   Capybara.default_driver = :rack_test
112
113   def self.included base
114     base.class_eval do
115       setup do
116         Capybara.use_default_driver
117         @headless = false
118       end
119
120       teardown do
121         if @headless
122           @headless.stop
123           @headless = false
124         end
125       end
126     end
127   end
128
129   def need_selenium reason=nil, driver=:selenium
130     Capybara.current_driver = driver
131     unless ENV['ARVADOS_TEST_HEADFUL'] or @headless
132       @headless = HeadlessSingleton.get
133       @headless.start
134     end
135   end
136
137   def need_javascript reason=nil
138     unless Capybara.current_driver == :selenium
139       Capybara.current_driver = :poltergeist
140     end
141   end
142 end
143
144 module KeepWebConfig
145   def getport service
146     File.read(File.expand_path("../../../../tmp/#{service}.port", __FILE__))
147   end
148
149   def use_keep_web_config
150     @kwport = getport 'keep-web-ssl'
151     @kwdport = getport 'keep-web-dl-ssl'
152     Rails.configuration.keep_web_url = "https://localhost:#{@kwport}/c=%{uuid_or_pdh}"
153     Rails.configuration.keep_web_download_url = "https://localhost:#{@kwdport}/c=%{uuid_or_pdh}"
154     CollectionsController.any_instance.expects(:file_enumerator).never
155   end
156 end
157
158 class ActionDispatch::IntegrationTest
159   # Make the Capybara DSL available in all integration tests
160   include Capybara::DSL
161   include ApiFixtureLoader
162   include WaitForAjax
163   include AssertDomEvent
164   include HeadlessHelper
165
166   @@API_AUTHS = self.api_fixture('api_client_authorizations')
167
168   def page_with_token(token, path='/')
169     # Generate a page path with an embedded API token.
170     # Typical usage: visit page_with_token('token_name', page)
171     # The token can be specified by the name of an api_client_authorizations
172     # fixture, or passed as a raw string.
173     api_token = ((@@API_AUTHS.include? token) ?
174                  @@API_AUTHS[token]['api_token'] : token)
175     path_parts = path.partition("#")
176     sep = (path_parts.first.include? '?') ? '&' : '?'
177     q_string = URI.encode_www_form('api_token' => api_token)
178     path_parts.insert(1, "#{sep}#{q_string}")
179     path_parts.join("")
180   end
181
182   # Find a page element, but return false instead of raising an
183   # exception if not found. Use this with assertions to explain that
184   # the error signifies a failed test rather than an unexpected error
185   # during a testing procedure.
186   def find? *args
187     begin
188       find *args
189     rescue Capybara::ElementNotFound
190       false
191     end
192   end
193
194   @@screenshot_count = 1
195   def screenshot
196     image_file = "./tmp/workbench-fail-#{@@screenshot_count}.png"
197     begin
198       page.save_screenshot image_file
199     rescue Capybara::NotSupportedByDriverError
200       # C'est la vie.
201     else
202       puts "Saved #{image_file}"
203       @@screenshot_count += 1
204     end
205   end
206
207   teardown do
208     if not passed?
209       screenshot
210     end
211     if Capybara.current_driver == :selenium
212       page.execute_script("window.localStorage.clear()")
213     end
214     Capybara.reset_sessions!
215   end
216 end