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