Skip to content

Commit

Permalink
Add a context manager to manage session handling
Browse files Browse the repository at this point in the history
  • Loading branch information
Stefan Oderbolz committed Oct 4, 2020
1 parent db80a1e commit a3f20a3
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
15 changes: 14 additions & 1 deletion osmapi/OsmApi.py
Expand Up @@ -251,13 +251,26 @@ def __init__(
self._session = self._get_http_session()

def __del__(self):
self.close()

return None

def __enter__(self):
self._session = self._get_http_session()
return self

def __exit__(self, *args):
self.close()

def close(self):
try:
if self._changesetauto:
self._changesetautoflush(True)
except ResponseEmptyApiError:
pass

return None
if self._session:
self._session.close()

##################################################
# Capabilities #
Expand Down
10 changes: 10 additions & 0 deletions tests/helper_tests.py
Expand Up @@ -23,6 +23,7 @@ def setupMock(self, status=200):
mock_response.reason = "test reason"
mock_response.content = 'test response'
self.api._session.request = mock.Mock(return_value=mock_response)
self.api._session.close = mock.Mock()
self.api._username = 'testuser'
self.api._password = 'testpassword'

Expand Down Expand Up @@ -56,6 +57,15 @@ def test_passwordfile_with_colon(self):
self.assertEquals('testuser', my_api._username)
self.assertEquals('test:userpass', my_api._password)

def test_close_call(self):
self.api.close()
self.assertEquals(self.api._session.close.call_count, 1)

def test_close_context_manager(self):
with osmapi.OsmApi() as my_api:
my_api._session.close = mock.Mock()
self.assertEquals(my_api._session.close.call_count, 1)

def test_http_request_get(self):
response = self.api._http_request(
'GET',
Expand Down

0 comments on commit a3f20a3

Please sign in to comment.