Merge branch '14196-api-v2-tokens' refs #14196
[arvados.git] / apps / workbench / test / test_helper.rb
index fdde55d41db63aced4559dc8d03409a58cc7246c..8435eb4b7c6331f54483a3b363d1af67f1c7521b 100644 (file)
@@ -1,3 +1,7 @@
+# Copyright (C) The Arvados Authors. All rights reserved.
+#
+# SPDX-License-Identifier: AGPL-3.0
+
 ENV["RAILS_ENV"] = "test" if (ENV["RAILS_ENV"] != "diagnostics" and ENV["RAILS_ENV"] != "performance")
 
 unless ENV["NO_COVERAGE_TEST"]
@@ -31,20 +35,22 @@ class ActiveSupport::TestCase
   # Note: You'll currently still have to declare fixtures explicitly
   # in integration tests -- they do not yet inherit this setting
   fixtures :all
-  def use_token token_name
-    was = Thread.current[:arvados_api_token]
+  def use_token(token_name)
+    user_was = Thread.current[:user]
+    token_was = Thread.current[:arvados_api_token]
     auth = api_fixture('api_client_authorizations')[token_name.to_s]
-    Thread.current[:arvados_api_token] = auth['api_token']
+    Thread.current[:arvados_api_token] = "v2/#{auth['uuid']}/#{auth['api_token']}"
     if block_given?
       begin
         yield
       ensure
-        Thread.current[:arvados_api_token] = was
+        Thread.current[:user] = user_was
+        Thread.current[:arvados_api_token] = token_was
       end
     end
   end
 
-  setup do
+  teardown do
     Thread.current[:arvados_api_token] = nil
     Thread.current[:user] = nil
     Thread.current[:reader_tokens] = nil
@@ -79,15 +85,23 @@ module ApiFixtureLoader
         file = IO.read(path)
         trim_index = file.index('# Test Helper trims the rest of the file')
         file = file[0, trim_index] if trim_index
-        YAML.load(file)
+        YAML.load(file).each do |name, ob|
+          ob.reject! { |k, v| k.start_with?('secret_') }
+        end
       end
-      keys.inject(@@api_fixtures[name]) { |hash, key| hash[key] }
+      keys.inject(@@api_fixtures[name]) { |hash, key| hash[key] }.deep_dup
     end
   end
+
   def api_fixture(name, *keys)
     self.class.api_fixture(name, *keys)
   end
 
+  def api_token(name)
+    auth = api_fixture('api_client_authorizations')[name]
+    "v2/#{auth['uuid']}/#{auth['api_token']}"
+  end
+
   def find_fixture(object_class, name)
     object_class.find(api_fixture(object_class.to_s.pluralize.underscore,
                                   name, "uuid"))
@@ -95,22 +109,40 @@ module ApiFixtureLoader
 end
 
 module ApiMockHelpers
-  def stub_api_calls_with_body body, status_code=200
+  def fake_api_response body, status_code, headers
     resp = mock
-    stubbed_client = ArvadosApiClient.new
-    stubbed_client.instance_eval do
-      resp.responds_like_instance_of HTTP::Message
-      resp.stubs(:content).returns body
-      resp.stubs(:status_code).returns status_code
+    resp.responds_like_instance_of HTTP::Message
+    resp.stubs(:headers).returns headers
+    resp.stubs(:content).returns body
+    resp.stubs(:status_code).returns status_code
+    resp
+  end
+
+  def stub_api_calls_with_body body, status_code=200, headers={}
+    stub_api_calls
+    resp = fake_api_response body, status_code, headers
+    stub_api_client.stubs(:post).returns resp
+  end
+
+  def stub_api_calls
+    @stubbed_client = ArvadosApiClient.new
+    @stubbed_client.instance_eval do
       @api_client = HTTPClient.new
-      @api_client.stubs(:post).returns resp
     end
-    ArvadosApiClient.stubs(:new_or_current).returns(stubbed_client)
+    ArvadosApiClient.stubs(:new_or_current).returns(@stubbed_client)
   end
 
   def stub_api_calls_with_invalid_json
     stub_api_calls_with_body ']"omg,bogus"['
   end
+
+  # Return the HTTPClient mock used by the ArvadosApiClient mock. You
+  # must have called stub_api_calls first.
+  def stub_api_client
+    @stubbed_client.instance_eval do
+      @api_client
+    end
+  end
 end
 
 class ActiveSupport::TestCase
