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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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. #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 with_locale(locale, &block)
  100. saved_localed = ::I18n.locale
  101. ::I18n.locale = locale
  102. yield
  103. ensure
  104. ::I18n.locale = saved_localed
  105. end
  106. def change_user_password(login, new_password)
  107. user = User.where(:login => login).first
  108. user.password, user.password_confirmation = new_password, new_password
  109. user.save!
  110. end
  111. def self.ldap_configured?
  112. @test_ldap = Net::LDAP.new(:host => '127.0.0.1', :port => 389)
  113. return @test_ldap.bind
  114. rescue Exception => e
  115. # LDAP is not listening
  116. return nil
  117. end
  118. def self.convert_installed?
  119. Redmine::Thumbnail.convert_available?
  120. end
  121. # Returns the path to the test +vendor+ repository
  122. def self.repository_path(vendor)
  123. Rails.root.join("tmp/test/#{vendor.downcase}_repository").to_s
  124. end
  125. # Returns the url of the subversion test repository
  126. def self.subversion_repository_url
  127. path = repository_path('subversion')
  128. path = '/' + path unless path.starts_with?('/')
  129. "file://#{path}"
  130. end
  131. # Returns true if the +vendor+ test repository is configured
  132. def self.repository_configured?(vendor)
  133. File.directory?(repository_path(vendor))
  134. end
  135. def repository_path_hash(arr)
  136. hs = {}
  137. hs[:path] = arr.join("/")
  138. hs[:param] = arr.join("/")
  139. hs
  140. end
  141. def assert_save(object)
  142. saved = object.save
  143. message = "#{object.class} could not be saved"
  144. errors = object.errors.full_messages.map {|m| "- #{m}"}
  145. message << ":\n#{errors.join("\n")}" if errors.any?
  146. assert_equal true, saved, message
  147. end
  148. def assert_error_tag(options={})
  149. assert_tag({:attributes => { :id => 'errorExplanation' }}.merge(options))
  150. end
  151. def assert_include(expected, s, message=nil)
  152. assert s.include?(expected), (message || "\"#{expected}\" not found in \"#{s}\"")
  153. end
  154. def assert_not_include(expected, s, message=nil)
  155. assert !s.include?(expected), (message || "\"#{expected}\" found in \"#{s}\"")
  156. end
  157. def assert_select_in(text, *args, &block)
  158. d = HTML::Document.new(CGI::unescapeHTML(String.new(text))).root
  159. assert_select(d, *args, &block)
  160. end
  161. def assert_mail_body_match(expected, mail, message=nil)
  162. if expected.is_a?(String)
  163. assert_include expected, mail_body(mail), message
  164. else
  165. assert_match expected, mail_body(mail), message
  166. end
  167. end
  168. def assert_mail_body_no_match(expected, mail, message=nil)
  169. if expected.is_a?(String)
  170. assert_not_include expected, mail_body(mail), message
  171. else
  172. assert_no_match expected, mail_body(mail), message
  173. end
  174. end
  175. def mail_body(mail)
  176. mail.parts.first.body.encoded
  177. end
  178. end
  179. module Redmine
  180. module ApiTest
  181. # Base class for API tests
  182. class Base < ActionDispatch::IntegrationTest
  183. # Test that a request allows the three types of API authentication
  184. #
  185. # * HTTP Basic with username and password
  186. # * HTTP Basic with an api key for the username
  187. # * Key based with the key=X parameter
  188. #
  189. # @param [Symbol] http_method the HTTP method for request (:get, :post, :put, :delete)
  190. # @param [String] url the request url
  191. # @param [optional, Hash] parameters additional request parameters
  192. # @param [optional, Hash] options additional options
  193. # @option options [Symbol] :success_code Successful response code (:success)
  194. # @option options [Symbol] :failure_code Failure response code (:unauthorized)
  195. def self.should_allow_api_authentication(http_method, url, parameters={}, options={})
  196. should_allow_http_basic_auth_with_username_and_password(http_method, url, parameters, options)
  197. should_allow_http_basic_auth_with_key(http_method, url, parameters, options)
  198. should_allow_key_based_auth(http_method, url, parameters, options)
  199. end
  200. # Test that a request allows the username and password for HTTP BASIC
  201. #
  202. # @param [Symbol] http_method the HTTP method for request (:get, :post, :put, :delete)
  203. # @param [String] url the request url
  204. # @param [optional, Hash] parameters additional request parameters
  205. # @param [optional, Hash] options additional options
  206. # @option options [Symbol] :success_code Successful response code (:success)
  207. # @option options [Symbol] :failure_code Failure response code (:unauthorized)
  208. def self.should_allow_http_basic_auth_with_username_and_password(http_method, url, parameters={}, options={})
  209. success_code = options[:success_code] || :success
  210. failure_code = options[:failure_code] || :unauthorized
  211. context "should allow http basic auth using a username and password for #{http_method} #{url}" do
  212. context "with a valid HTTP authentication" do
  213. setup do
  214. @user = User.generate! do |user|
  215. user.admin = true
  216. user.password = 'my_password'
  217. end
  218. send(http_method, url, parameters, credentials(@user.login, 'my_password'))
  219. end
  220. should_respond_with success_code
  221. should_respond_with_content_type_based_on_url(url)
  222. should "login as the user" do
  223. assert_equal @user, User.current
  224. end
  225. end
  226. context "with an invalid HTTP authentication" do
  227. setup do
  228. @user = User.generate!
  229. send(http_method, url, parameters, credentials(@user.login, 'wrong_password'))
  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)
  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! do |user|
  264. user.admin = true
  265. end
  266. @token = Token.create!(:user => @user, :action => 'api')
  267. send(http_method, url, parameters, credentials(@token.value, 'X'))
  268. end
  269. should_respond_with success_code
  270. should_respond_with_content_type_based_on_url(url)
  271. should_be_a_valid_response_string_based_on_url(url)
  272. should "login as the user" do
  273. assert_equal @user, User.current
  274. end
  275. end
  276. context "with an invalid HTTP authentication" do
  277. setup do
  278. @user = User.generate!
  279. @token = Token.create!(:user => @user, :action => 'feeds')
  280. send(http_method, url, parameters, credentials(@token.value, 'X'))
  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! do |user|
  305. user.admin = true
  306. end
  307. @token = Token.create!(:user => @user, :action => 'api')
  308. # Simple url parse to add on ?key= or &key=
  309. request_url = if url.match(/\?/)
  310. url + "&key=#{@token.value}"
  311. else
  312. url + "?key=#{@token.value}"
  313. end
  314. send(http_method, request_url, parameters)
  315. end
  316. should_respond_with success_code
  317. should_respond_with_content_type_based_on_url(url)
  318. should_be_a_valid_response_string_based_on_url(url)
  319. should "login as the user" do
  320. assert_equal @user, User.current
  321. end
  322. end
  323. context "with an invalid api token" do
  324. setup do
  325. @user = User.generate! do |user|
  326. user.admin = true
  327. end
  328. @token = Token.create!(:user => @user, :action => 'feeds')
  329. # Simple url parse to add on ?key= or &key=
  330. request_url = if url.match(/\?/)
  331. url + "&key=#{@token.value}"
  332. else
  333. url + "?key=#{@token.value}"
  334. end
  335. send(http_method, request_url, parameters)
  336. end
  337. should_respond_with failure_code
  338. should_respond_with_content_type_based_on_url(url)
  339. should "not login as the user" do
  340. assert_equal User.anonymous, User.current
  341. end
  342. end
  343. end
  344. context "should allow key based auth using X-Redmine-API-Key header for #{http_method} #{url}" do
  345. setup do
  346. @user = User.generate! do |user|
  347. user.admin = true
  348. end
  349. @token = Token.create!(:user => @user, :action => 'api')
  350. send(http_method, url, parameters, {'X-Redmine-API-Key' => @token.value.to_s})
  351. end
  352. should_respond_with success_code
  353. should_respond_with_content_type_based_on_url(url)
  354. should_be_a_valid_response_string_based_on_url(url)
  355. should "login as the user" do
  356. assert_equal @user, User.current
  357. end
  358. end
  359. end
  360. # Uses should_respond_with_content_type based on what's in the url:
  361. #
  362. # '/project/issues.xml' => should_respond_with_content_type :xml
  363. # '/project/issues.json' => should_respond_with_content_type :json
  364. #
  365. # @param [String] url Request
  366. def self.should_respond_with_content_type_based_on_url(url)
  367. case
  368. when url.match(/xml/i)
  369. should "respond with XML" do
  370. assert_equal 'application/xml', @response.content_type
  371. end
  372. when url.match(/json/i)
  373. should "respond with JSON" do
  374. assert_equal 'application/json', @response.content_type
  375. end
  376. else
  377. raise "Unknown content type for should_respond_with_content_type_based_on_url: #{url}"
  378. end
  379. end
  380. # Uses the url to assert which format the response should be in
  381. #
  382. # '/project/issues.xml' => should_be_a_valid_xml_string
  383. # '/project/issues.json' => should_be_a_valid_json_string
  384. #
  385. # @param [String] url Request
  386. def self.should_be_a_valid_response_string_based_on_url(url)
  387. case
  388. when url.match(/xml/i)
  389. should_be_a_valid_xml_string
  390. when url.match(/json/i)
  391. should_be_a_valid_json_string
  392. else
  393. raise "Unknown content type for should_be_a_valid_response_based_on_url: #{url}"
  394. end
  395. end
  396. # Checks that the response is a valid JSON string
  397. def self.should_be_a_valid_json_string
  398. should "be a valid JSON string (or empty)" do
  399. assert(response.body.blank? || ActiveSupport::JSON.decode(response.body))
  400. end
  401. end
  402. # Checks that the response is a valid XML string
  403. def self.should_be_a_valid_xml_string
  404. should "be a valid XML string" do
  405. assert REXML::Document.new(response.body)
  406. end
  407. end
  408. def self.should_respond_with(status)
  409. should "respond with #{status}" do
  410. assert_response status
  411. end
  412. end
  413. end
  414. end
  415. end
  416. # URL helpers do not work with config.threadsafe!
  417. # https://github.com/rspec/rspec-rails/issues/476#issuecomment-4705454
  418. ActionView::TestCase::TestController.instance_eval do
  419. helper Rails.application.routes.url_helpers
  420. end
  421. ActionView::TestCase::TestController.class_eval do
  422. def _routes
  423. Rails.application.routes
  424. end
  425. end