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