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

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