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

feat: add context manager support in client #51

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -514,6 +514,12 @@ async def delete_connector(
# 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
18 changes: 14 additions & 4 deletions google/cloud/vpcaccess_v1/services/vpc_access_service/client.py
Expand Up @@ -350,10 +350,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 create_connector(
Expand Down Expand Up @@ -703,6 +700,19 @@ def delete_connector(
# 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 @@ -170,6 +170,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 @@ -353,5 +353,8 @@ def delete_connector(
)
return self._stubs["delete_connector"]

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


__all__ = ("VpcAccessServiceGrpcTransport",)
Expand Up @@ -362,5 +362,8 @@ def delete_connector(
)
return self._stubs["delete_connector"]

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


__all__ = ("VpcAccessServiceGrpcAsyncIOTransport",)
7 changes: 7 additions & 0 deletions google/cloud/vpcaccess_v1/types/vpc_access.py
Expand Up @@ -34,6 +34,7 @@

class Connector(proto.Message):
r"""Definition of a Serverless VPC Access connector.

Attributes:
name (str):
The resource name in the format
Expand Down Expand Up @@ -71,6 +72,7 @@ class State(proto.Enum):

class Subnet(proto.Message):
r"""The subnet in which to house the connector

Attributes:
name (str):
Subnet name (relative, not fully qualified).
Expand Down Expand Up @@ -100,6 +102,7 @@ class Subnet(proto.Message):

class CreateConnectorRequest(proto.Message):
r"""Request for creating a Serverless VPC Access connector.

Attributes:
parent (str):
Required. The project and location in which the
Expand All @@ -118,6 +121,7 @@ class CreateConnectorRequest(proto.Message):

class GetConnectorRequest(proto.Message):
r"""Request for getting a Serverless VPC Access connector.

Attributes:
name (str):
Required. Name of a Serverless VPC Access
Expand Down Expand Up @@ -149,6 +153,7 @@ class ListConnectorsRequest(proto.Message):

class ListConnectorsResponse(proto.Message):
r"""Response for listing Serverless VPC Access connectors.

Attributes:
connectors (Sequence[google.cloud.vpcaccess_v1.types.Connector]):
List of Serverless VPC Access connectors.
Expand All @@ -166,6 +171,7 @@ def raw_page(self):

class DeleteConnectorRequest(proto.Message):
r"""Request for deleting a Serverless VPC Access connector.

Attributes:
name (str):
Required. Name of a Serverless VPC Access
Expand All @@ -177,6 +183,7 @@ class DeleteConnectorRequest(proto.Message):

class OperationMetadata(proto.Message):
r"""Metadata for google.longrunning.Operation.

Attributes:
method (str):
Output only. Method that initiated the
Expand Down
50 changes: 50 additions & 0 deletions tests/unit/gapic/vpcaccess_v1/test_vpc_access_service.py
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.vpcaccess_v1.services.vpc_access_service import (
Expand Down Expand Up @@ -1611,6 +1612,9 @@ def test_vpc_access_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 @@ -2124,3 +2128,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 = VpcAccessServiceAsyncClient(
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 = VpcAccessServiceClient(
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 = VpcAccessServiceClient(
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()