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