refs #13667 "Merge branch '13667-add-version-file'".
[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/mini_test'
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).api_token
45   end
46
47   def auth(api_client_auth_name)
48     {'HTTP_AUTHORIZATION' => "OAuth2 #{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 FactoryGirl::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[:user] = nil
69     restore_configuration
70   end
71
72   def assert_equal(expect, *args)
73     if expect.nil?
74       assert_nil(*args)
75     else
76       super
77     end
78   end
79
80   def assert_not_allowed
81     # Provide a block that calls a Rails boolean "true or false" success value,
82     # like model.save or model.destroy.  This method will test that it either
83     # returns false, or raises a Permission Denied exception.
84     begin
85       refute(yield)
86     rescue ArvadosModel::PermissionDeniedError
87     end
88   end
89
90   def add_permission_link from_who, to_what, perm_type
91     act_as_system_user do
92       Link.create!(tail_uuid: from_who.uuid,
93                    head_uuid: to_what.uuid,
94                    link_class: 'permission',
95                    name: perm_type)
96     end
97   end
98
99   def restore_configuration
100     # Restore configuration settings changed during tests
101     $application_config.each do |k,v|
102       if k.match(/^[^.]*$/)
103         Rails.configuration.send (k + '='), v
104       end
105     end
106   end
107
108   def set_user_from_auth(auth_name)
109     client_auth = api_client_authorizations(auth_name)
110     Thread.current[:api_client_authorization] = client_auth
111     Thread.current[:api_client] = client_auth.api_client
112     Thread.current[:user] = client_auth.user
113   end
114
115   def expect_json
116     self.request.headers["Accept"] = "text/json"
117   end
118
119   def authorize_with api_client_auth_name
120     authorize_with_token api_client_authorizations(api_client_auth_name).api_token
121   end
122
123   def authorize_with_token token
124     t = token
125     t = t.api_token if t.respond_to? :api_token
126     ArvadosApiToken.new.call("rack.input" => "",
127                              "HTTP_AUTHORIZATION" => "OAuth2 #{t}")
128   end
129
130   def salt_token(fixture:, remote:)
131     auth = api_client_authorizations(fixture)
132     uuid = auth.uuid
133     token = auth.api_token
134     hmac = OpenSSL::HMAC.hexdigest('sha1', token, remote)
135     return "v2/#{uuid}/#{hmac}"
136   end
137
138   def self.skip_slow_tests?
139     !(ENV['RAILS_TEST_SHORT'] || '').empty?
140   end
141
142   def self.skip(*args, &block)
143   end
144
145   def self.slow_test(name, &block)
146     test(name, &block) unless skip_slow_tests?
147   end
148 end
149
150 class ActionController::TestCase
151   setup do
152     @test_counter = 0
153   end
154
155   def check_counter action
156     @test_counter += 1
157     if @test_counter == 2
158       assert_equal 1, 2, "Multiple actions in functional test"
159     end
160   end
161
162   [:get, :post, :put, :patch, :delete].each do |method|
163     define_method method do |action, *args|
164       check_counter action
165       super action, *args
166     end
167   end
168
169   def self.suite
170     s = super
171     def s.run(*args)
172       @test_case.startup()
173       begin
174         super
175       ensure
176         @test_case.shutdown()
177       end
178     end
179     s
180   end
181   def self.startup; end
182   def self.shutdown; end
183 end
184
185 class ActionDispatch::IntegrationTest
186   teardown do
187     Thread.current[:api_client_ip_address] = nil
188     Thread.current[:api_client_authorization] = nil
189     Thread.current[:api_client_uuid] = nil
190     Thread.current[:api_client] = nil
191     Thread.current[:user] = nil
192   end
193 end
194
195 # Ensure permissions are computed from the test fixtures.
196 User.invalidate_permissions_cache