]> git.openstreetmap.org Git - rails.git/blob - test/test_helper.rb
Merge remote-tracking branch 'upstream/pull/7504'
[rails.git] / test / test_helper.rb
1 # frozen_string_literal: true
2
3 require "simplecov"
4 require "simplecov-lcov"
5
6 # Fix incompatibility of simplecov-lcov with older versions of simplecov that are not expresses in its gemspec.
7 # https://github.com/fortissimo1997/simplecov-lcov/pull/25
8 unless SimpleCov.respond_to?(:branch_coverage)
9   module SimpleCov
10     def self.branch_coverage?
11       false
12     end
13   end
14 end
15
16 SimpleCov::Formatter::LcovFormatter.config do |config|
17   config.report_with_single_file = true
18   config.single_report_path = "coverage/lcov.info"
19 end
20
21 SimpleCov.formatters = SimpleCov::Formatter::MultiFormatter.new(
22   [
23     SimpleCov::Formatter::HTMLFormatter,
24     SimpleCov::Formatter::LcovFormatter
25   ]
26 )
27
28 SimpleCov.start("rails")
29
30 require "securerandom"
31 require "digest/sha1"
32
33 ENV["RAILS_ENV"] = "test"
34 require_relative "../config/environment"
35 require "rails/test_help"
36 require "webmock/minitest"
37 require "minitest/focus"
38
39 WebMock.disable_net_connect!(:allow_localhost => true, :allow => %w[selenium-default selenium-de selenium-nolang rails-app])
40
41 # Scan each job performed for N+1 queries, in the same way as requests are
42 # scanned (see config/initializers/prosopite.rb).
43 #
44 # Jobs performed during a request, using perform_enqueued_jobs, aren't
45 # scanned as their queries would otherwise count towards the request's,
46 # whereas in production each job is performed separately.
47 ActiveJob::Base.around_perform do |_job, block|
48   if Prosopite.scan?
49     Prosopite.pause { block.call }
50   else
51     Prosopite.scan { block.call }
52   end
53 end
54
55 module ActiveSupport
56   class TestCase
57     include FactoryBot::Syntax::Methods
58     include ActiveJob::TestHelper
59     include LibXML
60
61     if ENV.key?("CAPYBARA_SERVER_PORT")
62       # Running in the devcontainer. Can't figure out how
63       # to run things in parallel at the moment, so for now
64       # we are not doing it.
65     elsif Settings.enable_parallel_tests
66       # Run tests in parallel with specified workers
67       parallelize(:workers => :number_of_processors)
68
69       parallelize_setup do |worker|
70         SimpleCov.command_name "#{SimpleCov.command_name}-#{worker}"
71       end
72
73       parallelize_teardown do
74         SimpleCov.result
75       end
76     end
77
78     ##
79     # takes a block which is executed in the context of a different
80     # ActionController instance. this is used so that code can call methods
81     # on the node controller whilst testing the old_node controller.
82     def with_controller(new_controller)
83       controller_save = @controller
84       begin
85         @controller = new_controller
86         yield
87       ensure
88         @controller = controller_save
89       end
90     end
91
92     ##
93     # execute a block with missing translation exceptions suppressed
94     def without_i18n_exceptions
95       exception_handler = I18n.exception_handler
96       begin
97         I18n.exception_handler = nil
98         yield
99       ensure
100         I18n.exception_handler = exception_handler
101       end
102     end
103
104     ##
105     # work round minitest insanity that causes it to tell you
106     # to use assert_nil to test for nil, which is fine if you're
107     # comparing to a nil constant but not if you're comparing
108     # an expression that might be nil sometimes
109     def assert_equal_allowing_nil(exp, act, msg = nil)
110       if exp.nil?
111         assert_nil act, msg
112       else
113         assert_equal exp, act, msg
114       end
115     end
116
117     ##
118     # for some reason assert_equal a, b fails when the relations are
119     # actually equal, so this method manually checks the fields...
120     def assert_relations_are_equal(a, b)
121       assert_not_nil a, "first relation is not allowed to be nil"
122       assert_not_nil b, "second relation #{a.id} is not allowed to be nil"
123       assert_equal a.id, b.id, "relation IDs"
124       assert_equal a.changeset_id, b.changeset_id, "changeset ID on relation #{a.id}"
125       assert_equal a.visible, b.visible, "visible on relation #{a.id}, #{a.visible.inspect} != #{b.visible.inspect}"
126       assert_equal a.version, b.version, "version on relation #{a.id}"
127       assert_equal a.tags, b.tags, "tags on relation #{a.id}"
128       assert_equal a.members, b.members, "member references on relation #{a.id}"
129     end
130
131     ##
132     # for some reason assert_equal a, b fails when the ways are actually
133     # equal, so this method manually checks the fields...
134     def assert_ways_are_equal(a, b)
135       assert_not_nil a, "first way is not allowed to be nil"
136       assert_not_nil b, "second way #{a.id} is not allowed to be nil"
137       assert_equal a.id, b.id, "way IDs"
138       assert_equal a.changeset_id, b.changeset_id, "changeset ID on way #{a.id}"
139       assert_equal a.visible, b.visible, "visible on way #{a.id}, #{a.visible.inspect} != #{b.visible.inspect}"
140       assert_equal a.version, b.version, "version on way #{a.id}"
141       assert_equal a.tags, b.tags, "tags on way #{a.id}"
142       assert_equal a.nds, b.nds, "node references on way #{a.id}"
143     end
144
145     ##
146     # for some reason a==b is false, but there doesn't seem to be any
147     # difference between the nodes, so i'm checking all the attributes
148     # manually and blaming it on ActiveRecord
149     def assert_nodes_are_equal(a, b)
150       assert_equal a.id, b.id, "node IDs"
151       assert_equal a.latitude, b.latitude, "latitude on node #{a.id}"
152       assert_equal a.longitude, b.longitude, "longitude on node #{a.id}"
153       assert_equal a.changeset_id, b.changeset_id, "changeset ID on node #{a.id}"
154       assert_equal a.visible, b.visible, "visible on node #{a.id}"
155       assert_equal a.version, b.version, "version on node #{a.id}"
156       assert_equal a.tags, b.tags, "tags on node #{a.id}"
157     end
158
159     ##
160     # return request header for HTTP Bearer Authorization
161     def bearer_authorization_header(token_or_user = nil, scopes: Oauth::SCOPES)
162       token = case token_or_user
163               when nil then create(:oauth_access_token, :scopes => scopes).token
164               when User then create(:oauth_access_token, :user => token_or_user, :scopes => scopes).token
165               when Doorkeeper::AccessToken then token_or_user.token
166               when String then token_or_user
167               end
168
169       { "Authorization" => "Bearer #{token}" }
170     end
171
172     ##
173     # return request header for HTTP Accept
174     def accept_format_header(format)
175       { "Accept" => format }
176     end
177
178     ##
179     # return request header to ask for a particular error format
180     def error_format_header(f)
181       { "X-Error-Format" => f }
182     end
183
184     ##
185     # Used to check that the error header and the forbidden responses are given
186     # when the owner of the changeset has their data not marked as public
187     def assert_require_public_data(msg = "Shouldn't be able to use API when the user's data is not public")
188       assert_response :forbidden, msg
189       assert_equal("You must make your edits public to upload new data", @response.headers["Error"], "Wrong error message")
190     end
191
192     ##
193     # Not sure this is the best response we could give
194     def assert_inactive_user(msg = "an inactive user shouldn't be able to access the API")
195       assert_response :forbidden, msg
196       # assert_equal @response.headers['Error'], ""
197     end
198
199     ##
200     # Check for missing translations in an HTML response
201     def assert_no_missing_translations(msg = "")
202       assert_select "span[class=translation_missing]", false, "Missing translation #{msg}"
203     end
204
205     ##
206     # Check that an email was received on the given email address,
207     # with the given subject. Note that it assumes that there's only
208     # one recipient and will fail otherwise. If you need a different
209     # behaviour, please extend.
210     def assert_email_received(expected_address, expected_subject)
211       email = ActionMailer::Base.deliveries.find { |e| e.to.first == expected_address }
212       assert_not_nil email
213       assert_equal 1, email.to.length
214       assert_equal expected_address, email.to.first
215       assert_equal expected_subject, email.subject
216     end
217
218     ##
219     # Check that no email was received on the given email address.
220     # Note that this assumes that any emails have only one recipient,
221     # and may give incorrect results otherwise. If you need a different
222     # behaviour, please extend.
223     def assert_email_not_received(expected_address)
224       email = ActionMailer::Base.deliveries.find { |e| e.to.first == expected_address }
225       assert_nil email
226     end
227
228     ##
229     # execute a block with a given set of HTTP responses stubbed
230     def with_http_stubs(stubs_file)
231       stubs = YAML.load_file(File.expand_path("../http/#{stubs_file}.yml", __FILE__))
232       stubs.each do |url, response|
233         stub_request(:get, Regexp.new(Regexp.quote(url))).to_return(:status => response["code"], :body => response["body"])
234       end
235
236       yield
237     end
238
239     def stub_gravatar_request(email, status = 200, body = nil)
240       hash = ::Digest::MD5.hexdigest(email.downcase)
241       url = "https://www.gravatar.com/avatar/#{hash}?d=404"
242       stub_request(:get, url).and_return(:status => status, :body => body)
243     end
244
245     def email_text_parts(message)
246       message.parts.each_with_object([]) do |part, text_parts|
247         if part.content_type.start_with?("text/")
248           text_parts.push(part)
249         elsif part.multipart?
250           text_parts.concat(email_text_parts(part))
251         end
252       end
253     end
254
255     def session_for(user)
256       get login_path
257       post login_path, :params => { :username => user.display_name, :password => "s3cr3t" }
258       follow_redirect!
259     end
260
261     def xml_for_node(node)
262       doc = OSM::API.new.xml_doc
263       doc.root << xml_node_for_node(node)
264       doc
265     end
266
267     def xml_node_for_node(node)
268       el = XML::Node.new "node"
269       el["id"] = node.id.to_s
270
271       add_metadata_to_xml_node(el, node, {}, {})
272
273       if node.visible?
274         el["lat"] = node.lat.to_s
275         el["lon"] = node.lon.to_s
276       end
277
278       add_tags_to_xml_node(el, node.element_tags)
279
280       el
281     end
282
283     def xml_for_way(way)
284       doc = OSM::API.new.xml_doc
285       doc.root << xml_node_for_way(way)
286       doc
287     end
288
289     def xml_node_for_way(way)
290       el = XML::Node.new "way"
291       el["id"] = way.id.to_s
292
293       add_metadata_to_xml_node(el, way, {}, {})
294
295       # make sure nodes are output in sequence_id order
296       ordered_nodes = []
297       way.way_nodes.each do |nd|
298         ordered_nodes[nd.sequence_id] = nd.node_id.to_s if nd.node&.visible?
299       end
300
301       ordered_nodes.each do |nd_id|
302         next unless nd_id && nd_id != "0"
303
304         node_el = XML::Node.new "nd"
305         node_el["ref"] = nd_id
306         el << node_el
307       end
308
309       add_tags_to_xml_node(el, way.element_tags)
310
311       el
312     end
313
314     def xml_for_relation(relation)
315       doc = OSM::API.new.xml_doc
316       doc.root << xml_node_for_relation(relation)
317       doc
318     end
319
320     def xml_node_for_relation(relation)
321       el = XML::Node.new "relation"
322       el["id"] = relation.id.to_s
323
324       add_metadata_to_xml_node(el, relation, {}, {})
325
326       relation.relation_members.each do |member|
327         member_el = XML::Node.new "member"
328         member_el["type"] = member.member_type.downcase
329         member_el["ref"] = member.member_id.to_s
330         member_el["role"] = member.member_role
331         el << member_el
332       end
333
334       add_tags_to_xml_node(el, relation.element_tags)
335
336       el
337     end
338
339     def add_metadata_to_xml_node(el, osm, changeset_cache, user_display_name_cache)
340       el["changeset"] = osm.changeset_id.to_s
341       el["redacted"] = osm.redaction.id.to_s if osm.redacted?
342       el["timestamp"] = osm.timestamp.xmlschema
343       el["version"] = osm.version.to_s
344       el["visible"] = osm.visible.to_s
345
346       if changeset_cache.key?(osm.changeset_id)
347         # use the cache if available
348       else
349         changeset_cache[osm.changeset_id] = osm.changeset.user_id
350       end
351
352       user_id = changeset_cache[osm.changeset_id]
353
354       if user_display_name_cache.key?(user_id)
355         # use the cache if available
356       elsif osm.changeset.user.data_public?
357         user_display_name_cache[user_id] = osm.changeset.user.display_name
358       else
359         user_display_name_cache[user_id] = nil
360       end
361
362       unless user_display_name_cache[user_id].nil?
363         el["user"] = user_display_name_cache[user_id]
364         el["uid"] = user_id.to_s
365       end
366     end
367
368     def add_tags_to_xml_node(el, tags)
369       tags.each do |tag|
370         tag_el = XML::Node.new("tag")
371
372         tag_el["k"] = tag.k
373         tag_el["v"] = tag.v
374
375         el << tag_el
376       end
377     end
378
379     def with_settings(settings)
380       saved_settings = Settings.to_hash.slice(*settings.keys)
381
382       settings.each_key do |key|
383         saved_settings[key] = nil unless saved_settings.key?(key)
384       end
385
386       Settings.merge!(settings)
387
388       yield
389     ensure
390       Settings.merge!(saved_settings)
391     end
392
393     def with_user_account_deletion_delay(value, &)
394       freeze_time
395
396       with_settings(:user_account_deletion_delay => value, &)
397     ensure
398       unfreeze_time
399     end
400
401     # This is a convenience method for checks of resources rendered in a map view sidebar
402     # First we check that when we don't have an id, it will correctly return a 404
403     # then we check that we get the correct 404 when a non-existent id is passed
404     # then we check that it will get a successful response, when we do pass an id
405     def sidebar_browse_check(path, id, template)
406       path_method = method(path)
407
408       assert_raise ActionController::UrlGenerationError do
409         get path_method.call
410       end
411
412       assert_raise ActionController::UrlGenerationError do
413         get path_method.call(:id => -10) # we won't have an id that's negative
414       end
415
416       get path_method.call(:id => 0)
417       assert_response :not_found
418       assert_template "browse/not_found"
419       assert_template :layout => "map"
420
421       get path_method.call(:id => 0), :headers => { "Turbo-Frame" => "sidebar_content_frame" }
422       assert_response :not_found
423       assert_template "browse/not_found"
424       assert_template :layout => "xhr"
425
426       get path_method.call(:id => id)
427       assert_response :success
428       assert_template template
429       assert_template :layout => "map"
430
431       get path_method.call(:id => id), :headers => { "Turbo-Frame" => "sidebar_content_frame" }
432       assert_response :success
433       assert_template template
434       assert_template :layout => "xhr"
435     end
436
437     def parse_html(html)
438       Rails::Dom::Testing.html_document_fragment.parse(html)
439     end
440
441     def read_fixture_file(relpath)
442       Rails.root.join("test", "fixtures", relpath).read
443     end
444   end
445 end