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