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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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 File.join(RAILS_ROOT,'test', 'mocks', 'open_id_authentication_mock.rb')
  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(ActiveSupport::TestCase.fixture_path + "/files/#{name}", mime, true)
  56. end
  57. # Mock out a file
  58. def self.mock_file
  59. file = 'a_file.png'
  60. file.stubs(:size).returns(32)
  61. file.stubs(:original_filename).returns('a_file.png')
  62. file.stubs(:content_type).returns('image/png')
  63. file.stubs(:read).returns(false)
  64. file
  65. end
  66. def mock_file
  67. self.class.mock_file
  68. end
  69. # Use a temporary directory for attachment related tests
  70. def set_tmp_attachments_directory
  71. Dir.mkdir "#{RAILS_ROOT}/tmp/test" unless File.directory?("#{RAILS_ROOT}/tmp/test")
  72. Dir.mkdir "#{RAILS_ROOT}/tmp/test/attachments" unless File.directory?("#{RAILS_ROOT}/tmp/test/attachments")
  73. Attachment.storage_path = "#{RAILS_ROOT}/tmp/test/attachments"
  74. end
  75. def with_settings(options, &block)
  76. saved_settings = options.keys.inject({}) {|h, k| h[k] = Setting[k].dup; h}
  77. options.each {|k, v| Setting[k] = v}
  78. yield
  79. ensure
  80. saved_settings.each {|k, v| Setting[k] = v}
  81. end
  82. def change_user_password(login, new_password)
  83. user = User.first(:conditions => {:login => login})
  84. user.password, user.password_confirmation = new_password, new_password
  85. user.save!
  86. end
  87. def self.ldap_configured?
  88. @test_ldap = Net::LDAP.new(:host => '127.0.0.1', :port => 389)
  89. return @test_ldap.bind
  90. rescue Exception => e
  91. # LDAP is not listening
  92. return nil
  93. end
  94. # Returns the path to the test +vendor+ repository
  95. def self.repository_path(vendor)
  96. File.join(RAILS_ROOT.gsub(%r{config\/\.\.}, ''), "/tmp/test/#{vendor.downcase}_repository")
  97. end
  98. # Returns the url of the subversion test repository
  99. def self.subversion_repository_url
  100. path = repository_path('subversion')
  101. path = '/' + path unless path.starts_with?('/')
  102. "file://#{path}"
  103. end
  104. # Returns true if the +vendor+ test repository is configured
  105. def self.repository_configured?(vendor)
  106. File.directory?(repository_path(vendor))
  107. end
  108. def assert_error_tag(options={})
  109. assert_tag({:attributes => { :id => 'errorExplanation' }}.merge(options))
  110. end
  111. # Shoulda macros
  112. def self.should_render_404
  113. should_respond_with :not_found
  114. should_render_template 'common/error'
  115. end
  116. def self.should_have_before_filter(expected_method, options = {})
  117. should_have_filter('before', expected_method, options)
  118. end
  119. def self.should_have_after_filter(expected_method, options = {})
  120. should_have_filter('after', expected_method, options)
  121. end
  122. def self.should_have_filter(filter_type, expected_method, options)
  123. description = "have #{filter_type}_filter :#{expected_method}"
  124. description << " with #{options.inspect}" unless options.empty?
  125. should description do
  126. klass = "action_controller/filters/#{filter_type}_filter".classify.constantize
  127. expected = klass.new(:filter, expected_method.to_sym, options)
  128. assert_equal 1, @controller.class.filter_chain.select { |filter|
  129. filter.method == expected.method && filter.kind == expected.kind &&
  130. filter.options == expected.options && filter.class == expected.class
  131. }.size
  132. end
  133. end
  134. def self.should_show_the_old_and_new_values_for(prop_key, model, &block)
  135. context "" do
  136. setup do
  137. if block_given?
  138. instance_eval &block
  139. else
  140. @old_value = model.generate!
  141. @new_value = model.generate!
  142. end
  143. end
  144. should "use the new value's name" do
  145. @detail = JournalDetail.generate!(:property => 'attr',
  146. :old_value => @old_value.id,
  147. :value => @new_value.id,
  148. :prop_key => prop_key)
  149. assert_match @new_value.name, show_detail(@detail, true)
  150. end
  151. should "use the old value's name" do
  152. @detail = JournalDetail.generate!(:property => 'attr',
  153. :old_value => @old_value.id,
  154. :value => @new_value.id,
  155. :prop_key => prop_key)
  156. assert_match @old_value.name, show_detail(@detail, true)
  157. end
  158. end
  159. end
  160. def self.should_create_a_new_user(&block)
  161. should "create a new user" do
  162. user = instance_eval &block
  163. assert user
  164. assert_kind_of User, user
  165. assert !user.new_record?
  166. end
  167. end
  168. # Test that a request allows the three types of API authentication
  169. #
  170. # * HTTP Basic with username and password
  171. # * HTTP Basic with an api key for the username
  172. # * Key based with the key=X parameter
  173. #
  174. # @param [Symbol] http_method the HTTP method for request (:get, :post, :put, :delete)
  175. # @param [String] url the request url
  176. # @param [optional, Hash] parameters additional request parameters
  177. # @param [optional, Hash] options additional options
  178. # @option options [Symbol] :success_code Successful response code (:success)
  179. # @option options [Symbol] :failure_code Failure response code (:unauthorized)
  180. def self.should_allow_api_authentication(http_method, url, parameters={}, options={})
  181. should_allow_http_basic_auth_with_username_and_password(http_method, url, parameters, options)
  182. should_allow_http_basic_auth_with_key(http_method, url, parameters, options)
  183. should_allow_key_based_auth(http_method, url, parameters, options)
  184. end
  185. # Test that a request allows the username and password for HTTP BASIC
  186. #
  187. # @param [Symbol] http_method the HTTP method for request (:get, :post, :put, :delete)
  188. # @param [String] url the request url
  189. # @param [optional, Hash] parameters additional request parameters
  190. # @param [optional, Hash] options additional options
  191. # @option options [Symbol] :success_code Successful response code (:success)
  192. # @option options [Symbol] :failure_code Failure response code (:unauthorized)
  193. def self.should_allow_http_basic_auth_with_username_and_password(http_method, url, parameters={}, options={})
  194. success_code = options[:success_code] || :success
  195. failure_code = options[:failure_code] || :unauthorized
  196. context "should allow http basic auth using a username and password for #{http_method} #{url}" do
  197. context "with a valid HTTP authentication" do
  198. setup do
  199. @user = User.generate_with_protected!(:password => 'my_password', :password_confirmation => 'my_password', :admin => true) # Admin so they can access the project
  200. @authorization = ActionController::HttpAuthentication::Basic.encode_credentials(@user.login, 'my_password')
  201. send(http_method, url, parameters, {:authorization => @authorization})
  202. end
  203. should_respond_with success_code
  204. should_respond_with_content_type_based_on_url(url)
  205. should "login as the user" do
  206. assert_equal @user, User.current
  207. end
  208. end
  209. context "with an invalid HTTP authentication" do
  210. setup do
  211. @user = User.generate_with_protected!
  212. @authorization = ActionController::HttpAuthentication::Basic.encode_credentials(@user.login, 'wrong_password')
  213. send(http_method, url, parameters, {:authorization => @authorization})
  214. end
  215. should_respond_with failure_code
  216. should_respond_with_content_type_based_on_url(url)
  217. should "not login as the user" do
  218. assert_equal User.anonymous, User.current
  219. end
  220. end
  221. context "without credentials" do
  222. setup do
  223. send(http_method, url, parameters, {:authorization => ''})
  224. end
  225. should_respond_with failure_code
  226. should_respond_with_content_type_based_on_url(url)
  227. should "include_www_authenticate_header" do
  228. assert @controller.response.headers.has_key?('WWW-Authenticate')
  229. end
  230. end
  231. end
  232. end
  233. # Test that a request allows the API key with HTTP BASIC
  234. #
  235. # @param [Symbol] http_method the HTTP method for request (:get, :post, :put, :delete)
  236. # @param [String] url the request url
  237. # @param [optional, Hash] parameters additional request parameters
  238. # @param [optional, Hash] options additional options
  239. # @option options [Symbol] :success_code Successful response code (:success)
  240. # @option options [Symbol] :failure_code Failure response code (:unauthorized)
  241. def self.should_allow_http_basic_auth_with_key(http_method, url, parameters={}, options={})
  242. success_code = options[:success_code] || :success
  243. failure_code = options[:failure_code] || :unauthorized
  244. context "should allow http basic auth with a key for #{http_method} #{url}" do
  245. context "with a valid HTTP authentication using the API token" do
  246. setup do
  247. @user = User.generate_with_protected!(:admin => true)
  248. @token = Token.generate!(:user => @user, :action => 'api')
  249. @authorization = ActionController::HttpAuthentication::Basic.encode_credentials(@token.value, 'X')
  250. send(http_method, url, parameters, {:authorization => @authorization})
  251. end
  252. should_respond_with success_code
  253. should_respond_with_content_type_based_on_url(url)
  254. should_be_a_valid_response_string_based_on_url(url)
  255. should "login as the user" do
  256. assert_equal @user, User.current
  257. end
  258. end
  259. context "with an invalid HTTP authentication" do
  260. setup do
  261. @user = User.generate_with_protected!
  262. @token = Token.generate!(:user => @user, :action => 'feeds')
  263. @authorization = ActionController::HttpAuthentication::Basic.encode_credentials(@token.value, 'X')
  264. send(http_method, url, parameters, {:authorization => @authorization})
  265. end
  266. should_respond_with failure_code
  267. should_respond_with_content_type_based_on_url(url)
  268. should "not login as the user" do
  269. assert_equal User.anonymous, User.current
  270. end
  271. end
  272. end
  273. end
  274. # Test that a request allows full key authentication
  275. #
  276. # @param [Symbol] http_method the HTTP method for request (:get, :post, :put, :delete)
  277. # @param [String] url the request url, without the key=ZXY parameter
  278. # @param [optional, Hash] parameters additional request parameters
  279. # @param [optional, Hash] options additional options
  280. # @option options [Symbol] :success_code Successful response code (:success)
  281. # @option options [Symbol] :failure_code Failure response code (:unauthorized)
  282. def self.should_allow_key_based_auth(http_method, url, parameters={}, options={})
  283. success_code = options[:success_code] || :success
  284. failure_code = options[:failure_code] || :unauthorized
  285. context "should allow key based auth using key=X for #{http_method} #{url}" do
  286. context "with a valid api token" do
  287. setup do
  288. @user = User.generate_with_protected!(:admin => true)
  289. @token = Token.generate!(:user => @user, :action => 'api')
  290. # Simple url parse to add on ?key= or &key=
  291. request_url = if url.match(/\?/)
  292. url + "&key=#{@token.value}"
  293. else
  294. url + "?key=#{@token.value}"
  295. end
  296. send(http_method, request_url, parameters)
  297. end
  298. should_respond_with success_code
  299. should_respond_with_content_type_based_on_url(url)
  300. should_be_a_valid_response_string_based_on_url(url)
  301. should "login as the user" do
  302. assert_equal @user, User.current
  303. end
  304. end
  305. context "with an invalid api token" do
  306. setup do
  307. @user = User.generate_with_protected!
  308. @token = Token.generate!(:user => @user, :action => 'feeds')
  309. # Simple url parse to add on ?key= or &key=
  310. request_url = if url.match(/\?/)
  311. url + "&key=#{@token.value}"
  312. else
  313. url + "?key=#{@token.value}"
  314. end
  315. send(http_method, request_url, parameters)
  316. end
  317. should_respond_with failure_code
  318. should_respond_with_content_type_based_on_url(url)
  319. should "not login as the user" do
  320. assert_equal User.anonymous, User.current
  321. end
  322. end
  323. end
  324. context "should allow key based auth using X-Redmine-API-Key header for #{http_method} #{url}" do
  325. setup do
  326. @user = User.generate_with_protected!(:admin => true)
  327. @token = Token.generate!(:user => @user, :action => 'api')
  328. send(http_method, url, parameters, {'X-Redmine-API-Key' => @token.value.to_s})
  329. end
  330. should_respond_with success_code
  331. should_respond_with_content_type_based_on_url(url)
  332. should_be_a_valid_response_string_based_on_url(url)
  333. should "login as the user" do
  334. assert_equal @user, User.current
  335. end
  336. end
  337. end
  338. # Uses should_respond_with_content_type based on what's in the url:
  339. #
  340. # '/project/issues.xml' => should_respond_with_content_type :xml
  341. # '/project/issues.json' => should_respond_with_content_type :json
  342. #
  343. # @param [String] url Request
  344. def self.should_respond_with_content_type_based_on_url(url)
  345. case
  346. when url.match(/xml/i)
  347. should_respond_with_content_type :xml
  348. when url.match(/json/i)
  349. should_respond_with_content_type :json
  350. else
  351. raise "Unknown content type for should_respond_with_content_type_based_on_url: #{url}"
  352. end
  353. end
  354. # Uses the url to assert which format the response should be in
  355. #
  356. # '/project/issues.xml' => should_be_a_valid_xml_string
  357. # '/project/issues.json' => should_be_a_valid_json_string
  358. #
  359. # @param [String] url Request
  360. def self.should_be_a_valid_response_string_based_on_url(url)
  361. case
  362. when url.match(/xml/i)
  363. should_be_a_valid_xml_string
  364. when url.match(/json/i)
  365. should_be_a_valid_json_string
  366. else
  367. raise "Unknown content type for should_be_a_valid_response_based_on_url: #{url}"
  368. end
  369. end
  370. # Checks that the response is a valid JSON string
  371. def self.should_be_a_valid_json_string
  372. should "be a valid JSON string (or empty)" do
  373. assert(response.body.blank? || ActiveSupport::JSON.decode(response.body))
  374. end
  375. end
  376. # Checks that the response is a valid XML string
  377. def self.should_be_a_valid_xml_string
  378. should "be a valid XML string" do
  379. assert REXML::Document.new(response.body)
  380. end
  381. end
  382. end
  383. # Simple module to "namespace" all of the API tests
  384. module ApiTest
  385. end