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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. # frozen_string_literal: true
  2. # Redmine - project management software
  3. # Copyright (C) 2006- 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_relative '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_relative '../config/environment'
  27. require 'rails/test_help'
  28. require_relative '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 false
  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 mysql8?
  169. version = Redmine::Database.mysql_version.sub(/^(\d+\.\d+\.\d+).*/, '\1')
  170. Gem::Version.new(version) >= Gem::Version.new('8.0.0')
  171. end
  172. def postgresql?
  173. Redmine::Database.postgresql?
  174. end
  175. def quoted_date(date)
  176. date = Date.parse(date) if date.is_a?(String)
  177. ActiveRecord::Base.connection.quoted_date(date)
  178. end
  179. # Asserts that a new record for the given class is created
  180. # and returns it
  181. def new_record(klass, &block)
  182. new_records(klass, 1, &block).first
  183. end
  184. # Asserts that count new records for the given class are created
  185. # and returns them as an array order by object id
  186. def new_records(klass, count, &block)
  187. assert_difference "#{klass}.count", count do
  188. yield
  189. end
  190. klass.order(:id => :desc).limit(count).to_a.reverse
  191. end
  192. def assert_save(object)
  193. saved = object.save
  194. message = "#{object.class} could not be saved"
  195. errors = object.errors.full_messages.map {|m| "- #{m}"}
  196. message += ":\n#{errors.join("\n")}" if errors.any?
  197. assert_equal true, saved, message
  198. end
  199. def assert_select_error(arg)
  200. assert_select '#errorExplanation', :text => arg
  201. end
  202. def assert_include(expected, s, message=nil)
  203. assert s.include?(expected), (message || "\"#{expected}\" not found in \"#{s}\"")
  204. end
  205. def assert_not_include(expected, s, message=nil)
  206. assert !s.include?(expected), (message || "\"#{expected}\" found in \"#{s}\"")
  207. end
  208. def assert_select_in(text, ...)
  209. d = Nokogiri::HTML(CGI.unescapeHTML(String.new(text))).root
  210. assert_select(d, ...)
  211. end
  212. def assert_select_email(...)
  213. email = ActionMailer::Base.deliveries.last
  214. assert_not_nil email
  215. html_body = email.parts.detect {|part| part.content_type.include?('text/html')}.try(&:body)
  216. assert_not_nil html_body
  217. assert_select_in(html_body.encoded, ...)
  218. end
  219. def assert_mail_body_match(expected, mail, message=nil)
  220. if expected.is_a?(String)
  221. assert_include expected, mail_body(mail), message
  222. else
  223. assert_match expected, mail_body(mail), message
  224. end
  225. end
  226. def assert_mail_body_no_match(expected, mail, message=nil)
  227. if expected.is_a?(String)
  228. assert_not_include expected, mail_body(mail), message
  229. else
  230. assert_no_match expected, mail_body(mail), message
  231. end
  232. end
  233. def mail_body(mail)
  234. (mail.multipart? ? mail.parts.first : mail).body.encoded
  235. end
  236. # Returns the lft value for a new root issue
  237. def new_issue_lft
  238. 1
  239. end
  240. end
  241. module Redmine
  242. class MockFile
  243. attr_reader :size, :original_filename, :content_type
  244. def initialize(options={})
  245. @size = options[:size] || 32
  246. @original_filename = options[:original_filename] || options[:filename]
  247. @content_type = options[:content_type]
  248. @content = options[:content] || 'x'*size
  249. end
  250. def read(*args)
  251. if @eof
  252. false
  253. else
  254. @eof = true
  255. @content
  256. end
  257. end
  258. end
  259. class RoutingTest < ActionDispatch::IntegrationTest
  260. def should_route(arg)
  261. arg = arg.dup
  262. request = arg.keys.detect {|key| key.is_a?(String)}
  263. raise ArgumentError unless request
  264. options = arg.slice!(request)
  265. raise ArgumentError unless request =~ /\A(GET|POST|PUT|PATCH|DELETE)\s+(.+)\z/
  266. method, path = $1.downcase.to_sym, $2
  267. raise ArgumentError unless arg.values.first =~ /\A(.+)#(.+)\z/
  268. controller, action = $1, $2
  269. assert_routing(
  270. {:method => method, :path => path},
  271. options.merge(:controller => controller, :action => action)
  272. )
  273. end
  274. end
  275. class HelperTest < ActionView::TestCase
  276. include Redmine::I18n
  277. include Propshaft::Helper
  278. def setup
  279. super
  280. User.current = nil
  281. ::I18n.locale = 'en'
  282. end
  283. end
  284. class ControllerTest < ActionController::TestCase
  285. # Returns the issues that are displayed in the list in the same order
  286. def issues_in_list
  287. ids = css_select('tr.issue td.id').map {|e| e.text.to_i}
  288. Issue.where(:id => ids).sort_by {|issue| ids.index(issue.id)}
  289. end
  290. # Return the columns that are displayed in the issue list
  291. def columns_in_issues_list
  292. css_select('table.issues thead th:not(.checkbox)').map(&:text).select(&:present?)
  293. end
  294. # Return the columns that are displayed in the list
  295. def columns_in_list
  296. css_select('table.list thead th:not(.checkbox)').map(&:text).select(&:present?)
  297. end
  298. # Returns the values that are displayed in tds with the given css class
  299. def columns_values_in_list(css_class)
  300. css_select("table.list tbody td.#{css_class}").map(&:text)
  301. end
  302. # Verifies that the query filters match the expected filters
  303. def assert_query_filters(expected_filters)
  304. response.body =~ /initFilters\(\);\s*((addFilter\(.+\);\s*)*)/
  305. filter_init = $1.to_s
  306. expected_filters.each do |field, operator, values|
  307. s = "addFilter(#{field.to_json}, #{operator.to_json}, #{Array(values).to_json});"
  308. assert_include s, filter_init
  309. end
  310. assert_equal expected_filters.size, filter_init.scan("addFilter").size, "filters counts don't match"
  311. end
  312. # Saves the generated PDF in tmp/test/pdf
  313. def save_pdf
  314. assert_equal 'application/pdf', response.media_type
  315. filename = "#{self.class.name.underscore}__#{method_name}.pdf"
  316. File.binwrite(File.join($redmine_tmp_pdf_directory, filename), response.body)
  317. end
  318. end
  319. class RepositoryControllerTest < ControllerTest
  320. def setup
  321. super
  322. # We need to explicitly set Accept header to html otherwise
  323. # requests that ends with a known format like:
  324. # GET /projects/foo/repository/entry/image.png would be
  325. # treated as image/png requests, resulting in a 406 error.
  326. request.env["HTTP_ACCEPT"] = "text/html"
  327. end
  328. end
  329. class IntegrationTest < ActionDispatch::IntegrationTest
  330. def setup
  331. ActionMailer::MailDeliveryJob.disable_test_adapter
  332. super
  333. end
  334. def log_user(login, password)
  335. User.anonymous
  336. get "/login"
  337. assert_nil session[:user_id]
  338. assert_response :success
  339. post(
  340. "/login",
  341. :params => {
  342. :username => login,
  343. :password => password
  344. }
  345. )
  346. assert_equal login, User.find(session[:user_id]).login
  347. end
  348. def credentials(user, password=nil)
  349. {'HTTP_AUTHORIZATION' => ActionController::HttpAuthentication::Basic.encode_credentials(user, password || user)}
  350. end
  351. end
  352. module ApiTest
  353. API_FORMATS = %w(json xml).freeze
  354. # Base class for API tests
  355. class Base < Redmine::IntegrationTest
  356. def setup
  357. Setting.rest_api_enabled = '1'
  358. end
  359. def teardown
  360. Setting.rest_api_enabled = '0'
  361. end
  362. # Uploads content using the XML API and returns the attachment token
  363. def xml_upload(content, credentials)
  364. upload('xml', content, credentials)
  365. end
  366. # Uploads content using the JSON API and returns the attachment token
  367. def json_upload(content, credentials)
  368. upload('json', content, credentials)
  369. end
  370. def upload(format, content, credentials)
  371. set_tmp_attachments_directory
  372. assert_difference 'Attachment.count' do
  373. post(
  374. "/uploads.#{format}",
  375. :params => content,
  376. :headers => {"CONTENT_TYPE" => 'application/octet-stream'}.merge(credentials)
  377. )
  378. assert_response :created
  379. end
  380. data = response_data
  381. assert_kind_of Hash, data['upload']
  382. token = data['upload']['token']
  383. assert_not_nil token
  384. token
  385. end
  386. # Parses the response body based on its content type
  387. def response_data
  388. unless response.media_type.to_s =~ /^application\/(.+)/
  389. raise "Unexpected response type: #{response.media_type}"
  390. end
  391. format = $1
  392. case format
  393. when 'xml'
  394. Hash.from_xml(response.body)
  395. when 'json'
  396. ActiveSupport::JSON.decode(response.body)
  397. else
  398. raise "Unknown response format: #{format}"
  399. end
  400. end
  401. end
  402. class Routing < Redmine::RoutingTest
  403. def should_route(arg)
  404. arg = arg.dup
  405. request = arg.keys.detect {|key| key.is_a?(String)}
  406. raise ArgumentError unless request
  407. options = arg.slice!(request)
  408. API_FORMATS.each do |format|
  409. format_request = request.sub /$/, ".#{format}"
  410. super(options.merge(format_request => arg[request], :format => format))
  411. end
  412. end
  413. end
  414. end
  415. end