Working on setup popup
[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 $ARV_API_SERVER_DIR = File.expand_path('../../../../services/api', __FILE__)
8 SERVER_PID_PATH = 'tmp/pids/server.pid'
9
10 class ActionDispatch::IntegrationTest
11   # Make the Capybara DSL available in all integration tests
12   include Capybara::DSL
13
14   def self.api_fixture(name)
15     # Returns the data structure from the named API server test fixture.
16     path = File.join($ARV_API_SERVER_DIR, 'test', 'fixtures', "#{name}.yml")
17     YAML.load(IO.read(path))
18   end
19
20   @@API_AUTHS = api_fixture('api_client_authorizations')
21
22   def page_with_token(token, path='/')
23     # Generate a page path with an embedded API token.
24     # Typical usage: visit page_with_token('token_name', page)
25     # The token can be specified by the name of an api_client_authorizations
26     # fixture, or passed as a raw string.
27     api_token = ((@@API_AUTHS.include? token) ?
28                  @@API_AUTHS[token]['api_token'] : token)
29     sep = (path.include? '?') ? '&' : '?'
30     q_string = URI.encode_www_form('api_token' => api_token)
31     "#{path}#{sep}#{q_string}"
32   end
33 end
34
35 class IntegrationTestRunner < MiniTest::Unit
36   # Make a hash that unsets Bundle's environment variables.
37   # We'll use this environment when we launch Bundle commands in the API
38   # server.  Otherwise, those commands will try to use Workbench's gems, etc.
39   @@APIENV = Hash[ENV.map { |key, val|
40                     (key =~ /^BUNDLE_/) ? [key, nil] : nil
41                   }.compact]
42
43   def _system(*cmd)
44     if not system(@@APIENV, *cmd)
45       raise RuntimeError, "#{cmd[0]} returned exit code #{$?.exitstatus}"
46     end
47   end
48
49   def _run(args=[])
50     Capybara.javascript_driver = :poltergeist
51     server_pid = Dir.chdir($ARV_API_SERVER_DIR) do |apidir|
52       _system('bundle', 'exec', 'rake', 'db:test:load')
53       _system('bundle', 'exec', 'rake', 'db:fixtures:load')
54       _system('bundle', 'exec', 'rails', 'server', '-d')
55       timeout = Time.now.tv_sec + 10
56       begin
57         sleep 0.2
58         begin
59           server_pid = IO.read(SERVER_PID_PATH).to_i
60           good_pid = (server_pid > 0) and (Process.kill(0, pid) rescue false)
61         rescue Errno::ENOENT
62           good_pid = false
63         end
64       end while (not good_pid) and (Time.now.tv_sec < timeout)
65       if not good_pid
66         raise RuntimeError, "could not find API server Rails pid"
67       end
68       server_pid
69     end
70     begin
71       super(args)
72     ensure
73       Process.kill('TERM', server_pid)
74     end
75   end
76 end
77
78 MiniTest::Unit.runner = IntegrationTestRunner.new