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

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