]> git.openstreetmap.org Git - rails.git/blob - test/controllers/api/relations_controller_test.rb
Change method to compare tags with response
[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
400       # check that the downloaded tags are the same as the uploaded tags...
401       new_version = do_update(rel, rel_id, auth_header)
402       get api_relation_path(rel_id)
403       assert_tags_equal_response rel
404
405       # check the original one in the current_* table again
406       get api_relation_path(relation)
407       assert_tags_equal_response rel
408
409       # now check the version in the history
410       get api_relation_version_path(relation, new_version)
411       assert_tags_equal_response rel
412     end
413
414     ##
415     # test that, when tags are updated on a relation when using the diff
416     # upload function, the correct things happen to the correct tables
417     # and the API gives sensible results. this is to test a case that
418     # gregory marler noticed and posted to josm-dev.
419     def test_update_relation_tags_via_upload
420       user = create(:user)
421       changeset = create(:changeset, :user => user)
422       relation = create(:relation)
423       create_list(:relation_tag, 4, :relation => relation)
424
425       auth_header = bearer_authorization_header user
426
427       get api_relation_path(relation)
428       assert_response :success
429       rel = xml_parse(@response.body)
430       rel_id = rel.find("//osm/relation").first["id"].to_i
431
432       # alter one of the tags
433       tag = rel.find("//osm/relation/tag").first
434       tag["v"] = "some changed value"
435       update_changeset(rel, changeset.id)
436
437       # check that the downloaded tags are the same as the uploaded tags...
438       new_version = do_update_diff(rel, auth_header)
439       get api_relation_path(rel_id)
440       assert_tags_equal_response rel
441
442       # check the original one in the current_* table again
443       get api_relation_path(relation)
444       assert_tags_equal_response rel
445
446       # now check the version in the history
447       get api_relation_version_path(relation, new_version)
448       assert_tags_equal_response rel
449     end
450
451     def test_update_wrong_id
452       user = create(:user)
453       changeset = create(:changeset, :user => user)
454       relation = create(:relation)
455       other_relation = create(:relation)
456
457       auth_header = bearer_authorization_header user
458       get api_relation_path(relation)
459       assert_response :success
460       rel = xml_parse(@response.body)
461
462       update_changeset(rel, changeset.id)
463       put api_relation_path(other_relation), :params => rel.to_s, :headers => auth_header
464       assert_response :bad_request
465     end
466
467     # -------------------------------------
468     # Test creating some invalid relations.
469     # -------------------------------------
470
471     def test_create_invalid
472       user = create(:user)
473       changeset = create(:changeset, :user => user)
474
475       auth_header = bearer_authorization_header user
476
477       # create a relation with non-existing node as member
478       xml = "<osm><relation changeset='#{changeset.id}'>" \
479             "<member type='node' ref='0'/><tag k='test' v='yes' />" \
480             "</relation></osm>"
481       post api_relations_path, :params => xml, :headers => auth_header
482       # expect failure
483       assert_response :precondition_failed,
484                       "relation upload with invalid node did not return 'precondition failed'"
485       assert_equal "Precondition failed: Relation with id  cannot be saved due to Node with id 0", @response.body
486     end
487
488     # -------------------------------------
489     # Test creating a relation, with some invalid XML
490     # -------------------------------------
491     def test_create_invalid_xml
492       user = create(:user)
493       changeset = create(:changeset, :user => user)
494       node = create(:node)
495
496       auth_header = bearer_authorization_header user
497
498       # create some xml that should return an error
499       xml = "<osm><relation changeset='#{changeset.id}'>" \
500             "<member type='type' ref='#{node.id}' role=''/>" \
501             "<tag k='tester' v='yep'/></relation></osm>"
502       post api_relations_path, :params => xml, :headers => auth_header
503       # expect failure
504       assert_response :bad_request
505       assert_match(/Cannot parse valid relation from xml string/, @response.body)
506       assert_match(/The type is not allowed only, /, @response.body)
507     end
508
509     # -------------------------------------
510     # Test deleting relations.
511     # -------------------------------------
512
513     def test_destroy
514       private_user = create(:user, :data_public => false)
515       private_user_closed_changeset = create(:changeset, :closed, :user => private_user)
516       user = create(:user)
517       closed_changeset = create(:changeset, :closed, :user => user)
518       changeset = create(:changeset, :user => user)
519       relation = create(:relation)
520       used_relation = create(:relation)
521       super_relation = create(:relation_member, :member => used_relation).relation
522       deleted_relation = create(:relation, :deleted)
523       multi_tag_relation = create(:relation)
524       create_list(:relation_tag, 4, :relation => multi_tag_relation)
525
526       ## First try to delete relation without auth
527       delete api_relation_path(relation)
528       assert_response :unauthorized
529
530       ## Then try with the private user, to make sure that you get a forbidden
531       auth_header = bearer_authorization_header private_user
532
533       # this shouldn't work, as we should need the payload...
534       delete api_relation_path(relation), :headers => auth_header
535       assert_response :forbidden
536
537       # try to delete without specifying a changeset
538       xml = "<osm><relation id='#{relation.id}'/></osm>"
539       delete api_relation_path(relation), :params => xml.to_s, :headers => auth_header
540       assert_response :forbidden
541
542       # try to delete with an invalid (closed) changeset
543       xml = update_changeset(xml_for_relation(relation),
544                              private_user_closed_changeset.id)
545       delete api_relation_path(relation), :params => xml.to_s, :headers => auth_header
546       assert_response :forbidden
547
548       # try to delete with an invalid (non-existent) changeset
549       xml = update_changeset(xml_for_relation(relation), 0)
550       delete api_relation_path(relation), :params => xml.to_s, :headers => auth_header
551       assert_response :forbidden
552
553       # this won't work because the relation is in-use by another relation
554       xml = xml_for_relation(used_relation)
555       delete api_relation_path(used_relation), :params => xml.to_s, :headers => auth_header
556       assert_response :forbidden
557
558       # this should work when we provide the appropriate payload...
559       xml = xml_for_relation(relation)
560       delete api_relation_path(relation), :params => xml.to_s, :headers => auth_header
561       assert_response :forbidden
562
563       # this won't work since the relation is already deleted
564       xml = xml_for_relation(deleted_relation)
565       delete api_relation_path(deleted_relation), :params => xml.to_s, :headers => auth_header
566       assert_response :forbidden
567
568       # this won't work since the relation never existed
569       delete api_relation_path(0), :headers => auth_header
570       assert_response :forbidden
571
572       ## now set auth for the public user
573       auth_header = bearer_authorization_header user
574
575       # this shouldn't work, as we should need the payload...
576       delete api_relation_path(relation), :headers => auth_header
577       assert_response :bad_request
578
579       # try to delete without specifying a changeset
580       xml = "<osm><relation id='#{relation.id}' version='#{relation.version}' /></osm>"
581       delete api_relation_path(relation), :params => xml.to_s, :headers => auth_header
582       assert_response :bad_request
583       assert_match(/Changeset id is missing/, @response.body)
584
585       # try to delete with an invalid (closed) changeset
586       xml = update_changeset(xml_for_relation(relation),
587                              closed_changeset.id)
588       delete api_relation_path(relation), :params => xml.to_s, :headers => auth_header
589       assert_response :conflict
590
591       # try to delete with an invalid (non-existent) changeset
592       xml = update_changeset(xml_for_relation(relation), 0)
593       delete api_relation_path(relation), :params => xml.to_s, :headers => auth_header
594       assert_response :conflict
595
596       # this won't work because the relation is in a changeset owned by someone else
597       xml = update_changeset(xml_for_relation(relation), create(:changeset).id)
598       delete api_relation_path(relation), :params => xml.to_s, :headers => auth_header
599       assert_response :conflict,
600                       "shouldn't be able to delete a relation in a changeset owned by someone else (#{@response.body})"
601
602       # this won't work because the relation in the payload is different to that passed
603       xml = update_changeset(xml_for_relation(relation), changeset.id)
604       delete api_relation_path(create(:relation)), :params => xml.to_s, :headers => auth_header
605       assert_response :bad_request, "shouldn't be able to delete a relation when payload is different to the url"
606
607       # this won't work because the relation is in-use by another relation
608       xml = update_changeset(xml_for_relation(used_relation), changeset.id)
609       delete api_relation_path(used_relation), :params => xml.to_s, :headers => auth_header
610       assert_response :precondition_failed,
611                       "shouldn't be able to delete a relation used in a relation (#{@response.body})"
612       assert_equal "Precondition failed: The relation #{used_relation.id} is used in relation #{super_relation.id}.", @response.body
613
614       # this should work when we provide the appropriate payload...
615       xml = update_changeset(xml_for_relation(multi_tag_relation), changeset.id)
616       delete api_relation_path(multi_tag_relation), :params => xml.to_s, :headers => auth_header
617       assert_response :success
618
619       # valid delete should return the new version number, which should
620       # be greater than the old version number
621       assert_operator @response.body.to_i, :>, multi_tag_relation.version, "delete request should return a new version number for relation"
622
623       # this won't work since the relation is already deleted
624       xml = update_changeset(xml_for_relation(deleted_relation), changeset.id)
625       delete api_relation_path(deleted_relation), :params => xml.to_s, :headers => auth_header
626       assert_response :gone
627
628       # Public visible relation needs to be deleted
629       xml = update_changeset(xml_for_relation(super_relation), changeset.id)
630       delete api_relation_path(super_relation), :params => xml.to_s, :headers => auth_header
631       assert_response :success
632
633       # this works now because the relation which was using this one
634       # has been deleted.
635       xml = update_changeset(xml_for_relation(used_relation), changeset.id)
636       delete api_relation_path(used_relation), :params => xml.to_s, :headers => auth_header
637       assert_response :success,
638                       "should be able to delete a relation used in an old relation (#{@response.body})"
639
640       # this won't work since the relation never existed
641       delete api_relation_path(0), :headers => auth_header
642       assert_response :not_found
643     end
644
645     ##
646     # when a relation's tag is modified then it should put the bounding
647     # box of all its members into the changeset.
648     def test_tag_modify_bounding_box
649       relation = create(:relation)
650       node1 = create(:node, :lat => 0.3, :lon => 0.3)
651       node2 = create(:node, :lat => 0.5, :lon => 0.5)
652       way = create(:way)
653       create(:way_node, :way => way, :node => node1)
654       create(:relation_member, :relation => relation, :member => way)
655       create(:relation_member, :relation => relation, :member => node2)
656       # the relation contains nodes1 and node2 (node1
657       # indirectly via the way), so the bbox should be [0.3,0.3,0.5,0.5].
658       check_changeset_modify(BoundingBox.new(0.3, 0.3, 0.5, 0.5)) do |changeset_id, auth_header|
659         # add a tag to an existing relation
660         relation_xml = xml_for_relation(relation)
661         relation_element = relation_xml.find("//osm/relation").first
662         new_tag = XML::Node.new("tag")
663         new_tag["k"] = "some_new_tag"
664         new_tag["v"] = "some_new_value"
665         relation_element << new_tag
666
667         # update changeset ID to point to new changeset
668         update_changeset(relation_xml, changeset_id)
669
670         # upload the change
671         put api_relation_path(relation), :params => relation_xml.to_s, :headers => auth_header
672         assert_response :success, "can't update relation for tag/bbox test"
673       end
674     end
675
676     ##
677     # add a member to a relation and check the bounding box is only that
678     # element.
679     def test_add_member_bounding_box
680       relation = create(:relation)
681       node1 = create(:node, :lat => 4, :lon => 4)
682       node2 = create(:node, :lat => 7, :lon => 7)
683       way1 = create(:way)
684       create(:way_node, :way => way1, :node => create(:node, :lat => 8, :lon => 8))
685       way2 = create(:way)
686       create(:way_node, :way => way2, :node => create(:node, :lat => 9, :lon => 9), :sequence_id => 1)
687       create(:way_node, :way => way2, :node => create(:node, :lat => 10, :lon => 10), :sequence_id => 2)
688
689       [node1, node2, way1, way2].each do |element|
690         bbox = element.bbox.to_unscaled
691         check_changeset_modify(bbox) do |changeset_id, auth_header|
692           relation_xml = xml_for_relation(Relation.find(relation.id))
693           relation_element = relation_xml.find("//osm/relation").first
694           new_member = XML::Node.new("member")
695           new_member["ref"] = element.id.to_s
696           new_member["type"] = element.class.to_s.downcase
697           new_member["role"] = "some_role"
698           relation_element << new_member
699
700           # update changeset ID to point to new changeset
701           update_changeset(relation_xml, changeset_id)
702
703           # upload the change
704           put api_relation_path(relation), :params => relation_xml.to_s, :headers => auth_header
705           assert_response :success, "can't update relation for add #{element.class}/bbox test: #{@response.body}"
706
707           # get it back and check the ordering
708           get api_relation_path(relation)
709           assert_response :success, "can't read back the relation: #{@response.body}"
710           check_ordering(relation_xml, @response.body)
711         end
712       end
713     end
714
715     ##
716     # remove a member from a relation and check the bounding box is
717     # only that element.
718     def test_remove_member_bounding_box
719       relation = create(:relation)
720       node1 = create(:node, :lat => 3, :lon => 3)
721       node2 = create(:node, :lat => 5, :lon => 5)
722       create(:relation_member, :relation => relation, :member => node1)
723       create(:relation_member, :relation => relation, :member => node2)
724
725       check_changeset_modify(BoundingBox.new(5, 5, 5, 5)) do |changeset_id, auth_header|
726         # remove node 5 (5,5) from an existing relation
727         relation_xml = xml_for_relation(relation)
728         relation_xml
729           .find("//osm/relation/member[@type='node'][@ref='#{node2.id}']")
730           .first.remove!
731
732         # update changeset ID to point to new changeset
733         update_changeset(relation_xml, changeset_id)
734
735         # upload the change
736         put api_relation_path(relation), :params => relation_xml.to_s, :headers => auth_header
737         assert_response :success, "can't update relation for remove node/bbox test"
738       end
739     end
740
741     ##
742     # check that relations are ordered
743     def test_relation_member_ordering
744       user = create(:user)
745       changeset = create(:changeset, :user => user)
746       node1 = create(:node)
747       node2 = create(:node)
748       node3 = create(:node)
749       way1 = create(:way_with_nodes, :nodes_count => 2)
750       way2 = create(:way_with_nodes, :nodes_count => 2)
751
752       auth_header = bearer_authorization_header user
753
754       doc_str = <<~OSM
755         <osm>
756          <relation changeset='#{changeset.id}'>
757           <member ref='#{node1.id}' type='node' role='first'/>
758           <member ref='#{node2.id}' type='node' role='second'/>
759           <member ref='#{way1.id}' type='way' role='third'/>
760           <member ref='#{way2.id}' type='way' role='fourth'/>
761          </relation>
762         </osm>
763       OSM
764       doc = XML::Parser.string(doc_str).parse
765
766       post api_relations_path, :params => doc.to_s, :headers => auth_header
767       assert_response :success, "can't create a relation: #{@response.body}"
768       relation_id = @response.body.to_i
769
770       # get it back and check the ordering
771       get api_relation_path(relation_id)
772       assert_response :success, "can't read back the relation: #{@response.body}"
773       check_ordering(doc, @response.body)
774
775       # insert a member at the front
776       new_member = XML::Node.new "member"
777       new_member["ref"] = node3.id.to_s
778       new_member["type"] = "node"
779       new_member["role"] = "new first"
780       doc.find("//osm/relation").first.child.prev = new_member
781       # update the version, should be 1?
782       doc.find("//osm/relation").first["id"] = relation_id.to_s
783       doc.find("//osm/relation").first["version"] = 1.to_s
784
785       # upload the next version of the relation
786       put api_relation_path(relation_id), :params => doc.to_s, :headers => auth_header
787       assert_response :success, "can't update relation: #{@response.body}"
788       assert_equal 2, @response.body.to_i
789
790       # get it back again and check the ordering again
791       get api_relation_path(relation_id)
792       assert_response :success, "can't read back the relation: #{@response.body}"
793       check_ordering(doc, @response.body)
794
795       # check the ordering in the history tables:
796       with_controller(OldRelationsController.new) do
797         get api_relation_version_path(relation_id, 2)
798         assert_response :success, "can't read back version 2 of the relation #{relation_id}"
799         check_ordering(doc, @response.body)
800       end
801     end
802
803     ##
804     # check that relations can contain duplicate members
805     def test_relation_member_duplicates
806       private_user = create(:user, :data_public => false)
807       user = create(:user)
808       changeset = create(:changeset, :user => user)
809       node1 = create(:node)
810       node2 = create(:node)
811
812       doc_str = <<~OSM
813         <osm>
814          <relation changeset='#{changeset.id}'>
815           <member ref='#{node1.id}' type='node' role='forward'/>
816           <member ref='#{node2.id}' type='node' role='forward'/>
817           <member ref='#{node1.id}' type='node' role='forward'/>
818           <member ref='#{node2.id}' type='node' role='forward'/>
819          </relation>
820         </osm>
821       OSM
822       doc = XML::Parser.string(doc_str).parse
823
824       ## First try with the private user
825       auth_header = bearer_authorization_header private_user
826
827       post api_relations_path, :params => doc.to_s, :headers => auth_header
828       assert_response :forbidden
829
830       ## Now try with the public user
831       auth_header = bearer_authorization_header user
832
833       post api_relations_path, :params => doc.to_s, :headers => auth_header
834       assert_response :success, "can't create a relation: #{@response.body}"
835       relation_id = @response.body.to_i
836
837       # get it back and check the ordering
838       get api_relation_path(relation_id)
839       assert_response :success, "can't read back the relation: #{relation_id}"
840       check_ordering(doc, @response.body)
841     end
842
843     ##
844     # test that the ordering of elements in the history is the same as in current.
845     def test_history_ordering
846       user = create(:user)
847       changeset = create(:changeset, :user => user)
848       node1 = create(:node)
849       node2 = create(:node)
850       node3 = create(:node)
851       node4 = create(:node)
852
853       doc_str = <<~OSM
854         <osm>
855          <relation changeset='#{changeset.id}'>
856           <member ref='#{node1.id}' type='node' role='forward'/>
857           <member ref='#{node4.id}' type='node' role='forward'/>
858           <member ref='#{node3.id}' type='node' role='forward'/>
859           <member ref='#{node2.id}' type='node' role='forward'/>
860          </relation>
861         </osm>
862       OSM
863       doc = XML::Parser.string(doc_str).parse
864       auth_header = bearer_authorization_header user
865
866       post api_relations_path, :params => doc.to_s, :headers => auth_header
867       assert_response :success, "can't create a relation: #{@response.body}"
868       relation_id = @response.body.to_i
869
870       # check the ordering in the current tables:
871       get api_relation_path(relation_id)
872       assert_response :success, "can't read back the relation: #{@response.body}"
873       check_ordering(doc, @response.body)
874
875       # check the ordering in the history tables:
876       with_controller(OldRelationsController.new) do
877         get api_relation_version_path(relation_id, 1)
878         assert_response :success, "can't read back version 1 of the relation: #{@response.body}"
879         check_ordering(doc, @response.body)
880       end
881     end
882
883     ##
884     # remove all the members from a relation. the result is pretty useless, but
885     # still technically valid.
886     def test_remove_all_members
887       relation = create(:relation)
888       node1 = create(:node, :lat => 0.3, :lon => 0.3)
889       node2 = create(:node, :lat => 0.5, :lon => 0.5)
890       way = create(:way)
891       create(:way_node, :way => way, :node => node1)
892       create(:relation_member, :relation => relation, :member => way)
893       create(:relation_member, :relation => relation, :member => node2)
894
895       check_changeset_modify(BoundingBox.new(0.3, 0.3, 0.5, 0.5)) do |changeset_id, auth_header|
896         relation_xml = xml_for_relation(relation)
897         relation_xml
898           .find("//osm/relation/member")
899           .each(&:remove!)
900
901         # update changeset ID to point to new changeset
902         update_changeset(relation_xml, changeset_id)
903
904         # upload the change
905         put api_relation_path(relation), :params => relation_xml.to_s, :headers => auth_header
906         assert_response :success, "can't update relation for remove all members test"
907         checkrelation = Relation.find(relation.id)
908         assert_not_nil(checkrelation,
909                        "uploaded relation not found in database after upload")
910         assert_equal(0, checkrelation.members.length,
911                      "relation contains members but they should have all been deleted")
912       end
913     end
914
915     ##
916     # test initial rate limit
917     def test_initial_rate_limit
918       # create a user
919       user = create(:user)
920
921       # create some nodes
922       node1 = create(:node)
923       node2 = create(:node)
924
925       # create a changeset that puts us near the initial rate limit
926       changeset = create(:changeset, :user => user,
927                                      :created_at => Time.now.utc - 5.minutes,
928                                      :num_changes => Settings.initial_changes_per_hour - 1)
929
930       # create authentication header
931       auth_header = bearer_authorization_header user
932
933       # try creating a relation
934       xml = "<osm><relation changeset='#{changeset.id}'>" \
935             "<member  ref='#{node1.id}' type='node' role='some'/>" \
936             "<member  ref='#{node2.id}' type='node' role='some'/>" \
937             "<tag k='test' v='yes' /></relation></osm>"
938       post api_relations_path, :params => xml, :headers => auth_header
939       assert_response :success, "relation create did not return success status"
940
941       # get the id of the relation we created
942       relationid = @response.body
943
944       # try updating the relation, which should be rate limited
945       xml = "<osm><relation id='#{relationid}' version='1' changeset='#{changeset.id}'>" \
946             "<member  ref='#{node2.id}' type='node' role='some'/>" \
947             "<member  ref='#{node1.id}' type='node' role='some'/>" \
948             "<tag k='test' v='yes' /></relation></osm>"
949       put api_relation_path(relationid), :params => xml, :headers => auth_header
950       assert_response :too_many_requests, "relation update did not hit rate limit"
951
952       # try deleting the relation, which should be rate limited
953       xml = "<osm><relation id='#{relationid}' version='2' changeset='#{changeset.id}'/></osm>"
954       delete api_relation_path(relationid), :params => xml, :headers => auth_header
955       assert_response :too_many_requests, "relation delete did not hit rate limit"
956
957       # try creating a relation, which should be rate limited
958       xml = "<osm><relation changeset='#{changeset.id}'>" \
959             "<member  ref='#{node1.id}' type='node' role='some'/>" \
960             "<member  ref='#{node2.id}' type='node' role='some'/>" \
961             "<tag k='test' v='yes' /></relation></osm>"
962       post api_relations_path, :params => xml, :headers => auth_header
963       assert_response :too_many_requests, "relation create did not hit rate limit"
964     end
965
966     ##
967     # test maximum rate limit
968     def test_maximum_rate_limit
969       # create a user
970       user = create(:user)
971
972       # create some nodes
973       node1 = create(:node)
974       node2 = create(:node)
975
976       # create a changeset to establish our initial edit time
977       changeset = create(:changeset, :user => user,
978                                      :created_at => Time.now.utc - 28.days)
979
980       # create changeset to put us near the maximum rate limit
981       total_changes = Settings.max_changes_per_hour - 1
982       while total_changes.positive?
983         changes = [total_changes, Changeset::MAX_ELEMENTS].min
984         changeset = create(:changeset, :user => user,
985                                        :created_at => Time.now.utc - 5.minutes,
986                                        :num_changes => changes)
987         total_changes -= changes
988       end
989
990       # create authentication header
991       auth_header = bearer_authorization_header user
992
993       # try creating a relation
994       xml = "<osm><relation changeset='#{changeset.id}'>" \
995             "<member  ref='#{node1.id}' type='node' role='some'/>" \
996             "<member  ref='#{node2.id}' type='node' role='some'/>" \
997             "<tag k='test' v='yes' /></relation></osm>"
998       post api_relations_path, :params => xml, :headers => auth_header
999       assert_response :success, "relation create did not return success status"
1000
1001       # get the id of the relation we created
1002       relationid = @response.body
1003
1004       # try updating the relation, which should be rate limited
1005       xml = "<osm><relation id='#{relationid}' version='1' changeset='#{changeset.id}'>" \
1006             "<member  ref='#{node2.id}' type='node' role='some'/>" \
1007             "<member  ref='#{node1.id}' type='node' role='some'/>" \
1008             "<tag k='test' v='yes' /></relation></osm>"
1009       put api_relation_path(relationid), :params => xml, :headers => auth_header
1010       assert_response :too_many_requests, "relation update did not hit rate limit"
1011
1012       # try deleting the relation, which should be rate limited
1013       xml = "<osm><relation id='#{relationid}' version='2' changeset='#{changeset.id}'/></osm>"
1014       delete api_relation_path(relationid), :params => xml, :headers => auth_header
1015       assert_response :too_many_requests, "relation delete did not hit rate limit"
1016
1017       # try creating a relation, which should be rate limited
1018       xml = "<osm><relation changeset='#{changeset.id}'>" \
1019             "<member  ref='#{node1.id}' type='node' role='some'/>" \
1020             "<member  ref='#{node2.id}' type='node' role='some'/>" \
1021             "<tag k='test' v='yes' /></relation></osm>"
1022       post api_relations_path, :params => xml, :headers => auth_header
1023       assert_response :too_many_requests, "relation create did not hit rate limit"
1024     end
1025
1026     private
1027
1028     ##
1029     # checks that the XML document and the string arguments have
1030     # members in the same order.
1031     def check_ordering(doc, xml)
1032       new_doc = XML::Parser.string(xml).parse
1033
1034       doc_members = doc.find("//osm/relation/member").collect do |m|
1035         [m["ref"].to_i, m["type"].to_sym, m["role"]]
1036       end
1037
1038       new_members = new_doc.find("//osm/relation/member").collect do |m|
1039         [m["ref"].to_i, m["type"].to_sym, m["role"]]
1040       end
1041
1042       assert_equal doc_members, new_members, "members are not equal - ordering is wrong? (#{doc}, #{xml})"
1043     end
1044
1045     ##
1046     # create a changeset and yield to the caller to set it up, then assert
1047     # that the changeset bounding box is +bbox+.
1048     def check_changeset_modify(bbox)
1049       ## First test with the private user to check that you get a forbidden
1050       auth_header = bearer_authorization_header create(:user, :data_public => false)
1051
1052       # create a new changeset for this operation, so we are assured
1053       # that the bounding box will be newly-generated.
1054       with_controller(Api::ChangesetsController.new) do
1055         xml = "<osm><changeset/></osm>"
1056         post api_changesets_path, :params => xml, :headers => auth_header
1057         assert_response :forbidden, "shouldn't be able to create changeset for modify test, as should get forbidden"
1058       end
1059
1060       ## Now do the whole thing with the public user
1061       auth_header = bearer_authorization_header
1062
1063       # create a new changeset for this operation, so we are assured
1064       # that the bounding box will be newly-generated.
1065       changeset_id = with_controller(Api::ChangesetsController.new) do
1066         xml = "<osm><changeset/></osm>"
1067         post api_changesets_path, :params => xml, :headers => auth_header
1068         assert_response :success, "couldn't create changeset for modify test"
1069         @response.body.to_i
1070       end
1071
1072       # go back to the block to do the actual modifies
1073       yield changeset_id, auth_header
1074
1075       # now download the changeset to check its bounding box
1076       with_controller(Api::ChangesetsController.new) do
1077         get api_changeset_path(changeset_id)
1078         assert_response :success, "can't re-read changeset for modify test"
1079         assert_select "osm>changeset", 1, "Changeset element doesn't exist in #{@response.body}"
1080         assert_select "osm>changeset[id='#{changeset_id}']", 1, "Changeset id=#{changeset_id} doesn't exist in #{@response.body}"
1081         assert_select "osm>changeset[min_lon='#{format('%<lon>.7f', :lon => bbox.min_lon)}']", 1, "Changeset min_lon wrong in #{@response.body}"
1082         assert_select "osm>changeset[min_lat='#{format('%<lat>.7f', :lat => bbox.min_lat)}']", 1, "Changeset min_lat wrong in #{@response.body}"
1083         assert_select "osm>changeset[max_lon='#{format('%<lon>.7f', :lon => bbox.max_lon)}']", 1, "Changeset max_lon wrong in #{@response.body}"
1084         assert_select "osm>changeset[max_lat='#{format('%<lat>.7f', :lat => bbox.max_lat)}']", 1, "Changeset max_lat wrong in #{@response.body}"
1085       end
1086     end
1087
1088     ##
1089     # updates the relation (XML) +rel+ and
1090     # returns the new version of that relation.
1091     def do_update(rel, rel_id, headers)
1092       put api_relation_path(rel_id), :params => rel.to_s, :headers => headers
1093       assert_response :success, "can't update relation: #{@response.body}"
1094       version = @response.body.to_i
1095
1096       version
1097     end
1098
1099     ##
1100     # updates the relation (XML) +rel+ via the diff-upload API and
1101     # returns the new version of that relation.
1102     def do_update_diff(rel, headers)
1103       cs_id = rel.find("//osm/relation").first["changeset"].to_i
1104       version = nil
1105
1106       with_controller(Api::ChangesetsController.new) do
1107         doc = OSM::API.new.xml_doc
1108         change = XML::Node.new "osmChange"
1109         doc.root = change
1110         modify = XML::Node.new "modify"
1111         change << modify
1112         modify << doc.import(rel.find("//osm/relation").first)
1113
1114         post api_changeset_upload_path(cs_id), :params => doc.to_s, :headers => headers
1115         assert_response :success, "can't upload diff relation: #{@response.body}"
1116         version = xml_parse(@response.body).find("//diffResult/relation").first["new_version"].to_i
1117       end
1118
1119       version
1120     end
1121
1122     ##
1123     # returns a k->v hash of tags from an xml doc
1124     def get_tags_as_hash(a)
1125       a.find("//osm/relation/tag").to_h do |tag|
1126         [tag["k"], tag["v"]]
1127       end
1128     end
1129
1130     ##
1131     # assert that tags on relation document +rel+
1132     # are equal to tags in response
1133     def assert_tags_equal_response(rel)
1134       assert_response :success
1135       response_xml = xml_parse(@response.body)
1136
1137       # turn the XML doc into tags hashes
1138       rel_tags = get_tags_as_hash(rel)
1139       response_tags = get_tags_as_hash(response_xml)
1140
1141       assert_equal rel_tags, response_tags, "Tags should be identical."
1142     end
1143
1144     ##
1145     # update the changeset_id of a node element
1146     def update_changeset(xml, changeset_id)
1147       xml_attr_rewrite(xml, "changeset", changeset_id)
1148     end
1149
1150     ##
1151     # update an attribute in the node element
1152     def xml_attr_rewrite(xml, name, value)
1153       xml.find("//osm/relation").first[name] = value.to_s
1154       xml
1155     end
1156
1157     ##
1158     # parse some xml
1159     def xml_parse(xml)
1160       parser = XML::Parser.string(xml)
1161       parser.parse
1162     end
1163   end
1164 end