workbench: Improve API server integration launch.
[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
9 class ActionDispatch::IntegrationTest
10   # Make the Capybara DSL available in all integration tests
11   include Capybara::DSL
12
13   def self.api_fixture(name)
14     # Returns the data structure from the named API server test fixture.
15     path = File.join($ARV_API_SERVER_DIR, 'test', 'fixtures', "#{name}.yml")
16     YAML.load(IO.read(path))
17   end
18
19   @@API_AUTHS = api_fixture('api_client_authorizations')
20
21   def page_with_token(token, path='/')
22     # Generate a page path with an embedded API token.
23     # Typical usage: visit page_with_token('token_name', page)
24     # The token can be specified by the name of an api_client_authorizations
25     # fixture, or passed as a raw string.
26     api_token = ((@@API_AUTHS.include? token) ?
27                  @@API_AUTHS[token]['api_token'] : token)
28     sep = (path.include? '?') ? '&' : '?'
29     q_string = URI.encode_www_form('api_token' => api_token)
30     "#{path}#{sep}#{q_string}"
31   end
32 end
33
34 class IntegrationTestRunner < MiniTest::Unit
35   # Don't try to re-use the current Bundle environment when we launch the
36   # API server.
37   @@APIENV = {
38     'BUNDLE_BIN_PATH' => nil,
39     'BUNDLE_GEMFILE' => nil,
40     'RUBYLIB' => nil,
41     'RUBYOPT' => nil,
42   }
43
44   def _system(*cmd)
45     if not system(@@APIENV, *cmd)
46       raise RuntimeError, "#{cmd[0]} returned exit code #{$?.exitstatus}"
47     end
48   end
49
50   def _run(args=[])
51     Capybara.javascript_driver = :poltergeist
52     server_pid = Dir.chdir($ARV_API_SERVER_DIR) do |apidir|
53       _system('bundle', 'exec', 'rake', 'db:test:load')
54       _system('bundle', 'exec', 'rake', 'db:fixtures:load')
55       _system('bundle', 'exec', 'rails', 'server', '-d')
56       pid_path = 'tmp/pids/server.pid'
57       timeout = Time.now.tv_sec + 5
58       while (not File.exists? pid_path) and (Time.now.tv_sec < timeout)
59         sleep 0.2
60       end
61       IO.read(pid_path).to_i
62     end
63     begin
64       super(args)
65     ensure
66       Process.kill('TERM', server_pid)
67     end
68   end
69 end
70
71 MiniTest::Unit.runner = IntegrationTestRunner.new