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

feat: add context manager support in client #49

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 @@ -526,6 +526,12 @@ async def batch_get_services(
# 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/service_usage_v1/services/service_usage/client.py
Expand Up @@ -335,10 +335,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 enable_service(
Expand Down Expand Up @@ -709,6 +706,19 @@ def batch_get_services(
# 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 @@ -183,6 +183,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 @@ -434,5 +434,8 @@ def batch_get_services(
)
return self._stubs["batch_get_services"]

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


__all__ = ("ServiceUsageGrpcTransport",)
Expand Up @@ -446,5 +446,8 @@ def batch_get_services(
)
return self._stubs["batch_get_services"]

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


__all__ = ("ServiceUsageGrpcAsyncIOTransport",)
2 changes: 2 additions & 0 deletions google/cloud/service_usage_v1/types/resources.py
Expand Up @@ -42,6 +42,7 @@ class State(proto.Enum):

class Service(proto.Message):
r"""A service that is available for use by the consumer.

Attributes:
name (str):
The resource name of the consumer and
Expand Down Expand Up @@ -71,6 +72,7 @@ class Service(proto.Message):

class ServiceConfig(proto.Message):
r"""The configuration of the service.

Attributes:
name (str):
The DNS address at which this service is available.
Expand Down
1 change: 1 addition & 0 deletions google/cloud/service_usage_v1/types/serviceusage.py
Expand Up @@ -236,6 +236,7 @@ class BatchEnableServicesResponse(proto.Message):

class EnableFailure(proto.Message):
r"""Provides error messages for the failing services.

Attributes:
service_id (str):
The service id of a service that could not be
Expand Down
50 changes: 50 additions & 0 deletions tests/unit/gapic/service_usage_v1/test_service_usage.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.service_usage_v1.services.service_usage import ServiceUsageAsyncClient
Expand Down Expand Up @@ -1547,6 +1548,9 @@ def test_service_usage_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 @@ -2053,3 +2057,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 = ServiceUsageAsyncClient(
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 = ServiceUsageClient(
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 = ServiceUsageClient(
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()