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

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