@@ -120,8 +152,9 @@ end
 class ActiveSupport::TestCase
   include ApiFixtureLoader
   def session_for api_client_auth_name
+    auth = api_fixture('api_client_authorizations')[api_client_auth_name.to_s]
     {
-      arvados_api_token: api_fixture('api_client_authorizations')[api_client_auth_name.to_s]['api_token']
+      arvados_api_token: "v2/#{auth['uuid']}/#{auth['api_token']}"
     }
   end
   def json_response
@@ -137,7 +170,7 @@ class ApiServerForTests
   @main_process_pid = $$
   @@server_is_running = false
 
-  def check_call *args
+  def check_output *args
     output = nil
     Bundler.with_clean_env do
       output = IO.popen *args do |io|
@@ -151,26 +184,14 @@ class ApiServerForTests
   end
 
   def run_test_server
-    env_script = nil
     Dir.chdir PYTHON_TESTS_DIR do
-      env_script = check_call %w(python ./run_test_server.py start --auth admin)
+      check_output %w(python ./run_test_server.py start_keep)
     end
-    test_env = {}
-    env_script.each_line do |line|
-      line = line.chomp
-      if 0 == line.index('export ')
-        toks = line.sub('export ', '').split '=', 2
-        $stderr.puts "run_test_server.py: #{toks[0]}=#{toks[1]}"
-        test_env[toks[0]] = toks[1]
-      end
-    end
-    test_env
   end
 
   def stop_test_server
     Dir.chdir PYTHON_TESTS_DIR do
-      # This is a no-op if we're running within run-tests.sh
-      check_call %w(python ./run_test_server.py stop)
+      check_output %w(python ./run_test_server.py stop_keep)
     end
     @@server_is_running = false
   end
@@ -185,9 +206,9 @@ class ApiServerForTests
       stop_test_server
     end
 
-    test_env = run_test_server
-    $application_config['arvados_login_base'] = "https://#{test_env['ARVADOS_API_HOST']}/login"
-    $application_config['arvados_v1_base'] = "https://#{test_env['ARVADOS_API_HOST']}/arvados/v1"
+    run_test_server
+    $application_config['arvados_login_base'] = "https://#{ENV['ARVADOS_API_HOST']}/login"
+    $application_config['arvados_v1_base'] = "https://#{ENV['ARVADOS_API_HOST']}/arvados/v1"
     $application_config['arvados_insecure_host'] = true
     ActiveSupport::TestCase.reset_application_config
 
@@ -196,19 +217,19 @@ class ApiServerForTests
 
   def run_rake_task task_name, arg_string
     Dir.chdir ARV_API_SERVER_DIR do
-      check_call ['bundle', 'exec', 'rake', "#{task_name}[#{arg_string}]"]
+      check_output ['bundle', 'exec', 'rake', "#{task_name}[#{arg_string}]"]
     end
   end
 end
 
 class ActionController::TestCase
   setup do
-    @counter = 0
+    @test_counter = 0
   end
 
   def check_counter action
-    @counter += 1
-    if @counter == 2
+    @test_counter += 1
+    if @test_counter == 2
       assert_equal 1, 2, "Multiple actions in controller test"
     end
   end
@@ -270,12 +291,17 @@ class ActiveSupport::TestCase
   end
 
   def after_teardown
-    if self.class.want_reset_api_fixtures[:after_each_test]
+    if self.class.want_reset_api_fixtures[:after_each_test] and
+        @want_reset_api_fixtures != false
       self.class.reset_api_fixtures_now
     end
     super
   end
 
+  def reset_api_fixtures_after_test t=true
+    @want_reset_api_fixtures = t
+  end
+
   protected
   def self.reset_api_fixtures_now
     # Never try to reset fixtures when we're just using test
@@ -283,7 +309,7 @@ class ActiveSupport::TestCase
     return unless Rails.env == 'test'
 
     auth = api_fixture('api_client_authorizations')['admin_trustedclient']
-    Thread.current[:arvados_api_token] = auth['api_token']
+    Thread.current[:arvados_api_token] = "v2/#{auth['uuid']}/#{auth['api_token']}"
     ArvadosApiClient.new.api(nil, '../../database/reset', {})
     Thread.current[:arvados_api_token] = nil
   end