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