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

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