7709: Fix state leaking between test suites.
[arvados.git] / services / api / test / test_helper.rb
1 ENV["RAILS_ENV"] = "test"
2 unless ENV["NO_COVERAGE_TEST"]
3   begin
4     require 'simplecov'
5     require 'simplecov-rcov'
6     class SimpleCov::Formatter::MergedFormatter
7       def format(result)
8         SimpleCov::Formatter::HTMLFormatter.new.format(result)
9         SimpleCov::Formatter::RcovFormatter.new.format(result)
10       end
11     end
12     SimpleCov.formatter = SimpleCov::Formatter::MergedFormatter
13     SimpleCov.start do
14       add_filter '/test/'
15       add_filter 'initializers/secret_token'
16       add_filter 'initializers/omniauth'
17     end
18   rescue Exception => e
19     $stderr.puts "SimpleCov unavailable (#{e}). Proceeding without."
20   end
21 end
22
23 require File.expand_path('../../config/environment', __FILE__)
24 require 'rails/test_help'
25 require 'mocha'
26 require 'mocha/mini_test'
27
28 module ArvadosTestSupport
29   def json_response
30     Oj.strict_load response.body
31   end
32
33   def api_token(api_client_auth_name)
34     api_client_authorizations(api_client_auth_name).api_token
35   end
36
37   def auth(api_client_auth_name)
38     {'HTTP_AUTHORIZATION' => "OAuth2 #{api_token(api_client_auth_name)}"}
39   end
40
41   def show_errors model
42     return lambda { model.errors.full_messages.inspect }
43   end
44 end
45
46 class ActiveSupport::TestCase
47   include FactoryGirl::Syntax::Methods
48   fixtures :all
49
50   include ArvadosTestSupport
51   include CurrentApiClient
52
53   teardown do
54     Thread.current[:api_client_ip_address] = nil
55     Thread.current[:api_client_authorization] = nil
56     Thread.current[:api_client_uuid] = nil
57     Thread.current[:api_client] = nil
58     Thread.current[:user] = nil
59     restore_configuration
60     User.invalidate_permissions_cache
61   end
62
63   def assert_not_allowed
64     # Provide a block that calls a Rails boolean "true or false" success value,
65     # like model.save or model.destroy.  This method will test that it either
66     # returns false, or raises a Permission Denied exception.
67     begin
68       refute(yield)
69     rescue ArvadosModel::PermissionDeniedError
70     end
71   end
72
73   def add_permission_link from_who, to_what, perm_type
74     act_as_system_user do
75       Link.create!(tail_uuid: from_who.uuid,
76                    head_uuid: to_what.uuid,
77                    link_class: 'permission',
78                    name: perm_type)
79     end
80   end
81
82   def restore_configuration
83     # Restore configuration settings changed during tests
84     $application_config.each do |k,v|
85       if k.match(/^[^.]*$/)
86         Rails.configuration.send (k + '='), v
87       end
88     end
89   end
90
91   def set_user_from_auth(auth_name)
92     client_auth = api_client_authorizations(auth_name)
93     Thread.current[:api_client_authorization] = client_auth
94     Thread.current[:api_client] = client_auth.api_client
95     Thread.current[:user] = client_auth.user
96   end
97
98   def expect_json
99     self.request.headers["Accept"] = "text/json"
100   end
101
102   def authorize_with api_client_auth_name
103     authorize_with_token api_client_authorizations(api_client_auth_name).api_token
104   end
105
106   def authorize_with_token token
107     t = token
108     t = t.api_token if t.respond_to? :api_token
109     ArvadosApiToken.new.call("rack.input" => "",
110                              "HTTP_AUTHORIZATION" => "OAuth2 #{t}")
111   end
112
113   def self.skip_slow_tests?
114     !(ENV['RAILS_TEST_SHORT'] || '').empty?
115   end
116
117   def self.skip(*args, &block)
118   end
119
120   def self.slow_test(name, &block)
121     define_method(name, block) unless skip_slow_tests?
122   end
123 end
124
125 class ActionController::TestCase
126   setup do
127     @test_counter = 0
128   end
129
130   def check_counter action
131     @test_counter += 1
132     if @test_counter == 2
133       assert_equal 1, 2, "Multiple actions in functional test"
134     end
135   end
136
137   [:get, :post, :put, :patch, :delete].each do |method|
138     define_method method do |action, *args|
139       check_counter action
140       super action, *args
141     end
142   end
143
144   def self.suite
145     s = super
146     def s.run(*args)
147       @test_case.startup()
148       begin
149         super
150       ensure
151         @test_case.shutdown()
152       end
153     end
154     s
155   end
156   def self.startup; end
157   def self.shutdown; end
158 end
159
160 class ActionDispatch::IntegrationTest
161   teardown do
162     Thread.current[:api_client_ip_address] = nil
163     Thread.current[:api_client_authorization] = nil
164     Thread.current[:api_client_uuid] = nil
165     Thread.current[:api_client] = nil
166     Thread.current[:user] = nil
167   end
168 end
169
170 # Ensure permissions are computed from the test fixtures.
171 User.invalidate_permissions_cache