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 (#9)
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 c9c9684 commit bdcf454
Show file tree
Hide file tree
Showing 7 changed files with 117 additions and 5 deletions.
6 changes: 6 additions & 0 deletions google/cloud/deploy_v1/services/cloud_deploy/async_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -1811,6 +1811,12 @@ async def get_config(
# 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/deploy_v1/services/cloud_deploy/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -474,10 +474,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_delivery_pipelines(
Expand Down Expand Up @@ -2029,6 +2026,19 @@ def get_config(
# 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
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,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
Original file line number Diff line number Diff line change
Expand Up @@ -733,5 +733,8 @@ def get_config(
)
return self._stubs["get_config"]

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


__all__ = ("CloudDeployGrpcTransport",)
Original file line number Diff line number Diff line change
Expand Up @@ -755,5 +755,8 @@ def get_config(
)
return self._stubs["get_config"]

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


__all__ = ("CloudDeployGrpcAsyncIOTransport",)
33 changes: 32 additions & 1 deletion google/cloud/deploy_v1/types/cloud_deploy.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,7 @@ class SerialPipeline(proto.Message):

class Stage(proto.Message):
r"""Stage specifies a location to which to deploy.
Attributes:
target_id (str):
The target_id to which this stage points. This field refers
Expand Down Expand Up @@ -224,6 +225,7 @@ class PipelineCondition(proto.Message):

class ListDeliveryPipelinesRequest(proto.Message):
r"""The request object for ``ListDeliveryPipelines``.
Attributes:
parent (str):
Required. The parent, which owns this collection of
Expand Down Expand Up @@ -260,6 +262,7 @@ class ListDeliveryPipelinesRequest(proto.Message):

class ListDeliveryPipelinesResponse(proto.Message):
r"""The response object from ``ListDeliveryPipelines``.
Attributes:
delivery_pipelines (Sequence[google.cloud.deploy_v1.types.DeliveryPipeline]):
The ``DeliveryPipeline`` objects.
Expand All @@ -284,6 +287,7 @@ def raw_page(self):

class GetDeliveryPipelineRequest(proto.Message):
r"""The request object for ``GetDeliveryPipeline``
Attributes:
name (str):
Required. Name of the ``DeliveryPipeline``. Format must be
Expand All @@ -295,6 +299,7 @@ class GetDeliveryPipelineRequest(proto.Message):

class CreateDeliveryPipelineRequest(proto.Message):
r"""The request object for ``CreateDeliveryPipeline``.
Attributes:
parent (str):
Required. The parent collection in which the
Expand Down Expand Up @@ -339,6 +344,7 @@ class CreateDeliveryPipelineRequest(proto.Message):

class UpdateDeliveryPipelineRequest(proto.Message):
r"""The request object for ``UpdateDeliveryPipeline``.
Attributes:
update_mask (google.protobuf.field_mask_pb2.FieldMask):
Required. Field mask is used to specify the fields to be
Expand Down Expand Up @@ -390,6 +396,7 @@ class UpdateDeliveryPipelineRequest(proto.Message):

class DeleteDeliveryPipelineRequest(proto.Message):
r"""The request object for ``DeleteDeliveryPipeline``.
Attributes:
name (str):
Required. The name of the ``DeliveryPipeline`` to delete.
Expand Down Expand Up @@ -547,6 +554,7 @@ class ExecutionEnvironmentUsage(proto.Enum):

class DefaultPool(proto.Message):
r"""Execution using the default Cloud Build pool.
Attributes:
service_account (str):
Optional. Google service account to use for execution. If
Expand All @@ -568,6 +576,7 @@ class DefaultPool(proto.Message):

class PrivatePool(proto.Message):
r"""Execution using a private Cloud Build pool.
Attributes:
worker_pool (str):
Required. Resource name of the Cloud Build worker pool to
Expand All @@ -594,6 +603,7 @@ class PrivatePool(proto.Message):

class GkeCluster(proto.Message):
r"""Information specifying a GKE Cluster.
Attributes:
cluster (str):
Information specifying a GKE Cluster. Format is
Expand All @@ -605,6 +615,7 @@ class GkeCluster(proto.Message):

class ListTargetsRequest(proto.Message):
r"""The request object for ``ListTargets``.
Attributes:
parent (str):
Required. The parent, which owns this collection of targets.
Expand Down Expand Up @@ -641,6 +652,7 @@ class ListTargetsRequest(proto.Message):

class ListTargetsResponse(proto.Message):
r"""The response object from ``ListTargets``.
Attributes:
targets (Sequence[google.cloud.deploy_v1.types.Target]):
The ``Target`` objects.
Expand All @@ -663,6 +675,7 @@ def raw_page(self):

class GetTargetRequest(proto.Message):
r"""The request object for ``GetTarget``.
Attributes:
name (str):
Required. Name of the ``Target``. Format must be
Expand All @@ -674,6 +687,7 @@ class GetTargetRequest(proto.Message):

class CreateTargetRequest(proto.Message):
r"""The request object for ``CreateTarget``.
Attributes:
parent (str):
Required. The parent collection in which the ``Target``
Expand Down Expand Up @@ -716,6 +730,7 @@ class CreateTargetRequest(proto.Message):

class UpdateTargetRequest(proto.Message):
r"""The request object for ``UpdateTarget``.
Attributes:
update_mask (google.protobuf.field_mask_pb2.FieldMask):
Required. Field mask is used to specify the fields to be
Expand Down Expand Up @@ -764,6 +779,7 @@ class UpdateTargetRequest(proto.Message):

class DeleteTargetRequest(proto.Message):
r"""The request object for ``DeleteTarget``.
Attributes:
name (str):
Required. The name of the ``Target`` to delete. Format
Expand Down Expand Up @@ -896,6 +912,7 @@ class RenderState(proto.Enum):

class TargetRender(proto.Message):
r"""Details of rendering for a single target.
Attributes:
rendering_build (str):
Output only. The resource name of the Cloud Build ``Build``
Expand Down Expand Up @@ -953,6 +970,7 @@ class TargetRenderState(proto.Enum):

class BuildArtifact(proto.Message):
r"""Description of an a image to use during Skaffold rendering.
Attributes:
image (str):
Image name in Skaffold configuration.
Expand All @@ -969,6 +987,7 @@ class BuildArtifact(proto.Message):

class TargetArtifact(proto.Message):
r"""The artifacts produced by a target render operation.
Attributes:
artifact_uri (str):
Output only. URI of a directory containing
Expand All @@ -990,6 +1009,7 @@ class TargetArtifact(proto.Message):

class ListReleasesRequest(proto.Message):
r"""The request object for ``ListReleases``.
Attributes:
parent (str):
Required. The ``DeliveryPipeline`` which owns this
Expand Down Expand Up @@ -1025,6 +1045,7 @@ class ListReleasesRequest(proto.Message):

class ListReleasesResponse(proto.Message):
r"""The response object from ``ListReleases``.
Attributes:
releases (Sequence[google.cloud.deploy_v1.types.Release]):
The ``Release`` objects.
Expand All @@ -1047,6 +1068,7 @@ def raw_page(self):

class GetReleaseRequest(proto.Message):
r"""The request object for ``GetRelease``.
Attributes:
name (str):
Required. Name of the ``Release``. Format must be
Expand All @@ -1058,6 +1080,7 @@ class GetReleaseRequest(proto.Message):

class CreateReleaseRequest(proto.Message):
r"""The request object for ``CreateRelease``,
Attributes:
parent (str):
Required. The parent collection in which the ``Release``
Expand Down Expand Up @@ -1209,6 +1232,7 @@ class State(proto.Enum):

class ListRolloutsRequest(proto.Message):
r"""ListRolloutsRequest is the request object used by ``ListRollouts``.
Attributes:
parent (str):
Required. The ``Release`` which owns this collection of
Expand Down Expand Up @@ -1268,6 +1292,7 @@ def raw_page(self):

class GetRolloutRequest(proto.Message):
r"""GetRolloutRequest is the request object used by ``GetRollout``.
Attributes:
name (str):
Required. Name of the ``Rollout``. Format must be
Expand Down Expand Up @@ -1323,6 +1348,7 @@ class CreateRolloutRequest(proto.Message):

class OperationMetadata(proto.Message):
r"""Represents the metadata of the long-running operation.
Attributes:
create_time (google.protobuf.timestamp_pb2.Timestamp):
Output only. The time the operation was
Expand Down Expand Up @@ -1361,6 +1387,7 @@ class OperationMetadata(proto.Message):

class ApproveRolloutRequest(proto.Message):
r"""The request object used by ``ApproveRollout``.
Attributes:
name (str):
Required. Name of the Rollout. Format is
Expand All @@ -1375,11 +1402,13 @@ class ApproveRolloutRequest(proto.Message):


class ApproveRolloutResponse(proto.Message):
r"""The response object from ``ApproveRollout``. """
r"""The response object from ``ApproveRollout``.
"""


class Config(proto.Message):
r"""Service-wide configuration.
Attributes:
name (str):
Name of the configuration.
Expand All @@ -1401,6 +1430,7 @@ class Config(proto.Message):

class SkaffoldVersion(proto.Message):
r"""Details of a supported Skaffold version.
Attributes:
version (str):
Release version number. For example,
Expand All @@ -1416,6 +1446,7 @@ class SkaffoldVersion(proto.Message):

class GetConfigRequest(proto.Message):
r"""Request to get a configuration.
Attributes:
name (str):
Required. Name of requested configuration.
Expand Down
50 changes: 50 additions & 0 deletions tests/unit/gapic/deploy_v1/test_cloud_deploy.py
Original file line number Diff line number Diff line change
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.deploy_v1.services.cloud_deploy import CloudDeployAsyncClient
Expand Down Expand Up @@ -5023,6 +5024,9 @@ def test_cloud_deploy_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 @@ -5704,3 +5708,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 = CloudDeployAsyncClient(
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 = CloudDeployClient(
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 = CloudDeployClient(
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 bdcf454

Please sign in to comment.