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.

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