]> git.openstreetmap.org Git - rails.git/blob - test/test_helper.rb
Add frozen_string_literal comments to ruby files
[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" unless ENV["CI"]
38
39 WebMock.disable_net_connect!(:allow_localhost => true)
40
41 module ActiveSupport
42   class TestCase
43     include FactoryBot::Syntax::Methods
44     include ActiveJob::TestHelper
45
46     # Run tests in parallel with specified workers
47     parallelize(:workers => :number_of_processors)
48
49     parallelize_setup do |worker|
50       SimpleCov.command_name "#{SimpleCov.command_name}-#{worker}"
51     end
52
53     parallelize_teardown do
54       SimpleCov.result
55     end
56
57     ##
58     # takes a block which is executed in the context of a different
59     # ActionController instance. this is used so that code can call methods
60     # on the node controller whilst testing the old_node controller.
61     def with_controller(new_controller)
62       controller_save = @controller
63       begin
64         @controller = new_controller
65         yield
66       ensure
67         @controller = controller_save
68       end
69     end
70
71     ##
72     # execute a block with missing translation exceptions suppressed
73     def without_i18n_exceptions
74       exception_handler = I18n.exception_handler
75       begin
76         I18n.exception_handler = nil
77         yield
78       ensure
79         I18n.exception_handler = exception_handler
80       end
81     end
82
83     ##
84     # work round minitest insanity that causes it to tell you
85     # to use assert_nil to test for nil, which is fine if you're
86     # comparing to a nil constant but not if you're comparing
87     # an expression that might be nil sometimes
88     def assert_equal_allowing_nil(exp, act, msg = nil)
89       if exp.nil?
90         assert_nil act, msg
91       else
92         assert_equal exp, act, msg
93       end
94     end
95
96     ##
97     # for some reason assert_equal a, b fails when the relations are
98     # actually equal, so this method manually checks the fields...
99     def assert_relations_are_equal(a, b)
100       assert_not_nil a, "first relation is not allowed to be nil"
101       assert_not_nil b, "second relation #{a.id} is not allowed to be nil"
102       assert_equal a.id, b.id, "relation IDs"
103       assert_equal a.changeset_id, b.changeset_id, "changeset ID on relation #{a.id}"
104       assert_equal a.visible, b.visible, "visible on relation #{a.id}, #{a.visible.inspect} != #{b.visible.inspect}"
105       assert_equal a.version, b.version, "version on relation #{a.id}"
106       assert_equal a.tags, b.tags, "tags on relation #{a.id}"
107       assert_equal a.members, b.members, "member references on relation #{a.id}"
108     end
109
110     ##
111     # for some reason assert_equal a, b fails when the ways are actually
112     # equal, so this method manually checks the fields...
113     def assert_ways_are_equal(a, b)
114       assert_not_nil a, "first way is not allowed to be nil"
115       assert_not_nil b, "second way #{a.id} is not allowed to be nil"
116       assert_equal a.id, b.id, "way IDs"
117       assert_equal a.changeset_id, b.changeset_id, "changeset ID on way #{a.id}"
118       assert_equal a.visible, b.visible, "visible on way #{a.id}, #{a.visible.inspect} != #{b.visible.inspect}"
119       assert_equal a.version, b.version, "version on way #{a.id}"
120       assert_equal a.tags, b.tags, "tags on way #{a.id}"
121       assert_equal a.nds, b.nds, "node references on way #{a.id}"
122     end
123
124     ##
125     # for some reason a==b is false, but there doesn't seem to be any
126     # difference between the nodes, so i'm checking all the attributes
127     # manually and blaming it on ActiveRecord
128     def assert_nodes_are_equal(a, b)
129       assert_equal a.id, b.id, "node IDs"
130       assert_equal a.latitude, b.latitude, "latitude on node #{a.id}"
131       assert_equal a.longitude, b.longitude, "longitude on node #{a.id}"
132       assert_equal a.changeset_id, b.changeset_id, "changeset ID on node #{a.id}"
133       assert_equal a.visible, b.visible, "visible on node #{a.id}"
134       assert_equal a.version, b.version, "version on node #{a.id}"
135       assert_equal a.tags, b.tags, "tags on node #{a.id}"
136     end
137
138     ##
139     # return request header for HTTP Bearer Authorization
140     def bearer_authorization_header(token_or_user = nil, scopes: Oauth::SCOPES)
141       token = case token_or_user
142               when nil then create(:oauth_access_token, :scopes => scopes).token
143               when User then create(:oauth_access_token, :user => token_or_user, :scopes => scopes).token
144               when Doorkeeper::AccessToken then token_or_user.token
145               when String then token_or_user
146               end
147
148       { "Authorization" => "Bearer #{token}" }
149     end
150
151     ##
152     # return request header for HTTP Accept
153     def accept_format_header(format)
154       { "Accept" => format }
155     end
156
157     ##
158     # return request header to ask for a particular error format
159     def error_format_header(f)
160       { "X-Error-Format" => f }
161     end
162
163     ##
164     # Used to check that the error header and the forbidden responses are given
165     # when the owner of the changeset has their data not marked as public
166     def assert_require_public_data(msg = "Shouldn't be able to use API when the user's data is not public")
167       assert_response :forbidden, msg
168       assert_equal("You must make your edits public to upload new data", @response.headers["Error"], "Wrong error message")
169     end
170
171     ##
172     # Not sure this is the best response we could give
173     def assert_inactive_user(msg = "an inactive user shouldn't be able to access the API")
174       assert_response :forbidden, msg
175       # assert_equal @response.headers['Error'], ""
176     end
177
178     ##
179     # Check for missing translations in an HTML response
180     def assert_no_missing_translations(msg = "")
181       assert_select "span[class=translation_missing]", false, "Missing translation #{msg}"
182     end
183
184     ##
185     # execute a block with a given set of HTTP responses stubbed
186     def with_http_stubs(stubs_file)
187       stubs = YAML.load_file(File.expand_path("../http/#{stubs_file}.yml", __FILE__))
188       stubs.each do |url, response|
189         stub_request(:get, Regexp.new(Regexp.quote(url))).to_return(:status => response["code"], :body => response["body"])
190       end
191
192       yield
193     end
194
195     def stub_gravatar_request(email, status = 200, body = nil)
196       hash = ::Digest::MD5.hexdigest(email.downcase)
197       url = "https://www.gravatar.com/avatar/#{hash}?d=404"
198       stub_request(:get, url).and_return(:status => status, :body => body)
199     end
200
201     def email_text_parts(message)
202       message.parts.each_with_object([]) do |part, text_parts|
203         if part.content_type.start_with?("text/")
204           text_parts.push(part)
205         elsif part.multipart?
206           text_parts.concat(email_text_parts(part))
207         end
208       end
209     end
210
211     def session_for(user)
212       get login_path
213       post login_path, :params => { :username => user.display_name, :password => "test" }
214       follow_redirect!
215     end
216
217     def xml_for_node(node)
218       doc = OSM::API.new.xml_doc
219       doc.root << xml_node_for_node(node)
220       doc
221     end
222
223     def xml_node_for_node(node)
224       el = XML::Node.new "node"
225       el["id"] = node.id.to_s
226
227       add_metadata_to_xml_node(el, node, {}, {})
228
229       if node.visible?
230         el["lat"] = node.lat.to_s
231         el["lon"] = node.lon.to_s
232       end
233
234       add_tags_to_xml_node(el, node.element_tags)
235
236       el
237     end
238
239     def xml_for_way(way)
240       doc = OSM::API.new.xml_doc
241       doc.root << xml_node_for_way(way)
242       doc
243     end
244
245     def xml_node_for_way(way)
246       el = XML::Node.new "way"
247       el["id"] = way.id.to_s
248
249       add_metadata_to_xml_node(el, way, {}, {})
250
251       # make sure nodes are output in sequence_id order
252       ordered_nodes = []
253       way.way_nodes.each do |nd|
254         ordered_nodes[nd.sequence_id] = nd.node_id.to_s if nd.node&.visible?
255       end
256
257       ordered_nodes.each do |nd_id|
258         next unless nd_id && nd_id != "0"
259
260         node_el = XML::Node.new "nd"
261         node_el["ref"] = nd_id
262         el << node_el
263       end
264
265       add_tags_to_xml_node(el, way.element_tags)
266
267       el
268     end
269
270     def xml_for_relation(relation)
271       doc = OSM::API.new.xml_doc
272       doc.root << xml_node_for_relation(relation)
273       doc
274     end
275
276     def xml_node_for_relation(relation)
277       el = XML::Node.new "relation"
278       el["id"] = relation.id.to_s
279
280       add_metadata_to_xml_node(el, relation, {}, {})
281
282       relation.relation_members.each do |member|
283         member_el = XML::Node.new "member"
284         member_el["type"] = member.member_type.downcase
285         member_el["ref"] = member.member_id.to_s
286         member_el["role"] = member.member_role
287         el << member_el
288       end
289
290       add_tags_to_xml_node(el, relation.element_tags)
291
292       el
293     end
294
295     def add_metadata_to_xml_node(el, osm, changeset_cache, user_display_name_cache)
296       el["changeset"] = osm.changeset_id.to_s
297       el["redacted"] = osm.redaction.id.to_s if osm.redacted?
298       el["timestamp"] = osm.timestamp.xmlschema
299       el["version"] = osm.version.to_s
300       el["visible"] = osm.visible.to_s
301
302       if changeset_cache.key?(osm.changeset_id)
303         # use the cache if available
304       else
305         changeset_cache[osm.changeset_id] = osm.changeset.user_id
306       end
307
308       user_id = changeset_cache[osm.changeset_id]
309
310       if user_display_name_cache.key?(user_id)
311         # use the cache if available
312       elsif osm.changeset.user.data_public?
313         user_display_name_cache[user_id] = osm.changeset.user.display_name
314       else
315         user_display_name_cache[user_id] = nil
316       end
317
318       unless user_display_name_cache[user_id].nil?
319         el["user"] = user_display_name_cache[user_id]
320         el["uid"] = user_id.to_s
321       end
322     end
323
324     def add_tags_to_xml_node(el, tags)
325       tags.each do |tag|
326         tag_el = XML::Node.new("tag")
327
328         tag_el["k"] = tag.k
329         tag_el["v"] = tag.v
330
331         el << tag_el
332       end
333     end
334
335     def with_settings(settings)
336       saved_settings = Settings.to_hash.slice(*settings.keys)
337
338       Settings.merge!(settings)
339
340       yield
341     ensure
342       Settings.merge!(saved_settings)
343     end
344
345     def with_user_account_deletion_delay(value, &)
346       freeze_time
347
348       with_settings(:user_account_deletion_delay => value, &)
349     ensure
350       unfreeze_time
351     end
352
353     # This is a convenience method for checks of resources rendered in a map view sidebar
354     # First we check that when we don't have an id, it will correctly return a 404
355     # then we check that we get the correct 404 when a non-existant id is passed
356     # then we check that it will get a successful response, when we do pass an id
357     def sidebar_browse_check(path, id, template)
358       path_method = method(path)
359
360       assert_raise ActionController::UrlGenerationError do
361         get path_method.call
362       end
363
364       assert_raise ActionController::UrlGenerationError do
365         get path_method.call(:id => -10) # we won't have an id that's negative
366       end
367
368       get path_method.call(:id => 0)
369       assert_response :not_found
370       assert_template "browse/not_found"
371       assert_template :layout => "map"
372
373       get path_method.call(:id => 0), :xhr => true
374       assert_response :not_found
375       assert_template "browse/not_found"
376       assert_template :layout => "xhr"
377
378       get path_method.call(:id => id)
379       assert_response :success
380       assert_template template
381       assert_template :layout => "map"
382
383       get path_method.call(:id => id), :xhr => true
384       assert_response :success
385       assert_template template
386       assert_template :layout => "xhr"
387     end
388   end
389 end