Skip to content
This repository has been archived by the owner on Feb 1, 2024. It is now read-only.

Commit

Permalink
feat: add context manager support in client (#173)
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 61a5857 commit ceec8f1
Show file tree
Hide file tree
Showing 24 changed files with 266 additions and 13 deletions.
6 changes: 6 additions & 0 deletions google/cloud/tasks_v2/services/cloud_tasks/async_client.py
Expand Up @@ -1755,6 +1755,12 @@ async def run_task(
# 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/tasks_v2/services/cloud_tasks/client.py
Expand Up @@ -370,10 +370,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_queues(
Expand Down Expand Up @@ -1879,6 +1876,19 @@ def run_task(
# 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
9 changes: 9 additions & 0 deletions google/cloud/tasks_v2/services/cloud_tasks/transports/base.py
Expand Up @@ -305,6 +305,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 list_queues(
self,
Expand Down
3 changes: 3 additions & 0 deletions google/cloud/tasks_v2/services/cloud_tasks/transports/grpc.py
Expand Up @@ -768,5 +768,8 @@ def run_task(self) -> Callable[[cloudtasks.RunTaskRequest], task.Task]:
)
return self._stubs["run_task"]

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


__all__ = ("CloudTasksGrpcTransport",)
Expand Up @@ -787,5 +787,8 @@ def run_task(self) -> Callable[[cloudtasks.RunTaskRequest], Awaitable[task.Task]
)
return self._stubs["run_task"]

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


__all__ = ("CloudTasksGrpcAsyncIOTransport",)
2 changes: 2 additions & 0 deletions google/cloud/tasks_v2/types/task.py
Expand Up @@ -28,6 +28,7 @@

class Task(proto.Message):
r"""A unit of scheduled work.
Attributes:
name (str):
Optionally caller-specified in
Expand Down Expand Up @@ -177,6 +178,7 @@ class View(proto.Enum):

class Attempt(proto.Message):
r"""The status of a task attempt.
Attributes:
schedule_time (google.protobuf.timestamp_pb2.Timestamp):
Output only. The time that this attempt was scheduled.
Expand Down
Expand Up @@ -2189,6 +2189,12 @@ async def run_task(
# 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/tasks_v2beta2/services/cloud_tasks/client.py
Expand Up @@ -370,10 +370,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_queues(
Expand Down Expand Up @@ -2313,6 +2310,19 @@ def run_task(
# 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 @@ -317,6 +317,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 list_queues(
self,
Expand Down
Expand Up @@ -927,5 +927,8 @@ def run_task(self) -> Callable[[cloudtasks.RunTaskRequest], task.Task]:
)
return self._stubs["run_task"]

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


__all__ = ("CloudTasksGrpcTransport",)
Expand Up @@ -952,5 +952,8 @@ def run_task(self) -> Callable[[cloudtasks.RunTaskRequest], Awaitable[task.Task]
)
return self._stubs["run_task"]

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


__all__ = ("CloudTasksGrpcAsyncIOTransport",)
1 change: 1 addition & 0 deletions google/cloud/tasks_v2beta2/types/queue.py
Expand Up @@ -408,6 +408,7 @@ class RetryConfig(proto.Message):

class QueueStats(proto.Message):
r"""Statistics for a queue.
Attributes:
tasks_count (int):
Output only. An estimation of the number of
Expand Down
3 changes: 2 additions & 1 deletion google/cloud/tasks_v2beta2/types/target.py
Expand Up @@ -40,7 +40,8 @@ class HttpMethod(proto.Enum):


class PullTarget(proto.Message):
r"""Pull target. """
r"""Pull target.
"""


class PullMessage(proto.Message):
Expand Down
3 changes: 3 additions & 0 deletions google/cloud/tasks_v2beta2/types/task.py
Expand Up @@ -28,6 +28,7 @@

class Task(proto.Message):
r"""A unit of scheduled work.
Attributes:
name (str):
Optionally caller-specified in
Expand Down Expand Up @@ -129,6 +130,7 @@ class View(proto.Enum):

class TaskStatus(proto.Message):
r"""Status of the task.
Attributes:
attempt_dispatch_count (int):
Output only. The number of attempts
Expand Down Expand Up @@ -169,6 +171,7 @@ class TaskStatus(proto.Message):

class AttemptStatus(proto.Message):
r"""The status of a task attempt.
Attributes:
schedule_time (google.protobuf.timestamp_pb2.Timestamp):
Output only. The time that this attempt was scheduled.
Expand Down
Expand Up @@ -1757,6 +1757,12 @@ async def run_task(
# 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/tasks_v2beta3/services/cloud_tasks/client.py
Expand Up @@ -370,10 +370,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_queues(
Expand Down Expand Up @@ -1881,6 +1878,19 @@ def run_task(
# 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 @@ -305,6 +305,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 list_queues(
self,
Expand Down
Expand Up @@ -769,5 +769,8 @@ def run_task(self) -> Callable[[cloudtasks.RunTaskRequest], task.Task]:
)
return self._stubs["run_task"]

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


__all__ = ("CloudTasksGrpcTransport",)
Expand Up @@ -788,5 +788,8 @@ def run_task(self) -> Callable[[cloudtasks.RunTaskRequest], Awaitable[task.Task]
)
return self._stubs["run_task"]

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


__all__ = ("CloudTasksGrpcAsyncIOTransport",)
1 change: 1 addition & 0 deletions google/cloud/tasks_v2beta3/types/queue.py
Expand Up @@ -433,6 +433,7 @@ class StackdriverLoggingConfig(proto.Message):

class QueueStats(proto.Message):
r"""Statistics for a queue.
Attributes:
tasks_count (int):
Output only. An estimation of the number of
Expand Down
2 changes: 2 additions & 0 deletions google/cloud/tasks_v2beta3/types/task.py
Expand Up @@ -28,6 +28,7 @@

class Task(proto.Message):
r"""A unit of scheduled work.
Attributes:
name (str):
Optionally caller-specified in
Expand Down Expand Up @@ -192,6 +193,7 @@ class View(proto.Enum):

class Attempt(proto.Message):
r"""The status of a task attempt.
Attributes:
schedule_time (google.protobuf.timestamp_pb2.Timestamp):
Output only. The time that this attempt was scheduled.
Expand Down
50 changes: 50 additions & 0 deletions tests/unit/gapic/tasks_v2/test_cloud_tasks.py
Expand Up @@ -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.tasks_v2.services.cloud_tasks import CloudTasksAsyncClient
Expand Down Expand Up @@ -4091,6 +4092,9 @@ def test_cloud_tasks_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_cloud_tasks_base_transport_with_credentials_file():
Expand Down Expand Up @@ -4582,3 +4586,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 = CloudTasksAsyncClient(
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 = CloudTasksClient(
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 = CloudTasksClient(
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 ceec8f1

Please sign in to comment.