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 #71

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
6 changes: 6 additions & 0 deletions google/cloud/domains_v1beta1/services/domains/async_client.py
Expand Up @@ -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(
Expand Down
18 changes: 14 additions & 4 deletions google/cloud/domains_v1beta1/services/domains/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 search_domains(
Expand Down Expand Up @@ -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(
Expand Down
Expand Up @@ -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."""
Expand Down
Expand Up @@ -648,5 +648,8 @@ def reset_authorization_code(
)
return self._stubs["reset_authorization_code"]

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


__all__ = ("DomainsGrpcTransport",)
Expand Up @@ -668,5 +668,8 @@ def reset_authorization_code(
)
return self._stubs["reset_authorization_code"]

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


__all__ = ("DomainsGrpcAsyncIOTransport",)
20 changes: 20 additions & 0 deletions google/cloud/domains_v1beta1/types/domains.py
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand All @@ -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.
Expand All @@ -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
Expand All @@ -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``
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand All @@ -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
Expand All @@ -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.
Expand All @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
50 changes: 50 additions & 0 deletions tests/unit/gapic/domains_v1beta1/test_domains.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.domains_v1beta1.services.domains import DomainsAsyncClient
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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()