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 (#54)
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 8, 2021
1 parent a6fb757 commit 0dc1edd
Show file tree
Hide file tree
Showing 14 changed files with 181 additions and 8 deletions.
Expand Up @@ -253,6 +253,12 @@ async def list_connections(
# 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 @@ -345,10 +345,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_connections(
Expand Down Expand Up @@ -432,6 +429,19 @@ def list_connections(
# 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 list_connections(
self,
Expand Down
Expand Up @@ -255,5 +255,8 @@ def list_connections(
)
return self._stubs["list_connections"]

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


__all__ = ("ConnectionServiceGrpcTransport",)
Expand Up @@ -259,5 +259,8 @@ def list_connections(
)
return self._stubs["list_connections"]

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


__all__ = ("ConnectionServiceGrpcAsyncIOTransport",)
6 changes: 6 additions & 0 deletions google/cloud/apigeeconnect_v1/services/tether/async_client.py
Expand Up @@ -208,6 +208,12 @@ def egress(
# 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/apigeeconnect_v1/services/tether/client.py
Expand Up @@ -330,10 +330,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 egress(
Expand Down Expand Up @@ -378,6 +375,19 @@ def egress(
# 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 @@ -159,6 +159,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 egress(
self,
Expand Down
Expand Up @@ -260,5 +260,8 @@ def egress(self) -> Callable[[tether.EgressResponse], tether.EgressRequest]:
)
return self._stubs["egress"]

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


__all__ = ("TetherGrpcTransport",)
Expand Up @@ -265,5 +265,8 @@ def egress(
)
return self._stubs["egress"]

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


__all__ = ("TetherGrpcAsyncIOTransport",)
4 changes: 4 additions & 0 deletions google/cloud/apigeeconnect_v1/types/connection.py
Expand Up @@ -29,6 +29,7 @@

class ListConnectionsRequest(proto.Message):
r"""The request for [ListConnections][Management.ListConnections].
Attributes:
parent (str):
Required. Parent name of the form:
Expand All @@ -55,6 +56,7 @@ class ListConnectionsRequest(proto.Message):

class ListConnectionsResponse(proto.Message):
r"""The response for [ListConnections][Management.ListConnections].
Attributes:
connections (Sequence[google.cloud.apigeeconnect_v1.types.Connection]):
A list of clients.
Expand All @@ -74,6 +76,7 @@ def raw_page(self):

class Connection(proto.Message):
r"""
Attributes:
endpoint (str):
The endpoint that the connection is made against. Format:
Expand All @@ -91,6 +94,7 @@ class Connection(proto.Message):

class Cluster(proto.Message):
r"""
Attributes:
name (str):
The name of the cluster.
Expand Down
7 changes: 7 additions & 0 deletions google/cloud/apigeeconnect_v1/types/tether.py
Expand Up @@ -59,6 +59,7 @@ class Scheme(proto.Enum):

class EgressRequest(proto.Message):
r"""gRPC request payload for tether.
Attributes:
id (str):
Unique identifier for the request.
Expand All @@ -85,6 +86,7 @@ class EgressRequest(proto.Message):

class Payload(proto.Message):
r"""Payload for EgressRequest.
Attributes:
http_request (google.cloud.apigeeconnect_v1.types.HttpRequest):
The HttpRequest proto.
Expand All @@ -105,6 +107,7 @@ class Payload(proto.Message):

class StreamInfo(proto.Message):
r"""The Information of bi-directional stream.
Attributes:
id (str):
Unique identifier for the stream.
Expand All @@ -115,6 +118,7 @@ class StreamInfo(proto.Message):

class EgressResponse(proto.Message):
r"""gRPC response payload for tether.
Attributes:
id (str):
Unique identifier for the response. Matches
Expand Down Expand Up @@ -148,6 +152,7 @@ class EgressResponse(proto.Message):

class HttpRequest(proto.Message):
r"""The proto definition of http request.
Attributes:
id (str):
A unique identifier for the request.
Expand Down Expand Up @@ -192,6 +197,7 @@ class Url(proto.Message):

class Header(proto.Message):
r"""The http headers.
Attributes:
key (str):
Expand All @@ -205,6 +211,7 @@ class Header(proto.Message):

class HttpResponse(proto.Message):
r"""The proto definition of http response.
Attributes:
id (str):
A unique identifier that matches the request
Expand Down
50 changes: 50 additions & 0 deletions tests/unit/gapic/apigeeconnect_v1/test_connection_service.py
Expand Up @@ -29,6 +29,7 @@
from google.api_core import gapic_v1
from google.api_core import grpc_helpers
from google.api_core import grpc_helpers_async
from google.api_core import path_template
from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
from google.cloud.apigeeconnect_v1.services.connection_service import (
Expand Down Expand Up @@ -956,6 +957,9 @@ def test_connection_service_base_transport():
with pytest.raises(NotImplementedError):
getattr(transport, method)(request=object())

with pytest.raises(NotImplementedError):
transport.close()


@requires_google_auth_gte_1_25_0
def test_connection_service_base_transport_with_credentials_file():
Expand Down Expand Up @@ -1436,3 +1440,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 = ConnectionServiceAsyncClient(
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 = ConnectionServiceClient(
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 = ConnectionServiceClient(
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()
50 changes: 50 additions & 0 deletions tests/unit/gapic/apigeeconnect_v1/test_tether.py
Expand Up @@ -29,6 +29,7 @@
from google.api_core import gapic_v1
from google.api_core import grpc_helpers
from google.api_core import grpc_helpers_async
from google.api_core import path_template
from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
from google.cloud.apigeeconnect_v1.services.tether import TetherAsyncClient
Expand Down Expand Up @@ -623,6 +624,9 @@ def test_tether_base_transport():
with pytest.raises(NotImplementedError):
getattr(transport, method)(request=object())

with pytest.raises(NotImplementedError):
transport.close()


@requires_google_auth_gte_1_25_0
def test_tether_base_transport_with_credentials_file():
Expand Down Expand Up @@ -1064,3 +1068,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 = TetherAsyncClient(
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 = TetherClient(
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 = TetherClient(
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 0dc1edd

Please sign in to comment.