]> git.openstreetmap.org Git - rails.git/blob - test/test_helper.rb
Merge remote-tracking branch 'upstream/pull/3257'
[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
36 WebMock.disable_net_connect!(:allow_localhost => true)
37
38 module ActiveSupport
39   class TestCase
40     include FactoryBot::Syntax::Methods
41     include ActiveJob::TestHelper
42
43     # Run tests in parallel with specified workers
44     parallelize(:workers => :number_of_processors)
45
46     parallelize_setup do |worker|
47       SimpleCov.command_name "#{SimpleCov.command_name}-#{worker}"
48     end
49
50     parallelize_teardown do
51       SimpleCov.result
52     end
53
54     ##
55     # takes a block which is executed in the context of a different
56     # ActionController instance. this is used so that code can call methods
57     # on the node controller whilst testing the old_node controller.
58     def with_controller(new_controller)
59       controller_save = @controller
60       begin
61         @controller = new_controller
62         yield
63       ensure
64         @controller = controller_save
65       end
66     end
67
68     ##
69     # execute a block with missing translation exceptions suppressed
70     def without_i18n_exceptions
71       exception_handler = I18n.exception_handler
72       begin
73         I18n.exception_handler = nil
74         yield
75       ensure
76         I18n.exception_handler = exception_handler
77       end
78     end
79
80     ##
81     # work round minitest insanity that causes it to tell you
82     # to use assert_nil to test for nil, which is fine if you're
83     # comparing to a nil constant but not if you're comparing
84     # an expression that might be nil sometimes
85     def assert_equal_allowing_nil(exp, act, msg = nil)
86       if exp.nil?
87         assert_nil act, msg
88       else
89         assert_equal exp, act, msg
90       end
91     end
92
93     ##
94     # for some reason assert_equal a, b fails when the relations are
95     # actually equal, so this method manually checks the fields...
96     def assert_relations_are_equal(a, b)
97       assert_not_nil a, "first relation is not allowed to be nil"
98       assert_not_nil b, "second relation #{a.id} is not allowed to be nil"
99       assert_equal a.id, b.id, "relation IDs"
100       assert_equal a.changeset_id, b.changeset_id, "changeset ID on relation #{a.id}"
101       assert_equal a.visible, b.visible, "visible on relation #{a.id}, #{a.visible.inspect} != #{b.visible.inspect}"
102       assert_equal a.version, b.version, "version on relation #{a.id}"
103       assert_equal a.tags, b.tags, "tags on relation #{a.id}"
104       assert_equal a.members, b.members, "member references on relation #{a.id}"
105     end
106
107     ##
108     # for some reason assert_equal a, b fails when the ways are actually
109     # equal, so this method manually checks the fields...
110     def assert_ways_are_equal(a, b)
111       assert_not_nil a, "first way is not allowed to be nil"
112       assert_not_nil b, "second way #{a.id} is not allowed to be nil"
113       assert_equal a.id, b.id, "way IDs"
114       assert_equal a.changeset_id, b.changeset_id, "changeset ID on way #{a.id}"
115       assert_equal a.visible, b.visible, "visible on way #{a.id}, #{a.visible.inspect} != #{b.visible.inspect}"
116       assert_equal a.version, b.version, "version on way #{a.id}"
117       assert_equal a.tags, b.tags, "tags on way #{a.id}"
118       assert_equal a.nds, b.nds, "node references on way #{a.id}"
119     end
120
121     ##
122     # for some reason a==b is false, but there doesn't seem to be any
123     # difference between the nodes, so i'm checking all the attributes
124     # manually and blaming it on ActiveRecord
125     def assert_nodes_are_equal(a, b)
126       assert_equal a.id, b.id, "node IDs"
127       assert_equal a.latitude, b.latitude, "latitude on node #{a.id}"
128       assert_equal a.longitude, b.longitude, "longitude on node #{a.id}"
129       assert_equal a.changeset_id, b.changeset_id, "changeset ID on node #{a.id}"
130       assert_equal a.visible, b.visible, "visible on node #{a.id}"
131       assert_equal a.version, b.version, "version on node #{a.id}"
132       assert_equal a.tags, b.tags, "tags on node #{a.id}"
133     end
134
135     ##
136     # return request header for HTTP Basic Authorization
137     def basic_authorization_header(user, pass)
138       { "Authorization" => format("Basic %<auth>s", :auth => Base64.encode64("#{user}:#{pass}")) }
139     end
140
141     ##
142     # return request header for HTTP Bearer Authorization
143     def bearer_authorization_header(token)
144       { "Authorization" => "Bearer #{token}" }
145     end
146
147     ##
148     # make an OAuth signed request
149     def signed_request(method, uri, options = {})
150       uri = URI.parse(uri)
151       uri.scheme ||= "http"
152       uri.host ||= "www.example.com"
153
154       oauth = options.delete(:oauth)
155       params = options.fetch(:params, {}).transform_keys(&:to_s)
156
157       oauth[:consumer] ||= oauth[:token].client_application
158
159       helper = OAuth::Client::Helper.new(nil, oauth)
160
161       request = OAuth::RequestProxy.proxy(
162         "method" => method.to_s.upcase,
163         "uri" => uri,
164         "parameters" => params.merge(helper.oauth_parameters)
165       )
166
167       request.sign!(oauth)
168
169       method(method).call(request.signed_uri, **options)
170     end
171
172     ##
173     # make an OAuth signed GET request
174     def signed_get(uri, options = {})
175       signed_request(:get, uri, options)
176     end
177
178     ##
179     # make an OAuth signed POST request
180     def signed_post(uri, options = {})
181       signed_request(:post, uri, options)
182     end
183
184     ##
185     # return request header for HTTP Accept
186     def accept_format_header(format)
187       { "Accept" => format }
188     end
189
190     ##
191     # return request header to ask for a particular error format
192     def error_format_header(f)
193       { "X-Error-Format" => f }
194     end
195
196     ##
197     # Used to check that the error header and the forbidden responses are given
198     # when the owner of the changeset has their data not marked as public
199     def assert_require_public_data(msg = "Shouldn't be able to use API when the user's data is not public")
200       assert_response :forbidden, msg
201       assert_equal("You must make your edits public to upload new data", @response.headers["Error"], "Wrong error message")
202     end
203
204     ##
205     # Not sure this is the best response we could give
206     def assert_inactive_user(msg = "an inactive user shouldn't be able to access the API")
207       assert_response :unauthorized, msg
208       # assert_equal @response.headers['Error'], ""
209     end
210
211     ##
212     # Check for missing translations in an HTML response
213     def assert_no_missing_translations(msg = "")
214       assert_select "span[class=translation_missing]", false, "Missing translation #{msg}"
215     end
216
217     ##
218     # execute a block with a given set of HTTP responses stubbed
219     def with_http_stubs(stubs_file)
220       stubs = YAML.load_file(File.expand_path("../http/#{stubs_file}.yml", __FILE__))
221       stubs.each do |url, response|
222         stub_request(:get, Regexp.new(Regexp.quote(url))).to_return(:status => response["code"], :body => response["body"])
223       end
224
225       yield
226     end
227
228     def stub_gravatar_request(email, status = 200, body = nil)
229       hash = ::Digest::MD5.hexdigest(email.downcase)
230       url = "https://www.gravatar.com/avatar/#{hash}?d=404"
231       stub_request(:get, url).and_return(:status => status, :body => body)
232     end
233
234     def email_text_parts(message)
235       message.parts.each_with_object([]) do |part, text_parts|
236         if part.content_type.start_with?("text/")
237           text_parts.push(part)
238         elsif part.multipart?
239           text_parts.concat(email_text_parts(part))
240         end
241       end
242     end
243
244     def sign_in_as(user)
245       visit login_path
246       fill_in "username", :with => user.email
247       fill_in "password", :with => "test"
248       click_on "Login", :match => :first
249     end
250
251     def session_for(user)
252       get login_path
253       post login_path, :params => { :username => user.display_name, :password => "test" }
254       follow_redirect!
255     end
256
257     def xml_for_node(node)
258       doc = OSM::API.new.get_xml_doc
259       doc.root << xml_node_for_node(node)
260       doc
261     end
262
263     def xml_node_for_node(node)
264       el = XML::Node.new "node"
265       el["id"] = node.id.to_s
266
267       OMHelper.add_metadata_to_xml_node(el, node, {}, {})
268
269       if node.visible?
270         el["lat"] = node.lat.to_s
271         el["lon"] = node.lon.to_s
272       end
273
274       OMHelper.add_tags_to_xml_node(el, node.node_tags)
275
276       el
277     end
278
279     def xml_for_way(way)
280       doc = OSM::API.new.get_xml_doc
281       doc.root << xml_node_for_way(way)
282       doc
283     end
284
285     def xml_node_for_way(way)
286       el = XML::Node.new "way"
287       el["id"] = way.id.to_s
288
289       OMHelper.add_metadata_to_xml_node(el, way, {}, {})
290
291       # make sure nodes are output in sequence_id order
292       ordered_nodes = []
293       way.way_nodes.each do |nd|
294         ordered_nodes[nd.sequence_id] = nd.node_id.to_s if nd.node&.visible?
295       end
296
297       ordered_nodes.each do |nd_id|
298         next unless nd_id && nd_id != "0"
299
300         node_el = XML::Node.new "nd"
301         node_el["ref"] = nd_id
302         el << node_el
303       end
304
305       OMHelper.add_tags_to_xml_node(el, way.way_tags)
306
307       el
308     end
309
310     def xml_for_relation(relation)
311       doc = OSM::API.new.get_xml_doc
312       doc.root << xml_node_for_relation(relation)
313       doc
314     end
315
316     def xml_node_for_relation(relation)
317       el = XML::Node.new "relation"
318       el["id"] = relation.id.to_s
319
320       OMHelper.add_metadata_to_xml_node(el, relation, {}, {})
321
322       relation.relation_members.each do |member|
323         member_el = XML::Node.new "member"
324         member_el["type"] = member.member_type.downcase
325         member_el["ref"] = member.member_id.to_s
326         member_el["role"] = member.member_role
327         el << member_el
328       end
329
330       OMHelper.add_tags_to_xml_node(el, relation.relation_tags)
331
332       el
333     end
334
335     class OMHelper
336       extend ObjectMetadata
337     end
338   end
339 end