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

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