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

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