annotate test/test_helper.rb @ 1459:cf78a7ade302 luisf

Merge from branch "bug_794"
author luisf <luis.figueira@eecs.qmul.ac.uk>
date Mon, 11 Nov 2013 18:25:50 +0000
parents bb32da3bea34
children 4f746d8966dd fb9a13467253
rev   line source
Chris@441 1 # Redmine - project management software
Chris@1115 2 # Copyright (C) 2006-2012 Jean-Philippe Lang
Chris@0 3 #
Chris@0 4 # This program is free software; you can redistribute it and/or
Chris@0 5 # modify it under the terms of the GNU General Public License
Chris@0 6 # as published by the Free Software Foundation; either version 2
Chris@0 7 # of the License, or (at your option) any later version.
Chris@909 8 #
Chris@0 9 # This program is distributed in the hope that it will be useful,
Chris@0 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
Chris@0 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
Chris@0 12 # GNU General Public License for more details.
Chris@909 13 #
Chris@0 14 # You should have received a copy of the GNU General Public License
Chris@0 15 # along with this program; if not, write to the Free Software
Chris@0 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
Chris@0 17
Chris@1115 18 #require 'shoulda'
Chris@0 19 ENV["RAILS_ENV"] = "test"
Chris@0 20 require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
Chris@1115 21 require 'rails/test_help'
Chris@909 22 require Rails.root.join('test', 'mocks', 'open_id_authentication_mock.rb').to_s
Chris@0 23
Chris@1115 24 require File.expand_path(File.dirname(__FILE__) + '/object_helpers')
Chris@1115 25 include ObjectHelpers
Chris@0 26
Chris@0 27 class ActiveSupport::TestCase
Chris@1115 28 include ActionDispatch::TestProcess
Chris@1115 29
Chris@0 30 # Transactional fixtures accelerate your tests by wrapping each test method
Chris@0 31 # in a transaction that's rolled back on completion. This ensures that the
Chris@0 32 # test database remains unchanged so your fixtures don't have to be reloaded
Chris@0 33 # between every test method. Fewer database queries means faster tests.
Chris@0 34 #
Chris@0 35 # Read Mike Clark's excellent walkthrough at
Chris@0 36 # http://clarkware.com/cgi/blosxom/2005/10/24#Rails10FastTesting
Chris@0 37 #
Chris@0 38 # Every Active Record database supports transactions except MyISAM tables
Chris@0 39 # in MySQL. Turn off transactional fixtures in this case; however, if you
Chris@0 40 # don't care one way or the other, switching from MyISAM to InnoDB tables
Chris@0 41 # is recommended.
Chris@0 42 self.use_transactional_fixtures = true
Chris@0 43
Chris@0 44 # Instantiated fixtures are slow, but give you @david where otherwise you
Chris@0 45 # would need people(:david). If you don't want to migrate your existing
Chris@0 46 # test cases which use the @david style and don't mind the speed hit (each
Chris@0 47 # instantiated fixtures translates to a database query per test method),
Chris@0 48 # then set this back to true.
Chris@0 49 self.use_instantiated_fixtures = false
Chris@0 50
Chris@0 51 # Add more helper methods to be used by all tests here...
Chris@909 52
Chris@0 53 def log_user(login, password)
Chris@0 54 User.anonymous
Chris@0 55 get "/login"
Chris@0 56 assert_equal nil, session[:user_id]
Chris@0 57 assert_response :success
Chris@0 58 assert_template "account/login"
Chris@0 59 post "/login", :username => login, :password => password
Chris@0 60 assert_equal login, User.find(session[:user_id]).login
Chris@0 61 end
Chris@909 62
Chris@0 63 def uploaded_test_file(name, mime)
Chris@1115 64 fixture_file_upload("files/#{name}", mime, true)
Chris@1115 65 end
Chris@1115 66
Chris@1115 67 def credentials(user, password=nil)
Chris@1115 68 {'HTTP_AUTHORIZATION' => ActionController::HttpAuthentication::Basic.encode_credentials(user, password || user)}
Chris@0 69 end
Chris@0 70
Chris@0 71 # Mock out a file
Chris@14 72 def self.mock_file
Chris@0 73 file = 'a_file.png'
Chris@0 74 file.stubs(:size).returns(32)
Chris@0 75 file.stubs(:original_filename).returns('a_file.png')
Chris@0 76 file.stubs(:content_type).returns('image/png')
Chris@0 77 file.stubs(:read).returns(false)
Chris@0 78 file
Chris@0 79 end
Chris@14 80
Chris@14 81 def mock_file
Chris@14 82 self.class.mock_file
Chris@14 83 end
Chris@14 84
Chris@909 85 def mock_file_with_options(options={})
Chris@909 86 file = ''
Chris@909 87 file.stubs(:size).returns(32)
Chris@909 88 original_filename = options[:original_filename] || nil
Chris@909 89 file.stubs(:original_filename).returns(original_filename)
Chris@909 90 content_type = options[:content_type] || nil
Chris@909 91 file.stubs(:content_type).returns(content_type)
Chris@909 92 file.stubs(:read).returns(false)
Chris@909 93 file
Chris@909 94 end
Chris@909 95
Chris@0 96 # Use a temporary directory for attachment related tests
Chris@0 97 def set_tmp_attachments_directory
Chris@909 98 Dir.mkdir "#{Rails.root}/tmp/test" unless File.directory?("#{Rails.root}/tmp/test")
Chris@909 99 unless File.directory?("#{Rails.root}/tmp/test/attachments")
Chris@909 100 Dir.mkdir "#{Rails.root}/tmp/test/attachments"
Chris@909 101 end
Chris@909 102 Attachment.storage_path = "#{Rails.root}/tmp/test/attachments"
Chris@0 103 end
Chris@909 104
Chris@1115 105 def set_fixtures_attachments_directory
Chris@1115 106 Attachment.storage_path = "#{Rails.root}/test/fixtures/files"
Chris@1115 107 end
Chris@1115 108
Chris@0 109 def with_settings(options, &block)
Chris@909 110 saved_settings = options.keys.inject({}) {|h, k| h[k] = Setting[k].is_a?(Symbol) ? Setting[k] : Setting[k].dup; h}
Chris@0 111 options.each {|k, v| Setting[k] = v}
Chris@0 112 yield
Chris@441 113 ensure
Chris@909 114 saved_settings.each {|k, v| Setting[k] = v} if saved_settings
Chris@0 115 end
Chris@0 116
Chris@1115 117 # Yields the block with user as the current user
Chris@1115 118 def with_current_user(user, &block)
Chris@1115 119 saved_user = User.current
Chris@1115 120 User.current = user
Chris@1115 121 yield
Chris@1115 122 ensure
Chris@1115 123 User.current = saved_user
Chris@1115 124 end
Chris@1115 125
Chris@14 126 def change_user_password(login, new_password)
Chris@14 127 user = User.first(:conditions => {:login => login})
Chris@14 128 user.password, user.password_confirmation = new_password, new_password
Chris@14 129 user.save!
Chris@14 130 end
Chris@14 131
Chris@0 132 def self.ldap_configured?
Chris@0 133 @test_ldap = Net::LDAP.new(:host => '127.0.0.1', :port => 389)
Chris@0 134 return @test_ldap.bind
Chris@0 135 rescue Exception => e
Chris@0 136 # LDAP is not listening
Chris@0 137 return nil
Chris@0 138 end
Chris@909 139
Chris@1115 140 def self.convert_installed?
Chris@1115 141 Redmine::Thumbnail.convert_available?
Chris@1115 142 end
Chris@1115 143
Chris@0 144 # Returns the path to the test +vendor+ repository
Chris@0 145 def self.repository_path(vendor)
Chris@909 146 Rails.root.join("tmp/test/#{vendor.downcase}_repository").to_s
Chris@0 147 end
Chris@909 148
Chris@441 149 # Returns the url of the subversion test repository
Chris@441 150 def self.subversion_repository_url
Chris@441 151 path = repository_path('subversion')
Chris@441 152 path = '/' + path unless path.starts_with?('/')
Chris@441 153 "file://#{path}"
Chris@441 154 end
Chris@909 155
Chris@0 156 # Returns true if the +vendor+ test repository is configured
Chris@0 157 def self.repository_configured?(vendor)
Chris@0 158 File.directory?(repository_path(vendor))
Chris@0 159 end
Chris@909 160
Chris@1115 161 def repository_path_hash(arr)
Chris@1115 162 hs = {}
Chris@1115 163 hs[:path] = arr.join("/")
Chris@1115 164 hs[:param] = arr.join("/")
Chris@1115 165 hs
Chris@1115 166 end
Chris@1115 167
Chris@1115 168 def assert_save(object)
Chris@1115 169 saved = object.save
Chris@1115 170 message = "#{object.class} could not be saved"
Chris@1115 171 errors = object.errors.full_messages.map {|m| "- #{m}"}
Chris@1115 172 message << ":\n#{errors.join("\n")}" if errors.any?
Chris@1115 173 assert_equal true, saved, message
Chris@1115 174 end
Chris@1115 175
chris@37 176 def assert_error_tag(options={})
Chris@119 177 assert_tag({:attributes => { :id => 'errorExplanation' }}.merge(options))
chris@37 178 end
Chris@0 179
Chris@1115 180 def assert_include(expected, s, message=nil)
Chris@1115 181 assert s.include?(expected), (message || "\"#{expected}\" not found in \"#{s}\"")
Chris@1115 182 end
Chris@1115 183
Chris@1115 184 def assert_not_include(expected, s)
Chris@1115 185 assert !s.include?(expected), "\"#{expected}\" found in \"#{s}\""
Chris@1115 186 end
Chris@1115 187
Chris@1115 188 def assert_select_in(text, *args, &block)
Chris@1115 189 d = HTML::Document.new(CGI::unescapeHTML(String.new(text))).root
Chris@1115 190 assert_select(d, *args, &block)
Chris@1115 191 end
Chris@1115 192
Chris@1115 193 def assert_mail_body_match(expected, mail)
Chris@1115 194 if expected.is_a?(String)
Chris@1115 195 assert_include expected, mail_body(mail)
Chris@1115 196 else
Chris@1115 197 assert_match expected, mail_body(mail)
Chris@1115 198 end
Chris@1115 199 end
Chris@1115 200
Chris@1115 201 def assert_mail_body_no_match(expected, mail)
Chris@1115 202 if expected.is_a?(String)
Chris@1115 203 assert_not_include expected, mail_body(mail)
Chris@1115 204 else
Chris@1115 205 assert_no_match expected, mail_body(mail)
Chris@1115 206 end
Chris@1115 207 end
Chris@1115 208
Chris@1115 209 def mail_body(mail)
Chris@1115 210 mail.parts.first.body.encoded
Chris@909 211 end
Chris@909 212
Chris@0 213 # Shoulda macros
Chris@0 214 def self.should_render_404
Chris@0 215 should_respond_with :not_found
chris@37 216 should_render_template 'common/error'
Chris@0 217 end
Chris@0 218
Chris@0 219 def self.should_have_before_filter(expected_method, options = {})
Chris@0 220 should_have_filter('before', expected_method, options)
Chris@0 221 end
Chris@0 222
Chris@0 223 def self.should_have_after_filter(expected_method, options = {})
Chris@0 224 should_have_filter('after', expected_method, options)
Chris@0 225 end
Chris@0 226
Chris@0 227 def self.should_have_filter(filter_type, expected_method, options)
Chris@0 228 description = "have #{filter_type}_filter :#{expected_method}"
Chris@0 229 description << " with #{options.inspect}" unless options.empty?
Chris@0 230
Chris@0 231 should description do
Chris@0 232 klass = "action_controller/filters/#{filter_type}_filter".classify.constantize
Chris@0 233 expected = klass.new(:filter, expected_method.to_sym, options)
Chris@0 234 assert_equal 1, @controller.class.filter_chain.select { |filter|
Chris@0 235 filter.method == expected.method && filter.kind == expected.kind &&
Chris@0 236 filter.options == expected.options && filter.class == expected.class
Chris@0 237 }.size
Chris@0 238 end
Chris@0 239 end
Chris@0 240
chris@37 241 # Test that a request allows the three types of API authentication
chris@37 242 #
chris@37 243 # * HTTP Basic with username and password
chris@37 244 # * HTTP Basic with an api key for the username
chris@37 245 # * Key based with the key=X parameter
chris@37 246 #
chris@37 247 # @param [Symbol] http_method the HTTP method for request (:get, :post, :put, :delete)
chris@37 248 # @param [String] url the request url
chris@37 249 # @param [optional, Hash] parameters additional request parameters
chris@37 250 # @param [optional, Hash] options additional options
chris@37 251 # @option options [Symbol] :success_code Successful response code (:success)
chris@37 252 # @option options [Symbol] :failure_code Failure response code (:unauthorized)
chris@37 253 def self.should_allow_api_authentication(http_method, url, parameters={}, options={})
chris@37 254 should_allow_http_basic_auth_with_username_and_password(http_method, url, parameters, options)
chris@37 255 should_allow_http_basic_auth_with_key(http_method, url, parameters, options)
chris@37 256 should_allow_key_based_auth(http_method, url, parameters, options)
chris@37 257 end
chris@37 258
chris@37 259 # Test that a request allows the username and password for HTTP BASIC
chris@37 260 #
chris@37 261 # @param [Symbol] http_method the HTTP method for request (:get, :post, :put, :delete)
chris@37 262 # @param [String] url the request url
chris@37 263 # @param [optional, Hash] parameters additional request parameters
chris@37 264 # @param [optional, Hash] options additional options
chris@37 265 # @option options [Symbol] :success_code Successful response code (:success)
chris@37 266 # @option options [Symbol] :failure_code Failure response code (:unauthorized)
chris@37 267 def self.should_allow_http_basic_auth_with_username_and_password(http_method, url, parameters={}, options={})
chris@37 268 success_code = options[:success_code] || :success
chris@37 269 failure_code = options[:failure_code] || :unauthorized
Chris@909 270
chris@37 271 context "should allow http basic auth using a username and password for #{http_method} #{url}" do
chris@37 272 context "with a valid HTTP authentication" do
chris@37 273 setup do
Chris@1115 274 @user = User.generate! do |user|
Chris@1115 275 user.admin = true
Chris@1115 276 user.password = 'my_password'
Chris@1115 277 end
Chris@1115 278 send(http_method, url, parameters, credentials(@user.login, 'my_password'))
chris@37 279 end
Chris@909 280
chris@37 281 should_respond_with success_code
chris@37 282 should_respond_with_content_type_based_on_url(url)
chris@37 283 should "login as the user" do
chris@37 284 assert_equal @user, User.current
chris@37 285 end
chris@37 286 end
chris@37 287
chris@37 288 context "with an invalid HTTP authentication" do
chris@37 289 setup do
Chris@1115 290 @user = User.generate!
Chris@1115 291 send(http_method, url, parameters, credentials(@user.login, 'wrong_password'))
chris@37 292 end
Chris@909 293
chris@37 294 should_respond_with failure_code
chris@37 295 should_respond_with_content_type_based_on_url(url)
chris@37 296 should "not login as the user" do
chris@37 297 assert_equal User.anonymous, User.current
chris@37 298 end
chris@37 299 end
Chris@909 300
chris@37 301 context "without credentials" do
chris@37 302 setup do
Chris@1115 303 send(http_method, url, parameters)
chris@37 304 end
chris@37 305
chris@37 306 should_respond_with failure_code
chris@37 307 should_respond_with_content_type_based_on_url(url)
chris@37 308 should "include_www_authenticate_header" do
chris@37 309 assert @controller.response.headers.has_key?('WWW-Authenticate')
chris@37 310 end
chris@37 311 end
chris@37 312 end
chris@37 313 end
chris@37 314
chris@37 315 # Test that a request allows the API key with HTTP BASIC
chris@37 316 #
chris@37 317 # @param [Symbol] http_method the HTTP method for request (:get, :post, :put, :delete)
chris@37 318 # @param [String] url the request url
chris@37 319 # @param [optional, Hash] parameters additional request parameters
chris@37 320 # @param [optional, Hash] options additional options
chris@37 321 # @option options [Symbol] :success_code Successful response code (:success)
chris@37 322 # @option options [Symbol] :failure_code Failure response code (:unauthorized)
chris@37 323 def self.should_allow_http_basic_auth_with_key(http_method, url, parameters={}, options={})
chris@37 324 success_code = options[:success_code] || :success
chris@37 325 failure_code = options[:failure_code] || :unauthorized
chris@37 326
chris@37 327 context "should allow http basic auth with a key for #{http_method} #{url}" do
chris@37 328 context "with a valid HTTP authentication using the API token" do
chris@37 329 setup do
Chris@1115 330 @user = User.generate! do |user|
Chris@1115 331 user.admin = true
Chris@1115 332 end
Chris@1115 333 @token = Token.create!(:user => @user, :action => 'api')
Chris@1115 334 send(http_method, url, parameters, credentials(@token.value, 'X'))
chris@37 335 end
chris@37 336 should_respond_with success_code
chris@37 337 should_respond_with_content_type_based_on_url(url)
chris@37 338 should_be_a_valid_response_string_based_on_url(url)
chris@37 339 should "login as the user" do
chris@37 340 assert_equal @user, User.current
chris@37 341 end
chris@37 342 end
chris@37 343
chris@37 344 context "with an invalid HTTP authentication" do
chris@37 345 setup do
Chris@1115 346 @user = User.generate!
Chris@1115 347 @token = Token.create!(:user => @user, :action => 'feeds')
Chris@1115 348 send(http_method, url, parameters, credentials(@token.value, 'X'))
chris@37 349 end
chris@37 350 should_respond_with failure_code
chris@37 351 should_respond_with_content_type_based_on_url(url)
chris@37 352 should "not login as the user" do
chris@37 353 assert_equal User.anonymous, User.current
chris@37 354 end
chris@37 355 end
chris@37 356 end
chris@37 357 end
Chris@909 358
chris@37 359 # Test that a request allows full key authentication
chris@37 360 #
chris@37 361 # @param [Symbol] http_method the HTTP method for request (:get, :post, :put, :delete)
chris@37 362 # @param [String] url the request url, without the key=ZXY parameter
chris@37 363 # @param [optional, Hash] parameters additional request parameters
chris@37 364 # @param [optional, Hash] options additional options
chris@37 365 # @option options [Symbol] :success_code Successful response code (:success)
chris@37 366 # @option options [Symbol] :failure_code Failure response code (:unauthorized)
chris@37 367 def self.should_allow_key_based_auth(http_method, url, parameters={}, options={})
chris@37 368 success_code = options[:success_code] || :success
chris@37 369 failure_code = options[:failure_code] || :unauthorized
chris@37 370
chris@37 371 context "should allow key based auth using key=X for #{http_method} #{url}" do
chris@37 372 context "with a valid api token" do
chris@37 373 setup do
Chris@1115 374 @user = User.generate! do |user|
Chris@1115 375 user.admin = true
Chris@1115 376 end
Chris@1115 377 @token = Token.create!(:user => @user, :action => 'api')
chris@37 378 # Simple url parse to add on ?key= or &key=
chris@37 379 request_url = if url.match(/\?/)
chris@37 380 url + "&key=#{@token.value}"
chris@37 381 else
chris@37 382 url + "?key=#{@token.value}"
chris@37 383 end
chris@37 384 send(http_method, request_url, parameters)
chris@37 385 end
chris@37 386 should_respond_with success_code
chris@37 387 should_respond_with_content_type_based_on_url(url)
chris@37 388 should_be_a_valid_response_string_based_on_url(url)
chris@37 389 should "login as the user" do
chris@37 390 assert_equal @user, User.current
chris@37 391 end
chris@37 392 end
chris@37 393
chris@37 394 context "with an invalid api token" do
chris@37 395 setup do
Chris@1115 396 @user = User.generate! do |user|
Chris@1115 397 user.admin = true
Chris@1115 398 end
Chris@1115 399 @token = Token.create!(:user => @user, :action => 'feeds')
chris@37 400 # Simple url parse to add on ?key= or &key=
chris@37 401 request_url = if url.match(/\?/)
chris@37 402 url + "&key=#{@token.value}"
chris@37 403 else
chris@37 404 url + "?key=#{@token.value}"
chris@37 405 end
chris@37 406 send(http_method, request_url, parameters)
chris@37 407 end
chris@37 408 should_respond_with failure_code
chris@37 409 should_respond_with_content_type_based_on_url(url)
chris@37 410 should "not login as the user" do
chris@37 411 assert_equal User.anonymous, User.current
chris@37 412 end
chris@37 413 end
chris@37 414 end
Chris@909 415
Chris@119 416 context "should allow key based auth using X-Redmine-API-Key header for #{http_method} #{url}" do
Chris@119 417 setup do
Chris@1115 418 @user = User.generate! do |user|
Chris@1115 419 user.admin = true
Chris@1115 420 end
Chris@1115 421 @token = Token.create!(:user => @user, :action => 'api')
Chris@119 422 send(http_method, url, parameters, {'X-Redmine-API-Key' => @token.value.to_s})
Chris@119 423 end
Chris@119 424 should_respond_with success_code
Chris@119 425 should_respond_with_content_type_based_on_url(url)
Chris@119 426 should_be_a_valid_response_string_based_on_url(url)
Chris@119 427 should "login as the user" do
Chris@119 428 assert_equal @user, User.current
Chris@119 429 end
Chris@119 430 end
chris@37 431 end
chris@37 432
chris@37 433 # Uses should_respond_with_content_type based on what's in the url:
chris@37 434 #
chris@37 435 # '/project/issues.xml' => should_respond_with_content_type :xml
chris@37 436 # '/project/issues.json' => should_respond_with_content_type :json
chris@37 437 #
chris@37 438 # @param [String] url Request
chris@37 439 def self.should_respond_with_content_type_based_on_url(url)
chris@37 440 case
chris@37 441 when url.match(/xml/i)
Chris@1115 442 should "respond with XML" do
Chris@1115 443 assert_equal 'application/xml', @response.content_type
Chris@1115 444 end
chris@37 445 when url.match(/json/i)
Chris@1115 446 should "respond with JSON" do
Chris@1115 447 assert_equal 'application/json', @response.content_type
Chris@1115 448 end
chris@37 449 else
chris@37 450 raise "Unknown content type for should_respond_with_content_type_based_on_url: #{url}"
chris@37 451 end
chris@37 452 end
chris@37 453
chris@37 454 # Uses the url to assert which format the response should be in
chris@37 455 #
chris@37 456 # '/project/issues.xml' => should_be_a_valid_xml_string
chris@37 457 # '/project/issues.json' => should_be_a_valid_json_string
chris@37 458 #
chris@37 459 # @param [String] url Request
chris@37 460 def self.should_be_a_valid_response_string_based_on_url(url)
chris@37 461 case
chris@37 462 when url.match(/xml/i)
chris@37 463 should_be_a_valid_xml_string
chris@37 464 when url.match(/json/i)
chris@37 465 should_be_a_valid_json_string
chris@37 466 else
chris@37 467 raise "Unknown content type for should_be_a_valid_response_based_on_url: #{url}"
chris@37 468 end
chris@37 469 end
Chris@909 470
chris@37 471 # Checks that the response is a valid JSON string
chris@37 472 def self.should_be_a_valid_json_string
chris@37 473 should "be a valid JSON string (or empty)" do
Chris@441 474 assert(response.body.blank? || ActiveSupport::JSON.decode(response.body))
chris@37 475 end
chris@37 476 end
chris@37 477
chris@37 478 # Checks that the response is a valid XML string
chris@37 479 def self.should_be_a_valid_xml_string
chris@37 480 should "be a valid XML string" do
chris@37 481 assert REXML::Document.new(response.body)
chris@37 482 end
chris@37 483 end
Chris@909 484
Chris@1115 485 def self.should_respond_with(status)
Chris@1115 486 should "respond with #{status}" do
Chris@1115 487 assert_response status
Chris@1115 488 end
Chris@1115 489 end
Chris@0 490 end
chris@37 491
chris@37 492 # Simple module to "namespace" all of the API tests
chris@37 493 module ApiTest
chris@37 494 end