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

Commit

Permalink
feat: add context manager support in client (#28)
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 effe0a2 commit 54fcd0f
Show file tree
Hide file tree
Showing 8 changed files with 98 additions and 4 deletions.
Expand Up @@ -579,6 +579,12 @@ async def run_transfer_job(
# 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 @@ -338,10 +338,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 get_google_service_account(
Expand Down Expand Up @@ -765,6 +762,19 @@ def run_transfer_job(
# 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 @@ -190,6 +190,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 @@ -480,5 +480,8 @@ def run_transfer_job(
)
return self._stubs["run_transfer_job"]

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


__all__ = ("StorageTransferServiceGrpcTransport",)
Expand Up @@ -496,5 +496,8 @@ def run_transfer_job(
)
return self._stubs["run_transfer_job"]

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


__all__ = ("StorageTransferServiceGrpcAsyncIOTransport",)
8 changes: 8 additions & 0 deletions google/cloud/storage_transfer_v1/types/transfer.py
Expand Up @@ -37,6 +37,7 @@

class GetGoogleServiceAccountRequest(proto.Message):
r"""Request passed to GetGoogleServiceAccount.
Attributes:
project_id (str):
Required. The ID of the Google Cloud Platform
Expand All @@ -49,6 +50,7 @@ class GetGoogleServiceAccountRequest(proto.Message):

class CreateTransferJobRequest(proto.Message):
r"""Request passed to CreateTransferJob.
Attributes:
transfer_job (google.cloud.storage_transfer_v1.types.TransferJob):
Required. The job to create.
Expand All @@ -61,6 +63,7 @@ class CreateTransferJobRequest(proto.Message):

class UpdateTransferJobRequest(proto.Message):
r"""Request passed to UpdateTransferJob.
Attributes:
job_name (str):
Required. The name of job to update.
Expand Down Expand Up @@ -107,6 +110,7 @@ class UpdateTransferJobRequest(proto.Message):

class GetTransferJobRequest(proto.Message):
r"""Request passed to GetTransferJob.
Attributes:
job_name (str):
Required.
Expand Down Expand Up @@ -153,6 +157,7 @@ class ListTransferJobsRequest(proto.Message):

class ListTransferJobsResponse(proto.Message):
r"""Response from ListTransferJobs.
Attributes:
transfer_jobs (Sequence[google.cloud.storage_transfer_v1.types.TransferJob]):
A list of transfer jobs.
Expand All @@ -172,6 +177,7 @@ def raw_page(self):

class PauseTransferOperationRequest(proto.Message):
r"""Request passed to PauseTransferOperation.
Attributes:
name (str):
Required. The name of the transfer operation.
Expand All @@ -182,6 +188,7 @@ class PauseTransferOperationRequest(proto.Message):

class ResumeTransferOperationRequest(proto.Message):
r"""Request passed to ResumeTransferOperation.
Attributes:
name (str):
Required. The name of the transfer operation.
Expand All @@ -192,6 +199,7 @@ class ResumeTransferOperationRequest(proto.Message):

class RunTransferJobRequest(proto.Message):
r"""Request passed to RunTransferJob.
Attributes:
job_name (str):
Required. The name of the transfer job.
Expand Down
5 changes: 5 additions & 0 deletions google/cloud/storage_transfer_v1/types/transfer_types.py
Expand Up @@ -48,6 +48,7 @@

class GoogleServiceAccount(proto.Message):
r"""Google service account
Attributes:
account_email (str):
Email address of the service account.
Expand Down Expand Up @@ -446,6 +447,7 @@ class TransferOptions(proto.Message):

class TransferSpec(proto.Message):
r"""Configuration for running a transfer.
Attributes:
gcs_data_sink (google.cloud.storage_transfer_v1.types.GcsData):
A Cloud Storage data sink.
Expand Down Expand Up @@ -494,6 +496,7 @@ class TransferSpec(proto.Message):

class Schedule(proto.Message):
r"""Transfers can be scheduled to recur or to run just once.
Attributes:
schedule_start_date (google.type.date_pb2.Date):
Required. The start date of a transfer. Date boundaries are
Expand Down Expand Up @@ -685,6 +688,7 @@ class Status(proto.Enum):

class ErrorLogEntry(proto.Message):
r"""An entry describing an error that has occurred.
Attributes:
url (str):
Required. A URL that refers to the target (a
Expand Down Expand Up @@ -868,6 +872,7 @@ class PayloadFormat(proto.Enum):

class TransferOperation(proto.Message):
r"""A description of the execution of a transfer.
Attributes:
name (str):
A globally unique ID assigned by the system.
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.storage_transfer_v1.services.storage_transfer_service import (
Expand Down Expand Up @@ -1835,6 +1836,9 @@ def test_storage_transfer_service_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 @@ -2328,3 +2332,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 = StorageTransferServiceAsyncClient(
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 = StorageTransferServiceClient(
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 = StorageTransferServiceClient(
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 54fcd0f

Please sign in to comment.