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