Merge branch 'master' into 2752-arv-put-resume-wip
[arvados.git] / apps / workbench / test / test_helper.rb
1 ENV["RAILS_ENV"] = "test"
2 unless ENV["NO_COVERAGE_TEST"]
3   begin
4     require 'simplecov'
5     require 'simplecov-rcov'
6     class SimpleCov::Formatter::MergedFormatter
7       def format(result)
8         SimpleCov::Formatter::HTMLFormatter.new.format(result)
9         SimpleCov::Formatter::RcovFormatter.new.format(result)
10       end
11     end
12     SimpleCov.formatter = SimpleCov::Formatter::MergedFormatter
13     SimpleCov.start do
14       add_filter '/test/'
15       add_filter 'initializers/secret_token'
16     end
17   rescue Exception => e
18     $stderr.puts "SimpleCov unavailable (#{e}). Proceeding without."
19   end
20 end
21
22 require File.expand_path('../../config/environment', __FILE__)
23 require 'rails/test_help'
24
25 class ActiveSupport::TestCase
26   # Setup all fixtures in test/fixtures/*.(yml|csv) for all tests in
27   # alphabetical order.
28   #
29   # Note: You'll currently still have to declare fixtures explicitly
30   # in integration tests -- they do not yet inherit this setting
31   fixtures :all
32   def use_token token_name
33     auth = api_fixture('api_client_authorizations')[token_name.to_s]
34     Thread.current[:arvados_api_token] = auth['api_token']
35   end
36
37   def teardown
38     Thread.current[:arvados_api_token] = nil
39     Thread.current[:reader_tokens] = nil
40     super
41   end
42 end
43
44 module ApiFixtureLoader
45   def self.included(base)
46     base.extend(ClassMethods)
47   end
48
49   module ClassMethods
50     @@api_fixtures = {}
51     def api_fixture(name)
52       # Returns the data structure from the named API server test fixture.
53       @@api_fixtures[name] ||= \
54       begin
55         path = File.join(ApiServerForTests::ARV_API_SERVER_DIR,
56                          'test', 'fixtures', "#{name}.yml")
57         YAML.load(IO.read(path))
58       end
59     end
60   end
61   def api_fixture name
62     self.class.api_fixture name
63   end
64 end
65
66 class ActiveSupport::TestCase
67   include ApiFixtureLoader
68   def session_for api_client_auth_name
69     {
70       arvados_api_token: api_fixture('api_client_authorizations')[api_client_auth_name.to_s]['api_token']
71     }
72   end
73 end
74
75 class ApiServerForTests
76   ARV_API_SERVER_DIR = File.expand_path('../../../../services/api', __FILE__)
77   SERVER_PID_PATH = File.expand_path('tmp/pids/wbtest-server.pid', ARV_API_SERVER_DIR)
78   @main_process_pid = $$
79
80   def self._system(*cmd)
81     $stderr.puts "_system #{cmd.inspect}"
82     Bundler.with_clean_env do
83       if not system({'RAILS_ENV' => 'test'}, *cmd)
84         raise RuntimeError, "#{cmd[0]} returned exit code #{$?.exitstatus}"
85       end
86     end
87   end
88
89   def self.make_ssl_cert
90     unless File.exists? './self-signed.key'
91       _system('openssl', 'req', '-new', '-x509', '-nodes',
92               '-out', './self-signed.pem',
93               '-keyout', './self-signed.key',
94               '-days', '3650',
95               '-subj', '/CN=localhost')
96     end
97   end
98
99   def self.kill_server
100     if (pid = find_server_pid)
101       $stderr.puts "Sending TERM to API server, pid #{pid}"
102       Process.kill 'TERM', pid
103     end
104   end
105
106   def self.find_server_pid
107     pid = nil
108     begin
109       pid = IO.read(SERVER_PID_PATH).to_i
110       $stderr.puts "API server is running, pid #{pid.inspect}"
111     rescue Errno::ENOENT
112     end
113     return pid
114   end
115
116   def self.run(args=[])
117     ::MiniTest.after_run do
118       self.kill_server
119     end
120
121     # Kill server left over from previous test run
122     self.kill_server
123
124     Capybara.javascript_driver = :poltergeist
125     Dir.chdir(ARV_API_SERVER_DIR) do |apidir|
126       ENV["NO_COVERAGE_TEST"] = "1"
127       make_ssl_cert
128       _system('bundle', 'exec', 'rake', 'db:test:load')
129       _system('bundle', 'exec', 'rake', 'db:fixtures:load')
130       _system('bundle', 'exec', 'passenger', 'start', '-d', '-p3001',
131               '--pid-file', SERVER_PID_PATH,
132               '--ssl',
133               '--ssl-certificate', 'self-signed.pem',
134               '--ssl-certificate-key', 'self-signed.key')
135       timeout = Time.now.tv_sec + 10
136       good_pid = false
137       while (not good_pid) and (Time.now.tv_sec < timeout)
138         sleep 0.2
139         server_pid = find_server_pid
140         good_pid = (server_pid and
141                     (server_pid > 0) and
142                     (Process.kill(0, server_pid) rescue false))
143       end
144       if not good_pid
145         raise RuntimeError, "could not find API server Rails pid"
146       end
147     end
148   end
149 end
150
151 ApiServerForTests.run