comparison .svn/pristine/67/67c0428911abf350e9f2025e9810f70bf182d6ea.svn-base @ 1494:e248c7af89ec redmine-2.4

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