]> git.openstreetmap.org Git - rails.git/blob - test/controllers/api/relations_controller_test.rb
Make api create relation path resourceful
[rails.git] / test / controllers / api / relations_controller_test.rb
1 require "test_helper"
2
3 module Api
4   class RelationsControllerTest < ActionDispatch::IntegrationTest
5     ##
6     # test all routes which lead to this controller
7     def test_routes
8       assert_routing(
9         { :path => "/api/0.6/relations", :method => :get },
10         { :controller => "api/relations", :action => "index" }
11       )
12       assert_routing(
13         { :path => "/api/0.6/relations.json", :method => :get },
14         { :controller => "api/relations", :action => "index", :format => "json" }
15       )
16       assert_routing(
17         { :path => "/api/0.6/relations", :method => :post },
18         { :controller => "api/relations", :action => "create" }
19       )
20       assert_routing(
21         { :path => "/api/0.6/relation/1/full", :method => :get },
22         { :controller => "api/relations", :action => "full", :id => "1" }
23       )
24       assert_routing(
25         { :path => "/api/0.6/relation/1/full.json", :method => :get },
26         { :controller => "api/relations", :action => "full", :id => "1", :format => "json" }
27       )
28       assert_routing(
29         { :path => "/api/0.6/relation/1", :method => :get },
30         { :controller => "api/relations", :action => "show", :id => "1" }
31       )
32       assert_routing(
33         { :path => "/api/0.6/relation/1.json", :method => :get },
34         { :controller => "api/relations", :action => "show", :id => "1", :format => "json" }
35       )
36       assert_routing(
37         { :path => "/api/0.6/relation/1", :method => :put },
38         { :controller => "api/relations", :action => "update", :id => "1" }
39       )
40       assert_routing(
41         { :path => "/api/0.6/relation/1", :method => :delete },
42         { :controller => "api/relations", :action => "delete", :id => "1" }
43       )
44
45       assert_routing(
46         { :path => "/api/0.6/node/1/relations", :method => :get },
47         { :controller => "api/relations", :action => "relations_for_node", :id => "1" }
48       )
49       assert_routing(
50         { :path => "/api/0.6/way/1/relations", :method => :get },
51         { :controller => "api/relations", :action => "relations_for_way", :id => "1" }
52       )
53       assert_routing(
54         { :path => "/api/0.6/relation/1/relations", :method => :get },
55         { :controller => "api/relations", :action => "relations_for_relation", :id => "1" }
56       )
57       assert_routing(
58         { :path => "/api/0.6/node/1/relations.json", :method => :get },
59         { :controller => "api/relations", :action => "relations_for_node", :id => "1", :format => "json" }
60       )
61       assert_routing(
62         { :path => "/api/0.6/way/1/relations.json", :method => :get },
63         { :controller => "api/relations", :action => "relations_for_way", :id => "1", :format => "json" }
64       )
65       assert_routing(
66         { :path => "/api/0.6/relation/1/relations.json", :method => :get },
67         { :controller => "api/relations", :action => "relations_for_relation", :id => "1", :format => "json" }
68       )
69
70       assert_recognizes(
71         { :controller => "api/relations", :action => "create" },
72         { :path => "/api/0.6/relation/create", :method => :put }
73       )
74     end
75
76     ##
77     # test fetching multiple relations
78     def test_index
79       relation1 = create(:relation)
80       relation2 = create(:relation, :deleted)
81       relation3 = create(:relation, :with_history, :version => 2)
82       relation4 = create(:relation, :with_history, :version => 2)
83       relation4.old_relations.find_by(:version => 1).redact!(create(:redaction))
84
85       # check error when no parameter provided
86       get api_relations_path
87       assert_response :bad_request
88
89       # check error when no parameter value provided
90       get api_relations_path(:relations => "")
91       assert_response :bad_request
92
93       # test a working call
94       get api_relations_path(:relations => "#{relation1.id},#{relation2.id},#{relation3.id},#{relation4.id}")
95       assert_response :success
96       assert_select "osm" do
97         assert_select "relation", :count => 4
98         assert_select "relation[id='#{relation1.id}'][visible='true']", :count => 1
99         assert_select "relation[id='#{relation2.id}'][visible='false']", :count => 1
100         assert_select "relation[id='#{relation3.id}'][visible='true']", :count => 1
101         assert_select "relation[id='#{relation4.id}'][visible='true']", :count => 1
102       end
103
104       # test a working call with json format
105       get api_relations_path(:relations => "#{relation1.id},#{relation2.id},#{relation3.id},#{relation4.id}", :format => "json")
106
107       js = ActiveSupport::JSON.decode(@response.body)
108       assert_not_nil js
109       assert_equal 4, js["elements"].count
110       assert_equal 4, (js["elements"].count { |a| a["type"] == "relation" })
111       assert_equal 1, (js["elements"].count { |a| a["id"] == relation1.id && a["visible"].nil? })
112       assert_equal 1, (js["elements"].count { |a| a["id"] == relation2.id && a["visible"] == false })
113       assert_equal 1, (js["elements"].count { |a| a["id"] == relation3.id && a["visible"].nil? })
114       assert_equal 1, (js["elements"].count { |a| a["id"] == relation4.id && a["visible"].nil? })
115
116       # check error when a non-existent relation is included
117       get api_relations_path(:relations => "#{relation1.id},#{relation2.id},#{relation3.id},#{relation4.id},0")
118       assert_response :not_found
119     end
120
121     # -------------------------------------
122     # Test showing relations.
123     # -------------------------------------
124
125     def test_show
126       # check that a visible relation is returned properly
127       get api_relation_path(create(:relation))
128       assert_response :success
129
130       # check that an invisible relation is not returned
131       get api_relation_path(create(:relation, :deleted))
132       assert_response :gone
133
134       # check chat a non-existent relation is not returned
135       get api_relation_path(0)
136       assert_response :not_found
137     end
138
139     ##
140     # check that all relations containing a particular node, and no extra
141     # relations, are returned from the relations_for_node call.
142     def test_relations_for_node
143       node = create(:node)
144       # should include relations with that node as a member
145       relation_with_node = create(:relation_member, :member => node).relation
146       # should ignore relations without that node as a member
147       _relation_without_node = create(:relation_member).relation
148       # should ignore relations with the node involved indirectly, via a way
149       way = create(:way_node, :node => node).way
150       _relation_with_way = create(:relation_member, :member => way).relation
151       # should ignore relations with the node involved indirectly, via a relation
152       second_relation = create(:relation_member, :member => node).relation
153       _super_relation = create(:relation_member, :member => second_relation).relation
154       # should combine multiple relation_member references into just one relation entry
155       create(:relation_member, :member => node, :relation => relation_with_node)
156       # should not include deleted relations
157       deleted_relation = create(:relation, :deleted)
158       create(:relation_member, :member => node, :relation => deleted_relation)
159
160       check_relations_for_element(node_relations_path(node), "node",
161                                   node.id,
162                                   [relation_with_node, second_relation])
163     end
164
165     def test_relations_for_way
166       way = create(:way)
167       # should include relations with that way as a member
168       relation_with_way = create(:relation_member, :member => way).relation
169       # should ignore relations without that way as a member
170       _relation_without_way = create(:relation_member).relation
171       # should ignore relations with the way involved indirectly, via a relation
172       second_relation = create(:relation_member, :member => way).relation
173       _super_relation = create(:relation_member, :member => second_relation).relation
174       # should combine multiple relation_member references into just one relation entry
175       create(:relation_member, :member => way, :relation => relation_with_way)
176       # should not include deleted relations
177       deleted_relation = create(:relation, :deleted)
178       create(:relation_member, :member => way, :relation => deleted_relation)
179
180       check_relations_for_element(way_relations_path(way), "way",
181                                   way.id,
182                                   [relation_with_way, second_relation])
183     end
184
185     def test_relations_for_relation
186       relation = create(:relation)
187       # should include relations with that relation as a member
188       relation_with_relation = create(:relation_member, :member => relation).relation
189       # should ignore any relation without that relation as a member
190       _relation_without_relation = create(:relation_member).relation
191       # should ignore relations with the relation involved indirectly, via a relation
192       second_relation = create(:relation_member, :member => relation).relation
193       _super_relation = create(:relation_member, :member => second_relation).relation
194       # should combine multiple relation_member references into just one relation entry
195       create(:relation_member, :member => relation, :relation => relation_with_relation)
196       # should not include deleted relations
197       deleted_relation = create(:relation, :deleted)
198       create(:relation_member, :member => relation, :relation => deleted_relation)
199       check_relations_for_element(relation_relations_path(relation), "relation",
200                                   relation.id,
201                                   [relation_with_relation, second_relation])
202     end
203
204     def test_full
205       # check the "full" mode
206       get relation_full_path(:id => 999999)
207       assert_response :not_found
208
209       get relation_full_path(:id => create(:relation, :deleted).id)
210       assert_response :gone
211
212       get relation_full_path(:id => create(:relation).id)
213       assert_response :success
214       # FIXME: check whether this contains the stuff we want!
215     end
216
217     # -------------------------------------
218     # Test simple relation creation.
219     # -------------------------------------
220
221     def test_create
222       private_user = create(:user, :data_public => false)
223       private_changeset = create(:changeset, :user => private_user)
224       user = create(:user)
225       changeset = create(:changeset, :user => user)
226       node = create(:node)
227       way = create(:way_with_nodes, :nodes_count => 2)
228
229       auth_header = bearer_authorization_header private_user
230
231       # create an relation without members
232       xml = "<osm><relation changeset='#{private_changeset.id}'><tag k='test' v='yes' /></relation></osm>"
233       post api_relations_path, :params => xml, :headers => auth_header
234       # hope for forbidden, due to user
235       assert_response :forbidden,
236                       "relation upload should have failed with forbidden"
237
238       ###
239       # create an relation with a node as member
240       # This time try with a role attribute in the relation
241       xml = "<osm><relation changeset='#{private_changeset.id}'>" \
242             "<member  ref='#{node.id}' type='node' role='some'/>" \
243             "<tag k='test' v='yes' /></relation></osm>"
244       post api_relations_path, :params => xml, :headers => auth_header
245       # hope for forbidden due to user
246       assert_response :forbidden,
247                       "relation upload did not return forbidden status"
248
249       ###
250       # create an relation with a node as member, this time test that we don't
251       # need a role attribute to be included
252       xml = "<osm><relation changeset='#{private_changeset.id}'>" \
253             "<member  ref='#{node.id}' type='node'/><tag k='test' v='yes' /></relation></osm>"
254       post api_relations_path, :params => xml, :headers => auth_header
255       # hope for forbidden due to user
256       assert_response :forbidden,
257                       "relation upload did not return forbidden status"
258
259       ###
260       # create an relation with a way and a node as members
261       xml = "<osm><relation changeset='#{private_changeset.id}'>" \
262             "<member type='node' ref='#{node.id}' role='some'/>" \
263             "<member type='way' ref='#{way.id}' role='other'/>" \
264             "<tag k='test' v='yes' /></relation></osm>"
265       post api_relations_path, :params => xml, :headers => auth_header
266       # hope for forbidden, due to user
267       assert_response :forbidden,
268                       "relation upload did not return success status"
269
270       ## Now try with the public user
271       auth_header = bearer_authorization_header user
272
273       # create an relation without members
274       xml = "<osm><relation changeset='#{changeset.id}'><tag k='test' v='yes' /></relation></osm>"
275       post api_relations_path, :params => xml, :headers => auth_header
276       # hope for success
277       assert_response :success,
278                       "relation upload did not return success status"
279       # read id of created relation and search for it
280       relationid = @response.body
281       checkrelation = Relation.find(relationid)
282       assert_not_nil checkrelation,
283                      "uploaded relation not found in data base after upload"
284       # compare values
285       assert_equal(0, checkrelation.members.length, "saved relation contains members but should not")
286       assert_equal(1, checkrelation.tags.length, "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 user.id, checkrelation.changeset.user_id,
290                    "saved relation does not belong to user that created it"
291       assert checkrelation.visible,
292              "saved relation is not visible"
293       # ok the relation is there but can we also retrieve it?
294       get api_relation_path(relationid)
295       assert_response :success
296
297       ###
298       # create an relation with a node as member
299       # This time try with a role attribute in the relation
300       xml = "<osm><relation changeset='#{changeset.id}'>" \
301             "<member  ref='#{node.id}' type='node' role='some'/>" \
302             "<tag k='test' v='yes' /></relation></osm>"
303       post api_relations_path, :params => xml, :headers => auth_header
304       # hope for success
305       assert_response :success,
306                       "relation upload did not return success status"
307       # read id of created relation and search for it
308       relationid = @response.body
309       checkrelation = Relation.find(relationid)
310       assert_not_nil checkrelation,
311                      "uploaded relation not found in data base after upload"
312       # compare values
313       assert_equal(1, checkrelation.members.length, "saved relation does not contain exactly one member")
314       assert_equal(1, checkrelation.tags.length, "saved relation does not contain exactly one tag")
315       assert_equal changeset.id, checkrelation.changeset.id,
316                    "saved relation does not belong in the changeset it was assigned to"
317       assert_equal user.id, checkrelation.changeset.user_id,
318                    "saved relation does not belong to user that created it"
319       assert checkrelation.visible,
320              "saved relation is not visible"
321       # ok the relation is there but can we also retrieve it?
322
323       get api_relation_path(relationid)
324       assert_response :success
325
326       ###
327       # create an relation with a node as member, this time test that we don't
328       # need a role attribute to be included
329       xml = "<osm><relation changeset='#{changeset.id}'>" \
330             "<member  ref='#{node.id}' type='node'/><tag k='test' v='yes' /></relation></osm>"
331       post api_relations_path, :params => xml, :headers => auth_header
332       # hope for success
333       assert_response :success,
334                       "relation upload did not return success status"
335       # read id of created relation and search for it
336       relationid = @response.body
337       checkrelation = Relation.find(relationid)
338       assert_not_nil checkrelation,
339                      "uploaded relation not found in data base after upload"
340       # compare values
341       assert_equal(1, checkrelation.members.length, "saved relation does not contain exactly one member")
342       assert_equal(1, checkrelation.tags.length, "saved relation does not contain exactly one tag")
343       assert_equal changeset.id, checkrelation.changeset.id,
344                    "saved relation does not belong in the changeset it was assigned to"
345       assert_equal user.id, checkrelation.changeset.user_id,
346                    "saved relation does not belong to user that created it"
347       assert checkrelation.visible,
348              "saved relation is not visible"
349       # ok the relation is there but can we also retrieve it?
350
351       get api_relation_path(relationid)
352       assert_response :success
353
354       ###
355       # create an relation with a way and a node as members
356       xml = "<osm><relation changeset='#{changeset.id}'>" \
357             "<member type='node' ref='#{node.id}' role='some'/>" \
358             "<member type='way' ref='#{way.id}' role='other'/>" \
359             "<tag k='test' v='yes' /></relation></osm>"
360       post api_relations_path, :params => xml, :headers => auth_header
361       # hope for success
362       assert_response :success,
363                       "relation upload did not return success status"
364       # read id of created relation and search for it
365       relationid = @response.body
366       checkrelation = Relation.find(relationid)
367       assert_not_nil checkrelation,
368                      "uploaded relation not found in data base after upload"
369       # compare values
370       assert_equal(2, checkrelation.members.length, "saved relation does not have exactly two members")
371       assert_equal(1, checkrelation.tags.length, "saved relation does not contain exactly one tag")
372       assert_equal changeset.id, checkrelation.changeset.id,
373                    "saved relation does not belong in the changeset it was assigned to"
374       assert_equal user.id, checkrelation.changeset.user_id,
375                    "saved relation does not belong to user that created it"
376       assert checkrelation.visible,
377              "saved relation is not visible"
378       # ok the relation is there but can we also retrieve it?
379       get api_relation_path(relationid)
380       assert_response :success
381     end
382
383     # ------------------------------------
384     # Test updating relations
385     # ------------------------------------
386
387     ##
388     # test that, when tags are updated on a relation, the correct things
389     # happen to the correct tables and the API gives sensible results.
390     # this is to test a case that gregory marler noticed and posted to
391     # josm-dev.
392     ## FIXME Move this to an integration test
393     def test_update_relation_tags
394       user = create(:user)
395       changeset = create(:changeset, :user => user)
396       relation = create(:relation)
397       create_list(:relation_tag, 4, :relation => relation)
398
399       auth_header = bearer_authorization_header user
400
401       with_relation(relation.id) do |rel|
402         # alter one of the tags
403         tag = rel.find("//osm/relation/tag").first
404         tag["v"] = "some changed value"
405         update_changeset(rel, changeset.id)
406
407         # check that the downloaded tags are the same as the uploaded tags...
408         new_version = with_update(rel, auth_header) do |new_rel|
409           assert_tags_equal rel, new_rel
410         end
411
412         # check the original one in the current_* table again
413         with_relation(relation.id) { |r| assert_tags_equal rel, r }
414
415         # now check the version in the history
416         with_relation(relation.id, new_version) { |r| assert_tags_equal rel, r }
417       end
418     end
419
420     ##
421     # test that, when tags are updated on a relation when using the diff
422     # upload function, the correct things happen to the correct tables
423     # and the API gives sensible results. this is to test a case that
424     # gregory marler noticed and posted to josm-dev.
425     def test_update_relation_tags_via_upload
426       user = create(:user)
427       changeset = create(:changeset, :user => user)
428       relation = create(:relation)
429       create_list(:relation_tag, 4, :relation => relation)
430
431       auth_header = bearer_authorization_header user
432
433       with_relation(relation.id) do |rel|
434         # alter one of the tags
435         tag = rel.find("//osm/relation/tag").first
436         tag["v"] = "some changed value"
437         update_changeset(rel, changeset.id)
438
439         # check that the downloaded tags are the same as the uploaded tags...
440         new_version = with_update_diff(rel, auth_header) do |new_rel|
441           assert_tags_equal rel, new_rel
442         end
443
444         # check the original one in the current_* table again
445         with_relation(relation.id) { |r| assert_tags_equal rel, r }
446
447         # now check the version in the history
448         with_relation(relation.id, new_version) { |r| assert_tags_equal rel, r }
449       end
450     end
451
452     def test_update_wrong_id
453       user = create(:user)
454       changeset = create(:changeset, :user => user)
455       relation = create(:relation)
456       other_relation = create(:relation)
457
458       auth_header = bearer_authorization_header user
459       with_relation(relation.id) do |rel|
460         update_changeset(rel, changeset.id)
461         put api_relation_path(other_relation), :params => rel.to_s, :headers => auth_header
462         assert_response :bad_request
463       end
464     end
465
466     # -------------------------------------
467     # Test creating some invalid relations.
468     # -------------------------------------
469
470     def test_create_invalid
471       user = create(:user)
472       changeset = create(:changeset, :user => user)
473
474       auth_header = bearer_authorization_header user
475
476       # create a relation with non-existing node as member
477       xml = "<osm><relation changeset='#{changeset.id}'>" \
478             "<member type='node' ref='0'/><tag k='test' v='yes' />" \
479             "</relation></osm>"
480       post api_relations_path, :params => xml, :headers => auth_header
481       # expect failure
482       assert_response :precondition_failed,
483                       "relation upload with invalid node did not return 'precondition failed'"
484       assert_equal "Precondition failed: Relation with id  cannot be saved due to Node with id 0", @response.body
485     end
486
487     # -------------------------------------
488     # Test creating a relation, with some invalid XML
489     # -------------------------------------
490     def test_create_invalid_xml
491       user = create(:user)
492       changeset = create(:changeset, :user => user)
493       node = create(:node)
494
495       auth_header = bearer_authorization_header user
496
497       # create some xml that should return an error
498       xml = "<osm><relation changeset='#{changeset.id}'>" \
499             "<member type='type' ref='#{node.id}' role=''/>" \
500             "<tag k='tester' v='yep'/></relation></osm>"
501       post api_relations_path, :params => xml, :headers => auth_header
502       # expect failure
503       assert_response :bad_request
504       assert_match(/Cannot parse valid relation from xml string/, @response.body)
505       assert_match(/The type is not allowed only, /, @response.body)
506     end
507
508     # -------------------------------------
509     # Test deleting relations.
510     # -------------------------------------
511
512     def test_delete
513       private_user = create(:user, :data_public => false)
514       private_user_closed_changeset = create(:changeset, :closed, :user => private_user)
515       user = create(:user)
516       closed_changeset = create(:changeset, :closed, :user => user)
517       changeset = create(:changeset, :user => user)
518       relation = create(:relation)
519       used_relation = create(:relation)
520       super_relation = create(:relation_member, :member => used_relation).relation
521       deleted_relation = create(:relation, :deleted)
522       multi_tag_relation = create(:relation)
523       create_list(:relation_tag, 4, :relation => multi_tag_relation)
524
525       ## First try to delete relation without auth
526       delete api_relation_path(relation)
527       assert_response :unauthorized
528
529       ## Then try with the private user, to make sure that you get a forbidden
530       auth_header = bearer_authorization_header private_user
531
532       # this shouldn't work, as we should need the payload...
533       delete api_relation_path(relation), :headers => auth_header
534       assert_response :forbidden
535
536       # try to delete without specifying a changeset
537       xml = "<osm><relation id='#{relation.id}'/></osm>"
538       delete api_relation_path(relation), :params => xml.to_s, :headers => auth_header
539       assert_response :forbidden
540
541       # try to delete with an invalid (closed) changeset
542       xml = update_changeset(xml_for_relation(relation),
543                              private_user_closed_changeset.id)
544       delete api_relation_path(relation), :params => xml.to_s, :headers => auth_header
545       assert_response :forbidden
546
547       # try to delete with an invalid (non-existent) changeset
548       xml = update_changeset(xml_for_relation(relation), 0)
549       delete api_relation_path(relation), :params => xml.to_s, :headers => auth_header
550       assert_response :forbidden
551
552       # this won't work because the relation is in-use by another relation
553       xml = xml_for_relation(used_relation)
554       delete api_relation_path(used_relation), :params => xml.to_s, :headers => auth_header
555       assert_response :forbidden
556
557       # this should work when we provide the appropriate payload...
558       xml = xml_for_relation(relation)
559       delete api_relation_path(relation), :params => xml.to_s, :headers => auth_header
560       assert_response :forbidden
561
562       # this won't work since the relation is already deleted
563       xml = xml_for_relation(deleted_relation)
564       delete api_relation_path(deleted_relation), :params => xml.to_s, :headers => auth_header
565       assert_response :forbidden
566
567       # this won't work since the relation never existed
568       delete api_relation_path(0), :headers => auth_header
569       assert_response :forbidden
570
571       ## now set auth for the public user
572       auth_header = bearer_authorization_header user
573
574       # this shouldn't work, as we should need the payload...
575       delete api_relation_path(relation), :headers => auth_header
576       assert_response :bad_request
577
578       # try to delete without specifying a changeset
579       xml = "<osm><relation id='#{relation.id}' version='#{relation.version}' /></osm>"
580       delete api_relation_path(relation), :params => xml.to_s, :headers => auth_header
581       assert_response :bad_request
582       assert_match(/Changeset id is missing/, @response.body)
583
584       # try to delete with an invalid (closed) changeset
585       xml = update_changeset(xml_for_relation(relation),
586                              closed_changeset.id)
587       delete api_relation_path(relation), :params => xml.to_s, :headers => auth_header
588       assert_response :conflict
589
590       # try to delete with an invalid (non-existent) changeset
591       xml = update_changeset(xml_for_relation(relation), 0)
592       delete api_relation_path(relation), :params => xml.to_s, :headers => auth_header
593       assert_response :conflict
594
595       # this won't work because the relation is in a changeset owned by someone else
596       xml = update_changeset(xml_for_relation(relation), create(:changeset).id)
597       delete api_relation_path(relation), :params => xml.to_s, :headers => auth_header
598       assert_response :conflict,
599                       "shouldn't be able to delete a relation in a changeset owned by someone else (#{@response.body})"
600
601       # this won't work because the relation in the payload is different to that passed
602       xml = update_changeset(xml_for_relation(relation), changeset.id)
603       delete api_relation_path(create(:relation)), :params => xml.to_s, :headers => auth_header
604       assert_response :bad_request, "shouldn't be able to delete a relation when payload is different to the url"
605
606       # this won't work because the relation is in-use by another relation
607       xml = update_changeset(xml_for_relation(used_relation), changeset.id)
608       delete api_relation_path(used_relation), :params => xml.to_s, :headers => auth_header
609       assert_response :precondition_failed,
610                       "shouldn't be able to delete a relation used in a relation (#{@response.body})"
611       assert_equal "Precondition failed: The relation #{used_relation.id} is used in relation #{super_relation.id}.", @response.body
612
613       # this should work when we provide the appropriate payload...
614       xml = update_changeset(xml_for_relation(multi_tag_relation), changeset.id)
615       delete api_relation_path(multi_tag_relation), :params => xml.to_s, :headers => auth_header
616       assert_response :success
617
618       # valid delete should return the new version number, which should
619       # be greater than the old version number
620       assert_operator @response.body.to_i, :>, multi_tag_relation.version, "delete request should return a new version number for relation"
621
622       # this won't work since the relation is already deleted
623       xml = update_changeset(xml_for_relation(deleted_relation), changeset.id)
624       delete api_relation_path(deleted_relation), :params => xml.to_s, :headers => auth_header
625       assert_response :gone
626
627       # Public visible relation needs to be deleted
628       xml = update_changeset(xml_for_relation(super_relation), changeset.id)
629       delete api_relation_path(super_relation), :params => xml.to_s, :headers => auth_header
630       assert_response :success
631
632       # this works now because the relation which was using this one
633       # has been deleted.
634       xml = update_changeset(xml_for_relation(used_relation), changeset.id)
635       delete api_relation_path(used_relation), :params => xml.to_s, :headers => auth_header
636       assert_response :success,
637                       "should be able to delete a relation used in an old relation (#{@response.body})"
638
639       # this won't work since the relation never existed
640       delete api_relation_path(0), :headers => auth_header
641       assert_response :not_found
642     end
643
644     ##
645     # when a relation's tag is modified then it should put the bounding
646     # box of all its members into the changeset.
647     def test_tag_modify_bounding_box
648       relation = create(:relation)
649       node1 = create(:node, :lat => 0.3, :lon => 0.3)
650       node2 = create(:node, :lat => 0.5, :lon => 0.5)
651       way = create(:way)
652       create(:way_node, :way => way, :node => node1)
653       create(:relation_member, :relation => relation, :member => way)
654       create(:relation_member, :relation => relation, :member => node2)
655       # the relation contains nodes1 and node2 (node1
656       # indirectly via the way), so the bbox should be [0.3,0.3,0.5,0.5].
657       check_changeset_modify(BoundingBox.new(0.3, 0.3, 0.5, 0.5)) do |changeset_id, auth_header|
658         # add a tag to an existing relation
659         relation_xml = xml_for_relation(relation)
660         relation_element = relation_xml.find("//osm/relation").first
661         new_tag = XML::Node.new("tag")
662         new_tag["k"] = "some_new_tag"
663         new_tag["v"] = "some_new_value"
664         relation_element << new_tag
665
666         # update changeset ID to point to new changeset
667         update_changeset(relation_xml, changeset_id)
668
669         # upload the change
670         put api_relation_path(relation), :params => relation_xml.to_s, :headers => auth_header
671         assert_response :success, "can't update relation for tag/bbox test"
672       end
673     end
674
675     ##
676     # add a member to a relation and check the bounding box is only that
677     # element.
678     def test_add_member_bounding_box
679       relation = create(:relation)
680       node1 = create(:node, :lat => 4, :lon => 4)
681       node2 = create(:node, :lat => 7, :lon => 7)
682       way1 = create(:way)
683       create(:way_node, :way => way1, :node => create(:node, :lat => 8, :lon => 8))
684       way2 = create(:way)
685       create(:way_node, :way => way2, :node => create(:node, :lat => 9, :lon => 9), :sequence_id => 1)
686       create(:way_node, :way => way2, :node => create(:node, :lat => 10, :lon => 10), :sequence_id => 2)
687
688       [node1, node2, way1, way2].each do |element|
689         bbox = element.bbox.to_unscaled
690         check_changeset_modify(bbox) do |changeset_id, auth_header|
691           relation_xml = xml_for_relation(Relation.find(relation.id))
692           relation_element = relation_xml.find("//osm/relation").first
693           new_member = XML::Node.new("member")
694           new_member["ref"] = element.id.to_s
695           new_member["type"] = element.class.to_s.downcase
696           new_member["role"] = "some_role"
697           relation_element << new_member
698
699           # update changeset ID to point to new changeset
700           update_changeset(relation_xml, changeset_id)
701
702           # upload the change
703           put api_relation_path(relation), :params => relation_xml.to_s, :headers => auth_header
704           assert_response :success, "can't update relation for add #{element.class}/bbox test: #{@response.body}"
705
706           # get it back and check the ordering
707           get api_relation_path(relation)
708           assert_response :success, "can't read back the relation: #{@response.body}"
709           check_ordering(relation_xml, @response.body)
710         end
711       end
712     end
713
714     ##
715     # remove a member from a relation and check the bounding box is
716     # only that element.
717     def test_remove_member_bounding_box
718       relation = create(:relation)
719       node1 = create(:node, :lat => 3, :lon => 3)
720       node2 = create(:node, :lat => 5, :lon => 5)
721       create(:relation_member, :relation => relation, :member => node1)
722       create(:relation_member, :relation => relation, :member => node2)
723
724       check_changeset_modify(BoundingBox.new(5, 5, 5, 5)) do |changeset_id, auth_header|
725         # remove node 5 (5,5) from an existing relation
726         relation_xml = xml_for_relation(relation)
727         relation_xml
728           .find("//osm/relation/member[@type='node'][@ref='#{node2.id}']")
729           .first.remove!
730
731         # update changeset ID to point to new changeset
732         update_changeset(relation_xml, changeset_id)
733
734         # upload the change
735         put api_relation_path(relation), :params => relation_xml.to_s, :headers => auth_header
736         assert_response :success, "can't update relation for remove node/bbox test"
737       end
738     end
739
740     ##
741     # check that relations are ordered
742     def test_relation_member_ordering
743       user = create(:user)
744       changeset = create(:changeset, :user => user)
745       node1 = create(:node)
746       node2 = create(:node)
747       node3 = create(:node)
748       way1 = create(:way_with_nodes, :nodes_count => 2)
749       way2 = create(:way_with_nodes, :nodes_count => 2)
750
751       auth_header = bearer_authorization_header user
752
753       doc_str = <<~OSM
754         <osm>
755          <relation changeset='#{changeset.id}'>
756           <member ref='#{node1.id}' type='node' role='first'/>
757           <member ref='#{node2.id}' type='node' role='second'/>
758           <member ref='#{way1.id}' type='way' role='third'/>
759           <member ref='#{way2.id}' type='way' role='fourth'/>
760          </relation>
761         </osm>
762       OSM
763       doc = XML::Parser.string(doc_str).parse
764
765       post api_relations_path, :params => doc.to_s, :headers => auth_header
766       assert_response :success, "can't create a relation: #{@response.body}"
767       relation_id = @response.body.to_i
768
769       # get it back and check the ordering
770       get api_relation_path(relation_id)
771       assert_response :success, "can't read back the relation: #{@response.body}"
772       check_ordering(doc, @response.body)
773
774       # insert a member at the front
775       new_member = XML::Node.new "member"
776       new_member["ref"] = node3.id.to_s
777       new_member["type"] = "node"
778       new_member["role"] = "new first"
779       doc.find("//osm/relation").first.child.prev = new_member
780       # update the version, should be 1?
781       doc.find("//osm/relation").first["id"] = relation_id.to_s
782       doc.find("//osm/relation").first["version"] = 1.to_s
783
784       # upload the next version of the relation
785       put api_relation_path(relation_id), :params => doc.to_s, :headers => auth_header
786       assert_response :success, "can't update relation: #{@response.body}"
787       assert_equal 2, @response.body.to_i
788
789       # get it back again and check the ordering again
790       get api_relation_path(relation_id)
791       assert_response :success, "can't read back the relation: #{@response.body}"
792       check_ordering(doc, @response.body)
793
794       # check the ordering in the history tables:
795       with_controller(OldRelationsController.new) do
796         get api_old_relation_path(relation_id, 2)
797         assert_response :success, "can't read back version 2 of the relation #{relation_id}"
798         check_ordering(doc, @response.body)
799       end
800     end
801
802     ##
803     # check that relations can contain duplicate members
804     def test_relation_member_duplicates
805       private_user = create(:user, :data_public => false)
806       user = create(:user)
807       changeset = create(:changeset, :user => user)
808       node1 = create(:node)
809       node2 = create(:node)
810
811       doc_str = <<~OSM
812         <osm>
813          <relation changeset='#{changeset.id}'>
814           <member ref='#{node1.id}' type='node' role='forward'/>
815           <member ref='#{node2.id}' type='node' role='forward'/>
816           <member ref='#{node1.id}' type='node' role='forward'/>
817           <member ref='#{node2.id}' type='node' role='forward'/>
818          </relation>
819         </osm>
820       OSM
821       doc = XML::Parser.string(doc_str).parse
822
823       ## First try with the private user
824       auth_header = bearer_authorization_header private_user
825
826       post api_relations_path, :params => doc.to_s, :headers => auth_header
827       assert_response :forbidden
828
829       ## Now try with the public user
830       auth_header = bearer_authorization_header user
831
832       post api_relations_path, :params => doc.to_s, :headers => auth_header
833       assert_response :success, "can't create a relation: #{@response.body}"
834       relation_id = @response.body.to_i
835
836       # get it back and check the ordering
837       get api_relation_path(relation_id)
838       assert_response :success, "can't read back the relation: #{relation_id}"
839       check_ordering(doc, @response.body)
840     end
841
842     ##
843     # test that the ordering of elements in the history is the same as in current.
844     def test_history_ordering
845       user = create(:user)
846       changeset = create(:changeset, :user => user)
847       node1 = create(:node)
848       node2 = create(:node)
849       node3 = create(:node)
850       node4 = create(:node)
851
852       doc_str = <<~OSM
853         <osm>
854          <relation changeset='#{changeset.id}'>
855           <member ref='#{node1.id}' type='node' role='forward'/>
856           <member ref='#{node4.id}' type='node' role='forward'/>
857           <member ref='#{node3.id}' type='node' role='forward'/>
858           <member ref='#{node2.id}' type='node' role='forward'/>
859          </relation>
860         </osm>
861       OSM
862       doc = XML::Parser.string(doc_str).parse
863       auth_header = bearer_authorization_header user
864
865       post api_relations_path, :params => doc.to_s, :headers => auth_header
866       assert_response :success, "can't create a relation: #{@response.body}"
867       relation_id = @response.body.to_i
868
869       # check the ordering in the current tables:
870       get api_relation_path(relation_id)
871       assert_response :success, "can't read back the relation: #{@response.body}"
872       check_ordering(doc, @response.body)
873
874       # check the ordering in the history tables:
875       with_controller(OldRelationsController.new) do
876         get api_old_relation_path(relation_id, 1)
877         assert_response :success, "can't read back version 1 of the relation: #{@response.body}"
878         check_ordering(doc, @response.body)
879       end
880     end
881
882     ##
883     # remove all the members from a relation. the result is pretty useless, but
884     # still technically valid.
885     def test_remove_all_members
886       relation = create(:relation)
887       node1 = create(:node, :lat => 0.3, :lon => 0.3)
888       node2 = create(:node, :lat => 0.5, :lon => 0.5)
889       way = create(:way)
890       create(:way_node, :way => way, :node => node1)
891       create(:relation_member, :relation => relation, :member => way)
892       create(:relation_member, :relation => relation, :member => node2)
893
894       check_changeset_modify(BoundingBox.new(0.3, 0.3, 0.5, 0.5)) do |changeset_id, auth_header|
895         relation_xml = xml_for_relation(relation)
896         relation_xml
897           .find("//osm/relation/member")
898           .each(&:remove!)
899
900         # update changeset ID to point to new changeset
901         update_changeset(relation_xml, changeset_id)
902
903         # upload the change
904         put api_relation_path(relation), :params => relation_xml.to_s, :headers => auth_header
905         assert_response :success, "can't update relation for remove all members test"
906         checkrelation = Relation.find(relation.id)
907         assert_not_nil(checkrelation,
908                        "uploaded relation not found in database after upload")
909         assert_equal(0, checkrelation.members.length,
910                      "relation contains members but they should have all been deleted")
911       end
912     end
913
914     ##
915     # test initial rate limit
916     def test_initial_rate_limit
917       # create a user
918       user = create(:user)
919
920       # create some nodes
921       node1 = create(:node)
922       node2 = create(:node)
923
924       # create a changeset that puts us near the initial rate limit
925       changeset = create(:changeset, :user => user,
926                                      :created_at => Time.now.utc - 5.minutes,
927                                      :num_changes => Settings.initial_changes_per_hour - 1)
928
929       # create authentication header
930       auth_header = bearer_authorization_header user
931
932       # try creating a relation
933       xml = "<osm><relation changeset='#{changeset.id}'>" \
934             "<member  ref='#{node1.id}' type='node' role='some'/>" \
935             "<member  ref='#{node2.id}' type='node' role='some'/>" \
936             "<tag k='test' v='yes' /></relation></osm>"
937       post api_relations_path, :params => xml, :headers => auth_header
938       assert_response :success, "relation create did not return success status"
939
940       # get the id of the relation we created
941       relationid = @response.body
942
943       # try updating the relation, which should be rate limited
944       xml = "<osm><relation id='#{relationid}' version='1' changeset='#{changeset.id}'>" \
945             "<member  ref='#{node2.id}' type='node' role='some'/>" \
946             "<member  ref='#{node1.id}' type='node' role='some'/>" \
947             "<tag k='test' v='yes' /></relation></osm>"
948       put api_relation_path(relationid), :params => xml, :headers => auth_header
949       assert_response :too_many_requests, "relation update did not hit rate limit"
950
951       # try deleting the relation, which should be rate limited
952       xml = "<osm><relation id='#{relationid}' version='2' changeset='#{changeset.id}'/></osm>"
953       delete api_relation_path(relationid), :params => xml, :headers => auth_header
954       assert_response :too_many_requests, "relation delete did not hit rate limit"
955
956       # try creating a relation, which should be rate limited
957       xml = "<osm><relation changeset='#{changeset.id}'>" \
958             "<member  ref='#{node1.id}' type='node' role='some'/>" \
959             "<member  ref='#{node2.id}' type='node' role='some'/>" \
960             "<tag k='test' v='yes' /></relation></osm>"
961       post api_relations_path, :params => xml, :headers => auth_header
962       assert_response :too_many_requests, "relation create did not hit rate limit"
963     end
964
965     ##
966     # test maximum rate limit
967     def test_maximum_rate_limit
968       # create a user
969       user = create(:user)
970
971       # create some nodes
972       node1 = create(:node)
973       node2 = create(:node)
974
975       # create a changeset to establish our initial edit time
976       changeset = create(:changeset, :user => user,
977                                      :created_at => Time.now.utc - 28.days)
978
979       # create changeset to put us near the maximum rate limit
980       total_changes = Settings.max_changes_per_hour - 1
981       while total_changes.positive?
982         changes = [total_changes, Changeset::MAX_ELEMENTS].min
983         changeset = create(:changeset, :user => user,
984                                        :created_at => Time.now.utc - 5.minutes,
985                                        :num_changes => changes)
986         total_changes -= changes
987       end
988
989       # create authentication header
990       auth_header = bearer_authorization_header user
991
992       # try creating a relation
993       xml = "<osm><relation changeset='#{changeset.id}'>" \
994             "<member  ref='#{node1.id}' type='node' role='some'/>" \
995             "<member  ref='#{node2.id}' type='node' role='some'/>" \
996             "<tag k='test' v='yes' /></relation></osm>"
997       post api_relations_path, :params => xml, :headers => auth_header
998       assert_response :success, "relation create did not return success status"
999
1000       # get the id of the relation we created
1001       relationid = @response.body
1002
1003       # try updating the relation, which should be rate limited
1004       xml = "<osm><relation id='#{relationid}' version='1' changeset='#{changeset.id}'>" \
1005             "<member  ref='#{node2.id}' type='node' role='some'/>" \
1006             "<member  ref='#{node1.id}' type='node' role='some'/>" \
1007             "<tag k='test' v='yes' /></relation></osm>"
1008       put api_relation_path(relationid), :params => xml, :headers => auth_header
1009       assert_response :too_many_requests, "relation update did not hit rate limit"
1010
1011       # try deleting the relation, which should be rate limited
1012       xml = "<osm><relation id='#{relationid}' version='2' changeset='#{changeset.id}'/></osm>"
1013       delete api_relation_path(relationid), :params => xml, :headers => auth_header
1014       assert_response :too_many_requests, "relation delete did not hit rate limit"
1015
1016       # try creating a relation, which should be rate limited
1017       xml = "<osm><relation changeset='#{changeset.id}'>" \
1018             "<member  ref='#{node1.id}' type='node' role='some'/>" \
1019             "<member  ref='#{node2.id}' type='node' role='some'/>" \
1020             "<tag k='test' v='yes' /></relation></osm>"
1021       post api_relations_path, :params => xml, :headers => auth_header
1022       assert_response :too_many_requests, "relation create did not hit rate limit"
1023     end
1024
1025     private
1026
1027     def check_relations_for_element(path, type, id, expected_relations)
1028       # check the "relations for relation" mode
1029       get path
1030       assert_response :success
1031
1032       # count one osm element
1033       assert_select "osm[version='#{Settings.api_version}'][generator='#{Settings.generator}']", 1
1034
1035       # we should have only the expected number of relations
1036       assert_select "osm>relation", expected_relations.size
1037
1038       # and each of them should contain the element we originally searched for
1039       expected_relations.each do |relation|
1040         # The relation should appear once, but the element could appear multiple times
1041         assert_select "osm>relation[id='#{relation.id}']", 1
1042         assert_select "osm>relation[id='#{relation.id}']>member[type='#{type}'][ref='#{id}']"
1043       end
1044     end
1045
1046     ##
1047     # checks that the XML document and the string arguments have
1048     # members in the same order.
1049     def check_ordering(doc, xml)
1050       new_doc = XML::Parser.string(xml).parse
1051
1052       doc_members = doc.find("//osm/relation/member").collect do |m|
1053         [m["ref"].to_i, m["type"].to_sym, m["role"]]
1054       end
1055
1056       new_members = new_doc.find("//osm/relation/member").collect do |m|
1057         [m["ref"].to_i, m["type"].to_sym, m["role"]]
1058       end
1059
1060       doc_members.zip(new_members).each do |d, n|
1061         assert_equal d, n, "members are not equal - ordering is wrong? (#{doc}, #{xml})"
1062       end
1063     end
1064
1065     ##
1066     # create a changeset and yield to the caller to set it up, then assert
1067     # that the changeset bounding box is +bbox+.
1068     def check_changeset_modify(bbox)
1069       ## First test with the private user to check that you get a forbidden
1070       auth_header = bearer_authorization_header create(:user, :data_public => false)
1071
1072       # create a new changeset for this operation, so we are assured
1073       # that the bounding box will be newly-generated.
1074       with_controller(Api::ChangesetsController.new) do
1075         xml = "<osm><changeset/></osm>"
1076         put changeset_create_path, :params => xml, :headers => auth_header
1077         assert_response :forbidden, "shouldn't be able to create changeset for modify test, as should get forbidden"
1078       end
1079
1080       ## Now do the whole thing with the public user
1081       auth_header = bearer_authorization_header
1082
1083       # create a new changeset for this operation, so we are assured
1084       # that the bounding box will be newly-generated.
1085       changeset_id = with_controller(Api::ChangesetsController.new) do
1086         xml = "<osm><changeset/></osm>"
1087         put changeset_create_path, :params => xml, :headers => auth_header
1088         assert_response :success, "couldn't create changeset for modify test"
1089         @response.body.to_i
1090       end
1091
1092       # go back to the block to do the actual modifies
1093       yield changeset_id, auth_header
1094
1095       # now download the changeset to check its bounding box
1096       with_controller(Api::ChangesetsController.new) do
1097         get changeset_show_path(changeset_id)
1098         assert_response :success, "can't re-read changeset for modify test"
1099         assert_select "osm>changeset", 1, "Changeset element doesn't exist in #{@response.body}"
1100         assert_select "osm>changeset[id='#{changeset_id}']", 1, "Changeset id=#{changeset_id} doesn't exist in #{@response.body}"
1101         assert_select "osm>changeset[min_lon='#{format('%<lon>.7f', :lon => bbox.min_lon)}']", 1, "Changeset min_lon wrong in #{@response.body}"
1102         assert_select "osm>changeset[min_lat='#{format('%<lat>.7f', :lat => bbox.min_lat)}']", 1, "Changeset min_lat wrong in #{@response.body}"
1103         assert_select "osm>changeset[max_lon='#{format('%<lon>.7f', :lon => bbox.max_lon)}']", 1, "Changeset max_lon wrong in #{@response.body}"
1104         assert_select "osm>changeset[max_lat='#{format('%<lat>.7f', :lat => bbox.max_lat)}']", 1, "Changeset max_lat wrong in #{@response.body}"
1105       end
1106     end
1107
1108     ##
1109     # yields the relation with the given +id+ (and optional +version+
1110     # to read from the history tables) into the block. the parsed XML
1111     # doc is returned.
1112     def with_relation(id, ver = nil)
1113       if ver.nil?
1114         get api_relation_path(id)
1115       else
1116         with_controller(OldRelationsController.new) do
1117           get api_old_relation_path(id, ver)
1118         end
1119       end
1120       assert_response :success
1121       yield xml_parse(@response.body)
1122     end
1123
1124     ##
1125     # updates the relation (XML) +rel+ and
1126     # yields the new version of that relation into the block.
1127     # the parsed XML doc is returned.
1128     def with_update(rel, headers)
1129       rel_id = rel.find("//osm/relation").first["id"].to_i
1130       put api_relation_path(rel_id), :params => rel.to_s, :headers => headers
1131       assert_response :success, "can't update relation: #{@response.body}"
1132       version = @response.body.to_i
1133
1134       # now get the new version
1135       get api_relation_path(rel_id)
1136       assert_response :success
1137       new_rel = xml_parse(@response.body)
1138
1139       yield new_rel
1140
1141       version
1142     end
1143
1144     ##
1145     # updates the relation (XML) +rel+ via the diff-upload API and
1146     # yields the new version of that relation into the block.
1147     # the parsed XML doc is returned.
1148     def with_update_diff(rel, headers)
1149       rel_id = rel.find("//osm/relation").first["id"].to_i
1150       cs_id = rel.find("//osm/relation").first["changeset"].to_i
1151       version = nil
1152
1153       with_controller(Api::ChangesetsController.new) do
1154         doc = OSM::API.new.xml_doc
1155         change = XML::Node.new "osmChange"
1156         doc.root = change
1157         modify = XML::Node.new "modify"
1158         change << modify
1159         modify << doc.import(rel.find("//osm/relation").first)
1160
1161         post changeset_upload_path(cs_id), :params => doc.to_s, :headers => headers
1162         assert_response :success, "can't upload diff relation: #{@response.body}"
1163         version = xml_parse(@response.body).find("//diffResult/relation").first["new_version"].to_i
1164       end
1165
1166       # now get the new version
1167       get api_relation_path(rel_id)
1168       assert_response :success
1169       new_rel = xml_parse(@response.body)
1170
1171       yield new_rel
1172
1173       version
1174     end
1175
1176     ##
1177     # returns a k->v hash of tags from an xml doc
1178     def get_tags_as_hash(a)
1179       a.find("//osm/relation/tag").sort_by { |v| v["k"] }.each_with_object({}) do |v, h|
1180         h[v["k"]] = v["v"]
1181       end
1182     end
1183
1184     ##
1185     # assert that all tags on relation documents +a+ and +b+
1186     # are equal
1187     def assert_tags_equal(a, b)
1188       # turn the XML doc into tags hashes
1189       a_tags = get_tags_as_hash(a)
1190       b_tags = get_tags_as_hash(b)
1191
1192       assert_equal a_tags.keys, b_tags.keys, "Tag keys should be identical."
1193       a_tags.each do |k, v|
1194         assert_equal v, b_tags[k],
1195                      "Tags which were not altered should be the same. " \
1196                      "#{a_tags.inspect} != #{b_tags.inspect}"
1197       end
1198     end
1199
1200     ##
1201     # update the changeset_id of a node element
1202     def update_changeset(xml, changeset_id)
1203       xml_attr_rewrite(xml, "changeset", changeset_id)
1204     end
1205
1206     ##
1207     # update an attribute in the node element
1208     def xml_attr_rewrite(xml, name, value)
1209       xml.find("//osm/relation").first[name] = value.to_s
1210       xml
1211     end
1212
1213     ##
1214     # parse some xml
1215     def xml_parse(xml)
1216       parser = XML::Parser.string(xml)
1217       parser.parse
1218     end
1219   end
1220 end