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