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

Commit 9cad312

Browse files
feat: add context manager support in client (#78)
- [ ] 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 3af2382 commit 9cad312

File tree

8 files changed

+87
-4
lines changed

8 files changed

+87
-4
lines changed

google/cloud/managedidentities_v1/services/managed_identities_service/async_client.py

+6
Original file line numberDiff line numberDiff line change
@@ -1119,6 +1119,12 @@ async def validate_trust(
11191119
# Done; return the response.
11201120
return response
11211121

1122+
async def __aenter__(self):
1123+
return self
1124+
1125+
async def __aexit__(self, exc_type, exc, tb):
1126+
await self.transport.close()
1127+
11221128

11231129
try:
11241130
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(

google/cloud/managedidentities_v1/services/managed_identities_service/client.py

+14-4
Original file line numberDiff line numberDiff line change
@@ -387,10 +387,7 @@ def __init__(
387387
client_cert_source_for_mtls=client_cert_source_func,
388388
quota_project_id=client_options.quota_project_id,
389389
client_info=client_info,
390-
always_use_jwt_access=(
391-
Transport == type(self).get_transport_class("grpc")
392-
or Transport == type(self).get_transport_class("grpc_asyncio")
393-
),
390+
always_use_jwt_access=True,
394391
)
395392

396393
def create_microsoft_ad_domain(
@@ -1315,6 +1312,19 @@ def validate_trust(
13151312
# Done; return the response.
13161313
return response
13171314

1315+
def __enter__(self):
1316+
return self
1317+
1318+
def __exit__(self, type, value, traceback):
1319+
"""Releases underlying transport's resources.
1320+
1321+
.. warning::
1322+
ONLY use as a context manager if the transport is NOT shared
1323+
with other clients! Exiting the with block will CLOSE the transport
1324+
and may cause errors in other clients!
1325+
"""
1326+
self.transport.close()
1327+
13181328

13191329
try:
13201330
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(

google/cloud/managedidentities_v1/services/managed_identities_service/transports/base.py

+9
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,15 @@ def _prep_wrapped_messages(self, client_info):
193193
),
194194
}
195195

196+
def close(self):
197+
"""Closes resources associated with the transport.
198+
199+
.. warning::
200+
Only call this method if the transport is NOT shared
201+
with other clients - this may cause errors in other clients!
202+
"""
203+
raise NotImplementedError()
204+
196205
@property
197206
def operations_client(self) -> operations_v1.OperationsClient:
198207
"""Return the client designed to process long-running operations."""

google/cloud/managedidentities_v1/services/managed_identities_service/transports/grpc.py

+3
Original file line numberDiff line numberDiff line change
@@ -560,5 +560,8 @@ def validate_trust(
560560
)
561561
return self._stubs["validate_trust"]
562562

563+
def close(self):
564+
self.grpc_channel.close()
565+
563566

564567
__all__ = ("ManagedIdentitiesServiceGrpcTransport",)

google/cloud/managedidentities_v1/services/managed_identities_service/transports/grpc_asyncio.py

+3
Original file line numberDiff line numberDiff line change
@@ -573,5 +573,8 @@ def validate_trust(
573573
)
574574
return self._stubs["validate_trust"]
575575

576+
def close(self):
577+
return self.grpc_channel.close()
578+
576579

577580
__all__ = ("ManagedIdentitiesServiceGrpcAsyncIOTransport",)

google/cloud/managedidentities_v1/types/managed_identities_service.py

+1
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@
4242

4343
class OpMetadata(proto.Message):
4444
r"""Represents the metadata of the long-running operation.
45+
4546
Attributes:
4647
create_time (google.protobuf.timestamp_pb2.Timestamp):
4748
Output only. The time the operation was

google/cloud/managedidentities_v1/types/resource.py

+1
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525

2626
class Domain(proto.Message):
2727
r"""Represents a managed Microsoft Active Directory domain.
28+
2829
Attributes:
2930
name (str):
3031
Required. The unique name of the domain using the form:

tests/unit/gapic/managedidentities_v1/test_managed_identities_service.py

+50
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.managedidentities_v1.services.managed_identities_service import (
@@ -3047,6 +3048,9 @@ def test_managed_identities_service_base_transport():
30473048
with pytest.raises(NotImplementedError):
30483049
getattr(transport, method)(request=object())
30493050

3051+
with pytest.raises(NotImplementedError):
3052+
transport.close()
3053+
30503054
# Additionally, the LRO client (a property) should
30513055
# also raise NotImplementedError
30523056
with pytest.raises(NotImplementedError):
@@ -3564,3 +3568,49 @@ def test_client_withDEFAULT_CLIENT_INFO():
35643568
credentials=ga_credentials.AnonymousCredentials(), client_info=client_info,
35653569
)
35663570
prep.assert_called_once_with(client_info)
3571+
3572+
3573+
@pytest.mark.asyncio
3574+
async def test_transport_close_async():
3575+
client = ManagedIdentitiesServiceAsyncClient(
3576+
credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio",
3577+
)
3578+
with mock.patch.object(
3579+
type(getattr(client.transport, "grpc_channel")), "close"
3580+
) as close:
3581+
async with client:
3582+
close.assert_not_called()
3583+
close.assert_called_once()
3584+
3585+
3586+
def test_transport_close():
3587+
transports = {
3588+
"grpc": "_grpc_channel",
3589+
}
3590+
3591+
for transport, close_name in transports.items():
3592+
client = ManagedIdentitiesServiceClient(
3593+
credentials=ga_credentials.AnonymousCredentials(), transport=transport
3594+
)
3595+
with mock.patch.object(
3596+
type(getattr(client.transport, close_name)), "close"
3597+
) as close:
3598+
with client:
3599+
close.assert_not_called()
3600+
close.assert_called_once()
3601+
3602+
3603+
def test_client_ctx():
3604+
transports = [
3605+
"grpc",
3606+
]
3607+
for transport in transports:
3608+
client = ManagedIdentitiesServiceClient(
3609+
credentials=ga_credentials.AnonymousCredentials(), transport=transport
3610+
)
3611+
# Test client calls underlying transport.
3612+
with mock.patch.object(type(client.transport), "close") as close:
3613+
close.assert_not_called()
3614+
with client:
3615+
pass
3616+
close.assert_called()

0 commit comments

Comments
 (0)