Debian Codegraph @

tests/changeset_test.py

raw
1 import osmapi
2 import xmltodict
3 import datetime
4 import pytest
5 from responses import GET, PUT, POST
6 import requests
7
8 from .conftest import GENERATOR
9
10
11 def xmltosorteddict(xml):
12 xml_dict = xmltodict.parse(xml, dict_constructor=dict)
13 return xml_dict
14
15
16 def test_changeset_contextmanager(auth_api, add_response):
17 # Setup mock
18 resp = add_response(PUT, "/changeset/create", filename="test_changeset_create.xml")
19 resp = add_response(PUT, "/node/create", filename="test_changeset_create_node.xml")
20 resp = add_response(
21 PUT, "/changeset/1414/close", filename="test_changeset_close.xml"
22 )
23
24 test_node = {
25 "lat": 47.123,
26 "lon": 8.555,
27 "tag": {"amenity": "place_of_worship", "religion": "pastafarian"},
28 }
29
30 # use context manager
31 with auth_api.changeset() as changeset_id:
32 assert changeset_id == 1414
33
34 # add test node
35 node = auth_api.node_create(test_node)
36 assert node["id"] == 7272
37
38 # check requests
39 assert len(resp.calls) == 3
40
41
42 def test_changeset_get(api, add_response):
43 # Setup mock
44 add_response(GET, "/changeset/123")
45 # Call
46 result = api.changeset_get(123)
47 test_changeset = {
48 "id": 123,
49 "closed_at": datetime.datetime(2009, 9, 7, 22, 57, 37),
50 "created_at": datetime.datetime(2009, 9, 7, 21, 57, 36),
51 "max_lat": "52.4710193",
52 "max_lon": "-1.4831815",
53 "min_lat": "45.9667901",
54 "min_lon": "-1.4998534",
55 "open": False,
56 "user": "randomjunk",
57 "uid": 3,
58 "tag": {
59 "comment": "correct node bug",
60 "created_by": "Potlatch 1.2a",
61 },
62 }
63 assert result == test_changeset
64
65
66 def test_changeset_get_with_connection_error(api, add_response):
67 # Setup mock
68 add_response(
69 GET,
70 "/changeset/123",
71 body=requests.exceptions.ConnectionError("Connection aborted."),
72 )
73
74 # Call
75 with pytest.raises(osmapi.ConnectionApiError) as execinfo:
76 api.changeset_get(123)
77 assert (
78 str(execinfo.value)
79 == "Request failed: 0 - Connection error: Connection aborted. - "
80 )
81
82
83 def test_changeset_get_with_timeout(api, add_response):
84 # Setup mock
85 add_response(GET, "/changeset/123", body=requests.exceptions.Timeout())
86
87 # Call
88 with pytest.raises(osmapi.TimeoutApiError) as execinfo:
89 api.changeset_get(123)
90 assert (
91 str(execinfo.value) == "Request failed: 0 - Request timed out (timeout=30) - "
92 )
93
94
95 def test_changeset_update(auth_api, add_response):
96 # Setup mock
97 resp = add_response(PUT, "/changeset/create", filename="test_changeset_create.xml")
98 resp = add_response(PUT, "/changeset/1414", filename="test_changeset_update.xml")
99
100 # Call
101 result = auth_api.changeset_create()
102 assert result == 1414
103
104 result = auth_api.changeset_update({"test": "foobar"})
105 changeset_xml = xmltosorteddict(
106 '<?xml version="1.0" encoding="UTF-8"?>\n'
107 f'<osm version="0.6" generator="{GENERATOR}">\n'
108 ' <changeset visible="true">\n'
109 ' <tag k="test" v="foobar"/>\n'
110 f' <tag k="created_by" v="{GENERATOR}"/>\n'
111 " </changeset>\n"
112 "</osm>\n"
113 )
114 assert xmltosorteddict(resp.calls[1].request.body) == changeset_xml
115 assert result == 1414
116
117
118 def test_changeset_update_with_created_by(auth_api, add_response):
119 # Setup mock
120 resp = add_response(PUT, "/changeset/create", filename="test_changeset_create.xml")
121 resp = add_response(PUT, "/changeset/1414", filename="test_changeset_update.xml")
122
123 # Call
124 result = auth_api.changeset_create()
125 assert result == 1414
126
127 result = auth_api.changeset_update({"test": "foobar", "created_by": "MyTestOSMApp"})
128 changeset_xml = xmltosorteddict(
129 '<?xml version="1.0" encoding="UTF-8"?>\n'
130 f'<osm version="0.6" generator="{GENERATOR}">\n'
131 ' <changeset visible="true">\n'
132 ' <tag k="test" v="foobar"/>\n'
133 ' <tag k="created_by" v="MyTestOSMApp"/>\n'
134 " </changeset>\n"
135 "</osm>\n"
136 )
137 assert xmltosorteddict(resp.calls[1].request.body) == changeset_xml
138 assert result == 1414
139
140
141 def test_changeset_update_wo_changeset(auth_api):
142 with pytest.raises(osmapi.NoChangesetOpenError) as execinfo:
143 auth_api.changeset_update({"test": "foobar"})
144 assert str(execinfo.value) == "No changeset currently opened"
145
146
147 def test_changeset_create(auth_api, add_response):
148 resp = add_response(PUT, "/changeset/create")
149 result = auth_api.changeset_create({"foobar": "A new test changeset"})
150 assert result == 1414
151
152 changeset_xml = xmltosorteddict(
153 '<?xml version="1.0" encoding="UTF-8"?>\n'
154 f'<osm version="0.6" generator="{GENERATOR}">\n'
155 ' <changeset visible="true">\n'
156 ' <tag k="foobar" v="A new test changeset"/>\n'
157 f' <tag k="created_by" v="{GENERATOR}"/>\n'
158 " </changeset>\n"
159 "</osm>\n"
160 )
161 assert xmltosorteddict(resp.calls[0].request.body) == changeset_xml
162
163
164 def test_changeset_create_with_created_by(auth_api, add_response):
165 resp = add_response(PUT, "/changeset/create")
166
167 result = auth_api.changeset_create(
168 {
169 "foobar": "A new test changeset",
170 "created_by": "CoolTestApp",
171 }
172 )
173 assert result == 1234
174
175 changeset_xml = xmltosorteddict(
176 '<?xml version="1.0" encoding="UTF-8"?>\n'
177 f'<osm version="0.6" generator="{GENERATOR}">\n'
178 ' <changeset visible="true">\n'
179 ' <tag k="foobar" v="A new test changeset"/>\n'
180 ' <tag k="created_by" v="CoolTestApp"/>\n'
181 " </changeset>\n"
182 "</osm>\n"
183 )
184 assert xmltosorteddict(resp.calls[0].request.body) == changeset_xml
185
186
187 def test_changeset_create_with_open_changeset(auth_api, add_response):
188 add_response(PUT, "/changeset/create")
189
190 auth_api.changeset_create(
191 {
192 "test": "an already open changeset",
193 }
194 )
195
196 with pytest.raises(osmapi.ChangesetAlreadyOpenError) as execinfo:
197 auth_api.changeset_create({"test": "foobar"})
198 assert str(execinfo.value) == "Changeset already opened"
199
200
201 def test_changeset_create_with_prod_api_and_test_comment(prod_api):
202 with pytest.raises(osmapi.OsmApiError) as execinfo:
203 prod_api.changeset_create(
204 {
205 "comment": "My first test",
206 }
207 )
208 assert (
209 str(execinfo.value) == "DO NOT CREATE test changesets on the production server"
210 )
211
212
213 def test_changeset_close(auth_api, add_response):
214 # setup mock
215 resp = add_response(PUT, "/changeset/create", filename="test_changeset_create.xml")
216 resp = add_response(PUT, "/changeset/1414/close")
217
218 # Call
219 auth_api.changeset_create()
220 auth_api.changeset_close()
221
222 assert "/api/0.6/changeset/1414/close" in resp.calls[1].request.url
223
224
225 def test_changeset_close_with_no_changeset(auth_api):
226 with pytest.raises(osmapi.NoChangesetOpenError) as execinfo:
227 auth_api.changeset_close()
228 assert str(execinfo.value) == "No changeset currently opened"
229
230
231 def test_changeset_upload_create_node(auth_api, add_response):
232 # Setup
233 resp = add_response(PUT, "/changeset/create", body="4444")
234 resp = add_response(POST, "/changeset/4444/upload")
235
236 changesdata = [
237 {
238 "type": "node",
239 "action": "create",
240 "data": [
241 {
242 "lat": 47.123,
243 "lon": 8.555,
244 "tag": {"amenity": "place_of_worship", "religion": "pastafarian"},
245 },
246 {
247 "lat": 47.125,
248 "lon": 8.557,
249 "tag": {"amenity": "place_of_worship", "religion": "pastafarian"},
250 },
251 ],
252 }
253 ]
254
255 upload_xml = xmltosorteddict(
256 '<?xml version="1.0" encoding="UTF-8"?>\n'
257 f'<osmChange version="0.6" generator="{GENERATOR}">\n'
258 "<create>\n"
259 ' <node lat="47.123" lon="8.555" visible="true" '
260 'changeset="4444">\n'
261 ' <tag k="amenity" v="place_of_worship"/>\n'
262 ' <tag k="religion" v="pastafarian"/>\n'
263 " </node>\n"
264 ' <node lat="47.125" lon="8.557" visible="true" '
265 'changeset="4444">\n'
266 ' <tag k="amenity" v="place_of_worship"/>\n'
267 ' <tag k="religion" v="pastafarian"/>\n'
268 " </node>\n"
269 "</create>\n"
270 "</osmChange>"
271 )
272
273 # Call
274 auth_api.changeset_create()
275 result = auth_api.changeset_upload(changesdata)
276
277 # Assert
278 assert xmltosorteddict(resp.calls[1].request.body) == upload_xml
279 assert result[0]["type"] == changesdata[0]["type"]
280 assert result[0]["action"] == changesdata[0]["action"]
281
282 data = result[0]["data"]
283 assert data[0]["lat"] == changesdata[0]["data"][0]["lat"]
284 assert data[0]["lon"] == changesdata[0]["data"][0]["lon"]
285 assert data[0]["tag"] == changesdata[0]["data"][0]["tag"]
286 assert data[0]["id"] == 4295832900
287 assert result[0]["data"][0]["version"] == 1
288
289
290 def test_changeset_upload_modify_way(auth_api, add_response):
291 # setup mock
292 resp = add_response(PUT, "/changeset/create", body="4444")
293 resp = add_response(POST, "/changeset/4444/upload")
294
295 changesdata = [
296 {
297 "type": "way",
298 "action": "modify",
299 "data": [
300 {
301 "id": 4294967296,
302 "version": 2,
303 "nd": [
304 4295832773,
305 4295832773,
306 4294967304,
307 4294967303,
308 4294967300,
309 4608751,
310 4294967305,
311 4294967302,
312 8548430,
313 4294967296,
314 4294967301,
315 4294967298,
316 4294967306,
317 7855737,
318 4294967297,
319 4294967299,
320 ],
321 "tag": {"highway": "secondary", "name": "Stansted Road"},
322 }
323 ],
324 }
325 ]
326
327 upload_xml = xmltosorteddict(
328 '<?xml version="1.0" encoding="UTF-8"?>\n'
329 f'<osmChange version="0.6" generator="{GENERATOR}">\n'
330 "<modify>\n"
331 ' <way id="4294967296" version="2" visible="true" '
332 'changeset="4444">\n'
333 ' <tag k="highway" v="secondary"/>\n'
334 ' <tag k="name" v="Stansted Road"/>\n'
335 ' <nd ref="4295832773"/>\n'
336 ' <nd ref="4295832773"/>\n'
337 ' <nd ref="4294967304"/>\n'
338 ' <nd ref="4294967303"/>\n'
339 ' <nd ref="4294967300"/>\n'
340 ' <nd ref="4608751"/>\n'
341 ' <nd ref="4294967305"/>\n'
342 ' <nd ref="4294967302"/>\n'
343 ' <nd ref="8548430"/>\n'
344 ' <nd ref="4294967296"/>\n'
345 ' <nd ref="4294967301"/>\n'
346 ' <nd ref="4294967298"/>\n'
347 ' <nd ref="4294967306"/>\n'
348 ' <nd ref="7855737"/>\n'
349 ' <nd ref="4294967297"/>\n'
350 ' <nd ref="4294967299"/>\n'
351 " </way>\n"
352 "</modify>\n"
353 "</osmChange>"
354 )
355
356 # Call
357 auth_api.changeset_create()
358 result = auth_api.changeset_upload(changesdata)
359 # Assert
360 assert xmltosorteddict(resp.calls[1].request.body) == upload_xml
361
362 assert result[0]["type"] == changesdata[0]["type"]
363 assert result[0]["action"] == changesdata[0]["action"]
364
365 data = result[0]["data"][0]
366 print(data)
367 assert data["nd"] == changesdata[0]["data"][0]["nd"]
368 assert data["tag"] == changesdata[0]["data"][0]["tag"]
369 assert data["id"] == 4294967296
370 assert data["version"] == 3
371
372
373 def test_changeset_upload_delete_relation(auth_api, add_response):
374 # setup mock
375 resp = add_response(PUT, "/changeset/create", body="4444")
376 resp = add_response(POST, "/changeset/4444/upload")
377
378 changesdata = [
379 {
380 "type": "relation",
381 "action": "delete",
382 "data": [
383 {
384 "id": 676,
385 "version": 2,
386 "member": [
387 {"ref": 4799, "role": "outer", "type": "way"},
388 {"ref": 9391, "role": "outer", "type": "way"},
389 ],
390 "tag": {
391 "admin_level": "9",
392 "boundary": "administrative",
393 "type": "multipolygon",
394 },
395 }
396 ],
397 }
398 ]
399
400 upload_xml = xmltosorteddict(
401 '<?xml version="1.0" encoding="UTF-8"?>\n'
402 f'<osmChange version="0.6" generator="{GENERATOR}">\n'
403 "<delete>\n"
404 ' <relation id="676" version="2" visible="true" '
405 'changeset="4444">\n'
406 ' <tag k="admin_level" v="9"/>\n'
407 ' <tag k="boundary" v="administrative"/>\n'
408 ' <tag k="type" v="multipolygon"/>\n'
409 ' <member type="way" ref="4799" role="outer"/>\n'
410 ' <member type="way" ref="9391" role="outer"/>\n'
411 " </relation>\n"
412 "</delete>\n"
413 "</osmChange>"
414 )
415
416 # Call
417 auth_api.changeset_create()
418 result = auth_api.changeset_upload(changesdata)
419
420 # Assert
421 assert xmltosorteddict(resp.calls[1].request.body) == upload_xml
422 assert result[0]["type"] == changesdata[0]["type"]
423 assert result[0]["action"] == changesdata[0]["action"]
424
425 data = result[0]["data"][0]
426 assert data["member"], changesdata[0]["data"][0]["member"]
427 assert data["tag"] == changesdata[0]["data"][0]["tag"]
428 assert data["id"] == 676
429 assert "version" not in data
430
431
432 def test_changeset_upload_invalid_response(auth_api, add_response):
433 # setup mock
434 add_response(PUT, "/changeset/create", body="4444")
435 add_response(POST, "/changeset/4444/upload", body="4444")
436
437 changesdata = [
438 {
439 "type": "relation",
440 "action": "delete",
441 "data": [
442 {
443 "id": 676,
444 "version": 2,
445 "member": [
446 {"ref": 4799, "role": "outer", "type": "way"},
447 {"ref": 9391, "role": "outer", "type": "way"},
448 ],
449 "tag": {
450 "admin_level": "9",
451 "boundary": "administrative",
452 "type": "multipolygon",
453 },
454 }
455 ],
456 }
457 ]
458
459 # Call + assert
460 auth_api.changeset_create()
461 with pytest.raises(osmapi.XmlResponseInvalidError) as execinfo:
462 auth_api.changeset_upload(changesdata)
463 assert "The XML response from the OSM API is invalid" in str(execinfo.value)
464
465
466 def test_changeset_upload_no_auth(api):
467 changesdata = [
468 {
469 "type": "node",
470 "action": "create",
471 "data": [
472 {
473 "lat": 47.123,
474 "lon": 8.555,
475 "tag": {"amenity": "place_of_worship", "religion": "pastafarian"},
476 }
477 ],
478 }
479 ]
480
481 with pytest.raises(osmapi.AuthenticationMissingError) as execinfo:
482 api.changeset_upload(changesdata)
483 assert "Authentication missing" in str(execinfo.value)
484
485
486 def test_changeset_upload_version_mismatch_raises_api_error(auth_api, add_response):
487 """HTTP 409 version mismatch must raise ApiError, not TypeError."""
488 add_response(PUT, "/changeset/create", body="4444")
489 add_response(
490 POST,
491 "/changeset/4444/upload",
492 body=b"Version mismatch: Provided 3, server had: 4",
493 status=409,
494 )
495
496 changesdata = [
497 {
498 "type": "node",
499 "action": "modify",
500 "data": [{"id": 1, "version": 3, "lat": 47.0, "lon": 8.0, "tag": {}}],
501 }
502 ]
503
504 auth_api.changeset_create()
505 with pytest.raises(osmapi.errors.ApiError) as execinfo:
506 auth_api.changeset_upload(changesdata)
507 assert execinfo.value.status == 409
508 assert b"Version mismatch" in execinfo.value.payload
509
510
511 def test_changeset_upload_closed_changeset_raises_correct_error(auth_api, add_response):
512 """HTTP 409 'changeset closed' must raise ChangesetClosedApiError."""
513 add_response(PUT, "/changeset/create", body="4444")
514 add_response(
515 POST,
516 "/changeset/4444/upload",
517 body=b"The changeset 4444 was closed at 2024-01-01T00:00:00Z",
518 status=409,
519 )
520
521 changesdata = [
522 {
523 "type": "node",
524 "action": "modify",
525 "data": [{"id": 1, "version": 1, "lat": 47.0, "lon": 8.0, "tag": {}}],
526 }
527 ]
528
529 auth_api.changeset_create()
530 with pytest.raises(osmapi.errors.ChangesetClosedApiError):
531 auth_api.changeset_upload(changesdata)
532
533
534 def test_changeset_download(api, add_response):
535 # Setup mock
536 add_response(GET, "/changeset/23123/download")
537
538 # Call
539 result = api.changeset_download(23123)
540
541 # Assertion
542 assert len(result) == 16
543 assert result[1] == (
544 {
545 "action": "create",
546 "type": "node",
547 "data": {
548 "changeset": 23123,
549 "id": 4295668171,
550 "lat": 46.4909781,
551 "lon": 11.2743295,
552 "tag": {"highway": "traffic_signals"},
553 "timestamp": datetime.datetime(2013, 5, 14, 10, 33, 4),
554 "uid": 1178,
555 "user": "tyrTester06",
556 "version": 1,
557 "visible": True,
558 },
559 }
560 )
561
562
563 def test_changeset_download_invalid_response(api, add_response):
564 add_response(GET, "/changeset/23123/download")
565 with pytest.raises(osmapi.XmlResponseInvalidError) as execinfo:
566 api.changeset_download(23123)
567 assert "The XML response from the OSM API is invalid" in str(execinfo.value)
568
569
570 def test_changeset_download_containing_unicode(api, add_response):
571 add_response(GET, "/changeset/37393499/download")
572
573 # This changeset contains unicode tag values
574 # Note that the fixture data has been reduced from the
575 # original from openstreetmap.org
576 result = api.changeset_download(37393499)
577
578 assert len(result) == 2
579 assert result[1] == (
580 {
581 "action": "create",
582 "type": "way",
583 "data": {
584 "changeset": 37393499,
585 "id": 399491497,
586 "nd": [4022271571, 4022271567, 4022271565],
587 "tag": {
588 "highway": "service",
589 # UTF-8 encoded 'LATIN SMALL LETTER O WITH STROKE'
590 # Aka. 0xf8 in latin-1/ISO 8859-1 Emoji: 😀
591 "name": b"S\xc3\xb8nderskovvej".decode("utf-8") + " \U0001f600",
592 "service": "driveway",
593 },
594 "timestamp": datetime.datetime(2016, 2, 23, 16, 55, 35),
595 "uid": 328556,
596 "user": "InternationalUser",
597 "version": 1,
598 "visible": True,
599 },
600 }
601 )
602
603
604 def test_changesets_get(api, add_response):
605 resp = add_response(GET, "/changesets")
606 result = api.changesets_get(only_closed=True, username="metaodi")
607 assert resp.calls[0].request.params == {"display_name": "metaodi", "closed": "1"}
608 assert len(result) == 10
609 assert result[41417] == (
610 {
611 "closed_at": datetime.datetime(2014, 4, 29, 20, 25, 1),
612 "created_at": datetime.datetime(2014, 4, 29, 20, 25, 1),
613 "id": 41417,
614 "max_lat": "58.8997467",
615 "max_lon": "22.7364427",
616 "min_lat": "58.8501594",
617 "min_lon": "22.6984333",
618 "open": False,
619 "tag": {
620 "comment": "Test delete of relation",
621 "created_by": "iD 1.3.9",
622 "imagery_used": "Bing",
623 },
624 "uid": 1841,
625 "user": "metaodi",
626 }
627 )
628
629
630 def test_changeset_get_with_comment(api, add_response):
631 resp = add_response(GET, "/changeset/52924")
632
633 result = api.changeset_get(52924, include_discussion=True)
634
635 assert resp.calls[0].request.params == {"include_discussion": "true"}
636 assert result == {
637 "id": 52924,
638 "closed_at": datetime.datetime(2015, 1, 1, 14, 54, 2),
639 "created_at": datetime.datetime(2015, 1, 1, 14, 54, 1),
640 "comments_count": 3,
641 "max_lat": "58.3369242",
642 "max_lon": "25.8829107",
643 "min_lat": "58.336813",
644 "min_lon": "25.8823273",
645 "discussion": [
646 {
647 "date": datetime.datetime(2015, 1, 1, 18, 56, 48),
648 "text": "test",
649 "uid": 1841,
650 "user": "metaodi",
651 },
652 {
653 "date": datetime.datetime(2015, 1, 1, 18, 58, 3),
654 "text": "another comment",
655 "uid": 1841,
656 "user": "metaodi",
657 },
658 {
659 "date": datetime.datetime(2015, 1, 1, 19, 16, 5),
660 "text": "hello",
661 "uid": 1841,
662 "user": "metaodi",
663 },
664 ],
665 "open": False,
666 "user": "metaodi",
667 "uid": 1841,
668 "tag": {
669 "comment": "My test",
670 "created_by": "osmapi/0.4.1",
671 },
672 }
673
674
675 def test_changeset_get_without_discussion(api, add_response):
676 resp = add_response(GET, "/changeset/52924")
677
678 result = api.changeset_get(52924, include_discussion=False)
679
680 assert resp.calls[0].request.params == {}
681 assert result == {
682 "id": 52924,
683 "closed_at": datetime.datetime(2015, 1, 1, 14, 54, 2),
684 "created_at": datetime.datetime(2015, 1, 1, 14, 54, 1),
685 "max_lat": "58.3369242",
686 "max_lon": "25.8829107",
687 "min_lat": "58.336813",
688 "min_lon": "25.8823273",
689 "open": False,
690 "user": "metaodi",
691 "uid": 1841,
692 "tag": {
693 "comment": "My test",
694 "created_by": "osmapi/0.4.1",
695 },
696 }
697
698
699 def test_changeset_comment(auth_api, add_response):
700 resp = add_response(POST, "/changeset/123/comment")
701
702 result = auth_api.changeset_comment(123, comment="test comment")
703
704 assert resp.calls[0].request.body == "text=test+comment"
705 assert result == {
706 "id": 123,
707 "closed_at": datetime.datetime(2009, 9, 7, 22, 57, 37),
708 "created_at": datetime.datetime(2009, 9, 7, 21, 57, 36),
709 "max_lat": "52.4710193",
710 "max_lon": "-1.4831815",
711 "min_lat": "45.9667901",
712 "min_lon": "-1.4998534",
713 "open": False,
714 "user": "randomjunk",
715 "uid": 3,
716 "tag": {
717 "comment": "correct node bug",
718 "created_by": "Potlatch 1.2a",
719 },
720 }
721
722
723 def test_changeset_comment_no_auth(api):
724 with pytest.raises(osmapi.AuthenticationMissingError) as execinfo:
725 api.changeset_comment(123, comment="test comment")
726 assert "Authentication missing" in str(execinfo.value)
727
728
729 def test_changeset_subscribe(auth_api, add_response):
730 add_response(POST, "/changeset/123/subscribe")
731
732 result = auth_api.changeset_subscribe(123)
733
734 assert result == {
735 "id": 123,
736 "closed_at": datetime.datetime(2009, 9, 7, 22, 57, 37),
737 "created_at": datetime.datetime(2009, 9, 7, 21, 57, 36),
738 "max_lat": "52.4710193",
739 "max_lon": "-1.4831815",
740 "min_lat": "45.9667901",
741 "min_lon": "-1.4998534",
742 "open": False,
743 "user": "randomjunk",
744 "uid": 3,
745 "tag": {
746 "comment": "correct node bug",
747 "created_by": "Potlatch 1.2a",
748 },
749 }
750
751
752 def test_changeset_subscribe_when_already_subscribed(auth_api, add_response):
753 add_response(POST, "/changeset/52924/subscribe", status=409)
754
755 with pytest.raises(osmapi.AlreadySubscribedApiError) as execinfo:
756 auth_api.changeset_subscribe(52924)
757
758 assert execinfo.value.payload == b"You are already subscribed to changeset 52924."
759 assert execinfo.value.reason == "Conflict"
760 assert execinfo.value.status == 409
761
762
763 def test_changeset_subscribe_no_auth(api):
764 with pytest.raises(osmapi.AuthenticationMissingError) as execinfo:
765 api.changeset_subscribe(45627)
766 assert "Authentication missing" in str(execinfo.value)
767
768
769 def test_changeset_unsubscribe(auth_api, add_response):
770 add_response(POST, "/changeset/123/unsubscribe")
771
772 result = auth_api.changeset_unsubscribe(123)
773
774 assert result == {
775 "id": 123,
776 "closed_at": datetime.datetime(2009, 9, 7, 22, 57, 37),
777 "created_at": datetime.datetime(2009, 9, 7, 21, 57, 36),
778 "max_lat": "52.4710193",
779 "max_lon": "-1.4831815",
780 "min_lat": "45.9667901",
781 "min_lon": "-1.4998534",
782 "open": False,
783 "user": "randomjunk",
784 "uid": 3,
785 "tag": {
786 "comment": "correct node bug",
787 "created_by": "Potlatch 1.2a",
788 },
789 }
790
791
792 def test_changeset_unsubscribe_when_not_subscribed(auth_api, add_response):
793 add_response(POST, "/changeset/52924/unsubscribe", status=404)
794
795 with pytest.raises(osmapi.NotSubscribedApiError) as execinfo:
796 auth_api.changeset_unsubscribe(52924)
797
798 assert execinfo.value.payload == b"You are not subscribed to changeset 52924."
799 assert execinfo.value.reason == "Not Found"
800 assert execinfo.value.status == 404
801
802
803 def test_changeset_unsubscribe_no_auth(api):
804 with pytest.raises(osmapi.AuthenticationMissingError) as execinfo:
805 api.changeset_unsubscribe(45627)
806 assert "Authentication missing" in str(execinfo.value)
807
808
809 ##################################################
810 # changesets_get query parameters #
811 ##################################################
812
813
814 def test_changesets_get_no_filters(api, add_response):
815 resp = add_response(GET, "/changesets", filename="test_changesets_get.xml")
816
817 api.changesets_get()
818
819 assert resp.calls[0].request.url == (
820 "http://api06.dev.openstreetmap.org/api/0.6/changesets"
821 )
822
823
824 def test_changesets_get_by_userid(api, add_response):
825 resp = add_response(GET, "/changesets", filename="test_changesets_get.xml")
826
827 api.changesets_get(userid=1841)
828
829 assert resp.calls[0].request.params == {"user": "1841"}
830
831
832 def test_changesets_get_only_open(api, add_response):
833 resp = add_response(GET, "/changesets", filename="test_changesets_get.xml")
834
835 api.changesets_get(only_open=True)
836
837 assert resp.calls[0].request.params == {"open": "1"}
838
839
840 def test_changesets_get_bbox(api, add_response):
841 resp = add_response(GET, "/changesets", filename="test_changesets_get.xml")
842
843 api.changesets_get(min_lon=8.7, min_lat=47.2, max_lon=8.8, max_lat=47.3)
844
845 assert resp.calls[0].request.params == {"bbox": "8.7,47.2,8.8,47.3"}
846
847
848 def test_changesets_get_bbox_at_origin(api, add_response):
849 """A bbox of all zeros is a real bbox and must not be dropped."""
850 resp = add_response(GET, "/changesets", filename="test_changesets_get.xml")
851
852 api.changesets_get(min_lon=0, min_lat=0, max_lon=0, max_lat=0)
853
854 assert resp.calls[0].request.params == {"bbox": "0,0,0,0"}
855
856
857 @pytest.mark.parametrize(
858 "kwargs",
859 [
860 {"min_lon": 8.7},
861 {"min_lon": 8.7, "min_lat": 47.2},
862 {"min_lon": 8.7, "min_lat": 47.2, "max_lon": 8.8},
863 {"max_lat": 47.3},
864 ],
865 )
866 def test_changesets_get_partial_bbox_raises(api, kwargs):
867 """A partial bbox is rejected instead of being sent with 'None' in it."""
868 with pytest.raises(ValueError, match="bounding box needs all of"):
869 api.changesets_get(**kwargs)
870
871
872 def test_changesets_get_closed_after(api, add_response):
873 resp = add_response(GET, "/changesets", filename="test_changesets_get.xml")
874
875 api.changesets_get(closed_after="2024-01-01T00:00:00Z")
876
877 assert resp.calls[0].request.params == {"time": "2024-01-01T00:00:00Z"}
878
879
880 def test_changesets_get_created_before(api, add_response):
881 """`created_before` alone becomes a range starting at the epoch."""
882 resp = add_response(GET, "/changesets", filename="test_changesets_get.xml")
883
884 api.changesets_get(created_before="2024-06-01T00:00:00Z")
885
886 assert resp.calls[0].request.params == {
887 "time": "1970-01-01T00:00:00Z,2024-06-01T00:00:00Z"
888 }
889
890
891 def test_changesets_get_time_range(api, add_response):
892 resp = add_response(GET, "/changesets", filename="test_changesets_get.xml")
893
894 api.changesets_get(
895 closed_after="2024-01-01T00:00:00Z", created_before="2024-06-01T00:00:00Z"
896 )
897
898 assert resp.calls[0].request.params == {
899 "time": "2024-01-01T00:00:00Z,2024-06-01T00:00:00Z"
900 }
901
902
903 def test_changesets_get_all_filters(api, add_response):
904 resp = add_response(GET, "/changesets", filename="test_changesets_get.xml")
905
906 api.changesets_get(
907 min_lon=8.7,
908 min_lat=47.2,
909 max_lon=8.8,
910 max_lat=47.3,
911 userid=1841,
912 username="metaodi",
913 closed_after="2024-01-01T00:00:00Z",
914 created_before="2024-06-01T00:00:00Z",
915 only_open=True,
916 only_closed=True,
917 )
918
919 assert resp.calls[0].request.params == {
920 "bbox": "8.7,47.2,8.8,47.3",
921 "user": "1841",
922 "display_name": "metaodi",
923 "time": "2024-01-01T00:00:00Z,2024-06-01T00:00:00Z",
924 "open": "1",
925 "closed": "1",
926 }
927
928
929 ##################################################
930 # Error paths of the changeset operations #
931 ##################################################
932
933
934 def test_changeset_update_on_closed_changeset(auth_api, add_response):
935 add_response(PUT, "/changeset/create", filename="test_changeset_create.xml")
936 add_response(PUT, "/changeset/1414", status=409)
937
938 auth_api.changeset_create()
939
940 with pytest.raises(osmapi.ChangesetClosedApiError) as execinfo:
941 auth_api.changeset_update({"test": "foobar"})
942
943 assert execinfo.value.status == 409
944 assert (
945 execinfo.value.payload_str
946 == "The changeset 1414 was closed at 2024-03-01 10:00:00 UTC."
947 )
948
949
950 def test_changeset_update_server_error(auth_api, add_response):
951 """A non-409 error is re-raised unchanged rather than mapped."""
952 add_response(PUT, "/changeset/create", filename="test_changeset_create.xml")
953 # a 5xx is retried, so every attempt needs a registered response
954 for _ in range(osmapi.http.OsmApiSession.MAX_RETRY_LIMIT):
955 add_response(PUT, "/changeset/1414", status=500)
956
957 auth_api.changeset_create()
958
959 with pytest.raises(osmapi.ApiError) as execinfo:
960 auth_api.changeset_update({"test": "foobar"})
961
962 assert type(execinfo.value) is osmapi.ApiError
963 assert execinfo.value.status == 500
964
965
966 def test_changeset_close_on_closed_changeset(auth_api, add_response):
967 add_response(PUT, "/changeset/create", filename="test_changeset_create.xml")
968 add_response(PUT, "/changeset/1414/close", status=409)
969
970 auth_api.changeset_create()
971
972 with pytest.raises(osmapi.ChangesetClosedApiError) as execinfo:
973 auth_api.changeset_close()
974
975 assert execinfo.value.status == 409
976 assert (
977 execinfo.value.payload_str
978 == "The changeset 1414 was closed at 2024-03-01 10:00:00 UTC."
979 )
980
981
982 def test_changeset_comment_on_closed_changeset(auth_api, add_response):
983 add_response(POST, "/changeset/123/comment", status=409)
984
985 with pytest.raises(osmapi.ChangesetClosedApiError) as execinfo:
986 auth_api.changeset_comment(123, comment="too late")
987
988 assert execinfo.value.status == 409
989 assert (
990 execinfo.value.payload_str
991 == "The changeset 123 was closed at 2024-03-01 10:00:00 UTC."
992 )
993
994
995 def test_changeset_comment_not_found(auth_api, add_response):
996 """A non-409 error is re-raised unchanged rather than mapped."""
997 add_response(POST, "/changeset/123/comment", status=404)
998
999 with pytest.raises(osmapi.ElementNotFoundApiError) as execinfo:
1000 auth_api.changeset_comment(123, comment="test comment")
1001
1002 assert execinfo.value.status == 404
1003
1004
1005 def test_changeset_subscribe_other_error(auth_api, add_response):
1006 """Only a 409 means 'already subscribed'; anything else is re-raised."""
1007 add_response(POST, "/changeset/52924/subscribe", status=403)
1008
1009 with pytest.raises(osmapi.ApiError) as execinfo:
1010 auth_api.changeset_subscribe(52924)
1011
1012 assert type(execinfo.value) is osmapi.ApiError
1013 assert execinfo.value.status == 403
1014
1015
1016 def test_changeset_unsubscribe_other_error(auth_api, add_response):
1017 """Only a 404 means 'not subscribed'; anything else is re-raised."""
1018 add_response(POST, "/changeset/52924/unsubscribe", status=403)
1019
1020 with pytest.raises(osmapi.ApiError) as execinfo:
1021 auth_api.changeset_unsubscribe(52924)
1022
1023 assert type(execinfo.value) is osmapi.ApiError
1024 assert execinfo.value.status == 403
1025
1026
1027 ##################################################
1028 # The changeset() context manager #
1029 ##################################################
1030
1031
1032 def test_changeset_contextmanager_closes_on_exception(auth_api, add_response):
1033 """An error inside the block must not leave the changeset open."""
1034 resp = add_response(PUT, "/changeset/create", filename="test_changeset_create.xml")
1035 add_response(PUT, "/changeset/1414/close", filename="test_changeset_close.xml")
1036
1037 with pytest.raises(ValueError, match="boom"):
1038 with auth_api.changeset({"comment": "will fail"}):
1039 raise ValueError("boom")
1040
1041 assert "/api/0.6/changeset/1414/close" in resp.calls[1].request.url
1042 assert auth_api._current_changeset_id == 0
1043
1044
1045 def test_changeset_contextmanager_reusable_after_exception(auth_api, add_response):
1046 """After a failed block a new changeset can be opened straight away."""
1047 add_response(PUT, "/changeset/create", filename="test_changeset_create.xml")
1048 add_response(PUT, "/changeset/1414/close", filename="test_changeset_close.xml")
1049 add_response(PUT, "/changeset/create", filename="test_changeset_create.xml")
1050 add_response(PUT, "/changeset/1414/close", filename="test_changeset_close.xml")
1051
1052 with pytest.raises(ValueError):
1053 with auth_api.changeset():
1054 raise ValueError("boom")
1055
1056 # would raise ChangesetAlreadyOpenError if the first one had leaked
1057 with auth_api.changeset() as changeset_id:
1058 assert changeset_id == 1414
1059
1060 assert auth_api._current_changeset_id == 0
1061
1062
1063 def test_changeset_get_include_discussion_without_discussion(api, add_response):
1064 """Asking for the discussion of a changeset that has none yields nothing."""
1065 resp = add_response(
1066 GET, "/changeset/52924", filename="test_changeset_get_without_discussion.xml"
1067 )
1068
1069 result = api.changeset_get(52924, include_discussion=True)
1070
1071 assert resp.calls[0].request.params == {"include_discussion": "true"}
1072 # the key is present but empty, rather than the parse failing
1073 assert result["discussion"] == []
1074 assert result["id"] == 52924
1075
1076
1077 def test_changeset_update_without_tags(auth_api, add_response):
1078 """Called with no tags, only `created_by` is sent."""
1079 add_response(PUT, "/changeset/create", filename="test_changeset_create.xml")
1080 resp = add_response(PUT, "/changeset/1414", filename="test_changeset_update.xml")
1081
1082 auth_api.changeset_create()
1083 auth_api.changeset_update()
1084
1085 assert xmltosorteddict(resp.calls[1].request.body) == xmltosorteddict(
1086 '<?xml version="1.0" encoding="UTF-8"?>'
1087 f'<osm version="0.6" generator="{GENERATOR}">'
1088 '<changeset visible="true">'
1089 f'<tag k="created_by" v="{GENERATOR}"/>'
1090 "</changeset>"
1091 "</osm>"
1092 )
1093
1094
1095 def test_changeset_close_server_error(auth_api, add_response):
1096 """A non-409 error while closing is re-raised unchanged."""
1097 add_response(PUT, "/changeset/create", filename="test_changeset_create.xml")
1098 for _ in range(osmapi.http.OsmApiSession.MAX_RETRY_LIMIT):
1099 add_response(PUT, "/changeset/1414/close", status=500)
1100
1101 auth_api.changeset_create()
1102
1103 with pytest.raises(osmapi.ApiError) as execinfo:
1104 auth_api.changeset_close()
1105
1106 assert type(execinfo.value) is osmapi.ApiError
1107 assert execinfo.value.status == 500
1108 # the changeset is still considered open, since closing it failed
1109 assert auth_api._current_changeset_id == 1414