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

Commit 070897f

Browse files
feat: add context manager support in client (#125)
- [ ] 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 d5eead8 commit 070897f

File tree

7 files changed

+93
-4
lines changed

7 files changed

+93
-4
lines changed

google/cloud/iam_credentials_v1/services/iam_credentials/async_client.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -659,6 +659,12 @@ async def sign_jwt(
659659
# Done; return the response.
660660
return response
661661

662+
async def __aenter__(self):
663+
return self
664+
665+
async def __aexit__(self, exc_type, exc, tb):
666+
await self.transport.close()
667+
662668

663669
try:
664670
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(

google/cloud/iam_credentials_v1/services/iam_credentials/client.py

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -355,10 +355,7 @@ def __init__(
355355
client_cert_source_for_mtls=client_cert_source_func,
356356
quota_project_id=client_options.quota_project_id,
357357
client_info=client_info,
358-
always_use_jwt_access=(
359-
Transport == type(self).get_transport_class("grpc")
360-
or Transport == type(self).get_transport_class("grpc_asyncio")
361-
),
358+
always_use_jwt_access=True,
362359
)
363360

364361
def generate_access_token(
@@ -806,6 +803,19 @@ def sign_jwt(
806803
# Done; return the response.
807804
return response
808805

806+
def __enter__(self):
807+
return self
808+
809+
def __exit__(self, type, value, traceback):
810+
"""Releases underlying transport's resources.
811+
812+
.. warning::
813+
ONLY use as a context manager if the transport is NOT shared
814+
with other clients! Exiting the with block will CLOSE the transport
815+
and may cause errors in other clients!
816+
"""
817+
self.transport.close()
818+
809819

810820
try:
811821
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(

google/cloud/iam_credentials_v1/services/iam_credentials/transports/base.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,15 @@ def _prep_wrapped_messages(self, client_info):
214214
),
215215
}
216216

217+
def close(self):
218+
"""Closes resources associated with the transport.
219+
220+
.. warning::
221+
Only call this method if the transport is NOT shared
222+
with other clients - this may cause errors in other clients!
223+
"""
224+
raise NotImplementedError()
225+
217226
@property
218227
def generate_access_token(
219228
self,

google/cloud/iam_credentials_v1/services/iam_credentials/transports/grpc.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -340,5 +340,8 @@ def sign_jwt(self) -> Callable[[common.SignJwtRequest], common.SignJwtResponse]:
340340
)
341341
return self._stubs["sign_jwt"]
342342

343+
def close(self):
344+
self.grpc_channel.close()
345+
343346

344347
__all__ = ("IAMCredentialsGrpcTransport",)

google/cloud/iam_credentials_v1/services/iam_credentials/transports/grpc_asyncio.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -350,5 +350,8 @@ def sign_jwt(
350350
)
351351
return self._stubs["sign_jwt"]
352352

353+
def close(self):
354+
return self.grpc_channel.close()
355+
353356

354357
__all__ = ("IAMCredentialsGrpcAsyncIOTransport",)

google/cloud/iam_credentials_v1/types/common.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636

3737
class GenerateAccessTokenRequest(proto.Message):
3838
r"""
39+
3940
Attributes:
4041
name (str):
4142
Required. The resource name of the service account for which
@@ -79,6 +80,7 @@ class GenerateAccessTokenRequest(proto.Message):
7980

8081
class GenerateAccessTokenResponse(proto.Message):
8182
r"""
83+
8284
Attributes:
8385
access_token (str):
8486
The OAuth 2.0 access token.
@@ -93,6 +95,7 @@ class GenerateAccessTokenResponse(proto.Message):
9395

9496
class SignBlobRequest(proto.Message):
9597
r"""
98+
9699
Attributes:
97100
name (str):
98101
Required. The resource name of the service account for which
@@ -125,6 +128,7 @@ class SignBlobRequest(proto.Message):
125128

126129
class SignBlobResponse(proto.Message):
127130
r"""
131+
128132
Attributes:
129133
key_id (str):
130134
The ID of the key used to sign the blob.
@@ -138,6 +142,7 @@ class SignBlobResponse(proto.Message):
138142

139143
class SignJwtRequest(proto.Message):
140144
r"""
145+
141146
Attributes:
142147
name (str):
143148
Required. The resource name of the service account for which
@@ -171,6 +176,7 @@ class SignJwtRequest(proto.Message):
171176

172177
class SignJwtResponse(proto.Message):
173178
r"""
179+
174180
Attributes:
175181
key_id (str):
176182
The ID of the key used to sign the JWT.
@@ -184,6 +190,7 @@ class SignJwtResponse(proto.Message):
184190

185191
class GenerateIdTokenRequest(proto.Message):
186192
r"""
193+
187194
Attributes:
188195
name (str):
189196
Required. The resource name of the service account for which
@@ -223,6 +230,7 @@ class GenerateIdTokenRequest(proto.Message):
223230

224231
class GenerateIdTokenResponse(proto.Message):
225232
r"""
233+
226234
Attributes:
227235
token (str):
228236
The OpenId Connect ID token.

tests/unit/gapic/credentials_v1/test_iam_credentials.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
from google.api_core import gapic_v1
3030
from google.api_core import grpc_helpers
3131
from google.api_core import grpc_helpers_async
32+
from google.api_core import path_template
3233
from google.auth import credentials as ga_credentials
3334
from google.auth.exceptions import MutualTLSChannelError
3435
from google.cloud.iam_credentials_v1.services.iam_credentials import (
@@ -1531,6 +1532,9 @@ def test_iam_credentials_base_transport():
15311532
with pytest.raises(NotImplementedError):
15321533
getattr(transport, method)(request=object())
15331534

1535+
with pytest.raises(NotImplementedError):
1536+
transport.close()
1537+
15341538

15351539
@requires_google_auth_gte_1_25_0
15361540
def test_iam_credentials_base_transport_with_credentials_file():
@@ -2011,3 +2015,49 @@ def test_client_withDEFAULT_CLIENT_INFO():
20112015
credentials=ga_credentials.AnonymousCredentials(), client_info=client_info,
20122016
)
20132017
prep.assert_called_once_with(client_info)
2018+
2019+
2020+
@pytest.mark.asyncio
2021+
async def test_transport_close_async():
2022+
client = IAMCredentialsAsyncClient(
2023+
credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio",
2024+
)
2025+
with mock.patch.object(
2026+
type(getattr(client.transport, "grpc_channel")), "close"
2027+
) as close:
2028+
async with client:
2029+
close.assert_not_called()
2030+
close.assert_called_once()
2031+
2032+
2033+
def test_transport_close():
2034+
transports = {
2035+
"grpc": "_grpc_channel",
2036+
}
2037+
2038+
for transport, close_name in transports.items():
2039+
client = IAMCredentialsClient(
2040+
credentials=ga_credentials.AnonymousCredentials(), transport=transport
2041+
)
2042+
with mock.patch.object(
2043+
type(getattr(client.transport, close_name)), "close"
2044+
) as close:
2045+
with client:
2046+
close.assert_not_called()
2047+
close.assert_called_once()
2048+
2049+
2050+
def test_client_ctx():
2051+
transports = [
2052+
"grpc",
2053+
]
2054+
for transport in transports:
2055+
client = IAMCredentialsClient(
2056+
credentials=ga_credentials.AnonymousCredentials(), transport=transport
2057+
)
2058+
# Test client calls underlying transport.
2059+
with mock.patch.object(type(client.transport), "close") as close:
2060+
close.assert_not_called()
2061+
with client:
2062+
pass
2063+
close.assert_called()

0 commit comments

Comments
 (0)