Chris@909: # Redmine - project management software Chris@909: # Copyright (C) 2006-2011 Jean-Philippe Lang Chris@909: # Chris@909: # This program is free software; you can redistribute it and/or Chris@909: # modify it under the terms of the GNU General Public License Chris@909: # as published by the Free Software Foundation; either version 2 Chris@909: # of the License, or (at your option) any later version. Chris@909: # Chris@909: # This program is distributed in the hope that it will be useful, Chris@909: # but WITHOUT ANY WARRANTY; without even the implied warranty of Chris@909: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Chris@909: # GNU General Public License for more details. Chris@909: # Chris@909: # You should have received a copy of the GNU General Public License Chris@909: # along with this program; if not, write to the Free Software Chris@909: # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Chris@909: Chris@909: ENV["RAILS_ENV"] = "test" Chris@909: require File.expand_path(File.dirname(__FILE__) + "/../config/environment") Chris@909: require 'test_help' Chris@909: require File.expand_path(File.dirname(__FILE__) + '/helper_testcase') Chris@909: require Rails.root.join('test', 'mocks', 'open_id_authentication_mock.rb').to_s Chris@909: Chris@909: require File.expand_path(File.dirname(__FILE__) + '/object_daddy_helpers') Chris@909: include ObjectDaddyHelpers Chris@909: Chris@909: class ActiveSupport::TestCase Chris@909: # Transactional fixtures accelerate your tests by wrapping each test method Chris@909: # in a transaction that's rolled back on completion. This ensures that the Chris@909: # test database remains unchanged so your fixtures don't have to be reloaded Chris@909: # between every test method. Fewer database queries means faster tests. Chris@909: # Chris@909: # Read Mike Clark's excellent walkthrough at Chris@909: # http://clarkware.com/cgi/blosxom/2005/10/24#Rails10FastTesting Chris@909: # Chris@909: # Every Active Record database supports transactions except MyISAM tables Chris@909: # in MySQL. Turn off transactional fixtures in this case; however, if you Chris@909: # don't care one way or the other, switching from MyISAM to InnoDB tables Chris@909: # is recommended. Chris@909: self.use_transactional_fixtures = true Chris@909: Chris@909: # Instantiated fixtures are slow, but give you @david where otherwise you Chris@909: # would need people(:david). If you don't want to migrate your existing Chris@909: # test cases which use the @david style and don't mind the speed hit (each Chris@909: # instantiated fixtures translates to a database query per test method), Chris@909: # then set this back to true. Chris@909: self.use_instantiated_fixtures = false Chris@909: Chris@909: # Add more helper methods to be used by all tests here... Chris@909: Chris@909: def log_user(login, password) Chris@909: User.anonymous Chris@909: get "/login" Chris@909: assert_equal nil, session[:user_id] Chris@909: assert_response :success Chris@909: assert_template "account/login" Chris@909: post "/login", :username => login, :password => password Chris@909: assert_equal login, User.find(session[:user_id]).login Chris@909: end Chris@909: Chris@909: def uploaded_test_file(name, mime) Chris@909: ActionController::TestUploadedFile.new( Chris@909: ActiveSupport::TestCase.fixture_path + "/files/#{name}", mime, true) Chris@909: end Chris@909: Chris@909: # Mock out a file Chris@909: def self.mock_file Chris@909: file = 'a_file.png' Chris@909: file.stubs(:size).returns(32) Chris@909: file.stubs(:original_filename).returns('a_file.png') Chris@909: file.stubs(:content_type).returns('image/png') Chris@909: file.stubs(:read).returns(false) Chris@909: file Chris@909: end Chris@909: Chris@909: def mock_file Chris@909: self.class.mock_file Chris@909: end Chris@909: 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@909: # Use a temporary directory for attachment related tests Chris@909: 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@909: end Chris@909: Chris@909: 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@909: options.each {|k, v| Setting[k] = v} Chris@909: yield Chris@909: ensure Chris@909: saved_settings.each {|k, v| Setting[k] = v} if saved_settings Chris@909: end Chris@909: Chris@909: def change_user_password(login, new_password) Chris@909: user = User.first(:conditions => {:login => login}) Chris@909: user.password, user.password_confirmation = new_password, new_password Chris@909: user.save! Chris@909: end Chris@909: Chris@909: def self.ldap_configured? Chris@909: @test_ldap = Net::LDAP.new(:host => '127.0.0.1', :port => 389) Chris@909: return @test_ldap.bind Chris@909: rescue Exception => e Chris@909: # LDAP is not listening Chris@909: return nil Chris@909: end Chris@909: Chris@909: # Returns the path to the test +vendor+ repository Chris@909: def self.repository_path(vendor) Chris@909: Rails.root.join("tmp/test/#{vendor.downcase}_repository").to_s Chris@909: end Chris@909: Chris@909: # Returns the url of the subversion test repository Chris@909: def self.subversion_repository_url Chris@909: path = repository_path('subversion') Chris@909: path = '/' + path unless path.starts_with?('/') Chris@909: "file://#{path}" Chris@909: end Chris@909: Chris@909: # Returns true if the +vendor+ test repository is configured Chris@909: def self.repository_configured?(vendor) Chris@909: File.directory?(repository_path(vendor)) Chris@909: end Chris@909: Chris@909: def assert_error_tag(options={}) Chris@909: assert_tag({:attributes => { :id => 'errorExplanation' }}.merge(options)) Chris@909: end Chris@909: Chris@909: def assert_include(expected, s) Chris@909: assert s.include?(expected), "\"#{expected}\" not found in \"#{s}\"" Chris@909: end Chris@909: Chris@909: # Shoulda macros Chris@909: def self.should_render_404 Chris@909: should_respond_with :not_found Chris@909: should_render_template 'common/error' Chris@909: end Chris@909: Chris@909: def self.should_have_before_filter(expected_method, options = {}) Chris@909: should_have_filter('before', expected_method, options) Chris@909: end Chris@909: Chris@909: def self.should_have_after_filter(expected_method, options = {}) Chris@909: should_have_filter('after', expected_method, options) Chris@909: end Chris@909: Chris@909: def self.should_have_filter(filter_type, expected_method, options) Chris@909: description = "have #{filter_type}_filter :#{expected_method}" Chris@909: description << " with #{options.inspect}" unless options.empty? Chris@909: Chris@909: should description do Chris@909: klass = "action_controller/filters/#{filter_type}_filter".classify.constantize Chris@909: expected = klass.new(:filter, expected_method.to_sym, options) Chris@909: assert_equal 1, @controller.class.filter_chain.select { |filter| Chris@909: filter.method == expected.method && filter.kind == expected.kind && Chris@909: filter.options == expected.options && filter.class == expected.class Chris@909: }.size Chris@909: end Chris@909: end Chris@909: Chris@909: def self.should_show_the_old_and_new_values_for(prop_key, model, &block) Chris@909: context "" do Chris@909: setup do Chris@909: if block_given? Chris@909: instance_eval &block Chris@909: else Chris@909: @old_value = model.generate! Chris@909: @new_value = model.generate! Chris@909: end Chris@909: end Chris@909: Chris@909: should "use the new value's name" do Chris@909: @detail = JournalDetail.generate!(:property => 'attr', Chris@909: :old_value => @old_value.id, Chris@909: :value => @new_value.id, Chris@909: :prop_key => prop_key) Chris@909: Chris@909: assert_match @new_value.name, show_detail(@detail, true) Chris@909: end Chris@909: Chris@909: should "use the old value's name" do Chris@909: @detail = JournalDetail.generate!(:property => 'attr', Chris@909: :old_value => @old_value.id, Chris@909: :value => @new_value.id, Chris@909: :prop_key => prop_key) Chris@909: Chris@909: assert_match @old_value.name, show_detail(@detail, true) Chris@909: end Chris@909: end Chris@909: end Chris@909: Chris@909: def self.should_create_a_new_user(&block) Chris@909: should "create a new user" do Chris@909: user = instance_eval &block Chris@909: assert user Chris@909: assert_kind_of User, user Chris@909: assert !user.new_record? Chris@909: end Chris@909: end Chris@909: Chris@909: # Test that a request allows the three types of API authentication Chris@909: # Chris@909: # * HTTP Basic with username and password Chris@909: # * HTTP Basic with an api key for the username Chris@909: # * Key based with the key=X parameter Chris@909: # Chris@909: # @param [Symbol] http_method the HTTP method for request (:get, :post, :put, :delete) Chris@909: # @param [String] url the request url Chris@909: # @param [optional, Hash] parameters additional request parameters Chris@909: # @param [optional, Hash] options additional options Chris@909: # @option options [Symbol] :success_code Successful response code (:success) Chris@909: # @option options [Symbol] :failure_code Failure response code (:unauthorized) Chris@909: def self.should_allow_api_authentication(http_method, url, parameters={}, options={}) Chris@909: should_allow_http_basic_auth_with_username_and_password(http_method, url, parameters, options) Chris@909: should_allow_http_basic_auth_with_key(http_method, url, parameters, options) Chris@909: should_allow_key_based_auth(http_method, url, parameters, options) Chris@909: end Chris@909: Chris@909: # Test that a request allows the username and password for HTTP BASIC Chris@909: # Chris@909: # @param [Symbol] http_method the HTTP method for request (:get, :post, :put, :delete) Chris@909: # @param [String] url the request url Chris@909: # @param [optional, Hash] parameters additional request parameters Chris@909: # @param [optional, Hash] options additional options Chris@909: # @option options [Symbol] :success_code Successful response code (:success) Chris@909: # @option options [Symbol] :failure_code Failure response code (:unauthorized) Chris@909: def self.should_allow_http_basic_auth_with_username_and_password(http_method, url, parameters={}, options={}) Chris@909: success_code = options[:success_code] || :success Chris@909: failure_code = options[:failure_code] || :unauthorized Chris@909: Chris@909: context "should allow http basic auth using a username and password for #{http_method} #{url}" do Chris@909: context "with a valid HTTP authentication" do Chris@909: setup do Chris@909: @user = User.generate_with_protected!(:password => 'my_password', :password_confirmation => 'my_password', :admin => true) # Admin so they can access the project Chris@909: @authorization = ActionController::HttpAuthentication::Basic.encode_credentials(@user.login, 'my_password') Chris@909: send(http_method, url, parameters, {:authorization => @authorization}) Chris@909: end Chris@909: Chris@909: should_respond_with success_code Chris@909: should_respond_with_content_type_based_on_url(url) Chris@909: should "login as the user" do Chris@909: assert_equal @user, User.current Chris@909: end Chris@909: end Chris@909: Chris@909: context "with an invalid HTTP authentication" do Chris@909: setup do Chris@909: @user = User.generate_with_protected! Chris@909: @authorization = ActionController::HttpAuthentication::Basic.encode_credentials(@user.login, 'wrong_password') Chris@909: send(http_method, url, parameters, {:authorization => @authorization}) Chris@909: end Chris@909: Chris@909: should_respond_with failure_code Chris@909: should_respond_with_content_type_based_on_url(url) Chris@909: should "not login as the user" do Chris@909: assert_equal User.anonymous, User.current Chris@909: end Chris@909: end Chris@909: Chris@909: context "without credentials" do Chris@909: setup do Chris@909: send(http_method, url, parameters, {:authorization => ''}) Chris@909: end Chris@909: Chris@909: should_respond_with failure_code Chris@909: should_respond_with_content_type_based_on_url(url) Chris@909: should "include_www_authenticate_header" do Chris@909: assert @controller.response.headers.has_key?('WWW-Authenticate') Chris@909: end Chris@909: end Chris@909: end Chris@909: Chris@909: end Chris@909: Chris@909: # Test that a request allows the API key with HTTP BASIC Chris@909: # Chris@909: # @param [Symbol] http_method the HTTP method for request (:get, :post, :put, :delete) Chris@909: # @param [String] url the request url Chris@909: # @param [optional, Hash] parameters additional request parameters Chris@909: # @param [optional, Hash] options additional options Chris@909: # @option options [Symbol] :success_code Successful response code (:success) Chris@909: # @option options [Symbol] :failure_code Failure response code (:unauthorized) Chris@909: def self.should_allow_http_basic_auth_with_key(http_method, url, parameters={}, options={}) Chris@909: success_code = options[:success_code] || :success Chris@909: failure_code = options[:failure_code] || :unauthorized Chris@909: Chris@909: context "should allow http basic auth with a key for #{http_method} #{url}" do Chris@909: context "with a valid HTTP authentication using the API token" do Chris@909: setup do Chris@909: @user = User.generate_with_protected!(:admin => true) Chris@909: @token = Token.generate!(:user => @user, :action => 'api') Chris@909: @authorization = ActionController::HttpAuthentication::Basic.encode_credentials(@token.value, 'X') Chris@909: send(http_method, url, parameters, {:authorization => @authorization}) Chris@909: end Chris@909: Chris@909: should_respond_with success_code Chris@909: should_respond_with_content_type_based_on_url(url) Chris@909: should_be_a_valid_response_string_based_on_url(url) Chris@909: should "login as the user" do Chris@909: assert_equal @user, User.current Chris@909: end Chris@909: end Chris@909: Chris@909: context "with an invalid HTTP authentication" do Chris@909: setup do Chris@909: @user = User.generate_with_protected! Chris@909: @token = Token.generate!(:user => @user, :action => 'feeds') Chris@909: @authorization = ActionController::HttpAuthentication::Basic.encode_credentials(@token.value, 'X') Chris@909: send(http_method, url, parameters, {:authorization => @authorization}) Chris@909: end Chris@909: Chris@909: should_respond_with failure_code Chris@909: should_respond_with_content_type_based_on_url(url) Chris@909: should "not login as the user" do Chris@909: assert_equal User.anonymous, User.current Chris@909: end Chris@909: end Chris@909: end Chris@909: end Chris@909: Chris@909: # Test that a request allows full key authentication Chris@909: # Chris@909: # @param [Symbol] http_method the HTTP method for request (:get, :post, :put, :delete) Chris@909: # @param [String] url the request url, without the key=ZXY parameter Chris@909: # @param [optional, Hash] parameters additional request parameters Chris@909: # @param [optional, Hash] options additional options Chris@909: # @option options [Symbol] :success_code Successful response code (:success) Chris@909: # @option options [Symbol] :failure_code Failure response code (:unauthorized) Chris@909: def self.should_allow_key_based_auth(http_method, url, parameters={}, options={}) Chris@909: success_code = options[:success_code] || :success Chris@909: failure_code = options[:failure_code] || :unauthorized Chris@909: Chris@909: context "should allow key based auth using key=X for #{http_method} #{url}" do Chris@909: context "with a valid api token" do Chris@909: setup do Chris@909: @user = User.generate_with_protected!(:admin => true) Chris@909: @token = Token.generate!(:user => @user, :action => 'api') Chris@909: # Simple url parse to add on ?key= or &key= Chris@909: request_url = if url.match(/\?/) Chris@909: url + "&key=#{@token.value}" Chris@909: else Chris@909: url + "?key=#{@token.value}" Chris@909: end Chris@909: send(http_method, request_url, parameters) Chris@909: end Chris@909: Chris@909: should_respond_with success_code Chris@909: should_respond_with_content_type_based_on_url(url) Chris@909: should_be_a_valid_response_string_based_on_url(url) Chris@909: should "login as the user" do Chris@909: assert_equal @user, User.current Chris@909: end Chris@909: end Chris@909: Chris@909: context "with an invalid api token" do Chris@909: setup do Chris@909: @user = User.generate_with_protected! Chris@909: @token = Token.generate!(:user => @user, :action => 'feeds') Chris@909: # Simple url parse to add on ?key= or &key= Chris@909: request_url = if url.match(/\?/) Chris@909: url + "&key=#{@token.value}" Chris@909: else Chris@909: url + "?key=#{@token.value}" Chris@909: end Chris@909: send(http_method, request_url, parameters) Chris@909: end Chris@909: Chris@909: should_respond_with failure_code Chris@909: should_respond_with_content_type_based_on_url(url) Chris@909: should "not login as the user" do Chris@909: assert_equal User.anonymous, User.current Chris@909: end Chris@909: end Chris@909: end Chris@909: Chris@909: context "should allow key based auth using X-Redmine-API-Key header for #{http_method} #{url}" do Chris@909: setup do Chris@909: @user = User.generate_with_protected!(:admin => true) Chris@909: @token = Token.generate!(:user => @user, :action => 'api') Chris@909: send(http_method, url, parameters, {'X-Redmine-API-Key' => @token.value.to_s}) Chris@909: end Chris@909: Chris@909: should_respond_with success_code Chris@909: should_respond_with_content_type_based_on_url(url) Chris@909: should_be_a_valid_response_string_based_on_url(url) Chris@909: should "login as the user" do Chris@909: assert_equal @user, User.current Chris@909: end Chris@909: end Chris@909: end Chris@909: Chris@909: # Uses should_respond_with_content_type based on what's in the url: Chris@909: # Chris@909: # '/project/issues.xml' => should_respond_with_content_type :xml Chris@909: # '/project/issues.json' => should_respond_with_content_type :json Chris@909: # Chris@909: # @param [String] url Request Chris@909: def self.should_respond_with_content_type_based_on_url(url) Chris@909: case Chris@909: when url.match(/xml/i) Chris@909: should_respond_with_content_type :xml Chris@909: when url.match(/json/i) Chris@909: should_respond_with_content_type :json Chris@909: else Chris@909: raise "Unknown content type for should_respond_with_content_type_based_on_url: #{url}" Chris@909: end Chris@909: Chris@909: end Chris@909: Chris@909: # Uses the url to assert which format the response should be in Chris@909: # Chris@909: # '/project/issues.xml' => should_be_a_valid_xml_string Chris@909: # '/project/issues.json' => should_be_a_valid_json_string Chris@909: # Chris@909: # @param [String] url Request Chris@909: def self.should_be_a_valid_response_string_based_on_url(url) Chris@909: case Chris@909: when url.match(/xml/i) Chris@909: should_be_a_valid_xml_string Chris@909: when url.match(/json/i) Chris@909: should_be_a_valid_json_string Chris@909: else Chris@909: raise "Unknown content type for should_be_a_valid_response_based_on_url: #{url}" Chris@909: end Chris@909: Chris@909: end Chris@909: Chris@909: # Checks that the response is a valid JSON string Chris@909: def self.should_be_a_valid_json_string Chris@909: should "be a valid JSON string (or empty)" do Chris@909: assert(response.body.blank? || ActiveSupport::JSON.decode(response.body)) Chris@909: end Chris@909: end Chris@909: Chris@909: # Checks that the response is a valid XML string Chris@909: def self.should_be_a_valid_xml_string Chris@909: should "be a valid XML string" do Chris@909: assert REXML::Document.new(response.body) Chris@909: end Chris@909: end Chris@909: Chris@909: end Chris@909: Chris@909: # Simple module to "namespace" all of the API tests Chris@909: module ApiTest Chris@909: end