Chris@441: # Redmine - project management software Chris@1115: # Copyright (C) 2006-2012 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@1115: Chris@0: # Transactional fixtures accelerate your tests by wrapping each test method Chris@0: # in a transaction that's rolled back on completion. This ensures that the Chris@0: # test database remains unchanged so your fixtures don't have to be reloaded Chris@0: # between every test method. Fewer database queries means faster tests. Chris@0: # Chris@0: # Read Mike Clark's excellent walkthrough at Chris@0: # http://clarkware.com/cgi/blosxom/2005/10/24#Rails10FastTesting Chris@0: # Chris@0: # Every Active Record database supports transactions except MyISAM tables Chris@0: # in MySQL. Turn off transactional fixtures in this case; however, if you Chris@0: # don't care one way or the other, switching from MyISAM to InnoDB tables Chris@0: # is recommended. Chris@0: self.use_transactional_fixtures = true Chris@0: Chris@0: # Instantiated fixtures are slow, but give you @david where otherwise you Chris@0: # would need people(:david). If you don't want to migrate your existing Chris@0: # test cases which use the @david style and don't mind the speed hit (each Chris@0: # instantiated fixtures translates to a database query per test method), Chris@0: # then set this back to true. Chris@0: self.use_instantiated_fixtures = false Chris@0: Chris@0: # Add more helper methods to be used by all tests here... Chris@909: 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@909: saved_settings = options.keys.inject({}) {|h, k| h[k] = Setting[k].is_a?(Symbol) ? Setting[k] : Setting[k].dup; h} 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@909: Chris@0: # Shoulda macros Chris@0: def self.should_render_404 Chris@0: should_respond_with :not_found chris@37: should_render_template 'common/error' Chris@0: end Chris@0: Chris@0: def self.should_have_before_filter(expected_method, options = {}) Chris@0: should_have_filter('before', expected_method, options) Chris@0: end Chris@0: Chris@0: def self.should_have_after_filter(expected_method, options = {}) Chris@0: should_have_filter('after', expected_method, options) Chris@0: end Chris@0: Chris@0: def self.should_have_filter(filter_type, expected_method, options) Chris@0: description = "have #{filter_type}_filter :#{expected_method}" Chris@0: description << " with #{options.inspect}" unless options.empty? Chris@0: Chris@0: should description do Chris@0: klass = "action_controller/filters/#{filter_type}_filter".classify.constantize Chris@0: expected = klass.new(:filter, expected_method.to_sym, options) Chris@0: assert_equal 1, @controller.class.filter_chain.select { |filter| Chris@0: filter.method == expected.method && filter.kind == expected.kind && Chris@0: filter.options == expected.options && filter.class == expected.class Chris@0: }.size Chris@0: end Chris@0: end Chris@0: chris@37: # Test that a request allows the three types of API authentication chris@37: # chris@37: # * HTTP Basic with username and password chris@37: # * HTTP Basic with an api key for the username chris@37: # * Key based with the key=X parameter chris@37: # chris@37: # @param [Symbol] http_method the HTTP method for request (:get, :post, :put, :delete) chris@37: # @param [String] url the request url chris@37: # @param [optional, Hash] parameters additional request parameters chris@37: # @param [optional, Hash] options additional options chris@37: # @option options [Symbol] :success_code Successful response code (:success) chris@37: # @option options [Symbol] :failure_code Failure response code (:unauthorized) chris@37: def self.should_allow_api_authentication(http_method, url, parameters={}, options={}) chris@37: should_allow_http_basic_auth_with_username_and_password(http_method, url, parameters, options) chris@37: should_allow_http_basic_auth_with_key(http_method, url, parameters, options) chris@37: should_allow_key_based_auth(http_method, url, parameters, options) chris@37: end chris@37: chris@37: # Test that a request allows the username and password for HTTP BASIC chris@37: # chris@37: # @param [Symbol] http_method the HTTP method for request (:get, :post, :put, :delete) chris@37: # @param [String] url the request url chris@37: # @param [optional, Hash] parameters additional request parameters chris@37: # @param [optional, Hash] options additional options chris@37: # @option options [Symbol] :success_code Successful response code (:success) chris@37: # @option options [Symbol] :failure_code Failure response code (:unauthorized) chris@37: def self.should_allow_http_basic_auth_with_username_and_password(http_method, url, parameters={}, options={}) chris@37: success_code = options[:success_code] || :success chris@37: failure_code = options[:failure_code] || :unauthorized Chris@909: chris@37: context "should allow http basic auth using a username and password for #{http_method} #{url}" do chris@37: context "with a valid HTTP authentication" do chris@37: setup do Chris@1115: @user = User.generate! do |user| Chris@1115: user.admin = true Chris@1115: user.password = 'my_password' Chris@1115: end Chris@1115: send(http_method, url, parameters, credentials(@user.login, 'my_password')) chris@37: end Chris@909: chris@37: should_respond_with success_code chris@37: should_respond_with_content_type_based_on_url(url) chris@37: should "login as the user" do chris@37: assert_equal @user, User.current chris@37: end chris@37: end chris@37: chris@37: context "with an invalid HTTP authentication" do chris@37: setup do Chris@1115: @user = User.generate! Chris@1115: send(http_method, url, parameters, credentials(@user.login, 'wrong_password')) chris@37: end Chris@909: chris@37: should_respond_with failure_code chris@37: should_respond_with_content_type_based_on_url(url) chris@37: should "not login as the user" do chris@37: assert_equal User.anonymous, User.current chris@37: end chris@37: end Chris@909: chris@37: context "without credentials" do chris@37: setup do Chris@1115: send(http_method, url, parameters) chris@37: end chris@37: chris@37: should_respond_with failure_code chris@37: should_respond_with_content_type_based_on_url(url) chris@37: should "include_www_authenticate_header" do chris@37: assert @controller.response.headers.has_key?('WWW-Authenticate') chris@37: end chris@37: end chris@37: end chris@37: end chris@37: chris@37: # Test that a request allows the API key with HTTP BASIC chris@37: # chris@37: # @param [Symbol] http_method the HTTP method for request (:get, :post, :put, :delete) chris@37: # @param [String] url the request url chris@37: # @param [optional, Hash] parameters additional request parameters chris@37: # @param [optional, Hash] options additional options chris@37: # @option options [Symbol] :success_code Successful response code (:success) chris@37: # @option options [Symbol] :failure_code Failure response code (:unauthorized) chris@37: def self.should_allow_http_basic_auth_with_key(http_method, url, parameters={}, options={}) chris@37: success_code = options[:success_code] || :success chris@37: failure_code = options[:failure_code] || :unauthorized chris@37: chris@37: context "should allow http basic auth with a key for #{http_method} #{url}" do chris@37: context "with a valid HTTP authentication using the API token" do chris@37: setup do Chris@1115: @user = User.generate! do |user| Chris@1115: user.admin = true Chris@1115: end Chris@1115: @token = Token.create!(:user => @user, :action => 'api') Chris@1115: send(http_method, url, parameters, credentials(@token.value, 'X')) chris@37: end chris@37: should_respond_with success_code chris@37: should_respond_with_content_type_based_on_url(url) chris@37: should_be_a_valid_response_string_based_on_url(url) chris@37: should "login as the user" do chris@37: assert_equal @user, User.current chris@37: end chris@37: end chris@37: chris@37: context "with an invalid HTTP authentication" do chris@37: setup do Chris@1115: @user = User.generate! Chris@1115: @token = Token.create!(:user => @user, :action => 'feeds') Chris@1115: send(http_method, url, parameters, credentials(@token.value, 'X')) chris@37: end chris@37: should_respond_with failure_code chris@37: should_respond_with_content_type_based_on_url(url) chris@37: should "not login as the user" do chris@37: assert_equal User.anonymous, User.current chris@37: end chris@37: end chris@37: end chris@37: end Chris@909: chris@37: # Test that a request allows full key authentication chris@37: # chris@37: # @param [Symbol] http_method the HTTP method for request (:get, :post, :put, :delete) chris@37: # @param [String] url the request url, without the key=ZXY parameter chris@37: # @param [optional, Hash] parameters additional request parameters chris@37: # @param [optional, Hash] options additional options chris@37: # @option options [Symbol] :success_code Successful response code (:success) chris@37: # @option options [Symbol] :failure_code Failure response code (:unauthorized) chris@37: def self.should_allow_key_based_auth(http_method, url, parameters={}, options={}) chris@37: success_code = options[:success_code] || :success chris@37: failure_code = options[:failure_code] || :unauthorized chris@37: chris@37: context "should allow key based auth using key=X for #{http_method} #{url}" do chris@37: context "with a valid api token" do chris@37: setup do Chris@1115: @user = User.generate! do |user| Chris@1115: user.admin = true Chris@1115: end Chris@1115: @token = Token.create!(:user => @user, :action => 'api') chris@37: # Simple url parse to add on ?key= or &key= chris@37: request_url = if url.match(/\?/) chris@37: url + "&key=#{@token.value}" chris@37: else chris@37: url + "?key=#{@token.value}" chris@37: end chris@37: send(http_method, request_url, parameters) chris@37: end chris@37: should_respond_with success_code chris@37: should_respond_with_content_type_based_on_url(url) chris@37: should_be_a_valid_response_string_based_on_url(url) chris@37: should "login as the user" do chris@37: assert_equal @user, User.current chris@37: end chris@37: end chris@37: chris@37: context "with an invalid api token" do chris@37: setup do Chris@1115: @user = User.generate! do |user| Chris@1115: user.admin = true Chris@1115: end Chris@1115: @token = Token.create!(:user => @user, :action => 'feeds') chris@37: # Simple url parse to add on ?key= or &key= chris@37: request_url = if url.match(/\?/) chris@37: url + "&key=#{@token.value}" chris@37: else chris@37: url + "?key=#{@token.value}" chris@37: end chris@37: send(http_method, request_url, parameters) chris@37: end chris@37: should_respond_with failure_code chris@37: should_respond_with_content_type_based_on_url(url) chris@37: should "not login as the user" do chris@37: assert_equal User.anonymous, User.current chris@37: end chris@37: end chris@37: end Chris@909: Chris@119: context "should allow key based auth using X-Redmine-API-Key header for #{http_method} #{url}" do Chris@119: setup do Chris@1115: @user = User.generate! do |user| Chris@1115: user.admin = true Chris@1115: end Chris@1115: @token = Token.create!(:user => @user, :action => 'api') Chris@119: send(http_method, url, parameters, {'X-Redmine-API-Key' => @token.value.to_s}) Chris@119: end Chris@119: should_respond_with success_code Chris@119: should_respond_with_content_type_based_on_url(url) Chris@119: should_be_a_valid_response_string_based_on_url(url) Chris@119: should "login as the user" do Chris@119: assert_equal @user, User.current Chris@119: end Chris@119: end chris@37: end chris@37: chris@37: # Uses should_respond_with_content_type based on what's in the url: chris@37: # chris@37: # '/project/issues.xml' => should_respond_with_content_type :xml chris@37: # '/project/issues.json' => should_respond_with_content_type :json chris@37: # chris@37: # @param [String] url Request chris@37: def self.should_respond_with_content_type_based_on_url(url) chris@37: case chris@37: when url.match(/xml/i) Chris@1115: should "respond with XML" do Chris@1115: assert_equal 'application/xml', @response.content_type Chris@1115: end chris@37: when url.match(/json/i) Chris@1115: should "respond with JSON" do Chris@1115: assert_equal 'application/json', @response.content_type Chris@1115: end chris@37: else chris@37: raise "Unknown content type for should_respond_with_content_type_based_on_url: #{url}" chris@37: end chris@37: end chris@37: chris@37: # Uses the url to assert which format the response should be in chris@37: # chris@37: # '/project/issues.xml' => should_be_a_valid_xml_string chris@37: # '/project/issues.json' => should_be_a_valid_json_string chris@37: # chris@37: # @param [String] url Request chris@37: def self.should_be_a_valid_response_string_based_on_url(url) chris@37: case chris@37: when url.match(/xml/i) chris@37: should_be_a_valid_xml_string chris@37: when url.match(/json/i) chris@37: should_be_a_valid_json_string chris@37: else chris@37: raise "Unknown content type for should_be_a_valid_response_based_on_url: #{url}" chris@37: end chris@37: end Chris@909: chris@37: # Checks that the response is a valid JSON string chris@37: def self.should_be_a_valid_json_string chris@37: should "be a valid JSON string (or empty)" do Chris@441: assert(response.body.blank? || ActiveSupport::JSON.decode(response.body)) chris@37: end chris@37: end chris@37: chris@37: # Checks that the response is a valid XML string chris@37: def self.should_be_a_valid_xml_string chris@37: should "be a valid XML string" do chris@37: assert REXML::Document.new(response.body) chris@37: end chris@37: end Chris@909: Chris@1115: def self.should_respond_with(status) Chris@1115: should "respond with #{status}" do Chris@1115: assert_response status Chris@1115: end Chris@1115: end Chris@0: end chris@37: chris@37: # Simple module to "namespace" all of the API tests chris@37: module ApiTest chris@37: end