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