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

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