Debian Codegraph @

tests/osmapi_test.py

raw
1 """Tests for construction and lifecycle of the OsmApi object."""
2
3 from unittest import mock
4
5 import osmapi
6 import pytest
7 import requests
8
9 from .conftest import API_BASE, authenticated_session
10
11
12 def test_constructor():
13 api = osmapi.OsmApi(api=API_BASE)
14
15 assert isinstance(api, osmapi.OsmApi)
16 api.close()
17
18
19 def test_constructor_strips_trailing_slash():
20 api = osmapi.OsmApi(api=f"{API_BASE}/")
21
22 assert api._api == API_BASE
23 api.close()
24
25
26 def test_constructor_created_by_defaults_to_version():
27 api = osmapi.OsmApi(api=API_BASE)
28
29 assert api._created_by == f"osmapi/{osmapi.__version__}"
30 api.close()
31
32
33 def test_constructor_with_appid():
34 """`appid` is prefixed to the generator / user-agent string."""
35 api = osmapi.OsmApi(api=API_BASE, appid="MyApp/1.0")
36
37 assert api._created_by == f"MyApp/1.0 (osmapi/{osmapi.__version__})"
38 assert api._session._session.headers["user-agent"] == api._created_by
39 api.close()
40
41
42 def test_constructor_with_custom_created_by():
43 api = osmapi.OsmApi(api=API_BASE, created_by="custom/9.9")
44
45 assert api._created_by == "custom/9.9"
46 api.close()
47
48
49 def test_no_changeset_open_initially():
50 api = osmapi.OsmApi(api=API_BASE)
51
52 assert api._current_changeset_id == 0
53 api.close()
54
55
56 def test_constructor_without_session_cannot_authenticate():
57 api = osmapi.OsmApi(api=API_BASE)
58
59 assert api._session._auth is None
60 assert api._session._can_authenticate is False
61 api.close()
62
63
64 def test_constructor_takes_auth_from_session():
65 """Authentication comes from the session, there is no other way to set it."""
66 api = osmapi.OsmApi(api=API_BASE, session=authenticated_session())
67
68 assert api._session._auth == ("testuser", "testpassword")
69 assert api._session._can_authenticate is True
70 api.close()
71
72
73 def test_constructor_trusts_a_session_without_visible_credentials():
74 """A session may authenticate in ways osmapi cannot inspect."""
75 api = osmapi.OsmApi(api=API_BASE, session=requests.Session())
76
77 assert api._session._auth is None
78 assert api._session._can_authenticate is True
79 api.close()
80
81
82 @pytest.mark.parametrize("credential", ["username", "password", "passwordfile"])
83 def test_constructor_rejects_username_password(credential):
84 """Username/password auth was removed in 6.0, an OAuth session is required."""
85 with pytest.raises(TypeError):
86 osmapi.OsmApi(api=API_BASE, **{credential: "testuser"})
87
88
89 def test_close_call(mock_api):
90 api, session = mock_api()
91
92 api.close()
93
94 assert session.close.call_count == 1
95
96
97 def test_close_context_manager():
98 with osmapi.OsmApi() as api:
99 api._session.close = mock.Mock()
100
101 assert api._session.close.call_count == 1