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