From 44c383a46d5759cb8ac4631c65d630ed5ededb5b Mon Sep 17 00:00:00 2001 From: Tres Seaver Date: Fri, 11 Jun 2021 16:42:46 -0400 Subject: [PATCH 1/3] feat: add 'Client.close' FBO use with 'contextlib.closing'. Closes #64. --- google/cloud/client.py | 14 ++++++++++++++ tests/unit/test_client.py | 14 ++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/google/cloud/client.py b/google/cloud/client.py index 0697741..39ee218 100644 --- a/google/cloud/client.py +++ b/google/cloud/client.py @@ -214,6 +214,20 @@ def _http(self): self._http_internal.configure_mtls_channel(self._client_cert_source) return self._http_internal + def close(self): + """Clean up transport, if set. + + Suggested use: + + .. code-block:: python + import contextlib + + with contextlib.closing(client): # closes on exit + do_something_with(client) + """ + if self._http_internal is not None: + self._http_internal.close() + class _ClientProjectMixin(object): """Mixin to allow setting the project on the client. diff --git a/tests/unit/test_client.py b/tests/unit/test_client.py index 9eeb757..6b96c95 100644 --- a/tests/unit/test_client.py +++ b/tests/unit/test_client.py @@ -205,6 +205,20 @@ def test_from_service_account_json(self): file_open.assert_called_once_with(mock.sentinel.filename, "r", encoding="utf-8") constructor.assert_called_once_with(info) + def test_close_w__http_internal_none(self): + credentials = _make_credentials() + client_obj = self._make_one(credentials=credentials, _http=None) + + client_obj.close() # noraise + + def test_close_w__http_internal_set(self): + credentials = _make_credentials() + http = mock.Mock(spec=["close"]) + client_obj = self._make_one(credentials=credentials, _http=http) + + client_obj.close() + + http.close.assert_called_once_with() class Test_ClientProjectMixin(unittest.TestCase): @staticmethod From 25cb420c0ffc17e0a1303ef813836f35f23c3265 Mon Sep 17 00:00:00 2001 From: Tres Seaver Date: Fri, 11 Jun 2021 17:10:19 -0400 Subject: [PATCH 2/3] chore: fix Sphinx docstring markup --- google/cloud/client.py | 1 + 1 file changed, 1 insertion(+) diff --git a/google/cloud/client.py b/google/cloud/client.py index 39ee218..9e09450 100644 --- a/google/cloud/client.py +++ b/google/cloud/client.py @@ -220,6 +220,7 @@ def close(self): Suggested use: .. code-block:: python + import contextlib with contextlib.closing(client): # closes on exit From 71b94c6e150c5ab51375b17fc4fb4d5ce81ac3e6 Mon Sep 17 00:00:00 2001 From: Tres Seaver Date: Mon, 14 Jun 2021 13:18:02 -0400 Subject: [PATCH 3/3] chore: appease lint --- tests/unit/test_client.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/unit/test_client.py b/tests/unit/test_client.py index 6b96c95..1b933a2 100644 --- a/tests/unit/test_client.py +++ b/tests/unit/test_client.py @@ -220,6 +220,7 @@ def test_close_w__http_internal_set(self): http.close.assert_called_once_with() + class Test_ClientProjectMixin(unittest.TestCase): @staticmethod def _get_target_class():