16826: Adds catch-all check for any config potentially changed during tests.
[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   teardown 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   def assert_equal(expect, *args)
76     if expect.nil?
77       assert_nil(*args)
78     else
79       super
80     end
81   end
82
83   def assert_not_allowed
84     # Provide a block that calls a Rails boolean "true or false" success value,
85     # like model.save or model.destroy.  This method will test that it either
86     # returns false, or raises a Permission Denied exception.
87     begin
88       refute(yield)
89     rescue ArvadosModel::PermissionDeniedError
90     end
91   end
92
93   def add_permission_link from_who, to_what, perm_type
94     act_as_system_user do
95       Link.create!(tail_uuid: from_who.uuid,
96                    head_uuid: to_what.uuid,
97                    link_class: 'permission',
98                    name: perm_type)
99     end
100   end
101
102   def confirm_keys_as_symbols(a_hash, section_name)
103     a_hash.keys.each do |k|
104       assert(k.is_a?(Symbol), "Key '#{k}' on section '#{section_name}' should be a Symbol")
105       confirm_keys_as_symbols(a_hash[k], "#{section_name}.#{k}") if a_hash[k].is_a?(Hash)
106     end
107   end
108
109   def restore_configuration
110     # Confirm that any changed configuration doesn't include non-symbol keys
111     $arvados_config.keys.each do |config_section_name|
112       config_section = Rails.configuration.send("#{config_section_name}")
113       if config_section.is_a?(Hash)
114         confirm_keys_as_symbols(config_section, config_section_name)
115       end
116     end
117     # Restore configuration settings changed during tests
118     ConfigLoader.copy_into_config $arvados_config, Rails.configuration
119     ConfigLoader.copy_into_config $remaining_config, Rails.configuration
120   end
121
122   def set_user_from_auth(auth_name)
123     client_auth = api_client_authorizations(auth_name)
124     Thread.current[:api_client_authorization] = client_auth
125     Thread.current[:api_client] = client_auth.api_client
126     Thread.current[:user] = client_auth.user
127     Thread.current[:token] = client_auth.token
128   end
129
130   def expect_json
131     self.request.headers["Accept"] = "text/json"
132   end
133
134   def authorize_with api_client_auth_name
135     authorize_with_token api_client_authorizations(api_client_auth_name).token
136   end
137
138   def authorize_with_token token
139     t = token
140     t = t.token if t.respond_to? :token
141     ArvadosApiToken.new.call("rack.input" => "",
142                              "HTTP_AUTHORIZATION" => "Bearer #{t}")
143   end
144
145   def salt_token(fixture:, remote:)
146     auth = api_client_authorizations(fixture)
147     uuid = auth.uuid
148     token = auth.api_token
149     hmac = OpenSSL::HMAC.hexdigest('sha1', token, remote)
150     return "v2/#{uuid}/#{hmac}"
151   end
152
153   def self.skip_slow_tests?
154     !(ENV['RAILS_TEST_SHORT'] || '').empty?
155   end
156
157   def self.skip(*args, &block)
158   end
159
160   def self.slow_test(name, &block)
161     test(name, &block) unless skip_slow_tests?
162   end
163 end
164
165 class ActionController::TestCase
166   setup do
167     @test_counter = 0
168     self.request.headers['Accept'] = 'application/json'
169     self.request.headers['Content-Type'] = 'application/json'
170   end
171
172   def check_counter action
173     @test_counter += 1
174     if @test_counter == 2
175       assert_equal 1, 2, "Multiple actions in functional test"
176     end
177   end
178
179   [:get, :post, :put, :patch, :delete].each do |method|
180     define_method method do |action, *args|
181       check_counter action
182       # After Rails 5.0 upgrade, some params don't get properly serialized.
183       # One case are filters: [['attr', 'op', 'val']] become [['attr'], ['op'], ['val']]
184       # if not passed upstream as a JSON string.
185       if args[0].is_a?(Hash) && args[0][:params].is_a?(Hash)
186         args[0][:params].each do |key, _|
187           next if key == :exclude_script_versions # Job Reuse tests
188           # Keys could be: :filters, :where, etc
189           if [Array, Hash].include?(args[0][:params][key].class)
190             args[0][:params][key] = SafeJSON.dump(args[0][:params][key])
191           end
192         end
193       end
194       super action, *args
195     end
196   end
197
198   def self.suite
199     s = super
200     def s.run(*args)
201       @test_case.startup()
202       begin
203         super
204       ensure
205         @test_case.shutdown()
206       end
207     end
208     s
209   end
210   def self.startup; end
211   def self.shutdown; end
212 end
213
214 class ActionDispatch::IntegrationTest
215   teardown do
216     Thread.current[:api_client_ip_address] = nil
217     Thread.current[:api_client_authorization] = nil
218     Thread.current[:api_client_uuid] = nil
219     Thread.current[:api_client] = nil
220     Thread.current[:token] = nil
221     Thread.current[:user] = nil
222   end
223 end
224
225 # Ensure permissions are computed from the test fixtures.
226 refresh_permissions
227 refresh_trashed