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 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. # Redmine - project management software
  2. # Copyright (C) 2006-2015 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. if ENV["COVERAGE"]
  18. require 'simplecov'
  19. require File.expand_path(File.dirname(__FILE__) + "/coverage/html_formatter")
  20. SimpleCov.formatter = Redmine::Coverage::HtmlFormatter
  21. SimpleCov.start 'rails'
  22. end
  23. ENV["RAILS_ENV"] = "test"
  24. require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
  25. require 'rails/test_help'
  26. require Rails.root.join('test', 'mocks', 'open_id_authentication_mock.rb').to_s
  27. require File.expand_path(File.dirname(__FILE__) + '/object_helpers')
  28. include ObjectHelpers
  29. require 'net/ldap'
  30. require 'mocha/setup'
  31. Redmine::SudoMode.disable!
  32. class ActionView::TestCase
  33. helper :application
  34. include ApplicationHelper
  35. end
  36. class ActiveSupport::TestCase
  37. include ActionDispatch::TestProcess
  38. self.use_transactional_fixtures = true
  39. self.use_instantiated_fixtures = false
  40. def uploaded_test_file(name, mime)
  41. fixture_file_upload("files/#{name}", mime, true)
  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 self.ldap_configured?
  107. @test_ldap = Net::LDAP.new(:host => '127.0.0.1', :port => 389)
  108. return @test_ldap.bind
  109. rescue Exception => e
  110. # LDAP is not listening
  111. return nil
  112. end
  113. def self.convert_installed?
  114. Redmine::Thumbnail.convert_available?
  115. end
  116. def convert_installed?
  117. self.class.convert_installed?
  118. end
  119. # Returns the path to the test +vendor+ repository
  120. def self.repository_path(vendor)
  121. path = Rails.root.join("tmp/test/#{vendor.downcase}_repository").to_s
  122. # Unlike ruby, JRuby returns Rails.root with backslashes under Windows
  123. path.tr("\\", "/")
  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 sqlite?
  142. ActiveRecord::Base.connection.adapter_name =~ /sqlite/i
  143. end
  144. def mysql?
  145. ActiveRecord::Base.connection.adapter_name =~ /mysql/i
  146. end
  147. def postgresql?
  148. ActiveRecord::Base.connection.adapter_name =~ /postgresql/i
  149. end
  150. def quoted_date(date)
  151. date = Date.parse(date) if date.is_a?(String)
  152. ActiveRecord::Base.connection.quoted_date(date)
  153. end
  154. # Asserts that a new record for the given class is created
  155. # and returns it
  156. def new_record(klass, &block)
  157. new_records(klass, 1, &block).first
  158. end
  159. # Asserts that count new records for the given class are created
  160. # and returns them as an array order by object id
  161. def new_records(klass, count, &block)
  162. assert_difference "#{klass}.count", count do
  163. yield
  164. end
  165. klass.order(:id => :desc).limit(count).to_a.reverse
  166. end
  167. def assert_save(object)
  168. saved = object.save
  169. message = "#{object.class} could not be saved"
  170. errors = object.errors.full_messages.map {|m| "- #{m}"}
  171. message << ":\n#{errors.join("\n")}" if errors.any?
  172. assert_equal true, saved, message
  173. end
  174. def assert_select_error(arg)
  175. assert_select '#errorExplanation', :text => arg
  176. end
  177. def assert_include(expected, s, message=nil)
  178. assert s.include?(expected), (message || "\"#{expected}\" not found in \"#{s}\"")
  179. end
  180. def assert_not_include(expected, s, message=nil)
  181. assert !s.include?(expected), (message || "\"#{expected}\" found in \"#{s}\"")
  182. end
  183. def assert_select_in(text, *args, &block)
  184. d = Nokogiri::HTML(CGI::unescapeHTML(String.new(text))).root
  185. assert_select(d, *args, &block)
  186. end
  187. def assert_select_email(*args, &block)
  188. email = ActionMailer::Base.deliveries.last
  189. assert_not_nil email
  190. html_body = email.parts.detect {|part| part.content_type.include?('text/html')}.try(&:body)
  191. assert_not_nil html_body
  192. assert_select_in html_body.encoded, *args, &block
  193. end
  194. def assert_mail_body_match(expected, mail, message=nil)
  195. if expected.is_a?(String)
  196. assert_include expected, mail_body(mail), message
  197. else
  198. assert_match expected, mail_body(mail), message
  199. end
  200. end
  201. def assert_mail_body_no_match(expected, mail, message=nil)
  202. if expected.is_a?(String)
  203. assert_not_include expected, mail_body(mail), message
  204. else
  205. assert_no_match expected, mail_body(mail), message
  206. end
  207. end
  208. def mail_body(mail)
  209. mail.parts.first.body.encoded
  210. end
  211. # Returns the lft value for a new root issue
  212. def new_issue_lft
  213. 1
  214. end
  215. end
  216. module Redmine
  217. class RoutingTest < ActionDispatch::IntegrationTest
  218. def should_route(arg)
  219. arg = arg.dup
  220. request = arg.keys.detect {|key| key.is_a?(String)}
  221. raise ArgumentError unless request
  222. options = arg.slice!(request)
  223. raise ArgumentError unless request =~ /\A(GET|POST|PUT|PATCH|DELETE)\s+(.+)\z/
  224. method, path = $1.downcase.to_sym, $2
  225. raise ArgumentError unless arg.values.first =~ /\A(.+)#(.+)\z/
  226. controller, action = $1, $2
  227. assert_routing(
  228. {:method => method, :path => path},
  229. options.merge(:controller => controller, :action => action)
  230. )
  231. end
  232. end
  233. class IntegrationTest < ActionDispatch::IntegrationTest
  234. def log_user(login, password)
  235. User.anonymous
  236. get "/login"
  237. assert_equal nil, session[:user_id]
  238. assert_response :success
  239. assert_template "account/login"
  240. post "/login", :username => login, :password => password
  241. assert_equal login, User.find(session[:user_id]).login
  242. end
  243. def credentials(user, password=nil)
  244. {'HTTP_AUTHORIZATION' => ActionController::HttpAuthentication::Basic.encode_credentials(user, password || user)}
  245. end
  246. end
  247. module ApiTest
  248. API_FORMATS = %w(json xml).freeze
  249. # Base class for API tests
  250. class Base < Redmine::IntegrationTest
  251. def setup
  252. Setting.rest_api_enabled = '1'
  253. end
  254. def teardown
  255. Setting.rest_api_enabled = '0'
  256. end
  257. # Uploads content using the XML API and returns the attachment token
  258. def xml_upload(content, credentials)
  259. upload('xml', content, credentials)
  260. end
  261. # Uploads content using the JSON API and returns the attachment token
  262. def json_upload(content, credentials)
  263. upload('json', content, credentials)
  264. end
  265. def upload(format, content, credentials)
  266. set_tmp_attachments_directory
  267. assert_difference 'Attachment.count' do
  268. post "/uploads.#{format}", content, {"CONTENT_TYPE" => 'application/octet-stream'}.merge(credentials)
  269. assert_response :created
  270. end
  271. data = response_data
  272. assert_kind_of Hash, data['upload']
  273. token = data['upload']['token']
  274. assert_not_nil token
  275. token
  276. end
  277. # Parses the response body based on its content type
  278. def response_data
  279. unless response.content_type.to_s =~ /^application\/(.+)/
  280. raise "Unexpected response type: #{response.content_type}"
  281. end
  282. format = $1
  283. case format
  284. when 'xml'
  285. Hash.from_xml(response.body)
  286. when 'json'
  287. ActiveSupport::JSON.decode(response.body)
  288. else
  289. raise "Unknown response format: #{format}"
  290. end
  291. end
  292. end
  293. class Routing < Redmine::RoutingTest
  294. def should_route(arg)
  295. arg = arg.dup
  296. request = arg.keys.detect {|key| key.is_a?(String)}
  297. raise ArgumentError unless request
  298. options = arg.slice!(request)
  299. API_FORMATS.each do |format|
  300. format_request = request.sub /$/, ".#{format}"
  301. super options.merge(format_request => arg[request], :format => format)
  302. end
  303. end
  304. end
  305. end
  306. end