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