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