diff --git a/google/cloud/essential_contacts_v1/gapic_metadata.json b/google/cloud/essential_contacts_v1/gapic_metadata.json index 5f48f80..e01eb19 100644 --- a/google/cloud/essential_contacts_v1/gapic_metadata.json +++ b/google/cloud/essential_contacts_v1/gapic_metadata.json @@ -86,6 +86,46 @@ ] } } + }, + "rest": { + "libraryClient": "EssentialContactsServiceClient", + "rpcs": { + "ComputeContacts": { + "methods": [ + "compute_contacts" + ] + }, + "CreateContact": { + "methods": [ + "create_contact" + ] + }, + "DeleteContact": { + "methods": [ + "delete_contact" + ] + }, + "GetContact": { + "methods": [ + "get_contact" + ] + }, + "ListContacts": { + "methods": [ + "list_contacts" + ] + }, + "SendTestMessage": { + "methods": [ + "send_test_message" + ] + }, + "UpdateContact": { + "methods": [ + "update_contact" + ] + } + } } } } diff --git a/google/cloud/essential_contacts_v1/services/essential_contacts_service/client.py b/google/cloud/essential_contacts_v1/services/essential_contacts_service/client.py index 9cda333..dbc4d89 100644 --- a/google/cloud/essential_contacts_v1/services/essential_contacts_service/client.py +++ b/google/cloud/essential_contacts_v1/services/essential_contacts_service/client.py @@ -57,6 +57,7 @@ from .transports.base import DEFAULT_CLIENT_INFO, EssentialContactsServiceTransport from .transports.grpc import EssentialContactsServiceGrpcTransport from .transports.grpc_asyncio import EssentialContactsServiceGrpcAsyncIOTransport +from .transports.rest import EssentialContactsServiceRestTransport class EssentialContactsServiceClientMeta(type): @@ -72,6 +73,7 @@ class EssentialContactsServiceClientMeta(type): ) # type: Dict[str, Type[EssentialContactsServiceTransport]] _transport_registry["grpc"] = EssentialContactsServiceGrpcTransport _transport_registry["grpc_asyncio"] = EssentialContactsServiceGrpcAsyncIOTransport + _transport_registry["rest"] = EssentialContactsServiceRestTransport def get_transport_class( cls, diff --git a/google/cloud/essential_contacts_v1/services/essential_contacts_service/transports/__init__.py b/google/cloud/essential_contacts_v1/services/essential_contacts_service/transports/__init__.py index 209c458..1177cd3 100644 --- a/google/cloud/essential_contacts_v1/services/essential_contacts_service/transports/__init__.py +++ b/google/cloud/essential_contacts_v1/services/essential_contacts_service/transports/__init__.py @@ -19,6 +19,10 @@ from .base import EssentialContactsServiceTransport from .grpc import EssentialContactsServiceGrpcTransport from .grpc_asyncio import EssentialContactsServiceGrpcAsyncIOTransport +from .rest import ( + EssentialContactsServiceRestInterceptor, + EssentialContactsServiceRestTransport, +) # Compile a registry of transports. _transport_registry = ( @@ -26,9 +30,12 @@ ) # type: Dict[str, Type[EssentialContactsServiceTransport]] _transport_registry["grpc"] = EssentialContactsServiceGrpcTransport _transport_registry["grpc_asyncio"] = EssentialContactsServiceGrpcAsyncIOTransport +_transport_registry["rest"] = EssentialContactsServiceRestTransport __all__ = ( "EssentialContactsServiceTransport", "EssentialContactsServiceGrpcTransport", "EssentialContactsServiceGrpcAsyncIOTransport", + "EssentialContactsServiceRestTransport", + "EssentialContactsServiceRestInterceptor", ) diff --git a/google/cloud/essential_contacts_v1/services/essential_contacts_service/transports/rest.py b/google/cloud/essential_contacts_v1/services/essential_contacts_service/transports/rest.py new file mode 100644 index 0000000..0afa7e4 --- /dev/null +++ b/google/cloud/essential_contacts_v1/services/essential_contacts_service/transports/rest.py @@ -0,0 +1,1099 @@ +# -*- 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, 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.protobuf import empty_pb2 # type: ignore + +from google.cloud.essential_contacts_v1.types import service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .base import EssentialContactsServiceTransport + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class EssentialContactsServiceRestInterceptor: + """Interceptor for EssentialContactsService. + + 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 EssentialContactsServiceRestTransport. + + .. code-block:: python + class MyCustomEssentialContactsServiceInterceptor(EssentialContactsServiceRestInterceptor): + def pre_compute_contacts(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_compute_contacts(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_contact(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_contact(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_contact(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_contact(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_contact(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_contacts(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_contacts(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_send_test_message(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_update_contact(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_contact(self, response): + logging.log(f"Received response: {response}") + return response + + transport = EssentialContactsServiceRestTransport(interceptor=MyCustomEssentialContactsServiceInterceptor()) + client = EssentialContactsServiceClient(transport=transport) + + + """ + + def pre_compute_contacts( + self, + request: service.ComputeContactsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.ComputeContactsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for compute_contacts + + Override in a subclass to manipulate the request or metadata + before they are sent to the EssentialContactsService server. + """ + return request, metadata + + def post_compute_contacts( + self, response: service.ComputeContactsResponse + ) -> service.ComputeContactsResponse: + """Post-rpc interceptor for compute_contacts + + Override in a subclass to manipulate the response + after it is returned by the EssentialContactsService server but before + it is returned to user code. + """ + return response + + def pre_create_contact( + self, request: service.CreateContactRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[service.CreateContactRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_contact + + Override in a subclass to manipulate the request or metadata + before they are sent to the EssentialContactsService server. + """ + return request, metadata + + def post_create_contact(self, response: service.Contact) -> service.Contact: + """Post-rpc interceptor for create_contact + + Override in a subclass to manipulate the response + after it is returned by the EssentialContactsService server but before + it is returned to user code. + """ + return response + + def pre_delete_contact( + self, request: service.DeleteContactRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[service.DeleteContactRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_contact + + Override in a subclass to manipulate the request or metadata + before they are sent to the EssentialContactsService server. + """ + return request, metadata + + def pre_get_contact( + self, request: service.GetContactRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[service.GetContactRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_contact + + Override in a subclass to manipulate the request or metadata + before they are sent to the EssentialContactsService server. + """ + return request, metadata + + def post_get_contact(self, response: service.Contact) -> service.Contact: + """Post-rpc interceptor for get_contact + + Override in a subclass to manipulate the response + after it is returned by the EssentialContactsService server but before + it is returned to user code. + """ + return response + + def pre_list_contacts( + self, request: service.ListContactsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[service.ListContactsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_contacts + + Override in a subclass to manipulate the request or metadata + before they are sent to the EssentialContactsService server. + """ + return request, metadata + + def post_list_contacts( + self, response: service.ListContactsResponse + ) -> service.ListContactsResponse: + """Post-rpc interceptor for list_contacts + + Override in a subclass to manipulate the response + after it is returned by the EssentialContactsService server but before + it is returned to user code. + """ + return response + + def pre_send_test_message( + self, + request: service.SendTestMessageRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.SendTestMessageRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for send_test_message + + Override in a subclass to manipulate the request or metadata + before they are sent to the EssentialContactsService server. + """ + return request, metadata + + def pre_update_contact( + self, request: service.UpdateContactRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[service.UpdateContactRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_contact + + Override in a subclass to manipulate the request or metadata + before they are sent to the EssentialContactsService server. + """ + return request, metadata + + def post_update_contact(self, response: service.Contact) -> service.Contact: + """Post-rpc interceptor for update_contact + + Override in a subclass to manipulate the response + after it is returned by the EssentialContactsService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class EssentialContactsServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: EssentialContactsServiceRestInterceptor + + +class EssentialContactsServiceRestTransport(EssentialContactsServiceTransport): + """REST backend transport for EssentialContactsService. + + Manages contacts for important Google Cloud notifications. + + 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 = "essentialcontacts.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[EssentialContactsServiceRestInterceptor] = 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 + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or EssentialContactsServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _ComputeContacts(EssentialContactsServiceRestStub): + def __hash__(self): + return hash("ComputeContacts") + + __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: service.ComputeContactsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.ComputeContactsResponse: + r"""Call the compute contacts method over HTTP. + + Args: + request (~.service.ComputeContactsRequest): + The request object. Request message for the + ComputeContacts 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: + ~.service.ComputeContactsResponse: + Response message for the + ComputeContacts method. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*}/contacts:compute", + }, + { + "method": "get", + "uri": "/v1/{parent=folders/*}/contacts:compute", + }, + { + "method": "get", + "uri": "/v1/{parent=organizations/*}/contacts:compute", + }, + ] + request, metadata = self._interceptor.pre_compute_contacts( + request, metadata + ) + pb_request = service.ComputeContactsRequest.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 = service.ComputeContactsResponse() + pb_resp = service.ComputeContactsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_compute_contacts(resp) + return resp + + class _CreateContact(EssentialContactsServiceRestStub): + def __hash__(self): + return hash("CreateContact") + + __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: service.CreateContactRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.Contact: + r"""Call the create contact method over HTTP. + + Args: + request (~.service.CreateContactRequest): + The request object. Request message for the CreateContact + 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: + ~.service.Contact: + A contact that will receive + notifications from Google Cloud. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*}/contacts", + "body": "contact", + }, + { + "method": "post", + "uri": "/v1/{parent=folders/*}/contacts", + "body": "contact", + }, + { + "method": "post", + "uri": "/v1/{parent=organizations/*}/contacts", + "body": "contact", + }, + ] + request, metadata = self._interceptor.pre_create_contact(request, metadata) + pb_request = service.CreateContactRequest.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 = service.Contact() + pb_resp = service.Contact.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_contact(resp) + return resp + + class _DeleteContact(EssentialContactsServiceRestStub): + def __hash__(self): + return hash("DeleteContact") + + __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: service.DeleteContactRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ): + r"""Call the delete contact method over HTTP. + + Args: + request (~.service.DeleteContactRequest): + The request object. Request message for the DeleteContact + 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. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/contacts/*}", + }, + { + "method": "delete", + "uri": "/v1/{name=folders/*/contacts/*}", + }, + { + "method": "delete", + "uri": "/v1/{name=organizations/*/contacts/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_contact(request, metadata) + pb_request = service.DeleteContactRequest.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) + + class _GetContact(EssentialContactsServiceRestStub): + def __hash__(self): + return hash("GetContact") + + __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: service.GetContactRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.Contact: + r"""Call the get contact method over HTTP. + + Args: + request (~.service.GetContactRequest): + The request object. Request message for the GetContact + 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: + ~.service.Contact: + A contact that will receive + notifications from Google Cloud. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/contacts/*}", + }, + { + "method": "get", + "uri": "/v1/{name=folders/*/contacts/*}", + }, + { + "method": "get", + "uri": "/v1/{name=organizations/*/contacts/*}", + }, + ] + request, metadata = self._interceptor.pre_get_contact(request, metadata) + pb_request = service.GetContactRequest.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 = service.Contact() + pb_resp = service.Contact.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_contact(resp) + return resp + + class _ListContacts(EssentialContactsServiceRestStub): + def __hash__(self): + return hash("ListContacts") + + __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: service.ListContactsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.ListContactsResponse: + r"""Call the list contacts method over HTTP. + + Args: + request (~.service.ListContactsRequest): + The request object. Request message for the ListContacts + 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: + ~.service.ListContactsResponse: + Response message for the ListContacts + method. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*}/contacts", + }, + { + "method": "get", + "uri": "/v1/{parent=folders/*}/contacts", + }, + { + "method": "get", + "uri": "/v1/{parent=organizations/*}/contacts", + }, + ] + request, metadata = self._interceptor.pre_list_contacts(request, metadata) + pb_request = service.ListContactsRequest.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 = service.ListContactsResponse() + pb_resp = service.ListContactsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_contacts(resp) + return resp + + class _SendTestMessage(EssentialContactsServiceRestStub): + def __hash__(self): + return hash("SendTestMessage") + + __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: service.SendTestMessageRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ): + r"""Call the send test message method over HTTP. + + Args: + request (~.service.SendTestMessageRequest): + The request object. Request message for the + SendTestMessage 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. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{resource=projects/*}/contacts:sendTestMessage", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=folders/*}/contacts:sendTestMessage", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=organizations/*}/contacts:sendTestMessage", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_send_test_message( + request, metadata + ) + pb_request = service.SendTestMessageRequest.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) + + class _UpdateContact(EssentialContactsServiceRestStub): + def __hash__(self): + return hash("UpdateContact") + + __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: service.UpdateContactRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.Contact: + r"""Call the update contact method over HTTP. + + Args: + request (~.service.UpdateContactRequest): + The request object. Request message for the UpdateContact + 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: + ~.service.Contact: + A contact that will receive + notifications from Google Cloud. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{contact.name=projects/*/contacts/*}", + "body": "contact", + }, + { + "method": "patch", + "uri": "/v1/{contact.name=folders/*/contacts/*}", + "body": "contact", + }, + { + "method": "patch", + "uri": "/v1/{contact.name=organizations/*/contacts/*}", + "body": "contact", + }, + ] + request, metadata = self._interceptor.pre_update_contact(request, metadata) + pb_request = service.UpdateContactRequest.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 = service.Contact() + pb_resp = service.Contact.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_contact(resp) + return resp + + @property + def compute_contacts( + self, + ) -> Callable[[service.ComputeContactsRequest], service.ComputeContactsResponse]: + # 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._ComputeContacts(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_contact( + self, + ) -> Callable[[service.CreateContactRequest], service.Contact]: + # 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._CreateContact(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_contact( + self, + ) -> Callable[[service.DeleteContactRequest], empty_pb2.Empty]: + # 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._DeleteContact(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_contact(self) -> Callable[[service.GetContactRequest], service.Contact]: + # 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._GetContact(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_contacts( + self, + ) -> Callable[[service.ListContactsRequest], service.ListContactsResponse]: + # 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._ListContacts(self._session, self._host, self._interceptor) # type: ignore + + @property + def send_test_message( + self, + ) -> Callable[[service.SendTestMessageRequest], empty_pb2.Empty]: + # 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._SendTestMessage(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_contact( + self, + ) -> Callable[[service.UpdateContactRequest], service.Contact]: + # 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._UpdateContact(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("EssentialContactsServiceRestTransport",) diff --git a/tests/unit/gapic/essential_contacts_v1/test_essential_contacts_service.py b/tests/unit/gapic/essential_contacts_v1/test_essential_contacts_service.py index e9c42ee..ace3ade 100644 --- a/tests/unit/gapic/essential_contacts_v1/test_essential_contacts_service.py +++ b/tests/unit/gapic/essential_contacts_v1/test_essential_contacts_service.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 gapic_v1, grpc_helpers, grpc_helpers_async, path_template @@ -32,12 +34,15 @@ from google.auth.exceptions import MutualTLSChannelError from google.oauth2 import service_account from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import json_format from google.protobuf import timestamp_pb2 # type: ignore import grpc from grpc.experimental import aio 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.essential_contacts_v1.services.essential_contacts_service import ( EssentialContactsServiceAsyncClient, @@ -98,6 +103,7 @@ def test__get_default_mtls_endpoint(): [ (EssentialContactsServiceClient, "grpc"), (EssentialContactsServiceAsyncClient, "grpc_asyncio"), + (EssentialContactsServiceClient, "rest"), ], ) def test_essential_contacts_service_client_from_service_account_info( @@ -113,7 +119,11 @@ def test_essential_contacts_service_client_from_service_account_info( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("essentialcontacts.googleapis.com:443") + assert client.transport._host == ( + "essentialcontacts.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://essentialcontacts.googleapis.com" + ) @pytest.mark.parametrize( @@ -121,6 +131,7 @@ def test_essential_contacts_service_client_from_service_account_info( [ (transports.EssentialContactsServiceGrpcTransport, "grpc"), (transports.EssentialContactsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.EssentialContactsServiceRestTransport, "rest"), ], ) def test_essential_contacts_service_client_service_account_always_use_jwt( @@ -146,6 +157,7 @@ def test_essential_contacts_service_client_service_account_always_use_jwt( [ (EssentialContactsServiceClient, "grpc"), (EssentialContactsServiceAsyncClient, "grpc_asyncio"), + (EssentialContactsServiceClient, "rest"), ], ) def test_essential_contacts_service_client_from_service_account_file( @@ -168,13 +180,18 @@ def test_essential_contacts_service_client_from_service_account_file( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("essentialcontacts.googleapis.com:443") + assert client.transport._host == ( + "essentialcontacts.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://essentialcontacts.googleapis.com" + ) def test_essential_contacts_service_client_get_transport_class(): transport = EssentialContactsServiceClient.get_transport_class() available_transports = [ transports.EssentialContactsServiceGrpcTransport, + transports.EssentialContactsServiceRestTransport, ] assert transport in available_transports @@ -195,6 +212,11 @@ def test_essential_contacts_service_client_get_transport_class(): transports.EssentialContactsServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + ( + EssentialContactsServiceClient, + transports.EssentialContactsServiceRestTransport, + "rest", + ), ], ) @mock.patch.object( @@ -354,6 +376,18 @@ def test_essential_contacts_service_client_client_options( "grpc_asyncio", "false", ), + ( + EssentialContactsServiceClient, + transports.EssentialContactsServiceRestTransport, + "rest", + "true", + ), + ( + EssentialContactsServiceClient, + transports.EssentialContactsServiceRestTransport, + "rest", + "false", + ), ], ) @mock.patch.object( @@ -560,6 +594,11 @@ def test_essential_contacts_service_client_get_mtls_endpoint_and_cert_source( transports.EssentialContactsServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + ( + EssentialContactsServiceClient, + transports.EssentialContactsServiceRestTransport, + "rest", + ), ], ) def test_essential_contacts_service_client_client_options_scopes( @@ -600,6 +639,12 @@ def test_essential_contacts_service_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + ( + EssentialContactsServiceClient, + transports.EssentialContactsServiceRestTransport, + "rest", + None, + ), ], ) def test_essential_contacts_service_client_client_options_credentials_file( @@ -2604,161 +2649,2088 @@ async def test_send_test_message_field_headers_async(): ) in kw["metadata"] -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.EssentialContactsServiceGrpcTransport( +@pytest.mark.parametrize( + "request_type", + [ + service.CreateContactRequest, + dict, + ], +) +def test_create_contact_rest(request_type): + client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = EssentialContactsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request_init["contact"] = { + "name": "name_value", + "email": "email_value", + "notification_category_subscriptions": [2], + "language_tag": "language_tag_value", + "validation_state": 1, + "validate_time": {"seconds": 751, "nanos": 543}, + } + 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 = service.Contact( + name="name_value", + email="email_value", + notification_category_subscriptions=[enums.NotificationCategory.ALL], + language_tag="language_tag_value", + validation_state=enums.ValidationState.VALID, ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.EssentialContactsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = EssentialContactsServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.Contact.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.create_contact(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, service.Contact) + assert response.name == "name_value" + assert response.email == "email_value" + assert response.notification_category_subscriptions == [ + enums.NotificationCategory.ALL + ] + assert response.language_tag == "language_tag_value" + assert response.validation_state == enums.ValidationState.VALID + + +def test_create_contact_rest_required_fields(request_type=service.CreateContactRequest): + transport_class = transports.EssentialContactsServiceRestTransport + + 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, ) + ) - # It is an error to provide an api_key and a transport instance. - transport = transports.EssentialContactsServiceGrpcTransport( + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_contact._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() + ).create_contact._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 = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.Contact() + # 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 = service.Contact.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.create_contact(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_contact_rest_unset_required_fields(): + transport = transports.EssentialContactsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = EssentialContactsServiceClient( - 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 = EssentialContactsServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + unset_fields = transport.create_contact._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "contact", + ) ) + ) - # It is an error to provide scopes and a transport instance. - transport = transports.EssentialContactsServiceGrpcTransport( + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_contact_rest_interceptors(null_interceptor): + transport = transports.EssentialContactsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EssentialContactsServiceRestInterceptor(), ) - with pytest.raises(ValueError): - client = EssentialContactsServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + client = EssentialContactsServiceClient(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.EssentialContactsServiceRestInterceptor, "post_create_contact" + ) as post, mock.patch.object( + transports.EssentialContactsServiceRestInterceptor, "pre_create_contact" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateContactRequest.pb(service.CreateContactRequest()) + 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 = service.Contact.to_json(service.Contact()) + + request = service.CreateContactRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.Contact() + + client.create_contact( + 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.EssentialContactsServiceGrpcTransport( + +def test_create_contact_rest_bad_request( + transport: str = "rest", request_type=service.CreateContactRequest +): + client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - client = EssentialContactsServiceClient(transport=transport) - assert client.transport is transport + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request_init["contact"] = { + "name": "name_value", + "email": "email_value", + "notification_category_subscriptions": [2], + "language_tag": "language_tag_value", + "validation_state": 1, + "validate_time": {"seconds": 751, "nanos": 543}, + } + request = request_type(**request_init) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.EssentialContactsServiceGrpcTransport( + # 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.create_contact(request) + + +def test_create_contact_rest_flattened(): + client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.EssentialContactsServiceGrpcAsyncIOTransport( + # 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 = service.Contact() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + contact=service.Contact(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 = service.Contact.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.create_contact(**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/*}/contacts" % client.transport._host, args[1] + ) + + +def test_create_contact_rest_flattened_error(transport: str = "rest"): + client = EssentialContactsServiceClient( 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.create_contact( + service.CreateContactRequest(), + parent="parent_value", + contact=service.Contact(name="name_value"), + ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.EssentialContactsServiceGrpcTransport, - transports.EssentialContactsServiceGrpcAsyncIOTransport, - ], -) -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_create_contact_rest_error(): + client = EssentialContactsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) @pytest.mark.parametrize( - "transport_name", + "request_type", [ - "grpc", + service.UpdateContactRequest, + dict, ], ) -def test_transport_kind(transport_name): - transport = EssentialContactsServiceClient.get_transport_class(transport_name)( +def test_update_contact_rest(request_type): + client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + # send a request that will satisfy transcoding + request_init = {"contact": {"name": "projects/sample1/contacts/sample2"}} + request_init["contact"] = { + "name": "projects/sample1/contacts/sample2", + "email": "email_value", + "notification_category_subscriptions": [2], + "language_tag": "language_tag_value", + "validation_state": 1, + "validate_time": {"seconds": 751, "nanos": 543}, + } + 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 = service.Contact( + name="name_value", + email="email_value", + notification_category_subscriptions=[enums.NotificationCategory.ALL], + language_tag="language_tag_value", + validation_state=enums.ValidationState.VALID, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.Contact.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.update_contact(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, service.Contact) + assert response.name == "name_value" + assert response.email == "email_value" + assert response.notification_category_subscriptions == [ + enums.NotificationCategory.ALL + ] + assert response.language_tag == "language_tag_value" + assert response.validation_state == enums.ValidationState.VALID + + +def test_update_contact_rest_required_fields(request_type=service.UpdateContactRequest): + transport_class = transports.EssentialContactsServiceRestTransport + + 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_contact._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_contact._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 -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. client = EssentialContactsServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert isinstance( - client.transport, - transports.EssentialContactsServiceGrpcTransport, + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.Contact() + # 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 + + pb_return_value = service.Contact.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.update_contact(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_contact_rest_unset_required_fields(): + transport = transports.EssentialContactsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials ) + unset_fields = transport.update_contact._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("contact",))) -def test_essential_contacts_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.EssentialContactsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", - ) +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_contact_rest_interceptors(null_interceptor): + transport = transports.EssentialContactsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EssentialContactsServiceRestInterceptor(), + ) + client = EssentialContactsServiceClient(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.EssentialContactsServiceRestInterceptor, "post_update_contact" + ) as post, mock.patch.object( + transports.EssentialContactsServiceRestInterceptor, "pre_update_contact" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.UpdateContactRequest.pb(service.UpdateContactRequest()) + 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 = service.Contact.to_json(service.Contact()) + + request = service.UpdateContactRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.Contact() -def test_essential_contacts_service_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.essential_contacts_v1.services.essential_contacts_service.transports.EssentialContactsServiceTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.EssentialContactsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), + client.update_contact( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "create_contact", - "update_contact", - "list_contacts", - "get_contact", - "delete_contact", - "compute_contacts", - "send_test_message", + pre.assert_called_once() + post.assert_called_once() + + +def test_update_contact_rest_bad_request( + transport: str = "rest", request_type=service.UpdateContactRequest +): + client = EssentialContactsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - with pytest.raises(NotImplementedError): - transport.close() + # send a request that will satisfy transcoding + request_init = {"contact": {"name": "projects/sample1/contacts/sample2"}} + request_init["contact"] = { + "name": "projects/sample1/contacts/sample2", + "email": "email_value", + "notification_category_subscriptions": [2], + "language_tag": "language_tag_value", + "validation_state": 1, + "validate_time": {"seconds": 751, "nanos": 543}, + } + request = request_type(**request_init) - # Catch all for all remaining methods and properties - remainder = [ - "kind", + # 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_contact(request) + + +def test_update_contact_rest_flattened(): + client = EssentialContactsServiceClient( + 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 = service.Contact() + + # get arguments that satisfy an http rule for this method + sample_request = {"contact": {"name": "projects/sample1/contacts/sample2"}} + + # get truthy value for each flattened field + mock_args = dict( + contact=service.Contact(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 + pb_return_value = service.Contact.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.update_contact(**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/{contact.name=projects/*/contacts/*}" % client.transport._host, + args[1], + ) + + +def test_update_contact_rest_flattened_error(transport: str = "rest"): + client = EssentialContactsServiceClient( + 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_contact( + service.UpdateContactRequest(), + contact=service.Contact(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_contact_rest_error(): + client = EssentialContactsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ListContactsRequest, + dict, + ], +) +def test_list_contacts_rest(request_type): + client = EssentialContactsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + 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 = service.ListContactsResponse( + 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 = service.ListContactsResponse.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_contacts(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListContactsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_contacts_rest_required_fields(request_type=service.ListContactsRequest): + transport_class = transports.EssentialContactsServiceRestTransport + + 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_contacts._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_contacts._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "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 = EssentialContactsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListContactsResponse() + # 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 = service.ListContactsResponse.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_contacts(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_contacts_rest_unset_required_fields(): + transport = transports.EssentialContactsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_contacts._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_contacts_rest_interceptors(null_interceptor): + transport = transports.EssentialContactsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EssentialContactsServiceRestInterceptor(), + ) + client = EssentialContactsServiceClient(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.EssentialContactsServiceRestInterceptor, "post_list_contacts" + ) as post, mock.patch.object( + transports.EssentialContactsServiceRestInterceptor, "pre_list_contacts" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListContactsRequest.pb(service.ListContactsRequest()) + 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 = service.ListContactsResponse.to_json( + service.ListContactsResponse() + ) + + request = service.ListContactsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListContactsResponse() + + client.list_contacts( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_contacts_rest_bad_request( + transport: str = "rest", request_type=service.ListContactsRequest +): + client = EssentialContactsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + 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_contacts(request) + + +def test_list_contacts_rest_flattened(): + client = EssentialContactsServiceClient( + 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 = service.ListContactsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1"} + + # 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 = service.ListContactsResponse.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_contacts(**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/*}/contacts" % client.transport._host, args[1] + ) + + +def test_list_contacts_rest_flattened_error(transport: str = "rest"): + client = EssentialContactsServiceClient( + 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_contacts( + service.ListContactsRequest(), + parent="parent_value", + ) + + +def test_list_contacts_rest_pager(transport: str = "rest"): + client = EssentialContactsServiceClient( + 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 = ( + service.ListContactsResponse( + contacts=[ + service.Contact(), + service.Contact(), + service.Contact(), + ], + next_page_token="abc", + ), + service.ListContactsResponse( + contacts=[], + next_page_token="def", + ), + service.ListContactsResponse( + contacts=[ + service.Contact(), + ], + next_page_token="ghi", + ), + service.ListContactsResponse( + contacts=[ + service.Contact(), + service.Contact(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListContactsResponse.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"} + + pager = client.list_contacts(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, service.Contact) for i in results) + + pages = list(client.list_contacts(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", + [ + service.GetContactRequest, + dict, + ], +) +def test_get_contact_rest(request_type): + client = EssentialContactsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/contacts/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 = service.Contact( + name="name_value", + email="email_value", + notification_category_subscriptions=[enums.NotificationCategory.ALL], + language_tag="language_tag_value", + validation_state=enums.ValidationState.VALID, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.Contact.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_contact(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, service.Contact) + assert response.name == "name_value" + assert response.email == "email_value" + assert response.notification_category_subscriptions == [ + enums.NotificationCategory.ALL + ] + assert response.language_tag == "language_tag_value" + assert response.validation_state == enums.ValidationState.VALID + + +def test_get_contact_rest_required_fields(request_type=service.GetContactRequest): + transport_class = transports.EssentialContactsServiceRestTransport + + 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_contact._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_contact._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 = EssentialContactsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.Contact() + # 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 = service.Contact.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_contact(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_contact_rest_unset_required_fields(): + transport = transports.EssentialContactsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_contact._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_contact_rest_interceptors(null_interceptor): + transport = transports.EssentialContactsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EssentialContactsServiceRestInterceptor(), + ) + client = EssentialContactsServiceClient(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.EssentialContactsServiceRestInterceptor, "post_get_contact" + ) as post, mock.patch.object( + transports.EssentialContactsServiceRestInterceptor, "pre_get_contact" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetContactRequest.pb(service.GetContactRequest()) + 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 = service.Contact.to_json(service.Contact()) + + request = service.GetContactRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.Contact() + + client.get_contact( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_contact_rest_bad_request( + transport: str = "rest", request_type=service.GetContactRequest +): + client = EssentialContactsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/contacts/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.get_contact(request) + + +def test_get_contact_rest_flattened(): + client = EssentialContactsServiceClient( + 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 = service.Contact() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/contacts/sample2"} + + # 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 = service.Contact.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_contact(**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/*/contacts/*}" % client.transport._host, args[1] + ) + + +def test_get_contact_rest_flattened_error(transport: str = "rest"): + client = EssentialContactsServiceClient( + 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_contact( + service.GetContactRequest(), + name="name_value", + ) + + +def test_get_contact_rest_error(): + client = EssentialContactsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.DeleteContactRequest, + dict, + ], +) +def test_delete_contact_rest(request_type): + client = EssentialContactsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/contacts/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 = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_contact(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_contact_rest_required_fields(request_type=service.DeleteContactRequest): + transport_class = transports.EssentialContactsServiceRestTransport + + 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_contact._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_contact._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 = EssentialContactsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # 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 = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_contact(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_contact_rest_unset_required_fields(): + transport = transports.EssentialContactsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_contact._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_contact_rest_interceptors(null_interceptor): + transport = transports.EssentialContactsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EssentialContactsServiceRestInterceptor(), + ) + client = EssentialContactsServiceClient(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.EssentialContactsServiceRestInterceptor, "pre_delete_contact" + ) as pre: + pre.assert_not_called() + pb_message = service.DeleteContactRequest.pb(service.DeleteContactRequest()) + 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() + + request = service.DeleteContactRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_contact( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_delete_contact_rest_bad_request( + transport: str = "rest", request_type=service.DeleteContactRequest +): + client = EssentialContactsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/contacts/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.delete_contact(request) + + +def test_delete_contact_rest_flattened(): + client = EssentialContactsServiceClient( + 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 = None + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/contacts/sample2"} + + # 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 = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_contact(**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/*/contacts/*}" % client.transport._host, args[1] + ) + + +def test_delete_contact_rest_flattened_error(transport: str = "rest"): + client = EssentialContactsServiceClient( + 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_contact( + service.DeleteContactRequest(), + name="name_value", + ) + + +def test_delete_contact_rest_error(): + client = EssentialContactsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ComputeContactsRequest, + dict, + ], +) +def test_compute_contacts_rest(request_type): + client = EssentialContactsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + 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 = service.ComputeContactsResponse( + 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 = service.ComputeContactsResponse.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.compute_contacts(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ComputeContactsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_compute_contacts_rest_required_fields( + request_type=service.ComputeContactsRequest, +): + transport_class = transports.EssentialContactsServiceRestTransport + + 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() + ).compute_contacts._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() + ).compute_contacts._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "notification_categories", + "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 = EssentialContactsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ComputeContactsResponse() + # 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 = service.ComputeContactsResponse.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.compute_contacts(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_compute_contacts_rest_unset_required_fields(): + transport = transports.EssentialContactsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.compute_contacts._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "notificationCategories", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_compute_contacts_rest_interceptors(null_interceptor): + transport = transports.EssentialContactsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EssentialContactsServiceRestInterceptor(), + ) + client = EssentialContactsServiceClient(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.EssentialContactsServiceRestInterceptor, "post_compute_contacts" + ) as post, mock.patch.object( + transports.EssentialContactsServiceRestInterceptor, "pre_compute_contacts" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ComputeContactsRequest.pb(service.ComputeContactsRequest()) + 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 = service.ComputeContactsResponse.to_json( + service.ComputeContactsResponse() + ) + + request = service.ComputeContactsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ComputeContactsResponse() + + client.compute_contacts( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_compute_contacts_rest_bad_request( + transport: str = "rest", request_type=service.ComputeContactsRequest +): + client = EssentialContactsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + 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.compute_contacts(request) + + +def test_compute_contacts_rest_pager(transport: str = "rest"): + client = EssentialContactsServiceClient( + 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 = ( + service.ComputeContactsResponse( + contacts=[ + service.Contact(), + service.Contact(), + service.Contact(), + ], + next_page_token="abc", + ), + service.ComputeContactsResponse( + contacts=[], + next_page_token="def", + ), + service.ComputeContactsResponse( + contacts=[ + service.Contact(), + ], + next_page_token="ghi", + ), + service.ComputeContactsResponse( + contacts=[ + service.Contact(), + service.Contact(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ComputeContactsResponse.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"} + + pager = client.compute_contacts(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, service.Contact) for i in results) + + pages = list(client.compute_contacts(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", + [ + service.SendTestMessageRequest, + dict, + ], +) +def test_send_test_message_rest(request_type): + client = EssentialContactsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "projects/sample1"} + 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 = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.send_test_message(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_send_test_message_rest_required_fields( + request_type=service.SendTestMessageRequest, +): + transport_class = transports.EssentialContactsServiceRestTransport + + request_init = {} + request_init["contacts"] = "" + request_init["resource"] = "" + 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() + ).send_test_message._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["contacts"] = "contacts_value" + jsonified_request["resource"] = "resource_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).send_test_message._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "contacts" in jsonified_request + assert jsonified_request["contacts"] == "contacts_value" + assert "resource" in jsonified_request + assert jsonified_request["resource"] == "resource_value" + + client = EssentialContactsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # 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 = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.send_test_message(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_send_test_message_rest_unset_required_fields(): + transport = transports.EssentialContactsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.send_test_message._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "contacts", + "resource", + "notificationCategory", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_send_test_message_rest_interceptors(null_interceptor): + transport = transports.EssentialContactsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EssentialContactsServiceRestInterceptor(), + ) + client = EssentialContactsServiceClient(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.EssentialContactsServiceRestInterceptor, "pre_send_test_message" + ) as pre: + pre.assert_not_called() + pb_message = service.SendTestMessageRequest.pb(service.SendTestMessageRequest()) + 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() + + request = service.SendTestMessageRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.send_test_message( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_send_test_message_rest_bad_request( + transport: str = "rest", request_type=service.SendTestMessageRequest +): + client = EssentialContactsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "projects/sample1"} + 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.send_test_message(request) + + +def test_send_test_message_rest_error(): + client = EssentialContactsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.EssentialContactsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EssentialContactsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.EssentialContactsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EssentialContactsServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.EssentialContactsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = EssentialContactsServiceClient( + 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 = EssentialContactsServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.EssentialContactsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EssentialContactsServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.EssentialContactsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = EssentialContactsServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.EssentialContactsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.EssentialContactsServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.EssentialContactsServiceGrpcTransport, + transports.EssentialContactsServiceGrpcAsyncIOTransport, + transports.EssentialContactsServiceRestTransport, + ], +) +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 = EssentialContactsServiceClient.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 = EssentialContactsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.EssentialContactsServiceGrpcTransport, + ) + + +def test_essential_contacts_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.EssentialContactsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_essential_contacts_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.essential_contacts_v1.services.essential_contacts_service.transports.EssentialContactsServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.EssentialContactsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "create_contact", + "update_contact", + "list_contacts", + "get_contact", + "delete_contact", + "compute_contacts", + "send_test_message", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", ] for r in remainder: with pytest.raises(NotImplementedError): @@ -2834,6 +4806,7 @@ def test_essential_contacts_service_transport_auth_adc(transport_class): [ transports.EssentialContactsServiceGrpcTransport, transports.EssentialContactsServiceGrpcAsyncIOTransport, + transports.EssentialContactsServiceRestTransport, ], ) def test_essential_contacts_service_transport_auth_gdch_credentials(transport_class): @@ -2935,11 +4908,23 @@ def test_essential_contacts_service_grpc_transport_client_cert_source_for_mtls( ) +def test_essential_contacts_service_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.EssentialContactsServiceRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + @pytest.mark.parametrize( "transport_name", [ "grpc", "grpc_asyncio", + "rest", ], ) def test_essential_contacts_service_host_no_port(transport_name): @@ -2950,7 +4935,11 @@ def test_essential_contacts_service_host_no_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("essentialcontacts.googleapis.com:443") + assert client.transport._host == ( + "essentialcontacts.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://essentialcontacts.googleapis.com" + ) @pytest.mark.parametrize( @@ -2958,6 +4947,7 @@ def test_essential_contacts_service_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_essential_contacts_service_host_with_port(transport_name): @@ -2968,7 +4958,51 @@ def test_essential_contacts_service_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("essentialcontacts.googleapis.com:8000") + assert client.transport._host == ( + "essentialcontacts.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://essentialcontacts.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_essential_contacts_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = EssentialContactsServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = EssentialContactsServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_contact._session + session2 = client2.transport.create_contact._session + assert session1 != session2 + session1 = client1.transport.update_contact._session + session2 = client2.transport.update_contact._session + assert session1 != session2 + session1 = client1.transport.list_contacts._session + session2 = client2.transport.list_contacts._session + assert session1 != session2 + session1 = client1.transport.get_contact._session + session2 = client2.transport.get_contact._session + assert session1 != session2 + session1 = client1.transport.delete_contact._session + session2 = client2.transport.delete_contact._session + assert session1 != session2 + session1 = client1.transport.compute_contacts._session + session2 = client2.transport.compute_contacts._session + assert session1 != session2 + session1 = client1.transport.send_test_message._session + session2 = client2.transport.send_test_message._session + assert session1 != session2 def test_essential_contacts_service_grpc_transport_channel(): @@ -3262,6 +5296,7 @@ async def test_transport_close_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -3279,6 +5314,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: