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

Commit b50e7cb

Browse files
feat: add context manager support in client (#49)
- [ ] 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: https://github.com/googleapis/googleapis-gen/commit/81decffe9fc72396a8153e756d1d67a6eecfd620 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiODFkZWNmZmU5ZmM3MjM5NmE4MTUzZTc1NmQxZDY3YTZlZWNmZDYyMCJ9
1 parent 29742ce commit b50e7cb

File tree

8 files changed

+88
-4
lines changed

8 files changed

+88
-4
lines changed

google/cloud/service_usage_v1/services/service_usage/async_client.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -526,6 +526,12 @@ async def batch_get_services(
526526
# Done; return the response.
527527
return response
528528

529+
async def __aenter__(self):
530+
return self
531+
532+
async def __aexit__(self, exc_type, exc, tb):
533+
await self.transport.close()
534+
529535

530536
try:
531537
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(

google/cloud/service_usage_v1/services/service_usage/client.py

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -335,10 +335,7 @@ def __init__(
335335
client_cert_source_for_mtls=client_cert_source_func,
336336
quota_project_id=client_options.quota_project_id,
337337
client_info=client_info,
338-
always_use_jwt_access=(
339-
Transport == type(self).get_transport_class("grpc")
340-
or Transport == type(self).get_transport_class("grpc_asyncio")
341-
),
338+
always_use_jwt_access=True,
342339
)
343340

344341
def enable_service(
@@ -709,6 +706,19 @@ def batch_get_services(
709706
# Done; return the response.
710707
return response
711708

709+
def __enter__(self):
710+
return self
711+
712+
def __exit__(self, type, value, traceback):
713+
"""Releases underlying transport's resources.
714+
715+
.. warning::
716+
ONLY use as a context manager if the transport is NOT shared
717+
with other clients! Exiting the with block will CLOSE the transport
718+
and may cause errors in other clients!
719+
"""
720+
self.transport.close()
721+
712722

713723
try:
714724
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(

google/cloud/service_usage_v1/services/service_usage/transports/base.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,15 @@ def _prep_wrapped_messages(self, client_info):
183183
),
184184
}
185185

186+
def close(self):
187+
"""Closes resources associated with the transport.
188+
189+
.. warning::
190+
Only call this method if the transport is NOT shared
191+
with other clients - this may cause errors in other clients!
192+
"""
193+
raise NotImplementedError()
194+
186195
@property
187196
def operations_client(self) -> operations_v1.OperationsClient:
188197
"""Return the client designed to process long-running operations."""

google/cloud/service_usage_v1/services/service_usage/transports/grpc.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -434,5 +434,8 @@ def batch_get_services(
434434
)
435435
return self._stubs["batch_get_services"]
436436

437+
def close(self):
438+
self.grpc_channel.close()
439+
437440

438441
__all__ = ("ServiceUsageGrpcTransport",)

google/cloud/service_usage_v1/services/service_usage/transports/grpc_asyncio.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -446,5 +446,8 @@ def batch_get_services(
446446
)
447447
return self._stubs["batch_get_services"]
448448

449+
def close(self):
450+
return self.grpc_channel.close()
451+
449452

450453
__all__ = ("ServiceUsageGrpcAsyncIOTransport",)

google/cloud/service_usage_v1/types/resources.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ class State(proto.Enum):
4242

4343
class Service(proto.Message):
4444
r"""A service that is available for use by the consumer.
45+
4546
Attributes:
4647
name (str):
4748
The resource name of the consumer and
@@ -71,6 +72,7 @@ class Service(proto.Message):
7172

7273
class ServiceConfig(proto.Message):
7374
r"""The configuration of the service.
75+
7476
Attributes:
7577
name (str):
7678
The DNS address at which this service is available.

google/cloud/service_usage_v1/types/serviceusage.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,7 @@ class BatchEnableServicesResponse(proto.Message):
236236

237237
class EnableFailure(proto.Message):
238238
r"""Provides error messages for the failing services.
239+
239240
Attributes:
240241
service_id (str):
241242
The service id of a service that could not be

tests/unit/gapic/service_usage_v1/test_service_usage.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
from google.api_core import grpc_helpers_async
3333
from google.api_core import operation_async # type: ignore
3434
from google.api_core import operations_v1
35+
from google.api_core import path_template
3536
from google.auth import credentials as ga_credentials
3637
from google.auth.exceptions import MutualTLSChannelError
3738
from google.cloud.service_usage_v1.services.service_usage import ServiceUsageAsyncClient
@@ -1547,6 +1548,9 @@ def test_service_usage_base_transport():
15471548
with pytest.raises(NotImplementedError):
15481549
getattr(transport, method)(request=object())
15491550

1551+
with pytest.raises(NotImplementedError):
1552+
transport.close()
1553+
15501554
# Additionally, the LRO client (a property) should
15511555
# also raise NotImplementedError
15521556
with pytest.raises(NotImplementedError):
@@ -2053,3 +2057,49 @@ def test_client_withDEFAULT_CLIENT_INFO():
20532057
credentials=ga_credentials.AnonymousCredentials(), client_info=client_info,
20542058
)
20552059
prep.assert_called_once_with(client_info)
2060+
2061+
2062+
@pytest.mark.asyncio
2063+
async def test_transport_close_async():
2064+
client = ServiceUsageAsyncClient(
2065+
credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio",
2066+
)
2067+
with mock.patch.object(
2068+
type(getattr(client.transport, "grpc_channel")), "close"
2069+
) as close:
2070+
async with client:
2071+
close.assert_not_called()
2072+
close.assert_called_once()
2073+
2074+
2075+
def test_transport_close():
2076+
transports = {
2077+
"grpc": "_grpc_channel",
2078+
}
2079+
2080+
for transport, close_name in transports.items():
2081+
client = ServiceUsageClient(
2082+
credentials=ga_credentials.AnonymousCredentials(), transport=transport
2083+
)
2084+
with mock.patch.object(
2085+
type(getattr(client.transport, close_name)), "close"
2086+
) as close:
2087+
with client:
2088+
close.assert_not_called()
2089+
close.assert_called_once()
2090+
2091+
2092+
def test_client_ctx():
2093+
transports = [
2094+
"grpc",
2095+
]
2096+
for transport in transports:
2097+
client = ServiceUsageClient(
2098+
credentials=ga_credentials.AnonymousCredentials(), transport=transport
2099+
)
2100+
# Test client calls underlying transport.
2101+
with mock.patch.object(type(client.transport), "close") as close:
2102+
close.assert_not_called()
2103+
with client:
2104+
pass
2105+
close.assert_called()

0 commit comments

Comments
 (0)