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 (#43)
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 7, 2021
1 parent 7702dac commit 44bd253
Show file tree
Hide file tree
Showing 7 changed files with 97 additions and 5 deletions.
Expand Up @@ -243,6 +243,12 @@ async def run_pipeline(
# 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
Expand Up @@ -333,10 +333,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 run_pipeline(
Expand Down Expand Up @@ -418,6 +415,19 @@ def run_pipeline(
# 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 @@ -161,6 +161,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 @@ -286,5 +286,8 @@ def run_pipeline(
)
return self._stubs["run_pipeline"]

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


__all__ = ("WorkflowsServiceV2BetaGrpcTransport",)
Expand Up @@ -291,5 +291,8 @@ def run_pipeline(
)
return self._stubs["run_pipeline"]

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


__all__ = ("WorkflowsServiceV2BetaGrpcAsyncIOTransport",)
13 changes: 12 additions & 1 deletion google/cloud/lifesciences_v2beta/types/workflows.py
Expand Up @@ -94,7 +94,8 @@ class RunPipelineRequest(proto.Message):
class RunPipelineResponse(proto.Message):
r"""The response to the RunPipeline method, returned in the
operation's result field on success.
"""
"""


class Pipeline(proto.Message):
Expand Down Expand Up @@ -131,6 +132,7 @@ class Pipeline(proto.Message):

class Action(proto.Message):
r"""Specifies a single action that runs a Docker container.
Attributes:
container_name (str):
An optional name for the container. The
Expand Down Expand Up @@ -379,6 +381,7 @@ class Resources(proto.Message):

class VirtualMachine(proto.Message):
r"""Carries information about a Compute Engine VM resource.
Attributes:
machine_type (str):
Required. The machine type of the virtual machine to create.
Expand Down Expand Up @@ -501,6 +504,7 @@ class VirtualMachine(proto.Message):

class ServiceAccount(proto.Message):
r"""Carries information about a Google Cloud service account.
Attributes:
email (str):
Email address of the service account. If not
Expand Down Expand Up @@ -543,6 +547,7 @@ class Accelerator(proto.Message):

class Network(proto.Message):
r"""VM networking options.
Attributes:
network (str):
The network name to attach the VM's network interface to.
Expand Down Expand Up @@ -683,6 +688,7 @@ class PersistentDisk(proto.Message):

class ExistingDisk(proto.Message):
r"""Configuration for an existing disk to be attached to the VM.
Attributes:
disk (str):
If ``disk`` contains slashes, the Cloud Life Sciences API
Expand All @@ -705,6 +711,7 @@ class ExistingDisk(proto.Message):

class NFSMount(proto.Message):
r"""Configuration for an ``NFSMount`` to be attached to the VM.
Attributes:
target (str):
A target NFS mount. The target must be specified as
Expand Down Expand Up @@ -888,6 +895,7 @@ class WorkerReleasedEvent(proto.Message):

class PullStartedEvent(proto.Message):
r"""An event generated when the worker starts pulling an image.
Attributes:
image_uri (str):
The URI of the image that was pulled.
Expand All @@ -898,6 +906,7 @@ class PullStartedEvent(proto.Message):

class PullStoppedEvent(proto.Message):
r"""An event generated when the worker stops pulling an image.
Attributes:
image_uri (str):
The URI of the image that was pulled.
Expand All @@ -908,6 +917,7 @@ class PullStoppedEvent(proto.Message):

class ContainerStartedEvent(proto.Message):
r"""An event generated when a container starts.
Attributes:
action_id (int):
The numeric ID of the action that started
Expand All @@ -933,6 +943,7 @@ class ContainerStartedEvent(proto.Message):

class ContainerStoppedEvent(proto.Message):
r"""An event generated when a container exits.
Attributes:
action_id (int):
The numeric ID of the action that started
Expand Down
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.lifesciences_v2beta.services.workflows_service_v2_beta import (
Expand Down Expand Up @@ -764,6 +765,9 @@ def test_workflows_service_v2_beta_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 @@ -1257,3 +1261,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 = WorkflowsServiceV2BetaAsyncClient(
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 = WorkflowsServiceV2BetaClient(
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 = WorkflowsServiceV2BetaClient(
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 44bd253

Please sign in to comment.