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