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