From 59e20cc0a95b89dfd78ab8d28b7cedf25c39daed Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Fri, 8 Oct 2021 14:16:23 +0000 Subject: [PATCH] feat: add context manager support in client (#71) - [ ] Regenerate this pull request now. chore: fix docstring for first attribute of protos committer: @busunkim96 PiperOrigin-RevId: 401271153 Source-Link: https://github.com/googleapis/googleapis/commit/787f8c9a731f44e74a90b9847d48659ca9462d10 Source-Link: https://github.com/googleapis/googleapis-gen/commit/81decffe9fc72396a8153e756d1d67a6eecfd620 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiODFkZWNmZmU5ZmM3MjM5NmE4MTUzZTc1NmQxZDY3YTZlZWNmZDYyMCJ9 --- .../services/domains/async_client.py | 6 +++ .../services/domains/client.py | 18 +++++-- .../services/domains/transports/base.py | 9 ++++ .../services/domains/transports/grpc.py | 3 ++ .../domains/transports/grpc_asyncio.py | 3 ++ .../cloud/domains_v1beta1/types/domains.py | 20 ++++++++ .../gapic/domains_v1beta1/test_domains.py | 50 +++++++++++++++++++ 7 files changed, 105 insertions(+), 4 deletions(-) diff --git a/packages/google-cloud-domains/google/cloud/domains_v1beta1/services/domains/async_client.py b/packages/google-cloud-domains/google/cloud/domains_v1beta1/services/domains/async_client.py index c92d17794a48..05b829c573ea 100644 --- a/packages/google-cloud-domains/google/cloud/domains_v1beta1/services/domains/async_client.py +++ b/packages/google-cloud-domains/google/cloud/domains_v1beta1/services/domains/async_client.py @@ -1416,6 +1416,12 @@ async def reset_authorization_code( # 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( diff --git a/packages/google-cloud-domains/google/cloud/domains_v1beta1/services/domains/client.py b/packages/google-cloud-domains/google/cloud/domains_v1beta1/services/domains/client.py index 02823ea9815e..dc9516b9becd 100644 --- a/packages/google-cloud-domains/google/cloud/domains_v1beta1/services/domains/client.py +++ b/packages/google-cloud-domains/google/cloud/domains_v1beta1/services/domains/client.py @@ -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 search_domains( @@ -1619,6 +1616,19 @@ def reset_authorization_code( # 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( diff --git a/packages/google-cloud-domains/google/cloud/domains_v1beta1/services/domains/transports/base.py b/packages/google-cloud-domains/google/cloud/domains_v1beta1/services/domains/transports/base.py index 5a92605c7c71..561c774e505f 100644 --- a/packages/google-cloud-domains/google/cloud/domains_v1beta1/services/domains/transports/base.py +++ b/packages/google-cloud-domains/google/cloud/domains_v1beta1/services/domains/transports/base.py @@ -207,6 +207,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.""" diff --git a/packages/google-cloud-domains/google/cloud/domains_v1beta1/services/domains/transports/grpc.py b/packages/google-cloud-domains/google/cloud/domains_v1beta1/services/domains/transports/grpc.py index 43e7dbfe8d73..2e52c37e5cdd 100644 --- a/packages/google-cloud-domains/google/cloud/domains_v1beta1/services/domains/transports/grpc.py +++ b/packages/google-cloud-domains/google/cloud/domains_v1beta1/services/domains/transports/grpc.py @@ -648,5 +648,8 @@ def reset_authorization_code( ) return self._stubs["reset_authorization_code"] + def close(self): + self.grpc_channel.close() + __all__ = ("DomainsGrpcTransport",) diff --git a/packages/google-cloud-domains/google/cloud/domains_v1beta1/services/domains/transports/grpc_asyncio.py b/packages/google-cloud-domains/google/cloud/domains_v1beta1/services/domains/transports/grpc_asyncio.py index a420fda0b614..097612baecc1 100644 --- a/packages/google-cloud-domains/google/cloud/domains_v1beta1/services/domains/transports/grpc_asyncio.py +++ b/packages/google-cloud-domains/google/cloud/domains_v1beta1/services/domains/transports/grpc_asyncio.py @@ -668,5 +668,8 @@ def reset_authorization_code( ) return self._stubs["reset_authorization_code"] + def close(self): + return self.grpc_channel.close() + __all__ = ("DomainsGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-domains/google/cloud/domains_v1beta1/types/domains.py b/packages/google-cloud-domains/google/cloud/domains_v1beta1/types/domains.py index f18a31bcb825..6f71d5eb2785 100644 --- a/packages/google-cloud-domains/google/cloud/domains_v1beta1/types/domains.py +++ b/packages/google-cloud-domains/google/cloud/domains_v1beta1/types/domains.py @@ -235,6 +235,7 @@ class DsState(proto.Enum): class CustomDns(proto.Message): r"""Configuration for an arbitrary DNS provider. + Attributes: name_servers (Sequence[str]): Required. A list of name servers that store @@ -407,6 +408,7 @@ class ContactSettings(proto.Message): class Contact(proto.Message): r"""Details required for a contact associated with a ``Registration``. + Attributes: postal_address (google.type.postal_address_pb2.PostalAddress): Required. Postal address of the contact. @@ -435,6 +437,7 @@ class Contact(proto.Message): class SearchDomainsRequest(proto.Message): r"""Request for the ``SearchDomains`` method. + Attributes: query (str): Required. String used to search for available @@ -450,6 +453,7 @@ class SearchDomainsRequest(proto.Message): class SearchDomainsResponse(proto.Message): r"""Response for the ``SearchDomains`` method. + Attributes: register_parameters (Sequence[google.cloud.domains_v1beta1.types.RegisterParameters]): Results of the domain name search. @@ -462,6 +466,7 @@ class SearchDomainsResponse(proto.Message): class RetrieveRegisterParametersRequest(proto.Message): r"""Request for the ``RetrieveRegisterParameters`` method. + Attributes: domain_name (str): Required. The domain name. Unicode domain @@ -477,6 +482,7 @@ class RetrieveRegisterParametersRequest(proto.Message): class RetrieveRegisterParametersResponse(proto.Message): r"""Response for the ``RetrieveRegisterParameters`` method. + Attributes: register_parameters (google.cloud.domains_v1beta1.types.RegisterParameters): Parameters to use when calling the ``RegisterDomain`` @@ -490,6 +496,7 @@ class RetrieveRegisterParametersResponse(proto.Message): class RegisterDomainRequest(proto.Message): r"""Request for the ``RegisterDomain`` method. + Attributes: parent (str): Required. The parent resource of the ``Registration``. Must @@ -526,6 +533,7 @@ class RegisterDomainRequest(proto.Message): class ListRegistrationsRequest(proto.Message): r"""Request for the ``ListRegistrations`` method. + Attributes: parent (str): Required. The project and location from which to list @@ -567,6 +575,7 @@ class ListRegistrationsRequest(proto.Message): class ListRegistrationsResponse(proto.Message): r"""Response for the ``ListRegistrations`` method. + Attributes: registrations (Sequence[google.cloud.domains_v1beta1.types.Registration]): A list of ``Registration``\ s. @@ -588,6 +597,7 @@ def raw_page(self): class GetRegistrationRequest(proto.Message): r"""Request for the ``GetRegistration`` method. + Attributes: name (str): Required. The name of the ``Registration`` to get, in the @@ -599,6 +609,7 @@ class GetRegistrationRequest(proto.Message): class UpdateRegistrationRequest(proto.Message): r"""Request for the ``UpdateRegistration`` method. + Attributes: registration (google.cloud.domains_v1beta1.types.Registration): Fields of the ``Registration`` to update. @@ -617,6 +628,7 @@ class UpdateRegistrationRequest(proto.Message): class ConfigureManagementSettingsRequest(proto.Message): r"""Request for the ``ConfigureManagementSettings`` method. + Attributes: registration (str): Required. The name of the ``Registration`` whose management @@ -642,6 +654,7 @@ class ConfigureManagementSettingsRequest(proto.Message): class ConfigureDnsSettingsRequest(proto.Message): r"""Request for the ``ConfigureDnsSettings`` method. + Attributes: registration (str): Required. The name of the ``Registration`` whose DNS @@ -676,6 +689,7 @@ class ConfigureDnsSettingsRequest(proto.Message): class ConfigureContactSettingsRequest(proto.Message): r"""Request for the ``ConfigureContactSettings`` method. + Attributes: registration (str): Required. The name of the ``Registration`` whose contact @@ -708,6 +722,7 @@ class ConfigureContactSettingsRequest(proto.Message): class ExportRegistrationRequest(proto.Message): r"""Request for the ``ExportRegistration`` method. + Attributes: name (str): Required. The name of the ``Registration`` to export, in the @@ -719,6 +734,7 @@ class ExportRegistrationRequest(proto.Message): class DeleteRegistrationRequest(proto.Message): r"""Request for the ``DeleteRegistration`` method. + Attributes: name (str): Required. The name of the ``Registration`` to delete, in the @@ -730,6 +746,7 @@ class DeleteRegistrationRequest(proto.Message): class RetrieveAuthorizationCodeRequest(proto.Message): r"""Request for the ``RetrieveAuthorizationCode`` method. + Attributes: registration (str): Required. The name of the ``Registration`` whose @@ -742,6 +759,7 @@ class RetrieveAuthorizationCodeRequest(proto.Message): class ResetAuthorizationCodeRequest(proto.Message): r"""Request for the ``ResetAuthorizationCode`` method. + Attributes: registration (str): Required. The name of the ``Registration`` whose @@ -754,6 +772,7 @@ class ResetAuthorizationCodeRequest(proto.Message): class RegisterParameters(proto.Message): r"""Parameters required to register a new domain. + Attributes: domain_name (str): The domain name. Unicode domain names are @@ -793,6 +812,7 @@ class Availability(proto.Enum): class AuthorizationCode(proto.Message): r"""Defines an authorization code. + Attributes: code (str): The Authorization Code in ASCII. It can be diff --git a/packages/google-cloud-domains/tests/unit/gapic/domains_v1beta1/test_domains.py b/packages/google-cloud-domains/tests/unit/gapic/domains_v1beta1/test_domains.py index 3febe2e14d42..c3c2c7d903c4 100644 --- a/packages/google-cloud-domains/tests/unit/gapic/domains_v1beta1/test_domains.py +++ b/packages/google-cloud-domains/tests/unit/gapic/domains_v1beta1/test_domains.py @@ -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.domains_v1beta1.services.domains import DomainsAsyncClient @@ -3608,6 +3609,9 @@ def test_domains_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): @@ -4104,3 +4108,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 = DomainsAsyncClient( + 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 = DomainsClient( + 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 = DomainsClient( + 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()