Skip to content

Commit 0455431

Browse files
authored
feat: add 'Client.close' (#100)
FBO use with 'contextlib.closing'. Closes #64.
1 parent f7db69b commit 0455431

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

packages/google-cloud-core/google/cloud/client.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,21 @@ def _http(self):
214214
self._http_internal.configure_mtls_channel(self._client_cert_source)
215215
return self._http_internal
216216

217+
def close(self):
218+
"""Clean up transport, if set.
219+
220+
Suggested use:
221+
222+
.. code-block:: python
223+
224+
import contextlib
225+
226+
with contextlib.closing(client): # closes on exit
227+
do_something_with(client)
228+
"""
229+
if self._http_internal is not None:
230+
self._http_internal.close()
231+
217232

218233
class _ClientProjectMixin(object):
219234
"""Mixin to allow setting the project on the client.

packages/google-cloud-core/tests/unit/test_client.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,21 @@ def test_from_service_account_json(self):
205205
file_open.assert_called_once_with(mock.sentinel.filename, "r", encoding="utf-8")
206206
constructor.assert_called_once_with(info)
207207

208+
def test_close_w__http_internal_none(self):
209+
credentials = _make_credentials()
210+
client_obj = self._make_one(credentials=credentials, _http=None)
211+
212+
client_obj.close() # noraise
213+
214+
def test_close_w__http_internal_set(self):
215+
credentials = _make_credentials()
216+
http = mock.Mock(spec=["close"])
217+
client_obj = self._make_one(credentials=credentials, _http=http)
218+
219+
client_obj.close()
220+
221+
http.close.assert_called_once_with()
222+
208223

209224
class Test_ClientProjectMixin(unittest.TestCase):
210225
@staticmethod

0 commit comments

Comments
 (0)