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