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