Skip to content
This repository has been archived by the owner on Jul 6, 2023. It is now read-only.

Commit

Permalink
feat: add context manager support in client (#36)
Browse files Browse the repository at this point in the history
- [ ] Regenerate this pull request now.

chore: fix docstring for first attribute of protos

committer: @busunkim96
PiperOrigin-RevId: 401271153

Source-Link: googleapis/googleapis@787f8c9

Source-Link: googleapis/googleapis-gen@81decff
Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiODFkZWNmZmU5ZmM3MjM5NmE4MTUzZTc1NmQxZDY3YTZlZWNmZDYyMCJ9
  • Loading branch information
gcf-owl-bot[bot] committed Oct 8, 2021
1 parent a372869 commit 3c238d5
Show file tree
Hide file tree
Showing 7 changed files with 96 additions and 4 deletions.
Expand Up @@ -708,6 +708,12 @@ async def restart_instance(
# 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(
Expand Down
18 changes: 14 additions & 4 deletions google/cloud/data_fusion_v1/services/data_fusion/client.py
Expand Up @@ -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 list_available_versions(
Expand Down Expand Up @@ -904,6 +901,19 @@ def restart_instance(
# 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(
Expand Down
Expand Up @@ -181,6 +181,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 operations_client(self) -> operations_v1.OperationsClient:
"""Return the client designed to process long-running operations."""
Expand Down
Expand Up @@ -433,5 +433,8 @@ def restart_instance(
)
return self._stubs["restart_instance"]

def close(self):
self.grpc_channel.close()


__all__ = ("DataFusionGrpcTransport",)
Expand Up @@ -448,5 +448,8 @@ def restart_instance(
)
return self._stubs["restart_instance"]

def close(self):
return self.grpc_channel.close()


__all__ = ("DataFusionGrpcAsyncIOTransport",)
11 changes: 11 additions & 0 deletions google/cloud/data_fusion_v1/types/datafusion.py
Expand Up @@ -95,6 +95,7 @@ class Version(proto.Message):

class Accelerator(proto.Message):
r"""Identifies Data Fusion accelerators for an instance.
Attributes:
accelerator_type (google.cloud.data_fusion_v1.types.Accelerator.AcceleratorType):
The type of an accelator for a CDF instance.
Expand Down Expand Up @@ -139,6 +140,7 @@ class CryptoKeyConfig(proto.Message):

class Instance(proto.Message):
r"""Represents a Data Fusion instance.
Attributes:
name (str):
Output only. The name of this instance is in
Expand Down Expand Up @@ -291,6 +293,7 @@ class State(proto.Enum):

class ListInstancesRequest(proto.Message):
r"""Request message for listing Data Fusion instances.
Attributes:
parent (str):
The project and location for which to
Expand Down Expand Up @@ -320,6 +323,7 @@ class ListInstancesRequest(proto.Message):

class ListInstancesResponse(proto.Message):
r"""Response message for the list instance request.
Attributes:
instances (Sequence[google.cloud.data_fusion_v1.types.Instance]):
Represents a list of Data Fusion instances.
Expand All @@ -341,6 +345,7 @@ def raw_page(self):

class ListAvailableVersionsRequest(proto.Message):
r"""Request message for the list available versions request.
Attributes:
parent (str):
Required. The project and location for which
Expand All @@ -366,6 +371,7 @@ class ListAvailableVersionsRequest(proto.Message):

class ListAvailableVersionsResponse(proto.Message):
r"""Response message for the list available versions request.
Attributes:
available_versions (Sequence[google.cloud.data_fusion_v1.types.Version]):
Represents a list of versions that are
Expand Down Expand Up @@ -400,6 +406,7 @@ class GetInstanceRequest(proto.Message):

class CreateInstanceRequest(proto.Message):
r"""Request message for creating a Data Fusion instance.
Attributes:
parent (str):
The instance's project and location in the
Expand All @@ -417,6 +424,7 @@ class CreateInstanceRequest(proto.Message):

class DeleteInstanceRequest(proto.Message):
r"""Request message for deleting a Data Fusion instance.
Attributes:
name (str):
The instance resource name in the format
Expand All @@ -428,6 +436,7 @@ class DeleteInstanceRequest(proto.Message):

class UpdateInstanceRequest(proto.Message):
r"""
Attributes:
instance (google.cloud.data_fusion_v1.types.Instance):
The instance resource that replaces the
Expand All @@ -453,6 +462,7 @@ class UpdateInstanceRequest(proto.Message):

class RestartInstanceRequest(proto.Message):
r"""Request message for restarting a Data Fusion instance.
Attributes:
name (str):
Name of the Data Fusion instance which need
Expand All @@ -465,6 +475,7 @@ class RestartInstanceRequest(proto.Message):

class OperationMetadata(proto.Message):
r"""Represents the metadata of a long-running operation.
Attributes:
create_time (google.protobuf.timestamp_pb2.Timestamp):
The time the operation was created.
Expand Down
50 changes: 50 additions & 0 deletions tests/unit/gapic/data_fusion_v1/test_data_fusion.py
Expand Up @@ -32,6 +32,7 @@
from google.api_core import grpc_helpers_async
from google.api_core import operation_async # type: ignore
from google.api_core import operations_v1
from google.api_core import path_template
from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
from google.cloud.data_fusion_v1.services.data_fusion import DataFusionAsyncClient
Expand Down Expand Up @@ -2191,6 +2192,9 @@ def test_data_fusion_base_transport():
with pytest.raises(NotImplementedError):
getattr(transport, method)(request=object())

with pytest.raises(NotImplementedError):
transport.close()

# Additionally, the LRO client (a property) should
# also raise NotImplementedError
with pytest.raises(NotImplementedError):
Expand Down Expand Up @@ -2687,3 +2691,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 = DataFusionAsyncClient(
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 = DataFusionClient(
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 = DataFusionClient(
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()

0 comments on commit 3c238d5

Please sign in to comment.