2809: Merge branch '2809-workbench-rails4' refs #2809
[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     super
40   end
41 end
42
43 module ApiFixtureLoader
44   def self.included(base)
45     base.extend(ClassMethods)
46   end
47
48   module ClassMethods
49     @@api_fixtures = {}
50     def api_fixture(name)
51       # Returns the data structure from the named API server test fixture.
52       @@api_fixtures[name] ||= \
53       begin
54         path = File.join(ApiServerForTests::ARV_API_SERVER_DIR,
55                          'test', 'fixtures', "#{name}.yml")
56         YAML.load(IO.read(path))
57       end
58     end
59   end
60   def api_fixture name
61     self.class.api_fixture name
62   end
63 end
64
65 class ActiveSupport::TestCase
66   include ApiFixtureLoader
67   def session_for api_client_auth_name
68     {
69       arvados_api_token: api_fixture('api_client_authorizations')[api_client_auth_name.to_s]['api_token']
70     }
71   end
72 end
73
74 class ApiServerForTests
75   ARV_API_SERVER_DIR = File.expand_path('../../../../services/api', __FILE__)
76   SERVER_PID_PATH = File.expand_path('tmp/pids/wbtest-server.pid', ARV_API_SERVER_DIR)
77   @main_process_pid = $$
78
79   def self._system(*cmd)
80     $stderr.puts "_system #{cmd.inspect}"
81     Bundler.with_clean_env do
82       if not system({'RAILS_ENV' => 'test'}, *cmd)
83         raise RuntimeError, "#{cmd[0]} returned exit code #{$?.exitstatus}"
84       end
85     end
86   end
87
88   def self.make_ssl_cert
89     unless File.exists? './self-signed.key'
90       _system('openssl', 'req', '-new', '-x509', '-nodes',
91               '-out', './self-signed.pem',
92               '-keyout', './self-signed.key',
93               '-days', '3650',
94               '-subj', '/CN=localhost')
95     end
96   end
97
98   def self.kill_server
99     if (pid = find_server_pid)
100       $stderr.puts "Sending TERM to API server, pid #{pid}"
101       Process.kill 'TERM', pid
102     end
103   end
104
105   def self.find_server_pid
106     pid = nil
107     begin
108       pid = IO.read(SERVER_PID_PATH).to_i
109       $stderr.puts "API server is running, pid #{pid.inspect}"
110     rescue Errno::ENOENT
111     end
112     return pid
113   end
114
115   def self.run(args=[])
116     ::MiniTest.after_run do
117       self.kill_server
118     end
119
120     # Kill server left over from previous test run
121     self.kill_server
122
123     Capybara.javascript_driver = :poltergeist
124     Dir.chdir(ARV_API_SERVER_DIR) do |apidir|
125       ENV["NO_COVERAGE_TEST"] = "1"
126       make_ssl_cert
127       _system('bundle', 'exec', 'rake', 'db:test:load')
128       _system('bundle', 'exec', 'rake', 'db:fixtures:load')
129       _system('bundle', 'exec', 'passenger', 'start', '-d', '-p3001',
130               '--pid-file', SERVER_PID_PATH,
131               '--ssl',
132               '--ssl-certificate', 'self-signed.pem',
133               '--ssl-certificate-key', 'self-signed.key')
134       timeout = Time.now.tv_sec + 10
135       good_pid = false
136       while (not good_pid) and (Time.now.tv_sec < timeout)
137         sleep 0.2
138         server_pid = find_server_pid
139         good_pid = (server_pid and
140                     (server_pid > 0) and
141                     (Process.kill(0, server_pid) rescue false))
142       end
143       if not good_pid
144         raise RuntimeError, "could not find API server Rails pid"
145       end
146     end
147   end
148 end
149
150 ApiServerForTests.run