Reversed histogram format, so timestamps come first.
[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 = ENV.map { |(key, val)| (key =~ /^BUNDLE_/) ? [key, nil] : nil }.
40     compact.to_h
41
42   def _system(*cmd)
43     if not system(@@APIENV, *cmd)
44       raise RuntimeError, "#{cmd[0]} returned exit code #{$?.exitstatus}"
45     end
46   end
47
48   def _run(args=[])
49     Capybara.javascript_driver = :poltergeist
50     server_pid = Dir.chdir($ARV_API_SERVER_DIR) do |apidir|
51       _system('bundle', 'exec', 'rake', 'db:test:load')
52       _system('bundle', 'exec', 'rake', 'db:fixtures:load')
53       _system('bundle', 'exec', 'rails', 'server', '-d')
54       timeout = Time.now.tv_sec + 10
55       begin
56         sleep 0.2
57         begin
58           server_pid = IO.read(SERVER_PID_PATH).to_i
59           good_pid = (server_pid > 0) and (Process.kill(0, pid) rescue false)
60         rescue Errno::ENOENT
61           good_pid = false
62         end
63       end while (not good_pid) and (Time.now.tv_sec < timeout)
64       if not good_pid
65         raise RuntimeError, "could not find API server Rails pid"
66       end
67       server_pid
68     end
69     begin
70       super(args)
71     ensure
72       Process.kill('TERM', server_pid)
73     end
74   end
75 end
76
77 MiniTest::Unit.runner = IntegrationTestRunner.new