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