You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_helper.rb 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. # Redmine - project management software
  2. # Copyright (C) 2006-2011 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. ENV["RAILS_ENV"] = "test"
  18. require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
  19. require 'test_help'
  20. require File.expand_path(File.dirname(__FILE__) + '/helper_testcase')
  21. require Rails.root.join('test', 'mocks', 'open_id_authentication_mock.rb').to_s
  22. require File.expand_path(File.dirname(__FILE__) + '/object_daddy_helpers')
  23. include ObjectDaddyHelpers
  24. class ActiveSupport::TestCase
  25. # Transactional fixtures accelerate your tests by wrapping each test method
  26. # in a transaction that's rolled back on completion. This ensures that the
  27. # test database remains unchanged so your fixtures don't have to be reloaded
  28. # between every test method. Fewer database queries means faster tests.
  29. #
  30. # Read Mike Clark's excellent walkthrough at
  31. # http://clarkware.com/cgi/blosxom/2005/10/24#Rails10FastTesting
  32. #
  33. # Every Active Record database supports transactions except MyISAM tables
  34. # in MySQL. Turn off transactional fixtures in this case; however, if you
  35. # don't care one way or the other, switching from MyISAM to InnoDB tables
  36. # is recommended.
  37. self.use_transactional_fixtures = true
  38. # Instantiated fixtures are slow, but give you @david where otherwise you
  39. # would need people(:david). If you don't want to migrate your existing
  40. # test cases which use the @david style and don't mind the speed hit (each
  41. # instantiated fixtures translates to a database query per test method),
  42. # then set this back to true.
  43. self.use_instantiated_fixtures = false
  44. # Add more helper methods to be used by all tests here...
  45. def log_user(login, password)
  46. User.anonymous
  47. get "/login"
  48. assert_equal nil, session[:user_id]
  49. assert_response :success
  50. assert_template "account/login"
  51. post "/login", :username => login, :password => password
  52. assert_equal login, User.find(session[:user_id]).login
  53. end
  54. def uploaded_test_file(name, mime)
  55. ActionController::TestUploadedFile.new(
  56. ActiveSupport::TestCase.fixture_path + "/files/#{name}", mime, true)
  57. end
  58. # Mock out a file
  59. def self.mock_file
  60. file = 'a_file.png'
  61. file.stubs(:size).returns(32)
  62. file.stubs(:original_filename).returns('a_file.png')
  63. file.stubs(:content_type).returns('image/png')
  64. file.stubs(:read).returns(false)
  65. file
  66. end
  67. def mock_file
  68. self.class.mock_file
  69. end
  70. def mock_file_with_options(options={})
  71. file = ''
  72. file.stubs(:size).returns(32)
  73. original_filename = options[:original_filename] || nil
  74. file.stubs(:original_filename).returns(original_filename)
  75. content_type = options[:content_type] || nil
  76. file.stubs(:content_type).returns(content_type)
  77. file.stubs(:read).returns(false)
  78. file
  79. end
  80. # Use a temporary directory for attachment related tests
  81. def set_tmp_attachments_directory
  82. Dir.mkdir "#{Rails.root}/tmp/test" unless File.directory?("#{Rails.root}/tmp/test")
  83. unless File.directory?("#{Rails.root}/tmp/test/attachments")
  84. Dir.mkdir "#{Rails.root}/tmp/test/attachments"
  85. end
  86. Attachment.storage_path = "#{Rails.root}/tmp/test/attachments"
  87. end
  88. def with_settings(options, &block)
  89. saved_settings = options.keys.inject({}) {|h, k| h[k] = Setting[k].is_a?(Symbol) ? Setting[k] : Setting[k].dup; h}
  90. options.each {|k, v| Setting[k] = v}
  91. yield
  92. ensure
  93. saved_settings.each {|k, v| Setting[k] = v} if saved_settings
  94. end
  95. def change_user_password(login, new_password)
  96. user = User.first(:conditions => {:login => login})
  97. user.password, user.password_confirmation = new_password, new_password
  98. user.save!
  99. end
  100. def self.ldap_configured?
  101. @test_ldap = Net::LDAP.new(:host => '127.0.0.1', :port => 389)
  102. return @test_ldap.bind
  103. rescue Exception => e
  104. # LDAP is not listening
  105. return nil
  106. end
  107. # Returns the path to the test +vendor+ repository
  108. def self.repository_path(vendor)
  109. Rails.root.join("tmp/test/#{vendor.downcase}_repository").to_s
  110. end
  111. # Returns the url of the subversion test repository
  112. def self.subversion_repository_url
  113. path = repository_path('subversion')
  114. path = '/' + path unless path.starts_with?('/')
  115. "file://#{path}"
  116. end
  117. # Returns true if the +vendor+ test repository is configured
  118. def self.repository_configured?(vendor)
  119. File.directory?(repository_path(vendor))
  120. end
  121. def assert_error_tag(options={})
  122. assert_tag({:attributes => { :id => 'errorExplanation' }}.merge(options))
  123. end
  124. def assert_include(expected, s)
  125. assert s.include?(expected), "\"#{expected}\" not found in \"#{s}\""
  126. end
  127. # Shoulda macros
  128. def self.should_render_404
  129. should_respond_with :not_found
  130. should_render_template 'common/error'
  131. end
  132. def self.should_have_before_filter(expected_method, options = {})
  133. should_have_filter('before', expected_method, options)
  134. end
  135. def self.should_have_after_filter(expected_method, options = {})
  136. should_have_filter('after', expected_method, options)
  137. end
  138. def self.should_have_filter(filter_type, expected_method, options)
  139. description = "have #{filter_type}_filter :#{expected_method}"
  140. description << " with #{options.inspect}" unless options.empty?
  141. should description do
  142. klass = "action_controller/filters/#{filter_type}_filter".classify.constantize
  143. expected = klass.new(:filter, expected_method.to_sym, options)
  144. assert_equal 1, @controller.class.filter_chain.select { |filter|
  145. filter.method == expected.method && filter.kind == expected.kind &&
  146. filter.options == expected.options && filter.class == expected.class
  147. }.size
  148. end
  149. end
  150. def self.should_show_the_old_and_new_values_for(prop_key, model, &block)
  151. context "" do
  152. setup do
  153. if block_given?
  154. instance_eval &block
  155. else
  156. @old_value = model.generate!
  157. @new_value = model.generate!
  158. end
  159. end
  160. should "use the new value's name" do
  161. @detail = JournalDetail.generate!(:property => 'attr',
  162. :old_value => @old_value.id,
  163. :value => @new_value.id,
  164. :prop_key => prop_key)
  165. assert_match @new_value.name, show_detail(@detail, true)
  166. end
  167. should "use the old value's name" do
  168. @detail = JournalDetail.generate!(:property => 'attr',
  169. :old_value => @old_value.id,
  170. :value => @new_value.id,
  171. :prop_key => prop_key)
  172. assert_match @old_value.name, show_detail(@detail, true)
  173. end
  174. end
  175. end
  176. def self.should_create_a_new_user(&block)
  177. should "create a new user" do
  178. user = instance_eval &block
  179. assert user
  180. assert_kind_of User, user
  181. assert !user.new_record?
  182. end
  183. end
  184. # Test that a request allows the three types of API authentication
  185. #
  186. # * HTTP Basic with username and password
  187. # * HTTP Basic with an api key for the username
  188. # * Key based with the key=X parameter
  189. #
  190. # @param [Symbol] http_method the HTTP method for request (:get, :post, :put, :delete)
  191. # @param [String] url the request url
  192. # @param [optional, Hash] parameters additional request parameters
  193. # @param [optional, Hash] options additional options
  194. # @option options [Symbol] :success_code Successful response code (:success)
  195. # @option options [Symbol] :failure_code Failure response code (:unauthorized)
  196. def self.should_allow_api_authentication(http_method, url, parameters={}, options={})
  197. should_allow_http_basic_auth_with_username_and_password(http_method, url, parameters, options)
  198. should_allow_http_basic_auth_with_key(http_method, url, parameters, options)
  199. should_allow_key_based_auth(http_method, url, parameters, options)
  200. end
  201. # Test that a request allows the username and password for HTTP BASIC
  202. #
  203. # @param [Symbol] http_method the HTTP method for request (:get, :post, :put, :delete)
  204. # @param [String] url the request url
  205. # @param [optional, Hash] parameters additional request parameters
  206. # @param [optional, Hash] options additional options
  207. # @option options [Symbol] :success_code Successful response code (:success)
  208. # @option options [Symbol] :failure_code Failure response code (:unauthorized)
  209. def self.should_allow_http_basic_auth_with_username_and_password(http_method, url, parameters={}, options={})
  210. success_code = options[:success_code] || :success
  211. failure_code = options[:failure_code] || :unauthorized
  212. context "should allow http basic auth using a username and password for #{http_method} #{url}" do
  213. context "with a valid HTTP authentication" do
  214. setup do
  215. @user = User.generate_with_protected!(:password => 'my_password', :password_confirmation => 'my_password', :admin => true) # Admin so they can access the project
  216. @authorization = ActionController::HttpAuthentication::Basic.encode_credentials(@user.login, 'my_password')
  217. send(http_method, url, parameters, {:authorization => @authorization})
  218. end
  219. should_respond_with success_code
  220. should_respond_with_content_type_based_on_url(url)
  221. should "login as the user" do
  222. assert_equal @user, User.current
  223. end
  224. end
  225. context "with an invalid HTTP authentication" do
  226. setup do
  227. @user = User.generate_with_protected!
  228. @authorization = ActionController::HttpAuthentication::Basic.encode_credentials(@user.login, 'wrong_password')
  229. send(http_method, url, parameters, {:authorization => @authorization})
  230. end
  231. should_respond_with failure_code
  232. should_respond_with_content_type_based_on_url(url)
  233. should "not login as the user" do
  234. assert_equal User.anonymous, User.current
  235. end
  236. end
  237. context "without credentials" do
  238. setup do
  239. send(http_method, url, parameters, {:authorization => ''})
  240. end
  241. should_respond_with failure_code
  242. should_respond_with_content_type_based_on_url(url)
  243. should "include_www_authenticate_header" do
  244. assert @controller.response.headers.has_key?('WWW-Authenticate')
  245. end
  246. end
  247. end
  248. end
  249. # Test that a request allows the API key with HTTP BASIC
  250. #
  251. # @param [Symbol] http_method the HTTP method for request (:get, :post, :put, :delete)
  252. # @param [String] url the request url
  253. # @param [optional, Hash] parameters additional request parameters
  254. # @param [optional, Hash] options additional options
  255. # @option options [Symbol] :success_code Successful response code (:success)
  256. # @option options [Symbol] :failure_code Failure response code (:unauthorized)
  257. def self.should_allow_http_basic_auth_with_key(http_method, url, parameters={}, options={})
  258. success_code = options[:success_code] || :success
  259. failure_code = options[:failure_code] || :unauthorized
  260. context "should allow http basic auth with a key for #{http_method} #{url}" do
  261. context "with a valid HTTP authentication using the API token" do
  262. setup do
  263. @user = User.generate_with_protected!(:admin => true)
  264. @token = Token.generate!(:user => @user, :action => 'api')
  265. @authorization = ActionController::HttpAuthentication::Basic.encode_credentials(@token.value, 'X')
  266. send(http_method, url, parameters, {:authorization => @authorization})
  267. end
  268. should_respond_with success_code
  269. should_respond_with_content_type_based_on_url(url)
  270. should_be_a_valid_response_string_based_on_url(url)
  271. should "login as the user" do
  272. assert_equal @user, User.current
  273. end
  274. end
  275. context "with an invalid HTTP authentication" do
  276. setup do
  277. @user = User.generate_with_protected!
  278. @token = Token.generate!(:user => @user, :action => 'feeds')
  279. @authorization = ActionController::HttpAuthentication::Basic.encode_credentials(@token.value, 'X')
  280. send(http_method, url, parameters, {:authorization => @authorization})
  281. end
  282. should_respond_with failure_code
  283. should_respond_with_content_type_based_on_url(url)
  284. should "not login as the user" do
  285. assert_equal User.anonymous, User.current
  286. end
  287. end
  288. end
  289. end
  290. # Test that a request allows full key authentication
  291. #
  292. # @param [Symbol] http_method the HTTP method for request (:get, :post, :put, :delete)
  293. # @param [String] url the request url, without the key=ZXY parameter
  294. # @param [optional, Hash] parameters additional request parameters
  295. # @param [optional, Hash] options additional options
  296. # @option options [Symbol] :success_code Successful response code (:success)
  297. # @option options [Symbol] :failure_code Failure response code (:unauthorized)
  298. def self.should_allow_key_based_auth(http_method, url, parameters={}, options={})
  299. success_code = options[:success_code] || :success
  300. failure_code = options[:failure_code] || :unauthorized
  301. context "should allow key based auth using key=X for #{http_method} #{url}" do
  302. context "with a valid api token" do
  303. setup do
  304. @user = User.generate_with_protected!(:admin => true)
  305. @token = Token.generate!(:user => @user, :action => 'api')
  306. # Simple url parse to add on ?key= or &key=
  307. request_url = if url.match(/\?/)
  308. url + "&key=#{@token.value}"
  309. else
  310. url + "?key=#{@token.value}"
  311. end
  312. send(http_method, request_url, parameters)
  313. end
  314. should_respond_with success_code
  315. should_respond_with_content_type_based_on_url(url)
  316. should_be_a_valid_response_string_based_on_url(url)
  317. should "login as the user" do
  318. assert_equal @user, User.current
  319. end
  320. end
  321. context "with an invalid api token" do
  322. setup do
  323. @user = User.generate_with_protected!
  324. @token = Token.generate!(:user => @user, :action => 'feeds')
  325. # Simple url parse to add on ?key= or &key=
  326. request_url = if url.match(/\?/)
  327. url + "&key=#{@token.value}"
  328. else
  329. url + "?key=#{@token.value}"
  330. end
  331. send(http_method, request_url, parameters)
  332. end
  333. should_respond_with failure_code
  334. should_respond_with_content_type_based_on_url(url)
  335. should "not login as the user" do
  336. assert_equal User.anonymous, User.current
  337. end
  338. end
  339. end
  340. context "should allow key based auth using X-Redmine-API-Key header for #{http_method} #{url}" do
  341. setup do
  342. @user = User.generate_with_protected!(:admin => true)
  343. @token = Token.generate!(:user => @user, :action => 'api')
  344. send(http_method, url, parameters, {'X-Redmine-API-Key' => @token.value.to_s})
  345. end
  346. should_respond_with success_code
  347. should_respond_with_content_type_based_on_url(url)
  348. should_be_a_valid_response_string_based_on_url(url)
  349. should "login as the user" do
  350. assert_equal @user, User.current
  351. end
  352. end
  353. end
  354. # Uses should_respond_with_content_type based on what's in the url:
  355. #
  356. # '/project/issues.xml' => should_respond_with_content_type :xml
  357. # '/project/issues.json' => should_respond_with_content_type :json
  358. #
  359. # @param [String] url Request
  360. def self.should_respond_with_content_type_based_on_url(url)
  361. case
  362. when url.match(/xml/i)
  363. should_respond_with_content_type :xml
  364. when url.match(/json/i)
  365. should_respond_with_content_type :json
  366. else
  367. raise "Unknown content type for should_respond_with_content_type_based_on_url: #{url}"
  368. end
  369. end
  370. # Uses the url to assert which format the response should be in
  371. #
  372. # '/project/issues.xml' => should_be_a_valid_xml_string
  373. # '/project/issues.json' => should_be_a_valid_json_string
  374. #
  375. # @param [String] url Request
  376. def self.should_be_a_valid_response_string_based_on_url(url)
  377. case
  378. when url.match(/xml/i)
  379. should_be_a_valid_xml_string
  380. when url.match(/json/i)
  381. should_be_a_valid_json_string
  382. else
  383. raise "Unknown content type for should_be_a_valid_response_based_on_url: #{url}"
  384. end
  385. end
  386. # Checks that the response is a valid JSON string
  387. def self.should_be_a_valid_json_string
  388. should "be a valid JSON string (or empty)" do
  389. assert(response.body.blank? || ActiveSupport::JSON.decode(response.body))
  390. end
  391. end
  392. # Checks that the response is a valid XML string
  393. def self.should_be_a_valid_xml_string
  394. should "be a valid XML string" do
  395. assert REXML::Document.new(response.body)
  396. end
  397. end
  398. end
  399. # Simple module to "namespace" all of the API tests
  400. module ApiTest
  401. end