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

feat: add context manager support in client #111

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -849,6 +849,12 @@ async def apply_parameters(
# 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/memcache_v1/services/cloud_memcache/client.py
Expand Up @@ -366,10 +366,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_instances(
Expand Down Expand Up @@ -1036,6 +1033,19 @@ def apply_parameters(
# 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 @@ -177,6 +177,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 @@ -450,5 +450,8 @@ def apply_parameters(
)
return self._stubs["apply_parameters"]

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


__all__ = ("CloudMemcacheGrpcTransport",)
Expand Up @@ -468,5 +468,8 @@ def apply_parameters(
)
return self._stubs["apply_parameters"]

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


__all__ = ("CloudMemcacheGrpcAsyncIOTransport",)
6 changes: 6 additions & 0 deletions google/cloud/memcache_v1/types/cloud_memcache.py
Expand Up @@ -46,6 +46,7 @@ class MemcacheVersion(proto.Enum):

class Instance(proto.Message):
r"""

Attributes:
name (str):
Required. Unique name of the resource in this scope
Expand Down Expand Up @@ -129,6 +130,7 @@ class State(proto.Enum):

class NodeConfig(proto.Message):
r"""Configuration for a Memcached Node.

Attributes:
cpu_count (int):
Required. Number of cpus per Memcached node.
Expand All @@ -142,6 +144,7 @@ class NodeConfig(proto.Message):

class Node(proto.Message):
r"""

Attributes:
node_id (str):
Output only. Identifier of the Memcached
Expand Down Expand Up @@ -182,6 +185,7 @@ class State(proto.Enum):

class InstanceMessage(proto.Message):
r"""

Attributes:
code (google.cloud.memcache_v1.types.Instance.InstanceMessage.Code):
A code that correspond to one type of user-
Expand Down Expand Up @@ -417,6 +421,7 @@ class UpdateParametersRequest(proto.Message):

class MemcacheParameters(proto.Message):
r"""

Attributes:
id (str):
Output only. The unique ID associated with
Expand All @@ -436,6 +441,7 @@ class MemcacheParameters(proto.Message):

class OperationMetadata(proto.Message):
r"""Represents the metadata of a long-running operation.

Attributes:
create_time (google.protobuf.timestamp_pb2.Timestamp):
Output only. Time when the operation was
Expand Down
Expand Up @@ -960,6 +960,12 @@ async def apply_software_update(
# 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/memcache_v1beta2/services/cloud_memcache/client.py
Expand Up @@ -366,10 +366,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_instances(
Expand Down Expand Up @@ -1147,6 +1144,19 @@ def apply_software_update(
# 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 @@ -182,6 +182,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 @@ -479,5 +479,8 @@ def apply_software_update(
)
return self._stubs["apply_software_update"]

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


__all__ = ("CloudMemcacheGrpcTransport",)
Expand Up @@ -497,5 +497,8 @@ def apply_software_update(
)
return self._stubs["apply_software_update"]

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


__all__ = ("CloudMemcacheGrpcAsyncIOTransport",)
8 changes: 7 additions & 1 deletion google/cloud/memcache_v1beta2/types/cloud_memcache.py
Expand Up @@ -49,6 +49,7 @@ class MemcacheVersion(proto.Enum):

class Instance(proto.Message):
r"""A Memorystore for Memcached instance

Attributes:
name (str):
Required. Unique name of the resource in this scope
Expand Down Expand Up @@ -138,6 +139,7 @@ class State(proto.Enum):

class NodeConfig(proto.Message):
r"""Configuration for a Memcached Node.

Attributes:
cpu_count (int):
Required. Number of cpus per Memcached node.
Expand All @@ -151,6 +153,7 @@ class NodeConfig(proto.Message):

class Node(proto.Message):
r"""

Attributes:
node_id (str):
Output only. Identifier of the Memcached
Expand Down Expand Up @@ -195,6 +198,7 @@ class State(proto.Enum):

class InstanceMessage(proto.Message):
r"""

Attributes:
code (google.cloud.memcache_v1beta2.types.Instance.InstanceMessage.Code):
A code that correspond to one type of user-
Expand Down Expand Up @@ -475,6 +479,7 @@ class MemcacheParameters(proto.Message):

class OperationMetadata(proto.Message):
r"""Represents the metadata of a long-running operation.

Attributes:
create_time (google.protobuf.timestamp_pb2.Timestamp):
Output only. Time when the operation was
Expand Down Expand Up @@ -529,7 +534,8 @@ class LocationMetadata(proto.Message):


class ZoneMetadata(proto.Message):
r""" """
r"""
"""


__all__ = tuple(sorted(__protobuf__.manifest))
50 changes: 50 additions & 0 deletions tests/unit/gapic/memcache_v1/test_cloud_memcache.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.memcache_v1.services.cloud_memcache import CloudMemcacheAsyncClient
Expand Down Expand Up @@ -2274,6 +2275,9 @@ def test_cloud_memcache_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 @@ -2785,3 +2789,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 = CloudMemcacheAsyncClient(
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 = CloudMemcacheClient(
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 = CloudMemcacheClient(
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()
50 changes: 50 additions & 0 deletions tests/unit/gapic/memcache_v1beta2/test_cloud_memcache.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.memcache_v1beta2.services.cloud_memcache import (
Expand Down Expand Up @@ -2510,6 +2511,9 @@ def test_cloud_memcache_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 @@ -3021,3 +3025,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 = CloudMemcacheAsyncClient(
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 = CloudMemcacheClient(
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 = CloudMemcacheClient(
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()