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