Chris@441: # Redmine - project management software Chris@1295: # Copyright (C) 2006-2013 Jean-Philippe Lang Chris@0: # Chris@0: # This program is free software; you can redistribute it and/or Chris@0: # modify it under the terms of the GNU General Public License Chris@0: # as published by the Free Software Foundation; either version 2 Chris@0: # of the License, or (at your option) any later version. Chris@909: # Chris@0: # This program is distributed in the hope that it will be useful, Chris@0: # but WITHOUT ANY WARRANTY; without even the implied warranty of Chris@0: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Chris@0: # GNU General Public License for more details. Chris@909: # Chris@0: # You should have received a copy of the GNU General Public License Chris@0: # along with this program; if not, write to the Free Software Chris@0: # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Chris@0: Chris@1115: #require 'shoulda' Chris@0: ENV["RAILS_ENV"] = "test" Chris@0: require File.expand_path(File.dirname(__FILE__) + "/../config/environment") Chris@1115: require 'rails/test_help' Chris@909: require Rails.root.join('test', 'mocks', 'open_id_authentication_mock.rb').to_s Chris@0: Chris@1115: require File.expand_path(File.dirname(__FILE__) + '/object_helpers') Chris@1115: include ObjectHelpers Chris@0: Chris@0: class ActiveSupport::TestCase Chris@1115: include ActionDispatch::TestProcess Chris@1295: Chris@0: self.use_transactional_fixtures = true Chris@0: self.use_instantiated_fixtures = false Chris@0: Chris@0: def log_user(login, password) Chris@0: User.anonymous Chris@0: get "/login" Chris@0: assert_equal nil, session[:user_id] Chris@0: assert_response :success Chris@0: assert_template "account/login" Chris@0: post "/login", :username => login, :password => password Chris@0: assert_equal login, User.find(session[:user_id]).login Chris@0: end Chris@909: Chris@0: def uploaded_test_file(name, mime) Chris@1115: fixture_file_upload("files/#{name}", mime, true) Chris@1115: end Chris@1115: Chris@1115: def credentials(user, password=nil) Chris@1115: {'HTTP_AUTHORIZATION' => ActionController::HttpAuthentication::Basic.encode_credentials(user, password || user)} Chris@0: end Chris@0: Chris@0: # Mock out a file Chris@14: def self.mock_file Chris@0: file = 'a_file.png' Chris@0: file.stubs(:size).returns(32) Chris@0: file.stubs(:original_filename).returns('a_file.png') Chris@0: file.stubs(:content_type).returns('image/png') Chris@0: file.stubs(:read).returns(false) Chris@0: file Chris@0: end Chris@14: Chris@14: def mock_file Chris@14: self.class.mock_file Chris@14: end Chris@14: Chris@909: def mock_file_with_options(options={}) Chris@909: file = '' Chris@909: file.stubs(:size).returns(32) Chris@909: original_filename = options[:original_filename] || nil Chris@909: file.stubs(:original_filename).returns(original_filename) Chris@909: content_type = options[:content_type] || nil Chris@909: file.stubs(:content_type).returns(content_type) Chris@909: file.stubs(:read).returns(false) Chris@909: file Chris@909: end Chris@909: Chris@0: # Use a temporary directory for attachment related tests Chris@0: def set_tmp_attachments_directory Chris@909: Dir.mkdir "#{Rails.root}/tmp/test" unless File.directory?("#{Rails.root}/tmp/test") Chris@909: unless File.directory?("#{Rails.root}/tmp/test/attachments") Chris@909: Dir.mkdir "#{Rails.root}/tmp/test/attachments" Chris@909: end Chris@909: Attachment.storage_path = "#{Rails.root}/tmp/test/attachments" Chris@0: end Chris@909: Chris@1115: def set_fixtures_attachments_directory Chris@1115: Attachment.storage_path = "#{Rails.root}/test/fixtures/files" Chris@1115: end Chris@1115: Chris@0: def with_settings(options, &block) Chris@1295: saved_settings = options.keys.inject({}) do |h, k| Chris@1295: h[k] = case Setting[k] Chris@1295: when Symbol, false, true, nil Chris@1295: Setting[k] Chris@1295: else Chris@1295: Setting[k].dup Chris@1295: end Chris@1295: h Chris@1295: end Chris@0: options.each {|k, v| Setting[k] = v} Chris@0: yield Chris@441: ensure Chris@909: saved_settings.each {|k, v| Setting[k] = v} if saved_settings Chris@0: end Chris@0: Chris@1115: # Yields the block with user as the current user Chris@1115: def with_current_user(user, &block) Chris@1115: saved_user = User.current Chris@1115: User.current = user Chris@1115: yield Chris@1115: ensure Chris@1115: User.current = saved_user Chris@1115: end Chris@1115: Chris@14: def change_user_password(login, new_password) Chris@14: user = User.first(:conditions => {:login => login}) Chris@14: user.password, user.password_confirmation = new_password, new_password Chris@14: user.save! Chris@14: end Chris@14: Chris@0: def self.ldap_configured? Chris@0: @test_ldap = Net::LDAP.new(:host => '127.0.0.1', :port => 389) Chris@0: return @test_ldap.bind Chris@0: rescue Exception => e Chris@0: # LDAP is not listening Chris@0: return nil Chris@0: end Chris@909: Chris@1115: def self.convert_installed? Chris@1115: Redmine::Thumbnail.convert_available? Chris@1115: end Chris@1115: Chris@0: # Returns the path to the test +vendor+ repository Chris@0: def self.repository_path(vendor) Chris@909: Rails.root.join("tmp/test/#{vendor.downcase}_repository").to_s Chris@0: end Chris@909: Chris@441: # Returns the url of the subversion test repository Chris@441: def self.subversion_repository_url Chris@441: path = repository_path('subversion') Chris@441: path = '/' + path unless path.starts_with?('/') Chris@441: "file://#{path}" Chris@441: end Chris@909: Chris@0: # Returns true if the +vendor+ test repository is configured Chris@0: def self.repository_configured?(vendor) Chris@0: File.directory?(repository_path(vendor)) Chris@0: end Chris@909: Chris@1115: def repository_path_hash(arr) Chris@1115: hs = {} Chris@1115: hs[:path] = arr.join("/") Chris@1115: hs[:param] = arr.join("/") Chris@1115: hs Chris@1115: end Chris@1115: Chris@1115: def assert_save(object) Chris@1115: saved = object.save Chris@1115: message = "#{object.class} could not be saved" Chris@1115: errors = object.errors.full_messages.map {|m| "- #{m}"} Chris@1115: message << ":\n#{errors.join("\n")}" if errors.any? Chris@1115: assert_equal true, saved, message Chris@1115: end Chris@1115: chris@37: def assert_error_tag(options={}) Chris@119: assert_tag({:attributes => { :id => 'errorExplanation' }}.merge(options)) chris@37: end Chris@0: Chris@1115: def assert_include(expected, s, message=nil) Chris@1115: assert s.include?(expected), (message || "\"#{expected}\" not found in \"#{s}\"") Chris@1115: end Chris@1115: Chris@1115: def assert_not_include(expected, s) Chris@1115: assert !s.include?(expected), "\"#{expected}\" found in \"#{s}\"" Chris@1115: end Chris@1115: Chris@1115: def assert_select_in(text, *args, &block) Chris@1115: d = HTML::Document.new(CGI::unescapeHTML(String.new(text))).root Chris@1115: assert_select(d, *args, &block) Chris@1115: end Chris@1115: Chris@1115: def assert_mail_body_match(expected, mail) Chris@1115: if expected.is_a?(String) Chris@1115: assert_include expected, mail_body(mail) Chris@1115: else Chris@1115: assert_match expected, mail_body(mail) Chris@1115: end Chris@1115: end Chris@1115: Chris@1115: def assert_mail_body_no_match(expected, mail) Chris@1115: if expected.is_a?(String) Chris@1115: assert_not_include expected, mail_body(mail) Chris@1115: else Chris@1115: assert_no_match expected, mail_body(mail) Chris@1115: end Chris@1115: end Chris@1115: Chris@1115: def mail_body(mail) Chris@1115: mail.parts.first.body.encoded Chris@909: end Chris@1295: end Chris@909: Chris@1295: module Redmine Chris@1295: module ApiTest Chris@1295: # Base class for API tests Chris@1295: class Base < ActionDispatch::IntegrationTest Chris@1295: # Test that a request allows the three types of API authentication Chris@1295: # Chris@1295: # * HTTP Basic with username and password Chris@1295: # * HTTP Basic with an api key for the username Chris@1295: # * Key based with the key=X parameter Chris@1295: # Chris@1295: # @param [Symbol] http_method the HTTP method for request (:get, :post, :put, :delete) Chris@1295: # @param [String] url the request url Chris@1295: # @param [optional, Hash] parameters additional request parameters Chris@1295: # @param [optional, Hash] options additional options Chris@1295: # @option options [Symbol] :success_code Successful response code (:success) Chris@1295: # @option options [Symbol] :failure_code Failure response code (:unauthorized) Chris@1295: def self.should_allow_api_authentication(http_method, url, parameters={}, options={}) Chris@1295: should_allow_http_basic_auth_with_username_and_password(http_method, url, parameters, options) Chris@1295: should_allow_http_basic_auth_with_key(http_method, url, parameters, options) Chris@1295: should_allow_key_based_auth(http_method, url, parameters, options) Chris@1295: end Chris@1295: Chris@1295: # Test that a request allows the username and password for HTTP BASIC Chris@1295: # Chris@1295: # @param [Symbol] http_method the HTTP method for request (:get, :post, :put, :delete) Chris@1295: # @param [String] url the request url Chris@1295: # @param [optional, Hash] parameters additional request parameters Chris@1295: # @param [optional, Hash] options additional options Chris@1295: # @option options [Symbol] :success_code Successful response code (:success) Chris@1295: # @option options [Symbol] :failure_code Failure response code (:unauthorized) Chris@1295: def self.should_allow_http_basic_auth_with_username_and_password(http_method, url, parameters={}, options={}) Chris@1295: success_code = options[:success_code] || :success Chris@1295: failure_code = options[:failure_code] || :unauthorized Chris@1295: Chris@1295: context "should allow http basic auth using a username and password for #{http_method} #{url}" do Chris@1295: context "with a valid HTTP authentication" do Chris@1295: setup do Chris@1295: @user = User.generate! do |user| Chris@1295: user.admin = true Chris@1295: user.password = 'my_password' Chris@1295: end Chris@1295: send(http_method, url, parameters, credentials(@user.login, 'my_password')) Chris@1295: end Chris@1295: Chris@1295: should_respond_with success_code Chris@1295: should_respond_with_content_type_based_on_url(url) Chris@1295: should "login as the user" do Chris@1295: assert_equal @user, User.current Chris@1295: end Chris@1115: end Chris@1295: Chris@1295: context "with an invalid HTTP authentication" do Chris@1295: setup do Chris@1295: @user = User.generate! Chris@1295: send(http_method, url, parameters, credentials(@user.login, 'wrong_password')) Chris@1295: end Chris@1295: Chris@1295: should_respond_with failure_code Chris@1295: should_respond_with_content_type_based_on_url(url) Chris@1295: should "not login as the user" do Chris@1295: assert_equal User.anonymous, User.current Chris@1295: end Chris@1295: end Chris@1295: Chris@1295: context "without credentials" do Chris@1295: setup do Chris@1295: send(http_method, url, parameters) Chris@1295: end Chris@1295: Chris@1295: should_respond_with failure_code Chris@1295: should_respond_with_content_type_based_on_url(url) Chris@1295: should "include_www_authenticate_header" do Chris@1295: assert @controller.response.headers.has_key?('WWW-Authenticate') Chris@1295: end Chris@1295: end chris@37: end chris@37: end Chris@1295: Chris@1295: # Test that a request allows the API key with HTTP BASIC Chris@1295: # Chris@1295: # @param [Symbol] http_method the HTTP method for request (:get, :post, :put, :delete) Chris@1295: # @param [String] url the request url Chris@1295: # @param [optional, Hash] parameters additional request parameters Chris@1295: # @param [optional, Hash] options additional options Chris@1295: # @option options [Symbol] :success_code Successful response code (:success) Chris@1295: # @option options [Symbol] :failure_code Failure response code (:unauthorized) Chris@1295: def self.should_allow_http_basic_auth_with_key(http_method, url, parameters={}, options={}) Chris@1295: success_code = options[:success_code] || :success Chris@1295: failure_code = options[:failure_code] || :unauthorized Chris@1295: Chris@1295: context "should allow http basic auth with a key for #{http_method} #{url}" do Chris@1295: context "with a valid HTTP authentication using the API token" do Chris@1295: setup do Chris@1295: @user = User.generate! do |user| Chris@1295: user.admin = true Chris@1295: end Chris@1295: @token = Token.create!(:user => @user, :action => 'api') Chris@1295: send(http_method, url, parameters, credentials(@token.value, 'X')) Chris@1295: end Chris@1295: should_respond_with success_code Chris@1295: should_respond_with_content_type_based_on_url(url) Chris@1295: should_be_a_valid_response_string_based_on_url(url) Chris@1295: should "login as the user" do Chris@1295: assert_equal @user, User.current Chris@1295: end Chris@1295: end Chris@1295: Chris@1295: context "with an invalid HTTP authentication" do Chris@1295: setup do Chris@1295: @user = User.generate! Chris@1295: @token = Token.create!(:user => @user, :action => 'feeds') Chris@1295: send(http_method, url, parameters, credentials(@token.value, 'X')) Chris@1295: end Chris@1295: should_respond_with failure_code Chris@1295: should_respond_with_content_type_based_on_url(url) Chris@1295: should "not login as the user" do Chris@1295: assert_equal User.anonymous, User.current Chris@1295: end Chris@1295: end chris@37: end chris@37: end Chris@1295: Chris@1295: # Test that a request allows full key authentication Chris@1295: # Chris@1295: # @param [Symbol] http_method the HTTP method for request (:get, :post, :put, :delete) Chris@1295: # @param [String] url the request url, without the key=ZXY parameter Chris@1295: # @param [optional, Hash] parameters additional request parameters Chris@1295: # @param [optional, Hash] options additional options Chris@1295: # @option options [Symbol] :success_code Successful response code (:success) Chris@1295: # @option options [Symbol] :failure_code Failure response code (:unauthorized) Chris@1295: def self.should_allow_key_based_auth(http_method, url, parameters={}, options={}) Chris@1295: success_code = options[:success_code] || :success Chris@1295: failure_code = options[:failure_code] || :unauthorized Chris@1295: Chris@1295: context "should allow key based auth using key=X for #{http_method} #{url}" do Chris@1295: context "with a valid api token" do Chris@1295: setup do Chris@1295: @user = User.generate! do |user| Chris@1295: user.admin = true Chris@1295: end Chris@1295: @token = Token.create!(:user => @user, :action => 'api') Chris@1295: # Simple url parse to add on ?key= or &key= Chris@1295: request_url = if url.match(/\?/) Chris@1295: url + "&key=#{@token.value}" Chris@1295: else Chris@1295: url + "?key=#{@token.value}" Chris@1295: end Chris@1295: send(http_method, request_url, parameters) Chris@1295: end Chris@1295: should_respond_with success_code Chris@1295: should_respond_with_content_type_based_on_url(url) Chris@1295: should_be_a_valid_response_string_based_on_url(url) Chris@1295: should "login as the user" do Chris@1295: assert_equal @user, User.current Chris@1295: end Chris@1295: end Chris@1295: Chris@1295: context "with an invalid api token" do Chris@1295: setup do Chris@1295: @user = User.generate! do |user| Chris@1295: user.admin = true Chris@1295: end Chris@1295: @token = Token.create!(:user => @user, :action => 'feeds') Chris@1295: # Simple url parse to add on ?key= or &key= Chris@1295: request_url = if url.match(/\?/) Chris@1295: url + "&key=#{@token.value}" Chris@1295: else Chris@1295: url + "?key=#{@token.value}" Chris@1295: end Chris@1295: send(http_method, request_url, parameters) Chris@1295: end Chris@1295: should_respond_with failure_code Chris@1295: should_respond_with_content_type_based_on_url(url) Chris@1295: should "not login as the user" do Chris@1295: assert_equal User.anonymous, User.current Chris@1295: end Chris@1295: end chris@37: end Chris@1295: Chris@1295: context "should allow key based auth using X-Redmine-API-Key header for #{http_method} #{url}" do Chris@1295: setup do Chris@1295: @user = User.generate! do |user| Chris@1295: user.admin = true Chris@1295: end Chris@1295: @token = Token.create!(:user => @user, :action => 'api') Chris@1295: send(http_method, url, parameters, {'X-Redmine-API-Key' => @token.value.to_s}) Chris@1295: end Chris@1295: should_respond_with success_code Chris@1295: should_respond_with_content_type_based_on_url(url) Chris@1295: should_be_a_valid_response_string_based_on_url(url) Chris@1295: should "login as the user" do Chris@1295: assert_equal @user, User.current Chris@1295: end Chris@1295: end Chris@1295: end Chris@1295: Chris@1295: # Uses should_respond_with_content_type based on what's in the url: Chris@1295: # Chris@1295: # '/project/issues.xml' => should_respond_with_content_type :xml Chris@1295: # '/project/issues.json' => should_respond_with_content_type :json Chris@1295: # Chris@1295: # @param [String] url Request Chris@1295: def self.should_respond_with_content_type_based_on_url(url) Chris@1295: case Chris@1295: when url.match(/xml/i) Chris@1295: should "respond with XML" do Chris@1295: assert_equal 'application/xml', @response.content_type Chris@1295: end Chris@1295: when url.match(/json/i) Chris@1295: should "respond with JSON" do Chris@1295: assert_equal 'application/json', @response.content_type Chris@1295: end Chris@1295: else Chris@1295: raise "Unknown content type for should_respond_with_content_type_based_on_url: #{url}" Chris@1295: end Chris@1295: end Chris@1295: Chris@1295: # Uses the url to assert which format the response should be in Chris@1295: # Chris@1295: # '/project/issues.xml' => should_be_a_valid_xml_string Chris@1295: # '/project/issues.json' => should_be_a_valid_json_string Chris@1295: # Chris@1295: # @param [String] url Request Chris@1295: def self.should_be_a_valid_response_string_based_on_url(url) Chris@1295: case Chris@1295: when url.match(/xml/i) Chris@1295: should_be_a_valid_xml_string Chris@1295: when url.match(/json/i) Chris@1295: should_be_a_valid_json_string Chris@1295: else Chris@1295: raise "Unknown content type for should_be_a_valid_response_based_on_url: #{url}" Chris@1295: end Chris@1295: end Chris@1295: Chris@1295: # Checks that the response is a valid JSON string Chris@1295: def self.should_be_a_valid_json_string Chris@1295: should "be a valid JSON string (or empty)" do Chris@1295: assert(response.body.blank? || ActiveSupport::JSON.decode(response.body)) Chris@1295: end Chris@1295: end Chris@1295: Chris@1295: # Checks that the response is a valid XML string Chris@1295: def self.should_be_a_valid_xml_string Chris@1295: should "be a valid XML string" do Chris@1295: assert REXML::Document.new(response.body) Chris@1295: end Chris@1295: end Chris@1295: Chris@1295: def self.should_respond_with(status) Chris@1295: should "respond with #{status}" do Chris@1295: assert_response status chris@37: end chris@37: end chris@37: end chris@37: end Chris@1295: end chris@37: Chris@1295: # URL helpers do not work with config.threadsafe! Chris@1295: # https://github.com/rspec/rspec-rails/issues/476#issuecomment-4705454 Chris@1295: ActionView::TestCase::TestController.instance_eval do Chris@1295: helper Rails.application.routes.url_helpers Chris@1295: end Chris@1295: ActionView::TestCase::TestController.class_eval do Chris@1295: def _routes Chris@1295: Rails.application.routes Chris@1115: end Chris@0: end