21621: Fix accidentally passing through tabs prop to Tabs component
[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_relative '../lib/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 full_text_excluded_columns
53     [
54       # All the columns that end with "hash" or "uuid" as of June 2024/Arvados 3.0.
55       # It's okay if this list isn't complete, it just needs to be complete
56       # enough to test that full text indexes exclude the right columns.
57       "authorized_user_uuid",
58       "auth_uuid",
59       "cancelled_by_client_uuid",
60       "cancelled_by_user_uuid",
61       "container_uuid",
62       "current_version_uuid",
63       "for_container_uuid",
64       "frozen_by_uuid",
65       "group_uuid",
66       "head_uuid",
67       "is_locked_by_uuid",
68       "locked_by_uuid",
69       "log_uuid",
70       "modified_by_client_uuid",
71       "modified_by_user_uuid",
72       "node_uuid",
73       "object_owner_uuid",
74       "object_uuid",
75       "output_uuid",
76       "owner_uuid",
77       "perm_origin_uuid",
78       "portable_data_hash",
79       "pri_container_uuid",
80       "redirect_to_user_uuid",
81       "requesting_container_uuid",
82       "starting_uuid",
83       "tail_uuid",
84       "target_uuid",
85       "user_uuid",
86       "uuid",
87     ]
88   end
89
90   def show_errors model
91     return lambda { model.errors.full_messages.inspect }
92   end
93 end
94
95 class ActiveSupport::TestCase
96   include FactoryBot::Syntax::Methods
97   fixtures :all
98
99   include ArvadosTestSupport
100   include CurrentApiClient
101
102   setup do
103     Thread.current[:api_client_ip_address] = nil
104     Thread.current[:api_client_authorization] = nil
105     Thread.current[:api_client_uuid] = nil
106     Thread.current[:api_client] = nil
107     Thread.current[:token] = nil
108     Thread.current[:user] = nil
109     restore_configuration
110   end
111
112   teardown do
113     # Confirm that any changed configuration doesn't include non-symbol keys
114     $arvados_config.keys.each do |conf_name|
115       conf = Rails.configuration.send(conf_name)
116       confirm_keys_as_symbols(conf, conf_name) if conf.respond_to?('keys')
117     end
118   end
119
120   def assert_equal(expect, *args)
121     if expect.nil?
122       assert_nil(*args)
123     else
124       super
125     end
126   end
127
128   def assert_not_allowed
129     # Provide a block that calls a Rails boolean "true or false" success value,
130     # like model.save or model.destroy.  This method will test that it either
131     # returns false, or raises a Permission Denied exception.
132     begin
133       refute(yield)
134     rescue ArvadosModel::PermissionDeniedError
135     end
136   end
137
138   def add_permission_link from_who, to_what, perm_type
139     act_as_system_user do
140       Link.create!(tail_uuid: from_who.uuid,
141                    head_uuid: to_what.uuid,
142                    link_class: 'permission',
143                    name: perm_type)
144     end
145   end
146
147   def confirm_keys_as_symbols(conf, conf_name)
148     assert(conf.is_a?(ActiveSupport::OrderedOptions), "#{conf_name} should be an OrderedOptions object")
149     conf.keys.each do |k|
150       assert(k.is_a?(Symbol), "Key '#{k}' on section '#{conf_name}' should be a Symbol")
151       confirm_keys_as_symbols(conf[k], "#{conf_name}.#{k}") if conf[k].respond_to?('keys')
152     end
153   end
154
155   def restore_configuration
156     # Restore configuration settings changed during tests
157     ConfigLoader.copy_into_config $arvados_config, Rails.configuration
158     ConfigLoader.copy_into_config $remaining_config, Rails.configuration
159   end
160
161   def set_user_from_auth(auth_name)
162     client_auth = api_client_authorizations(auth_name)
163     client_auth.user.forget_cached_group_perms
164     Thread.current[:api_client_authorization] = client_auth
165     Thread.current[:api_client] = client_auth.api_client
166     Thread.current[:user] = client_auth.user
167     Thread.current[:token] = client_auth.token
168   end
169
170   def expect_json
171     self.request.headers["Accept"] = "text/json"
172   end
173
174   def authorize_with api_client_auth_name
175     authorize_with_token api_client_authorizations(api_client_auth_name).token
176   end
177
178   def authorize_with_token token
179     t = token
180     t = t.token if t.respond_to? :token
181     ArvadosApiToken.new.call("rack.input" => "",
182                              "HTTP_AUTHORIZATION" => "Bearer #{t}")
183   end
184
185   def salt_token(fixture:, remote:)
186     auth = api_client_authorizations(fixture)
187     uuid = auth.uuid
188     token = auth.api_token
189     hmac = OpenSSL::HMAC.hexdigest('sha1', token, remote)
190     return "v2/#{uuid}/#{hmac}"
191   end
192
193   def self.skip_slow_tests?
194     !(ENV['RAILS_TEST_SHORT'] || '').empty?
195   end
196
197   def self.skip(*args, &block)
198   end
199
200   def self.slow_test(name, &block)
201     test(name, &block) unless skip_slow_tests?
202   end
203 end
204
205 class ActionController::TestCase
206   setup do
207     @test_counter = 0
208     self.request.headers['Accept'] = 'application/json'
209     self.request.headers['Content-Type'] = 'application/json'
210   end
211
212   def check_counter action
213     @test_counter += 1
214     if @test_counter == 2
215       assert_equal 1, 2, "Multiple actions in functional test"
216     end
217   end
218
219   [:get, :post, :put, :patch, :delete].each do |method|
220     define_method method do |action, **kwargs|
221       check_counter action
222       # After Rails 5.0 upgrade, some params don't get properly serialized.
223       # One case are filters: [['attr', 'op', 'val']] become [['attr'], ['op'], ['val']]
224       # if not passed upstream as a JSON string.
225       if kwargs[:params].is_a?(Hash)
226         kwargs[:params].each do |key, _|
227           next if key == :exclude_script_versions # Job Reuse tests
228           # Keys could be: :filters, :where, etc
229           if [Array, Hash].include?(kwargs[:params][key].class)
230             kwargs[:params][key] = SafeJSON.dump(kwargs[:params][key])
231           end
232         end
233       end
234       super action, **kwargs
235     end
236   end
237
238   def self.suite
239     s = super
240     def s.run(*args)
241       @test_case.startup()
242       begin
243         super
244       ensure
245         @test_case.shutdown()
246       end
247     end
248     s
249   end
250   def self.startup; end
251   def self.shutdown; end
252 end
253
254 class ActionDispatch::IntegrationTest
255   teardown do
256     Thread.current[:api_client_ip_address] = nil
257     Thread.current[:api_client_authorization] = nil
258     Thread.current[:api_client_uuid] = nil
259     Thread.current[:api_client] = nil
260     Thread.current[:token] = nil
261     Thread.current[:user] = nil
262   end
263 end
264
265 # Ensure permissions are computed from the test fixtures.
266 refresh_permissions
267 refresh_trashed