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