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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. # frozen_string_literal: true
  2. # Redmine - project management software
  3. # Copyright (C) 2006-2021 Jean-Philippe Lang
  4. #
  5. # This program is free software; you can redistribute it and/or
  6. # modify it under the terms of the GNU General Public License
  7. # as published by the Free Software Foundation; either version 2
  8. # of the License, or (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program; if not, write to the Free Software
  17. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. if ENV["COVERAGE"]
  19. require 'simplecov'
  20. require File.expand_path(File.dirname(__FILE__) + "/coverage/html_formatter")
  21. SimpleCov.formatter = Redmine::Coverage::HtmlFormatter
  22. SimpleCov.start 'rails'
  23. end
  24. $redmine_test_ldap_server = ENV['REDMINE_TEST_LDAP_SERVER'] || '127.0.0.1'
  25. ENV["RAILS_ENV"] = "test"
  26. require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
  27. require 'rails/test_help'
  28. require File.expand_path(File.dirname(__FILE__) + '/object_helpers')
  29. include ObjectHelpers
  30. require 'net/ldap'
  31. require 'mocha/minitest'
  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. $redmine_tmp_pdf_directory = "#{Rails.root}/tmp/test/pdf"
  37. FileUtils.mkdir_p $redmine_tmp_pdf_directory
  38. FileUtils.rm Dir.glob('#$redmine_tmp_pdf_directory/*.pdf')
  39. class ActionView::TestCase
  40. helper :application
  41. include ApplicationHelper
  42. end
  43. class ActiveSupport::TestCase
  44. parallelize(workers: 1)
  45. include ActionDispatch::TestProcess
  46. self.use_transactional_tests = true
  47. self.use_instantiated_fixtures = false
  48. def uploaded_test_file(name, mime)
  49. fixture_file_upload(name.to_s, mime, true)
  50. end
  51. def mock_file(options=nil)
  52. options ||=
  53. {
  54. :original_filename => 'a_file.png',
  55. :content_type => 'image/png',
  56. :size => 32
  57. }
  58. Redmine::MockFile.new(options)
  59. end
  60. def mock_file_with_options(options={})
  61. mock_file(options)
  62. end
  63. # Use a temporary directory for attachment related tests
  64. def set_tmp_attachments_directory
  65. Attachment.storage_path = $redmine_tmp_attachments_directory
  66. end
  67. def set_fixtures_attachments_directory
  68. Attachment.storage_path = "#{Rails.root}/test/fixtures/files"
  69. end
  70. def with_settings(options, &block)
  71. saved_settings = options.keys.inject({}) do |h, k|
  72. h[k] =
  73. case Setting[k]
  74. when Symbol, false, true, nil
  75. Setting[k]
  76. else
  77. Setting[k].dup
  78. end
  79. h
  80. end
  81. options.each {|k, v| Setting[k] = v}
  82. yield
  83. ensure
  84. saved_settings.each {|k, v| Setting[k] = v} if saved_settings
  85. end
  86. # Yields the block with user as the current user
  87. def with_current_user(user, &block)
  88. saved_user = User.current
  89. User.current = user
  90. yield
  91. ensure
  92. User.current = saved_user
  93. end
  94. def with_locale(locale, &block)
  95. saved_localed = ::I18n.locale
  96. ::I18n.locale = locale
  97. yield
  98. ensure
  99. ::I18n.locale = saved_localed
  100. end
  101. def self.ldap_configured?
  102. @test_ldap = Net::LDAP.new(:host => $redmine_test_ldap_server, :port => 389)
  103. return @test_ldap.bind
  104. rescue => e
  105. # LDAP is not listening
  106. return nil
  107. end
  108. def self.convert_installed?
  109. Redmine::Thumbnail.convert_available?
  110. end
  111. def convert_installed?
  112. self.class.convert_installed?
  113. end
  114. def self.gs_installed?
  115. Redmine::Thumbnail.gs_available?
  116. end
  117. def gs_installed?
  118. self.class.gs_installed?
  119. end
  120. # Returns the path to the test +vendor+ repository
  121. def self.repository_path(vendor)
  122. path = Rails.root.join("tmp/test/#{vendor.downcase}_repository").to_s
  123. # Unlike ruby, JRuby returns Rails.root with backslashes under Windows
  124. path.tr("\\", "/")
  125. end
  126. # Returns the url of the subversion test repository
  127. def self.subversion_repository_url
  128. path = repository_path('subversion')
  129. path = '/' + path unless path.starts_with?('/')
  130. "file://#{path}"
  131. end
  132. # Returns true if the +vendor+ test repository is configured
  133. def self.repository_configured?(vendor)
  134. File.directory?(repository_path(vendor))
  135. end
  136. def repository_configured?(vendor)
  137. self.class.repository_configured?(vendor)
  138. end
  139. def self.is_mysql_utf8mb4
  140. return false unless Redmine::Database.mysql?
  141. character_sets = %w[
  142. character_set_connection
  143. character_set_database
  144. character_set_results
  145. character_set_server
  146. ]
  147. ActiveRecord::Base.connection.
  148. select_rows('show variables like "character%"').each do |r|
  149. return false if character_sets.include?(r[0]) && r[1] != "utf8mb4"
  150. end
  151. return true
  152. end
  153. def is_mysql_utf8mb4
  154. self.class.is_mysql_utf8mb4
  155. end
  156. def repository_path_hash(arr)
  157. hs = {}
  158. hs[:path] = arr.join("/")
  159. hs[:param] = arr.join("/")
  160. hs
  161. end
  162. def sqlite?
  163. Redmine::Database.sqlite?
  164. end
  165. def mysql?
  166. Redmine::Database.mysql?
  167. end
  168. def postgresql?
  169. Redmine::Database.postgresql?
  170. end
  171. def quoted_date(date)
  172. date = Date.parse(date) if date.is_a?(String)
  173. ActiveRecord::Base.connection.quoted_date(date)
  174. end
  175. # Asserts that a new record for the given class is created
  176. # and returns it
  177. def new_record(klass, &block)
  178. new_records(klass, 1, &block).first
  179. end
  180. # Asserts that count new records for the given class are created
  181. # and returns them as an array order by object id
  182. def new_records(klass, count, &block)
  183. assert_difference "#{klass}.count", count do
  184. yield
  185. end
  186. klass.order(:id => :desc).limit(count).to_a.reverse
  187. end
  188. def assert_save(object)
  189. saved = object.save
  190. message = "#{object.class} could not be saved"
  191. errors = object.errors.full_messages.map {|m| "- #{m}"}
  192. message += ":\n#{errors.join("\n")}" if errors.any?
  193. assert_equal true, saved, message
  194. end
  195. def assert_select_error(arg)
  196. assert_select '#errorExplanation', :text => arg
  197. end
  198. def assert_include(expected, s, message=nil)
  199. assert s.include?(expected), (message || "\"#{expected}\" not found in \"#{s}\"")
  200. end
  201. def assert_not_include(expected, s, message=nil)
  202. assert !s.include?(expected), (message || "\"#{expected}\" found in \"#{s}\"")
  203. end
  204. def assert_select_in(text, *args, &block)
  205. d = Nokogiri::HTML(CGI.unescapeHTML(String.new(text))).root
  206. assert_select(d, *args, &block)
  207. end
  208. def assert_select_email(*args, &block)
  209. email = ActionMailer::Base.deliveries.last
  210. assert_not_nil email
  211. html_body = email.parts.detect {|part| part.content_type.include?('text/html')}.try(&:body)
  212. assert_not_nil html_body
  213. assert_select_in html_body.encoded, *args, &block
  214. end
  215. def assert_mail_body_match(expected, mail, message=nil)
  216. if expected.is_a?(String)
  217. assert_include expected, mail_body(mail), message
  218. else
  219. assert_match expected, mail_body(mail), message
  220. end
  221. end
  222. def assert_mail_body_no_match(expected, mail, message=nil)
  223. if expected.is_a?(String)
  224. assert_not_include expected, mail_body(mail), message
  225. else
  226. assert_no_match expected, mail_body(mail), message
  227. end
  228. end
  229. def mail_body(mail)
  230. (mail.multipart? ? mail.parts.first : mail).body.encoded
  231. end
  232. # Returns the lft value for a new root issue
  233. def new_issue_lft
  234. 1
  235. end
  236. end
  237. module Redmine
  238. class MockFile
  239. attr_reader :size, :original_filename, :content_type
  240. def initialize(options={})
  241. @size = options[:size] || 32
  242. @original_filename = options[:original_filename] || options[:filename]
  243. @content_type = options[:content_type]
  244. @content = options[:content] || 'x'*size
  245. end
  246. def read(*args)
  247. if @eof
  248. false
  249. else
  250. @eof = true
  251. @content
  252. end
  253. end
  254. end
  255. class RoutingTest < ActionDispatch::IntegrationTest
  256. def should_route(arg)
  257. arg = arg.dup
  258. request = arg.keys.detect {|key| key.is_a?(String)}
  259. raise ArgumentError unless request
  260. options = arg.slice!(request)
  261. raise ArgumentError unless request =~ /\A(GET|POST|PUT|PATCH|DELETE)\s+(.+)\z/
  262. method, path = $1.downcase.to_sym, $2
  263. raise ArgumentError unless arg.values.first =~ /\A(.+)#(.+)\z/
  264. controller, action = $1, $2
  265. assert_routing(
  266. {:method => method, :path => path},
  267. options.merge(:controller => controller, :action => action)
  268. )
  269. end
  270. end
  271. class HelperTest < ActionView::TestCase
  272. include Redmine::I18n
  273. def setup
  274. super
  275. User.current = nil
  276. ::I18n.locale = 'en'
  277. end
  278. end
  279. class ControllerTest < ActionController::TestCase
  280. # Returns the issues that are displayed in the list in the same order
  281. def issues_in_list
  282. ids = css_select('tr.issue td.id').map(&:text).map(&:to_i)
  283. Issue.where(:id => ids).sort_by {|issue| ids.index(issue.id)}
  284. end
  285. # Return the columns that are displayed in the issue list
  286. def columns_in_issues_list
  287. css_select('table.issues thead th:not(.checkbox)').map(&:text).select(&:present?)
  288. end
  289. # Return the columns that are displayed in the list
  290. def columns_in_list
  291. css_select('table.list thead th:not(.checkbox)').map(&:text).select(&:present?)
  292. end
  293. # Returns the values that are displayed in tds with the given css class
  294. def columns_values_in_list(css_class)
  295. css_select("table.list tbody td.#{css_class}").map(&:text)
  296. end
  297. # Verifies that the query filters match the expected filters
  298. def assert_query_filters(expected_filters)
  299. response.body =~ /initFilters\(\);\s*((addFilter\(.+\);\s*)*)/
  300. filter_init = $1.to_s
  301. expected_filters.each do |field, operator, values|
  302. s = "addFilter(#{field.to_json}, #{operator.to_json}, #{Array(values).to_json});"
  303. assert_include s, filter_init
  304. end
  305. assert_equal expected_filters.size, filter_init.scan("addFilter").size, "filters counts don't match"
  306. end
  307. # Saves the generated PDF in tmp/test/pdf
  308. def save_pdf
  309. assert_equal 'application/pdf', response.media_type
  310. filename = "#{self.class.name.underscore}__#{method_name}.pdf"
  311. File.open(File.join($redmine_tmp_pdf_directory, filename), "wb") do |f|
  312. f.write response.body
  313. end
  314. end
  315. end
  316. class RepositoryControllerTest < ControllerTest
  317. def setup
  318. super
  319. # We need to explicitly set Accept header to html otherwise
  320. # requests that ends with a known format like:
  321. # GET /projects/foo/repository/entry/image.png would be
  322. # treated as image/png requests, resulting in a 406 error.
  323. request.env["HTTP_ACCEPT"] = "text/html"
  324. end
  325. end
  326. class IntegrationTest < ActionDispatch::IntegrationTest
  327. def setup
  328. ActionMailer::MailDeliveryJob.disable_test_adapter
  329. super
  330. end
  331. def log_user(login, password)
  332. User.anonymous
  333. get "/login"
  334. assert_nil session[:user_id]
  335. assert_response :success
  336. post(
  337. "/login",
  338. :params => {
  339. :username => login,
  340. :password => password
  341. }
  342. )
  343. assert_equal login, User.find(session[:user_id]).login
  344. end
  345. def credentials(user, password=nil)
  346. {'HTTP_AUTHORIZATION' => ActionController::HttpAuthentication::Basic.encode_credentials(user, password || user)}
  347. end
  348. end
  349. module ApiTest
  350. API_FORMATS = %w(json xml).freeze
  351. # Base class for API tests
  352. class Base < Redmine::IntegrationTest
  353. def setup
  354. Setting.rest_api_enabled = '1'
  355. end
  356. def teardown
  357. Setting.rest_api_enabled = '0'
  358. end
  359. # Uploads content using the XML API and returns the attachment token
  360. def xml_upload(content, credentials)
  361. upload('xml', content, credentials)
  362. end
  363. # Uploads content using the JSON API and returns the attachment token
  364. def json_upload(content, credentials)
  365. upload('json', content, credentials)
  366. end
  367. def upload(format, content, credentials)
  368. set_tmp_attachments_directory
  369. assert_difference 'Attachment.count' do
  370. post(
  371. "/uploads.#{format}",
  372. :params => content,
  373. :headers => {"CONTENT_TYPE" => 'application/octet-stream'}.merge(credentials)
  374. )
  375. assert_response :created
  376. end
  377. data = response_data
  378. assert_kind_of Hash, data['upload']
  379. token = data['upload']['token']
  380. assert_not_nil token
  381. token
  382. end
  383. # Parses the response body based on its content type
  384. def response_data
  385. unless response.media_type.to_s =~ /^application\/(.+)/
  386. raise "Unexpected response type: #{response.media_type}"
  387. end
  388. format = $1
  389. case format
  390. when 'xml'
  391. Hash.from_xml(response.body)
  392. when 'json'
  393. ActiveSupport::JSON.decode(response.body)
  394. else
  395. raise "Unknown response format: #{format}"
  396. end
  397. end
  398. end
  399. class Routing < Redmine::RoutingTest
  400. def should_route(arg)
  401. arg = arg.dup
  402. request = arg.keys.detect {|key| key.is_a?(String)}
  403. raise ArgumentError unless request
  404. options = arg.slice!(request)
  405. API_FORMATS.each do |format|
  406. format_request = request.sub /$/, ".#{format}"
  407. super options.merge(format_request => arg[request], :format => format)
  408. end
  409. end
  410. end
  411. end
  412. end