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