Skip to content
This repository was archived by the owner on Mar 15, 2025. It is now read-only.

Commit c12c571

Browse files
feat: add context manager support in client (#92)
- [ ] 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
1 parent c56eee6 commit c12c571

File tree

8 files changed

+88
-5
lines changed

8 files changed

+88
-5
lines changed

google/cloud/orgpolicy_v2/services/org_policy/async_client.py

+6
Original file line numberDiff line numberDiff line change
@@ -827,6 +827,12 @@ async def delete_policy(
827827
request, retry=retry, timeout=timeout, metadata=metadata,
828828
)
829829

830+
async def __aenter__(self):
831+
return self
832+
833+
async def __aexit__(self, exc_type, exc, tb):
834+
await self.transport.close()
835+
830836

831837
try:
832838
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(

google/cloud/orgpolicy_v2/services/org_policy/client.py

+14-4
Original file line numberDiff line numberDiff line change
@@ -377,10 +377,7 @@ def __init__(
377377
client_cert_source_for_mtls=client_cert_source_func,
378378
quota_project_id=client_options.quota_project_id,
379379
client_info=client_info,
380-
always_use_jwt_access=(
381-
Transport == type(self).get_transport_class("grpc")
382-
or Transport == type(self).get_transport_class("grpc_asyncio")
383-
),
380+
always_use_jwt_access=True,
384381
)
385382

386383
def list_constraints(
@@ -960,6 +957,19 @@ def delete_policy(
960957
request, retry=retry, timeout=timeout, metadata=metadata,
961958
)
962959

960+
def __enter__(self):
961+
return self
962+
963+
def __exit__(self, type, value, traceback):
964+
"""Releases underlying transport's resources.
965+
966+
.. warning::
967+
ONLY use as a context manager if the transport is NOT shared
968+
with other clients! Exiting the with block will CLOSE the transport
969+
and may cause errors in other clients!
970+
"""
971+
self.transport.close()
972+
963973

964974
try:
965975
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(

google/cloud/orgpolicy_v2/services/org_policy/transports/base.py

+9
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,15 @@ def _prep_wrapped_messages(self, client_info):
262262
),
263263
}
264264

265+
def close(self):
266+
"""Closes resources associated with the transport.
267+
268+
.. warning::
269+
Only call this method if the transport is NOT shared
270+
with other clients - this may cause errors in other clients!
271+
"""
272+
raise NotImplementedError()
273+
265274
@property
266275
def list_constraints(
267276
self,

google/cloud/orgpolicy_v2/services/org_policy/transports/grpc.py

+3
Original file line numberDiff line numberDiff line change
@@ -459,5 +459,8 @@ def delete_policy(
459459
)
460460
return self._stubs["delete_policy"]
461461

462+
def close(self):
463+
self.grpc_channel.close()
464+
462465

463466
__all__ = ("OrgPolicyGrpcTransport",)

google/cloud/orgpolicy_v2/services/org_policy/transports/grpc_asyncio.py

+3
Original file line numberDiff line numberDiff line change
@@ -466,5 +466,8 @@ def delete_policy(
466466
)
467467
return self._stubs["delete_policy"]
468468

469+
def close(self):
470+
return self.grpc_channel.close()
471+
469472

470473
__all__ = ("OrgPolicyGrpcAsyncIOTransport",)

google/cloud/orgpolicy_v2/types/constraint.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,8 @@ class BooleanConstraint(proto.Message):
110110
``constraints/compute.disableSerialPortAccess``. If it is enforced
111111
on a VM instance, serial port connections will not be opened to that
112112
instance.
113-
"""
113+
114+
"""
114115

115116
name = proto.Field(proto.STRING, number=1,)
116117
display_name = proto.Field(proto.STRING, number=2,)

google/cloud/orgpolicy_v2/types/orgpolicy.py

+1
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,7 @@ class PolicySpec(proto.Message):
149149

150150
class PolicyRule(proto.Message):
151151
r"""A rule used to express this policy.
152+
152153
Attributes:
153154
values (google.cloud.orgpolicy_v2.types.PolicySpec.PolicyRule.StringValues):
154155
List of values to be used for this

tests/unit/gapic/orgpolicy_v2/test_org_policy.py

+50
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.orgpolicy_v2.services.org_policy import OrgPolicyAsyncClient
@@ -2224,6 +2225,9 @@ def test_org_policy_base_transport():
22242225
with pytest.raises(NotImplementedError):
22252226
getattr(transport, method)(request=object())
22262227

2228+
with pytest.raises(NotImplementedError):
2229+
transport.close()
2230+
22272231

22282232
@requires_google_auth_gte_1_25_0
22292233
def test_org_policy_base_transport_with_credentials_file():
@@ -2709,3 +2713,49 @@ def test_client_withDEFAULT_CLIENT_INFO():
27092713
credentials=ga_credentials.AnonymousCredentials(), client_info=client_info,
27102714
)
27112715
prep.assert_called_once_with(client_info)
2716+
2717+
2718+
@pytest.mark.asyncio
2719+
async def test_transport_close_async():
2720+
client = OrgPolicyAsyncClient(
2721+
credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio",
2722+
)
2723+
with mock.patch.object(
2724+
type(getattr(client.transport, "grpc_channel")), "close"
2725+
) as close:
2726+
async with client:
2727+
close.assert_not_called()
2728+
close.assert_called_once()
2729+
2730+
2731+
def test_transport_close():
2732+
transports = {
2733+
"grpc": "_grpc_channel",
2734+
}
2735+
2736+
for transport, close_name in transports.items():
2737+
client = OrgPolicyClient(
2738+
credentials=ga_credentials.AnonymousCredentials(), transport=transport
2739+
)
2740+
with mock.patch.object(
2741+
type(getattr(client.transport, close_name)), "close"
2742+
) as close:
2743+
with client:
2744+
close.assert_not_called()
2745+
close.assert_called_once()
2746+
2747+
2748+
def test_client_ctx():
2749+
transports = [
2750+
"grpc",
2751+
]
2752+
for transport in transports:
2753+
client = OrgPolicyClient(
2754+
credentials=ga_credentials.AnonymousCredentials(), transport=transport
2755+
)
2756+
# Test client calls underlying transport.
2757+
with mock.patch.object(type(client.transport), "close") as close:
2758+
close.assert_not_called()
2759+
with client:
2760+
pass
2761+
close.assert_called()

0 commit comments

Comments
 (0)