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