diff --git a/google/cloud/domains_v1/gapic_metadata.json b/google/cloud/domains_v1/gapic_metadata.json index c6b54de..a2b2080 100644 --- a/google/cloud/domains_v1/gapic_metadata.json +++ b/google/cloud/domains_v1/gapic_metadata.json @@ -166,6 +166,86 @@ ] } } + }, + "rest": { + "libraryClient": "DomainsClient", + "rpcs": { + "ConfigureContactSettings": { + "methods": [ + "configure_contact_settings" + ] + }, + "ConfigureDnsSettings": { + "methods": [ + "configure_dns_settings" + ] + }, + "ConfigureManagementSettings": { + "methods": [ + "configure_management_settings" + ] + }, + "DeleteRegistration": { + "methods": [ + "delete_registration" + ] + }, + "ExportRegistration": { + "methods": [ + "export_registration" + ] + }, + "GetRegistration": { + "methods": [ + "get_registration" + ] + }, + "ListRegistrations": { + "methods": [ + "list_registrations" + ] + }, + "RegisterDomain": { + "methods": [ + "register_domain" + ] + }, + "ResetAuthorizationCode": { + "methods": [ + "reset_authorization_code" + ] + }, + "RetrieveAuthorizationCode": { + "methods": [ + "retrieve_authorization_code" + ] + }, + "RetrieveRegisterParameters": { + "methods": [ + "retrieve_register_parameters" + ] + }, + "RetrieveTransferParameters": { + "methods": [ + "retrieve_transfer_parameters" + ] + }, + "SearchDomains": { + "methods": [ + "search_domains" + ] + }, + "TransferDomain": { + "methods": [ + "transfer_domain" + ] + }, + "UpdateRegistration": { + "methods": [ + "update_registration" + ] + } + } } } } diff --git a/google/cloud/domains_v1/services/domains/client.py b/google/cloud/domains_v1/services/domains/client.py index fc3b678..c7ea405 100644 --- a/google/cloud/domains_v1/services/domains/client.py +++ b/google/cloud/domains_v1/services/domains/client.py @@ -59,6 +59,7 @@ from .transports.base import DEFAULT_CLIENT_INFO, DomainsTransport from .transports.grpc import DomainsGrpcTransport from .transports.grpc_asyncio import DomainsGrpcAsyncIOTransport +from .transports.rest import DomainsRestTransport class DomainsClientMeta(type): @@ -72,6 +73,7 @@ class DomainsClientMeta(type): _transport_registry = OrderedDict() # type: Dict[str, Type[DomainsTransport]] _transport_registry["grpc"] = DomainsGrpcTransport _transport_registry["grpc_asyncio"] = DomainsGrpcAsyncIOTransport + _transport_registry["rest"] = DomainsRestTransport def get_transport_class( cls, diff --git a/google/cloud/domains_v1/services/domains/transports/__init__.py b/google/cloud/domains_v1/services/domains/transports/__init__.py index 09748fe..8351ddd 100644 --- a/google/cloud/domains_v1/services/domains/transports/__init__.py +++ b/google/cloud/domains_v1/services/domains/transports/__init__.py @@ -19,14 +19,18 @@ from .base import DomainsTransport from .grpc import DomainsGrpcTransport from .grpc_asyncio import DomainsGrpcAsyncIOTransport +from .rest import DomainsRestInterceptor, DomainsRestTransport # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[DomainsTransport]] _transport_registry["grpc"] = DomainsGrpcTransport _transport_registry["grpc_asyncio"] = DomainsGrpcAsyncIOTransport +_transport_registry["rest"] = DomainsRestTransport __all__ = ( "DomainsTransport", "DomainsGrpcTransport", "DomainsGrpcAsyncIOTransport", + "DomainsRestTransport", + "DomainsRestInterceptor", ) diff --git a/google/cloud/domains_v1/services/domains/transports/rest.py b/google/cloud/domains_v1/services/domains/transports/rest.py new file mode 100644 index 0000000..2e28c7e --- /dev/null +++ b/google/cloud/domains_v1/services/domains/transports/rest.py @@ -0,0 +1,2251 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import dataclasses +import json # type: ignore +import re +from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import ( + gapic_v1, + operations_v1, + path_template, + rest_helpers, + rest_streaming, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.protobuf import json_format +import grpc # type: ignore +from requests import __version__ as requests_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.domains_v1.types import domains + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .base import DomainsTransport + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class DomainsRestInterceptor: + """Interceptor for Domains. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the DomainsRestTransport. + + .. code-block:: python + class MyCustomDomainsInterceptor(DomainsRestInterceptor): + def pre_configure_contact_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_configure_contact_settings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_configure_dns_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_configure_dns_settings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_configure_management_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_configure_management_settings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_registration(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_registration(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_export_registration(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_export_registration(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_registration(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_registration(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_registrations(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_registrations(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_register_domain(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_register_domain(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_reset_authorization_code(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_reset_authorization_code(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_retrieve_authorization_code(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_retrieve_authorization_code(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_retrieve_register_parameters(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_retrieve_register_parameters(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_retrieve_transfer_parameters(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_retrieve_transfer_parameters(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_search_domains(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_search_domains(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_transfer_domain(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_transfer_domain(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_registration(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_registration(self, response): + logging.log(f"Received response: {response}") + return response + + transport = DomainsRestTransport(interceptor=MyCustomDomainsInterceptor()) + client = DomainsClient(transport=transport) + + + """ + + def pre_configure_contact_settings( + self, + request: domains.ConfigureContactSettingsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[domains.ConfigureContactSettingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for configure_contact_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the Domains server. + """ + return request, metadata + + def post_configure_contact_settings( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for configure_contact_settings + + Override in a subclass to manipulate the response + after it is returned by the Domains server but before + it is returned to user code. + """ + return response + + def pre_configure_dns_settings( + self, + request: domains.ConfigureDnsSettingsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[domains.ConfigureDnsSettingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for configure_dns_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the Domains server. + """ + return request, metadata + + def post_configure_dns_settings( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for configure_dns_settings + + Override in a subclass to manipulate the response + after it is returned by the Domains server but before + it is returned to user code. + """ + return response + + def pre_configure_management_settings( + self, + request: domains.ConfigureManagementSettingsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[domains.ConfigureManagementSettingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for configure_management_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the Domains server. + """ + return request, metadata + + def post_configure_management_settings( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for configure_management_settings + + Override in a subclass to manipulate the response + after it is returned by the Domains server but before + it is returned to user code. + """ + return response + + def pre_delete_registration( + self, + request: domains.DeleteRegistrationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[domains.DeleteRegistrationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_registration + + Override in a subclass to manipulate the request or metadata + before they are sent to the Domains server. + """ + return request, metadata + + def post_delete_registration( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_registration + + Override in a subclass to manipulate the response + after it is returned by the Domains server but before + it is returned to user code. + """ + return response + + def pre_export_registration( + self, + request: domains.ExportRegistrationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[domains.ExportRegistrationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for export_registration + + Override in a subclass to manipulate the request or metadata + before they are sent to the Domains server. + """ + return request, metadata + + def post_export_registration( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for export_registration + + Override in a subclass to manipulate the response + after it is returned by the Domains server but before + it is returned to user code. + """ + return response + + def pre_get_registration( + self, + request: domains.GetRegistrationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[domains.GetRegistrationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_registration + + Override in a subclass to manipulate the request or metadata + before they are sent to the Domains server. + """ + return request, metadata + + def post_get_registration( + self, response: domains.Registration + ) -> domains.Registration: + """Post-rpc interceptor for get_registration + + Override in a subclass to manipulate the response + after it is returned by the Domains server but before + it is returned to user code. + """ + return response + + def pre_list_registrations( + self, + request: domains.ListRegistrationsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[domains.ListRegistrationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_registrations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Domains server. + """ + return request, metadata + + def post_list_registrations( + self, response: domains.ListRegistrationsResponse + ) -> domains.ListRegistrationsResponse: + """Post-rpc interceptor for list_registrations + + Override in a subclass to manipulate the response + after it is returned by the Domains server but before + it is returned to user code. + """ + return response + + def pre_register_domain( + self, + request: domains.RegisterDomainRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[domains.RegisterDomainRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for register_domain + + Override in a subclass to manipulate the request or metadata + before they are sent to the Domains server. + """ + return request, metadata + + def post_register_domain( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for register_domain + + Override in a subclass to manipulate the response + after it is returned by the Domains server but before + it is returned to user code. + """ + return response + + def pre_reset_authorization_code( + self, + request: domains.ResetAuthorizationCodeRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[domains.ResetAuthorizationCodeRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for reset_authorization_code + + Override in a subclass to manipulate the request or metadata + before they are sent to the Domains server. + """ + return request, metadata + + def post_reset_authorization_code( + self, response: domains.AuthorizationCode + ) -> domains.AuthorizationCode: + """Post-rpc interceptor for reset_authorization_code + + Override in a subclass to manipulate the response + after it is returned by the Domains server but before + it is returned to user code. + """ + return response + + def pre_retrieve_authorization_code( + self, + request: domains.RetrieveAuthorizationCodeRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[domains.RetrieveAuthorizationCodeRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for retrieve_authorization_code + + Override in a subclass to manipulate the request or metadata + before they are sent to the Domains server. + """ + return request, metadata + + def post_retrieve_authorization_code( + self, response: domains.AuthorizationCode + ) -> domains.AuthorizationCode: + """Post-rpc interceptor for retrieve_authorization_code + + Override in a subclass to manipulate the response + after it is returned by the Domains server but before + it is returned to user code. + """ + return response + + def pre_retrieve_register_parameters( + self, + request: domains.RetrieveRegisterParametersRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[domains.RetrieveRegisterParametersRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for retrieve_register_parameters + + Override in a subclass to manipulate the request or metadata + before they are sent to the Domains server. + """ + return request, metadata + + def post_retrieve_register_parameters( + self, response: domains.RetrieveRegisterParametersResponse + ) -> domains.RetrieveRegisterParametersResponse: + """Post-rpc interceptor for retrieve_register_parameters + + Override in a subclass to manipulate the response + after it is returned by the Domains server but before + it is returned to user code. + """ + return response + + def pre_retrieve_transfer_parameters( + self, + request: domains.RetrieveTransferParametersRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[domains.RetrieveTransferParametersRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for retrieve_transfer_parameters + + Override in a subclass to manipulate the request or metadata + before they are sent to the Domains server. + """ + return request, metadata + + def post_retrieve_transfer_parameters( + self, response: domains.RetrieveTransferParametersResponse + ) -> domains.RetrieveTransferParametersResponse: + """Post-rpc interceptor for retrieve_transfer_parameters + + Override in a subclass to manipulate the response + after it is returned by the Domains server but before + it is returned to user code. + """ + return response + + def pre_search_domains( + self, request: domains.SearchDomainsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[domains.SearchDomainsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for search_domains + + Override in a subclass to manipulate the request or metadata + before they are sent to the Domains server. + """ + return request, metadata + + def post_search_domains( + self, response: domains.SearchDomainsResponse + ) -> domains.SearchDomainsResponse: + """Post-rpc interceptor for search_domains + + Override in a subclass to manipulate the response + after it is returned by the Domains server but before + it is returned to user code. + """ + return response + + def pre_transfer_domain( + self, + request: domains.TransferDomainRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[domains.TransferDomainRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for transfer_domain + + Override in a subclass to manipulate the request or metadata + before they are sent to the Domains server. + """ + return request, metadata + + def post_transfer_domain( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for transfer_domain + + Override in a subclass to manipulate the response + after it is returned by the Domains server but before + it is returned to user code. + """ + return response + + def pre_update_registration( + self, + request: domains.UpdateRegistrationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[domains.UpdateRegistrationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_registration + + Override in a subclass to manipulate the request or metadata + before they are sent to the Domains server. + """ + return request, metadata + + def post_update_registration( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_registration + + Override in a subclass to manipulate the response + after it is returned by the Domains server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class DomainsRestStub: + _session: AuthorizedSession + _host: str + _interceptor: DomainsRestInterceptor + + +class DomainsRestTransport(DomainsTransport): + """REST backend transport for Domains. + + The Cloud Domains API enables management and configuration of + domain names. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__( + self, + *, + host: str = "domains.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[DomainsRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or DomainsRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}/operations", + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _ConfigureContactSettings(DomainsRestStub): + def __hash__(self): + return hash("ConfigureContactSettings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: domains.ConfigureContactSettingsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the configure contact + settings method over HTTP. + + Args: + request (~.domains.ConfigureContactSettingsRequest): + The request object. Request for the ``ConfigureContactSettings`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{registration=projects/*/locations/*/registrations/*}:configureContactSettings", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_configure_contact_settings( + request, metadata + ) + pb_request = domains.ConfigureContactSettingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_configure_contact_settings(resp) + return resp + + class _ConfigureDnsSettings(DomainsRestStub): + def __hash__(self): + return hash("ConfigureDnsSettings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: domains.ConfigureDnsSettingsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the configure dns settings method over HTTP. + + Args: + request (~.domains.ConfigureDnsSettingsRequest): + The request object. Request for the ``ConfigureDnsSettings`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{registration=projects/*/locations/*/registrations/*}:configureDnsSettings", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_configure_dns_settings( + request, metadata + ) + pb_request = domains.ConfigureDnsSettingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_configure_dns_settings(resp) + return resp + + class _ConfigureManagementSettings(DomainsRestStub): + def __hash__(self): + return hash("ConfigureManagementSettings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: domains.ConfigureManagementSettingsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the configure management + settings method over HTTP. + + Args: + request (~.domains.ConfigureManagementSettingsRequest): + The request object. Request for the ``ConfigureManagementSettings`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{registration=projects/*/locations/*/registrations/*}:configureManagementSettings", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_configure_management_settings( + request, metadata + ) + pb_request = domains.ConfigureManagementSettingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_configure_management_settings(resp) + return resp + + class _DeleteRegistration(DomainsRestStub): + def __hash__(self): + return hash("DeleteRegistration") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: domains.DeleteRegistrationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete registration method over HTTP. + + Args: + request (~.domains.DeleteRegistrationRequest): + The request object. Request for the ``DeleteRegistration`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/registrations/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_registration( + request, metadata + ) + pb_request = domains.DeleteRegistrationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_registration(resp) + return resp + + class _ExportRegistration(DomainsRestStub): + def __hash__(self): + return hash("ExportRegistration") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: domains.ExportRegistrationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the export registration method over HTTP. + + Args: + request (~.domains.ExportRegistrationRequest): + The request object. Request for the ``ExportRegistration`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/registrations/*}:export", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_export_registration( + request, metadata + ) + pb_request = domains.ExportRegistrationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_export_registration(resp) + return resp + + class _GetRegistration(DomainsRestStub): + def __hash__(self): + return hash("GetRegistration") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: domains.GetRegistrationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> domains.Registration: + r"""Call the get registration method over HTTP. + + Args: + request (~.domains.GetRegistrationRequest): + The request object. Request for the ``GetRegistration`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.domains.Registration: + The ``Registration`` resource facilitates managing and + configuring domain name registrations. + + There are several ways to create a new ``Registration`` + resource: + + To create a new ``Registration`` resource, find a + suitable domain name by calling the ``SearchDomains`` + method with a query to see available domain name + options. After choosing a name, call + ``RetrieveRegisterParameters`` to ensure availability + and obtain information like pricing, which is needed to + build a call to ``RegisterDomain``. + + Another way to create a new ``Registration`` is to + transfer an existing domain from another registrar. + First, go to the current registrar to unlock the domain + for transfer and retrieve the domain's transfer + authorization code. Then call + ``RetrieveTransferParameters`` to confirm that the + domain is unlocked and to get values needed to build a + call to ``TransferDomain``. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/registrations/*}", + }, + ] + request, metadata = self._interceptor.pre_get_registration( + request, metadata + ) + pb_request = domains.GetRegistrationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = domains.Registration() + pb_resp = domains.Registration.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_registration(resp) + return resp + + class _ListRegistrations(DomainsRestStub): + def __hash__(self): + return hash("ListRegistrations") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: domains.ListRegistrationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> domains.ListRegistrationsResponse: + r"""Call the list registrations method over HTTP. + + Args: + request (~.domains.ListRegistrationsRequest): + The request object. Request for the ``ListRegistrations`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.domains.ListRegistrationsResponse: + Response for the ``ListRegistrations`` method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/registrations", + }, + ] + request, metadata = self._interceptor.pre_list_registrations( + request, metadata + ) + pb_request = domains.ListRegistrationsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = domains.ListRegistrationsResponse() + pb_resp = domains.ListRegistrationsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_registrations(resp) + return resp + + class _RegisterDomain(DomainsRestStub): + def __hash__(self): + return hash("RegisterDomain") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: domains.RegisterDomainRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the register domain method over HTTP. + + Args: + request (~.domains.RegisterDomainRequest): + The request object. Request for the ``RegisterDomain`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}/registrations:register", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_register_domain(request, metadata) + pb_request = domains.RegisterDomainRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_register_domain(resp) + return resp + + class _ResetAuthorizationCode(DomainsRestStub): + def __hash__(self): + return hash("ResetAuthorizationCode") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: domains.ResetAuthorizationCodeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> domains.AuthorizationCode: + r"""Call the reset authorization code method over HTTP. + + Args: + request (~.domains.ResetAuthorizationCodeRequest): + The request object. Request for the ``ResetAuthorizationCode`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.domains.AuthorizationCode: + Defines an authorization code. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{registration=projects/*/locations/*/registrations/*}:resetAuthorizationCode", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_reset_authorization_code( + request, metadata + ) + pb_request = domains.ResetAuthorizationCodeRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = domains.AuthorizationCode() + pb_resp = domains.AuthorizationCode.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_reset_authorization_code(resp) + return resp + + class _RetrieveAuthorizationCode(DomainsRestStub): + def __hash__(self): + return hash("RetrieveAuthorizationCode") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: domains.RetrieveAuthorizationCodeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> domains.AuthorizationCode: + r"""Call the retrieve authorization + code method over HTTP. + + Args: + request (~.domains.RetrieveAuthorizationCodeRequest): + The request object. Request for the ``RetrieveAuthorizationCode`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.domains.AuthorizationCode: + Defines an authorization code. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{registration=projects/*/locations/*/registrations/*}:retrieveAuthorizationCode", + }, + ] + request, metadata = self._interceptor.pre_retrieve_authorization_code( + request, metadata + ) + pb_request = domains.RetrieveAuthorizationCodeRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = domains.AuthorizationCode() + pb_resp = domains.AuthorizationCode.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_retrieve_authorization_code(resp) + return resp + + class _RetrieveRegisterParameters(DomainsRestStub): + def __hash__(self): + return hash("RetrieveRegisterParameters") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + "domainName": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: domains.RetrieveRegisterParametersRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> domains.RetrieveRegisterParametersResponse: + r"""Call the retrieve register + parameters method over HTTP. + + Args: + request (~.domains.RetrieveRegisterParametersRequest): + The request object. Request for the ``RetrieveRegisterParameters`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.domains.RetrieveRegisterParametersResponse: + Response for the ``RetrieveRegisterParameters`` method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{location=projects/*/locations/*}/registrations:retrieveRegisterParameters", + }, + ] + request, metadata = self._interceptor.pre_retrieve_register_parameters( + request, metadata + ) + pb_request = domains.RetrieveRegisterParametersRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = domains.RetrieveRegisterParametersResponse() + pb_resp = domains.RetrieveRegisterParametersResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_retrieve_register_parameters(resp) + return resp + + class _RetrieveTransferParameters(DomainsRestStub): + def __hash__(self): + return hash("RetrieveTransferParameters") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + "domainName": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: domains.RetrieveTransferParametersRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> domains.RetrieveTransferParametersResponse: + r"""Call the retrieve transfer + parameters method over HTTP. + + Args: + request (~.domains.RetrieveTransferParametersRequest): + The request object. Request for the ``RetrieveTransferParameters`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.domains.RetrieveTransferParametersResponse: + Response for the ``RetrieveTransferParameters`` method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{location=projects/*/locations/*}/registrations:retrieveTransferParameters", + }, + ] + request, metadata = self._interceptor.pre_retrieve_transfer_parameters( + request, metadata + ) + pb_request = domains.RetrieveTransferParametersRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = domains.RetrieveTransferParametersResponse() + pb_resp = domains.RetrieveTransferParametersResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_retrieve_transfer_parameters(resp) + return resp + + class _SearchDomains(DomainsRestStub): + def __hash__(self): + return hash("SearchDomains") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + "query": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: domains.SearchDomainsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> domains.SearchDomainsResponse: + r"""Call the search domains method over HTTP. + + Args: + request (~.domains.SearchDomainsRequest): + The request object. Request for the ``SearchDomains`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.domains.SearchDomainsResponse: + Response for the ``SearchDomains`` method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{location=projects/*/locations/*}/registrations:searchDomains", + }, + ] + request, metadata = self._interceptor.pre_search_domains(request, metadata) + pb_request = domains.SearchDomainsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = domains.SearchDomainsResponse() + pb_resp = domains.SearchDomainsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_search_domains(resp) + return resp + + class _TransferDomain(DomainsRestStub): + def __hash__(self): + return hash("TransferDomain") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: domains.TransferDomainRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the transfer domain method over HTTP. + + Args: + request (~.domains.TransferDomainRequest): + The request object. Request for the ``TransferDomain`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}/registrations:transfer", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_transfer_domain(request, metadata) + pb_request = domains.TransferDomainRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_transfer_domain(resp) + return resp + + class _UpdateRegistration(DomainsRestStub): + def __hash__(self): + return hash("UpdateRegistration") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + "updateMask": {}, + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: domains.UpdateRegistrationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the update registration method over HTTP. + + Args: + request (~.domains.UpdateRegistrationRequest): + The request object. Request for the ``UpdateRegistration`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{registration.name=projects/*/locations/*/registrations/*}", + "body": "registration", + }, + ] + request, metadata = self._interceptor.pre_update_registration( + request, metadata + ) + pb_request = domains.UpdateRegistrationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_registration(resp) + return resp + + @property + def configure_contact_settings( + self, + ) -> Callable[[domains.ConfigureContactSettingsRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ConfigureContactSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def configure_dns_settings( + self, + ) -> Callable[[domains.ConfigureDnsSettingsRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ConfigureDnsSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def configure_management_settings( + self, + ) -> Callable[ + [domains.ConfigureManagementSettingsRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ConfigureManagementSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_registration( + self, + ) -> Callable[[domains.DeleteRegistrationRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteRegistration(self._session, self._host, self._interceptor) # type: ignore + + @property + def export_registration( + self, + ) -> Callable[[domains.ExportRegistrationRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ExportRegistration(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_registration( + self, + ) -> Callable[[domains.GetRegistrationRequest], domains.Registration]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetRegistration(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_registrations( + self, + ) -> Callable[ + [domains.ListRegistrationsRequest], domains.ListRegistrationsResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListRegistrations(self._session, self._host, self._interceptor) # type: ignore + + @property + def register_domain( + self, + ) -> Callable[[domains.RegisterDomainRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RegisterDomain(self._session, self._host, self._interceptor) # type: ignore + + @property + def reset_authorization_code( + self, + ) -> Callable[[domains.ResetAuthorizationCodeRequest], domains.AuthorizationCode]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ResetAuthorizationCode(self._session, self._host, self._interceptor) # type: ignore + + @property + def retrieve_authorization_code( + self, + ) -> Callable[ + [domains.RetrieveAuthorizationCodeRequest], domains.AuthorizationCode + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RetrieveAuthorizationCode(self._session, self._host, self._interceptor) # type: ignore + + @property + def retrieve_register_parameters( + self, + ) -> Callable[ + [domains.RetrieveRegisterParametersRequest], + domains.RetrieveRegisterParametersResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RetrieveRegisterParameters(self._session, self._host, self._interceptor) # type: ignore + + @property + def retrieve_transfer_parameters( + self, + ) -> Callable[ + [domains.RetrieveTransferParametersRequest], + domains.RetrieveTransferParametersResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RetrieveTransferParameters(self._session, self._host, self._interceptor) # type: ignore + + @property + def search_domains( + self, + ) -> Callable[[domains.SearchDomainsRequest], domains.SearchDomainsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SearchDomains(self._session, self._host, self._interceptor) # type: ignore + + @property + def transfer_domain( + self, + ) -> Callable[[domains.TransferDomainRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._TransferDomain(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_registration( + self, + ) -> Callable[[domains.UpdateRegistrationRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateRegistration(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("DomainsRestTransport",) diff --git a/google/cloud/domains_v1beta1/gapic_metadata.json b/google/cloud/domains_v1beta1/gapic_metadata.json index c6f9a69..fa29a8d 100644 --- a/google/cloud/domains_v1beta1/gapic_metadata.json +++ b/google/cloud/domains_v1beta1/gapic_metadata.json @@ -166,6 +166,86 @@ ] } } + }, + "rest": { + "libraryClient": "DomainsClient", + "rpcs": { + "ConfigureContactSettings": { + "methods": [ + "configure_contact_settings" + ] + }, + "ConfigureDnsSettings": { + "methods": [ + "configure_dns_settings" + ] + }, + "ConfigureManagementSettings": { + "methods": [ + "configure_management_settings" + ] + }, + "DeleteRegistration": { + "methods": [ + "delete_registration" + ] + }, + "ExportRegistration": { + "methods": [ + "export_registration" + ] + }, + "GetRegistration": { + "methods": [ + "get_registration" + ] + }, + "ListRegistrations": { + "methods": [ + "list_registrations" + ] + }, + "RegisterDomain": { + "methods": [ + "register_domain" + ] + }, + "ResetAuthorizationCode": { + "methods": [ + "reset_authorization_code" + ] + }, + "RetrieveAuthorizationCode": { + "methods": [ + "retrieve_authorization_code" + ] + }, + "RetrieveRegisterParameters": { + "methods": [ + "retrieve_register_parameters" + ] + }, + "RetrieveTransferParameters": { + "methods": [ + "retrieve_transfer_parameters" + ] + }, + "SearchDomains": { + "methods": [ + "search_domains" + ] + }, + "TransferDomain": { + "methods": [ + "transfer_domain" + ] + }, + "UpdateRegistration": { + "methods": [ + "update_registration" + ] + } + } } } } diff --git a/google/cloud/domains_v1beta1/services/domains/client.py b/google/cloud/domains_v1beta1/services/domains/client.py index 3731674..b0274ae 100644 --- a/google/cloud/domains_v1beta1/services/domains/client.py +++ b/google/cloud/domains_v1beta1/services/domains/client.py @@ -59,6 +59,7 @@ from .transports.base import DEFAULT_CLIENT_INFO, DomainsTransport from .transports.grpc import DomainsGrpcTransport from .transports.grpc_asyncio import DomainsGrpcAsyncIOTransport +from .transports.rest import DomainsRestTransport class DomainsClientMeta(type): @@ -72,6 +73,7 @@ class DomainsClientMeta(type): _transport_registry = OrderedDict() # type: Dict[str, Type[DomainsTransport]] _transport_registry["grpc"] = DomainsGrpcTransport _transport_registry["grpc_asyncio"] = DomainsGrpcAsyncIOTransport + _transport_registry["rest"] = DomainsRestTransport def get_transport_class( cls, diff --git a/google/cloud/domains_v1beta1/services/domains/transports/__init__.py b/google/cloud/domains_v1beta1/services/domains/transports/__init__.py index 09748fe..8351ddd 100644 --- a/google/cloud/domains_v1beta1/services/domains/transports/__init__.py +++ b/google/cloud/domains_v1beta1/services/domains/transports/__init__.py @@ -19,14 +19,18 @@ from .base import DomainsTransport from .grpc import DomainsGrpcTransport from .grpc_asyncio import DomainsGrpcAsyncIOTransport +from .rest import DomainsRestInterceptor, DomainsRestTransport # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[DomainsTransport]] _transport_registry["grpc"] = DomainsGrpcTransport _transport_registry["grpc_asyncio"] = DomainsGrpcAsyncIOTransport +_transport_registry["rest"] = DomainsRestTransport __all__ = ( "DomainsTransport", "DomainsGrpcTransport", "DomainsGrpcAsyncIOTransport", + "DomainsRestTransport", + "DomainsRestInterceptor", ) diff --git a/google/cloud/domains_v1beta1/services/domains/transports/rest.py b/google/cloud/domains_v1beta1/services/domains/transports/rest.py new file mode 100644 index 0000000..17c9b68 --- /dev/null +++ b/google/cloud/domains_v1beta1/services/domains/transports/rest.py @@ -0,0 +1,2251 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import dataclasses +import json # type: ignore +import re +from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import ( + gapic_v1, + operations_v1, + path_template, + rest_helpers, + rest_streaming, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.protobuf import json_format +import grpc # type: ignore +from requests import __version__ as requests_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.domains_v1beta1.types import domains + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .base import DomainsTransport + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class DomainsRestInterceptor: + """Interceptor for Domains. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the DomainsRestTransport. + + .. code-block:: python + class MyCustomDomainsInterceptor(DomainsRestInterceptor): + def pre_configure_contact_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_configure_contact_settings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_configure_dns_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_configure_dns_settings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_configure_management_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_configure_management_settings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_registration(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_registration(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_export_registration(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_export_registration(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_registration(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_registration(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_registrations(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_registrations(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_register_domain(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_register_domain(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_reset_authorization_code(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_reset_authorization_code(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_retrieve_authorization_code(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_retrieve_authorization_code(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_retrieve_register_parameters(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_retrieve_register_parameters(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_retrieve_transfer_parameters(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_retrieve_transfer_parameters(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_search_domains(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_search_domains(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_transfer_domain(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_transfer_domain(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_registration(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_registration(self, response): + logging.log(f"Received response: {response}") + return response + + transport = DomainsRestTransport(interceptor=MyCustomDomainsInterceptor()) + client = DomainsClient(transport=transport) + + + """ + + def pre_configure_contact_settings( + self, + request: domains.ConfigureContactSettingsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[domains.ConfigureContactSettingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for configure_contact_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the Domains server. + """ + return request, metadata + + def post_configure_contact_settings( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for configure_contact_settings + + Override in a subclass to manipulate the response + after it is returned by the Domains server but before + it is returned to user code. + """ + return response + + def pre_configure_dns_settings( + self, + request: domains.ConfigureDnsSettingsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[domains.ConfigureDnsSettingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for configure_dns_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the Domains server. + """ + return request, metadata + + def post_configure_dns_settings( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for configure_dns_settings + + Override in a subclass to manipulate the response + after it is returned by the Domains server but before + it is returned to user code. + """ + return response + + def pre_configure_management_settings( + self, + request: domains.ConfigureManagementSettingsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[domains.ConfigureManagementSettingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for configure_management_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the Domains server. + """ + return request, metadata + + def post_configure_management_settings( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for configure_management_settings + + Override in a subclass to manipulate the response + after it is returned by the Domains server but before + it is returned to user code. + """ + return response + + def pre_delete_registration( + self, + request: domains.DeleteRegistrationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[domains.DeleteRegistrationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_registration + + Override in a subclass to manipulate the request or metadata + before they are sent to the Domains server. + """ + return request, metadata + + def post_delete_registration( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_registration + + Override in a subclass to manipulate the response + after it is returned by the Domains server but before + it is returned to user code. + """ + return response + + def pre_export_registration( + self, + request: domains.ExportRegistrationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[domains.ExportRegistrationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for export_registration + + Override in a subclass to manipulate the request or metadata + before they are sent to the Domains server. + """ + return request, metadata + + def post_export_registration( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for export_registration + + Override in a subclass to manipulate the response + after it is returned by the Domains server but before + it is returned to user code. + """ + return response + + def pre_get_registration( + self, + request: domains.GetRegistrationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[domains.GetRegistrationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_registration + + Override in a subclass to manipulate the request or metadata + before they are sent to the Domains server. + """ + return request, metadata + + def post_get_registration( + self, response: domains.Registration + ) -> domains.Registration: + """Post-rpc interceptor for get_registration + + Override in a subclass to manipulate the response + after it is returned by the Domains server but before + it is returned to user code. + """ + return response + + def pre_list_registrations( + self, + request: domains.ListRegistrationsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[domains.ListRegistrationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_registrations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Domains server. + """ + return request, metadata + + def post_list_registrations( + self, response: domains.ListRegistrationsResponse + ) -> domains.ListRegistrationsResponse: + """Post-rpc interceptor for list_registrations + + Override in a subclass to manipulate the response + after it is returned by the Domains server but before + it is returned to user code. + """ + return response + + def pre_register_domain( + self, + request: domains.RegisterDomainRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[domains.RegisterDomainRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for register_domain + + Override in a subclass to manipulate the request or metadata + before they are sent to the Domains server. + """ + return request, metadata + + def post_register_domain( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for register_domain + + Override in a subclass to manipulate the response + after it is returned by the Domains server but before + it is returned to user code. + """ + return response + + def pre_reset_authorization_code( + self, + request: domains.ResetAuthorizationCodeRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[domains.ResetAuthorizationCodeRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for reset_authorization_code + + Override in a subclass to manipulate the request or metadata + before they are sent to the Domains server. + """ + return request, metadata + + def post_reset_authorization_code( + self, response: domains.AuthorizationCode + ) -> domains.AuthorizationCode: + """Post-rpc interceptor for reset_authorization_code + + Override in a subclass to manipulate the response + after it is returned by the Domains server but before + it is returned to user code. + """ + return response + + def pre_retrieve_authorization_code( + self, + request: domains.RetrieveAuthorizationCodeRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[domains.RetrieveAuthorizationCodeRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for retrieve_authorization_code + + Override in a subclass to manipulate the request or metadata + before they are sent to the Domains server. + """ + return request, metadata + + def post_retrieve_authorization_code( + self, response: domains.AuthorizationCode + ) -> domains.AuthorizationCode: + """Post-rpc interceptor for retrieve_authorization_code + + Override in a subclass to manipulate the response + after it is returned by the Domains server but before + it is returned to user code. + """ + return response + + def pre_retrieve_register_parameters( + self, + request: domains.RetrieveRegisterParametersRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[domains.RetrieveRegisterParametersRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for retrieve_register_parameters + + Override in a subclass to manipulate the request or metadata + before they are sent to the Domains server. + """ + return request, metadata + + def post_retrieve_register_parameters( + self, response: domains.RetrieveRegisterParametersResponse + ) -> domains.RetrieveRegisterParametersResponse: + """Post-rpc interceptor for retrieve_register_parameters + + Override in a subclass to manipulate the response + after it is returned by the Domains server but before + it is returned to user code. + """ + return response + + def pre_retrieve_transfer_parameters( + self, + request: domains.RetrieveTransferParametersRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[domains.RetrieveTransferParametersRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for retrieve_transfer_parameters + + Override in a subclass to manipulate the request or metadata + before they are sent to the Domains server. + """ + return request, metadata + + def post_retrieve_transfer_parameters( + self, response: domains.RetrieveTransferParametersResponse + ) -> domains.RetrieveTransferParametersResponse: + """Post-rpc interceptor for retrieve_transfer_parameters + + Override in a subclass to manipulate the response + after it is returned by the Domains server but before + it is returned to user code. + """ + return response + + def pre_search_domains( + self, request: domains.SearchDomainsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[domains.SearchDomainsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for search_domains + + Override in a subclass to manipulate the request or metadata + before they are sent to the Domains server. + """ + return request, metadata + + def post_search_domains( + self, response: domains.SearchDomainsResponse + ) -> domains.SearchDomainsResponse: + """Post-rpc interceptor for search_domains + + Override in a subclass to manipulate the response + after it is returned by the Domains server but before + it is returned to user code. + """ + return response + + def pre_transfer_domain( + self, + request: domains.TransferDomainRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[domains.TransferDomainRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for transfer_domain + + Override in a subclass to manipulate the request or metadata + before they are sent to the Domains server. + """ + return request, metadata + + def post_transfer_domain( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for transfer_domain + + Override in a subclass to manipulate the response + after it is returned by the Domains server but before + it is returned to user code. + """ + return response + + def pre_update_registration( + self, + request: domains.UpdateRegistrationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[domains.UpdateRegistrationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_registration + + Override in a subclass to manipulate the request or metadata + before they are sent to the Domains server. + """ + return request, metadata + + def post_update_registration( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_registration + + Override in a subclass to manipulate the response + after it is returned by the Domains server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class DomainsRestStub: + _session: AuthorizedSession + _host: str + _interceptor: DomainsRestInterceptor + + +class DomainsRestTransport(DomainsTransport): + """REST backend transport for Domains. + + The Cloud Domains API enables management and configuration of + domain names. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__( + self, + *, + host: str = "domains.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[DomainsRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or DomainsRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*}/operations", + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1beta1", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _ConfigureContactSettings(DomainsRestStub): + def __hash__(self): + return hash("ConfigureContactSettings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: domains.ConfigureContactSettingsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the configure contact + settings method over HTTP. + + Args: + request (~.domains.ConfigureContactSettingsRequest): + The request object. Request for the ``ConfigureContactSettings`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{registration=projects/*/locations/*/registrations/*}:configureContactSettings", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_configure_contact_settings( + request, metadata + ) + pb_request = domains.ConfigureContactSettingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_configure_contact_settings(resp) + return resp + + class _ConfigureDnsSettings(DomainsRestStub): + def __hash__(self): + return hash("ConfigureDnsSettings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: domains.ConfigureDnsSettingsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the configure dns settings method over HTTP. + + Args: + request (~.domains.ConfigureDnsSettingsRequest): + The request object. Request for the ``ConfigureDnsSettings`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{registration=projects/*/locations/*/registrations/*}:configureDnsSettings", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_configure_dns_settings( + request, metadata + ) + pb_request = domains.ConfigureDnsSettingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_configure_dns_settings(resp) + return resp + + class _ConfigureManagementSettings(DomainsRestStub): + def __hash__(self): + return hash("ConfigureManagementSettings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: domains.ConfigureManagementSettingsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the configure management + settings method over HTTP. + + Args: + request (~.domains.ConfigureManagementSettingsRequest): + The request object. Request for the ``ConfigureManagementSettings`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{registration=projects/*/locations/*/registrations/*}:configureManagementSettings", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_configure_management_settings( + request, metadata + ) + pb_request = domains.ConfigureManagementSettingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_configure_management_settings(resp) + return resp + + class _DeleteRegistration(DomainsRestStub): + def __hash__(self): + return hash("DeleteRegistration") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: domains.DeleteRegistrationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete registration method over HTTP. + + Args: + request (~.domains.DeleteRegistrationRequest): + The request object. Request for the ``DeleteRegistration`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta1/{name=projects/*/locations/*/registrations/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_registration( + request, metadata + ) + pb_request = domains.DeleteRegistrationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_registration(resp) + return resp + + class _ExportRegistration(DomainsRestStub): + def __hash__(self): + return hash("ExportRegistration") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: domains.ExportRegistrationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the export registration method over HTTP. + + Args: + request (~.domains.ExportRegistrationRequest): + The request object. Request for the ``ExportRegistration`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{name=projects/*/locations/*/registrations/*}:export", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_export_registration( + request, metadata + ) + pb_request = domains.ExportRegistrationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_export_registration(resp) + return resp + + class _GetRegistration(DomainsRestStub): + def __hash__(self): + return hash("GetRegistration") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: domains.GetRegistrationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> domains.Registration: + r"""Call the get registration method over HTTP. + + Args: + request (~.domains.GetRegistrationRequest): + The request object. Request for the ``GetRegistration`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.domains.Registration: + The ``Registration`` resource facilitates managing and + configuring domain name registrations. + + There are several ways to create a new ``Registration`` + resource: + + To create a new ``Registration`` resource, find a + suitable domain name by calling the ``SearchDomains`` + method with a query to see available domain name + options. After choosing a name, call + ``RetrieveRegisterParameters`` to ensure availability + and obtain information like pricing, which is needed to + build a call to ``RegisterDomain``. + + Another way to create a new ``Registration`` is to + transfer an existing domain from another registrar. + First, go to the current registrar to unlock the domain + for transfer and retrieve the domain's transfer + authorization code. Then call + ``RetrieveTransferParameters`` to confirm that the + domain is unlocked and to get values needed to build a + call to ``TransferDomain``. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*/registrations/*}", + }, + ] + request, metadata = self._interceptor.pre_get_registration( + request, metadata + ) + pb_request = domains.GetRegistrationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = domains.Registration() + pb_resp = domains.Registration.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_registration(resp) + return resp + + class _ListRegistrations(DomainsRestStub): + def __hash__(self): + return hash("ListRegistrations") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: domains.ListRegistrationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> domains.ListRegistrationsResponse: + r"""Call the list registrations method over HTTP. + + Args: + request (~.domains.ListRegistrationsRequest): + The request object. Request for the ``ListRegistrations`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.domains.ListRegistrationsResponse: + Response for the ``ListRegistrations`` method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{parent=projects/*/locations/*}/registrations", + }, + ] + request, metadata = self._interceptor.pre_list_registrations( + request, metadata + ) + pb_request = domains.ListRegistrationsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = domains.ListRegistrationsResponse() + pb_resp = domains.ListRegistrationsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_registrations(resp) + return resp + + class _RegisterDomain(DomainsRestStub): + def __hash__(self): + return hash("RegisterDomain") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: domains.RegisterDomainRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the register domain method over HTTP. + + Args: + request (~.domains.RegisterDomainRequest): + The request object. Request for the ``RegisterDomain`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{parent=projects/*/locations/*}/registrations:register", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_register_domain(request, metadata) + pb_request = domains.RegisterDomainRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_register_domain(resp) + return resp + + class _ResetAuthorizationCode(DomainsRestStub): + def __hash__(self): + return hash("ResetAuthorizationCode") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: domains.ResetAuthorizationCodeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> domains.AuthorizationCode: + r"""Call the reset authorization code method over HTTP. + + Args: + request (~.domains.ResetAuthorizationCodeRequest): + The request object. Request for the ``ResetAuthorizationCode`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.domains.AuthorizationCode: + Defines an authorization code. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{registration=projects/*/locations/*/registrations/*}:resetAuthorizationCode", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_reset_authorization_code( + request, metadata + ) + pb_request = domains.ResetAuthorizationCodeRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = domains.AuthorizationCode() + pb_resp = domains.AuthorizationCode.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_reset_authorization_code(resp) + return resp + + class _RetrieveAuthorizationCode(DomainsRestStub): + def __hash__(self): + return hash("RetrieveAuthorizationCode") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: domains.RetrieveAuthorizationCodeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> domains.AuthorizationCode: + r"""Call the retrieve authorization + code method over HTTP. + + Args: + request (~.domains.RetrieveAuthorizationCodeRequest): + The request object. Request for the ``RetrieveAuthorizationCode`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.domains.AuthorizationCode: + Defines an authorization code. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{registration=projects/*/locations/*/registrations/*}:retrieveAuthorizationCode", + }, + ] + request, metadata = self._interceptor.pre_retrieve_authorization_code( + request, metadata + ) + pb_request = domains.RetrieveAuthorizationCodeRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = domains.AuthorizationCode() + pb_resp = domains.AuthorizationCode.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_retrieve_authorization_code(resp) + return resp + + class _RetrieveRegisterParameters(DomainsRestStub): + def __hash__(self): + return hash("RetrieveRegisterParameters") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + "domainName": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: domains.RetrieveRegisterParametersRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> domains.RetrieveRegisterParametersResponse: + r"""Call the retrieve register + parameters method over HTTP. + + Args: + request (~.domains.RetrieveRegisterParametersRequest): + The request object. Request for the ``RetrieveRegisterParameters`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.domains.RetrieveRegisterParametersResponse: + Response for the ``RetrieveRegisterParameters`` method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{location=projects/*/locations/*}/registrations:retrieveRegisterParameters", + }, + ] + request, metadata = self._interceptor.pre_retrieve_register_parameters( + request, metadata + ) + pb_request = domains.RetrieveRegisterParametersRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = domains.RetrieveRegisterParametersResponse() + pb_resp = domains.RetrieveRegisterParametersResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_retrieve_register_parameters(resp) + return resp + + class _RetrieveTransferParameters(DomainsRestStub): + def __hash__(self): + return hash("RetrieveTransferParameters") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + "domainName": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: domains.RetrieveTransferParametersRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> domains.RetrieveTransferParametersResponse: + r"""Call the retrieve transfer + parameters method over HTTP. + + Args: + request (~.domains.RetrieveTransferParametersRequest): + The request object. Request for the ``RetrieveTransferParameters`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.domains.RetrieveTransferParametersResponse: + Response for the ``RetrieveTransferParameters`` method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{location=projects/*/locations/*}/registrations:retrieveTransferParameters", + }, + ] + request, metadata = self._interceptor.pre_retrieve_transfer_parameters( + request, metadata + ) + pb_request = domains.RetrieveTransferParametersRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = domains.RetrieveTransferParametersResponse() + pb_resp = domains.RetrieveTransferParametersResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_retrieve_transfer_parameters(resp) + return resp + + class _SearchDomains(DomainsRestStub): + def __hash__(self): + return hash("SearchDomains") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + "query": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: domains.SearchDomainsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> domains.SearchDomainsResponse: + r"""Call the search domains method over HTTP. + + Args: + request (~.domains.SearchDomainsRequest): + The request object. Request for the ``SearchDomains`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.domains.SearchDomainsResponse: + Response for the ``SearchDomains`` method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{location=projects/*/locations/*}/registrations:searchDomains", + }, + ] + request, metadata = self._interceptor.pre_search_domains(request, metadata) + pb_request = domains.SearchDomainsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = domains.SearchDomainsResponse() + pb_resp = domains.SearchDomainsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_search_domains(resp) + return resp + + class _TransferDomain(DomainsRestStub): + def __hash__(self): + return hash("TransferDomain") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: domains.TransferDomainRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the transfer domain method over HTTP. + + Args: + request (~.domains.TransferDomainRequest): + The request object. Request for the ``TransferDomain`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{parent=projects/*/locations/*}/registrations:transfer", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_transfer_domain(request, metadata) + pb_request = domains.TransferDomainRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_transfer_domain(resp) + return resp + + class _UpdateRegistration(DomainsRestStub): + def __hash__(self): + return hash("UpdateRegistration") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + "updateMask": {}, + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: domains.UpdateRegistrationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the update registration method over HTTP. + + Args: + request (~.domains.UpdateRegistrationRequest): + The request object. Request for the ``UpdateRegistration`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta1/{registration.name=projects/*/locations/*/registrations/*}", + "body": "registration", + }, + ] + request, metadata = self._interceptor.pre_update_registration( + request, metadata + ) + pb_request = domains.UpdateRegistrationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_registration(resp) + return resp + + @property + def configure_contact_settings( + self, + ) -> Callable[[domains.ConfigureContactSettingsRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ConfigureContactSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def configure_dns_settings( + self, + ) -> Callable[[domains.ConfigureDnsSettingsRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ConfigureDnsSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def configure_management_settings( + self, + ) -> Callable[ + [domains.ConfigureManagementSettingsRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ConfigureManagementSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_registration( + self, + ) -> Callable[[domains.DeleteRegistrationRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteRegistration(self._session, self._host, self._interceptor) # type: ignore + + @property + def export_registration( + self, + ) -> Callable[[domains.ExportRegistrationRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ExportRegistration(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_registration( + self, + ) -> Callable[[domains.GetRegistrationRequest], domains.Registration]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetRegistration(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_registrations( + self, + ) -> Callable[ + [domains.ListRegistrationsRequest], domains.ListRegistrationsResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListRegistrations(self._session, self._host, self._interceptor) # type: ignore + + @property + def register_domain( + self, + ) -> Callable[[domains.RegisterDomainRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RegisterDomain(self._session, self._host, self._interceptor) # type: ignore + + @property + def reset_authorization_code( + self, + ) -> Callable[[domains.ResetAuthorizationCodeRequest], domains.AuthorizationCode]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ResetAuthorizationCode(self._session, self._host, self._interceptor) # type: ignore + + @property + def retrieve_authorization_code( + self, + ) -> Callable[ + [domains.RetrieveAuthorizationCodeRequest], domains.AuthorizationCode + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RetrieveAuthorizationCode(self._session, self._host, self._interceptor) # type: ignore + + @property + def retrieve_register_parameters( + self, + ) -> Callable[ + [domains.RetrieveRegisterParametersRequest], + domains.RetrieveRegisterParametersResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RetrieveRegisterParameters(self._session, self._host, self._interceptor) # type: ignore + + @property + def retrieve_transfer_parameters( + self, + ) -> Callable[ + [domains.RetrieveTransferParametersRequest], + domains.RetrieveTransferParametersResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RetrieveTransferParameters(self._session, self._host, self._interceptor) # type: ignore + + @property + def search_domains( + self, + ) -> Callable[[domains.SearchDomainsRequest], domains.SearchDomainsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SearchDomains(self._session, self._host, self._interceptor) # type: ignore + + @property + def transfer_domain( + self, + ) -> Callable[[domains.TransferDomainRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._TransferDomain(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_registration( + self, + ) -> Callable[[domains.UpdateRegistrationRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateRegistration(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("DomainsRestTransport",) diff --git a/tests/unit/gapic/domains_v1/test_domains.py b/tests/unit/gapic/domains_v1/test_domains.py index 4a29f21..acb47a8 100644 --- a/tests/unit/gapic/domains_v1/test_domains.py +++ b/tests/unit/gapic/domains_v1/test_domains.py @@ -22,6 +22,8 @@ except ImportError: # pragma: NO COVER import mock +from collections.abc import Iterable +import json import math from google.api_core import ( @@ -43,6 +45,7 @@ from google.oauth2 import service_account from google.protobuf import empty_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import json_format from google.protobuf import timestamp_pb2 # type: ignore from google.type import money_pb2 # type: ignore from google.type import postal_address_pb2 # type: ignore @@ -51,6 +54,8 @@ from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session from google.cloud.domains_v1.services.domains import ( DomainsAsyncClient, @@ -104,6 +109,7 @@ def test__get_default_mtls_endpoint(): [ (DomainsClient, "grpc"), (DomainsAsyncClient, "grpc_asyncio"), + (DomainsClient, "rest"), ], ) def test_domains_client_from_service_account_info(client_class, transport_name): @@ -117,7 +123,11 @@ def test_domains_client_from_service_account_info(client_class, transport_name): assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("domains.googleapis.com:443") + assert client.transport._host == ( + "domains.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://domains.googleapis.com" + ) @pytest.mark.parametrize( @@ -125,6 +135,7 @@ def test_domains_client_from_service_account_info(client_class, transport_name): [ (transports.DomainsGrpcTransport, "grpc"), (transports.DomainsGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.DomainsRestTransport, "rest"), ], ) def test_domains_client_service_account_always_use_jwt(transport_class, transport_name): @@ -148,6 +159,7 @@ def test_domains_client_service_account_always_use_jwt(transport_class, transpor [ (DomainsClient, "grpc"), (DomainsAsyncClient, "grpc_asyncio"), + (DomainsClient, "rest"), ], ) def test_domains_client_from_service_account_file(client_class, transport_name): @@ -168,13 +180,18 @@ def test_domains_client_from_service_account_file(client_class, transport_name): assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("domains.googleapis.com:443") + assert client.transport._host == ( + "domains.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://domains.googleapis.com" + ) def test_domains_client_get_transport_class(): transport = DomainsClient.get_transport_class() available_transports = [ transports.DomainsGrpcTransport, + transports.DomainsRestTransport, ] assert transport in available_transports @@ -187,6 +204,7 @@ def test_domains_client_get_transport_class(): [ (DomainsClient, transports.DomainsGrpcTransport, "grpc"), (DomainsAsyncClient, transports.DomainsGrpcAsyncIOTransport, "grpc_asyncio"), + (DomainsClient, transports.DomainsRestTransport, "rest"), ], ) @mock.patch.object( @@ -326,6 +344,8 @@ def test_domains_client_client_options(client_class, transport_class, transport_ "grpc_asyncio", "false", ), + (DomainsClient, transports.DomainsRestTransport, "rest", "true"), + (DomainsClient, transports.DomainsRestTransport, "rest", "false"), ], ) @mock.patch.object( @@ -511,6 +531,7 @@ def test_domains_client_get_mtls_endpoint_and_cert_source(client_class): [ (DomainsClient, transports.DomainsGrpcTransport, "grpc"), (DomainsAsyncClient, transports.DomainsGrpcAsyncIOTransport, "grpc_asyncio"), + (DomainsClient, transports.DomainsRestTransport, "rest"), ], ) def test_domains_client_client_options_scopes( @@ -546,6 +567,7 @@ def test_domains_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + (DomainsClient, transports.DomainsRestTransport, "rest", None), ], ) def test_domains_client_client_options_credentials_file( @@ -4634,203 +4656,4562 @@ async def test_reset_authorization_code_flattened_error_async(): ) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.DomainsGrpcTransport( +@pytest.mark.parametrize( + "request_type", + [ + domains.SearchDomainsRequest, + dict, + ], +) +def test_search_domains_rest(request_type): + client = DomainsClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = DomainsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + + # send a request that will satisfy transcoding + request_init = {"location": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = domains.SearchDomainsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = domains.SearchDomainsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.search_domains(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, domains.SearchDomainsResponse) + + +def test_search_domains_rest_required_fields(request_type=domains.SearchDomainsRequest): + transport_class = transports.DomainsRestTransport + + request_init = {} + request_init["query"] = "" + request_init["location"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, ) + ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.DomainsGrpcTransport( + # verify fields with default values are dropped + assert "query" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).search_domains._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "query" in jsonified_request + assert jsonified_request["query"] == request_init["query"] + + jsonified_request["query"] = "query_value" + jsonified_request["location"] = "location_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).search_domains._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("query",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "query" in jsonified_request + assert jsonified_request["query"] == "query_value" + assert "location" in jsonified_request + assert jsonified_request["location"] == "location_value" + + client = DomainsClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = DomainsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = domains.SearchDomainsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = domains.SearchDomainsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.search_domains(request) + + expected_params = [ + ( + "query", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_search_domains_rest_unset_required_fields(): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.search_domains._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("query",)) + & set( + ( + "query", + "location", + ) ) + ) - # It is an error to provide an api_key and a transport instance. - transport = transports.DomainsGrpcTransport( + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_search_domains_rest_interceptors(null_interceptor): + transport = transports.DomainsRestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DomainsRestInterceptor(), ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = DomainsClient( - client_options=options, - transport=transport, + client = DomainsClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.DomainsRestInterceptor, "post_search_domains" + ) as post, mock.patch.object( + transports.DomainsRestInterceptor, "pre_search_domains" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = domains.SearchDomainsRequest.pb(domains.SearchDomainsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = domains.SearchDomainsResponse.to_json( + domains.SearchDomainsResponse() ) - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = DomainsClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + request = domains.SearchDomainsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = domains.SearchDomainsResponse() - # It is an error to provide scopes and a transport instance. - transport = transports.DomainsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DomainsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + client.search_domains( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) + pre.assert_called_once() + post.assert_called_once() -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.DomainsGrpcTransport( + +def test_search_domains_rest_bad_request( + transport: str = "rest", request_type=domains.SearchDomainsRequest +): + client = DomainsClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - client = DomainsClient(transport=transport) - assert client.transport is transport + # send a request that will satisfy transcoding + request_init = {"location": "projects/sample1/locations/sample2"} + request = request_type(**request_init) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.DomainsGrpcTransport( + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.search_domains(request) + + +def test_search_domains_rest_flattened(): + client = DomainsClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.DomainsGrpcAsyncIOTransport( + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = domains.SearchDomainsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"location": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + location="location_value", + query="query_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = domains.SearchDomainsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.search_domains(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{location=projects/*/locations/*}/registrations:searchDomains" + % client.transport._host, + args[1], + ) + + +def test_search_domains_rest_flattened_error(transport: str = "rest"): + client = DomainsClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - channel = transport.grpc_channel - assert channel + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.search_domains( + domains.SearchDomainsRequest(), + location="location_value", + query="query_value", + ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.DomainsGrpcTransport, - transports.DomainsGrpcAsyncIOTransport, - ], -) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() + +def test_search_domains_rest_error(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) @pytest.mark.parametrize( - "transport_name", + "request_type", [ - "grpc", + domains.RetrieveRegisterParametersRequest, + dict, ], ) -def test_transport_kind(transport_name): - transport = DomainsClient.get_transport_class(transport_name)( +def test_retrieve_register_parameters_rest(request_type): + client = DomainsClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + # send a request that will satisfy transcoding + request_init = {"location": "projects/sample1/locations/sample2"} + request = request_type(**request_init) -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = DomainsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.DomainsGrpcTransport, - ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = domains.RetrieveRegisterParametersResponse() + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = domains.RetrieveRegisterParametersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) -def test_domains_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.DomainsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", - ) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.retrieve_register_parameters(request) + # Establish that the response is the type that we expect. + assert isinstance(response, domains.RetrieveRegisterParametersResponse) -def test_domains_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.domains_v1.services.domains.transports.DomainsTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.DomainsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "search_domains", - "retrieve_register_parameters", - "register_domain", - "retrieve_transfer_parameters", - "transfer_domain", - "list_registrations", - "get_registration", - "update_registration", - "configure_management_settings", - "configure_dns_settings", - "configure_contact_settings", - "export_registration", - "delete_registration", - "retrieve_authorization_code", - "reset_authorization_code", +def test_retrieve_register_parameters_rest_required_fields( + request_type=domains.RetrieveRegisterParametersRequest, +): + transport_class = transports.DomainsRestTransport + + request_init = {} + request_init["domain_name"] = "" + request_init["location"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - with pytest.raises(NotImplementedError): - transport.close() + # verify fields with default values are dropped + assert "domainName" not in jsonified_request - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).retrieve_register_parameters._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - # Catch all for all remaining methods and properties - remainder = [ - "kind", - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() + # verify required fields with default values are now present + assert "domainName" in jsonified_request + assert jsonified_request["domainName"] == request_init["domain_name"] + jsonified_request["domainName"] = "domain_name_value" + jsonified_request["location"] = "location_value" -def test_domains_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).retrieve_register_parameters._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("domain_name",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "domainName" in jsonified_request + assert jsonified_request["domainName"] == "domain_name_value" + assert "location" in jsonified_request + assert jsonified_request["location"] == "location_value" + + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = domains.RetrieveRegisterParametersResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = domains.RetrieveRegisterParametersResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.retrieve_register_parameters(request) + + expected_params = [ + ( + "domainName", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_retrieve_register_parameters_rest_unset_required_fields(): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.retrieve_register_parameters._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("domainName",)) + & set( + ( + "domainName", + "location", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_retrieve_register_parameters_rest_interceptors(null_interceptor): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DomainsRestInterceptor(), + ) + client = DomainsClient(transport=transport) with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch( - "google.cloud.domains_v1.services.domains.transports.DomainsTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DomainsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.DomainsRestInterceptor, "post_retrieve_register_parameters" + ) as post, mock.patch.object( + transports.DomainsRestInterceptor, "pre_retrieve_register_parameters" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = domains.RetrieveRegisterParametersRequest.pb( + domains.RetrieveRegisterParametersRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = domains.RetrieveRegisterParametersResponse.to_json( + domains.RetrieveRegisterParametersResponse() ) - load_creds.assert_called_once_with( - "credentials.json", - scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id="octopus", + + request = domains.RetrieveRegisterParametersRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = domains.RetrieveRegisterParametersResponse() + + client.retrieve_register_parameters( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) + pre.assert_called_once() + post.assert_called_once() -def test_domains_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. + +def test_retrieve_register_parameters_rest_bad_request( + transport: str = "rest", request_type=domains.RetrieveRegisterParametersRequest +): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"location": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.retrieve_register_parameters(request) + + +def test_retrieve_register_parameters_rest_flattened(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = domains.RetrieveRegisterParametersResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"location": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + location="location_value", + domain_name="domain_name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = domains.RetrieveRegisterParametersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.retrieve_register_parameters(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{location=projects/*/locations/*}/registrations:retrieveRegisterParameters" + % client.transport._host, + args[1], + ) + + +def test_retrieve_register_parameters_rest_flattened_error(transport: str = "rest"): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.retrieve_register_parameters( + domains.RetrieveRegisterParametersRequest(), + location="location_value", + domain_name="domain_name_value", + ) + + +def test_retrieve_register_parameters_rest_error(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + domains.RegisterDomainRequest, + dict, + ], +) +def test_register_domain_rest(request_type): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.register_domain(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_register_domain_rest_required_fields( + request_type=domains.RegisterDomainRequest, +): + transport_class = transports.DomainsRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).register_domain._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).register_domain._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.register_domain(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_register_domain_rest_unset_required_fields(): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.register_domain._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "registration", + "yearlyPrice", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_register_domain_rest_interceptors(null_interceptor): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DomainsRestInterceptor(), + ) + client = DomainsClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.DomainsRestInterceptor, "post_register_domain" + ) as post, mock.patch.object( + transports.DomainsRestInterceptor, "pre_register_domain" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = domains.RegisterDomainRequest.pb(domains.RegisterDomainRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = domains.RegisterDomainRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.register_domain( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_register_domain_rest_bad_request( + transport: str = "rest", request_type=domains.RegisterDomainRequest +): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.register_domain(request) + + +def test_register_domain_rest_flattened(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + registration=domains.Registration(name="name_value"), + yearly_price=money_pb2.Money(currency_code="currency_code_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.register_domain(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*}/registrations:register" + % client.transport._host, + args[1], + ) + + +def test_register_domain_rest_flattened_error(transport: str = "rest"): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.register_domain( + domains.RegisterDomainRequest(), + parent="parent_value", + registration=domains.Registration(name="name_value"), + yearly_price=money_pb2.Money(currency_code="currency_code_value"), + ) + + +def test_register_domain_rest_error(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + domains.RetrieveTransferParametersRequest, + dict, + ], +) +def test_retrieve_transfer_parameters_rest(request_type): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"location": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = domains.RetrieveTransferParametersResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = domains.RetrieveTransferParametersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.retrieve_transfer_parameters(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, domains.RetrieveTransferParametersResponse) + + +def test_retrieve_transfer_parameters_rest_required_fields( + request_type=domains.RetrieveTransferParametersRequest, +): + transport_class = transports.DomainsRestTransport + + request_init = {} + request_init["domain_name"] = "" + request_init["location"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + assert "domainName" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).retrieve_transfer_parameters._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "domainName" in jsonified_request + assert jsonified_request["domainName"] == request_init["domain_name"] + + jsonified_request["domainName"] = "domain_name_value" + jsonified_request["location"] = "location_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).retrieve_transfer_parameters._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("domain_name",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "domainName" in jsonified_request + assert jsonified_request["domainName"] == "domain_name_value" + assert "location" in jsonified_request + assert jsonified_request["location"] == "location_value" + + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = domains.RetrieveTransferParametersResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = domains.RetrieveTransferParametersResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.retrieve_transfer_parameters(request) + + expected_params = [ + ( + "domainName", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_retrieve_transfer_parameters_rest_unset_required_fields(): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.retrieve_transfer_parameters._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("domainName",)) + & set( + ( + "domainName", + "location", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_retrieve_transfer_parameters_rest_interceptors(null_interceptor): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DomainsRestInterceptor(), + ) + client = DomainsClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.DomainsRestInterceptor, "post_retrieve_transfer_parameters" + ) as post, mock.patch.object( + transports.DomainsRestInterceptor, "pre_retrieve_transfer_parameters" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = domains.RetrieveTransferParametersRequest.pb( + domains.RetrieveTransferParametersRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = domains.RetrieveTransferParametersResponse.to_json( + domains.RetrieveTransferParametersResponse() + ) + + request = domains.RetrieveTransferParametersRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = domains.RetrieveTransferParametersResponse() + + client.retrieve_transfer_parameters( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_retrieve_transfer_parameters_rest_bad_request( + transport: str = "rest", request_type=domains.RetrieveTransferParametersRequest +): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"location": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.retrieve_transfer_parameters(request) + + +def test_retrieve_transfer_parameters_rest_flattened(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = domains.RetrieveTransferParametersResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"location": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + location="location_value", + domain_name="domain_name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = domains.RetrieveTransferParametersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.retrieve_transfer_parameters(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{location=projects/*/locations/*}/registrations:retrieveTransferParameters" + % client.transport._host, + args[1], + ) + + +def test_retrieve_transfer_parameters_rest_flattened_error(transport: str = "rest"): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.retrieve_transfer_parameters( + domains.RetrieveTransferParametersRequest(), + location="location_value", + domain_name="domain_name_value", + ) + + +def test_retrieve_transfer_parameters_rest_error(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + domains.TransferDomainRequest, + dict, + ], +) +def test_transfer_domain_rest(request_type): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.transfer_domain(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_transfer_domain_rest_required_fields( + request_type=domains.TransferDomainRequest, +): + transport_class = transports.DomainsRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).transfer_domain._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).transfer_domain._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.transfer_domain(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_transfer_domain_rest_unset_required_fields(): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.transfer_domain._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "registration", + "yearlyPrice", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_transfer_domain_rest_interceptors(null_interceptor): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DomainsRestInterceptor(), + ) + client = DomainsClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.DomainsRestInterceptor, "post_transfer_domain" + ) as post, mock.patch.object( + transports.DomainsRestInterceptor, "pre_transfer_domain" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = domains.TransferDomainRequest.pb(domains.TransferDomainRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = domains.TransferDomainRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.transfer_domain( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_transfer_domain_rest_bad_request( + transport: str = "rest", request_type=domains.TransferDomainRequest +): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.transfer_domain(request) + + +def test_transfer_domain_rest_flattened(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + registration=domains.Registration(name="name_value"), + yearly_price=money_pb2.Money(currency_code="currency_code_value"), + authorization_code=domains.AuthorizationCode(code="code_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.transfer_domain(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*}/registrations:transfer" + % client.transport._host, + args[1], + ) + + +def test_transfer_domain_rest_flattened_error(transport: str = "rest"): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.transfer_domain( + domains.TransferDomainRequest(), + parent="parent_value", + registration=domains.Registration(name="name_value"), + yearly_price=money_pb2.Money(currency_code="currency_code_value"), + authorization_code=domains.AuthorizationCode(code="code_value"), + ) + + +def test_transfer_domain_rest_error(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + domains.ListRegistrationsRequest, + dict, + ], +) +def test_list_registrations_rest(request_type): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = domains.ListRegistrationsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = domains.ListRegistrationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_registrations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRegistrationsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_registrations_rest_required_fields( + request_type=domains.ListRegistrationsRequest, +): + transport_class = transports.DomainsRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_registrations._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_registrations._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = domains.ListRegistrationsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = domains.ListRegistrationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_registrations(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_registrations_rest_unset_required_fields(): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_registrations._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_registrations_rest_interceptors(null_interceptor): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DomainsRestInterceptor(), + ) + client = DomainsClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.DomainsRestInterceptor, "post_list_registrations" + ) as post, mock.patch.object( + transports.DomainsRestInterceptor, "pre_list_registrations" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = domains.ListRegistrationsRequest.pb( + domains.ListRegistrationsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = domains.ListRegistrationsResponse.to_json( + domains.ListRegistrationsResponse() + ) + + request = domains.ListRegistrationsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = domains.ListRegistrationsResponse() + + client.list_registrations( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_registrations_rest_bad_request( + transport: str = "rest", request_type=domains.ListRegistrationsRequest +): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_registrations(request) + + +def test_list_registrations_rest_flattened(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = domains.ListRegistrationsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = domains.ListRegistrationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_registrations(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*}/registrations" + % client.transport._host, + args[1], + ) + + +def test_list_registrations_rest_flattened_error(transport: str = "rest"): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_registrations( + domains.ListRegistrationsRequest(), + parent="parent_value", + ) + + +def test_list_registrations_rest_pager(transport: str = "rest"): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + domains.ListRegistrationsResponse( + registrations=[ + domains.Registration(), + domains.Registration(), + domains.Registration(), + ], + next_page_token="abc", + ), + domains.ListRegistrationsResponse( + registrations=[], + next_page_token="def", + ), + domains.ListRegistrationsResponse( + registrations=[ + domains.Registration(), + ], + next_page_token="ghi", + ), + domains.ListRegistrationsResponse( + registrations=[ + domains.Registration(), + domains.Registration(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(domains.ListRegistrationsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_registrations(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, domains.Registration) for i in results) + + pages = list(client.list_registrations(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + domains.GetRegistrationRequest, + dict, + ], +) +def test_get_registration_rest(request_type): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/registrations/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = domains.Registration( + name="name_value", + domain_name="domain_name_value", + state=domains.Registration.State.REGISTRATION_PENDING, + issues=[domains.Registration.Issue.CONTACT_SUPPORT], + supported_privacy=[domains.ContactPrivacy.PUBLIC_CONTACT_DATA], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = domains.Registration.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_registration(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, domains.Registration) + assert response.name == "name_value" + assert response.domain_name == "domain_name_value" + assert response.state == domains.Registration.State.REGISTRATION_PENDING + assert response.issues == [domains.Registration.Issue.CONTACT_SUPPORT] + assert response.supported_privacy == [domains.ContactPrivacy.PUBLIC_CONTACT_DATA] + + +def test_get_registration_rest_required_fields( + request_type=domains.GetRegistrationRequest, +): + transport_class = transports.DomainsRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_registration._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_registration._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = domains.Registration() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = domains.Registration.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_registration(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_registration_rest_unset_required_fields(): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_registration._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_registration_rest_interceptors(null_interceptor): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DomainsRestInterceptor(), + ) + client = DomainsClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.DomainsRestInterceptor, "post_get_registration" + ) as post, mock.patch.object( + transports.DomainsRestInterceptor, "pre_get_registration" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = domains.GetRegistrationRequest.pb(domains.GetRegistrationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = domains.Registration.to_json(domains.Registration()) + + request = domains.GetRegistrationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = domains.Registration() + + client.get_registration( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_registration_rest_bad_request( + transport: str = "rest", request_type=domains.GetRegistrationRequest +): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/registrations/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_registration(request) + + +def test_get_registration_rest_flattened(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = domains.Registration() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/registrations/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = domains.Registration.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_registration(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/registrations/*}" + % client.transport._host, + args[1], + ) + + +def test_get_registration_rest_flattened_error(transport: str = "rest"): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_registration( + domains.GetRegistrationRequest(), + name="name_value", + ) + + +def test_get_registration_rest_error(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + domains.UpdateRegistrationRequest, + dict, + ], +) +def test_update_registration_rest(request_type): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "registration": { + "name": "projects/sample1/locations/sample2/registrations/sample3" + } + } + request_init["registration"] = { + "name": "projects/sample1/locations/sample2/registrations/sample3", + "domain_name": "domain_name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "expire_time": {}, + "state": 1, + "issues": [1], + "labels": {}, + "management_settings": {"renewal_method": 1, "transfer_lock_state": 1}, + "dns_settings": { + "custom_dns": { + "name_servers": ["name_servers_value1", "name_servers_value2"], + "ds_records": [ + { + "key_tag": 740, + "algorithm": 1, + "digest_type": 1, + "digest": "digest_value", + } + ], + }, + "google_domains_dns": { + "name_servers": ["name_servers_value1", "name_servers_value2"], + "ds_state": 1, + "ds_records": {}, + }, + "glue_records": [ + { + "host_name": "host_name_value", + "ipv4_addresses": [ + "ipv4_addresses_value1", + "ipv4_addresses_value2", + ], + "ipv6_addresses": [ + "ipv6_addresses_value1", + "ipv6_addresses_value2", + ], + } + ], + }, + "contact_settings": { + "privacy": 1, + "registrant_contact": { + "postal_address": { + "revision": 879, + "region_code": "region_code_value", + "language_code": "language_code_value", + "postal_code": "postal_code_value", + "sorting_code": "sorting_code_value", + "administrative_area": "administrative_area_value", + "locality": "locality_value", + "sublocality": "sublocality_value", + "address_lines": ["address_lines_value1", "address_lines_value2"], + "recipients": ["recipients_value1", "recipients_value2"], + "organization": "organization_value", + }, + "email": "email_value", + "phone_number": "phone_number_value", + "fax_number": "fax_number_value", + }, + "admin_contact": {}, + "technical_contact": {}, + }, + "pending_contact_settings": {}, + "supported_privacy": [1], + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_registration(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_registration_rest_required_fields( + request_type=domains.UpdateRegistrationRequest, +): + transport_class = transports.DomainsRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_registration._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_registration._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_registration(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_registration_rest_unset_required_fields(): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_registration._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("updateMask",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_registration_rest_interceptors(null_interceptor): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DomainsRestInterceptor(), + ) + client = DomainsClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.DomainsRestInterceptor, "post_update_registration" + ) as post, mock.patch.object( + transports.DomainsRestInterceptor, "pre_update_registration" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = domains.UpdateRegistrationRequest.pb( + domains.UpdateRegistrationRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = domains.UpdateRegistrationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_registration( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_registration_rest_bad_request( + transport: str = "rest", request_type=domains.UpdateRegistrationRequest +): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "registration": { + "name": "projects/sample1/locations/sample2/registrations/sample3" + } + } + request_init["registration"] = { + "name": "projects/sample1/locations/sample2/registrations/sample3", + "domain_name": "domain_name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "expire_time": {}, + "state": 1, + "issues": [1], + "labels": {}, + "management_settings": {"renewal_method": 1, "transfer_lock_state": 1}, + "dns_settings": { + "custom_dns": { + "name_servers": ["name_servers_value1", "name_servers_value2"], + "ds_records": [ + { + "key_tag": 740, + "algorithm": 1, + "digest_type": 1, + "digest": "digest_value", + } + ], + }, + "google_domains_dns": { + "name_servers": ["name_servers_value1", "name_servers_value2"], + "ds_state": 1, + "ds_records": {}, + }, + "glue_records": [ + { + "host_name": "host_name_value", + "ipv4_addresses": [ + "ipv4_addresses_value1", + "ipv4_addresses_value2", + ], + "ipv6_addresses": [ + "ipv6_addresses_value1", + "ipv6_addresses_value2", + ], + } + ], + }, + "contact_settings": { + "privacy": 1, + "registrant_contact": { + "postal_address": { + "revision": 879, + "region_code": "region_code_value", + "language_code": "language_code_value", + "postal_code": "postal_code_value", + "sorting_code": "sorting_code_value", + "administrative_area": "administrative_area_value", + "locality": "locality_value", + "sublocality": "sublocality_value", + "address_lines": ["address_lines_value1", "address_lines_value2"], + "recipients": ["recipients_value1", "recipients_value2"], + "organization": "organization_value", + }, + "email": "email_value", + "phone_number": "phone_number_value", + "fax_number": "fax_number_value", + }, + "admin_contact": {}, + "technical_contact": {}, + }, + "pending_contact_settings": {}, + "supported_privacy": [1], + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_registration(request) + + +def test_update_registration_rest_flattened(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "registration": { + "name": "projects/sample1/locations/sample2/registrations/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + registration=domains.Registration(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_registration(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{registration.name=projects/*/locations/*/registrations/*}" + % client.transport._host, + args[1], + ) + + +def test_update_registration_rest_flattened_error(transport: str = "rest"): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_registration( + domains.UpdateRegistrationRequest(), + registration=domains.Registration(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_registration_rest_error(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + domains.ConfigureManagementSettingsRequest, + dict, + ], +) +def test_configure_management_settings_rest(request_type): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "registration": "projects/sample1/locations/sample2/registrations/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.configure_management_settings(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_configure_management_settings_rest_required_fields( + request_type=domains.ConfigureManagementSettingsRequest, +): + transport_class = transports.DomainsRestTransport + + request_init = {} + request_init["registration"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).configure_management_settings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["registration"] = "registration_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).configure_management_settings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "registration" in jsonified_request + assert jsonified_request["registration"] == "registration_value" + + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.configure_management_settings(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_configure_management_settings_rest_unset_required_fields(): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.configure_management_settings._get_unset_required_fields( + {} + ) + assert set(unset_fields) == ( + set(()) + & set( + ( + "registration", + "updateMask", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_configure_management_settings_rest_interceptors(null_interceptor): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DomainsRestInterceptor(), + ) + client = DomainsClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.DomainsRestInterceptor, "post_configure_management_settings" + ) as post, mock.patch.object( + transports.DomainsRestInterceptor, "pre_configure_management_settings" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = domains.ConfigureManagementSettingsRequest.pb( + domains.ConfigureManagementSettingsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = domains.ConfigureManagementSettingsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.configure_management_settings( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_configure_management_settings_rest_bad_request( + transport: str = "rest", request_type=domains.ConfigureManagementSettingsRequest +): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "registration": "projects/sample1/locations/sample2/registrations/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.configure_management_settings(request) + + +def test_configure_management_settings_rest_flattened(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "registration": "projects/sample1/locations/sample2/registrations/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + registration="registration_value", + management_settings=domains.ManagementSettings( + renewal_method=domains.ManagementSettings.RenewalMethod.AUTOMATIC_RENEWAL + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.configure_management_settings(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{registration=projects/*/locations/*/registrations/*}:configureManagementSettings" + % client.transport._host, + args[1], + ) + + +def test_configure_management_settings_rest_flattened_error(transport: str = "rest"): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.configure_management_settings( + domains.ConfigureManagementSettingsRequest(), + registration="registration_value", + management_settings=domains.ManagementSettings( + renewal_method=domains.ManagementSettings.RenewalMethod.AUTOMATIC_RENEWAL + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_configure_management_settings_rest_error(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + domains.ConfigureDnsSettingsRequest, + dict, + ], +) +def test_configure_dns_settings_rest(request_type): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "registration": "projects/sample1/locations/sample2/registrations/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.configure_dns_settings(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_configure_dns_settings_rest_required_fields( + request_type=domains.ConfigureDnsSettingsRequest, +): + transport_class = transports.DomainsRestTransport + + request_init = {} + request_init["registration"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).configure_dns_settings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["registration"] = "registration_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).configure_dns_settings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "registration" in jsonified_request + assert jsonified_request["registration"] == "registration_value" + + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.configure_dns_settings(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_configure_dns_settings_rest_unset_required_fields(): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.configure_dns_settings._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "registration", + "updateMask", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_configure_dns_settings_rest_interceptors(null_interceptor): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DomainsRestInterceptor(), + ) + client = DomainsClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.DomainsRestInterceptor, "post_configure_dns_settings" + ) as post, mock.patch.object( + transports.DomainsRestInterceptor, "pre_configure_dns_settings" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = domains.ConfigureDnsSettingsRequest.pb( + domains.ConfigureDnsSettingsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = domains.ConfigureDnsSettingsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.configure_dns_settings( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_configure_dns_settings_rest_bad_request( + transport: str = "rest", request_type=domains.ConfigureDnsSettingsRequest +): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "registration": "projects/sample1/locations/sample2/registrations/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.configure_dns_settings(request) + + +def test_configure_dns_settings_rest_flattened(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "registration": "projects/sample1/locations/sample2/registrations/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + registration="registration_value", + dns_settings=domains.DnsSettings( + custom_dns=domains.DnsSettings.CustomDns( + name_servers=["name_servers_value"] + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.configure_dns_settings(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{registration=projects/*/locations/*/registrations/*}:configureDnsSettings" + % client.transport._host, + args[1], + ) + + +def test_configure_dns_settings_rest_flattened_error(transport: str = "rest"): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.configure_dns_settings( + domains.ConfigureDnsSettingsRequest(), + registration="registration_value", + dns_settings=domains.DnsSettings( + custom_dns=domains.DnsSettings.CustomDns( + name_servers=["name_servers_value"] + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_configure_dns_settings_rest_error(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + domains.ConfigureContactSettingsRequest, + dict, + ], +) +def test_configure_contact_settings_rest(request_type): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "registration": "projects/sample1/locations/sample2/registrations/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.configure_contact_settings(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_configure_contact_settings_rest_required_fields( + request_type=domains.ConfigureContactSettingsRequest, +): + transport_class = transports.DomainsRestTransport + + request_init = {} + request_init["registration"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).configure_contact_settings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["registration"] = "registration_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).configure_contact_settings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "registration" in jsonified_request + assert jsonified_request["registration"] == "registration_value" + + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.configure_contact_settings(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_configure_contact_settings_rest_unset_required_fields(): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.configure_contact_settings._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "registration", + "updateMask", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_configure_contact_settings_rest_interceptors(null_interceptor): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DomainsRestInterceptor(), + ) + client = DomainsClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.DomainsRestInterceptor, "post_configure_contact_settings" + ) as post, mock.patch.object( + transports.DomainsRestInterceptor, "pre_configure_contact_settings" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = domains.ConfigureContactSettingsRequest.pb( + domains.ConfigureContactSettingsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = domains.ConfigureContactSettingsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.configure_contact_settings( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_configure_contact_settings_rest_bad_request( + transport: str = "rest", request_type=domains.ConfigureContactSettingsRequest +): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "registration": "projects/sample1/locations/sample2/registrations/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.configure_contact_settings(request) + + +def test_configure_contact_settings_rest_flattened(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "registration": "projects/sample1/locations/sample2/registrations/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + registration="registration_value", + contact_settings=domains.ContactSettings( + privacy=domains.ContactPrivacy.PUBLIC_CONTACT_DATA + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.configure_contact_settings(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{registration=projects/*/locations/*/registrations/*}:configureContactSettings" + % client.transport._host, + args[1], + ) + + +def test_configure_contact_settings_rest_flattened_error(transport: str = "rest"): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.configure_contact_settings( + domains.ConfigureContactSettingsRequest(), + registration="registration_value", + contact_settings=domains.ContactSettings( + privacy=domains.ContactPrivacy.PUBLIC_CONTACT_DATA + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_configure_contact_settings_rest_error(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + domains.ExportRegistrationRequest, + dict, + ], +) +def test_export_registration_rest(request_type): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/registrations/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.export_registration(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_export_registration_rest_required_fields( + request_type=domains.ExportRegistrationRequest, +): + transport_class = transports.DomainsRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).export_registration._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).export_registration._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.export_registration(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_export_registration_rest_unset_required_fields(): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.export_registration._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_export_registration_rest_interceptors(null_interceptor): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DomainsRestInterceptor(), + ) + client = DomainsClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.DomainsRestInterceptor, "post_export_registration" + ) as post, mock.patch.object( + transports.DomainsRestInterceptor, "pre_export_registration" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = domains.ExportRegistrationRequest.pb( + domains.ExportRegistrationRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = domains.ExportRegistrationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.export_registration( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_export_registration_rest_bad_request( + transport: str = "rest", request_type=domains.ExportRegistrationRequest +): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/registrations/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.export_registration(request) + + +def test_export_registration_rest_flattened(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/registrations/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.export_registration(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/registrations/*}:export" + % client.transport._host, + args[1], + ) + + +def test_export_registration_rest_flattened_error(transport: str = "rest"): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.export_registration( + domains.ExportRegistrationRequest(), + name="name_value", + ) + + +def test_export_registration_rest_error(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + domains.DeleteRegistrationRequest, + dict, + ], +) +def test_delete_registration_rest(request_type): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/registrations/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_registration(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_registration_rest_required_fields( + request_type=domains.DeleteRegistrationRequest, +): + transport_class = transports.DomainsRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_registration._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_registration._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_registration(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_registration_rest_unset_required_fields(): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_registration._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_registration_rest_interceptors(null_interceptor): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DomainsRestInterceptor(), + ) + client = DomainsClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.DomainsRestInterceptor, "post_delete_registration" + ) as post, mock.patch.object( + transports.DomainsRestInterceptor, "pre_delete_registration" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = domains.DeleteRegistrationRequest.pb( + domains.DeleteRegistrationRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = domains.DeleteRegistrationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_registration( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_registration_rest_bad_request( + transport: str = "rest", request_type=domains.DeleteRegistrationRequest +): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/registrations/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_registration(request) + + +def test_delete_registration_rest_flattened(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/registrations/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_registration(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/registrations/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_registration_rest_flattened_error(transport: str = "rest"): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_registration( + domains.DeleteRegistrationRequest(), + name="name_value", + ) + + +def test_delete_registration_rest_error(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + domains.RetrieveAuthorizationCodeRequest, + dict, + ], +) +def test_retrieve_authorization_code_rest(request_type): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "registration": "projects/sample1/locations/sample2/registrations/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = domains.AuthorizationCode( + code="code_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = domains.AuthorizationCode.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.retrieve_authorization_code(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, domains.AuthorizationCode) + assert response.code == "code_value" + + +def test_retrieve_authorization_code_rest_required_fields( + request_type=domains.RetrieveAuthorizationCodeRequest, +): + transport_class = transports.DomainsRestTransport + + request_init = {} + request_init["registration"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).retrieve_authorization_code._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["registration"] = "registration_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).retrieve_authorization_code._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "registration" in jsonified_request + assert jsonified_request["registration"] == "registration_value" + + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = domains.AuthorizationCode() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = domains.AuthorizationCode.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.retrieve_authorization_code(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_retrieve_authorization_code_rest_unset_required_fields(): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.retrieve_authorization_code._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("registration",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_retrieve_authorization_code_rest_interceptors(null_interceptor): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DomainsRestInterceptor(), + ) + client = DomainsClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.DomainsRestInterceptor, "post_retrieve_authorization_code" + ) as post, mock.patch.object( + transports.DomainsRestInterceptor, "pre_retrieve_authorization_code" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = domains.RetrieveAuthorizationCodeRequest.pb( + domains.RetrieveAuthorizationCodeRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = domains.AuthorizationCode.to_json( + domains.AuthorizationCode() + ) + + request = domains.RetrieveAuthorizationCodeRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = domains.AuthorizationCode() + + client.retrieve_authorization_code( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_retrieve_authorization_code_rest_bad_request( + transport: str = "rest", request_type=domains.RetrieveAuthorizationCodeRequest +): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "registration": "projects/sample1/locations/sample2/registrations/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.retrieve_authorization_code(request) + + +def test_retrieve_authorization_code_rest_flattened(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = domains.AuthorizationCode() + + # get arguments that satisfy an http rule for this method + sample_request = { + "registration": "projects/sample1/locations/sample2/registrations/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + registration="registration_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = domains.AuthorizationCode.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.retrieve_authorization_code(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{registration=projects/*/locations/*/registrations/*}:retrieveAuthorizationCode" + % client.transport._host, + args[1], + ) + + +def test_retrieve_authorization_code_rest_flattened_error(transport: str = "rest"): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.retrieve_authorization_code( + domains.RetrieveAuthorizationCodeRequest(), + registration="registration_value", + ) + + +def test_retrieve_authorization_code_rest_error(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + domains.ResetAuthorizationCodeRequest, + dict, + ], +) +def test_reset_authorization_code_rest(request_type): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "registration": "projects/sample1/locations/sample2/registrations/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = domains.AuthorizationCode( + code="code_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = domains.AuthorizationCode.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.reset_authorization_code(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, domains.AuthorizationCode) + assert response.code == "code_value" + + +def test_reset_authorization_code_rest_required_fields( + request_type=domains.ResetAuthorizationCodeRequest, +): + transport_class = transports.DomainsRestTransport + + request_init = {} + request_init["registration"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).reset_authorization_code._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["registration"] = "registration_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).reset_authorization_code._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "registration" in jsonified_request + assert jsonified_request["registration"] == "registration_value" + + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = domains.AuthorizationCode() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = domains.AuthorizationCode.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.reset_authorization_code(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_reset_authorization_code_rest_unset_required_fields(): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.reset_authorization_code._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("registration",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_reset_authorization_code_rest_interceptors(null_interceptor): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DomainsRestInterceptor(), + ) + client = DomainsClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.DomainsRestInterceptor, "post_reset_authorization_code" + ) as post, mock.patch.object( + transports.DomainsRestInterceptor, "pre_reset_authorization_code" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = domains.ResetAuthorizationCodeRequest.pb( + domains.ResetAuthorizationCodeRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = domains.AuthorizationCode.to_json( + domains.AuthorizationCode() + ) + + request = domains.ResetAuthorizationCodeRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = domains.AuthorizationCode() + + client.reset_authorization_code( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_reset_authorization_code_rest_bad_request( + transport: str = "rest", request_type=domains.ResetAuthorizationCodeRequest +): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "registration": "projects/sample1/locations/sample2/registrations/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.reset_authorization_code(request) + + +def test_reset_authorization_code_rest_flattened(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = domains.AuthorizationCode() + + # get arguments that satisfy an http rule for this method + sample_request = { + "registration": "projects/sample1/locations/sample2/registrations/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + registration="registration_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = domains.AuthorizationCode.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.reset_authorization_code(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{registration=projects/*/locations/*/registrations/*}:resetAuthorizationCode" + % client.transport._host, + args[1], + ) + + +def test_reset_authorization_code_rest_flattened_error(transport: str = "rest"): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.reset_authorization_code( + domains.ResetAuthorizationCodeRequest(), + registration="registration_value", + ) + + +def test_reset_authorization_code_rest_error(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.DomainsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.DomainsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DomainsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.DomainsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = DomainsClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = DomainsClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.DomainsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DomainsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.DomainsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = DomainsClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.DomainsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.DomainsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.DomainsGrpcTransport, + transports.DomainsGrpcAsyncIOTransport, + transports.DomainsRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "rest", + ], +) +def test_transport_kind(transport_name): + transport = DomainsClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.DomainsGrpcTransport, + ) + + +def test_domains_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.DomainsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_domains_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.domains_v1.services.domains.transports.DomainsTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.DomainsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "search_domains", + "retrieve_register_parameters", + "register_domain", + "retrieve_transfer_parameters", + "transfer_domain", + "list_registrations", + "get_registration", + "update_registration", + "configure_management_settings", + "configure_dns_settings", + "configure_contact_settings", + "export_registration", + "delete_registration", + "retrieve_authorization_code", + "reset_authorization_code", + ) + for method in methods: + 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): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_domains_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.domains_v1.services.domains.transports.DomainsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DomainsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_domains_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.domains_v1.services.domains.transports.DomainsTransport._prep_wrapped_messages" ) as Transport: @@ -4877,6 +9258,7 @@ def test_domains_transport_auth_adc(transport_class): [ transports.DomainsGrpcTransport, transports.DomainsGrpcAsyncIOTransport, + transports.DomainsRestTransport, ], ) def test_domains_transport_auth_gdch_credentials(transport_class): @@ -4971,11 +9353,40 @@ def test_domains_grpc_transport_client_cert_source_for_mtls(transport_class): ) +def test_domains_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.DomainsRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_domains_rest_lro_client(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + @pytest.mark.parametrize( "transport_name", [ "grpc", "grpc_asyncio", + "rest", ], ) def test_domains_host_no_port(transport_name): @@ -4986,7 +9397,11 @@ def test_domains_host_no_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("domains.googleapis.com:443") + assert client.transport._host == ( + "domains.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://domains.googleapis.com" + ) @pytest.mark.parametrize( @@ -4994,6 +9409,7 @@ def test_domains_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_domains_host_with_port(transport_name): @@ -5004,7 +9420,75 @@ def test_domains_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("domains.googleapis.com:8000") + assert client.transport._host == ( + "domains.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://domains.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_domains_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = DomainsClient( + credentials=creds1, + transport=transport_name, + ) + client2 = DomainsClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.search_domains._session + session2 = client2.transport.search_domains._session + assert session1 != session2 + session1 = client1.transport.retrieve_register_parameters._session + session2 = client2.transport.retrieve_register_parameters._session + assert session1 != session2 + session1 = client1.transport.register_domain._session + session2 = client2.transport.register_domain._session + assert session1 != session2 + session1 = client1.transport.retrieve_transfer_parameters._session + session2 = client2.transport.retrieve_transfer_parameters._session + assert session1 != session2 + session1 = client1.transport.transfer_domain._session + session2 = client2.transport.transfer_domain._session + assert session1 != session2 + session1 = client1.transport.list_registrations._session + session2 = client2.transport.list_registrations._session + assert session1 != session2 + session1 = client1.transport.get_registration._session + session2 = client2.transport.get_registration._session + assert session1 != session2 + session1 = client1.transport.update_registration._session + session2 = client2.transport.update_registration._session + assert session1 != session2 + session1 = client1.transport.configure_management_settings._session + session2 = client2.transport.configure_management_settings._session + assert session1 != session2 + session1 = client1.transport.configure_dns_settings._session + session2 = client2.transport.configure_dns_settings._session + assert session1 != session2 + session1 = client1.transport.configure_contact_settings._session + session2 = client2.transport.configure_contact_settings._session + assert session1 != session2 + session1 = client1.transport.export_registration._session + session2 = client2.transport.export_registration._session + assert session1 != session2 + session1 = client1.transport.delete_registration._session + session2 = client2.transport.delete_registration._session + assert session1 != session2 + session1 = client1.transport.retrieve_authorization_code._session + session2 = client2.transport.retrieve_authorization_code._session + assert session1 != session2 + session1 = client1.transport.reset_authorization_code._session + session2 = client2.transport.reset_authorization_code._session + assert session1 != session2 def test_domains_grpc_transport_channel(): @@ -5329,6 +9813,7 @@ async def test_transport_close_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -5346,6 +9831,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: diff --git a/tests/unit/gapic/domains_v1beta1/test_domains.py b/tests/unit/gapic/domains_v1beta1/test_domains.py index e2160d0..618b38d 100644 --- a/tests/unit/gapic/domains_v1beta1/test_domains.py +++ b/tests/unit/gapic/domains_v1beta1/test_domains.py @@ -22,6 +22,8 @@ except ImportError: # pragma: NO COVER import mock +from collections.abc import Iterable +import json import math from google.api_core import ( @@ -43,6 +45,7 @@ from google.oauth2 import service_account from google.protobuf import empty_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import json_format from google.protobuf import timestamp_pb2 # type: ignore from google.type import money_pb2 # type: ignore from google.type import postal_address_pb2 # type: ignore @@ -51,6 +54,8 @@ from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session from google.cloud.domains_v1beta1.services.domains import ( DomainsAsyncClient, @@ -104,6 +109,7 @@ def test__get_default_mtls_endpoint(): [ (DomainsClient, "grpc"), (DomainsAsyncClient, "grpc_asyncio"), + (DomainsClient, "rest"), ], ) def test_domains_client_from_service_account_info(client_class, transport_name): @@ -117,7 +123,11 @@ def test_domains_client_from_service_account_info(client_class, transport_name): assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("domains.googleapis.com:443") + assert client.transport._host == ( + "domains.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://domains.googleapis.com" + ) @pytest.mark.parametrize( @@ -125,6 +135,7 @@ def test_domains_client_from_service_account_info(client_class, transport_name): [ (transports.DomainsGrpcTransport, "grpc"), (transports.DomainsGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.DomainsRestTransport, "rest"), ], ) def test_domains_client_service_account_always_use_jwt(transport_class, transport_name): @@ -148,6 +159,7 @@ def test_domains_client_service_account_always_use_jwt(transport_class, transpor [ (DomainsClient, "grpc"), (DomainsAsyncClient, "grpc_asyncio"), + (DomainsClient, "rest"), ], ) def test_domains_client_from_service_account_file(client_class, transport_name): @@ -168,13 +180,18 @@ def test_domains_client_from_service_account_file(client_class, transport_name): assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("domains.googleapis.com:443") + assert client.transport._host == ( + "domains.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://domains.googleapis.com" + ) def test_domains_client_get_transport_class(): transport = DomainsClient.get_transport_class() available_transports = [ transports.DomainsGrpcTransport, + transports.DomainsRestTransport, ] assert transport in available_transports @@ -187,6 +204,7 @@ def test_domains_client_get_transport_class(): [ (DomainsClient, transports.DomainsGrpcTransport, "grpc"), (DomainsAsyncClient, transports.DomainsGrpcAsyncIOTransport, "grpc_asyncio"), + (DomainsClient, transports.DomainsRestTransport, "rest"), ], ) @mock.patch.object( @@ -326,6 +344,8 @@ def test_domains_client_client_options(client_class, transport_class, transport_ "grpc_asyncio", "false", ), + (DomainsClient, transports.DomainsRestTransport, "rest", "true"), + (DomainsClient, transports.DomainsRestTransport, "rest", "false"), ], ) @mock.patch.object( @@ -511,6 +531,7 @@ def test_domains_client_get_mtls_endpoint_and_cert_source(client_class): [ (DomainsClient, transports.DomainsGrpcTransport, "grpc"), (DomainsAsyncClient, transports.DomainsGrpcAsyncIOTransport, "grpc_asyncio"), + (DomainsClient, transports.DomainsRestTransport, "rest"), ], ) def test_domains_client_client_options_scopes( @@ -546,6 +567,7 @@ def test_domains_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + (DomainsClient, transports.DomainsRestTransport, "rest", None), ], ) def test_domains_client_client_options_credentials_file( @@ -4634,203 +4656,4562 @@ async def test_reset_authorization_code_flattened_error_async(): ) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.DomainsGrpcTransport( +@pytest.mark.parametrize( + "request_type", + [ + domains.SearchDomainsRequest, + dict, + ], +) +def test_search_domains_rest(request_type): + client = DomainsClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = DomainsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + + # send a request that will satisfy transcoding + request_init = {"location": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = domains.SearchDomainsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = domains.SearchDomainsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.search_domains(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, domains.SearchDomainsResponse) + + +def test_search_domains_rest_required_fields(request_type=domains.SearchDomainsRequest): + transport_class = transports.DomainsRestTransport + + request_init = {} + request_init["query"] = "" + request_init["location"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, ) + ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.DomainsGrpcTransport( + # verify fields with default values are dropped + assert "query" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).search_domains._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "query" in jsonified_request + assert jsonified_request["query"] == request_init["query"] + + jsonified_request["query"] = "query_value" + jsonified_request["location"] = "location_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).search_domains._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("query",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "query" in jsonified_request + assert jsonified_request["query"] == "query_value" + assert "location" in jsonified_request + assert jsonified_request["location"] == "location_value" + + client = DomainsClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = DomainsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = domains.SearchDomainsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = domains.SearchDomainsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.search_domains(request) + + expected_params = [ + ( + "query", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_search_domains_rest_unset_required_fields(): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.search_domains._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("query",)) + & set( + ( + "query", + "location", + ) ) + ) - # It is an error to provide an api_key and a transport instance. - transport = transports.DomainsGrpcTransport( + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_search_domains_rest_interceptors(null_interceptor): + transport = transports.DomainsRestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DomainsRestInterceptor(), ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = DomainsClient( - client_options=options, - transport=transport, + client = DomainsClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.DomainsRestInterceptor, "post_search_domains" + ) as post, mock.patch.object( + transports.DomainsRestInterceptor, "pre_search_domains" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = domains.SearchDomainsRequest.pb(domains.SearchDomainsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = domains.SearchDomainsResponse.to_json( + domains.SearchDomainsResponse() ) - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = DomainsClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + request = domains.SearchDomainsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = domains.SearchDomainsResponse() - # It is an error to provide scopes and a transport instance. - transport = transports.DomainsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DomainsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + client.search_domains( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) + pre.assert_called_once() + post.assert_called_once() -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.DomainsGrpcTransport( + +def test_search_domains_rest_bad_request( + transport: str = "rest", request_type=domains.SearchDomainsRequest +): + client = DomainsClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - client = DomainsClient(transport=transport) - assert client.transport is transport + # send a request that will satisfy transcoding + request_init = {"location": "projects/sample1/locations/sample2"} + request = request_type(**request_init) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.DomainsGrpcTransport( + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.search_domains(request) + + +def test_search_domains_rest_flattened(): + client = DomainsClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.DomainsGrpcAsyncIOTransport( + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = domains.SearchDomainsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"location": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + location="location_value", + query="query_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = domains.SearchDomainsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.search_domains(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{location=projects/*/locations/*}/registrations:searchDomains" + % client.transport._host, + args[1], + ) + + +def test_search_domains_rest_flattened_error(transport: str = "rest"): + client = DomainsClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - channel = transport.grpc_channel - assert channel + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.search_domains( + domains.SearchDomainsRequest(), + location="location_value", + query="query_value", + ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.DomainsGrpcTransport, - transports.DomainsGrpcAsyncIOTransport, - ], -) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() + +def test_search_domains_rest_error(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) @pytest.mark.parametrize( - "transport_name", + "request_type", [ - "grpc", + domains.RetrieveRegisterParametersRequest, + dict, ], ) -def test_transport_kind(transport_name): - transport = DomainsClient.get_transport_class(transport_name)( +def test_retrieve_register_parameters_rest(request_type): + client = DomainsClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + # send a request that will satisfy transcoding + request_init = {"location": "projects/sample1/locations/sample2"} + request = request_type(**request_init) -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = DomainsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.DomainsGrpcTransport, - ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = domains.RetrieveRegisterParametersResponse() + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = domains.RetrieveRegisterParametersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) -def test_domains_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.DomainsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", - ) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.retrieve_register_parameters(request) + # Establish that the response is the type that we expect. + assert isinstance(response, domains.RetrieveRegisterParametersResponse) -def test_domains_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.domains_v1beta1.services.domains.transports.DomainsTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.DomainsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "search_domains", - "retrieve_register_parameters", - "register_domain", - "retrieve_transfer_parameters", - "transfer_domain", - "list_registrations", - "get_registration", - "update_registration", - "configure_management_settings", - "configure_dns_settings", - "configure_contact_settings", - "export_registration", - "delete_registration", - "retrieve_authorization_code", - "reset_authorization_code", +def test_retrieve_register_parameters_rest_required_fields( + request_type=domains.RetrieveRegisterParametersRequest, +): + transport_class = transports.DomainsRestTransport + + request_init = {} + request_init["domain_name"] = "" + request_init["location"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - with pytest.raises(NotImplementedError): - transport.close() + # verify fields with default values are dropped + assert "domainName" not in jsonified_request - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).retrieve_register_parameters._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - # Catch all for all remaining methods and properties - remainder = [ - "kind", - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() + # verify required fields with default values are now present + assert "domainName" in jsonified_request + assert jsonified_request["domainName"] == request_init["domain_name"] + jsonified_request["domainName"] = "domain_name_value" + jsonified_request["location"] = "location_value" -def test_domains_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).retrieve_register_parameters._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("domain_name",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "domainName" in jsonified_request + assert jsonified_request["domainName"] == "domain_name_value" + assert "location" in jsonified_request + assert jsonified_request["location"] == "location_value" + + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = domains.RetrieveRegisterParametersResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = domains.RetrieveRegisterParametersResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.retrieve_register_parameters(request) + + expected_params = [ + ( + "domainName", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_retrieve_register_parameters_rest_unset_required_fields(): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.retrieve_register_parameters._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("domainName",)) + & set( + ( + "domainName", + "location", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_retrieve_register_parameters_rest_interceptors(null_interceptor): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DomainsRestInterceptor(), + ) + client = DomainsClient(transport=transport) with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch( - "google.cloud.domains_v1beta1.services.domains.transports.DomainsTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DomainsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.DomainsRestInterceptor, "post_retrieve_register_parameters" + ) as post, mock.patch.object( + transports.DomainsRestInterceptor, "pre_retrieve_register_parameters" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = domains.RetrieveRegisterParametersRequest.pb( + domains.RetrieveRegisterParametersRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = domains.RetrieveRegisterParametersResponse.to_json( + domains.RetrieveRegisterParametersResponse() ) - load_creds.assert_called_once_with( - "credentials.json", - scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id="octopus", + + request = domains.RetrieveRegisterParametersRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = domains.RetrieveRegisterParametersResponse() + + client.retrieve_register_parameters( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) + pre.assert_called_once() + post.assert_called_once() -def test_domains_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. + +def test_retrieve_register_parameters_rest_bad_request( + transport: str = "rest", request_type=domains.RetrieveRegisterParametersRequest +): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"location": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.retrieve_register_parameters(request) + + +def test_retrieve_register_parameters_rest_flattened(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = domains.RetrieveRegisterParametersResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"location": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + location="location_value", + domain_name="domain_name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = domains.RetrieveRegisterParametersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.retrieve_register_parameters(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{location=projects/*/locations/*}/registrations:retrieveRegisterParameters" + % client.transport._host, + args[1], + ) + + +def test_retrieve_register_parameters_rest_flattened_error(transport: str = "rest"): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.retrieve_register_parameters( + domains.RetrieveRegisterParametersRequest(), + location="location_value", + domain_name="domain_name_value", + ) + + +def test_retrieve_register_parameters_rest_error(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + domains.RegisterDomainRequest, + dict, + ], +) +def test_register_domain_rest(request_type): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.register_domain(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_register_domain_rest_required_fields( + request_type=domains.RegisterDomainRequest, +): + transport_class = transports.DomainsRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).register_domain._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).register_domain._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.register_domain(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_register_domain_rest_unset_required_fields(): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.register_domain._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "registration", + "yearlyPrice", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_register_domain_rest_interceptors(null_interceptor): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DomainsRestInterceptor(), + ) + client = DomainsClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.DomainsRestInterceptor, "post_register_domain" + ) as post, mock.patch.object( + transports.DomainsRestInterceptor, "pre_register_domain" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = domains.RegisterDomainRequest.pb(domains.RegisterDomainRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = domains.RegisterDomainRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.register_domain( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_register_domain_rest_bad_request( + transport: str = "rest", request_type=domains.RegisterDomainRequest +): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.register_domain(request) + + +def test_register_domain_rest_flattened(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + registration=domains.Registration(name="name_value"), + yearly_price=money_pb2.Money(currency_code="currency_code_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.register_domain(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{parent=projects/*/locations/*}/registrations:register" + % client.transport._host, + args[1], + ) + + +def test_register_domain_rest_flattened_error(transport: str = "rest"): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.register_domain( + domains.RegisterDomainRequest(), + parent="parent_value", + registration=domains.Registration(name="name_value"), + yearly_price=money_pb2.Money(currency_code="currency_code_value"), + ) + + +def test_register_domain_rest_error(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + domains.RetrieveTransferParametersRequest, + dict, + ], +) +def test_retrieve_transfer_parameters_rest(request_type): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"location": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = domains.RetrieveTransferParametersResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = domains.RetrieveTransferParametersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.retrieve_transfer_parameters(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, domains.RetrieveTransferParametersResponse) + + +def test_retrieve_transfer_parameters_rest_required_fields( + request_type=domains.RetrieveTransferParametersRequest, +): + transport_class = transports.DomainsRestTransport + + request_init = {} + request_init["domain_name"] = "" + request_init["location"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + assert "domainName" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).retrieve_transfer_parameters._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "domainName" in jsonified_request + assert jsonified_request["domainName"] == request_init["domain_name"] + + jsonified_request["domainName"] = "domain_name_value" + jsonified_request["location"] = "location_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).retrieve_transfer_parameters._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("domain_name",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "domainName" in jsonified_request + assert jsonified_request["domainName"] == "domain_name_value" + assert "location" in jsonified_request + assert jsonified_request["location"] == "location_value" + + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = domains.RetrieveTransferParametersResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = domains.RetrieveTransferParametersResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.retrieve_transfer_parameters(request) + + expected_params = [ + ( + "domainName", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_retrieve_transfer_parameters_rest_unset_required_fields(): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.retrieve_transfer_parameters._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("domainName",)) + & set( + ( + "domainName", + "location", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_retrieve_transfer_parameters_rest_interceptors(null_interceptor): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DomainsRestInterceptor(), + ) + client = DomainsClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.DomainsRestInterceptor, "post_retrieve_transfer_parameters" + ) as post, mock.patch.object( + transports.DomainsRestInterceptor, "pre_retrieve_transfer_parameters" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = domains.RetrieveTransferParametersRequest.pb( + domains.RetrieveTransferParametersRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = domains.RetrieveTransferParametersResponse.to_json( + domains.RetrieveTransferParametersResponse() + ) + + request = domains.RetrieveTransferParametersRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = domains.RetrieveTransferParametersResponse() + + client.retrieve_transfer_parameters( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_retrieve_transfer_parameters_rest_bad_request( + transport: str = "rest", request_type=domains.RetrieveTransferParametersRequest +): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"location": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.retrieve_transfer_parameters(request) + + +def test_retrieve_transfer_parameters_rest_flattened(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = domains.RetrieveTransferParametersResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"location": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + location="location_value", + domain_name="domain_name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = domains.RetrieveTransferParametersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.retrieve_transfer_parameters(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{location=projects/*/locations/*}/registrations:retrieveTransferParameters" + % client.transport._host, + args[1], + ) + + +def test_retrieve_transfer_parameters_rest_flattened_error(transport: str = "rest"): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.retrieve_transfer_parameters( + domains.RetrieveTransferParametersRequest(), + location="location_value", + domain_name="domain_name_value", + ) + + +def test_retrieve_transfer_parameters_rest_error(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + domains.TransferDomainRequest, + dict, + ], +) +def test_transfer_domain_rest(request_type): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.transfer_domain(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_transfer_domain_rest_required_fields( + request_type=domains.TransferDomainRequest, +): + transport_class = transports.DomainsRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).transfer_domain._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).transfer_domain._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.transfer_domain(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_transfer_domain_rest_unset_required_fields(): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.transfer_domain._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "registration", + "yearlyPrice", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_transfer_domain_rest_interceptors(null_interceptor): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DomainsRestInterceptor(), + ) + client = DomainsClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.DomainsRestInterceptor, "post_transfer_domain" + ) as post, mock.patch.object( + transports.DomainsRestInterceptor, "pre_transfer_domain" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = domains.TransferDomainRequest.pb(domains.TransferDomainRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = domains.TransferDomainRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.transfer_domain( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_transfer_domain_rest_bad_request( + transport: str = "rest", request_type=domains.TransferDomainRequest +): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.transfer_domain(request) + + +def test_transfer_domain_rest_flattened(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + registration=domains.Registration(name="name_value"), + yearly_price=money_pb2.Money(currency_code="currency_code_value"), + authorization_code=domains.AuthorizationCode(code="code_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.transfer_domain(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{parent=projects/*/locations/*}/registrations:transfer" + % client.transport._host, + args[1], + ) + + +def test_transfer_domain_rest_flattened_error(transport: str = "rest"): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.transfer_domain( + domains.TransferDomainRequest(), + parent="parent_value", + registration=domains.Registration(name="name_value"), + yearly_price=money_pb2.Money(currency_code="currency_code_value"), + authorization_code=domains.AuthorizationCode(code="code_value"), + ) + + +def test_transfer_domain_rest_error(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + domains.ListRegistrationsRequest, + dict, + ], +) +def test_list_registrations_rest(request_type): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = domains.ListRegistrationsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = domains.ListRegistrationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_registrations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRegistrationsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_registrations_rest_required_fields( + request_type=domains.ListRegistrationsRequest, +): + transport_class = transports.DomainsRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_registrations._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_registrations._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = domains.ListRegistrationsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = domains.ListRegistrationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_registrations(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_registrations_rest_unset_required_fields(): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_registrations._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_registrations_rest_interceptors(null_interceptor): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DomainsRestInterceptor(), + ) + client = DomainsClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.DomainsRestInterceptor, "post_list_registrations" + ) as post, mock.patch.object( + transports.DomainsRestInterceptor, "pre_list_registrations" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = domains.ListRegistrationsRequest.pb( + domains.ListRegistrationsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = domains.ListRegistrationsResponse.to_json( + domains.ListRegistrationsResponse() + ) + + request = domains.ListRegistrationsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = domains.ListRegistrationsResponse() + + client.list_registrations( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_registrations_rest_bad_request( + transport: str = "rest", request_type=domains.ListRegistrationsRequest +): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_registrations(request) + + +def test_list_registrations_rest_flattened(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = domains.ListRegistrationsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = domains.ListRegistrationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_registrations(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{parent=projects/*/locations/*}/registrations" + % client.transport._host, + args[1], + ) + + +def test_list_registrations_rest_flattened_error(transport: str = "rest"): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_registrations( + domains.ListRegistrationsRequest(), + parent="parent_value", + ) + + +def test_list_registrations_rest_pager(transport: str = "rest"): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + domains.ListRegistrationsResponse( + registrations=[ + domains.Registration(), + domains.Registration(), + domains.Registration(), + ], + next_page_token="abc", + ), + domains.ListRegistrationsResponse( + registrations=[], + next_page_token="def", + ), + domains.ListRegistrationsResponse( + registrations=[ + domains.Registration(), + ], + next_page_token="ghi", + ), + domains.ListRegistrationsResponse( + registrations=[ + domains.Registration(), + domains.Registration(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(domains.ListRegistrationsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_registrations(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, domains.Registration) for i in results) + + pages = list(client.list_registrations(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + domains.GetRegistrationRequest, + dict, + ], +) +def test_get_registration_rest(request_type): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/registrations/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = domains.Registration( + name="name_value", + domain_name="domain_name_value", + state=domains.Registration.State.REGISTRATION_PENDING, + issues=[domains.Registration.Issue.CONTACT_SUPPORT], + supported_privacy=[domains.ContactPrivacy.PUBLIC_CONTACT_DATA], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = domains.Registration.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_registration(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, domains.Registration) + assert response.name == "name_value" + assert response.domain_name == "domain_name_value" + assert response.state == domains.Registration.State.REGISTRATION_PENDING + assert response.issues == [domains.Registration.Issue.CONTACT_SUPPORT] + assert response.supported_privacy == [domains.ContactPrivacy.PUBLIC_CONTACT_DATA] + + +def test_get_registration_rest_required_fields( + request_type=domains.GetRegistrationRequest, +): + transport_class = transports.DomainsRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_registration._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_registration._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = domains.Registration() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = domains.Registration.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_registration(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_registration_rest_unset_required_fields(): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_registration._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_registration_rest_interceptors(null_interceptor): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DomainsRestInterceptor(), + ) + client = DomainsClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.DomainsRestInterceptor, "post_get_registration" + ) as post, mock.patch.object( + transports.DomainsRestInterceptor, "pre_get_registration" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = domains.GetRegistrationRequest.pb(domains.GetRegistrationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = domains.Registration.to_json(domains.Registration()) + + request = domains.GetRegistrationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = domains.Registration() + + client.get_registration( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_registration_rest_bad_request( + transport: str = "rest", request_type=domains.GetRegistrationRequest +): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/registrations/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_registration(request) + + +def test_get_registration_rest_flattened(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = domains.Registration() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/registrations/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = domains.Registration.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_registration(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{name=projects/*/locations/*/registrations/*}" + % client.transport._host, + args[1], + ) + + +def test_get_registration_rest_flattened_error(transport: str = "rest"): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_registration( + domains.GetRegistrationRequest(), + name="name_value", + ) + + +def test_get_registration_rest_error(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + domains.UpdateRegistrationRequest, + dict, + ], +) +def test_update_registration_rest(request_type): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "registration": { + "name": "projects/sample1/locations/sample2/registrations/sample3" + } + } + request_init["registration"] = { + "name": "projects/sample1/locations/sample2/registrations/sample3", + "domain_name": "domain_name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "expire_time": {}, + "state": 1, + "issues": [1], + "labels": {}, + "management_settings": {"renewal_method": 1, "transfer_lock_state": 1}, + "dns_settings": { + "custom_dns": { + "name_servers": ["name_servers_value1", "name_servers_value2"], + "ds_records": [ + { + "key_tag": 740, + "algorithm": 1, + "digest_type": 1, + "digest": "digest_value", + } + ], + }, + "google_domains_dns": { + "name_servers": ["name_servers_value1", "name_servers_value2"], + "ds_state": 1, + "ds_records": {}, + }, + "glue_records": [ + { + "host_name": "host_name_value", + "ipv4_addresses": [ + "ipv4_addresses_value1", + "ipv4_addresses_value2", + ], + "ipv6_addresses": [ + "ipv6_addresses_value1", + "ipv6_addresses_value2", + ], + } + ], + }, + "contact_settings": { + "privacy": 1, + "registrant_contact": { + "postal_address": { + "revision": 879, + "region_code": "region_code_value", + "language_code": "language_code_value", + "postal_code": "postal_code_value", + "sorting_code": "sorting_code_value", + "administrative_area": "administrative_area_value", + "locality": "locality_value", + "sublocality": "sublocality_value", + "address_lines": ["address_lines_value1", "address_lines_value2"], + "recipients": ["recipients_value1", "recipients_value2"], + "organization": "organization_value", + }, + "email": "email_value", + "phone_number": "phone_number_value", + "fax_number": "fax_number_value", + }, + "admin_contact": {}, + "technical_contact": {}, + }, + "pending_contact_settings": {}, + "supported_privacy": [1], + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_registration(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_registration_rest_required_fields( + request_type=domains.UpdateRegistrationRequest, +): + transport_class = transports.DomainsRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_registration._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_registration._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_registration(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_registration_rest_unset_required_fields(): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_registration._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("updateMask",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_registration_rest_interceptors(null_interceptor): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DomainsRestInterceptor(), + ) + client = DomainsClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.DomainsRestInterceptor, "post_update_registration" + ) as post, mock.patch.object( + transports.DomainsRestInterceptor, "pre_update_registration" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = domains.UpdateRegistrationRequest.pb( + domains.UpdateRegistrationRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = domains.UpdateRegistrationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_registration( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_registration_rest_bad_request( + transport: str = "rest", request_type=domains.UpdateRegistrationRequest +): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "registration": { + "name": "projects/sample1/locations/sample2/registrations/sample3" + } + } + request_init["registration"] = { + "name": "projects/sample1/locations/sample2/registrations/sample3", + "domain_name": "domain_name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "expire_time": {}, + "state": 1, + "issues": [1], + "labels": {}, + "management_settings": {"renewal_method": 1, "transfer_lock_state": 1}, + "dns_settings": { + "custom_dns": { + "name_servers": ["name_servers_value1", "name_servers_value2"], + "ds_records": [ + { + "key_tag": 740, + "algorithm": 1, + "digest_type": 1, + "digest": "digest_value", + } + ], + }, + "google_domains_dns": { + "name_servers": ["name_servers_value1", "name_servers_value2"], + "ds_state": 1, + "ds_records": {}, + }, + "glue_records": [ + { + "host_name": "host_name_value", + "ipv4_addresses": [ + "ipv4_addresses_value1", + "ipv4_addresses_value2", + ], + "ipv6_addresses": [ + "ipv6_addresses_value1", + "ipv6_addresses_value2", + ], + } + ], + }, + "contact_settings": { + "privacy": 1, + "registrant_contact": { + "postal_address": { + "revision": 879, + "region_code": "region_code_value", + "language_code": "language_code_value", + "postal_code": "postal_code_value", + "sorting_code": "sorting_code_value", + "administrative_area": "administrative_area_value", + "locality": "locality_value", + "sublocality": "sublocality_value", + "address_lines": ["address_lines_value1", "address_lines_value2"], + "recipients": ["recipients_value1", "recipients_value2"], + "organization": "organization_value", + }, + "email": "email_value", + "phone_number": "phone_number_value", + "fax_number": "fax_number_value", + }, + "admin_contact": {}, + "technical_contact": {}, + }, + "pending_contact_settings": {}, + "supported_privacy": [1], + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_registration(request) + + +def test_update_registration_rest_flattened(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "registration": { + "name": "projects/sample1/locations/sample2/registrations/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + registration=domains.Registration(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_registration(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{registration.name=projects/*/locations/*/registrations/*}" + % client.transport._host, + args[1], + ) + + +def test_update_registration_rest_flattened_error(transport: str = "rest"): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_registration( + domains.UpdateRegistrationRequest(), + registration=domains.Registration(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_registration_rest_error(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + domains.ConfigureManagementSettingsRequest, + dict, + ], +) +def test_configure_management_settings_rest(request_type): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "registration": "projects/sample1/locations/sample2/registrations/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.configure_management_settings(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_configure_management_settings_rest_required_fields( + request_type=domains.ConfigureManagementSettingsRequest, +): + transport_class = transports.DomainsRestTransport + + request_init = {} + request_init["registration"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).configure_management_settings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["registration"] = "registration_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).configure_management_settings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "registration" in jsonified_request + assert jsonified_request["registration"] == "registration_value" + + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.configure_management_settings(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_configure_management_settings_rest_unset_required_fields(): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.configure_management_settings._get_unset_required_fields( + {} + ) + assert set(unset_fields) == ( + set(()) + & set( + ( + "registration", + "updateMask", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_configure_management_settings_rest_interceptors(null_interceptor): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DomainsRestInterceptor(), + ) + client = DomainsClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.DomainsRestInterceptor, "post_configure_management_settings" + ) as post, mock.patch.object( + transports.DomainsRestInterceptor, "pre_configure_management_settings" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = domains.ConfigureManagementSettingsRequest.pb( + domains.ConfigureManagementSettingsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = domains.ConfigureManagementSettingsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.configure_management_settings( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_configure_management_settings_rest_bad_request( + transport: str = "rest", request_type=domains.ConfigureManagementSettingsRequest +): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "registration": "projects/sample1/locations/sample2/registrations/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.configure_management_settings(request) + + +def test_configure_management_settings_rest_flattened(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "registration": "projects/sample1/locations/sample2/registrations/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + registration="registration_value", + management_settings=domains.ManagementSettings( + renewal_method=domains.ManagementSettings.RenewalMethod.AUTOMATIC_RENEWAL + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.configure_management_settings(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{registration=projects/*/locations/*/registrations/*}:configureManagementSettings" + % client.transport._host, + args[1], + ) + + +def test_configure_management_settings_rest_flattened_error(transport: str = "rest"): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.configure_management_settings( + domains.ConfigureManagementSettingsRequest(), + registration="registration_value", + management_settings=domains.ManagementSettings( + renewal_method=domains.ManagementSettings.RenewalMethod.AUTOMATIC_RENEWAL + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_configure_management_settings_rest_error(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + domains.ConfigureDnsSettingsRequest, + dict, + ], +) +def test_configure_dns_settings_rest(request_type): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "registration": "projects/sample1/locations/sample2/registrations/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.configure_dns_settings(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_configure_dns_settings_rest_required_fields( + request_type=domains.ConfigureDnsSettingsRequest, +): + transport_class = transports.DomainsRestTransport + + request_init = {} + request_init["registration"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).configure_dns_settings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["registration"] = "registration_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).configure_dns_settings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "registration" in jsonified_request + assert jsonified_request["registration"] == "registration_value" + + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.configure_dns_settings(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_configure_dns_settings_rest_unset_required_fields(): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.configure_dns_settings._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "registration", + "updateMask", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_configure_dns_settings_rest_interceptors(null_interceptor): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DomainsRestInterceptor(), + ) + client = DomainsClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.DomainsRestInterceptor, "post_configure_dns_settings" + ) as post, mock.patch.object( + transports.DomainsRestInterceptor, "pre_configure_dns_settings" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = domains.ConfigureDnsSettingsRequest.pb( + domains.ConfigureDnsSettingsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = domains.ConfigureDnsSettingsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.configure_dns_settings( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_configure_dns_settings_rest_bad_request( + transport: str = "rest", request_type=domains.ConfigureDnsSettingsRequest +): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "registration": "projects/sample1/locations/sample2/registrations/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.configure_dns_settings(request) + + +def test_configure_dns_settings_rest_flattened(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "registration": "projects/sample1/locations/sample2/registrations/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + registration="registration_value", + dns_settings=domains.DnsSettings( + custom_dns=domains.DnsSettings.CustomDns( + name_servers=["name_servers_value"] + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.configure_dns_settings(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{registration=projects/*/locations/*/registrations/*}:configureDnsSettings" + % client.transport._host, + args[1], + ) + + +def test_configure_dns_settings_rest_flattened_error(transport: str = "rest"): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.configure_dns_settings( + domains.ConfigureDnsSettingsRequest(), + registration="registration_value", + dns_settings=domains.DnsSettings( + custom_dns=domains.DnsSettings.CustomDns( + name_servers=["name_servers_value"] + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_configure_dns_settings_rest_error(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + domains.ConfigureContactSettingsRequest, + dict, + ], +) +def test_configure_contact_settings_rest(request_type): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "registration": "projects/sample1/locations/sample2/registrations/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.configure_contact_settings(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_configure_contact_settings_rest_required_fields( + request_type=domains.ConfigureContactSettingsRequest, +): + transport_class = transports.DomainsRestTransport + + request_init = {} + request_init["registration"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).configure_contact_settings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["registration"] = "registration_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).configure_contact_settings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "registration" in jsonified_request + assert jsonified_request["registration"] == "registration_value" + + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.configure_contact_settings(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_configure_contact_settings_rest_unset_required_fields(): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.configure_contact_settings._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "registration", + "updateMask", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_configure_contact_settings_rest_interceptors(null_interceptor): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DomainsRestInterceptor(), + ) + client = DomainsClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.DomainsRestInterceptor, "post_configure_contact_settings" + ) as post, mock.patch.object( + transports.DomainsRestInterceptor, "pre_configure_contact_settings" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = domains.ConfigureContactSettingsRequest.pb( + domains.ConfigureContactSettingsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = domains.ConfigureContactSettingsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.configure_contact_settings( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_configure_contact_settings_rest_bad_request( + transport: str = "rest", request_type=domains.ConfigureContactSettingsRequest +): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "registration": "projects/sample1/locations/sample2/registrations/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.configure_contact_settings(request) + + +def test_configure_contact_settings_rest_flattened(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "registration": "projects/sample1/locations/sample2/registrations/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + registration="registration_value", + contact_settings=domains.ContactSettings( + privacy=domains.ContactPrivacy.PUBLIC_CONTACT_DATA + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.configure_contact_settings(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{registration=projects/*/locations/*/registrations/*}:configureContactSettings" + % client.transport._host, + args[1], + ) + + +def test_configure_contact_settings_rest_flattened_error(transport: str = "rest"): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.configure_contact_settings( + domains.ConfigureContactSettingsRequest(), + registration="registration_value", + contact_settings=domains.ContactSettings( + privacy=domains.ContactPrivacy.PUBLIC_CONTACT_DATA + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_configure_contact_settings_rest_error(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + domains.ExportRegistrationRequest, + dict, + ], +) +def test_export_registration_rest(request_type): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/registrations/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.export_registration(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_export_registration_rest_required_fields( + request_type=domains.ExportRegistrationRequest, +): + transport_class = transports.DomainsRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).export_registration._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).export_registration._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.export_registration(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_export_registration_rest_unset_required_fields(): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.export_registration._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_export_registration_rest_interceptors(null_interceptor): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DomainsRestInterceptor(), + ) + client = DomainsClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.DomainsRestInterceptor, "post_export_registration" + ) as post, mock.patch.object( + transports.DomainsRestInterceptor, "pre_export_registration" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = domains.ExportRegistrationRequest.pb( + domains.ExportRegistrationRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = domains.ExportRegistrationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.export_registration( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_export_registration_rest_bad_request( + transport: str = "rest", request_type=domains.ExportRegistrationRequest +): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/registrations/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.export_registration(request) + + +def test_export_registration_rest_flattened(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/registrations/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.export_registration(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{name=projects/*/locations/*/registrations/*}:export" + % client.transport._host, + args[1], + ) + + +def test_export_registration_rest_flattened_error(transport: str = "rest"): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.export_registration( + domains.ExportRegistrationRequest(), + name="name_value", + ) + + +def test_export_registration_rest_error(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + domains.DeleteRegistrationRequest, + dict, + ], +) +def test_delete_registration_rest(request_type): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/registrations/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_registration(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_registration_rest_required_fields( + request_type=domains.DeleteRegistrationRequest, +): + transport_class = transports.DomainsRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_registration._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_registration._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_registration(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_registration_rest_unset_required_fields(): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_registration._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_registration_rest_interceptors(null_interceptor): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DomainsRestInterceptor(), + ) + client = DomainsClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.DomainsRestInterceptor, "post_delete_registration" + ) as post, mock.patch.object( + transports.DomainsRestInterceptor, "pre_delete_registration" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = domains.DeleteRegistrationRequest.pb( + domains.DeleteRegistrationRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = domains.DeleteRegistrationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_registration( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_registration_rest_bad_request( + transport: str = "rest", request_type=domains.DeleteRegistrationRequest +): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/registrations/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_registration(request) + + +def test_delete_registration_rest_flattened(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/registrations/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_registration(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{name=projects/*/locations/*/registrations/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_registration_rest_flattened_error(transport: str = "rest"): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_registration( + domains.DeleteRegistrationRequest(), + name="name_value", + ) + + +def test_delete_registration_rest_error(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + domains.RetrieveAuthorizationCodeRequest, + dict, + ], +) +def test_retrieve_authorization_code_rest(request_type): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "registration": "projects/sample1/locations/sample2/registrations/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = domains.AuthorizationCode( + code="code_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = domains.AuthorizationCode.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.retrieve_authorization_code(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, domains.AuthorizationCode) + assert response.code == "code_value" + + +def test_retrieve_authorization_code_rest_required_fields( + request_type=domains.RetrieveAuthorizationCodeRequest, +): + transport_class = transports.DomainsRestTransport + + request_init = {} + request_init["registration"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).retrieve_authorization_code._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["registration"] = "registration_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).retrieve_authorization_code._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "registration" in jsonified_request + assert jsonified_request["registration"] == "registration_value" + + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = domains.AuthorizationCode() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = domains.AuthorizationCode.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.retrieve_authorization_code(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_retrieve_authorization_code_rest_unset_required_fields(): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.retrieve_authorization_code._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("registration",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_retrieve_authorization_code_rest_interceptors(null_interceptor): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DomainsRestInterceptor(), + ) + client = DomainsClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.DomainsRestInterceptor, "post_retrieve_authorization_code" + ) as post, mock.patch.object( + transports.DomainsRestInterceptor, "pre_retrieve_authorization_code" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = domains.RetrieveAuthorizationCodeRequest.pb( + domains.RetrieveAuthorizationCodeRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = domains.AuthorizationCode.to_json( + domains.AuthorizationCode() + ) + + request = domains.RetrieveAuthorizationCodeRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = domains.AuthorizationCode() + + client.retrieve_authorization_code( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_retrieve_authorization_code_rest_bad_request( + transport: str = "rest", request_type=domains.RetrieveAuthorizationCodeRequest +): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "registration": "projects/sample1/locations/sample2/registrations/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.retrieve_authorization_code(request) + + +def test_retrieve_authorization_code_rest_flattened(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = domains.AuthorizationCode() + + # get arguments that satisfy an http rule for this method + sample_request = { + "registration": "projects/sample1/locations/sample2/registrations/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + registration="registration_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = domains.AuthorizationCode.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.retrieve_authorization_code(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{registration=projects/*/locations/*/registrations/*}:retrieveAuthorizationCode" + % client.transport._host, + args[1], + ) + + +def test_retrieve_authorization_code_rest_flattened_error(transport: str = "rest"): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.retrieve_authorization_code( + domains.RetrieveAuthorizationCodeRequest(), + registration="registration_value", + ) + + +def test_retrieve_authorization_code_rest_error(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + domains.ResetAuthorizationCodeRequest, + dict, + ], +) +def test_reset_authorization_code_rest(request_type): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "registration": "projects/sample1/locations/sample2/registrations/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = domains.AuthorizationCode( + code="code_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = domains.AuthorizationCode.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.reset_authorization_code(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, domains.AuthorizationCode) + assert response.code == "code_value" + + +def test_reset_authorization_code_rest_required_fields( + request_type=domains.ResetAuthorizationCodeRequest, +): + transport_class = transports.DomainsRestTransport + + request_init = {} + request_init["registration"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).reset_authorization_code._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["registration"] = "registration_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).reset_authorization_code._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "registration" in jsonified_request + assert jsonified_request["registration"] == "registration_value" + + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = domains.AuthorizationCode() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = domains.AuthorizationCode.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.reset_authorization_code(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_reset_authorization_code_rest_unset_required_fields(): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.reset_authorization_code._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("registration",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_reset_authorization_code_rest_interceptors(null_interceptor): + transport = transports.DomainsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DomainsRestInterceptor(), + ) + client = DomainsClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.DomainsRestInterceptor, "post_reset_authorization_code" + ) as post, mock.patch.object( + transports.DomainsRestInterceptor, "pre_reset_authorization_code" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = domains.ResetAuthorizationCodeRequest.pb( + domains.ResetAuthorizationCodeRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = domains.AuthorizationCode.to_json( + domains.AuthorizationCode() + ) + + request = domains.ResetAuthorizationCodeRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = domains.AuthorizationCode() + + client.reset_authorization_code( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_reset_authorization_code_rest_bad_request( + transport: str = "rest", request_type=domains.ResetAuthorizationCodeRequest +): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "registration": "projects/sample1/locations/sample2/registrations/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.reset_authorization_code(request) + + +def test_reset_authorization_code_rest_flattened(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = domains.AuthorizationCode() + + # get arguments that satisfy an http rule for this method + sample_request = { + "registration": "projects/sample1/locations/sample2/registrations/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + registration="registration_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = domains.AuthorizationCode.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.reset_authorization_code(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{registration=projects/*/locations/*/registrations/*}:resetAuthorizationCode" + % client.transport._host, + args[1], + ) + + +def test_reset_authorization_code_rest_flattened_error(transport: str = "rest"): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.reset_authorization_code( + domains.ResetAuthorizationCodeRequest(), + registration="registration_value", + ) + + +def test_reset_authorization_code_rest_error(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.DomainsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.DomainsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DomainsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.DomainsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = DomainsClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = DomainsClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.DomainsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DomainsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.DomainsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = DomainsClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.DomainsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.DomainsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.DomainsGrpcTransport, + transports.DomainsGrpcAsyncIOTransport, + transports.DomainsRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "rest", + ], +) +def test_transport_kind(transport_name): + transport = DomainsClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.DomainsGrpcTransport, + ) + + +def test_domains_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.DomainsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_domains_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.domains_v1beta1.services.domains.transports.DomainsTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.DomainsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "search_domains", + "retrieve_register_parameters", + "register_domain", + "retrieve_transfer_parameters", + "transfer_domain", + "list_registrations", + "get_registration", + "update_registration", + "configure_management_settings", + "configure_dns_settings", + "configure_contact_settings", + "export_registration", + "delete_registration", + "retrieve_authorization_code", + "reset_authorization_code", + ) + for method in methods: + 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): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_domains_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.domains_v1beta1.services.domains.transports.DomainsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DomainsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_domains_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.domains_v1beta1.services.domains.transports.DomainsTransport._prep_wrapped_messages" ) as Transport: @@ -4877,6 +9258,7 @@ def test_domains_transport_auth_adc(transport_class): [ transports.DomainsGrpcTransport, transports.DomainsGrpcAsyncIOTransport, + transports.DomainsRestTransport, ], ) def test_domains_transport_auth_gdch_credentials(transport_class): @@ -4971,11 +9353,40 @@ def test_domains_grpc_transport_client_cert_source_for_mtls(transport_class): ) +def test_domains_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.DomainsRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_domains_rest_lro_client(): + client = DomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + @pytest.mark.parametrize( "transport_name", [ "grpc", "grpc_asyncio", + "rest", ], ) def test_domains_host_no_port(transport_name): @@ -4986,7 +9397,11 @@ def test_domains_host_no_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("domains.googleapis.com:443") + assert client.transport._host == ( + "domains.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://domains.googleapis.com" + ) @pytest.mark.parametrize( @@ -4994,6 +9409,7 @@ def test_domains_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_domains_host_with_port(transport_name): @@ -5004,7 +9420,75 @@ def test_domains_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("domains.googleapis.com:8000") + assert client.transport._host == ( + "domains.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://domains.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_domains_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = DomainsClient( + credentials=creds1, + transport=transport_name, + ) + client2 = DomainsClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.search_domains._session + session2 = client2.transport.search_domains._session + assert session1 != session2 + session1 = client1.transport.retrieve_register_parameters._session + session2 = client2.transport.retrieve_register_parameters._session + assert session1 != session2 + session1 = client1.transport.register_domain._session + session2 = client2.transport.register_domain._session + assert session1 != session2 + session1 = client1.transport.retrieve_transfer_parameters._session + session2 = client2.transport.retrieve_transfer_parameters._session + assert session1 != session2 + session1 = client1.transport.transfer_domain._session + session2 = client2.transport.transfer_domain._session + assert session1 != session2 + session1 = client1.transport.list_registrations._session + session2 = client2.transport.list_registrations._session + assert session1 != session2 + session1 = client1.transport.get_registration._session + session2 = client2.transport.get_registration._session + assert session1 != session2 + session1 = client1.transport.update_registration._session + session2 = client2.transport.update_registration._session + assert session1 != session2 + session1 = client1.transport.configure_management_settings._session + session2 = client2.transport.configure_management_settings._session + assert session1 != session2 + session1 = client1.transport.configure_dns_settings._session + session2 = client2.transport.configure_dns_settings._session + assert session1 != session2 + session1 = client1.transport.configure_contact_settings._session + session2 = client2.transport.configure_contact_settings._session + assert session1 != session2 + session1 = client1.transport.export_registration._session + session2 = client2.transport.export_registration._session + assert session1 != session2 + session1 = client1.transport.delete_registration._session + session2 = client2.transport.delete_registration._session + assert session1 != session2 + session1 = client1.transport.retrieve_authorization_code._session + session2 = client2.transport.retrieve_authorization_code._session + assert session1 != session2 + session1 = client1.transport.reset_authorization_code._session + session2 = client2.transport.reset_authorization_code._session + assert session1 != session2 def test_domains_grpc_transport_channel(): @@ -5329,6 +9813,7 @@ async def test_transport_close_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -5346,6 +9831,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: