From bf9cc268363a2a6e115b6af65ab6b50c05bbde28 Mon Sep 17 00:00:00 2001
From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com>
Date: Fri, 8 Oct 2021 14:16:28 +0000
Subject: [PATCH] feat: add context manager support in client (#125)

- [ ] Regenerate this pull request now.

chore: fix docstring for first attribute of protos

committer: @busunkim96
PiperOrigin-RevId: 401271153

Source-Link: https://github.com/googleapis/googleapis/commit/787f8c9a731f44e74a90b9847d48659ca9462d10

Source-Link: https://github.com/googleapis/googleapis-gen/commit/81decffe9fc72396a8153e756d1d67a6eecfd620
Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiODFkZWNmZmU5ZmM3MjM5NmE4MTUzZTc1NmQxZDY3YTZlZWNmZDYyMCJ9
---
 .../connection_service/async_client.py        |  6 +++
 .../services/connection_service/client.py     | 18 +++++--
 .../connection_service/transports/base.py     |  9 ++++
 .../connection_service/transports/grpc.py     |  3 ++
 .../transports/grpc_asyncio.py                |  3 ++
 .../types/connection.py                       |  5 ++
 .../test_connection_service.py                | 50 +++++++++++++++++++
 7 files changed, 90 insertions(+), 4 deletions(-)

diff --git a/google/cloud/bigquery_connection_v1/services/connection_service/async_client.py b/google/cloud/bigquery_connection_v1/services/connection_service/async_client.py
index 6a33f05..b5b09f5 100644
--- a/google/cloud/bigquery_connection_v1/services/connection_service/async_client.py
+++ b/google/cloud/bigquery_connection_v1/services/connection_service/async_client.py
@@ -943,6 +943,12 @@ async def test_iam_permissions(
         # Done; return the response.
         return response
 
+    async def __aenter__(self):
+        return self
+
+    async def __aexit__(self, exc_type, exc, tb):
+        await self.transport.close()
+
 
 try:
     DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
diff --git a/google/cloud/bigquery_connection_v1/services/connection_service/client.py b/google/cloud/bigquery_connection_v1/services/connection_service/client.py
index 61dec54..fa3473c 100644
--- a/google/cloud/bigquery_connection_v1/services/connection_service/client.py
+++ b/google/cloud/bigquery_connection_v1/services/connection_service/client.py
@@ -350,10 +350,7 @@ def __init__(
                 client_cert_source_for_mtls=client_cert_source_func,
                 quota_project_id=client_options.quota_project_id,
                 client_info=client_info,
-                always_use_jwt_access=(
-                    Transport == type(self).get_transport_class("grpc")
-                    or Transport == type(self).get_transport_class("grpc_asyncio")
-                ),
+                always_use_jwt_access=True,
             )
 
     def create_connection(
@@ -1101,6 +1098,19 @@ def test_iam_permissions(
         # Done; return the response.
         return response
 
+    def __enter__(self):
+        return self
+
+    def __exit__(self, type, value, traceback):
+        """Releases underlying transport's resources.
+
+        .. warning::
+            ONLY use as a context manager if the transport is NOT shared
+            with other clients! Exiting the with block will CLOSE the transport
+            and may cause errors in other clients!
+        """
+        self.transport.close()
+
 
 try:
     DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
diff --git a/google/cloud/bigquery_connection_v1/services/connection_service/transports/base.py b/google/cloud/bigquery_connection_v1/services/connection_service/transports/base.py
index 7f5c9be..2bd9d67 100644
--- a/google/cloud/bigquery_connection_v1/services/connection_service/transports/base.py
+++ b/google/cloud/bigquery_connection_v1/services/connection_service/transports/base.py
@@ -225,6 +225,15 @@ def _prep_wrapped_messages(self, client_info):
             ),
         }
 
+    def close(self):
+        """Closes resources associated with the transport.
+
+       .. warning::
+            Only call this method if the transport is NOT shared
+            with other clients - this may cause errors in other clients!
+        """
+        raise NotImplementedError()
+
     @property
     def create_connection(
         self,
diff --git a/google/cloud/bigquery_connection_v1/services/connection_service/transports/grpc.py b/google/cloud/bigquery_connection_v1/services/connection_service/transports/grpc.py
index 1724f74..53f8b54 100644
--- a/google/cloud/bigquery_connection_v1/services/connection_service/transports/grpc.py
+++ b/google/cloud/bigquery_connection_v1/services/connection_service/transports/grpc.py
@@ -461,5 +461,8 @@ def test_iam_permissions(
             )
         return self._stubs["test_iam_permissions"]
 
+    def close(self):
+        self.grpc_channel.close()
+
 
 __all__ = ("ConnectionServiceGrpcTransport",)
diff --git a/google/cloud/bigquery_connection_v1/services/connection_service/transports/grpc_asyncio.py b/google/cloud/bigquery_connection_v1/services/connection_service/transports/grpc_asyncio.py
index 20d3be2..d0e8f8d 100644
--- a/google/cloud/bigquery_connection_v1/services/connection_service/transports/grpc_asyncio.py
+++ b/google/cloud/bigquery_connection_v1/services/connection_service/transports/grpc_asyncio.py
@@ -465,5 +465,8 @@ def test_iam_permissions(
             )
         return self._stubs["test_iam_permissions"]
 
+    def close(self):
+        return self.grpc_channel.close()
+
 
 __all__ = ("ConnectionServiceGrpcAsyncIOTransport",)
diff --git a/google/cloud/bigquery_connection_v1/types/connection.py b/google/cloud/bigquery_connection_v1/types/connection.py
index 12a3c85..92162ee 100644
--- a/google/cloud/bigquery_connection_v1/types/connection.py
+++ b/google/cloud/bigquery_connection_v1/types/connection.py
@@ -134,6 +134,7 @@ class UpdateConnectionRequest(proto.Message):
 
 class DeleteConnectionRequest(proto.Message):
     r"""The request for [ConnectionService.DeleteConnectionRequest][].
+
     Attributes:
         name (str):
             Required. Name of the deleted connection, for example:
@@ -192,6 +193,7 @@ class Connection(proto.Message):
 
 class CloudSqlProperties(proto.Message):
     r"""Connection properties specific to the Cloud SQL.
+
     Attributes:
         instance_id (str):
             Cloud SQL instance ID in the form
@@ -218,6 +220,7 @@ class DatabaseType(proto.Enum):
 
 class CloudSqlCredential(proto.Message):
     r"""Credential info for the Cloud SQL.
+
     Attributes:
         username (str):
             The username for the credential.
@@ -231,6 +234,7 @@ class CloudSqlCredential(proto.Message):
 
 class CloudSpannerProperties(proto.Message):
     r"""Connection properties specific to Cloud Spanner.
+
     Attributes:
         database (str):
             Cloud Spanner database in the form
@@ -246,6 +250,7 @@ class CloudSpannerProperties(proto.Message):
 
 class AwsProperties(proto.Message):
     r"""Connection properties specific to Amazon Web Services (AWS).
+
     Attributes:
         cross_account_role (google.cloud.bigquery_connection_v1.types.AwsCrossAccountRole):
             Authentication using Google owned AWS IAM
diff --git a/tests/unit/gapic/bigquery_connection_v1/test_connection_service.py b/tests/unit/gapic/bigquery_connection_v1/test_connection_service.py
index a2b8965..6edc88e 100644
--- a/tests/unit/gapic/bigquery_connection_v1/test_connection_service.py
+++ b/tests/unit/gapic/bigquery_connection_v1/test_connection_service.py
@@ -29,6 +29,7 @@
 from google.api_core import gapic_v1
 from google.api_core import grpc_helpers
 from google.api_core import grpc_helpers_async
+from google.api_core import path_template
 from google.auth import credentials as ga_credentials
 from google.auth.exceptions import MutualTLSChannelError
 from google.cloud.bigquery_connection_v1.services.connection_service import (
@@ -2608,6 +2609,9 @@ def test_connection_service_base_transport():
         with pytest.raises(NotImplementedError):
             getattr(transport, method)(request=object())
 
+    with pytest.raises(NotImplementedError):
+        transport.close()
+
 
 @requires_google_auth_gte_1_25_0
 def test_connection_service_base_transport_with_credentials_file():
@@ -3111,3 +3115,49 @@ def test_client_withDEFAULT_CLIENT_INFO():
             credentials=ga_credentials.AnonymousCredentials(), client_info=client_info,
         )
         prep.assert_called_once_with(client_info)
+
+
+@pytest.mark.asyncio
+async def test_transport_close_async():
+    client = ConnectionServiceAsyncClient(
+        credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio",
+    )
+    with mock.patch.object(
+        type(getattr(client.transport, "grpc_channel")), "close"
+    ) as close:
+        async with client:
+            close.assert_not_called()
+        close.assert_called_once()
+
+
+def test_transport_close():
+    transports = {
+        "grpc": "_grpc_channel",
+    }
+
+    for transport, close_name in transports.items():
+        client = ConnectionServiceClient(
+            credentials=ga_credentials.AnonymousCredentials(), transport=transport
+        )
+        with mock.patch.object(
+            type(getattr(client.transport, close_name)), "close"
+        ) as close:
+            with client:
+                close.assert_not_called()
+            close.assert_called_once()
+
+
+def test_client_ctx():
+    transports = [
+        "grpc",
+    ]
+    for transport in transports:
+        client = ConnectionServiceClient(
+            credentials=ga_credentials.AnonymousCredentials(), transport=transport
+        )
+        # Test client calls underlying transport.
+        with mock.patch.object(type(client.transport), "close") as close:
+            close.assert_not_called()
+            with client:
+                pass
+            close.assert_called()