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

Commit

Permalink
feat: add context manager support in client (#38)
Browse files Browse the repository at this point in the history
- [ ] 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
  • Loading branch information
gcf-owl-bot[bot] committed Oct 7, 2021
1 parent 39a3fd7 commit 376873d
Show file tree
Hide file tree
Showing 9 changed files with 100 additions and 4 deletions.
Expand Up @@ -729,6 +729,12 @@ async def delete_connectivity_test(
# 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
Expand Up @@ -362,10 +362,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 list_connectivity_tests(
Expand Down Expand Up @@ -916,6 +913,19 @@ def delete_connectivity_test(
# 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 @@ -189,6 +189,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 @@ -462,5 +462,8 @@ def delete_connectivity_test(
)
return self._stubs["delete_connectivity_test"]

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


__all__ = ("ReachabilityServiceGrpcTransport",)
Expand Up @@ -471,5 +471,8 @@ def delete_connectivity_test(
)
return self._stubs["delete_connectivity_test"]

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


__all__ = ("ReachabilityServiceGrpcAsyncIOTransport",)
2 changes: 2 additions & 0 deletions google/cloud/network_management_v1/types/connectivity_test.py
Expand Up @@ -28,6 +28,7 @@

class ConnectivityTest(proto.Message):
r"""A Connectivity Test for a network reachability analysis.
Attributes:
name (str):
Required. Unique name of the resource using the form:
Expand Down Expand Up @@ -134,6 +135,7 @@ class ConnectivityTest(proto.Message):

class Endpoint(proto.Message):
r"""Source or destination of the Connectivity Test.
Attributes:
ip_address (str):
The IP address of the endpoint, which can be an external or
Expand Down
8 changes: 8 additions & 0 deletions google/cloud/network_management_v1/types/reachability.py
Expand Up @@ -37,6 +37,7 @@

class ListConnectivityTestsRequest(proto.Message):
r"""Request for the ``ListConnectivityTests`` method.
Attributes:
parent (str):
Required. The parent resource of the Connectivity Tests:
Expand Down Expand Up @@ -80,6 +81,7 @@ class ListConnectivityTestsRequest(proto.Message):

class ListConnectivityTestsResponse(proto.Message):
r"""Response for the ``ListConnectivityTests`` method.
Attributes:
resources (Sequence[google.cloud.network_management_v1.types.ConnectivityTest]):
List of Connectivity Tests.
Expand All @@ -104,6 +106,7 @@ def raw_page(self):

class GetConnectivityTestRequest(proto.Message):
r"""Request for the ``GetConnectivityTest`` method.
Attributes:
name (str):
Required. ``ConnectivityTest`` resource name using the form:
Expand All @@ -115,6 +118,7 @@ class GetConnectivityTestRequest(proto.Message):

class CreateConnectivityTestRequest(proto.Message):
r"""Request for the ``CreateConnectivityTest`` method.
Attributes:
parent (str):
Required. The parent resource of the Connectivity Test to
Expand Down Expand Up @@ -142,6 +146,7 @@ class CreateConnectivityTestRequest(proto.Message):

class UpdateConnectivityTestRequest(proto.Message):
r"""Request for the ``UpdateConnectivityTest`` method.
Attributes:
update_mask (google.protobuf.field_mask_pb2.FieldMask):
Required. Mask of fields to update. At least
Expand All @@ -160,6 +165,7 @@ class UpdateConnectivityTestRequest(proto.Message):

class DeleteConnectivityTestRequest(proto.Message):
r"""Request for the ``DeleteConnectivityTest`` method.
Attributes:
name (str):
Required. Connectivity Test resource name using the form:
Expand All @@ -171,6 +177,7 @@ class DeleteConnectivityTestRequest(proto.Message):

class RerunConnectivityTestRequest(proto.Message):
r"""Request for the ``RerunConnectivityTest`` method.
Attributes:
name (str):
Required. Connectivity Test resource name using the form:
Expand All @@ -182,6 +189,7 @@ class RerunConnectivityTestRequest(proto.Message):

class OperationMetadata(proto.Message):
r"""Metadata describing an [Operation][google.longrunning.Operation]
Attributes:
create_time (google.protobuf.timestamp_pb2.Timestamp):
The time the operation was created.
Expand Down
5 changes: 5 additions & 0 deletions google/cloud/network_management_v1/types/trace.py
Expand Up @@ -428,6 +428,7 @@ class ForwardingRuleInfo(proto.Message):

class LoadBalancerInfo(proto.Message):
r"""For display only. Metadata associated with a load balancer.
Attributes:
load_balancer_type (google.cloud.network_management_v1.types.LoadBalancerInfo.LoadBalancerType):
Type of the load balancer.
Expand Down Expand Up @@ -626,6 +627,7 @@ class EndpointInfo(proto.Message):

class DeliverInfo(proto.Message):
r"""Details of the final state "deliver" and associated resource.
Attributes:
target (google.cloud.network_management_v1.types.DeliverInfo.Target):
Target type where the packet is delivered to.
Expand All @@ -649,6 +651,7 @@ class Target(proto.Enum):

class ForwardInfo(proto.Message):
r"""Details of the final state "forward" and associated resource.
Attributes:
target (google.cloud.network_management_v1.types.ForwardInfo.Target):
Target type where this packet is forwarded
Expand All @@ -674,6 +677,7 @@ class Target(proto.Enum):

class AbortInfo(proto.Message):
r"""Details of the final state "abort" and associated resource.
Attributes:
cause (google.cloud.network_management_v1.types.AbortInfo.Cause):
Causes that the analysis is aborted.
Expand Down Expand Up @@ -705,6 +709,7 @@ class Cause(proto.Enum):

class DropInfo(proto.Message):
r"""Details of the final state "drop" and associated resource.
Attributes:
cause (google.cloud.network_management_v1.types.DropInfo.Cause):
Cause that the packet is dropped.
Expand Down
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.network_management_v1.services.reachability_service import (
Expand Down Expand Up @@ -2130,6 +2131,9 @@ def test_reachability_service_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 @@ -2643,3 +2647,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 = ReachabilityServiceAsyncClient(
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 = ReachabilityServiceClient(
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 = ReachabilityServiceClient(
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()

0 comments on commit 376873d

Please sign in to comment.