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