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

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