]> git.openstreetmap.org Git - rails.git/blob - test/controllers/api/relations_controller_test.rb
Remove with_update_* block/yield
[rails.git] / test / controllers / api / relations_controller_test.rb
1 require "test_helper"
2
3 module Api
4   class RelationsControllerTest < ActionDispatch::IntegrationTest
5     ##
6     # test all routes which lead to this controller
7     def test_routes
8       assert_routing(
9         { :path => "/api/0.6/relations", :method => :get },
10         { :controller => "api/relations", :action => "index" }
11       )
12       assert_routing(
13         { :path => "/api/0.6/relations.json", :method => :get },
14         { :controller => "api/relations", :action => "index", :format => "json" }
15       )
16       assert_routing(
17         { :path => "/api/0.6/relations", :method => :post },
18         { :controller => "api/relations", :action => "create" }
19       )
20       assert_routing(
21         { :path => "/api/0.6/relation/1", :method => :get },
22         { :controller => "api/relations", :action => "show", :id => "1" }
23       )
24       assert_routing(
25         { :path => "/api/0.6/relation/1.json", :method => :get },
26         { :controller => "api/relations", :action => "show", :id => "1", :format => "json" }
27       )
28       assert_routing(
29         { :path => "/api/0.6/relation/1/full", :method => :get },
30         { :controller => "api/relations", :action => "show", :full => true, :id => "1" }
31       )
32       assert_routing(
33         { :path => "/api/0.6/relation/1/full.json", :method => :get },
34         { :controller => "api/relations", :action => "show", :full => true, :id => "1", :format => "json" }
35       )
36       assert_routing(
37         { :path => "/api/0.6/relation/1", :method => :put },
38         { :controller => "api/relations", :action => "update", :id => "1" }
39       )
40       assert_routing(
41         { :path => "/api/0.6/relation/1", :method => :delete },
42         { :controller => "api/relations", :action => "destroy", :id => "1" }
43       )
44
45       assert_recognizes(
46         { :controller => "api/relations", :action => "create" },
47         { :path => "/api/0.6/relation/create", :method => :put }
48       )
49     end
50
51     ##
52     # test fetching multiple relations
53     def test_index
54       relation1 = create(:relation)
55       relation2 = create(:relation, :deleted)
56       relation3 = create(:relation, :with_history, :version => 2)
57       relation4 = create(:relation, :with_history, :version => 2)
58       relation4.old_relations.find_by(:version => 1).redact!(create(:redaction))
59
60       # check error when no parameter provided
61       get api_relations_path
62       assert_response :bad_request
63
64       # check error when no parameter value provided
65       get api_relations_path(:relations => "")
66       assert_response :bad_request
67
68       # test a working call
69       get api_relations_path(:relations => "#{relation1.id},#{relation2.id},#{relation3.id},#{relation4.id}")
70       assert_response :success
71       assert_select "osm" do
72         assert_select "relation", :count => 4
73         assert_select "relation[id='#{relation1.id}'][visible='true']", :count => 1
74         assert_select "relation[id='#{relation2.id}'][visible='false']", :count => 1
75         assert_select "relation[id='#{relation3.id}'][visible='true']", :count => 1
76         assert_select "relation[id='#{relation4.id}'][visible='true']", :count => 1
77       end
78
79       # test a working call with json format
80       get api_relations_path(:relations => "#{relation1.id},#{relation2.id},#{relation3.id},#{relation4.id}", :format => "json")
81
82       js = ActiveSupport::JSON.decode(@response.body)
83       assert_not_nil js
84       assert_equal 4, js["elements"].count
85       assert_equal 4, (js["elements"].count { |a| a["type"] == "relation" })
86       assert_equal 1, (js["elements"].count { |a| a["id"] == relation1.id && a["visible"].nil? })
87       assert_equal 1, (js["elements"].count { |a| a["id"] == relation2.id && a["visible"] == false })
88       assert_equal 1, (js["elements"].count { |a| a["id"] == relation3.id && a["visible"].nil? })
89       assert_equal 1, (js["elements"].count { |a| a["id"] == relation4.id && a["visible"].nil? })
90
91       # check error when a non-existent relation is included
92       get api_relations_path(:relations => "#{relation1.id},#{relation2.id},#{relation3.id},#{relation4.id},0")
93       assert_response :not_found
94     end
95
96     # -------------------------------------
97     # Test showing relations.
98     # -------------------------------------
99
100     def test_show_not_found
101       get api_relation_path(0)
102       assert_response :not_found
103     end
104
105     def test_show_deleted
106       get api_relation_path(create(:relation, :deleted))
107       assert_response :gone
108     end
109
110     def test_show
111       relation = create(:relation, :timestamp => "2021-02-03T00:00:00Z")
112       node = create(:node, :timestamp => "2021-04-05T00:00:00Z")
113       create(:relation_member, :relation => relation, :member => node)
114
115       get api_relation_path(relation)
116
117       assert_response :success
118       assert_not_nil @response.header["Last-Modified"]
119       assert_equal "2021-02-03T00:00:00Z", Time.parse(@response.header["Last-Modified"]).utc.xmlschema
120       assert_dom "node", :count => 0
121       assert_dom "relation", :count => 1 do
122         assert_dom "> @id", :text => relation.id.to_s
123       end
124     end
125
126     def test_full_not_found
127       get api_relation_path(999999, :full => true)
128       assert_response :not_found
129     end
130
131     def test_full_deleted
132       get api_relation_path(create(:relation, :deleted), :full => true)
133       assert_response :gone
134     end
135
136     def test_full_empty
137       relation = create(:relation)
138
139       get api_relation_path(relation, :full => true)
140
141       assert_response :success
142       assert_dom "relation", :count => 1 do
143         assert_dom "> @id", :text => relation.id.to_s
144       end
145     end
146
147     def test_full_with_node_member
148       relation = create(:relation)
149       node = create(:node)
150       create(:relation_member, :relation => relation, :member => node)
151
152       get api_relation_path(relation, :full => true)
153
154       assert_response :success
155       assert_dom "node", :count => 1 do
156         assert_dom "> @id", :text => node.id.to_s
157       end
158       assert_dom "relation", :count => 1 do
159         assert_dom "> @id", :text => relation.id.to_s
160       end
161     end
162
163     def test_full_with_way_member
164       relation = create(:relation)
165       way = create(:way_with_nodes)
166       create(:relation_member, :relation => relation, :member => way)
167
168       get api_relation_path(relation, :full => true)
169
170       assert_response :success
171       assert_dom "node", :count => 1 do
172         assert_dom "> @id", :text => way.nodes[0].id.to_s
173       end
174       assert_dom "way", :count => 1 do
175         assert_dom "> @id", :text => way.id.to_s
176       end
177       assert_dom "relation", :count => 1 do
178         assert_dom "> @id", :text => relation.id.to_s
179       end
180     end
181
182     def test_full_with_node_member_json
183       relation = create(:relation)
184       node = create(:node)
185       create(:relation_member, :relation => relation, :member => node)
186
187       get api_relation_path(relation, :full => true, :format => "json")
188
189       assert_response :success
190       js = ActiveSupport::JSON.decode(@response.body)
191       assert_not_nil js
192       assert_equal 2, js["elements"].count
193
194       js_relations = js["elements"].filter { |e| e["type"] == "relation" }
195       assert_equal 1, js_relations.count
196       assert_equal relation.id, js_relations[0]["id"]
197       assert_equal 1, js_relations[0]["members"].count
198       assert_equal "node", js_relations[0]["members"][0]["type"]
199       assert_equal node.id, js_relations[0]["members"][0]["ref"]
200
201       js_nodes = js["elements"].filter { |e| e["type"] == "node" }
202       assert_equal 1, js_nodes.count
203       assert_equal node.id, js_nodes[0]["id"]
204     end
205
206     # -------------------------------------
207     # Test simple relation creation.
208     # -------------------------------------
209
210     def test_create
211       private_user = create(:user, :data_public => false)
212       private_changeset = create(:changeset, :user => private_user)
213       user = create(:user)
214       changeset = create(:changeset, :user => user)
215       node = create(:node)
216       way = create(:way_with_nodes, :nodes_count => 2)
217
218       auth_header = bearer_authorization_header private_user
219
220       # create an relation without members
221       xml = "<osm><relation changeset='#{private_changeset.id}'><tag k='test' v='yes' /></relation></osm>"
222       post api_relations_path, :params => xml, :headers => auth_header
223       # hope for forbidden, due to user
224       assert_response :forbidden,
225                       "relation upload should have failed with forbidden"
226
227       ###
228       # create an relation with a node as member
229       # This time try with a role attribute in the relation
230       xml = "<osm><relation changeset='#{private_changeset.id}'>" \
231             "<member  ref='#{node.id}' type='node' role='some'/>" \
232             "<tag k='test' v='yes' /></relation></osm>"
233       post api_relations_path, :params => xml, :headers => auth_header
234       # hope for forbidden due to user
235       assert_response :forbidden,
236                       "relation upload did not return forbidden status"
237
238       ###
239       # create an relation with a node as member, this time test that we don't
240       # need a role attribute to be included
241       xml = "<osm><relation changeset='#{private_changeset.id}'>" \
242             "<member  ref='#{node.id}' type='node'/><tag k='test' v='yes' /></relation></osm>"
243       post api_relations_path, :params => xml, :headers => auth_header
244       # hope for forbidden due to user
245       assert_response :forbidden,
246                       "relation upload did not return forbidden status"
247
248       ###
249       # create an relation with a way and a node as members
250       xml = "<osm><relation changeset='#{private_changeset.id}'>" \
251             "<member type='node' ref='#{node.id}' role='some'/>" \
252             "<member type='way' ref='#{way.id}' role='other'/>" \
253             "<tag k='test' v='yes' /></relation></osm>"
254       post api_relations_path, :params => xml, :headers => auth_header
255       # hope for forbidden, due to user
256       assert_response :forbidden,
257                       "relation upload did not return success status"
258
259       ## Now try with the public user
260       auth_header = bearer_authorization_header user
261
262       # create an relation without members
263       xml = "<osm><relation changeset='#{changeset.id}'><tag k='test' v='yes' /></relation></osm>"
264       post api_relations_path, :params => xml, :headers => auth_header
265       # hope for success
266       assert_response :success,
267                       "relation upload did not return success status"
268       # read id of created relation and search for it
269       relationid = @response.body
270       checkrelation = Relation.find(relationid)
271       assert_not_nil checkrelation,
272                      "uploaded relation not found in data base after upload"
273       # compare values
274       assert_equal(0, checkrelation.members.length, "saved relation contains members but should not")
275       assert_equal(1, checkrelation.tags.length, "saved relation does not contain exactly one tag")
276       assert_equal changeset.id, checkrelation.changeset.id,
277                    "saved relation does not belong in the changeset it was assigned to"
278       assert_equal user.id, checkrelation.changeset.user_id,
279                    "saved relation does not belong to user that created it"
280       assert checkrelation.visible,
281              "saved relation is not visible"
282       # ok the relation is there but can we also retrieve it?
283       get api_relation_path(relationid)
284       assert_response :success
285
286       ###
287       # create an relation with a node as member
288       # This time try with a role attribute in the relation
289       xml = "<osm><relation changeset='#{changeset.id}'>" \
290             "<member  ref='#{node.id}' type='node' role='some'/>" \
291             "<tag k='test' v='yes' /></relation></osm>"
292       post api_relations_path, :params => xml, :headers => auth_header
293       # hope for success
294       assert_response :success,
295                       "relation upload did not return success status"
296       # read id of created relation and search for it
297       relationid = @response.body
298       checkrelation = Relation.find(relationid)
299       assert_not_nil checkrelation,
300                      "uploaded relation not found in data base after upload"
301       # compare values
302       assert_equal(1, checkrelation.members.length, "saved relation does not contain exactly one member")
303       assert_equal(1, checkrelation.tags.length, "saved relation does not contain exactly one tag")
304       assert_equal changeset.id, checkrelation.changeset.id,
305                    "saved relation does not belong in the changeset it was assigned to"
306       assert_equal user.id, checkrelation.changeset.user_id,
307                    "saved relation does not belong to user that created it"
308       assert checkrelation.visible,
309              "saved relation is not visible"
310       # ok the relation is there but can we also retrieve it?
311
312       get api_relation_path(relationid)
313       assert_response :success
314
315       ###
316       # create an relation with a node as member, this time test that we don't
317       # need a role attribute to be included
318       xml = "<osm><relation changeset='#{changeset.id}'>" \
319             "<member  ref='#{node.id}' type='node'/><tag k='test' v='yes' /></relation></osm>"
320       post api_relations_path, :params => xml, :headers => auth_header
321       # hope for success
322       assert_response :success,
323                       "relation upload did not return success status"
324       # read id of created relation and search for it
325       relationid = @response.body
326       checkrelation = Relation.find(relationid)
327       assert_not_nil checkrelation,
328                      "uploaded relation not found in data base after upload"
329       # compare values
330       assert_equal(1, checkrelation.members.length, "saved relation does not contain exactly one member")
331       assert_equal(1, checkrelation.tags.length, "saved relation does not contain exactly one tag")
332       assert_equal changeset.id, checkrelation.changeset.id,
333                    "saved relation does not belong in the changeset it was assigned to"
334       assert_equal user.id, checkrelation.changeset.user_id,
335                    "saved relation does not belong to user that created it"
336       assert checkrelation.visible,
337              "saved relation is not visible"
338       # ok the relation is there but can we also retrieve it?
339
340       get api_relation_path(relationid)
341       assert_response :success
342
343       ###
344       # create an relation with a way and a node as members
345       xml = "<osm><relation changeset='#{changeset.id}'>" \
346             "<member type='node' ref='#{node.id}' role='some'/>" \
347             "<member type='way' ref='#{way.id}' role='other'/>" \
348             "<tag k='test' v='yes' /></relation></osm>"
349       post api_relations_path, :params => xml, :headers => auth_header
350       # hope for success
351       assert_response :success,
352                       "relation upload did not return success status"
353       # read id of created relation and search for it
354       relationid = @response.body
355       checkrelation = Relation.find(relationid)
356       assert_not_nil checkrelation,
357                      "uploaded relation not found in data base after upload"
358       # compare values
359       assert_equal(2, checkrelation.members.length, "saved relation does not have exactly two members")
360       assert_equal(1, checkrelation.tags.length, "saved relation does not contain exactly one tag")
361       assert_equal changeset.id, checkrelation.changeset.id,
362                    "saved relation does not belong in the changeset it was assigned to"
363       assert_equal user.id, checkrelation.changeset.user_id,
364                    "saved relation does not belong to user that created it"
365       assert checkrelation.visible,
366              "saved relation is not visible"
367       # ok the relation is there but can we also retrieve it?
368       get api_relation_path(relationid)
369       assert_response :success
370     end
371
372     # ------------------------------------
373     # Test updating relations
374     # ------------------------------------
375
376     ##
377     # test that, when tags are updated on a relation, the correct things
378     # happen to the correct tables and the API gives sensible results.
379     # this is to test a case that gregory marler noticed and posted to
380     # josm-dev.
381     ## FIXME Move this to an integration test
382     def test_update_relation_tags
383       user = create(:user)
384       changeset = create(:changeset, :user => user)
385       relation = create(:relation)
386       create_list(:relation_tag, 4, :relation => relation)
387
388       auth_header = bearer_authorization_header user
389
390       get api_relation_path(relation)
391       assert_response :success
392       rel = xml_parse(@response.body)
393       rel_id = rel.find("//osm/relation").first["id"].to_i
394
395       # alter one of the tags
396       tag = rel.find("//osm/relation/tag").first
397       tag["v"] = "some changed value"
398       update_changeset(rel, changeset.id)
399
400       # check that the downloaded tags are the same as the uploaded tags...
401       new_version = do_update(rel, rel_id, auth_header)
402       get api_relation_path(rel_id)
403       assert_response :success
404       assert_tags_equal rel, xml_parse(@response.body)
405
406       # check the original one in the current_* table again
407       get api_relation_path(relation)
408       assert_response :success
409       assert_tags_equal rel, xml_parse(@response.body)
410
411       # now check the version in the history
412       get api_relation_version_path(relation, new_version)
413       assert_response :success
414       assert_tags_equal rel, xml_parse(@response.body)
415     end
416
417     ##
418     # test that, when tags are updated on a relation when using the diff
419     # upload function, the correct things happen to the correct tables
420     # and the API gives sensible results. this is to test a case that
421     # gregory marler noticed and posted to josm-dev.
422     def test_update_relation_tags_via_upload
423       user = create(:user)
424       changeset = create(:changeset, :user => user)
425       relation = create(:relation)
426       create_list(:relation_tag, 4, :relation => relation)
427
428       auth_header = bearer_authorization_header user
429
430       get api_relation_path(relation)
431       assert_response :success
432       rel = xml_parse(@response.body)
433       rel_id = rel.find("//osm/relation").first["id"].to_i
434
435       # alter one of the tags
436       tag = rel.find("//osm/relation/tag").first
437       tag["v"] = "some changed value"
438       update_changeset(rel, changeset.id)
439
440       # check that the downloaded tags are the same as the uploaded tags...
441       new_version = do_update_diff(rel, auth_header)
442       get api_relation_path(rel_id)
443       assert_response :success
444       assert_tags_equal rel, xml_parse(@response.body)
445
446       # check the original one in the current_* table again
447       get api_relation_path(relation)
448       assert_response :success
449       assert_tags_equal rel, xml_parse(@response.body)
450
451       # now check the version in the history
452       get api_relation_version_path(relation, new_version)
453       assert_response :success
454       assert_tags_equal rel, xml_parse(@response.body)
455     end
456
457     def test_update_wrong_id
458       user = create(:user)
459       changeset = create(:changeset, :user => user)
460       relation = create(:relation)
461       other_relation = create(:relation)
462
463       auth_header = bearer_authorization_header user
464       get api_relation_path(relation)
465       assert_response :success
466       rel = xml_parse(@response.body)
467
468       update_changeset(rel, changeset.id)
469       put api_relation_path(other_relation), :params => rel.to_s, :headers => auth_header
470       assert_response :bad_request
471     end
472
473     # -------------------------------------
474     # Test creating some invalid relations.
475     # -------------------------------------
476
477     def test_create_invalid
478       user = create(:user)
479       changeset = create(:changeset, :user => user)
480
481       auth_header = bearer_authorization_header user
482
483       # create a relation with non-existing node as member
484       xml = "<osm><relation changeset='#{changeset.id}'>" \
485             "<member type='node' ref='0'/><tag k='test' v='yes' />" \
486             "</relation></osm>"
487       post api_relations_path, :params => xml, :headers => auth_header
488       # expect failure
489       assert_response :precondition_failed,
490                       "relation upload with invalid node did not return 'precondition failed'"
491       assert_equal "Precondition failed: Relation with id  cannot be saved due to Node with id 0", @response.body
492     end
493
494     # -------------------------------------
495     # Test creating a relation, with some invalid XML
496     # -------------------------------------
497     def test_create_invalid_xml
498       user = create(:user)
499       changeset = create(:changeset, :user => user)
500       node = create(:node)
501
502       auth_header = bearer_authorization_header user
503
504       # create some xml that should return an error
505       xml = "<osm><relation changeset='#{changeset.id}'>" \
506             "<member type='type' ref='#{node.id}' role=''/>" \
507             "<tag k='tester' v='yep'/></relation></osm>"
508       post api_relations_path, :params => xml, :headers => auth_header
509       # expect failure
510       assert_response :bad_request
511       assert_match(/Cannot parse valid relation from xml string/, @response.body)
512       assert_match(/The type is not allowed only, /, @response.body)
513     end
514
515     # -------------------------------------
516     # Test deleting relations.
517     # -------------------------------------
518
519     def test_destroy
520       private_user = create(:user, :data_public => false)
521       private_user_closed_changeset = create(:changeset, :closed, :user => private_user)
522       user = create(:user)
523       closed_changeset = create(:changeset, :closed, :user => user)
524       changeset = create(:changeset, :user => user)
525       relation = create(:relation)
526       used_relation = create(:relation)
527       super_relation = create(:relation_member, :member => used_relation).relation
528       deleted_relation = create(:relation, :deleted)
529       multi_tag_relation = create(:relation)
530       create_list(:relation_tag, 4, :relation => multi_tag_relation)
531
532       ## First try to delete relation without auth
533       delete api_relation_path(relation)
534       assert_response :unauthorized
535
536       ## Then try with the private user, to make sure that you get a forbidden
537       auth_header = bearer_authorization_header private_user
538
539       # this shouldn't work, as we should need the payload...
540       delete api_relation_path(relation), :headers => auth_header
541       assert_response :forbidden
542
543       # try to delete without specifying a changeset
544       xml = "<osm><relation id='#{relation.id}'/></osm>"
545       delete api_relation_path(relation), :params => xml.to_s, :headers => auth_header
546       assert_response :forbidden
547
548       # try to delete with an invalid (closed) changeset
549       xml = update_changeset(xml_for_relation(relation),
550                              private_user_closed_changeset.id)
551       delete api_relation_path(relation), :params => xml.to_s, :headers => auth_header
552       assert_response :forbidden
553
554       # try to delete with an invalid (non-existent) changeset
555       xml = update_changeset(xml_for_relation(relation), 0)
556       delete api_relation_path(relation), :params => xml.to_s, :headers => auth_header
557       assert_response :forbidden
558
559       # this won't work because the relation is in-use by another relation
560       xml = xml_for_relation(used_relation)
561       delete api_relation_path(used_relation), :params => xml.to_s, :headers => auth_header
562       assert_response :forbidden
563
564       # this should work when we provide the appropriate payload...
565       xml = xml_for_relation(relation)
566       delete api_relation_path(relation), :params => xml.to_s, :headers => auth_header
567       assert_response :forbidden
568
569       # this won't work since the relation is already deleted
570       xml = xml_for_relation(deleted_relation)
571       delete api_relation_path(deleted_relation), :params => xml.to_s, :headers => auth_header
572       assert_response :forbidden
573
574       # this won't work since the relation never existed
575       delete api_relation_path(0), :headers => auth_header
576       assert_response :forbidden
577
578       ## now set auth for the public user
579       auth_header = bearer_authorization_header user
580
581       # this shouldn't work, as we should need the payload...
582       delete api_relation_path(relation), :headers => auth_header
583       assert_response :bad_request
584
585       # try to delete without specifying a changeset
586       xml = "<osm><relation id='#{relation.id}' version='#{relation.version}' /></osm>"
587       delete api_relation_path(relation), :params => xml.to_s, :headers => auth_header
588       assert_response :bad_request
589       assert_match(/Changeset id is missing/, @response.body)
590
591       # try to delete with an invalid (closed) changeset
592       xml = update_changeset(xml_for_relation(relation),
593                              closed_changeset.id)
594       delete api_relation_path(relation), :params => xml.to_s, :headers => auth_header
595       assert_response :conflict
596
597       # try to delete with an invalid (non-existent) changeset
598       xml = update_changeset(xml_for_relation(relation), 0)
599       delete api_relation_path(relation), :params => xml.to_s, :headers => auth_header
600       assert_response :conflict
601
602       # this won't work because the relation is in a changeset owned by someone else
603       xml = update_changeset(xml_for_relation(relation), create(:changeset).id)
604       delete api_relation_path(relation), :params => xml.to_s, :headers => auth_header
605       assert_response :conflict,
606                       "shouldn't be able to delete a relation in a changeset owned by someone else (#{@response.body})"
607
608       # this won't work because the relation in the payload is different to that passed
609       xml = update_changeset(xml_for_relation(relation), changeset.id)
610       delete api_relation_path(create(:relation)), :params => xml.to_s, :headers => auth_header
611       assert_response :bad_request, "shouldn't be able to delete a relation when payload is different to the url"
612
613       # this won't work because the relation is in-use by another relation
614       xml = update_changeset(xml_for_relation(used_relation), changeset.id)
615       delete api_relation_path(used_relation), :params => xml.to_s, :headers => auth_header
616       assert_response :precondition_failed,
617                       "shouldn't be able to delete a relation used in a relation (#{@response.body})"
618       assert_equal "Precondition failed: The relation #{used_relation.id} is used in relation #{super_relation.id}.", @response.body
619
620       # this should work when we provide the appropriate payload...
621       xml = update_changeset(xml_for_relation(multi_tag_relation), changeset.id)
622       delete api_relation_path(multi_tag_relation), :params => xml.to_s, :headers => auth_header
623       assert_response :success
624
625       # valid delete should return the new version number, which should
626       # be greater than the old version number
627       assert_operator @response.body.to_i, :>, multi_tag_relation.version, "delete request should return a new version number for relation"
628
629       # this won't work since the relation is already deleted
630       xml = update_changeset(xml_for_relation(deleted_relation), changeset.id)
631       delete api_relation_path(deleted_relation), :params => xml.to_s, :headers => auth_header
632       assert_response :gone
633
634       # Public visible relation needs to be deleted
635       xml = update_changeset(xml_for_relation(super_relation), changeset.id)
636       delete api_relation_path(super_relation), :params => xml.to_s, :headers => auth_header
637       assert_response :success
638
639       # this works now because the relation which was using this one
640       # has been deleted.
641       xml = update_changeset(xml_for_relation(used_relation), changeset.id)
642       delete api_relation_path(used_relation), :params => xml.to_s, :headers => auth_header
643       assert_response :success,
644                       "should be able to delete a relation used in an old relation (#{@response.body})"
645
646       # this won't work since the relation never existed
647       delete api_relation_path(0), :headers => auth_header
648       assert_response :not_found
649     end
650
651     ##
652     # when a relation's tag is modified then it should put the bounding
653     # box of all its members into the changeset.
654     def test_tag_modify_bounding_box
655       relation = create(:relation)
656       node1 = create(:node, :lat => 0.3, :lon => 0.3)
657       node2 = create(:node, :lat => 0.5, :lon => 0.5)
658       way = create(:way)
659       create(:way_node, :way => way, :node => node1)
660       create(:relation_member, :relation => relation, :member => way)
661       create(:relation_member, :relation => relation, :member => node2)
662       # the relation contains nodes1 and node2 (node1
663       # indirectly via the way), so the bbox should be [0.3,0.3,0.5,0.5].
664       check_changeset_modify(BoundingBox.new(0.3, 0.3, 0.5, 0.5)) do |changeset_id, auth_header|
665         # add a tag to an existing relation
666         relation_xml = xml_for_relation(relation)
667         relation_element = relation_xml.find("//osm/relation").first
668         new_tag = XML::Node.new("tag")
669         new_tag["k"] = "some_new_tag"
670         new_tag["v"] = "some_new_value"
671         relation_element << new_tag
672
673         # update changeset ID to point to new changeset
674         update_changeset(relation_xml, changeset_id)
675
676         # upload the change
677         put api_relation_path(relation), :params => relation_xml.to_s, :headers => auth_header
678         assert_response :success, "can't update relation for tag/bbox test"
679       end
680     end
681
682     ##
683     # add a member to a relation and check the bounding box is only that
684     # element.
685     def test_add_member_bounding_box
686       relation = create(:relation)
687       node1 = create(:node, :lat => 4, :lon => 4)
688       node2 = create(:node, :lat => 7, :lon => 7)
689       way1 = create(:way)
690       create(:way_node, :way => way1, :node => create(:node, :lat => 8, :lon => 8))
691       way2 = create(:way)
692       create(:way_node, :way => way2, :node => create(:node, :lat => 9, :lon => 9), :sequence_id => 1)
693       create(:way_node, :way => way2, :node => create(:node, :lat => 10, :lon => 10), :sequence_id => 2)
694
695       [node1, node2, way1, way2].each do |element|
696         bbox = element.bbox.to_unscaled
697         check_changeset_modify(bbox) do |changeset_id, auth_header|
698           relation_xml = xml_for_relation(Relation.find(relation.id))
699           relation_element = relation_xml.find("//osm/relation").first
700           new_member = XML::Node.new("member")
701           new_member["ref"] = element.id.to_s
702           new_member["type"] = element.class.to_s.downcase
703           new_member["role"] = "some_role"
704           relation_element << new_member
705
706           # update changeset ID to point to new changeset
707           update_changeset(relation_xml, changeset_id)
708
709           # upload the change
710           put api_relation_path(relation), :params => relation_xml.to_s, :headers => auth_header
711           assert_response :success, "can't update relation for add #{element.class}/bbox test: #{@response.body}"
712
713           # get it back and check the ordering
714           get api_relation_path(relation)
715           assert_response :success, "can't read back the relation: #{@response.body}"
716           check_ordering(relation_xml, @response.body)
717         end
718       end
719     end
720
721     ##
722     # remove a member from a relation and check the bounding box is
723     # only that element.
724     def test_remove_member_bounding_box
725       relation = create(:relation)
726       node1 = create(:node, :lat => 3, :lon => 3)
727       node2 = create(:node, :lat => 5, :lon => 5)
728       create(:relation_member, :relation => relation, :member => node1)
729       create(:relation_member, :relation => relation, :member => node2)
730
731       check_changeset_modify(BoundingBox.new(5, 5, 5, 5)) do |changeset_id, auth_header|
732         # remove node 5 (5,5) from an existing relation
733         relation_xml = xml_for_relation(relation)
734         relation_xml
735           .find("//osm/relation/member[@type='node'][@ref='#{node2.id}']")
736           .first.remove!
737
738         # update changeset ID to point to new changeset
739         update_changeset(relation_xml, changeset_id)
740
741         # upload the change
742         put api_relation_path(relation), :params => relation_xml.to_s, :headers => auth_header
743         assert_response :success, "can't update relation for remove node/bbox test"
744       end
745     end
746
747     ##
748     # check that relations are ordered
749     def test_relation_member_ordering
750       user = create(:user)
751       changeset = create(:changeset, :user => user)
752       node1 = create(:node)
753       node2 = create(:node)
754       node3 = create(:node)
755       way1 = create(:way_with_nodes, :nodes_count => 2)
756       way2 = create(:way_with_nodes, :nodes_count => 2)
757
758       auth_header = bearer_authorization_header user
759
760       doc_str = <<~OSM
761         <osm>
762          <relation changeset='#{changeset.id}'>
763           <member ref='#{node1.id}' type='node' role='first'/>
764           <member ref='#{node2.id}' type='node' role='second'/>
765           <member ref='#{way1.id}' type='way' role='third'/>
766           <member ref='#{way2.id}' type='way' role='fourth'/>
767          </relation>
768         </osm>
769       OSM
770       doc = XML::Parser.string(doc_str).parse
771
772       post api_relations_path, :params => doc.to_s, :headers => auth_header
773       assert_response :success, "can't create a relation: #{@response.body}"
774       relation_id = @response.body.to_i
775
776       # get it back and check the ordering
777       get api_relation_path(relation_id)
778       assert_response :success, "can't read back the relation: #{@response.body}"
779       check_ordering(doc, @response.body)
780
781       # insert a member at the front
782       new_member = XML::Node.new "member"
783       new_member["ref"] = node3.id.to_s
784       new_member["type"] = "node"
785       new_member["role"] = "new first"
786       doc.find("//osm/relation").first.child.prev = new_member
787       # update the version, should be 1?
788       doc.find("//osm/relation").first["id"] = relation_id.to_s
789       doc.find("//osm/relation").first["version"] = 1.to_s
790
791       # upload the next version of the relation
792       put api_relation_path(relation_id), :params => doc.to_s, :headers => auth_header
793       assert_response :success, "can't update relation: #{@response.body}"
794       assert_equal 2, @response.body.to_i
795
796       # get it back again and check the ordering again
797       get api_relation_path(relation_id)
798       assert_response :success, "can't read back the relation: #{@response.body}"
799       check_ordering(doc, @response.body)
800
801       # check the ordering in the history tables:
802       with_controller(OldRelationsController.new) do
803         get api_relation_version_path(relation_id, 2)
804         assert_response :success, "can't read back version 2 of the relation #{relation_id}"
805         check_ordering(doc, @response.body)
806       end
807     end
808
809     ##
810     # check that relations can contain duplicate members
811     def test_relation_member_duplicates
812       private_user = create(:user, :data_public => false)
813       user = create(:user)
814       changeset = create(:changeset, :user => user)
815       node1 = create(:node)
816       node2 = create(:node)
817
818       doc_str = <<~OSM
819         <osm>
820          <relation changeset='#{changeset.id}'>
821           <member ref='#{node1.id}' type='node' role='forward'/>
822           <member ref='#{node2.id}' type='node' role='forward'/>
823           <member ref='#{node1.id}' type='node' role='forward'/>
824           <member ref='#{node2.id}' type='node' role='forward'/>
825          </relation>
826         </osm>
827       OSM
828       doc = XML::Parser.string(doc_str).parse
829
830       ## First try with the private user
831       auth_header = bearer_authorization_header private_user
832
833       post api_relations_path, :params => doc.to_s, :headers => auth_header
834       assert_response :forbidden
835
836       ## Now try with the public user
837       auth_header = bearer_authorization_header user
838
839       post api_relations_path, :params => doc.to_s, :headers => auth_header
840       assert_response :success, "can't create a relation: #{@response.body}"
841       relation_id = @response.body.to_i
842
843       # get it back and check the ordering
844       get api_relation_path(relation_id)
845       assert_response :success, "can't read back the relation: #{relation_id}"
846       check_ordering(doc, @response.body)
847     end
848
849     ##
850     # test that the ordering of elements in the history is the same as in current.
851     def test_history_ordering
852       user = create(:user)
853       changeset = create(:changeset, :user => user)
854       node1 = create(:node)
855       node2 = create(:node)
856       node3 = create(:node)
857       node4 = create(:node)
858
859       doc_str = <<~OSM
860         <osm>
861          <relation changeset='#{changeset.id}'>
862           <member ref='#{node1.id}' type='node' role='forward'/>
863           <member ref='#{node4.id}' type='node' role='forward'/>
864           <member ref='#{node3.id}' type='node' role='forward'/>
865           <member ref='#{node2.id}' type='node' role='forward'/>
866          </relation>
867         </osm>
868       OSM
869       doc = XML::Parser.string(doc_str).parse
870       auth_header = bearer_authorization_header user
871
872       post api_relations_path, :params => doc.to_s, :headers => auth_header
873       assert_response :success, "can't create a relation: #{@response.body}"
874       relation_id = @response.body.to_i
875
876       # check the ordering in the current tables:
877       get api_relation_path(relation_id)
878       assert_response :success, "can't read back the relation: #{@response.body}"
879       check_ordering(doc, @response.body)
880
881       # check the ordering in the history tables:
882       with_controller(OldRelationsController.new) do
883         get api_relation_version_path(relation_id, 1)
884         assert_response :success, "can't read back version 1 of the relation: #{@response.body}"
885         check_ordering(doc, @response.body)
886       end
887     end
888
889     ##
890     # remove all the members from a relation. the result is pretty useless, but
891     # still technically valid.
892     def test_remove_all_members
893       relation = create(:relation)
894       node1 = create(:node, :lat => 0.3, :lon => 0.3)
895       node2 = create(:node, :lat => 0.5, :lon => 0.5)
896       way = create(:way)
897       create(:way_node, :way => way, :node => node1)
898       create(:relation_member, :relation => relation, :member => way)
899       create(:relation_member, :relation => relation, :member => node2)
900
901       check_changeset_modify(BoundingBox.new(0.3, 0.3, 0.5, 0.5)) do |changeset_id, auth_header|
902         relation_xml = xml_for_relation(relation)
903         relation_xml
904           .find("//osm/relation/member")
905           .each(&:remove!)
906
907         # update changeset ID to point to new changeset
908         update_changeset(relation_xml, changeset_id)
909
910         # upload the change
911         put api_relation_path(relation), :params => relation_xml.to_s, :headers => auth_header
912         assert_response :success, "can't update relation for remove all members test"
913         checkrelation = Relation.find(relation.id)
914         assert_not_nil(checkrelation,
915                        "uploaded relation not found in database after upload")
916         assert_equal(0, checkrelation.members.length,
917                      "relation contains members but they should have all been deleted")
918       end
919     end
920
921     ##
922     # test initial rate limit
923     def test_initial_rate_limit
924       # create a user
925       user = create(:user)
926
927       # create some nodes
928       node1 = create(:node)
929       node2 = create(:node)
930
931       # create a changeset that puts us near the initial rate limit
932       changeset = create(:changeset, :user => user,
933                                      :created_at => Time.now.utc - 5.minutes,
934                                      :num_changes => Settings.initial_changes_per_hour - 1)
935
936       # create authentication header
937       auth_header = bearer_authorization_header user
938
939       # try creating a relation
940       xml = "<osm><relation changeset='#{changeset.id}'>" \
941             "<member  ref='#{node1.id}' type='node' role='some'/>" \
942             "<member  ref='#{node2.id}' type='node' role='some'/>" \
943             "<tag k='test' v='yes' /></relation></osm>"
944       post api_relations_path, :params => xml, :headers => auth_header
945       assert_response :success, "relation create did not return success status"
946
947       # get the id of the relation we created
948       relationid = @response.body
949
950       # try updating the relation, which should be rate limited
951       xml = "<osm><relation id='#{relationid}' version='1' changeset='#{changeset.id}'>" \
952             "<member  ref='#{node2.id}' type='node' role='some'/>" \
953             "<member  ref='#{node1.id}' type='node' role='some'/>" \
954             "<tag k='test' v='yes' /></relation></osm>"
955       put api_relation_path(relationid), :params => xml, :headers => auth_header
956       assert_response :too_many_requests, "relation update did not hit rate limit"
957
958       # try deleting the relation, which should be rate limited
959       xml = "<osm><relation id='#{relationid}' version='2' changeset='#{changeset.id}'/></osm>"
960       delete api_relation_path(relationid), :params => xml, :headers => auth_header
961       assert_response :too_many_requests, "relation delete did not hit rate limit"
962
963       # try creating a relation, which should be rate limited
964       xml = "<osm><relation changeset='#{changeset.id}'>" \
965             "<member  ref='#{node1.id}' type='node' role='some'/>" \
966             "<member  ref='#{node2.id}' type='node' role='some'/>" \
967             "<tag k='test' v='yes' /></relation></osm>"
968       post api_relations_path, :params => xml, :headers => auth_header
969       assert_response :too_many_requests, "relation create did not hit rate limit"
970     end
971
972     ##
973     # test maximum rate limit
974     def test_maximum_rate_limit
975       # create a user
976       user = create(:user)
977
978       # create some nodes
979       node1 = create(:node)
980       node2 = create(:node)
981
982       # create a changeset to establish our initial edit time
983       changeset = create(:changeset, :user => user,
984                                      :created_at => Time.now.utc - 28.days)
985
986       # create changeset to put us near the maximum rate limit
987       total_changes = Settings.max_changes_per_hour - 1
988       while total_changes.positive?
989         changes = [total_changes, Changeset::MAX_ELEMENTS].min
990         changeset = create(:changeset, :user => user,
991                                        :created_at => Time.now.utc - 5.minutes,
992                                        :num_changes => changes)
993         total_changes -= changes
994       end
995
996       # create authentication header
997       auth_header = bearer_authorization_header user
998
999       # try creating a relation
1000       xml = "<osm><relation changeset='#{changeset.id}'>" \
1001             "<member  ref='#{node1.id}' type='node' role='some'/>" \
1002             "<member  ref='#{node2.id}' type='node' role='some'/>" \
1003             "<tag k='test' v='yes' /></relation></osm>"
1004       post api_relations_path, :params => xml, :headers => auth_header
1005       assert_response :success, "relation create did not return success status"
1006
1007       # get the id of the relation we created
1008       relationid = @response.body
1009
1010       # try updating the relation, which should be rate limited
1011       xml = "<osm><relation id='#{relationid}' version='1' changeset='#{changeset.id}'>" \
1012             "<member  ref='#{node2.id}' type='node' role='some'/>" \
1013             "<member  ref='#{node1.id}' type='node' role='some'/>" \
1014             "<tag k='test' v='yes' /></relation></osm>"
1015       put api_relation_path(relationid), :params => xml, :headers => auth_header
1016       assert_response :too_many_requests, "relation update did not hit rate limit"
1017
1018       # try deleting the relation, which should be rate limited
1019       xml = "<osm><relation id='#{relationid}' version='2' changeset='#{changeset.id}'/></osm>"
1020       delete api_relation_path(relationid), :params => xml, :headers => auth_header
1021       assert_response :too_many_requests, "relation delete did not hit rate limit"
1022
1023       # try creating a relation, which should be rate limited
1024       xml = "<osm><relation changeset='#{changeset.id}'>" \
1025             "<member  ref='#{node1.id}' type='node' role='some'/>" \
1026             "<member  ref='#{node2.id}' type='node' role='some'/>" \
1027             "<tag k='test' v='yes' /></relation></osm>"
1028       post api_relations_path, :params => xml, :headers => auth_header
1029       assert_response :too_many_requests, "relation create did not hit rate limit"
1030     end
1031
1032     private
1033
1034     ##
1035     # checks that the XML document and the string arguments have
1036     # members in the same order.
1037     def check_ordering(doc, xml)
1038       new_doc = XML::Parser.string(xml).parse
1039
1040       doc_members = doc.find("//osm/relation/member").collect do |m|
1041         [m["ref"].to_i, m["type"].to_sym, m["role"]]
1042       end
1043
1044       new_members = new_doc.find("//osm/relation/member").collect do |m|
1045         [m["ref"].to_i, m["type"].to_sym, m["role"]]
1046       end
1047
1048       assert_equal doc_members, new_members, "members are not equal - ordering is wrong? (#{doc}, #{xml})"
1049     end
1050
1051     ##
1052     # create a changeset and yield to the caller to set it up, then assert
1053     # that the changeset bounding box is +bbox+.
1054     def check_changeset_modify(bbox)
1055       ## First test with the private user to check that you get a forbidden
1056       auth_header = bearer_authorization_header create(:user, :data_public => false)
1057
1058       # create a new changeset for this operation, so we are assured
1059       # that the bounding box will be newly-generated.
1060       with_controller(Api::ChangesetsController.new) do
1061         xml = "<osm><changeset/></osm>"
1062         post api_changesets_path, :params => xml, :headers => auth_header
1063         assert_response :forbidden, "shouldn't be able to create changeset for modify test, as should get forbidden"
1064       end
1065
1066       ## Now do the whole thing with the public user
1067       auth_header = bearer_authorization_header
1068
1069       # create a new changeset for this operation, so we are assured
1070       # that the bounding box will be newly-generated.
1071       changeset_id = with_controller(Api::ChangesetsController.new) do
1072         xml = "<osm><changeset/></osm>"
1073         post api_changesets_path, :params => xml, :headers => auth_header
1074         assert_response :success, "couldn't create changeset for modify test"
1075         @response.body.to_i
1076       end
1077
1078       # go back to the block to do the actual modifies
1079       yield changeset_id, auth_header
1080
1081       # now download the changeset to check its bounding box
1082       with_controller(Api::ChangesetsController.new) do
1083         get api_changeset_path(changeset_id)
1084         assert_response :success, "can't re-read changeset for modify test"
1085         assert_select "osm>changeset", 1, "Changeset element doesn't exist in #{@response.body}"
1086         assert_select "osm>changeset[id='#{changeset_id}']", 1, "Changeset id=#{changeset_id} doesn't exist in #{@response.body}"
1087         assert_select "osm>changeset[min_lon='#{format('%<lon>.7f', :lon => bbox.min_lon)}']", 1, "Changeset min_lon wrong in #{@response.body}"
1088         assert_select "osm>changeset[min_lat='#{format('%<lat>.7f', :lat => bbox.min_lat)}']", 1, "Changeset min_lat wrong in #{@response.body}"
1089         assert_select "osm>changeset[max_lon='#{format('%<lon>.7f', :lon => bbox.max_lon)}']", 1, "Changeset max_lon wrong in #{@response.body}"
1090         assert_select "osm>changeset[max_lat='#{format('%<lat>.7f', :lat => bbox.max_lat)}']", 1, "Changeset max_lat wrong in #{@response.body}"
1091       end
1092     end
1093
1094     ##
1095     # updates the relation (XML) +rel+ and
1096     # returns the new version of that relation.
1097     def do_update(rel, rel_id, headers)
1098       put api_relation_path(rel_id), :params => rel.to_s, :headers => headers
1099       assert_response :success, "can't update relation: #{@response.body}"
1100       version = @response.body.to_i
1101
1102       version
1103     end
1104
1105     ##
1106     # updates the relation (XML) +rel+ via the diff-upload API and
1107     # returns the new version of that relation.
1108     def do_update_diff(rel, headers)
1109       cs_id = rel.find("//osm/relation").first["changeset"].to_i
1110       version = nil
1111
1112       with_controller(Api::ChangesetsController.new) do
1113         doc = OSM::API.new.xml_doc
1114         change = XML::Node.new "osmChange"
1115         doc.root = change
1116         modify = XML::Node.new "modify"
1117         change << modify
1118         modify << doc.import(rel.find("//osm/relation").first)
1119
1120         post api_changeset_upload_path(cs_id), :params => doc.to_s, :headers => headers
1121         assert_response :success, "can't upload diff relation: #{@response.body}"
1122         version = xml_parse(@response.body).find("//diffResult/relation").first["new_version"].to_i
1123       end
1124
1125       version
1126     end
1127
1128     ##
1129     # returns a k->v hash of tags from an xml doc
1130     def get_tags_as_hash(a)
1131       a.find("//osm/relation/tag").to_h do |tag|
1132         [tag["k"], tag["v"]]
1133       end
1134     end
1135
1136     ##
1137     # assert that all tags on relation documents +a+ and +b+
1138     # are equal
1139     def assert_tags_equal(a, b)
1140       # turn the XML doc into tags hashes
1141       a_tags = get_tags_as_hash(a)
1142       b_tags = get_tags_as_hash(b)
1143
1144       assert_equal a_tags, b_tags, "Tags should be identical."
1145     end
1146
1147     ##
1148     # update the changeset_id of a node element
1149     def update_changeset(xml, changeset_id)
1150       xml_attr_rewrite(xml, "changeset", changeset_id)
1151     end
1152
1153     ##
1154     # update an attribute in the node element
1155     def xml_attr_rewrite(xml, name, value)
1156       xml.find("//osm/relation").first[name] = value.to_s
1157       xml
1158     end
1159
1160     ##
1161     # parse some xml
1162     def xml_parse(xml)
1163       parser = XML::Parser.string(xml)
1164       parser.parse
1165     end
1166   end
1167 end