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

Commit

Permalink
feat: add context manager support in client (#87)
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 8cecb83 commit e32a6f6
Show file tree
Hide file tree
Showing 8 changed files with 97 additions and 16 deletions.
Expand Up @@ -123,7 +123,7 @@ class MembershipSpec(proto.Message):


class ConfigSync(proto.Message):
r"""Configuration for Config Syn.
r"""Configuration for Config Sync
Attributes:
git (google.cloud.gkehub.configmanagement_v1.types.GitConfig):
Expand Down Expand Up @@ -179,7 +179,7 @@ class GitConfig(proto.Message):


class PolicyController(proto.Message):
r"""Configuration for Policy Controlle.
r"""Configuration for Policy Controller
Attributes:
enabled (bool):
Expand Down Expand Up @@ -214,7 +214,7 @@ class PolicyController(proto.Message):


class HierarchyControllerConfig(proto.Message):
r"""Configuration for Hierarchy Controlle.
r"""Configuration for Hierarchy Controller
Attributes:
enabled (bool):
Expand All @@ -234,7 +234,7 @@ class HierarchyControllerConfig(proto.Message):


class HierarchyControllerDeploymentState(proto.Message):
r"""Deployment state for Hierarchy Controlle.
r"""Deployment state for Hierarchy Controller
Attributes:
hnc (google.cloud.gkehub.configmanagement_v1.types.DeploymentState):
Expand All @@ -250,7 +250,7 @@ class HierarchyControllerDeploymentState(proto.Message):


class HierarchyControllerVersion(proto.Message):
r"""Version for Hierarchy Controlle.
r"""Version for Hierarchy Controller
Attributes:
hnc (str):
Expand All @@ -264,7 +264,7 @@ class HierarchyControllerVersion(proto.Message):


class HierarchyControllerState(proto.Message):
r"""State for Hierarchy Controlle.
r"""State for Hierarchy Controller
Attributes:
version (google.cloud.gkehub.configmanagement_v1.types.HierarchyControllerVersion):
Expand All @@ -282,7 +282,7 @@ class HierarchyControllerState(proto.Message):


class OperatorState(proto.Message):
r"""State information for an ACM's Operato.
r"""State information for an ACM's Operator
Attributes:
version (str):
Expand All @@ -299,7 +299,7 @@ class OperatorState(proto.Message):


class InstallError(proto.Message):
r"""Errors pertaining to the installation of AC.
r"""Errors pertaining to the installation of ACM
Attributes:
error_message (str):
Expand All @@ -311,7 +311,7 @@ class InstallError(proto.Message):


class ConfigSyncState(proto.Message):
r"""State information for ConfigSyn.
r"""State information for ConfigSync
Attributes:
version (google.cloud.gkehub.configmanagement_v1.types.ConfigSyncVersion):
Expand Down Expand Up @@ -362,7 +362,7 @@ class ConfigSyncVersion(proto.Message):


class ConfigSyncDeploymentState(proto.Message):
r"""The state of ConfigSync's deployment on a cluste.
r"""The state of ConfigSync's deployment on a cluster
Attributes:
importer (google.cloud.gkehub.configmanagement_v1.types.DeploymentState):
Expand Down Expand Up @@ -484,7 +484,7 @@ class ErrorResource(proto.Message):


class GroupVersionKind(proto.Message):
r"""A Kubernetes object's GV.
r"""A Kubernetes object's GVK
Attributes:
group (str):
Expand Down
6 changes: 6 additions & 0 deletions google/cloud/gkehub_v1/services/gke_hub/async_client.py
Expand Up @@ -1147,6 +1147,12 @@ async def generate_connect_manifest(
# 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/gkehub_v1/services/gke_hub/client.py
Expand Up @@ -379,10 +379,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_memberships(
Expand Down Expand Up @@ -1361,6 +1358,19 @@ def generate_connect_manifest(
# 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/gkehub_v1/services/gke_hub/transports/base.py
Expand Up @@ -193,6 +193,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
3 changes: 3 additions & 0 deletions google/cloud/gkehub_v1/services/gke_hub/transports/grpc.py
Expand Up @@ -556,5 +556,8 @@ def generate_connect_manifest(
)
return self._stubs["generate_connect_manifest"]

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


__all__ = ("GkeHubGrpcTransport",)
Expand Up @@ -573,5 +573,8 @@ def generate_connect_manifest(
)
return self._stubs["generate_connect_manifest"]

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


__all__ = ("GkeHubGrpcAsyncIOTransport",)
2 changes: 1 addition & 1 deletion google/cloud/gkehub_v1/types/feature.py
Expand Up @@ -172,7 +172,7 @@ class Code(proto.Enum):


class CommonFeatureSpec(proto.Message):
r"""CommonFeatureSpec contains Hub-wide configuration informatio.
r"""CommonFeatureSpec contains Hub-wide configuration information
Attributes:
multiclusteringress (google.cloud.gkehub_v1.multiclusteringress_v1.FeatureSpec):
Expand Down
50 changes: 50 additions & 0 deletions tests/unit/gapic/gkehub_v1/test_gke_hub.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.gkehub_v1 import configmanagement_v1 # type: ignore
Expand Down Expand Up @@ -3124,6 +3125,9 @@ def test_gke_hub_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 @@ -3644,3 +3648,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 = GkeHubAsyncClient(
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 = GkeHubClient(
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 = GkeHubClient(
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 e32a6f6

Please sign in to comment.