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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. # Redmine - project management software
  2. # Copyright (C) 2006-2017 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. $redmine_test_ldap_server = ENV['REDMINE_TEST_LDAP_SERVER'] || '127.0.0.1'
  24. ENV["RAILS_ENV"] = "test"
  25. require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
  26. require 'rails/test_help'
  27. require Rails.root.join('test', 'mocks', 'open_id_authentication_mock.rb').to_s
  28. require File.expand_path(File.dirname(__FILE__) + '/object_helpers')
  29. include ObjectHelpers
  30. require 'net/ldap'
  31. require 'mocha/setup'
  32. require 'fileutils'
  33. Redmine::SudoMode.disable!
  34. $redmine_tmp_attachments_directory = "#{Rails.root}/tmp/test/attachments"
  35. FileUtils.mkdir_p $redmine_tmp_attachments_directory
  36. class ActionView::TestCase
  37. helper :application
  38. include ApplicationHelper
  39. end
  40. class ActiveSupport::TestCase
  41. include ActionDispatch::TestProcess
  42. self.use_transactional_tests = true
  43. self.use_instantiated_fixtures = false
  44. def uploaded_test_file(name, mime)
  45. fixture_file_upload("files/#{name}", mime, true)
  46. end
  47. def mock_file(options=nil)
  48. options ||= {
  49. :original_filename => 'a_file.png',
  50. :content_type => 'image/png',
  51. :size => 32
  52. }
  53. Redmine::MockFile.new(options)
  54. end
  55. def mock_file_with_options(options={})
  56. mock_file(options)
  57. end
  58. # Use a temporary directory for attachment related tests
  59. def set_tmp_attachments_directory
  60. Attachment.storage_path = $redmine_tmp_attachments_directory
  61. end
  62. def set_fixtures_attachments_directory
  63. Attachment.storage_path = "#{Rails.root}/test/fixtures/files"
  64. end
  65. def with_settings(options, &block)
  66. saved_settings = options.keys.inject({}) do |h, k|
  67. h[k] = case Setting[k]
  68. when Symbol, false, true, nil
  69. Setting[k]
  70. else
  71. Setting[k].dup
  72. end
  73. h
  74. end
  75. options.each {|k, v| Setting[k] = v}
  76. yield
  77. ensure
  78. saved_settings.each {|k, v| Setting[k] = v} if saved_settings
  79. end
  80. # Yields the block with user as the current user
  81. def with_current_user(user, &block)
  82. saved_user = User.current
  83. User.current = user
  84. yield
  85. ensure
  86. User.current = saved_user
  87. end
  88. def with_locale(locale, &block)
  89. saved_localed = ::I18n.locale
  90. ::I18n.locale = locale
  91. yield
  92. ensure
  93. ::I18n.locale = saved_localed
  94. end
  95. def self.ldap_configured?
  96. @test_ldap = Net::LDAP.new(:host => $redmine_test_ldap_server, :port => 389)
  97. return @test_ldap.bind
  98. rescue Exception => e
  99. # LDAP is not listening
  100. return nil
  101. end
  102. def self.convert_installed?
  103. Redmine::Thumbnail.convert_available?
  104. end
  105. def convert_installed?
  106. self.class.convert_installed?
  107. end
  108. # Returns the path to the test +vendor+ repository
  109. def self.repository_path(vendor)
  110. path = Rails.root.join("tmp/test/#{vendor.downcase}_repository").to_s
  111. # Unlike ruby, JRuby returns Rails.root with backslashes under Windows
  112. path.tr("\\", "/")
  113. end
  114. # Returns the url of the subversion test repository
  115. def self.subversion_repository_url
  116. path = repository_path('subversion')
  117. path = '/' + path unless path.starts_with?('/')
  118. "file://#{path}"
  119. end
  120. # Returns true if the +vendor+ test repository is configured
  121. def self.repository_configured?(vendor)
  122. File.directory?(repository_path(vendor))
  123. end
  124. def repository_path_hash(arr)
  125. hs = {}
  126. hs[:path] = arr.join("/")
  127. hs[:param] = arr.join("/")
  128. hs
  129. end
  130. def sqlite?
  131. ActiveRecord::Base.connection.adapter_name =~ /sqlite/i
  132. end
  133. def mysql?
  134. ActiveRecord::Base.connection.adapter_name =~ /mysql/i
  135. end
  136. def postgresql?
  137. ActiveRecord::Base.connection.adapter_name =~ /postgresql/i
  138. end
  139. def quoted_date(date)
  140. date = Date.parse(date) if date.is_a?(String)
  141. ActiveRecord::Base.connection.quoted_date(date)
  142. end
  143. # Asserts that a new record for the given class is created
  144. # and returns it
  145. def new_record(klass, &block)
  146. new_records(klass, 1, &block).first
  147. end
  148. # Asserts that count new records for the given class are created
  149. # and returns them as an array order by object id
  150. def new_records(klass, count, &block)
  151. assert_difference "#{klass}.count", count do
  152. yield
  153. end
  154. klass.order(:id => :desc).limit(count).to_a.reverse
  155. end
  156. def assert_save(object)
  157. saved = object.save
  158. message = "#{object.class} could not be saved"
  159. errors = object.errors.full_messages.map {|m| "- #{m}"}
  160. message << ":\n#{errors.join("\n")}" if errors.any?
  161. assert_equal true, saved, message
  162. end
  163. def assert_select_error(arg)
  164. assert_select '#errorExplanation', :text => arg
  165. end
  166. def assert_include(expected, s, message=nil)
  167. assert s.include?(expected), (message || "\"#{expected}\" not found in \"#{s}\"")
  168. end
  169. def assert_not_include(expected, s, message=nil)
  170. assert !s.include?(expected), (message || "\"#{expected}\" found in \"#{s}\"")
  171. end
  172. def assert_select_in(text, *args, &block)
  173. d = Nokogiri::HTML(CGI::unescapeHTML(String.new(text))).root
  174. assert_select(d, *args, &block)
  175. end
  176. def assert_select_email(*args, &block)
  177. email = ActionMailer::Base.deliveries.last
  178. assert_not_nil email
  179. html_body = email.parts.detect {|part| part.content_type.include?('text/html')}.try(&:body)
  180. assert_not_nil html_body
  181. assert_select_in html_body.encoded, *args, &block
  182. end
  183. def assert_mail_body_match(expected, mail, message=nil)
  184. if expected.is_a?(String)
  185. assert_include expected, mail_body(mail), message
  186. else
  187. assert_match expected, mail_body(mail), message
  188. end
  189. end
  190. def assert_mail_body_no_match(expected, mail, message=nil)
  191. if expected.is_a?(String)
  192. assert_not_include expected, mail_body(mail), message
  193. else
  194. assert_no_match expected, mail_body(mail), message
  195. end
  196. end
  197. def mail_body(mail)
  198. mail.parts.first.body.encoded
  199. end
  200. # Returns the lft value for a new root issue
  201. def new_issue_lft
  202. 1
  203. end
  204. end
  205. module Redmine
  206. class MockFile
  207. attr_reader :size, :original_filename, :content_type
  208. def initialize(options={})
  209. @size = options[:size] || 32
  210. @original_filename = options[:original_filename] || options[:filename]
  211. @content_type = options[:content_type]
  212. @content = options[:content] || 'x'*size
  213. end
  214. def read(*args)
  215. if @eof
  216. false
  217. else
  218. @eof = true
  219. @content
  220. end
  221. end
  222. end
  223. class RoutingTest < ActionDispatch::IntegrationTest
  224. def should_route(arg)
  225. arg = arg.dup
  226. request = arg.keys.detect {|key| key.is_a?(String)}
  227. raise ArgumentError unless request
  228. options = arg.slice!(request)
  229. raise ArgumentError unless request =~ /\A(GET|POST|PUT|PATCH|DELETE)\s+(.+)\z/
  230. method, path = $1.downcase.to_sym, $2
  231. raise ArgumentError unless arg.values.first =~ /\A(.+)#(.+)\z/
  232. controller, action = $1, $2
  233. assert_routing(
  234. {:method => method, :path => path},
  235. options.merge(:controller => controller, :action => action)
  236. )
  237. end
  238. end
  239. class HelperTest < ActionView::TestCase
  240. include Redmine::I18n
  241. def setup
  242. super
  243. User.current = nil
  244. ::I18n.locale = 'en'
  245. end
  246. end
  247. class ControllerTest < ActionController::TestCase
  248. # Returns the issues that are displayed in the list in the same order
  249. def issues_in_list
  250. ids = css_select('tr.issue td.id').map(&:text).map(&:to_i)
  251. Issue.where(:id => ids).sort_by {|issue| ids.index(issue.id)}
  252. end
  253. # Return the columns that are displayed in the issue list
  254. def columns_in_issues_list
  255. css_select('table.issues thead th:not(.checkbox)').map(&:text)
  256. end
  257. # Return the columns that are displayed in the list
  258. def columns_in_list
  259. css_select('table.list thead th:not(.checkbox)').map(&:text).select(&:present?)
  260. end
  261. # Verifies that the query filters match the expected filters
  262. def assert_query_filters(expected_filters)
  263. response.body =~ /initFilters\(\);\s*((addFilter\(.+\);\s*)*)/
  264. filter_init = $1.to_s
  265. expected_filters.each do |field, operator, values|
  266. s = "addFilter(#{field.to_json}, #{operator.to_json}, #{Array(values).to_json});"
  267. assert_include s, filter_init
  268. end
  269. assert_equal expected_filters.size, filter_init.scan("addFilter").size, "filters counts don't match"
  270. end
  271. end
  272. class RepositoryControllerTest < ControllerTest
  273. def setup
  274. super
  275. # We need to explicitly set Accept header to html otherwise
  276. # requests that ends with a known format like:
  277. # GET /projects/foo/repository/entry/image.png would be
  278. # treated as image/png requests, resulting in a 406 error.
  279. request.env["HTTP_ACCEPT"] = "text/html"
  280. end
  281. end
  282. class IntegrationTest < ActionDispatch::IntegrationTest
  283. def log_user(login, password)
  284. User.anonymous
  285. get "/login"
  286. assert_nil session[:user_id]
  287. assert_response :success
  288. post "/login", :params => {
  289. :username => login,
  290. :password => password
  291. }
  292. assert_equal login, User.find(session[:user_id]).login
  293. end
  294. def credentials(user, password=nil)
  295. {'HTTP_AUTHORIZATION' => ActionController::HttpAuthentication::Basic.encode_credentials(user, password || user)}
  296. end
  297. end
  298. module ApiTest
  299. API_FORMATS = %w(json xml).freeze
  300. # Base class for API tests
  301. class Base < Redmine::IntegrationTest
  302. def setup
  303. Setting.rest_api_enabled = '1'
  304. end
  305. def teardown
  306. Setting.rest_api_enabled = '0'
  307. end
  308. # Uploads content using the XML API and returns the attachment token
  309. def xml_upload(content, credentials)
  310. upload('xml', content, credentials)
  311. end
  312. # Uploads content using the JSON API and returns the attachment token
  313. def json_upload(content, credentials)
  314. upload('json', content, credentials)
  315. end
  316. def upload(format, content, credentials)
  317. set_tmp_attachments_directory
  318. assert_difference 'Attachment.count' do
  319. post "/uploads.#{format}",
  320. :params => content,
  321. :headers => {"CONTENT_TYPE" => 'application/octet-stream'}.merge(credentials)
  322. assert_response :created
  323. end
  324. data = response_data
  325. assert_kind_of Hash, data['upload']
  326. token = data['upload']['token']
  327. assert_not_nil token
  328. token
  329. end
  330. # Parses the response body based on its content type
  331. def response_data
  332. unless response.content_type.to_s =~ /^application\/(.+)/
  333. raise "Unexpected response type: #{response.content_type}"
  334. end
  335. format = $1
  336. case format
  337. when 'xml'
  338. Hash.from_xml(response.body)
  339. when 'json'
  340. ActiveSupport::JSON.decode(response.body)
  341. else
  342. raise "Unknown response format: #{format}"
  343. end
  344. end
  345. end
  346. class Routing < Redmine::RoutingTest
  347. def should_route(arg)
  348. arg = arg.dup
  349. request = arg.keys.detect {|key| key.is_a?(String)}
  350. raise ArgumentError unless request
  351. options = arg.slice!(request)
  352. API_FORMATS.each do |format|
  353. format_request = request.sub /$/, ".#{format}"
  354. super options.merge(format_request => arg[request], :format => format)
  355. end
  356. end
  357. end
  358. end
  359. end