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