18874: Add 'services/workbench2/' from commit 'f6f88d9ca9cdeeeebfadcfe999789bfb9f69e5c6'
[arvados.git] / services / api / test / test_helper.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 require 'update_permissions'
6
7 ENV["RAILS_ENV"] = "test"
8 unless ENV["NO_COVERAGE_TEST"]
9   begin
10     verbose_orig = $VERBOSE
11     begin
12       $VERBOSE = nil
13       require 'simplecov'
14       require 'simplecov-rcov'
15     ensure
16       $VERBOSE = verbose_orig
17     end
18     class SimpleCov::Formatter::MergedFormatter
19       def format(result)
20         SimpleCov::Formatter::HTMLFormatter.new.format(result)
21         SimpleCov::Formatter::RcovFormatter.new.format(result)
22       end
23     end
24     SimpleCov.formatter = SimpleCov::Formatter::MergedFormatter
25     SimpleCov.start do
26       add_filter '/test/'
27       add_filter 'initializers/secret_token'
28     end
29   rescue Exception => e
30     $stderr.puts "SimpleCov unavailable (#{e}). Proceeding without."
31   end
32 end
33
34 require File.expand_path('../../config/environment', __FILE__)
35 require 'rails/test_help'
36 require 'mocha'
37 require 'mocha/minitest'
38
39 module ArvadosTestSupport
40   def json_response
41     Oj.strict_load response.body
42   end
43
44   def api_token(api_client_auth_name)
45     api_client_authorizations(api_client_auth_name).token
46   end
47
48   def auth(api_client_auth_name)
49     {'HTTP_AUTHORIZATION' => "Bearer #{api_token(api_client_auth_name)}"}
50   end
51
52   def show_errors model
53     return lambda { model.errors.full_messages.inspect }
54   end
55 end
56
57 class ActiveSupport::TestCase
58   include FactoryBot::Syntax::Methods
59   fixtures :all
60
61   include ArvadosTestSupport
62   include CurrentApiClient
63
64   setup do
65     Thread.current[:api_client_ip_address] = nil
66     Thread.current[:api_client_authorization] = nil
67     Thread.current[:api_client_uuid] = nil
68     Thread.current[:api_client] = nil
69     Thread.current[:token] = nil
70     Thread.current[:user] = nil
71     restore_configuration
72   end
73
74   teardown do
75     # Confirm that any changed configuration doesn't include non-symbol keys
76     $arvados_config.keys.each do |conf_name|
77       conf = Rails.configuration.send(conf_name)
78       confirm_keys_as_symbols(conf, conf_name) if conf.respond_to?('keys')
79     end
80   end
81
82   def assert_equal(expect, *args)
83     if expect.nil?
84       assert_nil(*args)
85     else
86       super
87     end
88   end
89
90   def assert_not_allowed
91     # Provide a block that calls a Rails boolean "true or false" success value,
92     # like model.save or model.destroy.  This method will test that it either
93     # returns false, or raises a Permission Denied exception.
94     begin
95       refute(yield)
96     rescue ArvadosModel::PermissionDeniedError
97     end
98   end
99
100   def add_permission_link from_who, to_what, perm_type
101     act_as_system_user do
102       Link.create!(tail_uuid: from_who.uuid,
103                    head_uuid: to_what.uuid,
104                    link_class: 'permission',
105                    name: perm_type)
106     end
107   end
108
109   def confirm_keys_as_symbols(conf, conf_name)
110     assert(conf.is_a?(ActiveSupport::OrderedOptions), "#{conf_name} should be an OrderedOptions object")
111     conf.keys.each do |k|
112       assert(k.is_a?(Symbol), "Key '#{k}' on section '#{conf_name}' should be a Symbol")
113       confirm_keys_as_symbols(conf[k], "#{conf_name}.#{k}") if conf[k].respond_to?('keys')
114     end
115   end
116
117   def restore_configuration
118     # Restore configuration settings changed during tests
119     ConfigLoader.copy_into_config $arvados_config, Rails.configuration
120     ConfigLoader.copy_into_config $remaining_config, Rails.configuration
121   end
122
123   def set_user_from_auth(auth_name)
124     client_auth = api_client_authorizations(auth_name)
125     client_auth.user.forget_cached_group_perms
126     Thread.current[:api_client_authorization] = client_auth
127     Thread.current[:api_client] = client_auth.api_client
128     Thread.current[:user] = client_auth.user
129     Thread.current[:token] = client_auth.token
130   end
131
132   def expect_json
133     self.request.headers["Accept"] = "text/json"
134   end
135
136   def authorize_with api_client_auth_name
137     authorize_with_token api_client_authorizations(api_client_auth_name).token
138   end
139
140   def authorize_with_token token
141     t = token
142     t = t.token if t.respond_to? :token
143     ArvadosApiToken.new.call("rack.input" => "",
144                              "HTTP_AUTHORIZATION" => "Bearer #{t}")
145   end
146
147   def salt_token(fixture:, remote:)
148     auth = api_client_authorizations(fixture)
149     uuid = auth.uuid
150     token = auth.api_token
151     hmac = OpenSSL::HMAC.hexdigest('sha1', token, remote)
152     return "v2/#{uuid}/#{hmac}"
153   end
154
155   def self.skip_slow_tests?
156     !(ENV['RAILS_TEST_SHORT'] || '').empty?
157   end
158
159   def self.skip(*args, &block)
160   end
161
162   def self.slow_test(name, &block)
163     test(name, &block) unless skip_slow_tests?
164   end
165 end
166
167 class ActionController::TestCase
168   setup do
169     @test_counter = 0
170     self.request.headers['Accept'] = 'application/json'
171     self.request.headers['Content-Type'] = 'application/json'
172   end
173
174   def check_counter action
175     @test_counter += 1
176     if @test_counter == 2
177       assert_equal 1, 2, "Multiple actions in functional test"
178     end
179   end
180
181   [:get, :post, :put, :patch, :delete].each do |method|
182     define_method method do |action, *args|
183       check_counter action
184       # After Rails 5.0 upgrade, some params don't get properly serialized.
185       # One case are filters: [['attr', 'op', 'val']] become [['attr'], ['op'], ['val']]
186       # if not passed upstream as a JSON string.
187       if args[0].is_a?(Hash) && args[0][:params].is_a?(Hash)
188         args[0][:params].each do |key, _|
189           next if key == :exclude_script_versions # Job Reuse tests
190           # Keys could be: :filters, :where, etc
191           if [Array, Hash].include?(args[0][:params][key].class)
192             args[0][:params][key] = SafeJSON.dump(args[0][:params][key])
193           end
194         end
195       end
196       super action, *args
197     end
198   end
199
200   def self.suite
201     s = super
202     def s.run(*args)
203       @test_case.startup()
204       begin
205         super
206       ensure
207         @test_case.shutdown()
208       end
209     end
210     s
211   end
212   def self.startup; end
213   def self.shutdown; end
214 end
215
216 class ActionDispatch::IntegrationTest
217   teardown do
218     Thread.current[:api_client_ip_address] = nil
219     Thread.current[:api_client_authorization] = nil
220     Thread.current[:api_client_uuid] = nil
221     Thread.current[:api_client] = nil
222     Thread.current[:token] = nil
223     Thread.current[:user] = nil
224   end
225 end
226
227 # Ensure permissions are computed from the test fixtures.
228 refresh_permissions
229 refresh_trashed